text
stringlengths
2
1.04M
meta
dict
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "abudget.settings.base") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
{ "content_hash": "af70ad57cae9de9eae862ef8bae54202", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 72, "avg_line_length": 34.2, "alnum_prop": 0.8011695906432749, "repo_name": "koriaf/django-abudget", "id": "d13cb3b3627616acd1ff8b3dddbe5f374b63c382", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/abudget/wsgi.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5159" }, { "name": "Dockerfile", "bytes": "320" }, { "name": "HTML", "bytes": "25170" }, { "name": "JavaScript", "bytes": "5058" }, { "name": "Python", "bytes": "40674" } ], "symlink_target": "" }
package org.mifos.test.acceptance.loan; import org.joda.time.DateTime; import org.mifos.test.acceptance.admin.FeeTestHelper; import org.mifos.test.acceptance.framework.MifosPage; import org.mifos.test.acceptance.framework.UiTestCaseBase; import org.mifos.test.acceptance.framework.admin.FeesCreatePage; import org.mifos.test.acceptance.framework.loan.CreateLoanAccountSearchParameters; import org.mifos.test.acceptance.framework.testhelpers.LoanTestHelper; import org.mifos.test.acceptance.framework.testhelpers.NavigationHelper; import org.mifos.test.acceptance.util.ApplicationDatabaseOperation; import org.mifos.test.acceptance.util.TestDataSetup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @ContextConfiguration(locations = {"classpath:ui-test-context.xml"}) @Test(singleThreaded = true, groups = {"loanproduct", "acceptance", "ui", "no_db_unit"}) public class VariableInstalmentLoanTest extends UiTestCaseBase { @Autowired private ApplicationDatabaseOperation applicationDatabaseOperation; private static final String clientName = "Client WeeklyTue"; private static final String loanProductName = "WeeklyClientVariableInstallmentsLoan"; private LoanTestHelper loanTestHelper; private DateTime systemDateTime; private NavigationHelper navigationHelper; private FeeTestHelper feeTestHelper; @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception @AfterMethod public void logOut() throws Exception{ applicationDatabaseOperation.updateLSIM(0); (new MifosPage(selenium)).logout(); } @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception @BeforeMethod public void setUp() throws Exception { super.setUp(); navigationHelper = new NavigationHelper(selenium); systemDateTime = new DateTime(2010, 10, 11, 10, 0, 0, 0); loanTestHelper = new LoanTestHelper(selenium); loanTestHelper.setApplicationTime(systemDateTime); TestDataSetup dataSetup = new TestDataSetup(selenium, applicationDatabaseOperation); feeTestHelper = new FeeTestHelper(dataSetup, new NavigationHelper(selenium)); applicationDatabaseOperation.updateLSIM(1); } @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception @Test(enabled = true) public void verifyRepaymentScheduleField() throws Exception { int noOfInstallments = 5; int maxGap = 10; int minGap = 1; int minInstalmentAmount = 100; DateTime disbursalDate = systemDateTime.plusDays(1); navigationHelper.navigateToHomePage(); loanTestHelper. navigateToCreateLoanAccountEntryPageWithoutLogout(setLoanSearchParameters()). setDisbursalDate(disbursalDate). clickContinue(). validateRepaymentScheduleFieldDefault(noOfInstallments). validateDateFieldValidations(disbursalDate, minGap, maxGap, noOfInstallments). verifyInstallmentTotalValidations(noOfInstallments, minInstalmentAmount, disbursalDate, minGap). verifyValidData(noOfInstallments, minGap, minInstalmentAmount, disbursalDate, maxGap). clickPreviewAndGoToReviewLoanAccountPage(). verifyEditSchedule(). verifySchedulePersistOnEdit(noOfInstallments, minGap, minInstalmentAmount, disbursalDate, maxGap); } @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception @Test(enabled = true) public void verifyInvalidFees() throws Exception { DateTime disbursalDate = systemDateTime.plusDays(1); String periodicFees = feeTestHelper.createPeriodicFee("loanWeeklyFee", FeesCreatePage.SubmitFormParameters.LOAN, FeesCreatePage.SubmitFormParameters.WEEKLY_FEE_RECURRENCE, 1, 100); String fixedFeePerAmountAndInterest = feeTestHelper.createFixedFee("fixedFeePerAmountAndInterest", FeesCreatePage.SubmitFormParameters.LOAN, "Upfront", 100, "Loan Amount+Interest"); String fixedFeePerInterest = feeTestHelper.createFixedFee("fixedFeePerInterest", FeesCreatePage.SubmitFormParameters.LOAN, "Upfront", 20, "Interest"); String[] blockedInterest = {periodicFees, fixedFeePerAmountAndInterest, fixedFeePerInterest}; navigationHelper.navigateToHomePage(); loanTestHelper. navigateToCreateLoanAccountEntryPageWithoutLogout(setLoanSearchParameters()). setDisbursalDate(disbursalDate). verifyInvalidFeeBlocked(blockedInterest); } private CreateLoanAccountSearchParameters setLoanSearchParameters() { CreateLoanAccountSearchParameters accountSearchParameters = new CreateLoanAccountSearchParameters(); accountSearchParameters.setSearchString(clientName); accountSearchParameters.setLoanProduct(loanProductName); return accountSearchParameters; } }
{ "content_hash": "1bb53a7bcdcc2d35b19aece55fa04c84", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 189, "avg_line_length": 50.22857142857143, "alnum_prop": 0.7593856655290102, "repo_name": "maduhu/head", "id": "cdc2e0f751f126e4b6fd685db98c9c050d0650eb", "size": "6035", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "acceptanceTests/src/test/java/org/mifos/test/acceptance/loan/VariableInstalmentLoanTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4245" }, { "name": "CSS", "bytes": "111180" }, { "name": "Groff", "bytes": "671" }, { "name": "HTML", "bytes": "83311" }, { "name": "Java", "bytes": "22987418" }, { "name": "JavaScript", "bytes": "835209" }, { "name": "Makefile", "bytes": "44" }, { "name": "PLSQL", "bytes": "71576" }, { "name": "Python", "bytes": "37612" }, { "name": "Shell", "bytes": "73897" } ], "symlink_target": "" }
package org.xdi.oxauth.session.ws.rs; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.xdi.model.security.Identity; import org.xdi.oxauth.audit.ApplicationAuditLogger; import org.xdi.oxauth.model.audit.Action; import org.xdi.oxauth.model.audit.OAuth2AuditLog; import org.xdi.oxauth.model.authorize.AuthorizeRequestParam; import org.xdi.oxauth.model.common.AuthorizationGrant; import org.xdi.oxauth.model.common.AuthorizationGrantList; import org.xdi.oxauth.model.common.SessionId; import org.xdi.oxauth.model.config.Constants; import org.xdi.oxauth.model.configuration.AppConfiguration; import org.xdi.oxauth.model.error.ErrorResponseFactory; import org.xdi.oxauth.model.registration.Client; import org.xdi.oxauth.model.session.EndSessionErrorResponseType; import org.xdi.oxauth.model.session.EndSessionParamsValidator; import org.xdi.oxauth.model.util.Util; import org.xdi.oxauth.service.ClientService; import org.xdi.oxauth.service.GrantService; import org.xdi.oxauth.service.RedirectionUriService; import org.xdi.oxauth.service.SessionIdService; import org.xdi.oxauth.service.external.ExternalApplicationSessionService; import org.xdi.oxauth.util.ServerUtil; import org.xdi.util.Pair; import org.xdi.util.StringHelper; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import java.net.URI; import java.net.URISyntaxException; import java.util.Set; /** * @author Javier Rojas Blum * @author Yuriy Movchan * @author Yuriy Zabrovarnyy * @version August 9, 2017 */ @Path("/") public class EndSessionRestWebServiceImpl implements EndSessionRestWebService { @Inject private Logger log; @Inject private ErrorResponseFactory errorResponseFactory; @Inject private RedirectionUriService redirectionUriService; @Inject private AuthorizationGrantList authorizationGrantList; @Inject private ExternalApplicationSessionService externalApplicationSessionService; @Inject private SessionIdService sessionIdService; @Inject private ClientService clientService; @Inject private GrantService grantService; @Inject private Identity identity; @Inject private ApplicationAuditLogger applicationAuditLogger; @Inject private AppConfiguration appConfiguration; @Override public Response requestEndSession(String idTokenHint, String postLogoutRedirectUri, String state, String sessionId, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) { log.debug("Attempting to end session, idTokenHint: {}, postLogoutRedirectUri: {}, sessionId: {}, Is Secure = {}", idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure()); EndSessionParamsValidator.validateParams(idTokenHint, sessionId, errorResponseFactory); final Pair<SessionId, AuthorizationGrant> pair = endSession(idTokenHint, sessionId, httpRequest, httpResponse, sec); auditLogging(httpRequest, pair); //Perform redirect to RP if id_token is expired (see https://github.com/GluuFederation/oxAuth/issues/575) if (pair.getFirst() == null && pair.getSecond() == null) { try { String error = errorResponseFactory.getErrorAsJson(EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION); return Response.temporaryRedirect(new URI(postLogoutRedirectUri)).entity(error).build(); } catch (URISyntaxException e) { log.error("Can't perform redirect", e); } } return httpBased(postLogoutRedirectUri, state, pair); } public Response httpBased(String postLogoutRedirectUri, String state, Pair<SessionId, AuthorizationGrant> pair) { SessionId sessionId = pair.getFirst(); AuthorizationGrant authorizationGrant = pair.getSecond(); // Validate redirectUri String redirectUri; if (authorizationGrant == null) { redirectUri = redirectionUriService.validatePostLogoutRedirectUri(sessionId, postLogoutRedirectUri); } else { redirectUri = redirectionUriService.validatePostLogoutRedirectUri(authorizationGrant.getClient().getClientId(), postLogoutRedirectUri); } final Set<String> frontchannelLogoutUris = getRpFrontchannelLogoutUris(pair); final String html = constructPage(frontchannelLogoutUris, redirectUri, state); log.debug("Constructed http logout page: " + html); return Response.ok(). cacheControl(ServerUtil.cacheControl(true, true)). header("Pragma", "no-cache"). type(MediaType.TEXT_HTML_TYPE).entity(html). build(); } private Pair<SessionId, AuthorizationGrant> endSession(String idTokenHint, String sessionId, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) { AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint); if (authorizationGrant == null) { Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken(); if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) { authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint); } } SessionId ldapSessionId = removeSessionId(sessionId, httpRequest, httpResponse); if ((authorizationGrant == null) && (ldapSessionId == null)) { log.info("Failed to find out authorization grant for id_token_hint '{}' and session_id '{}'", idTokenHint, sessionId); //see https://github.com/GluuFederation/oxAuth/issues/575 return new Pair<SessionId, AuthorizationGrant>(null, null); } // Clean up authorization session removeConsentSessionId(httpRequest, httpResponse); boolean isExternalLogoutPresent; boolean externalLogoutResult = false; isExternalLogoutPresent = externalApplicationSessionService.isEnabled(); if (isExternalLogoutPresent && (ldapSessionId != null)) { String userName = ldapSessionId.getSessionAttributes().get(Constants.AUTHENTICATED_USER); externalLogoutResult = externalApplicationSessionService.executeExternalEndSessionMethods(httpRequest, ldapSessionId); log.info("End session result for '{}': '{}'", userName, "logout", externalLogoutResult); } boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult; if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) { errorResponseFactory.throwUnauthorizedException(EndSessionErrorResponseType.INVALID_GRANT); } if (ldapSessionId != null) { grantService.removeAllTokensBySession(ldapSessionId.getDn()); } if (identity != null) { identity.logout(); } return new Pair<SessionId, AuthorizationGrant>(ldapSessionId, authorizationGrant); } private Set<String> getRpFrontchannelLogoutUris(Pair<SessionId, AuthorizationGrant> pair) { final Set<String> result = Sets.newHashSet(); SessionId sessionId = pair.getFirst(); AuthorizationGrant authorizationGrant = pair.getSecond(); if (sessionId == null) { log.error("session_id is not passed to endpoint (as cookie or manually). Therefore unable to match clients for session_id." + "Http based html will contain no iframes."); return result; } final Set<Client> clientsByDns = sessionId.getPermissionGrantedMap() != null ? clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) : Sets.<Client>newHashSet(); if (authorizationGrant != null) { clientsByDns.add(authorizationGrant.getClient()); } for (Client client : clientsByDns) { String[] logoutUris = client.getFrontChannelLogoutUri(); if (logoutUris == null) { continue; } for (String logoutUri : logoutUris) { if (Util.isNullOrEmpty(logoutUri)) { continue; // skip client if logout_uri is blank } if (client.getFrontChannelLogoutSessionRequired() != null && client.getFrontChannelLogoutSessionRequired()) { if (logoutUri.contains("?")) { logoutUri = logoutUri + "&sid=" + sessionId.getId(); } else { logoutUri = logoutUri + "?sid=" + sessionId.getId(); } } result.add(logoutUri); } } return result; } private SessionId removeSessionId(String sessionId, HttpServletRequest httpRequest, HttpServletResponse httpResponse) { SessionId ldapSessionId = null; try { String id = sessionId; if (StringHelper.isEmpty(id)) { id = sessionIdService.getSessionIdFromCookie(httpRequest); } if (StringHelper.isNotEmpty(id)) { ldapSessionId = sessionIdService.getSessionId(id); if (ldapSessionId != null) { boolean result = sessionIdService.remove(ldapSessionId); if (!result) { log.error("Failed to remove session_id '{}' from LDAP", id); } } else { log.error("Failed to load session from LDAP by session_id: '{}'", id); } } } catch (Exception e) { log.error(e.getMessage(), e); } finally { sessionIdService.removeSessionIdCookie(httpResponse); } return ldapSessionId; } private SessionId removeConsentSessionId(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { SessionId ldapSessionId = null; try { String id = sessionIdService.getConsentSessionIdFromCookie(httpRequest); if (StringHelper.isNotEmpty(id)) { ldapSessionId = sessionIdService.getSessionId(id); if (ldapSessionId != null) { boolean result = sessionIdService.remove(ldapSessionId); if (!result) { log.error("Failed to remove session_id '{}' from LDAP", id); } } else { log.error("Failed to load session from LDAP by session_id: '{}'", id); } } } catch (Exception e) { log.error(e.getMessage(), e); } finally { sessionIdService.removeConsentSessionIdCookie(httpResponse); } return ldapSessionId; } private String constructPage(Set<String> logoutUris, String postLogoutUrl, String state) { String iframes = ""; for (String logoutUri : logoutUris) { iframes = iframes + String.format("<iframe height=\"0\" width=\"0\" src=\"%s\"></iframe>", logoutUri); } String html = "<!DOCTYPE html>" + "<html>" + "<head>"; if (!Util.isNullOrEmpty(postLogoutUrl)) { if (!Util.isNullOrEmpty(state)) { if (postLogoutUrl.contains("?")) { postLogoutUrl += "&state=" + state; } else { postLogoutUrl += "?state=" + state; } } html += "<script>" + "window.onload=function() {" + "window.location='" + postLogoutUrl + "'" + "}" + "</script>"; } html += "<title>Gluu Generated logout page</title>" + "</head>" + "<body>" + "Logout requests sent.<br/>" + iframes + "</body>" + "</html>"; return html; } private void auditLogging(HttpServletRequest request, Pair<SessionId, AuthorizationGrant> pair) { SessionId sessionId = pair.getFirst(); AuthorizationGrant authorizationGrant = pair.getSecond(); OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.SESSION_DESTROYED); oAuth2AuditLog.setSuccess(true); if (authorizationGrant != null) { oAuth2AuditLog.setClientId(authorizationGrant.getClientId()); oAuth2AuditLog.setScope(StringUtils.join(authorizationGrant.getScopes(), " ")); oAuth2AuditLog.setUsername(authorizationGrant.getUserId()); } else if (sessionId != null) { oAuth2AuditLog.setClientId(sessionId.getPermissionGrantedMap().getClientIds(true).toString()); oAuth2AuditLog.setScope(sessionId.getSessionAttributes().get(AuthorizeRequestParam.SCOPE)); oAuth2AuditLog.setUsername(sessionId.getUserDn()); } applicationAuditLogger.sendMessage(oAuth2AuditLog); } }
{ "content_hash": "94d3b8519c3e98360335d21e2b66ff26", "timestamp": "", "source": "github", "line_count": 332, "max_line_length": 147, "avg_line_length": 40.62951807228916, "alnum_prop": 0.6442286307361554, "repo_name": "madumlao/oxAuth", "id": "3262aff43ab9f2946ac9bc4509b6664fdfdb4385", "size": "13633", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Server/src/main/java/org/xdi/oxauth/session/ws/rs/EndSessionRestWebServiceImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "49" }, { "name": "CSS", "bytes": "66182" }, { "name": "HTML", "bytes": "307892" }, { "name": "Java", "bytes": "5478487" }, { "name": "JavaScript", "bytes": "417438" }, { "name": "PHP", "bytes": "19193" }, { "name": "Python", "bytes": "479444" } ], "symlink_target": "" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (12.0.2) on Wed Feb 02 09:07:18 EST 2022 --> <title>Uses of Package org.opensextant.extractors.geo.rules (Xponents Extraction Toolkit)</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2022-02-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../jquery/jquery-3.3.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-migrate-3.0.1.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.opensextant.extractors.geo.rules (Xponents Extraction Toolkit)"; } } catch(err) { } //--> var pathtoroot = "../../../../../"; var useModuleDirectories = true; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <header role="banner"> <nav role="navigation"> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a id="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><img alt='[OpenSextant Logo]' height='36' width='36' src='doc-files/opensextant-manual-logo.png'/><br>copyright OpenSextant.org, 2013-2021</div> </div> <div class="subNav"> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> </div> <a id="skip.navbar.top"> <!-- --> </a> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> </nav> </header> <main role="main"> <div class="header"> <h1 title="Uses of Package org.opensextant.extractors.geo.rules" class="title">Uses of Package<br>org.opensextant.extractors.geo.rules</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <div class="useSummary"> <table> <caption><span>Packages that use <a href="package-summary.html">org.opensextant.extractors.geo.rules</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="#org.opensextant.extractors.geo">org.opensextant.extractors.geo</a></th> <td class="colLast"> <div class="block">Geo Extraction: PlaceGeocoder, SolrGazetteer, GazetteerMatcher and related items</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="#org.opensextant.extractors.geo.rules">org.opensextant.extractors.geo.rules</a></th> <td class="colLast"> <div class="block">GeocodeRules</div> </td> </tr> </tbody> </table> </div> </li> <li class="blockList"><a id="org.opensextant.extractors.geo"> <!-- --> </a> <div class="useSummary"> <table> <caption><span>Classes in <a href="package-summary.html">org.opensextant.extractors.geo.rules</a> used by <a href="../package-summary.html">org.opensextant.extractors.geo</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="class-use/GeocodeRule.html#org.opensextant.extractors.geo">GeocodeRule</a></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </div> </li> <li class="blockList"><a id="org.opensextant.extractors.geo.rules"> <!-- --> </a> <div class="useSummary"> <table> <caption><span>Classes in <a href="package-summary.html">org.opensextant.extractors.geo.rules</a> used by <a href="package-summary.html">org.opensextant.extractors.geo.rules</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <th class="colFirst" scope="row"><a href="class-use/FeatureClassMeta.html#org.opensextant.extractors.geo.rules">FeatureClassMeta</a></th> <td class="colLast"> <div class="block">data structure to capture our assumptions about feature types.</div> </td> </tr> <tr class="rowColor"> <th class="colFirst" scope="row"><a href="class-use/GeocodeRule.html#org.opensextant.extractors.geo.rules">GeocodeRule</a></th> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </div> </li> </ul> </div> </main> <footer role="contentinfo"> <nav role="navigation"> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a id="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a id="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../index.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><img alt='[OpenSextant Logo]' height='36' width='36' src='doc-files/opensextant-manual-logo.png'/><br>copyright OpenSextant.org, 2013-2021</div> </div> <a id="skip.navbar.bottom"> <!-- --> </a> <!-- ======== END OF BOTTOM NAVBAR ======= --> </nav> <p class="legalCopy"><small>Copyright &#169; 2013&#x2013;2022. All rights reserved.</small></p> </footer> </body> </html>
{ "content_hash": "bc4ef43a2edeeedc2acbf7ea6fe15dc7", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 228, "avg_line_length": 37.52910052910053, "alnum_prop": 0.6410545608346256, "repo_name": "OpenSextant/Xponents", "id": "25d6ca941b0a5754f15b87bf9e9269c34daf59f4", "size": "7093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/sdk-apidocs/org/opensextant/extractors/geo/rules/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "72623" }, { "name": "Java", "bytes": "1344792" }, { "name": "Python", "bytes": "343525" }, { "name": "Shell", "bytes": "106459" } ], "symlink_target": "" }
var EnvatoWizard = (function($){ var t; // callbacks from form button clicks. var callbacks = { install_plugins: function(btn){ var plugins = new PluginManager(); plugins.init(btn); }, install_content: function(btn){ var content = new ContentManager(); content.init(btn); } }; function window_loaded(){ // init button clicks: $('.button-next').on( 'click', function(e) { var loading_button = dtbaker_loading_button(this); if(!loading_button){ return false; } if($(this).data('callback') && typeof callbacks[$(this).data('callback')] != 'undefined'){ // we have to process a callback before continue with form submission callbacks[$(this).data('callback')](this); return false; }else{ loading_content(); return true; } }); $('.button-upload').on( 'click', function(e) { e.preventDefault(); renderMediaUploader(); }); $('.theme-presets a').on( 'click', function(e) { e.preventDefault(); var $ul = $(this).parents('ul').first(); $ul.find('.current').removeClass('current'); var $li = $(this).parents('li').first(); $li.addClass('current'); var newcolor = $(this).data('style'); $('#new_style').val(newcolor); return false; }); } function loading_content(){ $('.envato-setup-content').block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 } }); } function PluginManager(){ var complete; var items_completed = 0; var current_item = ''; var $current_node; var current_item_hash = ''; function ajax_callback(response){ if(typeof response == 'object' && typeof response.message != 'undefined'){ $current_node.find('span').text(response.message); if(typeof response.url != 'undefined'){ // we have an ajax url action to perform. if(response.hash == current_item_hash){ $current_node.find('span').text("failed"); find_next(); }else { current_item_hash = response.hash; jQuery.post(response.url, response, function(response2) { process_current(); $current_node.find('span').text(response.message + envato_setup_params.verify_text); }).fail(ajax_callback); } }else if(typeof response.done != 'undefined'){ // finished processing this plugin, move onto next find_next(); }else{ // error processing this plugin find_next(); } }else{ // error - try again with next plugin $current_node.find('span').text("ajax error"); find_next(); } } function process_current(){ if(current_item){ // query our ajax handler to get the ajax to send to TGM // if we don't get a reply we can assume everything worked and continue onto the next one. jQuery.post(envato_setup_params.ajaxurl, { action: 'envato_setup_plugins', wpnonce: envato_setup_params.wpnonce, slug: current_item }, ajax_callback).fail(ajax_callback); } } function find_next(){ var do_next = false; if($current_node){ if(!$current_node.data('done_item')){ items_completed++; $current_node.data('done_item',1); } $current_node.find('.spinner').css('visibility','hidden'); } var $li = $('.envato-wizard-plugins li'); $li.each(function(){ if(current_item == '' || do_next){ current_item = $(this).data('slug'); $current_node = $(this); process_current(); do_next = false; }else if($(this).data('slug') == current_item){ do_next = true; } }); if(items_completed >= $li.length){ // finished all plugins! complete(); } } return { init: function(btn){ $('.envato-wizard-plugins').addClass('installing'); complete = function(){ loading_content(); window.location.href=btn.href; }; find_next(); } } } function ContentManager(){ var complete; var items_completed = 0; var current_item = ''; var $current_node; var current_item_hash = ''; function ajax_callback(response) { if(typeof response == 'object' && typeof response.message != 'undefined'){ $current_node.find('span').text(response.message); if(typeof response.url != 'undefined'){ // we have an ajax url action to perform. if(response.hash == current_item_hash){ $current_node.find('span').text("failed"); find_next(); }else { current_item_hash = response.hash; jQuery.post(response.url, response, ajax_callback).fail(ajax_callback); // recuurrssionnnnn } }else if(typeof response.done != 'undefined'){ // finished processing this plugin, move onto next find_next(); }else{ // error processing this plugin find_next(); } }else{ // error - try again with next plugin $current_node.find('span').text("ajax error"); find_next(); } } function process_current(){ if(current_item){ var $check = $current_node.find('input:checkbox'); if($check.is(':checked')) { console.log("Doing 2 "+current_item); // process htis one! jQuery.post(envato_setup_params.ajaxurl, { action: 'envato_setup_content', wpnonce: envato_setup_params.wpnonce, content: current_item }, ajax_callback).fail(ajax_callback); }else{ $current_node.find('span').text("Skipping"); setTimeout(find_next,300); } } } function find_next(){ var do_next = false; if($current_node){ if(!$current_node.data('done_item')){ items_completed++; $current_node.data('done_item',1); } $current_node.find('.spinner').css('visibility','hidden'); } var $items = $('tr.envato_default_content'); var $enabled_items = $('tr.envato_default_content input:checked'); $items.each(function(){ if (current_item == '' || do_next) { current_item = $(this).data('content'); $current_node = $(this); process_current(); do_next = false; } else if ($(this).data('content') == current_item) { do_next = true; } }); if(items_completed >= $items.length){ // finished all items! complete(); } } return { init: function(btn){ $('.envato-setup-pages').addClass('installing'); $('.envato-setup-pages').find('input').prop("disabled", true); complete = function(){ loading_content(); window.location.href=btn.href; }; find_next(); } } } /** * Callback function for the 'click' event of the 'Set Footer Image' * anchor in its meta box. * * Displays the media uploader for selecting an image. * * @since 0.1.0 */ function renderMediaUploader() { 'use strict'; var file_frame, attachment; if ( undefined !== file_frame ) { file_frame.open(); return; } file_frame = wp.media.frames.file_frame = wp.media({ title: 'Upload Logo',//jQuery( this ).data( 'uploader_title' ), button: { text: 'Select Logo' //jQuery( this ).data( 'uploader_button_text' ) }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on( 'select', function() { // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); jQuery('.site-logo').attr('src',attachment.url); jQuery('#new_logo_id').val(attachment.id); // Do something with attachment.id and/or attachment.url here }); // Now display the actual file_frame file_frame.open(); } function dtbaker_loading_button(btn){ var $button = jQuery(btn); if($button.data('done-loading') == 'yes')return false; var existing_text = $button.text(); var existing_width = $button.outerWidth(); var loading_text = '⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⠄⠂⠁⠁⠂⠄'; var completed = false; $button.css('width',existing_width); $button.addClass('dtbaker_loading_button_current'); var _modifier = $button.is('input') || $button.is('button') ? 'val' : 'text'; $button[_modifier](loading_text); //$button.attr('disabled',true); $button.data('done-loading','yes'); var anim_index = [0,1,2]; // animate the text indent function moo() { if (completed)return; var current_text = ''; // increase each index up to the loading length for(var i = 0; i < anim_index.length; i++){ anim_index[i] = anim_index[i]+1; if(anim_index[i] >= loading_text.length)anim_index[i] = 0; current_text += loading_text.charAt(anim_index[i]); } $button[_modifier](current_text); setTimeout(function(){ moo();},60); } moo(); return { done: function(){ completed = true; $button[_modifier](existing_text); $button.removeClass('dtbaker_loading_button_current'); $button.attr('disabled',false); } } } return { init: function(){ t = this; $(window_loaded); }, callback: function(func){ console.log(func); console.log(this); } } })(jQuery); EnvatoWizard.init();
{ "content_hash": "c7e1eccdaa016073f733c75a9925e549", "timestamp": "", "source": "github", "line_count": 338, "max_line_length": 115, "avg_line_length": 34.866863905325445, "alnum_prop": 0.4605854900296988, "repo_name": "PramaAditya/pramaaditya.github.io", "id": "57b0ee3fb88b22500693e4006d0be23d381f5e67", "size": "11817", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sinarsaber/wp-content/themes/flatsome/inc/admin/envato_setup/js/envato-setup.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5779276" }, { "name": "HTML", "bytes": "3299055" }, { "name": "JavaScript", "bytes": "1210386" }, { "name": "PHP", "bytes": "1097" }, { "name": "Ruby", "bytes": "1860" }, { "name": "Shell", "bytes": "9252" } ], "symlink_target": "" }
// ----------------------------------------------------------------------- // <copyright file="DataGridSettingsSerializer.cs" company=""> // Copyright 2014 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Controls; using System.Xml.Serialization; namespace QDMSApp { public static class DataGridExtensions { public static void SerializeLayout(this DataGrid grid, StreamWriter sw) { var allSettings = grid.Columns.Select(c => new ColumnOptions { DisplayIndex = c.DisplayIndex, Width = c.ActualWidth, SortDirection = c.SortDirection }).ToList(); var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); serializer.Serialize(sw, allSettings); } public static void DeserializeLayout(this DataGrid grid, string settings) { List<ColumnOptions> allSettings; var serializer = new XmlSerializer(typeof(List<ColumnOptions>)); using (var sw = new StringReader(settings)) { allSettings = (List<ColumnOptions>)serializer.Deserialize(sw); } for (int i = 0; i < allSettings.Count; i++) { ColumnOptions co = allSettings[i]; grid.Columns[i].Width = co.Width; grid.Columns[i].SortDirection = co.SortDirection; if (co.DisplayIndex >= 0) grid.Columns[i].DisplayIndex = co.DisplayIndex; } } } }
{ "content_hash": "ec36352966cb5435163faba279eff702", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 81, "avg_line_length": 34.32, "alnum_prop": 0.539044289044289, "repo_name": "qusma/qdms", "id": "5e3988a7806c54f9bcfc981c552a834282d38188", "size": "1718", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "QDMSApp/ExtensionMethods/DataGridExtensions.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "1791861" }, { "name": "F#", "bytes": "25998" }, { "name": "HTML", "bytes": "311055" } ], "symlink_target": "" }
#include "third_party/blink/renderer/core/dom/context_features.h" #include <memory> #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" namespace blink { std::unique_ptr<ContextFeaturesClient> ContextFeaturesClient::Empty() { return std::make_unique<ContextFeaturesClient>(); } const char ContextFeatures::kSupplementName[] = "ContextFeatures"; ContextFeatures& ContextFeatures::DefaultSwitch() { DEFINE_STATIC_LOCAL( Persistent<ContextFeatures>, instance, (MakeGarbageCollected<ContextFeatures>(ContextFeaturesClient::Empty()))); return *instance; } bool ContextFeatures::PagePopupEnabled(Document* document) { if (!document) return false; return document->GetContextFeatures().IsEnabled(document, kPagePopup, false); } bool ContextFeatures::MutationEventsEnabled(Document* document) { DCHECK(document); if (!document) return true; return document->GetContextFeatures().IsEnabled(document, kMutationEvents, true); } void ProvideContextFeaturesTo(Page& page, std::unique_ptr<ContextFeaturesClient> client) { Supplement<Page>::ProvideTo( page, MakeGarbageCollected<ContextFeatures>(std::move(client))); } void ProvideContextFeaturesToDocumentFrom(Document& document, Page& page) { ContextFeatures* provided = Supplement<Page>::From<ContextFeatures>(page); if (!provided) return; document.SetContextFeatures(*provided); } } // namespace blink
{ "content_hash": "3f642d90283b959805b503d3d30e3b06", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 79, "avg_line_length": 31.096153846153847, "alnum_prop": 0.7272727272727273, "repo_name": "chromium/chromium", "id": "97d2fe71e59fc1e3cb3cf0ce7d8bde2ba2131aaa", "size": "2958", "binary": false, "copies": "10", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/dom/context_features.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
 dnn.controls.DNNRichText=function(initFunc) {this.supportsCE=(document.body.contentEditable!=null);this.text='';this.supportsMultiLine=true;this.document=null;this.control=null;this.initialized=false;this.isRichText=true;this.loaded=false;if(this.supportsCE) {this.document=document;this.container=document.createElement('span');this.container.contentEditable=true;this.control=this.container;this.initialized=true;} else {this.container=document.createElement('iframe');this.container.src='';this.container.style.border='0';this.initFunc=initFunc;this._initDelegate=Function.createDelegate(this,this.initDocument);dnn.doDelay(this.container.id+'initEdit',10,this._initDelegate);}} dnn.controls.DNNRichText.prototype={focus:function() {if(this.supportsCE) this.control.focus();else this.container.contentWindow.focus();},execCommand:function(cmd,ui,vValue) {this.document.execCommand(cmd,ui,vValue);},getText:function() {return this.control.innerHTML;},setText:function(s) {if(this.initialized) this.control.innerHTML=s;else this.text=s;},initDocument:function() {if(this.container.contentDocument!=null) {if(this.document==null) {this.container.contentDocument.designMode='on';this.document=this.container.contentWindow.document;this.document.open();dnn.dom.addSafeHandler(this.container,'onload',this,'initDocument');this.document.write('<HEAD>'+this._getCSSLinks()+'</HEAD><BODY id="__dnn_body"></BODY>');this.document.close();} else if(this.control==null&&this.document.getElementById('__dnn_body')!=null) {this.control=this.document.getElementById('__dnn_body');this.control.style.margin=0;this.control.tabIndex=0;this.initialized=true;this.setText(this.text);this.initFunc();}} if(this.initialized==false) dnn.doDelay(this.container.id+'initEdit',10,this._initDelegate);},_getCSSLinks:function() {var arr=dnn.dom.getByTagName('link');var s='';for(var i=0;i<arr.length;i++) {s+='<LINK href="'+arr[i].href+'" type=text/css rel=stylesheet>';} return s;}} dnn.controls.DNNRichText.registerClass('dnn.controls.DNNRichText');
{ "content_hash": "3a54b43273b909c4c7aff9ae34cff747", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 301, "avg_line_length": 77.96153846153847, "alnum_prop": 0.785397138628515, "repo_name": "51Degrees/Dnn.Platform", "id": "8565cb75577573de806e9406fe3cb45958cc6c1e", "size": "2029", "binary": false, "copies": "4", "ref": "refs/heads/development", "path": "Website/js/dnn.controls.dnnrichtext.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "1324375" }, { "name": "Batchfile", "bytes": "374" }, { "name": "C#", "bytes": "20857779" }, { "name": "CSS", "bytes": "1024904" }, { "name": "Erlang", "bytes": "2168" }, { "name": "HTML", "bytes": "628764" }, { "name": "JavaScript", "bytes": "3820356" }, { "name": "PHP", "bytes": "2199" }, { "name": "Smalltalk", "bytes": "66184" }, { "name": "Visual Basic", "bytes": "139461" }, { "name": "XSLT", "bytes": "16560" } ], "symlink_target": "" }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.NonHideableIconGutterMark; import com.intellij.codeInsight.folding.impl.FoldingUtil; import com.intellij.codeInsight.hint.TooltipController; import com.intellij.codeInsight.hint.TooltipGroup; import com.intellij.codeInsight.hint.TooltipRenderer; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.dnd.*; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.ColorKey; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorFontType; import com.intellij.openapi.editor.event.EditorMouseEventArea; import com.intellij.openapi.editor.ex.*; import com.intellij.openapi.editor.ex.util.EditorUIUtil; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.impl.view.IterationState; import com.intellij.openapi.editor.impl.view.VisualLinesIterator; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.util.ProgressIndicatorBase; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.ui.HintHint; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.paint.LinePainter2D; import com.intellij.ui.paint.LinePainter2D.StrokeType; import com.intellij.ui.paint.PaintUtil; import com.intellij.ui.paint.PaintUtil.RoundingMode; import com.intellij.ui.paint.RectanglePainter2D; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.*; import com.intellij.util.ui.JBUI.ScaleContext; import com.intellij.util.ui.JBValue.JBValueGroup; import gnu.trove.TIntArrayList; import gnu.trove.TIntFunction; import gnu.trove.TIntObjectHashMap; import gnu.trove.TIntObjectProcedure; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.util.*; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * Gutter content (left to right): * <ul> * <li>GAP_BETWEEN_AREAS</li> * <li>Line numbers area * <ul> * <li>Line numbers</li> * <li>GAP_BETWEEN_AREAS</li> * <li>Additional line numbers (used in diff)</li> * </ul> * </li> * <li>GAP_BETWEEN_AREAS</li> * <li>Annotations area * <ul> * <li>Annotations</li> * <li>Annotations extra (used in distraction free mode)</li> * </ul> * </li> * <li>GAP_BETWEEN_AREAS</li> * <li>Line markers area * <ul> * <li>Left free painters</li> * <li>Icons</li> * <li>Gap (required by debugger to set breakpoints with mouse click - IDEA-137353) </li> * <li>Free painters</li> * </ul> * </li> * <li>Folding area</li> *</ul> */ class EditorGutterComponentImpl extends EditorGutterComponentEx implements MouseListener, MouseMotionListener, DataProvider { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorGutterComponentImpl"); private static final JBValueGroup JBVG = new JBValueGroup(); private static final JBValue START_ICON_AREA_WIDTH = JBVG.value(17); private static final JBValue FREE_PAINTERS_LEFT_AREA_WIDTH = JBVG.value(8); private static final JBValue FREE_PAINTERS_RIGHT_AREA_WIDTH = JBVG.value(5); private static final JBValue GAP_BETWEEN_ICONS = JBVG.value(3); private static final JBValue GAP_BETWEEN_AREAS = JBVG.value(5); private static final JBValue GAP_BETWEEN_ANNOTATIONS = JBVG.value(5); private static final TooltipGroup GUTTER_TOOLTIP_GROUP = new TooltipGroup("GUTTER_TOOLTIP_GROUP", 0); private final EditorImpl myEditor; private final FoldingAnchorsOverlayStrategy myAnchorsDisplayStrategy; @Nullable private TIntObjectHashMap<List<GutterMark>> myLineToGutterRenderers; private boolean myLineToGutterRenderersCacheForLogicalLines; private int myStartIconAreaWidth = START_ICON_AREA_WIDTH.get(); private int myIconsAreaWidth; private int myLineNumberAreaWidth; private int myAdditionalLineNumberAreaWidth; private FoldRegion myActiveFoldRegion; private int myTextAnnotationGuttersSize; private int myTextAnnotationExtraSize; private TIntArrayList myTextAnnotationGutterSizes = new TIntArrayList(); private ArrayList<TextAnnotationGutterProvider> myTextAnnotationGutters = new ArrayList<>(); private final Map<TextAnnotationGutterProvider, EditorGutterAction> myProviderToListener = new HashMap<>(); private String myLastGutterToolTip; @NotNull private TIntFunction myLineNumberConvertor = value -> value; @Nullable private TIntFunction myAdditionalLineNumberConvertor; private boolean myShowDefaultGutterPopup = true; @Nullable private ActionGroup myCustomGutterPopupGroup; private final TIntObjectHashMap<Color> myTextFgColors = new TIntObjectHashMap<>(); private boolean myPaintBackground = true; private boolean myLeftFreePaintersAreaShown; private boolean myRightFreePaintersAreaShown; private boolean myForceLeftFreePaintersAreaShown; private boolean myForceRightFreePaintersAreaShown; private int myLastNonDumbModeIconAreaWidth; boolean myDnDInProgress; EditorGutterComponentImpl(@NotNull EditorImpl editor) { myEditor = editor; if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { installDnD(); } setOpaque(true); myAnchorsDisplayStrategy = new FoldingAnchorsOverlayStrategy(editor); Project project = myEditor.getProject(); if (project != null) { project.getMessageBus().connect(myEditor.getDisposable()).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() { @Override public void exitDumbMode() { updateSize(); } }); } } @SuppressWarnings("ConstantConditions") private void installDnD() { DnDSupport.createBuilder(this) .setBeanProvider(info -> { final GutterMark renderer = getGutterRenderer(info.getPoint()); if (renderer instanceof GutterIconRenderer && ((GutterIconRenderer)renderer).getDraggableObject() != null && (info.isCopy() || info.isMove())) { myDnDInProgress = true; return new DnDDragStartBean(renderer); } return null; }) .setDropHandler(e -> { final Object attachedObject = e.getAttachedObject(); if (attachedObject instanceof GutterIconRenderer && checkDumbAware(attachedObject)) { final GutterDraggableObject draggableObject = ((GutterIconRenderer)attachedObject).getDraggableObject(); if (draggableObject != null) { final int line = convertPointToLineNumber(e.getPoint()); if (line != -1) { draggableObject.copy(line, myEditor.getVirtualFile(), e.getAction().getActionId()); } } } else if (attachedObject instanceof DnDNativeTarget.EventInfo && myEditor.getSettings().isDndEnabled()) { Transferable transferable = ((DnDNativeTarget.EventInfo)attachedObject).getTransferable(); if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { EditorImpl.handleDrop(myEditor, transferable, e.getAction().getActionId()); } } myDnDInProgress = false; }) .setTargetChecker(e -> { final Object attachedObject = e.getAttachedObject(); if (attachedObject instanceof GutterIconRenderer && checkDumbAware(attachedObject)) { final GutterDraggableObject draggableObject = ((GutterIconRenderer)attachedObject).getDraggableObject(); if (draggableObject != null) { final int line = convertPointToLineNumber(e.getPoint()); if (line != -1) { e.setDropPossible(true); e.setCursor(draggableObject.getCursor(line, e.getAction().getActionId())); } } } else if (attachedObject instanceof DnDNativeTarget.EventInfo && myEditor.getSettings().isDndEnabled()) { Transferable transferable = ((DnDNativeTarget.EventInfo)attachedObject).getTransferable(); if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { final int line = convertPointToLineNumber(e.getPoint()); if (line != -1) { e.setDropPossible(true); myEditor.getCaretModel().moveToOffset(myEditor.getDocument().getLineStartOffset(line)); } } } return true; }) .setImageProvider((NullableFunction<DnDActionInfo, DnDImage>)info -> { // [tav] temp workaround for JRE-224 boolean inUserScale = !SystemInfo.isWindows || !UIUtil.isJreHiDPI(myEditor.getComponent()); Image image = ImageUtil.toBufferedImage(getDragImage(getGutterRenderer(info.getPoint())), inUserScale); return new DnDImage(image, new Point(image.getWidth(null) / 2, image.getHeight(null) / 2)); }) .enableAsNativeTarget() // required to accept dragging from editor (as editor component doesn't use DnDSupport to implement drag'n'drop) .install(); } Image getDragImage(GutterMark renderer) { return IconUtil.toImage(scaleIcon(renderer.getIcon())); } private void fireResized() { processComponentEvent(new ComponentEvent(this, ComponentEvent.COMPONENT_RESIZED)); } @Override public Dimension getPreferredSize() { int w = getFoldingAreaOffset() + getFoldingAreaWidth(); Dimension size = new Dimension(w, myEditor.getPreferredHeight()); JBInsets.addTo(size, getInsets()); return size; } @Override protected void setUI(ComponentUI newUI) { super.setUI(newUI); reinitSettings(true); } @Override public void updateUI() { super.updateUI(); reinitSettings(true); } public void reinitSettings(boolean updateGutterSize) { updateSize(false, updateGutterSize); repaint(); } @Override protected Graphics getComponentGraphics(Graphics graphics) { return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics)); } @Override public void paint(Graphics g_) { Rectangle clip = g_.getClipBounds(); if (clip.height < 0) return; Graphics2D g = (Graphics2D)getComponentGraphics(g_); AffineTransform old = setMirrorTransformIfNeeded(g, 0, getWidth()); EditorUIUtil.setupAntialiasing(g); Color backgroundColor = getBackground(); if (myEditor.isDisposed()) { g.setColor(myEditor.getDisposedBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); return; } int startVisualLine = myEditor.yToVisibleLine(clip.y); int endVisualLine = myEditor.yToVisibleLine(clip.y + clip.height); // paint all backgrounds int gutterSeparatorX = getWhitespaceSeparatorOffset(); paintBackground(g, clip, 0, gutterSeparatorX, backgroundColor); paintBackground(g, clip, gutterSeparatorX, getFoldingAreaWidth(), myEditor.getBackgroundColor()); int firstVisibleOffset = myEditor.visualLineStartOffset(startVisualLine); int lastVisibleOffset = myEditor.visualLineStartOffset(endVisualLine + 1); paintEditorBackgrounds(g, firstVisibleOffset, lastVisibleOffset); Object hint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); if (!UIUtil.isJreHiDPI(g)) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); try { paintAnnotations(g, startVisualLine, endVisualLine); paintLineMarkers(g, firstVisibleOffset, lastVisibleOffset, startVisualLine, endVisualLine); paintFoldingLines(g, clip); paintFoldingTree(g, clip, firstVisibleOffset, lastVisibleOffset); paintLineNumbers(g, startVisualLine, endVisualLine); } finally { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint); } if (old != null) g.setTransform(old); } private void paintEditorBackgrounds(Graphics g, int firstVisibleOffset, int lastVisibleOffset) { myTextFgColors.clear(); Color defaultBackgroundColor = myEditor.getBackgroundColor(); Color defaultForegroundColor = myEditor.getColorsScheme().getDefaultForeground(); int startX = myEditor.isInDistractionFreeMode() ? 0 : getWhitespaceSeparatorOffset(); IterationState state = new IterationState(myEditor, firstVisibleOffset, lastVisibleOffset, null, true, false, true, false); while (!state.atEnd()) { drawEditorBackgroundForRange(g, state.getStartOffset(), state.getEndOffset(), state.getMergedAttributes(), defaultBackgroundColor, defaultForegroundColor, startX); state.advance(); } } private void drawEditorBackgroundForRange(Graphics g, int startOffset, int endOffset, TextAttributes attributes, Color defaultBackgroundColor, Color defaultForegroundColor, int startX) { VisualPosition visualStart = myEditor.offsetToVisualPosition(startOffset, true, false); VisualPosition visualEnd = myEditor.offsetToVisualPosition(endOffset, false, false); for (int line = visualStart.getLine(); line <= visualEnd.getLine(); line++) { if (line == visualStart.getLine()) { if (visualStart.getColumn() == 0) { drawEditorLineBackgroundRect(g, attributes, line, defaultBackgroundColor, defaultForegroundColor, startX, myEditor.visibleLineToY(line)); } } else if (line != visualEnd.getLine() || visualEnd.getColumn() != 0) { drawEditorLineBackgroundRect(g, attributes, line, defaultBackgroundColor, defaultForegroundColor, startX, myEditor.visibleLineToY(line)); } } } private void drawEditorLineBackgroundRect(Graphics g, TextAttributes attributes, int visualLine, Color defaultBackgroundColor, Color defaultForegroundColor, int startX, int startY) { Color color = myEditor.getBackgroundColor(attributes); if (!Comparing.equal(color, defaultBackgroundColor)) { Color fgColor = attributes.getForegroundColor(); if (!Comparing.equal(fgColor, defaultForegroundColor)) { myTextFgColors.put(visualLine, fgColor); } g.setColor(color); g.fillRect(startX, startY, getWidth() - startX, myEditor.getLineHeight()); } } private void processClose(final MouseEvent e) { final IdeEventQueue queue = IdeEventQueue.getInstance(); // See IDEA-59553 for rationale on why this feature is disabled //if (isLineNumbersShown()) { // if (e.getX() >= getLineNumberAreaOffset() && getLineNumberAreaOffset() + getLineNumberAreaWidth() >= e.getX()) { // queue.blockNextEvents(e); // myEditor.getSettings().setLineNumbersShown(false); // e.consume(); // return; // } //} if (getGutterRenderer(e) != null) return; if (myEditor.getMouseEventArea(e) == EditorMouseEventArea.ANNOTATIONS_AREA) { queue.blockNextEvents(e); closeAllAnnotations(); e.consume(); } } private void paintAnnotations(Graphics2D g, int startVisualLine, int endVisualLine) { int x = getAnnotationsAreaOffset(); int w = getAnnotationsAreaWidthEx(); if (w == 0) return; AffineTransform old = setMirrorTransformIfNeeded(g, x, w); try { Color color = myEditor.getColorsScheme().getColor(EditorColors.ANNOTATIONS_COLOR); g.setColor(color != null ? color : JBColor.blue); g.setFont(myEditor.getColorsScheme().getFont(EditorFontType.PLAIN)); for (int i = 0; i < myTextAnnotationGutters.size(); i++) { TextAnnotationGutterProvider gutterProvider = myTextAnnotationGutters.get(i); int lineHeight = myEditor.getLineHeight(); int lastLine = myEditor.logicalToVisualPosition(new LogicalPosition(endLineNumber(), 0)).line; endVisualLine = Math.min(endVisualLine, lastLine); if (startVisualLine > endVisualLine) { break; } int annotationSize = myTextAnnotationGutterSizes.get(i); if (startVisualLine == 0 && endVisualLine == 0) { //allow paining gutters for empty documents paintAnnotationLine(g, gutterProvider, 0, x, 0, annotationSize, lineHeight); } else { VisualLinesIterator visLinesIterator = new VisualLinesIterator(myEditor, startVisualLine); while (!visLinesIterator.atEnd() && visLinesIterator.getVisualLine() <= endVisualLine) { int logLine = visLinesIterator.getStartLogicalLine(); int y = visLinesIterator.getY(); paintAnnotationLine(g, gutterProvider, logLine, x, y, annotationSize, lineHeight); visLinesIterator.advance(); } } x += annotationSize; } } finally { if (old != null) g.setTransform(old); } } private void paintAnnotationLine(Graphics g, TextAnnotationGutterProvider gutterProvider, int line, int x, int y, int width, int height) { String s = gutterProvider.getLineText(line, myEditor); final Color bg = gutterProvider.getBgColor(line, myEditor); if (bg != null) { g.setColor(bg); g.fillRect(x, y, width, height); } if (!StringUtil.isEmpty(s)) { g.setColor(myEditor.getColorsScheme().getColor(gutterProvider.getColor(line, myEditor))); EditorFontType style = gutterProvider.getStyle(line, myEditor); Font font = getFontForText(s, style); g.setFont(font); g.drawString(s, getGapBetweenAnnotations() / 2 + x, y + myEditor.getAscent()); } } private Font getFontForText(String text, EditorFontType style) { Font font = myEditor.getColorsScheme().getFont(style); if (font.canDisplayUpTo(text) != -1) { font = UIUtil.getFontWithFallback(font); } return font; } private void paintFoldingTree(Graphics g, Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { if (isFoldingOutlineShown()) { doPaintFoldingTree((Graphics2D)g, clip, firstVisibleOffset, lastVisibleOffset); } } private void paintLineMarkers(Graphics2D g, int firstVisibleOffset, int lastVisibleOffset, int firstVisibleLine, int lastVisibleLine) { if (isLineMarkersShown()) { paintGutterRenderers(g, firstVisibleOffset, lastVisibleOffset, firstVisibleLine, lastVisibleLine); } } private void paintBackground(final Graphics g, final Rectangle clip, final int x, final int width, Color background) { g.setColor(background); g.fillRect(x, clip.y, width, clip.height); paintCaretRowBackground(g, x, width); } private void paintCaretRowBackground(final Graphics g, final int x, final int width) { if (!myEditor.getSettings().isCaretRowShown()) return; final VisualPosition visCaret = myEditor.getCaretModel().getVisualPosition(); Color caretRowColor = myEditor.getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR); if (caretRowColor != null) { g.setColor(caretRowColor); final Point caretPoint = myEditor.visualPositionToXY(visCaret); g.fillRect(x, caretPoint.y, width, myEditor.getLineHeight()); } } private void paintLineNumbers(Graphics2D g, int startVisualLine, int endVisualLine) { if (isLineNumbersShown()) { int offset = getLineNumberAreaOffset() + myLineNumberAreaWidth; doPaintLineNumbers(g, startVisualLine, endVisualLine, offset, myLineNumberConvertor); if (myAdditionalLineNumberConvertor != null) { doPaintLineNumbers(g, startVisualLine, endVisualLine, offset + getAreaWidthWithGap(myAdditionalLineNumberAreaWidth), myAdditionalLineNumberConvertor); } } } @Override public Color getBackground() { if (myEditor.isInDistractionFreeMode() || !myPaintBackground) { return myEditor.getBackgroundColor(); } Color color = myEditor.getColorsScheme().getColor(EditorColors.GUTTER_BACKGROUND); return color != null ? color : EditorColors.GUTTER_BACKGROUND.getDefaultColor(); } private Font getFontForLineNumbers() { Font editorFont = myEditor.getColorsScheme().getFont(EditorFontType.PLAIN); float editorFontSize = editorFont.getSize2D(); return editorFont.deriveFont(Math.max(1f, editorFontSize - 1f)); } private int calcLineNumbersAreaWidth(int maxLineNumber) { return getFontMetrics(getFontForLineNumbers()).stringWidth(Integer.toString(maxLineNumber + 1)); } private void doPaintLineNumbers(Graphics2D g, int startVisualLine, int endVisualLine, int offset, @NotNull TIntFunction convertor) { int lastLine = myEditor.logicalToVisualPosition( new LogicalPosition(endLineNumber(), 0)) .line; endVisualLine = Math.min(endVisualLine, lastLine); if (startVisualLine > endVisualLine) { return; } Color color = myEditor.getColorsScheme().getColor(EditorColors.LINE_NUMBERS_COLOR); g.setColor(color != null ? color : JBColor.blue); Font font = getFontForLineNumbers(); g.setFont(font); AffineTransform old = setMirrorTransformIfNeeded(g, getLineNumberAreaOffset(), getLineNumberAreaWidth()); try { VisualLinesIterator visLinesIterator = new VisualLinesIterator(myEditor, startVisualLine); while (!visLinesIterator.atEnd() && visLinesIterator.getVisualLine() <= endVisualLine) { LogicalPosition logicalPosition = myEditor.visualToLogicalPosition(new VisualPosition(visLinesIterator.getVisualLine(), 0)); if (EditorUtil.getSoftWrapCountAfterLineStart(myEditor, logicalPosition) <= 0) { int logLine = convertor.execute(visLinesIterator.getStartLogicalLine()); if (logLine >= 0) { int startY = visLinesIterator.getY(); if (myEditor.isInDistractionFreeMode()) { Color fgColor = myTextFgColors.get(visLinesIterator.getVisualLine()); g.setColor(fgColor != null ? fgColor : color != null ? color : JBColor.blue); } String s = String.valueOf(logLine + 1); int textOffset = isMirrored() ? offset - getLineNumberAreaWidth() - 1 : offset - g.getFontMetrics().stringWidth(s); g.drawString(s, textOffset, startY + myEditor.getAscent()); } } visLinesIterator.advance(); } } finally { if (old != null) g.setTransform(old); } } private int endLineNumber() { return Math.max(0, myEditor.getDocument().getLineCount() - 1); } @Nullable @Override public Object getData(@NonNls String dataId) { if (myEditor.isDisposed()) return null; if (EditorGutter.KEY.is(dataId)) { return this; } if (CommonDataKeys.EDITOR.is(dataId)) { return myEditor; } return null; } @FunctionalInterface private interface RangeHighlighterProcessor { void process(@NotNull RangeHighlighter highlighter); } private void processRangeHighlighters(int startOffset, int endOffset, @NotNull RangeHighlighterProcessor processor) { Document document = myEditor.getDocument(); // we limit highlighters to process to between line starting at startOffset and line ending at endOffset MarkupIterator<RangeHighlighterEx> docHighlighters = myEditor.getFilteredDocumentMarkupModel().overlappingIterator(startOffset, endOffset); MarkupIterator<RangeHighlighterEx> editorHighlighters = myEditor.getMarkupModel().overlappingIterator(startOffset, endOffset); try { RangeHighlighterEx lastDocHighlighter = null; RangeHighlighterEx lastEditorHighlighter = null; while (true) { if (lastDocHighlighter == null && docHighlighters.hasNext()) { lastDocHighlighter = docHighlighters.next(); if (!lastDocHighlighter.isValid() || lastDocHighlighter.getAffectedAreaStartOffset() > endOffset) { lastDocHighlighter = null; continue; } if (lastDocHighlighter.getAffectedAreaEndOffset() < startOffset) { lastDocHighlighter = null; continue; } } if (lastEditorHighlighter == null && editorHighlighters.hasNext()) { lastEditorHighlighter = editorHighlighters.next(); if (!lastEditorHighlighter.isValid() || lastEditorHighlighter.getAffectedAreaStartOffset() > endOffset) { lastEditorHighlighter = null; continue; } if (lastEditorHighlighter.getAffectedAreaEndOffset() < startOffset) { lastEditorHighlighter = null; continue; } } if (lastDocHighlighter == null && lastEditorHighlighter == null) return; final RangeHighlighterEx lowerHighlighter; if (less(lastDocHighlighter, lastEditorHighlighter)) { lowerHighlighter = lastDocHighlighter; lastDocHighlighter = null; } else { lowerHighlighter = lastEditorHighlighter; lastEditorHighlighter = null; } if (!lowerHighlighter.isValid()) continue; int startLineIndex = lowerHighlighter.getDocument().getLineNumber(startOffset); if (!isValidLine(document, startLineIndex)) continue; int endLineIndex = lowerHighlighter.getDocument().getLineNumber(endOffset); if (!isValidLine(document, endLineIndex)) continue; processor.process(lowerHighlighter); } } finally { docHighlighters.dispose(); editorHighlighters.dispose(); } } private static boolean isValidLine(@NotNull Document document, int line) { if (line < 0) return false; int lineCount = document.getLineCount(); return lineCount == 0 ? line == 0 : line < lineCount; } private static boolean less(RangeHighlighter h1, RangeHighlighter h2) { return h1 != null && (h2 == null || h1.getStartOffset() < h2.getStartOffset()); } @Override public void revalidateMarkup() { updateSize(); } void updateSizeOnShowNotify() { updateSize(false, true); } public void updateSize() { updateSize(false, false); } void updateSize(boolean onLayout, boolean canShrink) { int prevHash = sizeHash(); if (!onLayout) { clearLineToGutterRenderersCache(); calcLineNumberAreaWidth(); calcLineMarkerAreaWidth(canShrink); calcAnnotationsSize(); } calcAnnotationExtraSize(); if (prevHash != sizeHash()) { fireResized(); } repaint(); } private int sizeHash() { int result = getLineMarkerAreaWidth(); result = 31 * result + myTextAnnotationGuttersSize; result = 31 * result + myTextAnnotationExtraSize; result = 31 * result + getLineNumberAreaWidth(); return result; } private void calcAnnotationsSize() { myTextAnnotationGuttersSize = 0; final int lineCount = Math.max(myEditor.getDocument().getLineCount(), 1); for (int j = 0; j < myTextAnnotationGutters.size(); j++) { TextAnnotationGutterProvider gutterProvider = myTextAnnotationGutters.get(j); int gutterSize = 0; for (int i = 0; i < lineCount; i++) { String lineText = gutterProvider.getLineText(i, myEditor); if (!StringUtil.isEmpty(lineText)) { EditorFontType style = gutterProvider.getStyle(i, myEditor); Font font = getFontForText(lineText, style); FontMetrics fontMetrics = getFontMetrics(font); gutterSize = Math.max(gutterSize, fontMetrics.stringWidth(lineText)); } } if (gutterSize > 0) gutterSize += getGapBetweenAnnotations(); myTextAnnotationGutterSizes.set(j, gutterSize); myTextAnnotationGuttersSize += gutterSize; } } private void calcAnnotationExtraSize() { myTextAnnotationExtraSize = 0; if (!myEditor.isInDistractionFreeMode() || isMirrored()) return; Window frame = SwingUtilities.getWindowAncestor(myEditor.getComponent()); if (frame == null) return; EditorSettings settings = myEditor.getSettings(); int rightMargin = settings.getRightMargin(myEditor.getProject()); if (rightMargin <= 0) return; JComponent editorComponent = myEditor.getComponent(); RelativePoint point = new RelativePoint(editorComponent, new Point(0, 0)); Point editorLocationInWindow = point.getPoint(frame); int editorLocationX = (int)editorLocationInWindow.getX(); int rightMarginX = rightMargin * EditorUtil.getSpaceWidth(Font.PLAIN, myEditor) + editorLocationX; int width = editorLocationX + editorComponent.getWidth(); if (rightMarginX < width && editorLocationX < width - rightMarginX) { int centeredSize = (width - rightMarginX - editorLocationX) / 2 - (getLineMarkerAreaWidth() + getLineNumberAreaWidth() + getFoldingAreaWidth() + 2 * getGapBetweenAreas()); myTextAnnotationExtraSize = Math.max(0, centeredSize - myTextAnnotationGuttersSize); } } private boolean logicalLinesMatchVisualOnes() { return myEditor.getSoftWrapModel().getSoftWrapsIntroducedLinesNumber() == 0 && myEditor.getFoldingModel().getTotalNumberOfFoldedLines() == 0; } void clearLineToGutterRenderersCache() { myLineToGutterRenderers = null; } private void buildGutterRenderersCache() { myLineToGutterRenderersCacheForLogicalLines = logicalLinesMatchVisualOnes(); myLineToGutterRenderers = new TIntObjectHashMap<>(); processRangeHighlighters(0, myEditor.getDocument().getTextLength(), highlighter -> { GutterMark renderer = highlighter.getGutterIconRenderer(); if (renderer == null) { return; } if (!areIconsShown() && !(renderer instanceof NonHideableIconGutterMark)) { return; } if (!isHighlighterVisible(highlighter)) { return; } int line = myEditor.offsetToVisualLine(highlighter.getStartOffset()); List<GutterMark> renderers = myLineToGutterRenderers.get(line); if (renderers == null) { renderers = new SmartList<>(); myLineToGutterRenderers.put(line, renderers); } renderers.add(renderer); }); myLineToGutterRenderers.transformValues(value -> { List<GutterMark> newValue = value; for (GutterMarkPreprocessor preprocessor : GutterMarkPreprocessor.EP_NAME.getExtensions()) { newValue = preprocessor.processMarkers(value); } if (newValue.size() >= 5) { // Don't allow more than 5 icons per line newValue = newValue.subList(0, 4); } return newValue; }); } private void calcLineMarkerAreaWidth(boolean canShrink) { myLeftFreePaintersAreaShown = myForceLeftFreePaintersAreaShown; myRightFreePaintersAreaShown = myForceRightFreePaintersAreaShown; processRangeHighlighters(0, myEditor.getDocument().getTextLength(), highlighter -> { LineMarkerRenderer lineMarkerRenderer = highlighter.getLineMarkerRenderer(); if (lineMarkerRenderer != null) { LineMarkerRendererEx.Position position = getLineMarkerPosition(lineMarkerRenderer); if (position == LineMarkerRendererEx.Position.LEFT && isLineMarkerVisible(highlighter)) myLeftFreePaintersAreaShown = true; if (position == LineMarkerRendererEx.Position.RIGHT && isLineMarkerVisible(highlighter)) myRightFreePaintersAreaShown = true; } }); int minWidth = areIconsShown() ? scaleWidth(myStartIconAreaWidth) : 0; myIconsAreaWidth = canShrink ? minWidth : Math.max(myIconsAreaWidth, minWidth); processGutterRenderers((line, renderers) -> { int width = 1; for (int i = 0; i < renderers.size(); i++) { GutterMark renderer = renderers.get(i); if (!checkDumbAware(renderer)) continue; width += scaleIcon(renderer.getIcon()).getIconWidth(); if (i > 0) width += getGapBetweenIcons(); } if (myIconsAreaWidth < width) { myIconsAreaWidth = width + 1; } return true; }); if (isDumbMode()) { myIconsAreaWidth = Math.max(myIconsAreaWidth, myLastNonDumbModeIconAreaWidth); } else { myLastNonDumbModeIconAreaWidth = myIconsAreaWidth; } } @Nullable private List<GutterMark> getGutterRenderers(int line) { if (myLineToGutterRenderers == null || myLineToGutterRenderersCacheForLogicalLines != logicalLinesMatchVisualOnes()) { buildGutterRenderersCache(); } return myLineToGutterRenderers.get(line); } private void processGutterRenderers(@NotNull TIntObjectProcedure<List<GutterMark>> processor) { if (myLineToGutterRenderers == null || myLineToGutterRenderersCacheForLogicalLines != logicalLinesMatchVisualOnes()) { buildGutterRenderersCache(); } myLineToGutterRenderers.forEachEntry(processor); } private boolean isHighlighterVisible(RangeHighlighter highlighter) { return !FoldingUtil.isHighlighterFolded(myEditor, highlighter); } private void paintGutterRenderers(final Graphics2D g, int firstVisibleOffset, int lastVisibleOffset, int firstVisibleLine, int lastVisibleLine) { Object hint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); try { List<RangeHighlighter> highlighters = new ArrayList<>(); processRangeHighlighters(firstVisibleOffset, lastVisibleOffset, highlighter -> { LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer(); if (renderer != null) highlighters.add(highlighter); }); ContainerUtil.sort(highlighters, Comparator.comparingInt(RangeHighlighter::getLayer)); for (RangeHighlighter highlighter : highlighters) { paintLineMarkerRenderer(highlighter, g); } } finally { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint); } paintIcons(firstVisibleLine, lastVisibleLine, g); } private void paintIcons(final int firstVisibleLine, final int lastVisibleLine, final Graphics2D g) { for (int line = firstVisibleLine; line <= lastVisibleLine; line++) { List<GutterMark> renderers = getGutterRenderers(line); if (renderers != null) { paintIconRow(line, renderers, g); } } } private void paintIconRow(int line, List<GutterMark> row, final Graphics2D g) { processIconsRow(line, row, (x, y, renderer) -> { Icon icon = scaleIcon(renderer.getIcon()); AffineTransform old = setMirrorTransformIfNeeded(g, x, icon.getIconWidth()); try { icon.paintIcon(this, g, x, y); } finally { if (old != null) g.setTransform(old); } }); } private void paintLineMarkerRenderer(RangeHighlighter highlighter, Graphics g) { LineMarkerRenderer lineMarkerRenderer = highlighter.getLineMarkerRenderer(); if (lineMarkerRenderer != null) { Rectangle rectangle = getLineRendererRectangle(highlighter); if (rectangle != null) { lineMarkerRenderer.paint(myEditor, g, rectangle); } } } private boolean isLineMarkerVisible(RangeHighlighter highlighter) { int startOffset = highlighter.getStartOffset(); int endOffset = highlighter.getEndOffset(); FoldRegion startFoldRegion = myEditor.getFoldingModel().getCollapsedRegionAtOffset(startOffset); FoldRegion endFoldRegion = myEditor.getFoldingModel().getCollapsedRegionAtOffset(endOffset); return startFoldRegion == null || !startFoldRegion.equals(endFoldRegion); } @Nullable private Rectangle getLineRendererRectangle(RangeHighlighter highlighter) { if (!isLineMarkerVisible(highlighter)) return null; int startOffset = highlighter.getStartOffset(); int endOffset = highlighter.getEndOffset(); int startY = myEditor.visibleLineToY(myEditor.offsetToVisualLine(startOffset)); // top edge of the last line of the highlighted area int endY = myEditor.visibleLineToY(myEditor.offsetToVisualLine(endOffset)); // => add one line height to make height correct (bottom edge of the highlighted area) endY += myEditor.getLineHeight(); LineMarkerRenderer renderer = ObjectUtils.assertNotNull(highlighter.getLineMarkerRenderer()); LineMarkerRendererEx.Position position = getLineMarkerPosition(renderer); int w; int x; switch (position) { case LEFT: w = getLeftFreePaintersAreaWidth(); x = getLeftFreePaintersAreaOffset(); break; case RIGHT: w = getRightFreePaintersAreaWidth(); x = getLineMarkerFreePaintersAreaOffset(); break; case CUSTOM: w = getWidth(); x = 0; break; default: throw new IllegalArgumentException(position.name()); } int height = endY - startY; return new Rectangle(x, startY, w, height); } @FunctionalInterface private interface LineGutterIconRendererProcessor { void process(int x, int y, @NotNull GutterMark renderer); } private float getEditorScaleFactor() { if (Registry.is("editor.scale.gutter.icons")) { float scale = myEditor.getScale(); if (Math.abs(1f - scale) > 0.10f) { return scale; } } return 1f; } private Icon scaleIcon(Icon icon) { float scale = getEditorScaleFactor(); return scale == 1 ? icon : IconUtil.scale(icon, this, scale); } private int scaleWidth(int width) { return (int) (getEditorScaleFactor() * width); } private void processIconsRow(int line, @NotNull List<GutterMark> row, @NotNull LineGutterIconRendererProcessor processor) { int middleCount = 0; int middleSize = 0; int x = getIconAreaOffset() + 2; final int y = myEditor.visibleLineToY(line); for (GutterMark r : row) { if (!checkDumbAware(r)) continue; final GutterIconRenderer.Alignment alignment = ((GutterIconRenderer)r).getAlignment(); final Icon icon = scaleIcon(r.getIcon()); if (alignment == GutterIconRenderer.Alignment.LEFT) { processor.process(x, y + getTextAlignmentShift(icon), r); x += icon.getIconWidth() + getGapBetweenIcons(); } else if (alignment == GutterIconRenderer.Alignment.CENTER) { middleCount++; middleSize += icon.getIconWidth() + getGapBetweenIcons(); } } final int leftSize = x - getIconAreaOffset(); x = getIconAreaOffset() + myIconsAreaWidth; for (GutterMark r : row) { if (!checkDumbAware(r)) continue; if (((GutterIconRenderer)r).getAlignment() == GutterIconRenderer.Alignment.RIGHT) { Icon icon = scaleIcon(r.getIcon()); x -= icon.getIconWidth(); processor.process(x, y + getTextAlignmentShift(icon), r); x -= getGapBetweenIcons(); } } int rightSize = myIconsAreaWidth + getIconAreaOffset() - x + 1; if (middleCount > 0) { middleSize -= getGapBetweenIcons(); x = getIconAreaOffset() + leftSize + (myIconsAreaWidth - leftSize - rightSize - middleSize) / 2; for (GutterMark r : row) { if (!checkDumbAware(r)) continue; if (((GutterIconRenderer)r).getAlignment() == GutterIconRenderer.Alignment.CENTER) { Icon icon = scaleIcon(r.getIcon()); processor.process(x, y + getTextAlignmentShift(icon), r); x += icon.getIconWidth() + getGapBetweenIcons(); } } } } private int getTextAlignmentShift(Icon icon) { int centerRelative = (myEditor.getLineHeight() - icon.getIconHeight()) / 2; int baselineRelative = myEditor.getAscent() - icon.getIconHeight(); return Math.max(centerRelative, baselineRelative); } private Color getOutlineColor(boolean isActive) { ColorKey key = isActive ? EditorColors.SELECTED_TEARLINE_COLOR : EditorColors.TEARLINE_COLOR; Color color = myEditor.getColorsScheme().getColor(key); return color != null ? color : JBColor.black; } @Override public void registerTextAnnotation(@NotNull TextAnnotationGutterProvider provider) { myTextAnnotationGutters.add(provider); myTextAnnotationGutterSizes.add(0); updateSize(); } @Override public void registerTextAnnotation(@NotNull TextAnnotationGutterProvider provider, @NotNull EditorGutterAction action) { myTextAnnotationGutters.add(provider); myProviderToListener.put(provider, action); myTextAnnotationGutterSizes.add(0); updateSize(); } private void doPaintFoldingTree(final Graphics2D g, final Rectangle clip, int firstVisibleOffset, int lastVisibleOffset) { final double width = getFoldingAnchorWidth2D(); Collection<DisplayedFoldingAnchor> anchorsToDisplay = myAnchorsDisplayStrategy.getAnchorsToDisplay(firstVisibleOffset, lastVisibleOffset, myActiveFoldRegion); for (DisplayedFoldingAnchor anchor : anchorsToDisplay) { drawFoldingAnchor(width, clip, g, anchor.visualLine, anchor.type, anchor.foldRegion == myActiveFoldRegion); } } private void paintFoldingLines(final Graphics2D g, final Rectangle clip) { boolean shown = isFoldingOutlineShown(); if ((shown || myEditor.isInDistractionFreeMode() && Registry.is("editor.distraction.gutter.separator")) && myPaintBackground) { g.setColor(getOutlineColor(false)); double x = getWhitespaceSeparatorOffset2D(); LinePainter2D.paint(g, x, clip.y, x, clip.y + clip.height, StrokeType.CENTERED, getStrokeWidth()); } if (!shown) return; final int anchorX = getFoldingAreaOffset(); final int width = getFoldingAnchorWidth(); if (myActiveFoldRegion != null && myActiveFoldRegion.isExpanded() && myActiveFoldRegion.isValid()) { int foldStart = myEditor.offsetToVisualLine(myActiveFoldRegion.getStartOffset()); int foldEnd = myEditor.offsetToVisualLine(getEndOffset(myActiveFoldRegion)); int startY = getLineCenterY(foldStart); int endY = getLineCenterY(foldEnd); if (startY <= clip.y + clip.height && endY + 1 + myEditor.getDescent() >= clip.y) { g.setColor(getOutlineColor(true)); int lineX = anchorX + width / 2; LinePainter2D.paint(g, lineX, startY, lineX, endY, StrokeType.CENTERED, getStrokeWidth()); } } } @Override public int getWhitespaceSeparatorOffset() { return (int)Math.round(getWhitespaceSeparatorOffset2D()); } private double getWhitespaceSeparatorOffset2D() { return PaintUtil.alignToInt(getFoldingAreaOffset() + getFoldingAnchorWidth() / 2, ScaleContext.create(myEditor.getComponent()), RoundingMode.ROUND, null); } void setActiveFoldRegion(FoldRegion activeFoldRegion) { if (myActiveFoldRegion != activeFoldRegion) { myActiveFoldRegion = activeFoldRegion; repaint(); } } private int getLineCenterY(int line) { return myEditor.visibleLineToY(line) + myEditor.getLineHeight() / 2; } private double getFoldAnchorY(int line, double width) { return myEditor.visibleLineToY(line) + myEditor.getAscent() - width; } int getHeadCenterY(FoldRegion foldRange) { return getLineCenterY(myEditor.offsetToVisualLine(foldRange.getStartOffset())); } private void drawFoldingAnchor(double width, Rectangle clip, Graphics2D g, int visualLine, DisplayedFoldingAnchor.Type type, boolean active) { double off = width / 4; double height = width + off; double baseHeight = height - width / 2; double y = getFoldAnchorY(visualLine, width); double centerX = LinePainter2D.getStrokeCenter(g, getWhitespaceSeparatorOffset2D(), StrokeType.CENTERED, getStrokeWidth()); double strokeOff = centerX - getWhitespaceSeparatorOffset2D(); // need to have the same sub-device-pixel offset as centerX for the square_with_plus rect to have equal dev width/height double centerY = PaintUtil.alignToInt(y + width / 2, g) + strokeOff; switch (type) { case COLLAPSED: if (y <= clip.y + clip.height && y + height >= clip.y) { drawSquareWithPlus(g, centerX, centerY, width, active); } break; case EXPANDED_TOP: if (y <= clip.y + clip.height && y + height >= clip.y) { drawDirectedBox(g, centerX, centerY, width, height, baseHeight, active); } break; case EXPANDED_BOTTOM: y += width; if (y - height <= clip.y + clip.height && y >= clip.y) { drawDirectedBox(g, centerX, centerY, width, -height, -baseHeight, active); } break; } } private int getEndOffset(FoldRegion foldRange) { LOG.assertTrue(foldRange.isValid(), foldRange); FoldingGroup group = foldRange.getGroup(); return group == null ? foldRange.getEndOffset() : myEditor.getFoldingModel().getEndOffset(group); } private void drawDirectedBox(Graphics2D g, double centerX, double centerY, double width, double height, double baseHeight, boolean active) { double sw = getStrokeWidth(); Rectangle2D rect = RectanglePainter2D.align(g, EnumSet.of(LinePainter2D.Align.CENTER_X, LinePainter2D.Align.CENTER_Y), centerX, centerY, width, width, StrokeType.CENTERED, sw); double x1 = rect.getX(); double x2 = x1 + rect.getWidth() - 1; double y = height > 0 ? rect.getY() : rect.getY() + rect.getHeight() - 1; double[] dxPoints = {x1, x1, x2, x2, centerX}; double[] dyPoints = {y + baseHeight, y, y, y + baseHeight, y + height + (height < 0 ? 1 : 0)}; g.setColor(myEditor.getBackgroundColor()); LinePainter2D.fillPolygon(g, dxPoints, dyPoints, 5, StrokeType.CENTERED_CAPS_SQUARE, sw, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(getOutlineColor(active)); LinePainter2D.paintPolygon(g, dxPoints, dyPoints, 5, StrokeType.CENTERED_CAPS_SQUARE, sw, RenderingHints.VALUE_ANTIALIAS_ON); drawPlusOrMinus(g, false, centerX, centerY, width, sw); } private void drawPlusOrMinus(Graphics2D g, boolean plus, double centerX, double centerY, double width, double strokeWidth) { double length = width - getSquareInnerOffset(width) * 2; Line2D line = LinePainter2D.align(g, EnumSet.of(LinePainter2D.Align.CENTER_X, LinePainter2D.Align.CENTER_Y), centerX, centerY, length, plus, StrokeType.CENTERED, strokeWidth); LinePainter2D.paint(g, line, StrokeType.CENTERED, strokeWidth, RenderingHints.VALUE_ANTIALIAS_OFF); } private void drawSquareWithPlus(Graphics2D g, double centerX, double centerY, double width, boolean active) { double sw = getStrokeWidth(); Rectangle2D rect = RectanglePainter2D.align(g, EnumSet.of(LinePainter2D.Align.CENTER_X, LinePainter2D.Align.CENTER_Y), centerX, centerY, width, width, StrokeType.CENTERED, sw); g.setColor(myEditor.getBackgroundColor()); RectanglePainter2D.FILL.paint(g, rect, null, StrokeType.CENTERED, sw, RenderingHints.VALUE_ANTIALIAS_OFF); g.setColor(getOutlineColor(active)); RectanglePainter2D.DRAW.paint(g, rect, null, StrokeType.CENTERED, sw, RenderingHints.VALUE_ANTIALIAS_OFF); drawPlusOrMinus(g, false, centerX, centerY, width, sw); drawPlusOrMinus(g, true, centerX, centerY, width, sw); } /** * Returns the gap between the sign and the square itself */ private double getSquareInnerOffset(double width) { return Math.max(width / 5, scale(2)); } private double scale(double v) { return JBUI.scale((float)v) * myEditor.getScale(); } private int getFoldingAnchorWidth() { return (int)Math.round(getFoldingAnchorWidth2D()); } private double getFoldingAnchorWidth2D() { return Math.min(scale(4f), myEditor.getLineHeight() / 2f - JBUI.scale(2f)) * 2; } private double getStrokeWidth() { double sw = UIUtil.isJreHiDPIEnabled() || scale(1f) < 2 ? 1 : 2; ScaleContext ctx = ScaleContext.create(myEditor.getComponent()); return PaintUtil.alignToInt(sw, ctx, PaintUtil.devValue(1, ctx) > 2 ? RoundingMode.FLOOR : RoundingMode.ROUND, null); } private int getFoldingAreaOffset() { return getLineMarkerAreaOffset() + getLineMarkerAreaWidth(); } private int getFoldingAreaWidth() { return isFoldingOutlineShown() ? getFoldingAnchorWidth() + JBUI.scale(2) : isRealEditor() ? getFoldingAnchorWidth() : 0; } private boolean isRealEditor() { return EditorUtil.isRealFileEditor(myEditor); } private boolean isLineMarkersShown() { return myEditor.getSettings().isLineMarkerAreaShown(); } private boolean areIconsShown() { return myEditor.getSettings().areGutterIconsShown(); } private boolean isLineNumbersShown() { return myEditor.getSettings().isLineNumbersShown(); } @Override public boolean isAnnotationsShown() { return !myTextAnnotationGutters.isEmpty(); } private boolean isFoldingOutlineShown() { return myEditor.getSettings().isFoldingOutlineShown() && myEditor.getFoldingModel().isFoldingEnabled() && !myEditor.isInPresentationMode(); } private static int getGapBetweenAreas() { return GAP_BETWEEN_AREAS.get(); } private static int getAreaWidthWithGap(int width) { if (width > 0) { return width + getGapBetweenAreas(); } return 0; } private static int getGapBetweenIcons() { return GAP_BETWEEN_ICONS.get(); } private static int getGapBetweenAnnotations() { return GAP_BETWEEN_ANNOTATIONS.get(); } private int getLineNumberAreaWidth() { return isLineNumbersShown() ? myLineNumberAreaWidth + getAreaWidthWithGap(myAdditionalLineNumberAreaWidth) : 0; } private int getLineMarkerAreaWidth() { return isLineMarkersShown() ? getLeftFreePaintersAreaWidth() + myIconsAreaWidth + getGapAfterIconsArea() + getRightFreePaintersAreaWidth() : 0; } private void calcLineNumberAreaWidth() { if (!isLineNumbersShown()) return; int maxLineNumber = getMaxLineNumber(myLineNumberConvertor); myLineNumberAreaWidth = calcLineNumbersAreaWidth(maxLineNumber); myAdditionalLineNumberAreaWidth = 0; if (myAdditionalLineNumberConvertor != null) { int maxAdditionalLineNumber = getMaxLineNumber(myAdditionalLineNumberConvertor); myAdditionalLineNumberAreaWidth = calcLineNumbersAreaWidth(maxAdditionalLineNumber); } } private int getMaxLineNumber(@NotNull TIntFunction convertor) { for (int i = endLineNumber(); i >= 0; i--) { int number = convertor.execute(i); if (number >= 0) { return number; } } return 0; } @Nullable EditorMouseEventArea getEditorMouseAreaByOffset(int offset) { if (isLineNumbersShown() && offset < getLineNumberAreaOffset() + getLineNumberAreaWidth()) { return EditorMouseEventArea.LINE_NUMBERS_AREA; } if (isAnnotationsShown() && offset < getAnnotationsAreaOffset() + getAnnotationsAreaWidth()) { return EditorMouseEventArea.ANNOTATIONS_AREA; } if (isLineMarkersShown() && offset < getFoldingAreaOffset()) { return EditorMouseEventArea.LINE_MARKERS_AREA; } if (isFoldingOutlineShown() && offset < getFoldingAreaOffset() + getFoldingAreaWidth()) { return EditorMouseEventArea.FOLDING_OUTLINE_AREA; } return null; } private int getLineNumberAreaOffset() { if (getLineNumberAreaWidth() == 0 && getAnnotationsAreaWidthEx() == 0 && getLineMarkerAreaWidth() == 0) { return getFoldingAreaWidth() == 0 ? 0 : 1; } if (getLineNumberAreaWidth() == 0 && getAnnotationsAreaWidthEx() > 0) { return 0; // no gap if annotations area is the first visible } return getGapBetweenAreas(); } @Override public int getAnnotationsAreaOffset() { return getLineNumberAreaOffset() + getAreaWidthWithGap(getLineNumberAreaWidth()); } @Override public int getAnnotationsAreaWidth() { return myTextAnnotationGuttersSize; } private int getAnnotationsAreaWidthEx() { return myTextAnnotationGuttersSize + myTextAnnotationExtraSize; } @Override public int getLineMarkerAreaOffset() { return getAnnotationsAreaOffset() + getAreaWidthWithGap(getAnnotationsAreaWidthEx()); } @Override public int getIconAreaOffset() { return getLineMarkerAreaOffset() + getLeftFreePaintersAreaWidth(); } private int getLeftFreePaintersAreaOffset() { return getLineMarkerAreaOffset(); } @Override public int getLineMarkerFreePaintersAreaOffset() { return getIconAreaOffset() + myIconsAreaWidth + getGapAfterIconsArea(); } private int getLeftFreePaintersAreaWidth() { return myLeftFreePaintersAreaShown ? FREE_PAINTERS_LEFT_AREA_WIDTH.get() : 0; } private int getRightFreePaintersAreaWidth() { return myRightFreePaintersAreaShown ? FREE_PAINTERS_RIGHT_AREA_WIDTH.get() : 0; } @Override public int getIconsAreaWidth() { return myIconsAreaWidth; } private int getGapAfterIconsArea() { return isRealEditor() && areIconsShown() ? getGapBetweenAreas() : 0; } private boolean isMirrored() { return myEditor.getVerticalScrollbarOrientation() != EditorEx.VERTICAL_SCROLLBAR_RIGHT; } @Nullable private AffineTransform setMirrorTransformIfNeeded(Graphics2D g, int offset, int width) { if (isMirrored()) { AffineTransform old = g.getTransform(); AffineTransform transform = new AffineTransform(old); transform.scale(-1, 1); transform.translate(-offset * 2 - width, 0); g.setTransform(transform); return old; } else { return null; } } @Nullable @Override public FoldRegion findFoldingAnchorAt(int x, int y) { if (!myEditor.getSettings().isFoldingOutlineShown()) return null; int anchorX = getFoldingAreaOffset(); int anchorWidth = getFoldingAnchorWidth(); int visualLine = myEditor.yToVisibleLine(y); int neighbourhoodStartOffset = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(visualLine, 0))); int neighbourhoodEndOffset = myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(visualLine, Integer.MAX_VALUE))); Collection<DisplayedFoldingAnchor> displayedAnchors = myAnchorsDisplayStrategy.getAnchorsToDisplay(neighbourhoodStartOffset, neighbourhoodEndOffset, null); x = convertX(x); for (DisplayedFoldingAnchor anchor : displayedAnchors) { Rectangle r = rectangleByFoldOffset(anchor.visualLine, anchorWidth, anchorX); if (r.x < x && x <= (r.x + r.width) && r.y < y && y <= (r.y + r.height)) return anchor.foldRegion; } return null; } @SuppressWarnings("SuspiciousNameCombination") private Rectangle rectangleByFoldOffset(int foldStart, int anchorWidth, int anchorX) { return new Rectangle(anchorX, (int)getFoldAnchorY(foldStart, anchorWidth), anchorWidth, anchorWidth); } @Override public void mouseDragged(MouseEvent e) { TooltipController.getInstance().cancelTooltips(); } @Override public void mouseMoved(final MouseEvent e) { final GutterIconRenderer renderer = getGutterRenderer(e); if (renderer == null) { TextAnnotationGutterProvider provider = getProviderAtPoint(e.getPoint()); String toolTip = null; if (provider == null) { ActiveGutterRenderer lineRenderer = getActiveRendererByMouseEvent(e); if (lineRenderer != null) { toolTip = lineRenderer.getTooltipText(); } } else { final int line = getLineNumAtPoint(e.getPoint()); toolTip = provider.getToolTip(line, myEditor); if (!Comparing.equal(toolTip, myLastGutterToolTip)) { TooltipController.getInstance().cancelTooltip(GUTTER_TOOLTIP_GROUP, e, true); myLastGutterToolTip = toolTip; } } tooltipAvailable(toolTip, e, null); } else { computeTooltipInBackground(renderer, e); } } private GutterIconRenderer myCalculatingInBackground; private ProgressIndicator myBackgroundIndicator = new EmptyProgressIndicator(); private void computeTooltipInBackground(@NotNull GutterIconRenderer renderer, @NotNull MouseEvent e) { if (myCalculatingInBackground == renderer && !myBackgroundIndicator.isCanceled()) return; // not yet calculated myCalculatingInBackground = renderer; myBackgroundIndicator.cancel(); myBackgroundIndicator = new ProgressIndicatorBase(); AtomicReference<String> tooltip = new AtomicReference<>(); ProgressManager.getInstance().runProcessWithProgressAsynchronously(new Task.Backgroundable(myEditor.getProject(), "Constructing Tooltip") { @Override public void run(@NotNull ProgressIndicator indicator) { tooltip.set(ReadAction.compute(() -> renderer.getTooltipText())); } @Override public void onSuccess() { tooltipAvailable(tooltip.get(), e, renderer); } }, myBackgroundIndicator); } private void tooltipAvailable(@Nullable String toolTip, @NotNull MouseEvent e, @Nullable GutterIconRenderer renderer) { myCalculatingInBackground = null; TooltipController controller = TooltipController.getInstance(); if (toolTip == null || toolTip.isEmpty() || myEditor.isDisposed()) { controller.cancelTooltip(GUTTER_TOOLTIP_GROUP, e, false); } else { final Ref<Point> t = new Ref<>(e.getPoint()); int line = myEditor.yToVisibleLine(e.getY()); List<GutterMark> row = getGutterRenderers(line); Balloon.Position ballPosition = Balloon.Position.atRight; if (row != null) { Map<Integer, GutterMark> xPos = new TreeMap<>(); final int[] currentPos = {0}; processIconsRow(line, row, (x, y, r) -> { xPos.put(x, r); if (renderer == r) { currentPos[0] = x; Icon icon = scaleIcon(r.getIcon()); t.set(new Point(x + icon.getIconWidth() / 2, y + icon.getIconHeight() / 2)); } }); List<Integer> xx = new ArrayList<>(xPos.keySet()); int posIndex = xx.indexOf(currentPos[0]); if (xPos.size() > 1 && posIndex == 0) { ballPosition = Balloon.Position.below; } } RelativePoint showPoint = new RelativePoint(this, t.get()); TooltipRenderer tr = ((EditorMarkupModel)myEditor.getMarkupModel()).getErrorStripTooltipRendererProvider().calcTooltipRenderer(toolTip); HintHint hint = new HintHint(this, t.get()).setAwtTooltip(true).setPreferredPosition(ballPosition); if (myEditor.getComponent().getRootPane() != null) { controller.showTooltipByMouseMove(myEditor, showPoint, tr, false, GUTTER_TOOLTIP_GROUP, hint); } } } void validateMousePointer(@NotNull MouseEvent e) { if (IdeGlassPaneImpl.hasPreProcessedCursor(this)) return; FoldRegion foldingAtCursor = findFoldingAnchorAt(e.getX(), e.getY()); setActiveFoldRegion(foldingAtCursor); Cursor cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); if (foldingAtCursor != null) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } GutterIconRenderer renderer = getGutterRenderer(e); if (renderer != null) { if (renderer.isNavigateAction()) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } } else { ActiveGutterRenderer lineRenderer = getActiveRendererByMouseEvent(e); if (lineRenderer != null) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } else { TextAnnotationGutterProvider provider = getProviderAtPoint(e.getPoint()); if (provider != null) { if (myProviderToListener.containsKey(provider)) { EditorGutterAction action = myProviderToListener.get(provider); if (action != null) { int line = getLineNumAtPoint(e.getPoint()); cursor = action.getCursor(line); } } } } } UIUtil.setCursor(this, cursor); } @Override public void mouseClicked(MouseEvent e) { if (e.isPopupTrigger()) { invokePopup(e); } } private void fireEventToTextAnnotationListeners(final MouseEvent e) { if (myEditor.getMouseEventArea(e) == EditorMouseEventArea.ANNOTATIONS_AREA) { final Point clickPoint = e.getPoint(); final TextAnnotationGutterProvider provider = getProviderAtPoint(clickPoint); if (provider == null) { return; } if (myProviderToListener.containsKey(provider)) { int line = getLineNumAtPoint(clickPoint); if (line >= 0 && line < myEditor.getDocument().getLineCount() && UIUtil.isActionClick(e, MouseEvent.MOUSE_RELEASED)) { myProviderToListener.get(provider).doAction(line); } } } } private int getLineNumAtPoint(final Point clickPoint) { return EditorUtil.yPositionToLogicalLine(myEditor, clickPoint); } @Nullable private TextAnnotationGutterProvider getProviderAtPoint(final Point clickPoint) { int current = getAnnotationsAreaOffset(); if (clickPoint.x < current) return null; for (int i = 0; i < myTextAnnotationGutterSizes.size(); i++) { current += myTextAnnotationGutterSizes.get(i); if (clickPoint.x <= current) return myTextAnnotationGutters.get(i); } return null; } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger() || isPopupAction(e)) { invokePopup(e); } else if (UIUtil.isCloseClick(e)) { processClose(e); } } private boolean isPopupAction(MouseEvent e) { GutterIconRenderer renderer = getGutterRenderer(e); return renderer != null && renderer.getClickAction() == null && renderer.getPopupMenuActions() != null; } @Override public void mouseReleased(final MouseEvent e) { if (e.isPopupTrigger()) { invokePopup(e); return; } GutterIconRenderer renderer = getGutterRenderer(e); AnAction clickAction = null; if (renderer != null && e.getButton() < 4) { clickAction = BitUtil.isSet(e.getModifiers(), InputEvent.BUTTON2_MASK) ? renderer.getMiddleButtonClickAction() : renderer.getClickAction(); } if (clickAction != null) { performAction(clickAction, e, "ICON_NAVIGATION", myEditor.getDataContext()); repaint(); e.consume(); } else { ActiveGutterRenderer lineRenderer = getActiveRendererByMouseEvent(e); if (lineRenderer != null) { lineRenderer.doAction(myEditor, e); } else { fireEventToTextAnnotationListeners(e); } } } private boolean isDumbMode() { Project project = myEditor.getProject(); return project != null && DumbService.isDumb(project); } private boolean checkDumbAware(@NotNull Object possiblyDumbAware) { return !isDumbMode() || DumbService.isDumbAware(possiblyDumbAware); } private void notifyNotDumbAware() { Project project = myEditor.getProject(); if (project != null) { DumbService.getInstance(project).showDumbModeNotification("This functionality is not available during indexing"); } } private void performAction(@NotNull AnAction action, @NotNull InputEvent e, @NotNull String place, @NotNull DataContext context) { if (!checkDumbAware(action)) { notifyNotDumbAware(); return; } AnActionEvent actionEvent = AnActionEvent.createFromAnAction(action, e, place, context); action.update(actionEvent); if (actionEvent.getPresentation().isEnabledAndVisible()) { ActionUtil.performActionDumbAwareWithCallbacks(action, actionEvent, context); } } @Nullable private ActiveGutterRenderer getActiveRendererByMouseEvent(final MouseEvent e) { if (findFoldingAnchorAt(e.getX(), e.getY()) != null) { return null; } if (e.isConsumed() || e.getX() > getWhitespaceSeparatorOffset()) { return null; } final ActiveGutterRenderer[] gutterRenderer = {null}; final int[] layer = {-1}; Rectangle clip = myEditor.getScrollingModel().getVisibleArea(); int firstVisibleOffset = myEditor.logicalPositionToOffset( myEditor.xyToLogicalPosition(new Point(0, clip.y - myEditor.getLineHeight()))); int lastVisibleOffset = myEditor.logicalPositionToOffset( myEditor.xyToLogicalPosition(new Point(0, clip.y + clip.height + myEditor.getLineHeight()))); processRangeHighlighters(firstVisibleOffset, lastVisibleOffset, highlighter -> { LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer(); if (renderer == null) return; if (gutterRenderer[0] != null && layer[0] >= highlighter.getLayer()) return; Rectangle rectangle = getLineRendererRectangle(highlighter); if (rectangle == null) return; int startY = rectangle.y; int endY = startY + rectangle.height; if (startY == endY) { endY += myEditor.getLineHeight(); } if (startY < e.getY() && e.getY() <= endY && renderer instanceof ActiveGutterRenderer && ((ActiveGutterRenderer)renderer).canDoAction(myEditor, e)) { gutterRenderer[0] = (ActiveGutterRenderer)renderer; layer[0] = highlighter.getLayer(); } }); return gutterRenderer[0]; } @Override public void closeAllAnnotations() { for (TextAnnotationGutterProvider provider : myTextAnnotationGutters) { provider.gutterClosed(); } revalidateSizes(); } private void revalidateSizes() { myTextAnnotationGutters = new ArrayList<>(); myTextAnnotationGutterSizes = new TIntArrayList(); updateSize(); } private class CloseAnnotationsAction extends DumbAwareAction { CloseAnnotationsAction() { super(EditorBundle.message("close.editor.annotations.action.name")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { closeAllAnnotations(); } } @Override @Nullable public Point getCenterPoint(final GutterIconRenderer renderer) { final Ref<Point> result = Ref.create(); if (!areIconsShown()) { processGutterRenderers((line, renderers) -> { if (ContainerUtil.find(renderers, renderer) != null) { result.set(new Point(getIconAreaOffset(), getLineCenterY(line))); return false; } return true; }); } else { processGutterRenderers((line, renderers) -> { processIconsRow(line, renderers, (x, y, r) -> { if (result.isNull() && r.equals(renderer)) { Icon icon = scaleIcon(r.getIcon()); result.set(new Point(x + icon.getIconWidth() / 2, y + icon.getIconHeight() / 2)); } }); return result.isNull(); }); } return result.get(); } @Override public void setLineNumberConvertor(@Nullable TIntFunction lineNumberConvertor) { setLineNumberConvertor(lineNumberConvertor, null); } @Override public void setLineNumberConvertor(@Nullable TIntFunction lineNumberConvertor1, @Nullable TIntFunction lineNumberConvertor2) { myLineNumberConvertor = lineNumberConvertor1 != null ? lineNumberConvertor1 : value -> value; myAdditionalLineNumberConvertor = lineNumberConvertor2; } @Override public void setShowDefaultGutterPopup(boolean show) { myShowDefaultGutterPopup = show; } @Override public void setGutterPopupGroup(@Nullable ActionGroup group) { myCustomGutterPopupGroup = group; } @Override public void setPaintBackground(boolean value) { myPaintBackground = value; } @Override public void setForceShowLeftFreePaintersArea(boolean value) { myForceLeftFreePaintersAreaShown = value; } @Override public void setForceShowRightFreePaintersArea(boolean value) { myForceRightFreePaintersAreaShown = value; } @Override public void setInitialIconAreaWidth(int width) { myStartIconAreaWidth = width; } private void invokePopup(MouseEvent e) { final ActionManager actionManager = ActionManager.getInstance(); if (myEditor.getMouseEventArea(e) == EditorMouseEventArea.ANNOTATIONS_AREA) { DefaultActionGroup actionGroup = new DefaultActionGroup(EditorBundle.message("editor.annotations.action.group.name"), true); actionGroup.add(new CloseAnnotationsAction()); final List<AnAction> addActions = new ArrayList<>(); final Point p = e.getPoint(); int line = EditorUtil.yPositionToLogicalLine(myEditor, p); //if (line >= myEditor.getDocument().getLineCount()) return; for (TextAnnotationGutterProvider gutterProvider : myTextAnnotationGutters) { final List<AnAction> list = gutterProvider.getPopupActions(line, myEditor); if (list != null) { for (AnAction action : list) { if (! addActions.contains(action)) { addActions.add(action); } } } } for (AnAction addAction : addActions) { actionGroup.add(addAction); } JPopupMenu menu = actionManager.createActionPopupMenu("", actionGroup).getComponent(); menu.show(this, e.getX(), e.getY()); e.consume(); } else { GutterIconRenderer renderer = getGutterRenderer(e); if (renderer != null) { AnAction rightButtonAction = renderer.getRightButtonClickAction(); if (rightButtonAction != null) { performAction(rightButtonAction, e, "ICON_NAVIGATION_SECONDARY_BUTTON", myEditor.getDataContext()); e.consume(); } else { ActionGroup actionGroup = renderer.getPopupMenuActions(); if (actionGroup != null) { if (checkDumbAware(actionGroup)) { actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, actionGroup).getComponent().show(this, e.getX(), e.getY()); } else { notifyNotDumbAware(); } e.consume(); } } } else { ActionGroup group = myCustomGutterPopupGroup; if (group == null && myShowDefaultGutterPopup) { group = (ActionGroup)CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_EDITOR_GUTTER); } if (group != null) { ActionPopupMenu popupMenu = actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group); popupMenu.getComponent().show(this, e.getX(), e.getY()); } e.consume(); } } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { TooltipController.getInstance().cancelTooltip(GUTTER_TOOLTIP_GROUP, e, false); } private int convertPointToLineNumber(final Point p) { DocumentEx document = myEditor.getDocument(); int line = EditorUtil.yPositionToLogicalLine(myEditor, p); if (!isValidLine(document, line)) return -1; int startOffset = document.getLineStartOffset(line); final FoldRegion region = myEditor.getFoldingModel().getCollapsedRegionAtOffset(startOffset); if (region != null) { return document.getLineNumber(region.getEndOffset()); } return line; } @Override @Nullable public GutterMark getGutterRenderer(final Point p) { int line = myEditor.yToVisibleLine(p.y); List<GutterMark> renderers = getGutterRenderers(line); if (renderers == null) { return null; } final GutterMark[] result = {null}; processIconsRow(line, renderers, (x, y, renderer) -> { final int ex = convertX((int)p.getX()); Icon icon = scaleIcon(renderer.getIcon()); // Do not check y to extend the area where users could click if (x <= ex && ex <= x + icon.getIconWidth()) { result[0] = renderer; } }); return result[0]; } @Nullable private GutterIconRenderer getGutterRenderer(final MouseEvent e) { return (GutterIconRenderer)getGutterRenderer(e.getPoint()); } @NotNull private static LineMarkerRendererEx.Position getLineMarkerPosition(@NotNull LineMarkerRenderer renderer) { if (renderer instanceof LineMarkerRendererEx) { return ((LineMarkerRendererEx)renderer).getPosition(); } return LineMarkerRendererEx.Position.RIGHT; } int convertX(int x) { if (!isMirrored()) return x; return getWidth() - x; } public void dispose() { for (TextAnnotationGutterProvider gutterProvider : myTextAnnotationGutters) { gutterProvider.gutterClosed(); } myProviderToListener.clear(); } }
{ "content_hash": "1f7b607a99bb9da7ffac6dec788fa56a", "timestamp": "", "source": "github", "line_count": 1976, "max_line_length": 158, "avg_line_length": 37.91801619433198, "alnum_prop": 0.682540106238155, "repo_name": "jk1/intellij-community", "id": "c8f21e5f391f3730778a2c1af3c98be384e17b4b", "size": "74926", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:40 PST 2014 --> <title>Uses of Class javax.sql.rowset.serial.SerialArray (Java Platform SE 7 )</title> <meta name="date" content="2014-12-18"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class javax.sql.rowset.serial.SerialArray (Java Platform SE 7 )"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../javax/sql/rowset/serial/SerialArray.html" title="class in javax.sql.rowset.serial">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/sql/rowset/serial/class-use/SerialArray.html" target="_top">Frames</a></li> <li><a href="SerialArray.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class javax.sql.rowset.serial.SerialArray" class="title">Uses of Class<br>javax.sql.rowset.serial.SerialArray</h2> </div> <div class="classUseContainer">No usage of javax.sql.rowset.serial.SerialArray</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../javax/sql/rowset/serial/SerialArray.html" title="class in javax.sql.rowset.serial">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;7</strong></em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?javax/sql/rowset/serial/class-use/SerialArray.html" target="_top">Frames</a></li> <li><a href="SerialArray.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../../legal/cpyr.html">Copyright</a> &#x00a9; 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
{ "content_hash": "0047eaef434f1e7795fbefdc6f3ad3dd", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 602, "avg_line_length": 42.398305084745765, "alnum_prop": 0.6310213871676994, "repo_name": "fbiville/annotation-processing-ftw", "id": "4b3a69b90bf9c5781a98ad13d8bf5274a30ab451", "size": "5003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/java/jdk7/javax/sql/rowset/serial/class-use/SerialArray.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "191178" }, { "name": "HTML", "bytes": "63904" }, { "name": "Java", "bytes": "107042" }, { "name": "JavaScript", "bytes": "246677" } ], "symlink_target": "" }
<?php namespace PDepend\Source\AST; /** * This class encapsulates possible default values for functions, methods, * parameters and properties. We use a separate class because otherwise you * cannot differentiate between no default value and a scalar <b>null</b>. * * @copyright 2008-2015 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @since 0.9.5 */ class ASTValue { /** * Boolean flag that is <b>true</b> when a PHP-value was set. * * @var boolean */ private $valueAvailable = false; /** * The parsed PHP-value, * * @var mixed */ private $value = null; /** * This method will return the parsed PHP value. * * @return mixed */ public function getValue() { return $this->value; } /** * This method will set the parsed PHP-value. Please note that this method * acts as a one-way-function, only the first call with set the value all * following calls will be ignored. * * @param mixed $value The parsed PHP-value. * * @return void */ public function setValue($value) { if ($this->valueAvailable === false) { $this->value = $value; $this->valueAvailable = true; } } /** * This method will return <b>true</b> when the PHP-value is already set. * * @return boolean */ public function isValueAvailable() { return $this->valueAvailable; } }
{ "content_hash": "6a2985eeb4a4617e21aedd6b82d0249a", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 78, "avg_line_length": 23.34328358208955, "alnum_prop": 0.592071611253197, "repo_name": "fsaibene/TPlaboratorioIV2016", "id": "6de89cd169cf8c31d560ca391b8d0a3dea5465f1", "size": "3400", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "vendor/pdepend/pdepend/src/main/php/PDepend/Source/AST/ASTValue.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20559" }, { "name": "HTML", "bytes": "21464" }, { "name": "JavaScript", "bytes": "43603" }, { "name": "PHP", "bytes": "1907865" } ], "symlink_target": "" }
namespace krystle { ConnectionPool::ConnectionPool():_pool(10000){} Connection* ConnectionPool::get(boost::asio::io_service& ioService) { Connection* connection; if (!_pool.pop(connection)) { std::cerr << "[create new connection]" << std::endl; connection = new Connection(ioService, this); } else { std::cerr << "[recycle connection]" << std::endl; } return connection; } void ConnectionPool::reset() { Connection* connection = NULL; do { if (connection != NULL) { delete connection; } } while(_pool.pop(connection)); } void ConnectionPool::add(Connection* connection) { if (!_pool.push(connection)) { std::cerr << "[could not reuse connection]" << std::endl; } } } // dushi
{ "content_hash": "f92c6d811b27b35e640c41f21d58b64c", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 67, "avg_line_length": 20.53846153846154, "alnum_prop": 0.5892634207240949, "repo_name": "signalfrax/krystle", "id": "ff55117664fb9171ab7c7a35f5f9199203d4234c", "size": "2353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ConnectionPool.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "529790" }, { "name": "C++", "bytes": "2835209" }, { "name": "IDL", "bytes": "2801" }, { "name": "Perl", "bytes": "5058" }, { "name": "Python", "bytes": "183962" }, { "name": "Shell", "bytes": "292107" } ], "symlink_target": "" }
namespace Azure.ResourceManager.MachineLearning.Models { /// <summary> HDInsight compute properties. </summary> public partial class HDInsightProperties { /// <summary> Initializes a new instance of HDInsightProperties. </summary> public HDInsightProperties() { } /// <summary> Initializes a new instance of HDInsightProperties. </summary> /// <param name="sshPort"> Port open for ssh connections on the master node of the cluster. </param> /// <param name="address"> Public IP address of the master node of the cluster. </param> /// <param name="administratorAccount"> Admin credentials for master node of the cluster. </param> internal HDInsightProperties(int? sshPort, string address, VirtualMachineSshCredentials administratorAccount) { SshPort = sshPort; Address = address; AdministratorAccount = administratorAccount; } /// <summary> Port open for ssh connections on the master node of the cluster. </summary> public int? SshPort { get; set; } /// <summary> Public IP address of the master node of the cluster. </summary> public string Address { get; set; } /// <summary> Admin credentials for master node of the cluster. </summary> public VirtualMachineSshCredentials AdministratorAccount { get; set; } } }
{ "content_hash": "4ff0793b9054b788b2f46d40d137adbe", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 117, "avg_line_length": 48.41379310344828, "alnum_prop": 0.6616809116809117, "repo_name": "Azure/azure-sdk-for-net", "id": "35a7b7be0f0396f8b4dc4c93d6f62d41b3a8e0b8", "size": "1542", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/machinelearningservices/Azure.ResourceManager.MachineLearning/src/Generated/Models/HDInsightProperties.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.gmail.brian.broll.taxidash.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Parcelable; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import it.gmariotti.cardslib.library.internal.Card; import it.gmariotti.cardslib.library.internal.CardArrayAdapter; import it.gmariotti.cardslib.library.view.CardListView; public class LocationFinder extends NavigationActivity implements GoogleMap.OnMarkerClickListener { private Driver currentDriver = null; private Geocoder geocoder; private Ride trip = null; private GoogleMap map; private Card.OnCardClickListener selectLocation = null; private List<Card> searchResults = new ArrayList<Card>(); private List<Marker> markers = new ArrayList<Marker>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View contentView = inflater.inflate(R.layout.activity_location_finder, null, false); content.addView(contentView, 0); //Get driver Intent intent = getIntent(); if(intent.hasExtra("Driver")){ this.currentDriver = intent.getParcelableExtra("Driver"); } //Initialize geocoder if(geocoder == null){ geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); } //Get the map map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); map.setOnMarkerClickListener(this); //Create new trip LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); this.trip = new Ride(latitude, longitude); //Create card listener selectLocation = new Card.OnCardClickListener() { @Override public void onClick(Card card, View view) { Address endpoint = ((LocationCard) card).getAddress(); trip.setEndPoint(endpoint.getLatitude(), endpoint.getLongitude()); //Move to the new activity Intent mapTrip = new Intent(getApplicationContext(), FareEstimator.class); mapTrip.putExtra("Driver", (Parcelable) currentDriver); mapTrip.putExtra("Ride", trip); startActivity(mapTrip); } }; //Add text changed listener EditText search = (EditText) findViewById(R.id.search); search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if(s.length() > 0) { searchLocations(s.toString()); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.location_finder, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //Search button pressed public void searchLocations(String query){ //Remove old results searchResults.clear(); Log.i("SEARCHING", "FOR " + query); //Populate the card list with results (within a lat long of curr location) double left = trip.getStartLongitude() - 1; double right = trip.getStartLongitude() + 1; double top = trip.getStartLatitude() - 1; double bottom = trip.getStartLatitude() + 1; try { List<Address> results = geocoder.getFromLocationName(query, 7, bottom, left, top, right); Log.i("GEOCODER", "FOUND " + results.size() + " RESULTS"); markers.clear(); for(Address result : results) { //addCard(result); addPin(result); } //Set up the card list CardListView list = (CardListView) findViewById(R.id.search_results); CardArrayAdapter adapter = new CardArrayAdapter(this, searchResults); list.setAdapter(adapter); } catch (IOException e) { e.printStackTrace(); } } private void addPin(Address addr){ markers.add(this.map.addMarker(new MarkerOptions() .position(new LatLng(addr.getLatitude(), addr.getLongitude())) .title(addr.getFeatureName()))); } private void addCard(Address addr){ //Create the card Card card = new LocationCard(getApplicationContext(), addr); //Add click listener card.setOnClickListener(selectLocation); searchResults.add(card); } @Override public boolean onMarkerClick(Marker marker) { LatLng endpoint = marker.getPosition(); trip.setEndPoint(endpoint.latitude, endpoint.longitude); //Move to the new activity Intent mapTrip = new Intent(getApplicationContext(), FareEstimator.class); mapTrip.putExtra("Driver", (Parcelable) currentDriver); mapTrip.putExtra("Ride", trip); startActivity(mapTrip); return true; } }
{ "content_hash": "d19ed193c972c75c4a030bc4824a2037", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 101, "avg_line_length": 35.66842105263158, "alnum_prop": 0.6498450641876937, "repo_name": "TaxiDash/Android", "id": "6ae71df10f318bdf5ae280031420d01582c7bb2e", "size": "6777", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/gmail/brian/broll/taxidash/app/LocationFinder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "2220" }, { "name": "Java", "bytes": "349947" }, { "name": "Shell", "bytes": "8" } ], "symlink_target": "" }
package y import ( "bytes" "encoding/binary" "fmt" "hash/crc32" "io" "math" "os" "reflect" "strconv" "sync" "time" "unsafe" "github.com/dgraph-io/badger/v3/pb" "github.com/dgraph-io/ristretto/z" "github.com/pkg/errors" ) var ( // ErrEOF indicates an end of file when trying to read from a memory mapped file // and encountering the end of slice. ErrEOF = errors.New("ErrEOF: End of file") // ErrCommitAfterFinish indicates that write batch commit was called after // finish ErrCommitAfterFinish = errors.New("Batch commit not permitted after finish") ) type Flags int const ( // Sync indicates that O_DSYNC should be set on the underlying file, // ensuring that data writes do not return until the data is flushed // to disk. Sync Flags = 1 << iota // ReadOnly opens the underlying file on a read-only basis. ReadOnly ) var ( // This is O_DSYNC (datasync) on platforms that support it -- see file_unix.go datasyncFileFlag = 0x0 // CastagnoliCrcTable is a CRC32 polynomial table CastagnoliCrcTable = crc32.MakeTable(crc32.Castagnoli) ) // OpenExistingFile opens an existing file, errors if it doesn't exist. func OpenExistingFile(filename string, flags Flags) (*os.File, error) { openFlags := os.O_RDWR if flags&ReadOnly != 0 { openFlags = os.O_RDONLY } if flags&Sync != 0 { openFlags |= datasyncFileFlag } return os.OpenFile(filename, openFlags, 0) } // CreateSyncedFile creates a new file (using O_EXCL), errors if it already existed. func CreateSyncedFile(filename string, sync bool) (*os.File, error) { flags := os.O_RDWR | os.O_CREATE | os.O_EXCL if sync { flags |= datasyncFileFlag } return os.OpenFile(filename, flags, 0600) } // OpenSyncedFile creates the file if one doesn't exist. func OpenSyncedFile(filename string, sync bool) (*os.File, error) { flags := os.O_RDWR | os.O_CREATE if sync { flags |= datasyncFileFlag } return os.OpenFile(filename, flags, 0600) } // OpenTruncFile opens the file with O_RDWR | O_CREATE | O_TRUNC func OpenTruncFile(filename string, sync bool) (*os.File, error) { flags := os.O_RDWR | os.O_CREATE | os.O_TRUNC if sync { flags |= datasyncFileFlag } return os.OpenFile(filename, flags, 0600) } // SafeCopy does append(a[:0], src...). func SafeCopy(a, src []byte) []byte { return append(a[:0], src...) } // Copy copies a byte slice and returns the copied slice. func Copy(a []byte) []byte { b := make([]byte, len(a)) copy(b, a) return b } func SetKeyTs(key []byte, ts uint64) { start := len(key) - 8 binary.BigEndian.PutUint64(key[start:], math.MaxUint64-ts) } // KeyWithTs generates a new key by appending ts to key. func KeyWithTs(key []byte, ts uint64) []byte { out := make([]byte, len(key)+8) copy(out, key) binary.BigEndian.PutUint64(out[len(key):], math.MaxUint64-ts) return out } // ParseTs parses the timestamp from the key bytes. func ParseTs(key []byte) uint64 { if len(key) <= 8 { return 0 } return math.MaxUint64 - binary.BigEndian.Uint64(key[len(key)-8:]) } // CompareKeys checks the key without timestamp and checks the timestamp if keyNoTs // is same. // a<timestamp> would be sorted higher than aa<timestamp> if we use bytes.compare // All keys should have timestamp. func CompareKeys(key1, key2 []byte) int { if cmp := bytes.Compare(key1[:len(key1)-8], key2[:len(key2)-8]); cmp != 0 { return cmp } return bytes.Compare(key1[len(key1)-8:], key2[len(key2)-8:]) } // ParseKey parses the actual key from the key bytes. func ParseKey(key []byte) []byte { if key == nil { return nil } return key[:len(key)-8] } // SameKey checks for key equality ignoring the version timestamp suffix. func SameKey(src, dst []byte) bool { if len(src) != len(dst) { return false } return bytes.Equal(ParseKey(src), ParseKey(dst)) } // Slice holds a reusable buf, will reallocate if you request a larger size than ever before. // One problem is with n distinct sizes in random order it'll reallocate log(n) times. type Slice struct { buf []byte } // Resize reuses the Slice's buffer (or makes a new one) and returns a slice in that buffer of // length sz. func (s *Slice) Resize(sz int) []byte { if cap(s.buf) < sz { s.buf = make([]byte, sz) } return s.buf[0:sz] } // FixedDuration returns a string representation of the given duration with the // hours, minutes, and seconds. func FixedDuration(d time.Duration) string { str := fmt.Sprintf("%02ds", int(d.Seconds())%60) if d >= time.Minute { str = fmt.Sprintf("%02dm", int(d.Minutes())%60) + str } if d >= time.Hour { str = fmt.Sprintf("%02dh", int(d.Hours())) + str } return str } // Throttle allows a limited number of workers to run at a time. It also // provides a mechanism to check for errors encountered by workers and wait for // them to finish. type Throttle struct { once sync.Once wg sync.WaitGroup ch chan struct{} errCh chan error finishErr error } // NewThrottle creates a new throttle with a max number of workers. func NewThrottle(max int) *Throttle { return &Throttle{ ch: make(chan struct{}, max), errCh: make(chan error, max), } } // Do should be called by workers before they start working. It blocks if there // are already maximum number of workers working. If it detects an error from // previously Done workers, it would return it. func (t *Throttle) Do() error { for { select { case t.ch <- struct{}{}: t.wg.Add(1) return nil case err := <-t.errCh: if err != nil { return err } } } } // Done should be called by workers when they finish working. They can also // pass the error status of work done. func (t *Throttle) Done(err error) { if err != nil { t.errCh <- err } select { case <-t.ch: default: panic("Throttle Do Done mismatch") } t.wg.Done() } // Finish waits until all workers have finished working. It would return any error passed by Done. // If Finish is called multiple time, it will wait for workers to finish only once(first time). // From next calls, it will return same error as found on first call. func (t *Throttle) Finish() error { t.once.Do(func() { t.wg.Wait() close(t.ch) close(t.errCh) for err := range t.errCh { if err != nil { t.finishErr = err return } } }) return t.finishErr } // U16ToBytes converts the given Uint16 to bytes func U16ToBytes(v uint16) []byte { var uBuf [2]byte binary.BigEndian.PutUint16(uBuf[:], v) return uBuf[:] } // BytesToU16 converts the given byte slice to uint16 func BytesToU16(b []byte) uint16 { return binary.BigEndian.Uint16(b) } // U32ToBytes converts the given Uint32 to bytes func U32ToBytes(v uint32) []byte { var uBuf [4]byte binary.BigEndian.PutUint32(uBuf[:], v) return uBuf[:] } // BytesToU32 converts the given byte slice to uint32 func BytesToU32(b []byte) uint32 { return binary.BigEndian.Uint32(b) } // U32SliceToBytes converts the given Uint32 slice to byte slice func U32SliceToBytes(u32s []uint32) []byte { if len(u32s) == 0 { return nil } var b []byte hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) hdr.Len = len(u32s) * 4 hdr.Cap = hdr.Len hdr.Data = uintptr(unsafe.Pointer(&u32s[0])) return b } // BytesToU32Slice converts the given byte slice to uint32 slice func BytesToU32Slice(b []byte) []uint32 { if len(b) == 0 { return nil } var u32s []uint32 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u32s)) hdr.Len = len(b) / 4 hdr.Cap = hdr.Len hdr.Data = uintptr(unsafe.Pointer(&b[0])) return u32s } // U64ToBytes converts the given Uint64 to bytes func U64ToBytes(v uint64) []byte { var uBuf [8]byte binary.BigEndian.PutUint64(uBuf[:], v) return uBuf[:] } // BytesToU64 converts the given byte slice to uint64 func BytesToU64(b []byte) uint64 { return binary.BigEndian.Uint64(b) } // U64SliceToBytes converts the given Uint64 slice to byte slice func U64SliceToBytes(u64s []uint64) []byte { if len(u64s) == 0 { return nil } var b []byte hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) hdr.Len = len(u64s) * 8 hdr.Cap = hdr.Len hdr.Data = uintptr(unsafe.Pointer(&u64s[0])) return b } // BytesToU64Slice converts the given byte slice to uint64 slice func BytesToU64Slice(b []byte) []uint64 { if len(b) == 0 { return nil } var u64s []uint64 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u64s)) hdr.Len = len(b) / 8 hdr.Cap = hdr.Len hdr.Data = uintptr(unsafe.Pointer(&b[0])) return u64s } // page struct contains one underlying buffer. type page struct { buf []byte } // PageBuffer consists of many pages. A page is a wrapper over []byte. PageBuffer can act as a // replacement of bytes.Buffer. Instead of having single underlying buffer, it has multiple // underlying buffers. Hence it avoids any copy during relocation(as happens in bytes.Buffer). // PageBuffer allocates memory in pages. Once a page is full, it will allocate page with double the // size of previous page. Its function are not thread safe. type PageBuffer struct { pages []*page length int // Length of PageBuffer. nextPageSize int // Size of next page to be allocated. } // NewPageBuffer returns a new PageBuffer with first page having size pageSize. func NewPageBuffer(pageSize int) *PageBuffer { b := &PageBuffer{} b.pages = append(b.pages, &page{buf: make([]byte, 0, pageSize)}) b.nextPageSize = pageSize * 2 return b } // Write writes data to PageBuffer b. It returns number of bytes written and any error encountered. func (b *PageBuffer) Write(data []byte) (int, error) { dataLen := len(data) for { cp := b.pages[len(b.pages)-1] // Current page. n := copy(cp.buf[len(cp.buf):cap(cp.buf)], data) cp.buf = cp.buf[:len(cp.buf)+n] b.length += n if len(data) == n { break } data = data[n:] b.pages = append(b.pages, &page{buf: make([]byte, 0, b.nextPageSize)}) b.nextPageSize *= 2 } return dataLen, nil } // WriteByte writes data byte to PageBuffer and returns any encountered error. func (b *PageBuffer) WriteByte(data byte) error { _, err := b.Write([]byte{data}) return err } // Len returns length of PageBuffer. func (b *PageBuffer) Len() int { return b.length } // pageForOffset returns pageIdx and startIdx for the offset. func (b *PageBuffer) pageForOffset(offset int) (int, int) { AssertTrue(offset < b.length) var pageIdx, startIdx, sizeNow int for i := 0; i < len(b.pages); i++ { cp := b.pages[i] if sizeNow+len(cp.buf)-1 < offset { sizeNow += len(cp.buf) } else { pageIdx = i startIdx = offset - sizeNow break } } return pageIdx, startIdx } // Truncate truncates PageBuffer to length n. func (b *PageBuffer) Truncate(n int) { pageIdx, startIdx := b.pageForOffset(n) // For simplicity of the code reject extra pages. These pages can be kept. b.pages = b.pages[:pageIdx+1] cp := b.pages[len(b.pages)-1] cp.buf = cp.buf[:startIdx] b.length = n } // Bytes returns whole Buffer data as single []byte. func (b *PageBuffer) Bytes() []byte { buf := make([]byte, b.length) written := 0 for i := 0; i < len(b.pages); i++ { written += copy(buf[written:], b.pages[i].buf) } return buf } // WriteTo writes whole buffer to w. It returns number of bytes written and any error encountered. func (b *PageBuffer) WriteTo(w io.Writer) (int64, error) { written := int64(0) for i := 0; i < len(b.pages); i++ { n, err := w.Write(b.pages[i].buf) written += int64(n) if err != nil { return written, err } } return written, nil } // NewReaderAt returns a reader which starts reading from offset in page buffer. func (b *PageBuffer) NewReaderAt(offset int) *PageBufferReader { pageIdx, startIdx := b.pageForOffset(offset) return &PageBufferReader{ buf: b, pageIdx: pageIdx, startIdx: startIdx, } } // PageBufferReader is a reader for PageBuffer. type PageBufferReader struct { buf *PageBuffer // Underlying page buffer. pageIdx int // Idx of page from where it will start reading. startIdx int // Idx inside page - buf.pages[pageIdx] from where it will start reading. } // Read reads upto len(p) bytes. It returns number of bytes read and any error encountered. func (r *PageBufferReader) Read(p []byte) (int, error) { // Check if there is enough to Read. pc := len(r.buf.pages) read := 0 for r.pageIdx < pc && read < len(p) { cp := r.buf.pages[r.pageIdx] // Current Page. endIdx := len(cp.buf) // Last Idx up to which we can read from this page. n := copy(p[read:], cp.buf[r.startIdx:endIdx]) read += n r.startIdx += n // Instead of len(cp.buf), we comparing with cap(cp.buf). This ensures that we move to next // page only when we have read all data. Reading from last page is an edge case. We don't // want to move to next page until last page is full to its capacity. if r.startIdx >= cap(cp.buf) { // We should move to next page. r.pageIdx++ r.startIdx = 0 continue } // When last page in not full to its capacity and we have read all data up to its // length, just break out of the loop. if r.pageIdx == pc-1 { break } } if read == 0 { return read, io.EOF } return read, nil } const kvsz = int(unsafe.Sizeof(pb.KV{})) func NewKV(alloc *z.Allocator) *pb.KV { if alloc == nil { return &pb.KV{} } b := alloc.AllocateAligned(kvsz) return (*pb.KV)(unsafe.Pointer(&b[0])) } // IBytesToString converts size in bytes to human readable format. // The code is taken from humanize library and changed to provide // value upto custom decimal precision. // IBytesToString(12312412, 1) -> 11.7 MiB func IBytesToString(size uint64, precision int) string { sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} base := float64(1024) if size < 10 { return fmt.Sprintf("%d B", size) } e := math.Floor(math.Log(float64(size)) / math.Log(base)) suffix := sizes[int(e)] val := float64(size) / math.Pow(base, e) f := "%." + strconv.Itoa(precision) + "f %s" return fmt.Sprintf(f, val, suffix) } type RateMonitor struct { start time.Time lastSent uint64 lastCapture time.Time rates []float64 idx int } func NewRateMonitor(numSamples int) *RateMonitor { return &RateMonitor{ start: time.Now(), rates: make([]float64, numSamples), } } const minRate = 0.0001 // Capture captures the current number of sent bytes. This number should be monotonically // increasing. func (rm *RateMonitor) Capture(sent uint64) { diff := sent - rm.lastSent dur := time.Since(rm.lastCapture) rm.lastCapture, rm.lastSent = time.Now(), sent rate := float64(diff) / dur.Seconds() if rate < minRate { rate = minRate } rm.rates[rm.idx] = rate rm.idx = (rm.idx + 1) % len(rm.rates) } // Rate returns the average rate of transmission smoothed out by the number of samples. func (rm *RateMonitor) Rate() uint64 { var total float64 var den float64 for _, r := range rm.rates { if r < minRate { // Ignore this. We always set minRate, so this is a zero. // Typically at the start of the rate monitor, we'd have zeros. continue } total += r den += 1.0 } if den < minRate { return 0 } return uint64(total / den) }
{ "content_hash": "446f4875852a92ef44f66320a2949335", "timestamp": "", "source": "github", "line_count": 585, "max_line_length": 99, "avg_line_length": 25.6974358974359, "alnum_prop": 0.6813676578194638, "repo_name": "dgraph-io/badger", "id": "81b8b629af8cad93a0ee053d502e112ecf22e068", "size": "15650", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "y/y.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1005704" }, { "name": "Makefile", "bytes": "2628" }, { "name": "Shell", "bytes": "5820" } ], "symlink_target": "" }
set -eu source pcf-pipelines/functions/generate_cert.sh if [[ -z "$SSL_CERT" ]]; then domains=( "*.${SYSTEM_DOMAIN}" "*.${APPS_DOMAIN}" "*.login.${SYSTEM_DOMAIN}" "*.uaa.${SYSTEM_DOMAIN}" ) certificates=$(generate_cert "${domains[*]}") SSL_CERT=`echo $certificates | jq --raw-output '.certificate'` SSL_PRIVATE_KEY=`echo $certificates | jq --raw-output '.key'` fi if [[ -z "$SAML_SSL_CERT" ]]; then saml_cert_domains=( "*.${SYSTEM_DOMAIN}" "*.login.${SYSTEM_DOMAIN}" "*.uaa.${SYSTEM_DOMAIN}" ) saml_certificates=$(generate_cert "${saml_cert_domains[*]}") SAML_SSL_CERT=$(echo $saml_certificates | jq --raw-output '.certificate') SAML_SSL_PRIVATE_KEY=$(echo $saml_certificates | jq --raw-output '.key') fi cf_properties=$( jq -n \ --arg tcp_routing "$TCP_ROUTING" \ --arg tcp_routing_ports "$TCP_ROUTING_PORTS" \ --arg loggregator_endpoint_port "$LOGGREGATOR_ENDPOINT_PORT" \ --arg route_services "$ROUTE_SERVICES" \ --arg ignore_ssl_cert "$IGNORE_SSL_CERT" \ --arg security_acknowledgement "$SECURITY_ACKNOWLEDGEMENT" \ --arg system_domain "$SYSTEM_DOMAIN" \ --arg apps_domain "$APPS_DOMAIN" \ --arg default_quota_memory_limit_in_mb "$DEFAULT_QUOTA_MEMORY_LIMIT_IN_MB" \ --arg default_quota_max_services_count "$DEFAULT_QUOTA_MAX_SERVICES_COUNT" \ --arg allow_app_ssh_access "$ALLOW_APP_SSH_ACCESS" \ --arg ha_proxy_ips "$HA_PROXY_IPS" \ --arg skip_cert_verify "$SKIP_CERT_VERIFY" \ --arg router_static_ips "$ROUTER_STATIC_IPS" \ --arg disable_insecure_cookies "$DISABLE_INSECURE_COOKIES" \ --arg router_request_timeout_seconds "$ROUTER_REQUEST_TIMEOUT_IN_SEC" \ --arg mysql_monitor_email "$MYSQL_MONITOR_EMAIL" \ --arg tcp_router_static_ips "$TCP_ROUTER_STATIC_IPS" \ --arg company_name "$COMPANY_NAME" \ --arg ssh_static_ips "$SSH_STATIC_IPS" \ --arg mysql_static_ips "$MYSQL_STATIC_IPS" \ --arg cert_pem "$SSL_CERT" \ --arg private_key_pem "$SSL_PRIVATE_KEY" \ --arg haproxy_forward_tls "$HAPROXY_FORWARD_TLS" \ --arg haproxy_backend_ca "$HAPROXY_BACKEND_CA" \ --arg router_tls_ciphers "$ROUTER_TLS_CIPHERS" \ --arg haproxy_tls_ciphers "$HAPROXY_TLS_CIPHERS" \ --arg disable_http_proxy "$DISABLE_HTTP_PROXY" \ --arg smtp_from "$SMTP_FROM" \ --arg smtp_address "$SMTP_ADDRESS" \ --arg smtp_port "$SMTP_PORT" \ --arg smtp_user "$SMTP_USER" \ --arg smtp_password "$SMTP_PWD" \ --arg smtp_enable_starttls_auto "$SMTP_ENABLE_STARTTLS_AUTO" \ --arg smtp_auth_mechanism "$SMTP_AUTH_MECHANISM" \ --arg enable_security_event_logging "$ENABLE_SECURITY_EVENT_LOGGING" \ --arg syslog_host "$SYSLOG_HOST" \ --arg syslog_drain_buffer_size "$SYSLOG_DRAIN_BUFFER_SIZE" \ --arg syslog_port "$SYSLOG_PORT" \ --arg syslog_protocol "$SYSLOG_PROTOCOL" \ --arg authentication_mode "$AUTHENTICATION_MODE" \ --arg ldap_url "$LDAP_URL" \ --arg ldap_user "$LDAP_USER" \ --arg ldap_password "$LDAP_PWD" \ --arg ldap_search_base "$SEARCH_BASE" \ --arg ldap_search_filter "$SEARCH_FILTER" \ --arg ldap_group_search_base "$GROUP_SEARCH_BASE" \ --arg ldap_group_search_filter "$GROUP_SEARCH_FILTER" \ --arg ldap_mail_attr_name "$MAIL_ATTR_NAME" \ --arg ldap_first_name_attr "$FIRST_NAME_ATTR" \ --arg ldap_last_name_attr "$LAST_NAME_ATTR" \ --arg saml_cert_pem "$SAML_SSL_CERT" \ --arg saml_key_pem "$SAML_SSL_PRIVATE_KEY" \ --arg mysql_backups "$MYSQL_BACKUPS" \ --arg mysql_backups_s3_endpoint_url "$MYSQL_BACKUPS_S3_ENDPOINT_URL" \ --arg mysql_backups_s3_bucket_name "$MYSQL_BACKUPS_S3_BUCKET_NAME" \ --arg mysql_backups_s3_bucket_path "$MYSQL_BACKUPS_S3_BUCKET_PATH" \ --arg mysql_backups_s3_access_key_id "$MYSQL_BACKUPS_S3_ACCESS_KEY_ID" \ --arg mysql_backups_s3_secret_access_key "$MYSQL_BACKUPS_S3_SECRET_ACCESS_KEY" \ --arg mysql_backups_s3_cron_schedule "$MYSQL_BACKUPS_S3_CRON_SCHEDULE" \ --arg mysql_backups_scp_server "$MYSQL_BACKUPS_SCP_SERVER" \ --arg mysql_backups_scp_port "$MYSQL_BACKUPS_SCP_PORT" \ --arg mysql_backups_scp_user "$MYSQL_BACKUPS_SCP_USER" \ --arg mysql_backups_scp_key "$MYSQL_BACKUPS_SCP_KEY" \ --arg mysql_backups_scp_destination "$MYSQL_BACKUPS_SCP_DESTINATION" \ --arg mysql_backups_scp_cron_schedule "$MYSQL_BACKUPS_SCP_CRON_SCHEDULE" \ --arg container_networking_nw_cidr "$CONTAINER_NETWORKING_NW_CIDR" \ ' { ".properties.system_blobstore": { "value": "internal" }, ".properties.logger_endpoint_port": { "value": $loggregator_endpoint_port }, ".properties.container_networking_interface_plugin.silk.network_cidr": { "value": $container_networking_nw_cidr }, ".properties.security_acknowledgement": { "value": $security_acknowledgement }, ".properties.push_apps_manager_company_name.": { "value": $company_name }, ".cloud_controller.system_domain": { "value": $system_domain }, ".cloud_controller.apps_domain": { "value": $apps_domain }, ".cloud_controller.default_quota_memory_limit_mb": { "value": $default_quota_memory_limit_in_mb }, ".cloud_controller.default_quota_max_number_services": { "value": $default_quota_max_services_count }, ".cloud_controller.allow_app_ssh_access": { "value": $allow_app_ssh_access }, ".ha_proxy.static_ips": { "value": $ha_proxy_ips }, ".ha_proxy.skip_cert_verify": { "value": $skip_cert_verify }, ".router.static_ips": { "value": $router_static_ips }, ".router.disable_insecure_cookies": { "value": $disable_insecure_cookies }, ".router.request_timeout_in_seconds": { "value": $router_request_timeout_seconds }, ".mysql_monitor.recipient_email": { "value": $mysql_monitor_email }, ".tcp_router.static_ips": { "value": $tcp_router_static_ips }, ".diego_brain.static_ips": { "value": $ssh_static_ips }, ".mysql_proxy.static_ips": { "value": $mysql_static_ips } } + # Route Services if $route_services == "enable" then { ".properties.route_services": { "value": "enable" }, ".properties.route_services.enable.ignore_ssl_cert_verification": { "value": $ignore_ssl_cert } } else { ".properties.route_services": { "value": "disable" } } end + # TCP Routing if $tcp_routing == "enable" then { ".properties.tcp_routing": { "value": "enable" }, ".properties.tcp_routing.enable.reservable_ports": { "value": $tcp_routing_ports } } else { ".properties.tcp_routing": { "value": "disable" } } end + # SSL Termination { ".properties.networking_poe_ssl_certs": { "value": [ { "certificate": { "cert_pem": $cert_pem, "private_key_pem": $private_key_pem }, "name": "Certificate" } ] } } + # HAProxy Forward TLS if $haproxy_forward_tls == "enable" then { ".properties.haproxy_forward_tls": { "value": "enable" }, ".properties.haproxy_forward_tls.enable.backend_ca": { "value": $haproxy_backend_ca } } else { ".properties.haproxy_forward_tls": { "value": "disable" } } end + { ".properties.routing_disable_http": { "value": $disable_http_proxy } } + # TLS Cipher Suites { ".properties.gorouter_ssl_ciphers": { "value": $router_tls_ciphers }, ".properties.haproxy_ssl_ciphers": { "value": $haproxy_tls_ciphers } } + # SMTP Configuration if $smtp_address != "" then { ".properties.smtp_from": { "value": $smtp_from }, ".properties.smtp_address": { "value": $smtp_address }, ".properties.smtp_port": { "value": $smtp_port }, ".properties.smtp_credentials": { "value": { "identity": $smtp_user, "password": $smtp_password } }, ".properties.smtp_enable_starttls_auto": { "value": $smtp_enable_starttls_auto }, ".properties.smtp_auth_mechanism": { "value": $smtp_auth_mechanism } } else . end + # Syslog if $syslog_host != "" then { ".doppler.message_drain_buffer_size": { "value": $syslog_drain_buffer_size }, ".cloud_controller.security_event_logging_enabled": { "value": $enable_security_event_logging }, ".properties.syslog_host": { "value": $syslog_host }, ".properties.syslog_port": { "value": $syslog_port }, ".properties.syslog_protocol": { "value": $syslog_protocol } } else . end + # Authentication if $authentication_mode == "internal" then { ".properties.uaa": { "value": "internal" } } elif $authentication_mode == "ldap" then { ".properties.uaa": { "value": "ldap" }, ".properties.uaa.ldap.url": { "value": $ldap_url }, ".properties.uaa.ldap.credentials": { "value": { "identity": $ldap_user, "password": $ldap_password } }, ".properties.uaa.ldap.search_base": { "value": $ldap_search_base }, ".properties.uaa.ldap.search_filter": { "value": $ldap_search_filter }, ".properties.uaa.ldap.group_search_base": { "value": $ldap_group_search_base }, ".properties.uaa.ldap.group_search_filter": { "value": $ldap_group_search_filter }, ".properties.uaa.ldap.mail_attribute_name": { "value": $ldap_mail_attr_name }, ".properties.uaa.ldap.first_name_attribute": { "value": $ldap_first_name_attr }, ".properties.uaa.ldap.last_name_attribute": { "value": $ldap_last_name_attr } } else . end + # UAA SAML Credentials { ".uaa.service_provider_key_credentials": { value: { "cert_pem": $saml_cert_pem, "private_key_pem": $saml_key_pem } } } + # MySQL Backups if $mysql_backups == "s3" then { ".properties.mysql_backups": { "value": "s3" }, ".properties.mysql_backups.s3.endpoint_url": { "value": $mysql_backups_s3_endpoint_url }, ".properties.mysql_backups.s3.bucket_name": { "value": $mysql_backups_s3_bucket_name }, ".properties.mysql_backups.s3.bucket_path": { "value": $mysql_backups_s3_bucket_path }, ".properties.mysql_backups.s3.access_key_id": { "value": $mysql_backups_s3_access_key_id }, ".properties.mysql_backups.s3.secret_access_key": { "value": $mysql_backups_s3_secret_access_key }, ".properties.mysql_backups.s3.cron_schedule": { "value": $mysql_backups_s3_cron_schedule } } elif $mysql_backups == "scp" then { ".properties.mysql_backups": { "value": "scp" }, ".properties.mysql_backups.scp.server": { "value": $mysql_backups_scp_server }, ".properties.mysql_backups.scp.port": { "value": $mysql_backups_scp_port }, ".properties.mysql_backups.scp.user": { "value": $mysql_backups_scp_user }, ".properties.mysql_backups.scp.key": { "value": $mysql_backups_scp_key }, ".properties.mysql_backups.scp.destination": { "value": $mysql_backups_scp_destination }, ".properties.mysql_backups.scp.cron_schedule" : { "value": $mysql_backups_scp_cron_schedule } } else . end ' ) cf_network=$( jq -n \ --arg network_name "$NETWORK_NAME" \ --arg other_azs "$DEPLOYMENT_NW_AZS" \ --arg singleton_az "$ERT_SINGLETON_JOB_AZ" \ ' { "network": { "name": $network_name }, "other_availability_zones": ($other_azs | split(",") | map({name: .})), "singleton_availability_zone": { "name": $singleton_az } } ' ) cf_resources=$( jq -n \ --arg iaas "$IAAS" \ --argjson internet_connected $INTERNET_CONNECTED \ --argjson database_instances $DATABASE_INSTANCES \ --argjson blobstore_instances $BLOBSTORE_INSTANCES \ --argjson control_instances $CONTROL_INSTANCES \ --argjson compute_instances $COMPUTE_INSTANCES \ --argjson backup_prepare_instances $BACKUP_PREPARE_INSTANCES \ --argjson ha_proxy_instances $HA_PROXY_INSTANCES \ --argjson router_instances $ROUTER_INSTANCES \ --argjson mysql_monitor_instances $MYSQL_MONITOR_INSTANCES \ --argjson tcp_router_instances $TCP_ROUTER_INSTANCES \ --arg ha_proxy_elb_name "$HA_PROXY_LB_NAME" \ --arg ha_proxy_floating_ips "$HAPROXY_FLOATING_IPS" \ --arg tcp_router_nsx_security_group "${TCP_ROUTER_NSX_SECURITY_GROUP}" \ --arg tcp_router_nsx_lb_edge_name "${TCP_ROUTER_NSX_LB_EDGE_NAME}" \ --arg tcp_router_nsx_lb_pool_name "${TCP_ROUTER_NSX_LB_POOL_NAME}" \ --arg tcp_router_nsx_lb_security_group "${TCP_ROUTER_NSX_LB_SECURITY_GROUP}" \ --arg tcp_router_nsx_lb_port "${TCP_ROUTER_NSX_LB_PORT}" \ --arg router_nsx_security_group "${ROUTER_NSX_SECURITY_GROUP}" \ --arg router_nsx_lb_edge_name "${ROUTER_NSX_LB_EDGE_NAME}" \ --arg router_nsx_lb_pool_name "${ROUTER_NSX_LB_POOL_NAME}" \ --arg router_nsx_lb_security_group "${ROUTER_NSX_LB_SECURITY_GROUP}" \ --arg router_nsx_lb_port "${ROUTER_NSX_LB_PORT}" \ --arg diego_brain_nsx_security_group "${DIEGO_BRAIN_NSX_SECURITY_GROUP}" \ --arg diego_brain_nsx_lb_edge_name "${DIEGO_BRAIN_NSX_LB_EDGE_NAME}" \ --arg diego_brain_nsx_lb_pool_name "${DIEGO_BRAIN_NSX_LB_POOL_NAME}" \ --arg diego_brain_nsx_lb_security_group "${DIEGO_BRAIN_NSX_LB_SECURITY_GROUP}" \ --arg diego_brain_nsx_lb_port "${DIEGO_BRAIN_NSX_LB_PORT}" \ --arg mysql_nsx_security_group "${MYSQL_NSX_SECURITY_GROUP}" \ --arg mysql_nsx_lb_edge_name "${MYSQL_NSX_LB_EDGE_NAME}" \ --arg mysql_nsx_lb_pool_name "${MYSQL_NSX_LB_POOL_NAME}" \ --arg mysql_nsx_lb_security_group "${MYSQL_NSX_LB_SECURITY_GROUP}" \ --arg mysql_nsx_lb_port "${MYSQL_NSX_LB_PORT}" \ ' { "database": { "instances": $database_instances }, "blobstore": { "instances": $blobstore_instances }, "control": { "instances": $control_instances }, "compute": { "instances": $compute_instances }, "backup-prepare": { "instances": $backup_prepare_instances }, "ha_proxy": { "instances": $ha_proxy_instances }, "router": { "instances": $router_instances }, "mysql_monitor": { "instances": $mysql_monitor_instances }, "tcp_router": { "instances": $tcp_router_instances } } + if $iaas == "azure" then { "database": {"internet_connected": $internet_connected}, "blobstore": {"internet_connected": $internet_connected}, "control": {"internet_connected": $internet_connected}, "compute": {"internet_connected": $internet_connected}, "backup-prepare": {"internet_connected": $internet_connected}, "router": {"internet_connected": $internet_connected}, "mysql_monitor": {"internet_connected": $internet_connected}, "tcp_router": {"internet_connected": $internet_connected}, "smoke-tests": {"internet_connected": $internet_connected}, "push-apps-manager": {"internet_connected": $internet_connected}, "push-usage-service": {"internet_connected": $internet_connected}, "notifications": {"internet_connected": $internet_connected}, "notifications-ui": {"internet_connected": $internet_connected}, "push-pivotal-account": {"internet_connected": $internet_connected}, "autoscaling": {"internet_connected": $internet_connected}, "autoscaling-register-broker": {"internet_connected": $internet_connected}, "nfsbrokerpush": {"internet_connected": $internet_connected}, "bootstrap": {"internet_connected": $internet_connected}, "mysql-rejoin-unsafe": {"internet_connected": $internet_connected} } else . end | if $ha_proxy_elb_name != "" then .ha_proxy |= . + { "elb_names": [ $ha_proxy_elb_name ] } else . end | if $ha_proxy_floating_ips != "" then .ha_proxy |= . + { "floating_ips": $ha_proxy_floating_ips } else . end | # NSX LBs if $tcp_router_nsx_lb_edge_name != "" then .tcp_router |= . + { "nsx_security_groups": [$tcp_router_nsx_security_group], "nsx_lbs": [ { "edge_name": $tcp_router_nsx_lb_edge_name, "pool_name": $tcp_router_nsx_lb_pool_name, "security_group": $tcp_router_nsx_lb_security_group, "port": $tcp_router_nsx_lb_port } ] } else . end | if $router_nsx_lb_edge_name != "" then .router |= . + { "nsx_security_groups": [$router_nsx_security_group], "nsx_lbs": [ { "edge_name": $router_nsx_lb_edge_name, "pool_name": $router_nsx_lb_pool_name, "security_group": $router_nsx_lb_security_group, "port": $router_nsx_lb_port } ] } else . end | if $diego_brain_nsx_lb_edge_name != "" then .diego_brain |= . + { "nsx_security_groups": [$diego_brain_nsx_security_group], "nsx_lbs": [ { "edge_name": $diego_brain_nsx_lb_edge_name, "pool_name": $diego_brain_nsx_lb_pool_name, "security_group": $diego_brain_nsx_lb_security_group, "port": $diego_brain_nsx_lb_port } ] } else . end | # MySQL if $mysql_nsx_lb_edge_name != "" then .mysql |= . + { "nsx_security_groups": [$mysql_nsx_security_group], "nsx_lbs": [ { "edge_name": $mysql_nsx_lb_edge_name, "pool_name": $mysql_nsx_lb_pool_name, "security_group": $mysql_nsx_lb_security_group, "port": $mysql_nsx_lb_port } ] } else . end ' ) om-linux \ --target https://$OPSMAN_DOMAIN_OR_IP_ADDRESS \ --client-id "${OPSMAN_CLIENT_ID}" \ --client-secret "${OPSMAN_CLIENT_SECRET}" \ --username "$OPS_MGR_USR" \ --password "$OPS_MGR_PWD" \ --skip-ssl-validation \ configure-product \ --product-name cf \ --product-properties "$cf_properties" \ --product-network "$cf_network" \ --product-resources "$cf_resources"
{ "content_hash": "b83e13f913f83e4c2212fca075ee411a", "timestamp": "", "source": "github", "line_count": 634, "max_line_length": 84, "avg_line_length": 30.63249211356467, "alnum_prop": 0.5608362082282066, "repo_name": "pvsone/pcf-pipelines", "id": "46f64063d38c1f46507d063213f3f99e2e2511dc", "size": "19434", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tasks/config-srt/task.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "12335" }, { "name": "HCL", "bytes": "147211" }, { "name": "Python", "bytes": "1548" }, { "name": "Shell", "bytes": "210479" } ], "symlink_target": "" }
layout: post date: 2016-05-19 share: true author: dtnguyen comments: true tags: [excel] title: "Công cụ tạo câu hỏi trắc nghiệm, chấm điểm trong Excel" excerpt: "Công cụ tạo câu hỏi trắc nghiệm, chấm điểm trong Excel" --- --- Công cụ tạo câu hỏi trắc nghiệm, chấm điểm trong Excel [**Học Excel Online**][khoa-hoc] <div class="videowrapper"> <iframe width="560" height="315" src="https://www.youtube.com/embed/WHriqaSp-Gs?autoplay=1&loop=1" frameborder="0" allowfullscreen></iframe> </div> ### Download tài liệu liên quan: [**Download tài liệu Excel kèm theo video**][xlsm]{:target="_blank"} ### Các kiến thức liên quan: • [**Series video về VBA trong excel**][vba-playlist]{:target="_blank"} • [**Bài số 48 - Tạo Form nhập liệu trong Excel**][xl-48]{:target="_blank"} --- [**Subscribe YouTube**][subscribe-link]{:target="_blank"} ◎ [**Facebook group**][facebook-group]{:target="_blank"} ◎ [**Facebook page**][facebook-page]{:target="_blank"} [khoa-hoc]: http://hocexcel.online/subscribe [addin-link]: https://db.tt/w8mPsh3G [vid-link]: https://youtu.be/arCda8sm524 [xl-48]: https://www.youtube.com/watch?v=ByPiOiOU58M&index=49&list=PLALCv46JuKEIb30S1S2jPgHLQnUvPpmsz [xlsm]: http://bit.ly/dtnEX86 [excel-playlist]: https://www.youtube.com/playlist?list=PLALCv46JuKEIb30S1S2jPgHLQnUvPpmsz [vba-playlist]: https://www.youtube.com/playlist?list=PLALCv46JuKELXd5Ie81UqaFqAfsoXQSQt [pivot-playlist]: https://www.youtube.com/playlist?list=PLALCv46JuKEJf-tiZrgU2820f5XpZdd_p [addin-playlist]: https://www.youtube.com/playlist?list=PLALCv46JuKEK_wwjtnN5_wVDB3VGkqS6P [subscribe-link]: http://youtube.com/user/ductnguy?subscribe_confirmation=1 [facebook-group]: https://www.facebook.com/groups/569100319856001/ [facebook-page]: https://www.facebook.com/www.hocexcel.online
{ "content_hash": "af58bada888f1321c0a3e09c7dcffe9e", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 169, "avg_line_length": 38.69565217391305, "alnum_prop": 0.7365168539325843, "repo_name": "ndthanh/ndthanh.github.io", "id": "f6e64d84e4bf4b98ea1fa3f31a20818c85650cfd", "size": "1870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-05-19-cong-cu-trac-nghiem-kiem-tra-excel.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27971" }, { "name": "HTML", "bytes": "27833" }, { "name": "JavaScript", "bytes": "356" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Frontend extends CI_Controller{ public function __construct(){ parent::__construct(); $this->load->model('mFrontend','mfrontend'); $this->returnArr = array('status'=> FALSE, 'title'=>'title for sweet alert', 'message'=> '', 'data'=>array() ); } /* * If user is present then storing his user id in session and redirecting to dashboard section. */ function hostels($limit=10, $offset=0){ $hostels = $this->mfrontend->getAllHostels($limit, $offset); if(!empty($hostels)){ $this->returnArr['status'] = TRUE; $this->returnArr['title'] = 'Hostels fetched successfully'; $this->returnArr['data'] = $hostels; } echo "<pre>"; print_r($this->returnArr); echo "</pre>"; die; $this->response($this->returnArr); } function response( $response ){ header("Content-type:application/json"); echo json_encode($response); die; } }
{ "content_hash": "a6d80539c436312dd6981ae28983c690", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 119, "avg_line_length": 29.77777777777778, "alnum_prop": 0.5746268656716418, "repo_name": "kunal1400/software", "id": "a3465f2a6d73540aa5f5625abf129284767e2a2b", "size": "1072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/api/Frontend.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1196331" }, { "name": "HTML", "bytes": "8861315" }, { "name": "JavaScript", "bytes": "248298" }, { "name": "PHP", "bytes": "3462260" } ], "symlink_target": "" }
require_relative '../../imcmo' require_relative '../../imccoremeta' require_relative '../../imcmeta' class BiosVfMirroringModeConsts VP_MIRRORING_MODE_INTER_SOCKET = "inter-socket" VP_MIRRORING_MODE_INTRA_SOCKET = "intra-socket" VP_MIRRORING_MODE_PLATFORM_DEFAULT = "platform-default" end class BiosVfMirroringMode < ManagedObject #This is BiosVfMirroringMode class. @@consts = BiosVfMirroringModeConsts.new() # @@naming_props = set([]) @@mo_meta = { "classic" => MoMeta.new("BiosVfMirroringMode", "biosVfMirroringMode", "Mirroring-Mode", VersionMeta::VERSION151F, "InputOutput", 0x1f, [], ["admin", "read-only", "user"], ["Get", "Set"]), "modular" => MoMeta.new("BiosVfMirroringMode", "biosVfMirroringMode", "Mirroring-Mode", VersionMeta::VERSION2013E, "InputOutput", 0x1f, [], ["admin", "read-only", "user"], ["Get", "Set"]) } def self.mo_meta @@mo_meta end @@prop_meta = { "classic" => { "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION151F, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []), "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION151F, MoPropertyMeta::READ_WRITE, 0x2, 0, 255, nil, [], []), "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION151F, MoPropertyMeta::READ_WRITE, 0x4, 0, 255, nil, [], []), "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION151F, MoPropertyMeta::READ_WRITE, 0x8, nil, nil, nil, ["", "created", "deleted", "modified", "removed"], []), "vp_mirroring_mode" => MoPropertyMeta.new("vp_mirroring_mode", "vpMirroringMode", "string", VersionMeta::VERSION151F, MoPropertyMeta::READ_WRITE, 0x10, nil, nil, nil, ["inter-socket", "intra-socket", "platform-default"], []), }, "modular" => { "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION2013E, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []), "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_WRITE, 0x2, 0, 255, nil, [], []), "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_WRITE, 0x4, 0, 255, nil, [], []), "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_WRITE, 0x8, nil, nil, nil, ["", "created", "deleted", "modified", "removed"], []), "vp_mirroring_mode" => MoPropertyMeta.new("vp_mirroring_mode", "vpMirroringMode", "string", VersionMeta::VERSION2013E, MoPropertyMeta::READ_WRITE, 0x10, nil, nil, nil, ["inter-socket", "intra-socket", "platform-default"], []), }, } def self.prop_meta @@prop_meta end @@prop_map = { "classic" => { "childAction" => "child_action", "dn" => "dn", "rn" => "rn", "status" => "status", "vpMirroringMode" => "vp_mirroring_mode", }, "modular" => { "childAction" => "child_action", "dn" => "dn", "rn" => "rn", "status" => "status", "vpMirroringMode" => "vp_mirroring_mode", }, } def self.prop_map @@prop_map end attr_reader :child_action attr_accessor :status attr_accessor :vp_mirroring_mode def initialize(parent_mo_or_dn: nil, **kwargs) @dirty_mask = 0 @child_action = nil @status = nil @vp_mirroring_mode = nil super(class_id: "BiosVfMirroringMode", parent_mo_or_dn: parent_mo_or_dn, **kwargs) end end
{ "content_hash": "7601d03f3e83573ec9e4d4f450c90107", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 239, "avg_line_length": 39.765957446808514, "alnum_prop": 0.5933654360620653, "repo_name": "amimanda/cisco_imc_cookbook", "id": "fdad98b93723ee06aab65f8430346d24af640190", "size": "3824", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "files/default/vendor/gems/ImcSdk-0.9.1/lib/ImcSdk/mometa/bios/BiosVfMirroringMode.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "92986" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Module cloudi_http_elli_handler</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc"> </head> <body bgcolor="white"> <div class="navbar"><a name="#navbar_top"></a><table width="100%" border="0" cellspacing="0" cellpadding="2" summary="navigation bar"><tr><td><a href="overview-summary.html" target="overviewFrame">Overview</a></td><td><a href="http://www.erlang.org/"><img src="erlang.png" align="right" border="0" alt="erlang logo"></a></td></tr></table></div> <hr> <h1>Module cloudi_http_elli_handler</h1> <ul class="index"><li><a href="#description">Description</a></li><li><a href="#index">Function Index</a></li><li><a href="#functions">Function Details</a></li></ul> <h3><a name="Elli_CloudI_HTTP_Handler">Elli CloudI HTTP Handler</a></h3>. <p>Copyright © 2013-2021 Michael Truog</p> <p><b>Version:</b> 2.0.3 Dec 3 2021 22:41:59 ------------------------------------------------------------------------</p> <p><b>Authors:</b> Michael Truog (<a href="mailto:mjtruog at protonmail dot com"><tt>mjtruog at protonmail dot com</tt></a>).</p> <h2><a name="description">Description</a></h2> <h3><a name="Elli_CloudI_HTTP_Handler">Elli CloudI HTTP Handler</a></h3> <h2><a name="index">Function Index</a></h2> <table width="100%" border="1" cellspacing="0" cellpadding="2" summary="function index"><tr><td valign="top"><a href="#handle-2">handle/2</a></td><td></td></tr> <tr><td valign="top"><a href="#handle_event-3">handle_event/3</a></td><td></td></tr> </table> <h2><a name="functions">Function Details</a></h2> <h3 class="function"><a name="handle-2">handle/2</a></h3> <div class="spec"> <p><tt>handle(Req, Elli_state) -&gt; any()</tt></p> <p> </p> </div> <h3 class="function"><a name="handle_event-3">handle_event/3</a></h3> <div class="spec"> <p><tt>handle_event(X1, Error, X3) -&gt; any()</tt></p> <p> </p> </div> <hr> <div class="navbar"><a name="#navbar_bottom"></a><table width="100%" border="0" cellspacing="0" cellpadding="2" summary="navigation bar"><tr><td><a href="overview-summary.html" target="overviewFrame">Overview</a></td><td><a href="http://www.erlang.org/"><img src="erlang.png" align="right" border="0" alt="erlang logo"></a></td></tr></table></div> <p><i>Generated by EDoc</i></p> </body> </html>
{ "content_hash": "31d117979890ae14ae8694ad86e00949", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 347, "avg_line_length": 51.40425531914894, "alnum_prop": 0.6353476821192053, "repo_name": "CloudI/website", "id": "661e6872ce56e390dac49a1f0c8dceb299db9a0e", "size": "2417", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "api/cloudi_service_http_elli-2.0.5/cloudi_http_elli_handler.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "82131" }, { "name": "HTML", "bytes": "2662958" }, { "name": "JavaScript", "bytes": "3131" } ], "symlink_target": "" }
module RuboCop module Cop module Bundler # Gems in consecutive lines should be alphabetically sorted # @example # # bad # gem 'rubocop' # gem 'rspec' # # # good # gem 'rspec' # gem 'rubocop' # # # good # gem 'rubocop' # # gem 'rspec' class OrderedGems < Cop MSG = 'Gem `%s` should appear before `%s` in their gem group.'.freeze def investigate(processed_source) return if processed_source.ast.nil? gem_declarations(processed_source.ast) .each_cons(2) do |previous, current| next unless consecutive_lines(previous, current) next unless current.children[2].children.first.to_s < previous.children[2].children.first.to_s register_offense(previous, current) end end def consecutive_lines(previous, current) previous.source_range.last_line == current.source_range.first_line - 1 end def register_offense(previous, current) add_offense( current, current.source_range, format( MSG, current.children[2].children.first, previous.children[2].children.first ) ) end def autocorrect(node) previous = previous_declaration(node) current_content = node.source previous_content = previous.source lambda do |corrector| corrector.replace(node.loc.expression, previous_content) corrector.replace(previous.loc.expression, current_content) end end def previous_declaration(node) gem_declarations(processed_source.ast) .find { |x| x.loc.line == node.loc.line - 1 } end def_node_search :gem_declarations, <<-PATTERN (:send, nil, :gem, ...) PATTERN end end end end
{ "content_hash": "54d2fc0e8aad72a8bb8e2da174257328", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 80, "avg_line_length": 28.65714285714286, "alnum_prop": 0.5473579262213359, "repo_name": "melch/rubocop", "id": "7356de1fca5e1be99bb4ecbc64801d1fd2a9dce4", "size": "2036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rubocop/cop/bundler/ordered_gems.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355" }, { "name": "HTML", "bytes": "7106" }, { "name": "Ruby", "bytes": "3389766" } ], "symlink_target": "" }
package org.olat.core.commons.modules.glossary.morphService; import java.util.ArrayList; /** * Description:<br> * Connects to a morphological service and lets retreive flexions for a word. * <P> * Initial Date: 23.12.2008 <br> * * @author Roman Haag, frentix GmbH, roman.haag@frentix.com */ public interface MorphologicalService { public static final String STATUS_KNOWN = "known"; public static final String STATUS_GUESSED = "guessed"; public static final String STATUS_ERROR = "error"; /** * returns a list of Flexions found for a given word. * * @param partOfSpeech possible values, see: assumePartOfSpeech() * @param word a single word or a wordgroup * @return list of flexions found with a morphological service */ public ArrayList<String> getFlexions(String partOfSpeech, String word); /** * same as getFlexions(String partOfSpeech, String word) but with automatic assumption of partofspeech * * @param word * @return */ public ArrayList<String> getFlexions(String word); /** * returns part-of-speech for a given word or wordgroup * * @param glossTerm * @return part of speech, which can be: - a for an adjective "schön" - n for a noun "Haus" - an for adjective and noun "schönes Haus" */ public String assumePartOfSpeech(String glossTerm); /** * Get the Status from the reply arrived from the morphological service status can either be: - known Flexions were found in Lexicon - guessed Flexions were generated * with heuristics - error Couldn't find anything or service error / unavailable * * @return */ public String getReplyStatus(); /** * get service name as description in guis * * @return */ public String getMorphServiceDescriptor(); /** * get unique identifier to store with glossary-config * * @return */ public String getMorphServiceIdentifier(); }
{ "content_hash": "6c10428cf7792b93cfccbadaaffbbd1d", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 167, "avg_line_length": 27.426470588235293, "alnum_prop": 0.7163538873994638, "repo_name": "srinivasiyerb/Scholst", "id": "f699785bcc462aeef53d81da058b7fc20603e492", "size": "2628", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/org/olat/core/commons/modules/glossary/morphService/MorphologicalService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2300074" }, { "name": "Java", "bytes": "20346154" }, { "name": "JavaScript", "bytes": "33958863" }, { "name": "Perl", "bytes": "4117" }, { "name": "Shell", "bytes": "42399" }, { "name": "XSLT", "bytes": "172058" } ], "symlink_target": "" }
package de.hbt.kicker.elo.statistik; import java.util.HashMap; import java.util.Map; import de.hbt.kicker.elo.v2.model.Spieler; public class Top3Statistik { private Map<Spieler, Integer> punkteMap = new HashMap<Spieler, Integer>(); private Spieler spieler1, spieler2, spieler3; private int punkte1, punkte2, punkte3; public void add(Spieler spieler, int punkte) { if(!spieler.isVisible() || !spieler.isTopFlopAktiviert()) { return; } Integer punkteValue = punkteMap.get(spieler); if (punkteValue != null) { punkteValue = punkteValue + punkte; } else { punkteValue = punkte; } punkteMap.put(spieler, punkteValue); } public void calculate() { for (Map.Entry<Spieler, Integer> entry : punkteMap.entrySet()) { if (spieler1 == null) { spieler1 = entry.getKey(); punkte1 = entry.getValue(); } else if (punkte1 < entry.getValue()) { spieler1 = entry.getKey(); punkte1 = entry.getValue(); } } for (Map.Entry<Spieler, Integer> entry : punkteMap.entrySet()) { if (entry.getKey() == spieler1) { continue; } if (spieler2 == null) { spieler2 = entry.getKey(); punkte2 = entry.getValue(); } else if (punkte2 < entry.getValue()) { spieler2 = entry.getKey(); punkte2 = entry.getValue(); } } for (Map.Entry<Spieler, Integer> entry : punkteMap.entrySet()) { if (!entry.getKey().isVisible() || entry.getKey() == spieler1 || entry.getKey() == spieler2) continue; if (spieler3 == null) { spieler3 = entry.getKey(); punkte3 = entry.getValue(); } else if (punkte3 < entry.getValue()) { spieler3 = entry.getKey(); punkte3 = entry.getValue(); } } } public Spieler getSpieler1() { return spieler1; } public Spieler getSpieler2() { return spieler2; } public Spieler getSpieler3() { return spieler3; } public int getPunkte1() { return punkte1; } public int getPunkte2() { return punkte2; } public int getPunkte3() { return punkte3; } }
{ "content_hash": "58eb0e886bf37c3f2892f87af235dca1", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 95, "avg_line_length": 23.011627906976745, "alnum_prop": 0.6523496715512885, "repo_name": "ilja82/Foosball-League", "id": "d3475aed7596c9e58aed1d1612f73aea96608017", "size": "1979", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/de/hbt/kicker/elo/statistik/Top3Statistik.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8520" }, { "name": "Java", "bytes": "198601" }, { "name": "JavaScript", "bytes": "106871" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>parent</artifactId> <groupId>tlatoolbox</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <groupId>tlatoolbox</groupId> <artifactId>org.lamport.tla.toolbox.tool.tlc</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>eclipse-plugin</packaging> </project>
{ "content_hash": "cee4d3d161fe8bd0ebba4dc8f100939b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 100, "avg_line_length": 40.125, "alnum_prop": 0.7040498442367601, "repo_name": "lemmy/tlaplus", "id": "069b6eb7dc1bfa041ad1662866cf7032a79e0b12", "size": "642", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "toolbox/org.lamport.tla.toolbox.tool.tlc/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "14696" }, { "name": "Batchfile", "bytes": "17418" }, { "name": "CSS", "bytes": "14084" }, { "name": "Groovy", "bytes": "13445" }, { "name": "HTML", "bytes": "2675861" }, { "name": "Java", "bytes": "14334047" }, { "name": "R", "bytes": "275" }, { "name": "Shell", "bytes": "8406" }, { "name": "TLA", "bytes": "6601130" }, { "name": "TeX", "bytes": "144613" }, { "name": "jq", "bytes": "610" } ], "symlink_target": "" }
@implementation SZShareDialogViewControllerIOS6 //navbar impl is set here, as this is a subclass of SZNavigationController - (id)initWithEntity:(id<SZEntity>)entity { if (self = [super initWithEntity:entity]) { [SZNavigationControllerIOS6 initNavigationBar:self]; } return self; } @end
{ "content_hash": "f926756938b350a16cdc75faaeac5ac4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 74, "avg_line_length": 24.153846153846153, "alnum_prop": 0.7261146496815286, "repo_name": "socialize/socialize-sdk-ios", "id": "2fa0266ef82a84282319aca1bc25f1549324f0f6", "size": "556", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Socialize/SZShareDialogViewControllerIOS6.m", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "248" }, { "name": "C", "bytes": "9495" }, { "name": "Groff", "bytes": "65678" }, { "name": "HTML", "bytes": "1155" }, { "name": "Makefile", "bytes": "10221" }, { "name": "Objective-C", "bytes": "1841497" }, { "name": "Perl", "bytes": "377988" }, { "name": "Python", "bytes": "2952" }, { "name": "Ruby", "bytes": "2990" }, { "name": "Shell", "bytes": "19138" } ], "symlink_target": "" }
/** * Returns an error to be thrown when attempting to find an unexisting column. * @param id Id whose lookup failed. * @docs-private */ export declare function getTableUnknownColumnError(id: string): Error; /** * Returns an error to be thrown when two column definitions have the same name. * @docs-private */ export declare function getTableDuplicateColumnNameError(name: string): Error;
{ "content_hash": "c3a5cd10cfd7905e2602e6787882b6e8", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 80, "avg_line_length": 33.166666666666664, "alnum_prop": 0.7562814070351759, "repo_name": "tongpa/pypollmanage", "id": "bb8483bc49b1ccb947ee1f205968e2fe833dc447", "size": "600", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "pypollmanage/public/javascript/node_modules/@angular_ols/cdk/typings/table/table-errors.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7100" }, { "name": "HTML", "bytes": "64063" }, { "name": "JavaScript", "bytes": "19761" }, { "name": "Python", "bytes": "15743" }, { "name": "TypeScript", "bytes": "103306" } ], "symlink_target": "" }
<?php namespace AlphaLemon\ThemeEngineBundle\Core\Generator\TemplateParser; use Symfony\Component\Finder\Finder; use Symfony\Component\Yaml\Yaml; /** * AlTemplateParser parses the twig templates from a given folder to look for * the information that defines the slot's attributes * * @author alphalemon <webmaster@alphalemon.com> */ class AlTemplateParser { private $templatesDir; private $kernelDir; private $themeName; private $ymlParser; /** * Constructor * * @param string $templatesDir */ public function __construct($templatesDir, $kernelDir, $themeName) { $this->templatesDir = $templatesDir; $this->kernelDir = $kernelDir; $this->themeName = $themeName; $this->ymlParser = new Yaml(); } /** * Parses the templates folder and returns the retrieved information * as array * * @return array */ public function parse() { $templates = array(); $finder = new Finder(); $directories = array( $this->templatesDir, ); $globalResourcesFolder = $this->kernelDir . '/Resources/views/' . $this->themeName; if (is_dir($globalResourcesFolder)) { $directories[] = $globalResourcesFolder; } $templateFiles = $finder->files('*.twig')->in($directories); foreach ($templateFiles as $template) { $template = (string)$template; $templateName = basename($template); $templateContents = file_get_contents($template); $slots = $this->fetchSlots($templateContents); if (empty($slots)) { continue; } $templates[$templateName]['assets']['external_stylesheets'] = $this->fetchExternalStylesheets($templateContents); $templates[$templateName]['assets']['external_javascripts'] = $this->fetchExternalJavascripts($templateContents); $templates[$templateName]['assets']['external_stylesheets_cms'] = $this->fetchExternalStylesheetsCms($templateContents); $templates[$templateName]['assets']['external_javascripts_cms'] = $this->fetchExternalJavascriptsCms($templateContents); $templates[$templateName]['slots'] = $slots; if (strpos($template, $this->kernelDir) === false) { $templates[$templateName]['generate_template'] = dirname($template) == $this->templatesDir; } } return $templates; } /** * Fetches the external stylesheets * * @param string $templateContents * @return array */ protected function fetchExternalStylesheets($templateContents) { return $this->fetchAssets($templateContents, 'EXTERNAL-STYLESHEETS'); } /** * Fetches the external javascripts * * @param string $templateContents * @return array */ protected function fetchExternalJavascripts($templateContents) { return $this->fetchAssets($templateContents, 'EXTERNAL-JAVASCRIPTS'); } /** * Fetches the external stylesheets loaded when in cms mode * * @param string $templateContents * @return array */ protected function fetchExternalStylesheetsCms($templateContents) { return $this->fetchAssets($templateContents, 'CMS-STYLESHEETS'); } /** * Fetches the external javascripts loaded when in cms mode * * @param string $templateContents * @return array */ protected function fetchExternalJavascriptsCms($templateContents) { return $this->fetchAssets($templateContents, 'CMS-JAVASCRIPTS'); } /** * Fetches the assets attributes indentified by a section * * @param string $templateContents * @param string $section * @return array */ protected function fetchAssets($templateContents, $section) { $pattern = sprintf('/BEGIN-%1$s[^\w\s]*[\r\n](.*?)[\r\n][^\w]*END-%1$s/s', $section); preg_match($pattern, $templateContents, $matches); return ( ! empty($matches)) ? explode("\n", $matches[1]) : array(); } /** * Fetches the slots attributes * * @param string $templateContents * @return array */ protected function fetchSlots($templateContents) { $validAttributes = array( 'repeated' => '', 'blockType' => '', 'htmlContent' => '' ); preg_match_all('/BEGIN-SLOT[^\w]*[\r\n]([\s]*)(.*?)[\r\n][^\w]*END-SLOT/s', $templateContents, $matches, PREG_SET_ORDER); $slots = array(); foreach ($matches as $slotAttributes) { $spaces = $slotAttributes[1]; $attributes = $slotAttributes[2]; if ($spaces !== "") { $attributesArray = explode("\n", $attributes); $trimmedAttributes = array(); // foreach ($attributesArray as $line) { $trimmedAttributes[] = str_replace($spaces, "", $line); } $attributes = implode("\n", $trimmedAttributes); } $parsedAttributes = $this->ymlParser->parse($attributes); if ( ! array_key_exists('name', $parsedAttributes)) { continue; } $slotName = $parsedAttributes['name']; unset($parsedAttributes['name']); $attributes = array_intersect_key($parsedAttributes, $validAttributes); $wrongAttributes = array_diff_key($parsedAttributes, $validAttributes); $slots[$slotName] = $attributes; if (count($wrongAttributes) > 0) { $slots[$slotName]['errors'] = $wrongAttributes; } } return $slots; } }
{ "content_hash": "183fc8cfb42a425624eca8d12c8ae824", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 132, "avg_line_length": 32.032786885245905, "alnum_prop": 0.5791538723984988, "repo_name": "alphalemon/ThemeEngineBundle", "id": "ad8606ced6a9a289915fe7638ccb1134e11d50d8", "size": "5862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Generator/TemplateParser/AlTemplateParser.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "306836" } ], "symlink_target": "" }
.. autoprogram:: pwndbg.commands.telescope:parser :prog: telescope
{ "content_hash": "709306c8929523ab1632dffb5c586cab", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 49, "avg_line_length": 35, "alnum_prop": 0.7571428571428571, "repo_name": "cebrusfs/217gdb", "id": "af8523a1e6e1767d31f26e0ee062ad37293a498c", "size": "70", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "docs/source/commands/telescope.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "584" }, { "name": "C", "bytes": "113" }, { "name": "Go", "bytes": "58" }, { "name": "Makefile", "bytes": "1302" }, { "name": "Python", "bytes": "1824522" }, { "name": "Shell", "bytes": "6068" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>strategy::centroid::bashein_detmer</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry"> <link rel="up" href="../strategies.html" title="Strategies"> <link rel="prev" href="strategy_centroid_average.html" title="strategy::centroid::average"> <link rel="next" href="strategy_convex_hull_graham_andrew.html" title="strategy::convex_hull::graham_andrew"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_centroid_average.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_convex_hull_graham_andrew.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer"></a><a class="link" href="strategy_centroid_bashein_detmer.html" title="strategy::centroid::bashein_detmer">strategy::centroid::bashein_detmer</a> </h4></div></div></div> <p> <a class="indexterm" name="idp63325720"></a><a class="indexterm" name="idp63326056"></a><a class="indexterm" name="idp63326392"></a> Centroid calculation using algorithm Bashein / Detmer. </p> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h0"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.description"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.description">Description</a> </h6> <p> Calculates centroid using triangulation method published by Bashein / Detmer </p> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h1"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.synopsis"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.synopsis">Synopsis</a> </h6> <p> </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">Point</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">PointOfSegment</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CalculationType</span><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">strategy</span><span class="special">::</span><span class="identifier">centroid</span><span class="special">::</span><span class="identifier">bashein_detmer</span> <span class="special">{</span> <span class="comment">// ...</span> <span class="special">};</span> </pre> <p> </p> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h2"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.template_parameter_s_"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.template_parameter_s_">Template parameter(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Default </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> typename Point </p> </td> <td> </td> <td> <p> point type of centroid to calculate </p> </td> </tr> <tr> <td> <p> typename PointOfSegment </p> </td> <td> <p> Point </p> </td> <td> <p> point type of segments, defaults to Point </p> </td> </tr> <tr> <td> <p> typename CalculationType </p> </td> <td> <p> void </p> </td> <td> <p> numeric type for calculation (e.g. high precision); if <span class="bold"><strong>void</strong></span> then it is extracted automatically from the coordinate type and (if necessary) promoted to floating point </p> </td> </tr> </tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h3"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.member_function_s_"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.member_function_s_">Member Function(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> Function </p> </th> <th> <p> Description </p> </th> <th> <p> Parameters </p> </th> <th> <p> Returns </p> </th> </tr></thead> <tbody> <tr> <td> <p> </p> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="keyword">void</span> <span class="identifier">apply</span><span class="special">(</span><span class="identifier">PointOfSegment</span> <span class="keyword">const</span> <span class="special">&amp;</span> <span class="identifier">p1</span><span class="special">,</span> <span class="identifier">PointOfSegment</span> <span class="keyword">const</span> <span class="special">&amp;</span> <span class="identifier">p2</span><span class="special">,</span> <span class="identifier">sums</span> <span class="special">&amp;</span> <span class="identifier">state</span><span class="special">)</span></pre> <p> </p> </td> <td> </td> <td> <p> <span class="bold"><strong>PointOfSegment const &amp;</strong></span>: <span class="emphasis"><em>p1</em></span>: </p> <p> <span class="bold"><strong>PointOfSegment const &amp;</strong></span>: <span class="emphasis"><em>p2</em></span>: </p> <p> <span class="bold"><strong>sums &amp;</strong></span>: <span class="emphasis"><em>state</em></span>: </p> </td> </tr> <tr> <td> <p> </p> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="keyword">bool</span> <span class="identifier">result</span><span class="special">(</span><span class="identifier">sums</span> <span class="keyword">const</span> <span class="special">&amp;</span> <span class="identifier">state</span><span class="special">,</span> <span class="identifier">Point</span> <span class="special">&amp;</span> <span class="identifier">centroid</span><span class="special">)</span></pre> <p> </p> </td> <td> </td> <td> <p> <span class="bold"><strong>sums const &amp;</strong></span>: <span class="emphasis"><em>state</em></span>: </p> <p> <span class="bold"><strong>Point &amp;</strong></span>: <span class="emphasis"><em>centroid</em></span>: </p> </td> </tr> </tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h4"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.header"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.header">Header</a> </h6> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">strategies</span><span class="special">/</span><span class="identifier">cartesian</span><span class="special">/</span><span class="identifier">centroid_bashein_detmer</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> <h6> <a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.h5"></a> <span class="phrase"><a name="geometry.reference.strategies.strategy_centroid_bashein_detmer.see_also"></a></span><a class="link" href="strategy_centroid_bashein_detmer.html#geometry.reference.strategies.strategy_centroid_bashein_detmer.see_also">See also</a> </h6> <p> <a class="link" href="../algorithms/centroid/centroid_3_with_strategy.html" title="centroid (with strategy)">centroid (with strategy)</a> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2013 Barend Gehrels, Bruno Lalande, Mateusz Loskot, Adam Wulkiewicz<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_centroid_average.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_convex_hull_graham_andrew.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "11bb1e1e021e2a507a874ee0aaf40699", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 711, "avg_line_length": 49.35655737704918, "alnum_prop": 0.5765174790334634, "repo_name": "yxcoin/yxcoin", "id": "7691aad0f1e7332fe7557b2309937fe1736fb022", "size": "12043", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/boost_1_55_0/libs/geometry/doc/html/geometry/reference/strategies/strategy_centroid_bashein_detmer.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "222528" }, { "name": "Batchfile", "bytes": "26447" }, { "name": "C", "bytes": "2572612" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "151033085" }, { "name": "CMake", "bytes": "1741" }, { "name": "CSS", "bytes": "270134" }, { "name": "Cuda", "bytes": "26749" }, { "name": "Fortran", "bytes": "1387" }, { "name": "HTML", "bytes": "151665458" }, { "name": "IDL", "bytes": "14" }, { "name": "JavaScript", "bytes": "132031" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1094300" }, { "name": "Max", "bytes": "36857" }, { "name": "NSIS", "bytes": "6041" }, { "name": "Objective-C", "bytes": "11848" }, { "name": "Objective-C++", "bytes": "3755" }, { "name": "PHP", "bytes": "59030" }, { "name": "Perl", "bytes": "28121" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1720604" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "24083" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "8039" }, { "name": "Shell", "bytes": "350488" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "13404" }, { "name": "XSLT", "bytes": "687839" }, { "name": "Yacc", "bytes": "18910" } ], "symlink_target": "" }
package com.google.zxing.common; import com.google.zxing.DecodeHintType; import java.nio.charset.Charset; import java.util.Map; /** * Common string-related functions. * * @author Sean Owen * @author Alex Dupre */ public final class StringUtils { public static final String SHIFT_JIS = "SJIS"; public static final String GB2312 = "GB2312"; private static final String PLATFORM_DEFAULT_ENCODING = Charset.defaultCharset().name(); private static final String EUC_JP = "EUC_JP"; private static final String UTF8 = "UTF8"; private static final String ISO88591 = "ISO8859_1"; private static final boolean ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING) || EUC_JP.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING); private StringUtils() { } /** * @param bytes bytes encoding a string, whose encoding should be guessed * @param hints decode hints if applicable * @return name of guessed encoding; at the moment will only guess one of: * {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform * default encoding if none of these can possibly be correct */ public static String guessEncoding(byte[] bytes, Map<DecodeHintType, ?> hints) { if (hints != null) { String characterSet = (String) hints.get(DecodeHintType.CHARACTER_SET); if (characterSet != null) { return characterSet; } } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; boolean canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; boolean utf8bom = bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) { int value = bytes[i] & 0xFF; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return UTF8; } // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return SHIFT_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length ? SHIFT_JIS : ISO88591; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return ISO88591; } if (canBeShiftJIS) { return SHIFT_JIS; } if (canBeUTF8) { return UTF8; } // Otherwise, we take a wild guess with platform encoding return PLATFORM_DEFAULT_ENCODING; } }
{ "content_hash": "962e28ac5ab1e48c1c4daba46209885b", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 129, "avg_line_length": 38.14, "alnum_prop": 0.4872836916622968, "repo_name": "ben-upsilon/exp-aqr", "id": "8057fba90be841be80642b2c9bb7d264e11b22eb", "size": "8229", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/com/google/zxing/common/StringUtils.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "587247" } ], "symlink_target": "" }
use core::default; //~ ERROR unresolved import `core` fn main() { let _: u8 = ::core::default::Default(); //~ ERROR failed to resolve }
{ "content_hash": "5e98ddcc06672ecb495edd5b51d99f42", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 71, "avg_line_length": 28.2, "alnum_prop": 0.624113475177305, "repo_name": "aidancully/rust", "id": "cff273ce2c55aa182080bd86898ee8bbf5639004", "size": "141", "binary": false, "copies": "23", "ref": "refs/heads/master", "path": "src/test/ui/feature-gates/feature-gate-extern_absolute_paths.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26968" }, { "name": "Assembly", "bytes": "20050" }, { "name": "Awk", "bytes": "159" }, { "name": "C", "bytes": "726643" }, { "name": "C++", "bytes": "54397" }, { "name": "CSS", "bytes": "22328" }, { "name": "JavaScript", "bytes": "38337" }, { "name": "LLVM", "bytes": "5040" }, { "name": "Lex", "bytes": "9238" }, { "name": "Makefile", "bytes": "238787" }, { "name": "Pascal", "bytes": "13073" }, { "name": "Puppet", "bytes": "3193" }, { "name": "Python", "bytes": "149063" }, { "name": "RenderScript", "bytes": "26426" }, { "name": "Rust", "bytes": "18504256" }, { "name": "Shell", "bytes": "270708" }, { "name": "TeX", "bytes": "57" }, { "name": "Yacc", "bytes": "80496" } ], "symlink_target": "" }
Expense Manager JS ================== #### Signin page ![Singin page](https://dl.dropboxusercontent.com/u/15542982/expense-manager-js/expense_signin.png "Signin page") #### History widget ![History widget](https://dl.dropboxusercontent.com/u/15542982/expense-manager-js/expense_history.png "History widget") #### Distribution widget ![Distribution widget](https://dl.dropboxusercontent.com/u/15542982/expense-manager-js/expense_distribution.png "Distribution widget") #### Timeline widget ![Timeline widget](https://dl.dropboxusercontent.com/u/15542982/expense-manager-js/expense_timeline.png "Timeline widget") ## Prerequisites Make sure you have installed all these prerequisites on your development machine. * Node.js - [Download & Install Node.js](http://www.nodejs.org/download/) and the npm package manager, if you encounter any problems, you can also use this [Github Gist](https://gist.github.com/isaacs/579814) to install Node.js. * MongoDB - [Download & Install MongoDB](http://www.mongodb.org/downloads), and make sure it's running on the default port (27017). * Bower - You're going to use the [Bower Package Manager](http://bower.io/) to manage your front-end packages, in order to install it make sure you've installed Node.js and npm, then install bower globally using npm: * MEAN.JS - [Download & install MEAN.JS](http://meanjs.org/), this full-stack JavaScript solution helps you build fast, robust and maintainble production web applications using MongoDB, Express, AngularJS, and Node.js. ``` $ sudo npm install -g grunt-cli ``` ## Cloning The GitHub Repository You can also use Git to directly clone the expense-manager-js repository: ``` $ git clone https://github.com/themerck/expense-manager-js.git expense-manager ```
{ "content_hash": "0b57d1ec26545bb26fe491c808f8bc42", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 228, "avg_line_length": 53.03030303030303, "alnum_prop": 0.756, "repo_name": "themerck/expense-manager-js", "id": "0b8753208774e3312bef2df5b236b259898fed9e", "size": "1750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5567" }, { "name": "JavaScript", "bytes": "86009" }, { "name": "Perl", "bytes": "48" } ], "symlink_target": "" }
package com.msopentech.odatajclient.engine.data.metadata.edm; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.msopentech.odatajclient.engine.data.metadata.edm.v4.Reference; import com.msopentech.odatajclient.engine.utils.ODataVersion; import java.io.IOException; @SuppressWarnings("rawtypes") public class EdmxDeserializer extends AbstractEdmDeserializer<AbstractEdmx> { @Override protected AbstractEdmx doDeserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final AbstractEdmx edmx = ODataVersion.V3 == client.getWorkingVersion() ? new com.msopentech.odatajclient.engine.data.metadata.edm.v3.Edmx() : new com.msopentech.odatajclient.engine.data.metadata.edm.v4.Edmx(); for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { final JsonToken token = jp.getCurrentToken(); if (token == JsonToken.FIELD_NAME) { if ("Version".equals(jp.getCurrentName())) { edmx.setVersion(jp.nextTextValue()); } else if ("DataServices".equals(jp.getCurrentName())) { jp.nextToken(); if (edmx instanceof com.msopentech.odatajclient.engine.data.metadata.edm.v3.Edmx) { ((com.msopentech.odatajclient.engine.data.metadata.edm.v3.Edmx) edmx). setDataServices(jp.getCodec().readValue(jp, com.msopentech.odatajclient.engine.data.metadata.edm.v3.DataServices.class)); } else { ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Edmx) edmx). setDataServices(jp.getCodec().readValue(jp, com.msopentech.odatajclient.engine.data.metadata.edm.v4.DataServices.class)); } } else if ("Reference".equals(jp.getCurrentName())) { jp.nextToken(); ((com.msopentech.odatajclient.engine.data.metadata.edm.v4.Edmx) edmx).getReferences(). add(jp.getCodec().readValue(jp, Reference.class)); } } } return edmx; } }
{ "content_hash": "1cd346a54eea0728a29e47458b0ec000", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 125, "avg_line_length": 50.97959183673469, "alnum_prop": 0.6164931945556446, "repo_name": "sujianping/Office-365-SDK-for-Android", "id": "9f7ccff4f6ce3a6f08df010e25112322c7c1e115", "size": "3211", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sdk/office365-mail-calendar-contact-sdk/odata/engine/src/main/java/com/msopentech/odatajclient/engine/data/metadata/edm/EdmxDeserializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2840" }, { "name": "Groovy", "bytes": "7902" }, { "name": "HTML", "bytes": "579880" }, { "name": "Java", "bytes": "2441205" } ], "symlink_target": "" }
module xlib.ui.element.elements.map { import IEvent = elements.IEvent; export interface IElement<T> extends elements.IElement<T> { getLang(): string; setLang(value: any): void; getXmlLang(): string; setXmlLang(value: any): void; getDir(): string; setDir(value: any): void; getTitle(): string; setTitle(value: any): void; getName(): string; setName(value: any): void; onClick(listener: (event?: IEvent<T>) => void): void; onDblClick(listener: (event?: IEvent<T>) => void): void; onMouseDown(listener: (event?: IEvent<T>) => void): void; onMouseUp(listener: (event?: IEvent<T>) => void): void; onMouseOver(listener: (event?: IEvent<T>) => void): void; onMouseMove(listener: (event?: IEvent<T>) => void): void; onMouseOut(listener: (event?: IEvent<T>) => void): void; onKeyPress(listener: (event?: IEvent<T>) => void): void; onKeyDown(listener: (event?: IEvent<T>) => void): void; onKeyUp(listener: (event?: IEvent<T>) => void): void; } }
{ "content_hash": "953928c35f27d821dde2cf8f28b3edb9", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 61, "avg_line_length": 36.57142857142857, "alnum_prop": 0.6298828125, "repo_name": "rodzewich/playground", "id": "87a8dec6112383b6d9fa89c9c5eb14961b7fe79a", "size": "1065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xlib/ui/element/elements/map/IElement.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3610" }, { "name": "CoffeeScript", "bytes": "45" }, { "name": "HTML", "bytes": "40043" }, { "name": "JavaScript", "bytes": "5072509" }, { "name": "PHP", "bytes": "3319" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "Shell", "bytes": "476" }, { "name": "TypeScript", "bytes": "20124847" } ], "symlink_target": "" }
package com.alibaba.weex.commons.util; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import javax.annotation.Nullable; /** * Listens for the user shaking their phone. Allocation-less once it starts listening. */ public class ShakeDetector implements SensorEventListener { private static final int MAX_SAMPLES = 25; private static final int MIN_TIME_BETWEEN_SAMPLES_MS = 20; private static final int VISIBLE_TIME_RANGE_MS = 500; private static final int MAGNITUDE_THRESHOLD = 25; private static final int PERCENT_OVER_THRESHOLD_FOR_SHAKE = 66; public static interface ShakeListener { void onShake(); } private final ShakeListener mShakeListener; @Nullable private SensorManager mSensorManager; private long mLastTimestamp; private int mCurrentIndex; @Nullable private double[] mMagnitudes; @Nullable private long[] mTimestamps; public ShakeDetector(ShakeListener listener) { mShakeListener = listener; } /** * Start listening for shakes. */ public void start(SensorManager manager) { Assertions.assertNotNull(manager); Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); if (accelerometer != null) { mSensorManager = manager; mLastTimestamp = -1; mCurrentIndex = 0; mMagnitudes = new double[MAX_SAMPLES]; mTimestamps = new long[MAX_SAMPLES]; mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI); } } /** * Stop listening for shakes. */ public void stop() { if (mSensorManager != null) { mSensorManager.unregisterListener(this); mSensorManager = null; } } @Override public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.timestamp - mLastTimestamp < MIN_TIME_BETWEEN_SAMPLES_MS) { return; } Assertions.assertNotNull(mTimestamps); Assertions.assertNotNull(mMagnitudes); float ax = sensorEvent.values[0]; float ay = sensorEvent.values[1]; float az = sensorEvent.values[2]; mLastTimestamp = sensorEvent.timestamp; mTimestamps[mCurrentIndex] = sensorEvent.timestamp; mMagnitudes[mCurrentIndex] = Math.sqrt(ax * ax + ay * ay + az * az); maybeDispatchShake(sensorEvent.timestamp); mCurrentIndex = (mCurrentIndex + 1) % MAX_SAMPLES; } @Override public void onAccuracyChanged(Sensor sensor, int i) { } private void maybeDispatchShake(long currentTimestamp) { Assertions.assertNotNull(mTimestamps); Assertions.assertNotNull(mMagnitudes); int numOverThreshold = 0; int total = 0; for (int i = 0; i < MAX_SAMPLES; i++) { int index = (mCurrentIndex - i + MAX_SAMPLES) % MAX_SAMPLES; if (currentTimestamp - mTimestamps[index] < VISIBLE_TIME_RANGE_MS) { total++; if (mMagnitudes[index] >= MAGNITUDE_THRESHOLD) { numOverThreshold++; } } } if (((double) numOverThreshold) / total > PERCENT_OVER_THRESHOLD_FOR_SHAKE / 100.0) { mShakeListener.onShake(); } } }
{ "content_hash": "68963a2eb1282829f7c60279af8baa23", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 90, "avg_line_length": 27.330434782608695, "alnum_prop": 0.699968183264397, "repo_name": "nepaul/learn-web-development-by-codes", "id": "fd73d48258976cedaf6255612307284e39228623", "size": "3455", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "hello-weex/platforms/android/appframework/src/main/java/com/alibaba/weex/commons/util/ShakeDetector.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "649" }, { "name": "CSS", "bytes": "5692" }, { "name": "Dockerfile", "bytes": "500" }, { "name": "HTML", "bytes": "38190" }, { "name": "Java", "bytes": "210876" }, { "name": "JavaScript", "bytes": "300313" }, { "name": "Objective-C", "bytes": "147514" }, { "name": "Python", "bytes": "6469" }, { "name": "Ruby", "bytes": "3209" }, { "name": "Shell", "bytes": "277" }, { "name": "TypeScript", "bytes": "2628" }, { "name": "Vue", "bytes": "15700" } ], "symlink_target": "" }
require "spec_helper" describe OpenXml::Docx::Properties::TableDescription do include ValuePropertyTestMacros it_should_use tag: :tblDescription, name: "table_description", value: "Something" with_value("Something Else") do it_should_work it_should_output "<w:tblDescription w:val=\"Something Else\"/>" end with_value("") do it_should_not_work end end
{ "content_hash": "d016996e66b021e418a49b4d8d4d5303", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 83, "avg_line_length": 22.41176470588235, "alnum_prop": 0.7165354330708661, "repo_name": "genebot/rocx", "id": "b5d4c45879de846182f56f8c619f693e55a9195d", "size": "381", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/properties/table_description_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "445539" } ], "symlink_target": "" }
from django.conf.urls import patterns from views import IndexView urlpatterns = patterns('', (r'^$', IndexView.as_view()), )
{ "content_hash": "e24a551339657d338d3b89c721a6d66a", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 37, "avg_line_length": 18.714285714285715, "alnum_prop": 0.6946564885496184, "repo_name": "littleq0903/fumoufeed", "id": "2161d4bf92ce7ec668493ab8ea5814b96d16512e", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fumoufeed/apps/globals/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "279" }, { "name": "JavaScript", "bytes": "48303" }, { "name": "Python", "bytes": "14156" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.camelinaction</groupId> <artifactId>kubernetes</artifactId> <version>2.0.0</version> <relativePath>..</relativePath> </parent> <artifactId>spring-kubernetes</artifactId> <name>Camel in Action 2 :: Chapter 18 :: Hello Spring Boot2 :: Kubernetes</name> <!-- use SNAPSHOT so f-m-p create a new docker image with a new unique tag --> <version>2.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <fabric8.maven.plugin.version>3.5.38</fabric8.maven.plugin.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencyManagement> <dependencies> <!-- import Spring Boot before Camel --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot-version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- import Camel --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-parent</artifactId> <version>${camel-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- spring-boot --> <!-- notice we do not use the -web as we just run spring boot minimal without a HTTP server --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- camel --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-spring-boot-starter</artifactId> </dependency> <!-- notice we use -starter components from Camel which are designed to use with Spring Boot --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-netty4-http-starter</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot-version}</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>io.fabric8</groupId> <artifactId>fabric8-maven-plugin</artifactId> <version>${fabric8.maven.plugin.version}</version> <executions> <execution> <id>fmp</id> <goals> <goal>resource</goal> <goal>helm</goal> <goal>build</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "d3d3bb6c2884ca2f7ccaf8f64025c4da", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 258, "avg_line_length": 31.65686274509804, "alnum_prop": 0.6200061938680707, "repo_name": "camelinaction/camelinaction2", "id": "b8b7b5fa23df456417b5882afca5a0f2ba643979", "size": "3229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter18/kubernetes/client-spring2/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15238" }, { "name": "Java", "bytes": "1127533" }, { "name": "JavaScript", "bytes": "17390" }, { "name": "Shell", "bytes": "109" } ], "symlink_target": "" }
/* * Minimalist Object Storage, (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package api import "github.com/minio/minio/pkg/donut" // Operation container for individual operations read by Ticket Master type Operation struct { ProceedCh chan struct{} } // Minio container for API and also carries OP (operation) channel type Minio struct { OP chan Operation Donut donut.Interface } // New instantiate a new minio API func New() Minio { // ignore errors for now d, err := donut.New() if err != nil { panic(err) } return Minio{ OP: make(chan Operation), Donut: d, } }
{ "content_hash": "77ebb73b215a138d9b866b47a84a7f2b", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 75, "avg_line_length": 26.27906976744186, "alnum_prop": 0.7194690265486726, "repo_name": "flandr/minio", "id": "389ce63e84054087aa168e66fd74ad4f1fa2ca58", "size": "1130", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pkg/server/api/api.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "550913" }, { "name": "C", "bytes": "72638" }, { "name": "C++", "bytes": "406451" }, { "name": "Go", "bytes": "536826" }, { "name": "Makefile", "bytes": "1915" }, { "name": "Shell", "bytes": "6292" } ], "symlink_target": "" }
@{ AllNodes = @( @{ #Global Settings for the configuration of Desired State Local Configuration Manager: NodeName = "*" PSDscAllowPlainTextPassword = $true RebootNodeIfNeeded = $true ConfigurationMode = "ApplyAndAutoCorrect" ConfigurationModeFrequencyMins = 120 RefreshFrequencyMins = 120 }, @{ #Node Settings for the configuration of an MDT Server: NodeName = "$env:computername" Role = "MDT Server" #Sources for download/Prereqs SourcePath = "E:\Source" #MDT deoployment share paths PSDriveName = "MDT001" PSDrivePath = "E:\MDTBuildLab" PSDriveShareName = "MDTBuildLab$" #Operating system MDT directory information OSDirectories = @( @{OperatingSystem = "Windows 7"} @{OperatingSystem = "Windows 10"} @{OperatingSystem = "Windows 2016"} ) #Packages Folder Structure PackagesFolderStructure = @( @{Folder = "Windows 7 x86"} @{Folder = "Windows 7 x64"} @{Folder = "Windows 10 x86"} @{Folder = "Windows 10 x64"} ) #MDT Application Folder Structure ApplicationFolderStructure = @( @{ Folder = "Core" SubFolders = @( @{SubFolder = "Configure"} @{SubFolder = "Microsoft"} ) } @{ Folder = "Common Applications" } ) #Selection profile creation SelectionProfiles = @( @{ Name = "Windows 7 x86" Comments = "Packages for Windows 7 x86" IncludePath = "Packages\Windows 7 x86" } @{ Name = "Windows 7 x64" Comments = "Packages for Windows 7 x64" IncludePath = "Packages\Windows 7 x64" } @{ Name = "Windows 10 x86" Comments = "Packages for Windows 10 x86" IncludePath = "Packages\Windows 10 x86" } @{ Name = "Windows 10 x64" Comments = "Packages for Windows 10 x64" IncludePath = "Packages\Windows 10 x64" } ) #Operating systems to import to MDT OperatingSystems = @( @{ Name = "Windows 7 x86" Path = "Windows 7" SourcePath = "Windows7x86" } @{ Name = "Windows 7 x64" Path = "Windows 7" SourcePath = "Windows7x64" } @{ Name = "Windows 10 x86" Path = "Windows 10" SourcePath = "Windows10x86" } @{ Name = "Windows 10 x64" Path = "Windows 10" SourcePath = "Windows10x64" } @{ Name = "Windows 2016" Path = "Windows 2016" SourcePath = "Windows2016" } @{ Name = "Windows 2019" Path = "Windows 2016" SourcePath = "Windows2019" } ) #Applications to import Applications = @( @{ Name = "Install - Microsoft Visual C++" Path = "\Applications\Core\Microsoft" CommandLine = "cscript.exe Install-MicrosoftVisualCx86x64.wsf" ApplicationSourcePath = "VC++" } @{ Name = "Install - Convenience rollup update for Windows 7 SP1 - x86" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe windows6.1-kb3125574-v4-x86_ba1ff5537312561795cc04db0b02fbb0a74b2cbd.msu /quiet /norestart" ApplicationSourcePath = "KB3125574-x86" } @{ Name = "Install - Convenience rollup update for Windows 7 SP1 - x64" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe windows6.1-kb3125574-v4-x64_2dafb1d203c8964239af3048b5dd4b1264cd93b9.msu /quiet /norestart" ApplicationSourcePath = "KB3125574-x64" } @{ Name = "Install - July 2016 update rollup for Windows 7 SP1 - x86" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe windows6.1-kb3172605-x86_ae03ccbd299e434ea2239f1ad86f164e5f4deeda.msu /quiet /norestart" ApplicationSourcePath = "KB3172605-x86" } @{ Name = "Install - July 2016 update rollup for Windows 7 SP1 - x64" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe windows6.1-kb3172605-x64_2bb9bc55f347eee34b1454b50c436eb6fd9301fc.msu /quiet /norestart" ApplicationSourcePath = "KB3172605-x64" } @{ Name = "Install - Windows Management Framework 3.0 - x86" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe Windows6.1-KB2506143-x86.msu /quiet /norestart" ApplicationSourcePath = "WMF30x86" } @{ Name = "Install - Windows Management Framework 3.0 - x64" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe Windows6.1-KB2506143-x64.msu /quiet /norestart" ApplicationSourcePath = "WMF30x64" } @{ Name = "Install - Windows Management Framework 5.1 - x86" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe Win8.1-KB3191564-x86.msu /quiet /norestart" ApplicationSourcePath = "WMF51w81x86" } @{ Name = "Install - Windows Management Framework 5.1 - x64" Path = "\Applications\Core\Microsoft" CommandLine = "wusa.exe Win8.1AndW2K12R2-KB3191564-x64.msu /quiet /norestart" ApplicationSourcePath = "WMF51w81x64" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Path = "\Applications\Core\Configure" CommandLine = "reg import Toggle.reg" ApplicationSourcePath = "KeyboardToggle" } @{ Name = "Action - CleanupBeforeSysprep" Path = "\Applications\Core\Configure" CommandLine = "cscript.exe Action-CleanupBeforeSysprep.wsf" ApplicationSourcePath = "CleanupBeforeSysprep" } @{ Name = "Configure - Firewall rules" Path = "\Applications\Core\Configure" CommandLine = "powershell.exe -ExecutionPolicy Bypass -File .\Config-NetFwRules.ps1" ApplicationSourcePath = "ConfigureFirewall" } @{ Name = "Configure - Set Start Layout" Path = "\Applications\Core\Configure" CommandLine = "powershell.exe -ExecutionPolicy Bypass -File .\Customize-DefaultProfile.ps1" ApplicationSourcePath = "Set-Startlayout" } @{ Name = "Install - APP-V Client 5.1 - x86-x64" Path = "\Applications\Common Applications" CommandLine = "appv_client_setup.exe /ACCEPTEULA /q /ENABLEPACKAGESCRIPTS=1" ApplicationSourcePath = "APPV51x86x64" } ) #Packages Packages = @( # Servicing stack update for Windows 7 SP1 x86 @{ Name = "Package_for_KB4490628 neutral x86 6.1.1.2" Path = "\Packages\Windows 7 x86" PackageSourcePath = "KB4490628-x86" } # Servicing stack update for Windows 7 SP1 x64 @{ Name = "Package_for_KB4490628 neutral amd64 6.1.1.2" Path = "\Packages\Windows 7 x64" PackageSourcePath = "KB4490628-x64" } ) #Task sqeuences; are dependent on imported Operating system and Applications in MDT TaskSequences = @( @{ Name = "Windows 7 x86" Path = "Windows 7" OSName = "Windows 7\Windows 7 ENTERPRISE in Windows 7 x86 install.wim" OrgName = "BuildLab" Template = "Client.xml" ID = "REFW7X86-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "33PXH-7Y6KF-2VJC9-XBBR8-HVTHH" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 7 x86" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Windows Update (Post-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Install - Microsoft NET Framework 3.5.1" Type = "Install Roles and Features" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" OSName = "Windows 7" OSFeatures = "InboxGames,NetFx3,TelnetClient" } @{ Name = "Configure - Disable SMB 1.0" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Command = 'powershell.exe -Command "Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters SMB1 -Type DWORD -Value 0 -Force"' AddAfter = "Install - Microsoft NET Framework 3.5.1" } @{ Name = "Install - Microsoft Visual C++" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Disable SMB 1.0" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Microsoft Visual C++" } @{ Name = "Install - Convenience rollup update for Windows 7 SP1 - x86" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Convenience rollup update for Windows 7 SP1 - x86" } @{ Name = "Install - July 2016 update rollup for Windows 7 SP1 - x86" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Restart Computer" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - July 2016 update rollup for Windows 7 SP1 - x86" } @{ Name = "Install APP-V 5.1" Type = "Group" GroupName = "State Restore" AddAfter = "Install Applications" } @{ Name = "Install - Windows Management Framework 3.0 - x86" Type = "Install Application" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" } @{ Name = "Restart Computer 2" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" AddAfter = "Install - Windows Management Framework 3.0 - x86" } @{ Name = "Install - APP-V Client 5.1 - x86-x64" Type = "Install Application" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" Disable = "true" AddAfter = "Restart Computer 2" } @{ Name = "Restart Computer 3" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" Disable = "true" AddAfter = "Install - APP-V Client 5.1 - x86-x64" } @{ Name = "Suspend" Type = "Run Command Line" GroupName = "State Restore" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Opt In to CEIP and WER" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 4" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } @{ Name = "Windows 7 x64" Path = "Windows 7" OSName = "Windows 7\Windows 7 ENTERPRISE in Windows 7 x64 install.wim" OrgName = "BuildLab" Template = "Client.xml" ID = "REFW7X64-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "33PXH-7Y6KF-2VJC9-XBBR8-HVTHH" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 7 x64" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Windows Update (Post-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Install - Microsoft NET Framework 3.5.1" Type = "Install Roles and Features" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" OSName = "Windows 7" OSFeatures = "InboxGames,NetFx3,TelnetClient" } @{ Name = "Configure - Disable SMB 1.0" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Command = 'powershell.exe -Command "Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters SMB1 -Type DWORD -Value 0 -Force"' AddAfter = "Install - Microsoft NET Framework 3.5.1" } @{ Name = "Install - Microsoft Visual C++" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Disable SMB 1.0" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Microsoft Visual C++" } @{ Name = "Install - Convenience rollup update for Windows 7 SP1 - x64" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Convenience rollup update for Windows 7 SP1 - x64" } @{ Name = "Install - July 2016 update rollup for Windows 7 SP1 - x64" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Restart Computer" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - July 2016 update rollup for Windows 7 SP1 - x64" } @{ Name = "Install APP-V 5.1" Type = "Group" GroupName = "State Restore" AddAfter = "Install Applications" } @{ Name = "Install - Windows Management Framework 3.0 - x64" Type = "Install Application" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" } @{ Name = "Restart Computer 2" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" AddAfter = "Install - Windows Management Framework 3.0 - x64" } @{ Name = "Install - APP-V Client 5.1 - x86-x64" Type = "Install Application" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" Disable = "true" AddAfter = "Restart Computer 2" } @{ Name = "Restart Computer 3" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Install APP-V 5.1" Disable = "true" AddAfter = "Install - APP-V Client 5.1 - x86-x64" } @{ Name = "Suspend" Type = "Run Command Line" GroupName = "State Restore" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Opt In to CEIP and WER" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 4" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } @{ Name = "Windows 10 x86" Path = "Windows 10" OSName = "Windows 10\Windows 10 Enterprise in Windows 10 x86 install.wim" OrgName = "BuildLab" Template = "Client.xml" ID = "REFW10X86-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "NPPR9-FWDCX-D2C8J-H872K-2YT43" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 10 x86" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Install - Microsoft NET Framework 3.5.1" Type = "Install Roles and Features" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" OSName = "Windows 10" OSFeatures = "NetFx3" } @{ Name = "Install - Microsoft Visual C++" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Microsoft NET Framework 3.5.1" } @{ Name = "Configure - Disable SMB 1.0" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Command = 'powershell.exe -Command "Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart"' AddAfter = "Install - Microsoft Visual C++" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Disable SMB 1.0" } @{ Name = "Configure - Set Start Layout" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Configure - Enable App-V Client" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Start Layout" Command = 'powershell.exe -ExecutionPolicy ByPass -Command "Enable-Appv; Set-AppvClientConfiguration -EnablePackageScripts 1"' } @{ Name = "Suspend1" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Configure - Enable App-V Client" } @{ Name = "Configure - Remove Windows Default Applications" Type = "Run PowerShell Script" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" PSCommand = "%SCRIPTROOT%\Invoke-RemoveBuiltinApps.ps1" AddAfter = "Suspend1" } @{ Name = "Suspend2" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Configure - Remove Windows Default Applications" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Suspend2" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } @{ Name = "Windows 10 x64" Path = "Windows 10" OSName = "Windows 10\Windows 10 Enterprise in Windows 10 x64 install.wim" OrgName = "BuildLab" Template = "Client.xml" ID = "REFW10X64-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "NPPR9-FWDCX-D2C8J-H872K-2YT43" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 10 x64" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Install - Microsoft NET Framework 3.5.1" Type = "Install Roles and Features" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" OSName = "Windows 10" OSFeatures = "NetFx3" } @{ Name = "Install - Microsoft Visual C++" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Install - Microsoft NET Framework 3.5.1" } @{ Name = "Configure - Disable SMB 1.0" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Command = 'powershell.exe -Command "Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart"' AddAfter = "Install - Microsoft Visual C++" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Disable SMB 1.0" } @{ Name = "Configure - Set Start Layout" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Configure - Enable App-V Client" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Set Start Layout" Command = 'powershell.exe -ExecutionPolicy ByPass -Command "Enable-Appv; Set-AppvClientConfiguration -EnablePackageScripts 1"' } @{ Name = "Suspend1" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Configure - Enable App-V Client" } @{ Name = "Configure - Remove Windows Default Applications" Type = "Run PowerShell Script" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" PSCommand = "%SCRIPTROOT%\Invoke-RemoveBuiltinApps.ps1" AddAfter = "Suspend1" } @{ Name = "Suspend2" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" Command = 'cscript.exe "%SCRIPTROOT%\LTISuspend.wsf"' AddAfter = "Configure - Remove Windows Default Applications" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Suspend2" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } @{ Name = "Windows 2016" Path = "Windows 2016" OSName = "Windows 2016\Windows Server 2016 SERVERSTANDARD in Windows 2016 install.wim" OrgName = "BuildLab" Template = "Server.xml" ID = "REFW2016-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "WC2BQ-8NRM3-FDDYY-2BFGV-KHKQY" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 10 x64" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Configure - Firewall rules" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Firewall rules" } @{ Name = "Configure - Disable SMB 1.0" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Command = 'powershell.exe -Command "Remove-WindowsFeature -Name FS-SMB1"' Disable = "true" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" AddAfter = "Configure - Disable SMB 1.0" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } @{ Name = "Windows 2019" Path = "Windows 2016" OSName = "Windows 2016\Windows Server 2019 SERVERSTANDARD in Windows 2019 install.wim" OrgName = "BuildLab" Template = "Server.xml" ID = "REFW2019-001" Customize = @( # Set Product Key needed for MSDN/Evalution Windows distributives only. Skip this step if your ISO sources is VLSC. @{ Name = "Set Product Key" Type = "Set Task Sequence Variable" GroupName = "Initialization" Description = "KMS Client Setup Keys: https://docs.microsoft.com/en-us/windows-server/get-started/kmsclientkeys" TSVarName = "ProductKey" TSVarValue = "N69G4-B89J2-4G8F4-WWYCC-J464C" Disable = "true" } @{ Name = "Apply Patches" Type = "Install Updates Offline" GroupName = "Preinstall" SelectionProfile = "Windows 10 x64" } @{ Name = "Windows Update (Pre-Application Installation)" Type = "Run Command Line" GroupName = "State Restore" Disable = "false" } @{ Name = "Custom Tasks (Pre-Windows Update)" Type = "Group" GroupName = "State Restore" AddAfter = "Tattoo" } @{ Name = "Custom Tasks" Type = "Group" GroupName = "State Restore" NewName = "Custom Tasks (Post-Windows Update)" } @{ Name = "Cleanup before Sysprep" Type = "Group" GroupName = "State Restore" AddAfter = "Apply Local GPO Package" } @{ Name = "Configure - Firewall rules" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Cleanup before Sysprep" } @{ Name = "Configure - Set Control+Shift Keyboard Toggle" Type = "Install Application" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" AddAfter = "Configure - Firewall rules" } @{ Name = "Restart Computer" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Custom Tasks (Pre-Windows Update)" Disable = "true" AddAfter = "Configure - Set Control+Shift Keyboard Toggle" } @{ Name = "Action - CleanupBuildWSUS" Type = "Run Command Line" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" Command = "reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /f" } @{ Name = "Action - CleanupBeforeSysprep" Type = "Install Application" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBuildWSUS" } @{ Name = "Restart Computer 1" Type = "Restart Computer" GroupName = "State Restore" SubGroup = "Cleanup before Sysprep" AddAfter = "Action - CleanupBeforeSysprep" } ) } ) #Custom folder/files to add to the MDT CustomSettings = @( @{ Name = "Scripts.zip" SourcePath = "Scripts" TestFiles = @("RemoveApps.ps1", "RemoveApps81.xml", "RemoveApps10.xml" ) } @{ Name = "Invoke-RemoveBuiltinApps.ps1" SourcePath = "RemoveDefaultApps" } ) #Custom settings and boot ini file management CustomizeIniFiles = @( @{ Name = "CustomSettingsIni" Path = "\Control\CustomSettings.ini" Company = "Build Lab" TimeZoneName = "Ekaterinburg Standard Time" WSUSServer = "http://fqdn:port" UserLocale = "en-US" KeyboardLocale = "en-US;ru-RU" } @{ Ensure = "Present" Name = "BootstrapIni" Path = "\Control\Bootstrap.ini" } ) #Boot image creation and management BootImage = @( @{ Version = "1.0" ExtraDirectory = "Extra" BackgroundFile = "%INSTALLDIR%\Samples\Background.bmp" LiteTouchWIMDescription = "MDT Build Lab" } ) } ) }
{ "content_hash": "e770c43576b00130f0f639db05efc5b2", "timestamp": "", "source": "github", "line_count": 1116, "max_line_length": 188, "avg_line_length": 53.797491039426525, "alnum_prop": 0.35459209167527234, "repo_name": "pvs043/cMDTBuildLab", "id": "0e15a84195e0cdc1578da37dca38553271462a70", "size": "60038", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Deploy/Deploy_MDT_Server_ConfigurationData.psd1", "mode": "33188", "license": "mit", "language": [ { "name": "PowerShell", "bytes": "300238" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <title>class Firebind::TcpTransport - RDoc Documentation</title> <link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet"> <script type="text/javascript"> var rdoc_rel_prefix = "../"; </script> <script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../js/navigation.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search_index.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search.js"></script> <script type="text/javascript" charset="utf-8" src="../js/searcher.js"></script> <script type="text/javascript" charset="utf-8" src="../js/darkfish.js"></script> <body id="top" class="class"> <nav id="metadata"> <nav id="home-section" class="section"> <h3 class="section-header"> <a href="../index.html">Home</a> <a href="../table_of_contents.html#classes">Classes</a> <a href="../table_of_contents.html#methods">Methods</a> </h3> </nav> <nav id="search-section" class="section project-section" class="initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <h3 class="section-header"> <input type="text" name="search" placeholder="Search" id="search-field" title="Type to search, Up and Down to navigate, Enter to load"> </h3> </form> <ul id="search-results" class="initially-hidden"></ul> </nav> <div id="file-metadata"> <nav id="file-list-section" class="section"> <h3 class="section-header">Defined In</h3> <ul> <li>lib/firebind/tcp_transport.rb </ul> </nav> </div> <div id="class-metadata"> <nav id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <p class="link">Transport </nav> <!-- Included Modules --> <nav id="includes-section" class="section"> <h3 class="section-header">Included Modules</h3> <ul class="link-list"> <li><a class="include" href="../Tools.html">Tools</a> </ul> </nav> <!-- Method Quickref --> <nav id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <li class="calls-super" ><a href="#method-c-new">::new</a> <li ><a href="#method-i-connect">#connect</a> <li ><a href="#method-i-receive">#receive</a> <li ><a href="#method-i-send">#send</a> </ul> </nav> </div> <div id="project-metadata"> <nav id="fileindex-section" class="section project-section"> <h3 class="section-header">Pages</h3> <ul> <li class="file"><a href="../LICENSE_txt.html">LICENSE</a> <li class="file"><a href="../README_txt.html">README</a> <li class="file"><a href="../USAGE_txt.html">USAGE</a> <li class="file"><a href="../VERSION_txt.html">VERSION</a> <li class="file"><a href="../doc/created_rid.html">created.rid</a> <li class="file"><a href="../firescan_gemspec.html">firescan.gemspec</a> </ul> </nav> <nav id="classindex-section" class="section project-section"> <h3 class="section-header">Class and Module Index</h3> <ul class="link-list"> <li><a href="../Example.html">Example</a> <li><a href="../Firebind.html">Firebind</a> <li><a href="../Firebind/Client.html">Firebind::Client</a> <li><a href="../Firebind/Portspec.html">Firebind::Portspec</a> <li><a href="../Firebind/Scan.html">Firebind::Scan</a> <li><a href="../Firebind/ScanError.html">Firebind::ScanError</a> <li><a href="../Firebind/ScanState.html">Firebind::ScanState</a> <li><a href="../Firebind/SimpleProtocol.html">Firebind::SimpleProtocol</a> <li><a href="../Firebind/TcpTransport.html">Firebind::TcpTransport</a> <li><a href="../Firebind/Transport.html">Firebind::Transport</a> <li><a href="../Firebind/UdpTransport.html">Firebind::UdpTransport</a> <li><a href="../Runner.html">Runner</a> <li><a href="../TestPortspec.html">TestPortspec</a> <li><a href="../Tools.html">Tools</a> </ul> </nav> </div> </nav> <div id="documentation"> <h1 class="class">class Firebind::TcpTransport</h1> <div id="description" class="description"> <p>Send and receive echo using TCP transport.</p> </div><!-- description --> <section id="5Buntitled-5D" class="documentation-section"> <!-- Methods --> <section id="public-class-5Buntitled-5D-method-details" class="method-section section"> <h3 class="section-header">Public Class Methods</h3> <div id="method-c-new" class="method-detail "> <div class="method-heading"> <span class="method-name">new</span><span class="method-args">(echo_server,timeout)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-calls-super"> Calls superclass method </div> <div class="method-source-code" id="new-source"> <pre><span class="ruby-comment"># File lib/firebind/tcp_transport.rb, line 28</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">initialize</span> (<span class="ruby-identifier">echo_server</span>,<span class="ruby-identifier">timeout</span>) <span class="ruby-keyword">super</span>(<span class="ruby-identifier">echo_server</span>,<span class="ruby-identifier">timeout</span>) <span class="ruby-keyword">end</span></pre> </div><!-- new-source --> </div> </div><!-- new-method --> </section><!-- public-class-method-details --> <section id="public-instance-5Buntitled-5D-method-details" class="method-section section"> <h3 class="section-header">Public Instance Methods</h3> <div id="method-i-connect" class="method-detail "> <div class="method-heading"> <span class="method-name">connect</span><span class="method-args">(port)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>establish connection to echo server on port</p> <div class="method-source-code" id="connect-source"> <pre><span class="ruby-comment"># File lib/firebind/tcp_transport.rb, line 33</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">connect</span>(<span class="ruby-identifier">port</span>) <span class="ruby-ivar">@port</span> = <span class="ruby-identifier">port</span> <span class="ruby-identifier">connect_start</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-comment">#host_addr = Socket.getaddrinfo(@echo_server,nil) # probably should get 0,3 from this guy for IPv6</span> <span class="ruby-keyword">begin</span> <span class="ruby-comment">#noinspection RubyArgCount</span> <span class="ruby-ivar">@socket</span> = <span class="ruby-constant">Socket</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:INET</span>, <span class="ruby-value">:STREAM</span>) <span class="ruby-ivar">@remote_addr</span> = <span class="ruby-constant">Socket</span>.<span class="ruby-identifier">pack_sockaddr_in</span>(<span class="ruby-ivar">@port</span>, <span class="ruby-ivar">@echo_server</span>) <span class="ruby-keyword">rescue</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span> <span class="ruby-value">:HANDSHAKE_CONNECTION_INITIATION_FAILURE</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">begin</span> <span class="ruby-ivar">@socket</span>.<span class="ruby-identifier">connect_nonblock</span> <span class="ruby-ivar">@remote_addr</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">Errno</span><span class="ruby-operator">::</span><span class="ruby-constant">EINPROGRESS</span> <span class="ruby-comment"># still doing handshake, wait @timeout until its ready to connect_nonblock again</span> <span class="ruby-identifier">debug</span>(<span class="ruby-node">&quot;connection still inprogress select for #{@timeout}ms&quot;</span>) <span class="ruby-comment"># interest ops: reading,writing,error,timeout</span> <span class="ruby-identifier">readables</span>,<span class="ruby-identifier">writables</span>,<span class="ruby-identifier">errors</span> = <span class="ruby-constant">IO</span>.<span class="ruby-identifier">select</span>([<span class="ruby-ivar">@socket</span>], [<span class="ruby-ivar">@socket</span>], [<span class="ruby-ivar">@socket</span>], <span class="ruby-ivar">@timeout_seconds</span>) <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;readables=#{readables} writables=#{writables} errors=#{errors}&quot;</span> <span class="ruby-identifier">readable</span> = <span class="ruby-identifier">readables</span> <span class="ruby-operator">!=</span> <span class="ruby-keyword">nil</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">readables</span>.<span class="ruby-identifier">length</span> <span class="ruby-operator">&gt;</span> <span class="ruby-value">0</span> <span class="ruby-identifier">writable</span> = <span class="ruby-identifier">writables</span> <span class="ruby-operator">!=</span> <span class="ruby-keyword">nil</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">writables</span>.<span class="ruby-identifier">length</span> <span class="ruby-operator">&gt;</span> <span class="ruby-value">0</span> <span class="ruby-identifier">error</span> = <span class="ruby-identifier">errors</span> <span class="ruby-operator">!=</span> <span class="ruby-keyword">nil</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">errors</span>.<span class="ruby-identifier">length</span> <span class="ruby-operator">&gt;</span> <span class="ruby-value">0</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">error</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:HANDSHAKE_CONNECTION_REFUSED</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">readable</span> <span class="ruby-operator">||</span> <span class="ruby-identifier">writable</span> <span class="ruby-keyword">retry</span> <span class="ruby-keyword">else</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;connection timeout after #{@timeout}ms&quot;</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span> <span class="ruby-value">:HANDSHAKE_CONNECTION_TIME_OUT</span> <span class="ruby-keyword">end</span> <span class="ruby-comment"># A time check may be required in the future (if we select for less than timeout)</span> <span class="ruby-comment"># if Time.now - connect_start &gt; @timeout_seconds</span> <span class="ruby-comment"># raise Firebind::ScanError.new :HANDSHAKE_CONNECTION_TIME_OUT</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">Errno</span><span class="ruby-operator">::</span><span class="ruby-constant">EISCONN</span> <span class="ruby-comment"># this is a linux code... todo: figure the platform codes for continuation</span> <span class="ruby-identifier">debug</span> <span class="ruby-string">'connection success'</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">Errno</span><span class="ruby-operator">::</span><span class="ruby-constant">ECONNREFUSED</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">e</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:HANDSHAKE_CONNECTION_REFUSED</span>, <span class="ruby-identifier">e</span>) <span class="ruby-keyword">rescue</span> <span class="ruby-comment">#collect all the ways a connection can fail... some of the conditions are:</span> <span class="ruby-comment"># 1) No route to host - connect(2)</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:HANDSHAKE_CONNECTION_REFUSED</span>, <span class="ruby-identifier">$!</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div><!-- connect-source --> </div> </div><!-- connect-method --> <div id="method-i-receive" class="method-detail "> <div class="method-heading"> <span class="method-name">receive</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Receive echo response from server.</p> <p>PAYLOAD_REFUSED_ON_RECV PAYLOAD_ERROR_ON_RECV PAYLOAD_TIMED_OUT_ON_RECV</p> <p>@return [Object]</p> <div class="method-source-code" id="receive-source"> <pre><span class="ruby-comment"># File lib/firebind/tcp_transport.rb, line 127</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">receive</span> <span class="ruby-identifier">size</span> = <span class="ruby-ivar">@payload</span>.<span class="ruby-identifier">length</span> <span class="ruby-identifier">count</span> = <span class="ruby-value">0</span> <span class="ruby-identifier">receive_start</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-identifier">receive_buffer</span> = <span class="ruby-string">''</span> <span class="ruby-keyword">while</span> <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-operator">-</span> <span class="ruby-identifier">receive_start</span> <span class="ruby-operator">&lt;=</span> <span class="ruby-ivar">@timeout_seconds</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">&lt;</span> <span class="ruby-identifier">size</span> <span class="ruby-keyword">begin</span> <span class="ruby-identifier">read_result</span> = <span class="ruby-ivar">@socket</span>.<span class="ruby-identifier">read_nonblock</span>(<span class="ruby-value">1024</span>) <span class="ruby-identifier">count</span> <span class="ruby-operator">+=</span> <span class="ruby-identifier">read_result</span>.<span class="ruby-identifier">length</span> <span class="ruby-comment"># because appending to receive_buffer won't count recv bytes via .length</span> <span class="ruby-comment"># add read_result to our buffer</span> <span class="ruby-identifier">receive_buffer</span> <span class="ruby-operator">&lt;&lt;</span> <span class="ruby-identifier">read_result</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;read buffer is #{count}&quot;</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">IO</span><span class="ruby-operator">::</span><span class="ruby-constant">WaitReadable</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">size</span> <span class="ruby-comment"># we're done - read all we had expected to receive</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;completed full read of #{count} bytes&quot;</span> <span class="ruby-keyword">break</span> <span class="ruby-keyword">elsif</span> <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-operator">-</span> <span class="ruby-identifier">receive_start</span> <span class="ruby-operator">&gt;</span> <span class="ruby-ivar">@timeout_seconds</span> <span class="ruby-comment"># timeout on receive</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:PAYLOAD_TIMED_OUT_ON_RECV</span>) <span class="ruby-keyword">else</span> <span class="ruby-comment"># keep going</span> <span class="ruby-constant">IO</span>.<span class="ruby-identifier">select</span>([<span class="ruby-ivar">@socket</span>],<span class="ruby-keyword">nil</span>,<span class="ruby-keyword">nil</span>,<span class="ruby-ivar">@timeout_seconds</span>) <span class="ruby-keyword">retry</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">EOFError</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">e</span> <span class="ruby-comment"># connection was forcefully dropped or sent a final FIN ACK closing sequence</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">!=</span> <span class="ruby-identifier">size</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:PAYLOAD_ERROR_ON_RECV</span>,<span class="ruby-identifier">e</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> <span class="ruby-comment">#collect all the ways a receive can fail... todo:</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">$debug</span> <span class="ruby-identifier">puts</span> <span class="ruby-string">'Caught unhandled socket error:'</span> <span class="ruby-identifier">p</span> <span class="ruby-node">$1</span> <span class="ruby-identifier">puts</span> <span class="ruby-identifier">$@</span> <span class="ruby-keyword">end</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:PAYLOAD_REFUSED_ON_RECV</span>,<span class="ruby-identifier">$!</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-comment"># we still could have timed out here, check rx buffer size first</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">&lt;</span> <span class="ruby-identifier">size</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:PAYLOAD_TIMED_OUT_ON_RECV</span>) <span class="ruby-keyword">end</span> <span class="ruby-comment"># now compare what we received with what we sent</span> <span class="ruby-identifier">received_array</span> = <span class="ruby-identifier">receive_buffer</span>.<span class="ruby-identifier">unpack</span>(<span class="ruby-string">'C*'</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">received_array</span> <span class="ruby-operator">!=</span> <span class="ruby-ivar">@payload</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;rx buffer #{received_array.to_s} is NOT equal to expected #{@payload.to_s}&quot;</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:PAYLOAD_MISMATCH_ON_RECV</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;rx buffer #{received_array.to_s} is equal to payload #{@payload.to_s}&quot;</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div><!-- receive-source --> </div> </div><!-- receive-method --> <div id="method-i-send" class="method-detail "> <div class="method-heading"> <span class="method-name">send</span><span class="method-args">(payload)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Send data to the echo server</p> <p>@param [<a href="http://">Array</a> payload - array of bytes</p> <div class="method-source-code" id="send-source"> <pre><span class="ruby-comment"># File lib/firebind/tcp_transport.rb, line 89</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">send</span>(<span class="ruby-identifier">payload</span>) <span class="ruby-ivar">@payload</span> = <span class="ruby-identifier">payload</span> <span class="ruby-identifier">size</span> = <span class="ruby-identifier">payload</span>.<span class="ruby-identifier">length</span> <span class="ruby-identifier">count</span> = <span class="ruby-value">0</span> <span class="ruby-identifier">send_start</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-identifier">payload</span>.<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">byte</span><span class="ruby-operator">|</span> <span class="ruby-keyword">begin</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">+=</span> <span class="ruby-ivar">@socket</span>.<span class="ruby-identifier">write_nonblock</span> [<span class="ruby-identifier">byte</span>].<span class="ruby-identifier">pack</span>(<span class="ruby-string">'C'</span>) <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;wrote #{count} bytes to #{@echo_server}:#{@port}&quot;</span> <span class="ruby-keyword">rescue</span> <span class="ruby-constant">IO</span><span class="ruby-operator">::</span><span class="ruby-constant">WaitWritable</span>, <span class="ruby-constant">Errno</span><span class="ruby-operator">::</span><span class="ruby-constant">EINTR</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">count</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">size</span> <span class="ruby-comment"># we've written our payload, we're done</span> <span class="ruby-identifier">debug</span> <span class="ruby-node">&quot;completed #{count} byte payload to #{@echo_server}:#{@port}&quot;</span> <span class="ruby-keyword">elsif</span> <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-operator">-</span> <span class="ruby-identifier">send_start</span> <span class="ruby-operator">&gt;</span> <span class="ruby-ivar">@timeout_seconds</span> <span class="ruby-comment"># we've timed out of sending</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span> <span class="ruby-value">:FAILURE_ON_PAYLOAD_SEND</span> <span class="ruby-keyword">else</span> <span class="ruby-comment"># try to write some more ? http://ruby-doc.org/core-1.9.3/IO.html#method-i-write_nonblock</span> <span class="ruby-keyword">retry</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">rescue</span> <span class="ruby-comment">#collect all the ways a send can fail...</span> <span class="ruby-identifier">raise</span> <span class="ruby-constant">Firebind</span><span class="ruby-operator">::</span><span class="ruby-constant">ScanError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:FAILURE_ON_PAYLOAD_SEND</span>, <span class="ruby-identifier">$!</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div><!-- send-source --> </div> </div><!-- send-method --> </section><!-- public-instance-method-details --> </section><!-- 5Buntitled-5D --> </div><!-- documentation --> <footer id="validator-badges"> <p><a href="http://validator.w3.org/check/referer">[Validate]</a> <p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 4.0.1. <p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3. </footer>
{ "content_hash": "9d00cbfaf0c8ecf8d7338050f8039a18", "timestamp": "", "source": "github", "line_count": 479, "max_line_length": 470, "avg_line_length": 54.782881002087684, "alnum_prop": 0.6571776990206166, "repo_name": "Firebind/firescan-ruby", "id": "f4d2701456a7211d6ef2ae9040e300513220515c", "size": "26241", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/Firebind/TcpTransport.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10365" }, { "name": "JavaScript", "bytes": "16758" }, { "name": "Ruby", "bytes": "49063" } ], "symlink_target": "" }
package piazza import ( "encoding/base64" "io" "io/ioutil" "net/http" "strings" ) type HeaderBuilder struct { header [][2]string } const GET, PUT, POST, DELETE, HEAD = "GET", "PUT", "POST", "DELETE", "HEAD" func NewHeaderBuilder() *HeaderBuilder { return &HeaderBuilder{[][2]string{}} } func (builder *HeaderBuilder) AddJsonContentType() *HeaderBuilder { builder.AddHeader("Content-Type", "application/json") return builder } func (builder *HeaderBuilder) AddBasicAuth(username, password string) *HeaderBuilder { auth := GetBasicAuthHeader(username, password) builder.AddHeader(auth[0], auth[1]) return builder } func (builder *HeaderBuilder) AddHeader(key, value string) *HeaderBuilder { builder.header = append(builder.header, [2]string{key, value}) return builder } func (builder *HeaderBuilder) GetHeader() [][2]string { return builder.header } func HTTP(requestType, url string, headers [][2]string, toSend io.Reader) (int, []byte, http.Header, error) { if !hasProtocol.MatchString(url) { url = "https://" + url } req, err := http.NewRequest(requestType, url, toSend) if err != nil { return 0, nil, nil, err } for _, v := range headers { req.Header.Set(v[0], v[1]) } client := &http.Client{} response, err := client.Do(req) if err != nil { return 0, nil, nil, err } defer func() { err = response.Body.Close() if err != nil { // TODO: no way to handle error in a defer! panic(err) } }() body, err := ioutil.ReadAll(response.Body) if err != nil { return response.StatusCode, nil, nil, err } return response.StatusCode, body, response.Header, nil } /* func HTTPReq(requestType, url string, headers [][2]string, toSend io.Reader) (*http.Response, error) { req, err := http.NewRequest(requestType, url, toSend) if err != nil { return nil, err } for _, v := range headers { req.Header.Set(v[0], v[1]) } client := &http.Client{} return client.Do(req) } */ func GetBasicAuthHeader(username, password string) [2]string { username = strings.TrimSpace(username) password = strings.TrimSpace(password) res := username + ":" + password enc := base64.URLEncoding.EncodeToString([]byte(res)) return [2]string{"Authorization", "Basic " + enc} } func GetValueFromHeader(header http.Header, field string) string { return header.Get(field) }
{ "content_hash": "06603a8885dc636c480d1dee695fb204", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 109, "avg_line_length": 24.827956989247312, "alnum_prop": 0.6868774361195322, "repo_name": "venicegeo/pz-gocommon", "id": "0526186b8c6006d79fa69269427245154de3dc0e", "size": "2884", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "gocommon/nt.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "706642" }, { "name": "Groovy", "bytes": "2691" }, { "name": "Shell", "bytes": "6521" } ], "symlink_target": "" }
package com.linkedin.metadata.kafka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration; @SuppressWarnings("checkstyle:HideUtilityClassConstructor") @SpringBootApplication(exclude = {RestClientAutoConfiguration.class}) public class MceConsumerApplication { public static void main(String[] args) { SpringApplication.run(MceConsumerApplication.class, args); } }
{ "content_hash": "0109b2c703df67ec09e93992520afc59", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 93, "avg_line_length": 35.6, "alnum_prop": 0.8426966292134831, "repo_name": "linkedin/WhereHows", "id": "b308b5dba8b5c8a321b3ee8872b011d3a0dd1b83", "size": "534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metadata-jobs/mce-consumer-job/src/main/java/com/linkedin/metadata/kafka/MceConsumerApplication.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "110129" }, { "name": "Dockerfile", "bytes": "2521" }, { "name": "HTML", "bytes": "131513" }, { "name": "Java", "bytes": "1307442" }, { "name": "JavaScript", "bytes": "148450" }, { "name": "Nearley", "bytes": "2837" }, { "name": "Python", "bytes": "1419332" }, { "name": "Shell", "bytes": "2564" }, { "name": "TSQL", "bytes": "42644" }, { "name": "TypeScript", "bytes": "641014" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/snapshot_old" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginLeft="8dp" /> <TextView android:id="@+id/snapshot_new" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8dp" /> <View android:layout_width="match_parent" android:layout_height="1px" android:layout_marginTop="8dp" android:background="@android:color/holo_blue_bright" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginLeft="8dp" android:text="@string/fg_bg_choices_hint" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8dp" > <CheckBox android:id="@+id/fg_traffic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/fg_traffic" /> <CheckBox android:id="@+id/bg_traffic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/bg_traffic" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1px" android:layout_marginTop="8dp" android:background="@android:color/holo_blue_bright" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginLeft="8dp" android:text="@string/iface_choices_hint" /> <GridView android:id="@+id/iface_choices" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:columnWidth="80dp" android:numColumns="auto_fit" /> <View android:layout_width="match_parent" android:layout_height="1px" android:layout_marginTop="8dp" android:background="@android:color/holo_blue_bright" /> <ListView android:id="@+id/tags_stats" android:layout_width="match_parent" android:layout_height="match_parent" /> <TextView android:id="@+id/empty_no_usage" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="@string/tips_no_traffic_usage" /> </LinearLayout>
{ "content_hash": "8278a06b0e5024f7e9178c9077c2434b", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 72, "avg_line_length": 35.714285714285715, "alnum_prop": 0.6243333333333333, "repo_name": "yongce/AppTrafficAnalyzer", "id": "27dee62e432df5768fef8c388da6dbf0b97b3929", "size": "3000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/usage_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "937" }, { "name": "Java", "bytes": "73829" } ], "symlink_target": "" }
layout: default description: Expressions as attribute names or using subqueries and ZIP() title: Dynamic Attribute Names in AQL --- Dynamic Attribute Names in AQL ============================== You might want an AQL query to return results with attribute names assembled by a function, or with a variable number of attributes. This will not work by specifying the result using a regular object literal, as object literals require the names and numbers of attributes to be fixed at query compile time. There are two solutions to getting dynamic attribute names to work: - Using expressions as attribute names (fixed amount of attributes) - Using subqueries and the `ZIP()` function (variable amount of attributes) ## Using expressions as attribute names This solution works in cases where the number of dynamic attributes to return is known in advance, and only the attribute names need to be calculated using an expression. Using expressions as attribute names instead of fixed attribute names in object literals requires enclosing the expression in extra `[` and `]` to disambiguate them from regular, unquoted attribute names. Let us create a result that returns the original document data contained in a dynamically named attribute. We will be using the expression `doc.type` for the attribute name. We will also return some other attributes from the original documents, but prefix them with the documents' `_key` attribute values. For this we also need attribute name expressions. Here is a query showing how to do this. The attribute name expressions all required to be enclosed in `[` and `]` in order to make this work: ```js LET documents = [ { "_key" : "3231748397810", "gender" : "f", "status" : "active", "type" : "user" }, { "_key" : "3231754427122", "gender" : "m", "status" : "inactive", "type" : "unknown" } ] FOR doc IN documents RETURN { [ doc.type ] : { [ CONCAT(doc._key, "_gender") ] : doc.gender, [ CONCAT(doc._key, "_status") ] : doc.status } } ``` This will return: ```json [ { "user": { "3231748397810_gender": "f", "3231748397810_status": "active" } }, { "unknown": { "3231754427122_gender": "m", "3231754427122_status": "inactive" } } ] ``` Note: Attribute name expressions and regular, unquoted attribute names can be mixed. ## Subquery solution A generalized solution is to let a subquery or another function produce the dynamic attribute names, and finally pass them through the `ZIP()` function to create an object from them. Let us assume we want to process the following input documents: ```json { "name": "test", "gender": "f", "status": "active", "type": "user" } { "name": "dummy", "gender": "m", "status": "inactive", "type": "unknown", "magicFlag": 23 } ``` Let us also assume our goal for each of these documents is to return only the attribute names that contain the letter `a`, together with their respective values. To extract the attribute names and values from the original documents, we can use a subquery as follows: ```js LET documents = [ { "name": "test"," gender": "f", "status": "active", "type": "user" }, { "name": "dummy", "gender": "m", "status": "inactive", "type": "unknown", "magicFlag": 23 } ] FOR doc IN documents RETURN ( FOR name IN ATTRIBUTES(doc) FILTER LIKE(name, '%a%') RETURN { name: name, value: doc[name] } ) ``` The subquery will only let attribute names pass that contain the letter `a`. The results of the subquery are then made available to the main query and will be returned. But the attribute names in the result are still `name` and `value`, so we're not there yet. So let us also employ AQL's [ZIP()](functions-document.html#zip) function, which can create an object from two arrays: - the first parameter to `ZIP()` is an array with the attribute names - the second parameter to `ZIP()` is an array with the attribute values Instead of directly returning the subquery result, we first capture it in a variable, and pass the variable's `name` and `value` components into `ZIP()` like this: ```js LET documents = [ { "name" : "test"," gender" : "f", "status" : "active", "type" : "user" }, { "name" : "dummy", "gender" : "m", "status" : "inactive", "type" : "unknown", "magicFlag" : 23 } ] FOR doc IN documents LET attributes = ( FOR name IN ATTRIBUTES(doc) FILTER LIKE(name, '%a%') RETURN { name: name, value: doc[name] } ) RETURN ZIP(attributes[*].name, attributes[*].value) ``` Note that we have to use the expansion operator (`[*]`) on `attributes` because `attributes` itself is an array, and we want either the `name` attribute or the `value` attribute of each of its members. To prove this is working, here is the above query's result: ```json [ { "name": "test", "status": "active" }, { "name": "dummy", "status": "inactive", "magicFlag": 23 } ] ``` As can be seen, the two results have a different amount of result attributes. We can also make the result a bit more dynamic by prefixing each attribute with the value of the `name` attribute: ```js LET documents = [ { "name": "test"," gender": "f", "status": "active", "type": "user" }, { "name": "dummy", "gender": "m", "status": "inactive", "type": "unknown", "magicFlag": 23 } ] FOR doc IN documents LET attributes = ( FOR name IN ATTRIBUTES(doc) FILTER LIKE(name, '%a%') RETURN { name: CONCAT(doc.name, '-', name), value: doc[name] } ) RETURN ZIP(attributes[*].name, attributes[*].value) ``` That will give us document-specific attribute names like this: ```json [ { "test-name": "test", "test-status": "active" }, { "dummy-name": "dummy", "dummy-status": "inactive", "dummy-magicFlag": 23 } ] ```
{ "content_hash": "9140979f90edba0cf31eef41e822c3fd", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 99, "avg_line_length": 29.084577114427862, "alnum_prop": 0.6696886760177899, "repo_name": "arangodb/docs", "id": "cba9bed31c4e71351d364d5f54910cce16435a84", "size": "5850", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "3.7/aql/examples-dynamic-attribute-names.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "111161" }, { "name": "Dockerfile", "bytes": "606" }, { "name": "HTML", "bytes": "20095" }, { "name": "JavaScript", "bytes": "7194" }, { "name": "Ruby", "bytes": "60609" }, { "name": "Shell", "bytes": "617" } ], "symlink_target": "" }
import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlParser { private static Logger logger = Logger.getLogger(XmlParser.class); private static final String STATUS = "FAIL"; private static final String filePath = "/dir/isoTestResponse.xml"; // Path to the Response XML public static void main(String[] args) { try { File xmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); logger.debug("Document path: " + filePath); logger.debug("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nodeList = doc.getElementsByTagName("test-method"); printFailedTests(nodeList); } catch (ParserConfigurationException e) { logger.error("Unable to parse Configuration at " + filePath, e); } catch (SAXException e) { logger.error("Unable to parse Configuration at " + filePath, e); } catch (IOException e) { logger.error("Unable to Read file at " + filePath, e); } } /** * Get only Failed Tests * @param nodeList */ public static void printFailedTests(NodeList nodeList) { if(nodeList != null) { for (int tmpNode = 0; tmpNode < nodeList.getLength(); tmpNode++) { Node nNode = nodeList.item(tmpNode); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element nodeElement = (Element) nNode; if(nodeElement.getAttribute("status") != null && STATUS.equals(nodeElement.getAttribute("status").trim())) { logger.debug("______________________________"); logger.debug("Name : " + nodeElement.getAttribute("name")); // Print Failed Test Name logger.debug("Description : " + nodeElement.getAttribute("description")); // Print Failed Test Description if(nodeElement.hasChildNodes()) { String testMessage = getMessage(nodeElement.getChildNodes()); logger.debug("Reason for failure : " + testMessage); // Print Reason why test failed } } } } } else { logger.error("Unable to get Failed Tests as NodeList was null.");; } } /** * Get Exception Message * @param nodeList * @return */ public static String getMessage(NodeList nodeList) { if(nodeList != null) { for (int count = 0; count < nodeList.getLength(); count++) { Node tempNode = nodeList.item(count); if (tempNode.getNodeType() == Node.ELEMENT_NODE) { // get Exception message if("exception".equals(tempNode.getNodeName())) { if(tempNode.hasChildNodes()) { NodeList list = tempNode.getChildNodes(); for(int i = 0; i < list.getLength(); i++) { Node messNode = list.item(i); if("message".equals(messNode.getNodeName())) { return(messNode.getTextContent() != null ? messNode.getTextContent().trim() : messNode.getTextContent()); } } } } } } } else { logger.debug("Cannot find Message as nodeLost was null."); } return null; } }
{ "content_hash": "53b6ca9ca84fb2468b26c58f9725a3ec", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 114, "avg_line_length": 26.925925925925927, "alnum_prop": 0.6176066024759285, "repo_name": "CINERGI/ets-19139", "id": "9c2ea7c92908ed5ea52f7556fb1ef3126fea70a9", "size": "3635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/javadoc/XmlParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Eagle", "bytes": "43258" }, { "name": "HTML", "bytes": "1321" }, { "name": "Java", "bytes": "216952" }, { "name": "KiCad", "bytes": "2110" } ], "symlink_target": "" }
namespace CivGen { using System; using System.Collections.Generic; public partial class Color { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Color() { this.PlayerColors = new HashSet<PlayerColor>(); this.PlayerColors1 = new HashSet<PlayerColor>(); this.PlayerColors2 = new HashSet<PlayerColor>(); } public string Type { get; set; } public double Red { get; set; } public double Green { get; set; } public double Blue { get; set; } public double Alpha { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<PlayerColor> PlayerColors { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<PlayerColor> PlayerColors1 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<PlayerColor> PlayerColors2 { get; set; } } }
{ "content_hash": "1cfc3251faef71ac05babdba3cab3d47", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 128, "avg_line_length": 44.62068965517241, "alnum_prop": 0.6792890262751159, "repo_name": "ls612/CFCGen", "id": "5b19e8e3d7cf5b25c321e89216765b92522fde17", "size": "1718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CivGen/Color.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "507560" }, { "name": "PowerShell", "bytes": "89630" } ], "symlink_target": "" }
<?php /** * Message translations. * * This file is automatically generated by 'yiic message' command. * It contains the localizable messages extracted from source code. * You may modify this file by translating the extracted messages. * * Each array element represents the translation (value) of a message (key). * If the value is empty, the message is considered as not translated. * Messages that no longer need translation will have their translations * enclosed between a pair of '@@' marks. * * Message string can be used with plural forms format. Check i18n section * of the guide for details. * * NOTE, this file must be saved in UTF-8 encoding. */ return array ( '63eu.com' => '', 'Contact Person' => '', 'Incorrect verification code' => '', 'SendRFQ' => '', 'Website Technology Support' => '', 'About Us' => '私達について', 'Advantage' => '利点', 'All Manufacturers' => '全メーカー', 'Applications' => 'アプリケーション', 'Barum Electronics Co., LTD' => 'Barum電子株式会社', 'Click to learn more' => 'より多くを学ぶためにクリック', 'Company Events' => '会社のイベント', 'Contact Us' => 'お問い合わせ', 'Culture' => '文化', 'Customers' => 'お客さま', 'Direction' => '方向', 'Distribution Brands' => 'ディストリビューションブランド', 'Feature' => 'フィーチャー', 'Help' => '助け', 'Home' => 'ホーム', 'Manufacturer' => 'メーカー', 'Manufacturers' => 'メーカー', 'Model' => 'モデル', 'New Technologies' => '新技術', 'Online Inquiry' => 'オンラインお問い合わせ', 'Order Tracking' => '商品追跡', 'Ordering Information' => '発注情報', 'Package' => 'パッケージ', 'Popular Searches' => '人気の検索ワード', 'Price based on quantity, market conditions and other factors vary. Please call or send a quick inquiry ... Thanks!' => '量に基づいて価格は、市場の状況やその他の要因は様々である。迅速な問い合わせを呼び出すか、送信してください...ありがとう!', 'Product Details' => '商品の詳細', 'Products' => '製品', 'Products Show' => '製品ショー', 'Quality Control' => '品質管理', 'Quantity' => '数量', 'Questions? Please consult our sales' => '質問?弊社営業にご相談ください', 'Service' => 'サービス', 'Technology' => 'テクノロジー', 'Tips: Please fill in the following information to facilitate contact!' => 'ヒント:連絡先を容易にするために、以下の情報を入力してください!', );
{ "content_hash": "c89be2e0b3468d7b73f0497caa16580b", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 186, "avg_line_length": 35.59322033898305, "alnum_prop": 0.6533333333333333, "repo_name": "defclass/etw", "id": "3b127eb60902e4317891e97c0c481150da560a2f", "size": "2634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/protected/messages/ja/main.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "105" }, { "name": "Batchfile", "bytes": "2948" }, { "name": "CSS", "bytes": "744445" }, { "name": "HTML", "bytes": "3945698" }, { "name": "JavaScript", "bytes": "1337659" }, { "name": "PHP", "bytes": "17831357" } ], "symlink_target": "" }
/* * external.js * Cal Evans <cal@calevans.com> * (c) Evans Internet Construction Company, Inc. * Released under the MIT license * Load external files into a reveal.js presentation. * * This is a reveal.js plugin to load external html files. It replaces the * content of any element with a data-external="file.ext" with the contents * of file.ext. * * This started life as markdown.js. Thank you to whomever wrote it. * Small mods by JJ Merelo, github.com/JJ */ (function(){ loadExternal(); function loadExternal() { var sections = document.querySelectorAll( '[data-external]'); for( var i = 0, len = sections.length; i < len; i++ ) { var this_section = sections[i]; if( this_section.getAttribute( 'data-external' ).length ) { var xhr = new XMLHttpRequest(), url = this_section.getAttribute( 'data-external' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { // file protocol yields status code 0 (useful for local debug, mobile applications etc.) if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) { this_section.innerHTML = xhr.responseText; } else { this_section.innerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } } return; } })();
{ "content_hash": "41500725610bf79216b05a37cd7e8630", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 164, "avg_line_length": 28.014285714285716, "alnum_prop": 0.6134625191228965, "repo_name": "angular-moon/fed-upgrade-ppt-2017", "id": "3de9ff26ad065dbc1ebd62c12b8ab414076fd693", "size": "1961", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "plugin/external/external.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "197714" }, { "name": "HTML", "bytes": "125959" }, { "name": "JavaScript", "bytes": "275495" } ], "symlink_target": "" }
package com.ilivoo.common.resource.core.definition; import java.util.ArrayList; import java.util.List; public class ExcelDefinition extends ResourceDefinition{ private List<String> readedSheet = new ArrayList<String>(); public ExcelDefinition(Class<?> clz, String path){ super(clz, path, ResourceType.EXCEL); } public void addSheet(String sheetName){ readedSheet.add(sheetName); } public boolean hasReaded(String sheetName){ return readedSheet.contains(sheetName); } public List<String> getReadSheet() { return readedSheet; } public void setReadSheet(List<String> readSheet) { this.readedSheet = readSheet; } }
{ "content_hash": "d4b382712cca1765a200bcffb73c8d3a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 63, "avg_line_length": 25.75, "alnum_prop": 0.6754507628294036, "repo_name": "ilivoo/ilivoo", "id": "4817a40e8e8a923e7b6e4bda72f7e868afb9d58e", "size": "721", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "resource/src/main/java/com/ilivoo/common/resource/core/definition/ExcelDefinition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9273" }, { "name": "HTML", "bytes": "33783" }, { "name": "Java", "bytes": "8744908" }, { "name": "JavaScript", "bytes": "19" }, { "name": "Roff", "bytes": "370" } ], "symlink_target": "" }
Allow configuration mapping to code usages. Simplify configuration use and different formats.
{ "content_hash": "e6a59a16edb2918a23c7215dfec4a78c", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 93, "avg_line_length": 94, "alnum_prop": 0.851063829787234, "repo_name": "perfill/mechmeta", "id": "7432ee6da55598a9912f932d7cce2d1a0333ad01", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "5829" } ], "symlink_target": "" }
package controllers import org.scalatest.{BeforeAndAfterAll, MustMatchers, WordSpec} import org.scalatestplus.play.guice.GuiceOneAppPerTest import org.slf4j.LoggerFactory import play.api.test.Helpers._ import play.api.test._ /** * Run functional tests using WithApplication */ class HomeControllerSpec extends WordSpec with GuiceOneAppPerTest with MustMatchers with BeforeAndAfterAll { private val logger = LoggerFactory.getLogger("embedded-cassandra") override protected def beforeAll(): Unit = { EmbeddedCassandra.start(logger) } override protected def afterAll(): Unit = { EmbeddedCassandra.cleanup(logger) } "Application" should { "render the index page" in { val result = route(app, FakeRequest(GET, "/")).get status(result) must equal(OK) contentAsString(result) must include("Spring Bud") } } }
{ "content_hash": "c30dcbc348bd4fc7a0b201d2a077c4b1", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 108, "avg_line_length": 26.060606060606062, "alnum_prop": 0.7418604651162791, "repo_name": "websudos/phantom-activator-template", "id": "137cc401e3b4c140ee28def578adbbde69bd7d28", "size": "860", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/controllers/HomeControllerSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "673" }, { "name": "JavaScript", "bytes": "88" }, { "name": "Scala", "bytes": "6190" } ], "symlink_target": "" }
// // MAManifestEditor.m // MunkiAdmin // // Created by Hannes Juutilainen on 20.3.2015. // // #import "MAManifestEditor.h" #import "DataModelHeaders.h" #import "MASelectManifestItemsWindow.h" #import "MASelectPkginfoItemsWindow.h" #import "MAPredicateEditor.h" #import "MAMunkiAdmin_AppDelegate.h" #import "MAManifestsView.h" #import "MARequestStringValueController.h" #import "MAMunkiRepositoryManager.h" #import "CocoaLumberjack.h" DDLogLevel ddLogLevel; NSString *MAConditionalItemType = @"ConditionalItemType"; #pragma mark - #pragma mark MAManifestEditorSection @interface MAManifestEditorSection : NSObject typedef NS_ENUM(NSInteger, MAEditorSectionTag) { MAEditorSectionTagGeneral, MAEditorSectionTagManagedInstalls, MAEditorSectionTagManagedUninstalls, MAEditorSectionTagManagedUpdates, MAEditorSectionTagOptionalInstalls, MAEditorSectionTagFeaturedItems, MAEditorSectionTagIncludedManifests, MAEditorSectionTagReferencingManifests, MAEditorSectionTagConditions }; @property (strong) NSString *title; @property (strong) NSString *subtitle; @property (strong) NSImage *icon; @property (strong) NSString *identifier; @property NSInteger tag; @property (assign) NSView *view; @end @implementation MAManifestEditorSection @end #pragma mark - #pragma mark ItemCellView @interface ItemCellView : NSTableCellView @property (nonatomic, retain) IBOutlet NSTextField *detailTextField; @property (nonatomic, retain) IBOutlet NSPopUpButton *popupButton; @end @implementation ItemCellView @synthesize detailTextField = _detailTextField; @synthesize popupButton = _popupButton; - (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle { //NSColor *textColor = (backgroundStyle == NSBackgroundStyleDark) ? [NSColor selectedTextColor] : [NSColor secondaryLabelColor]; //self.detailTextField.textColor = textColor; [super setBackgroundStyle:backgroundStyle]; } @end #pragma mark - #pragma mark MAManifestEditor @interface MAManifestEditor () @property (assign) NSView *currentDetailView; @end @implementation MAManifestEditor - (void)windowDidLoad { [super windowDidLoad]; [self.adminNotesTextView setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]]; NSSortDescriptor *sortByCatalogTitle = [NSSortDescriptor sortDescriptorWithKey:@"catalog.title" ascending:YES selector:@selector(localizedStandardCompare:)]; NSSortDescriptor *sortByIndexInManifest = [NSSortDescriptor sortDescriptorWithKey:@"indexInManifest" ascending:YES selector:@selector(compare:)]; self.catalogInfosArrayController.sortDescriptors = @[sortByIndexInManifest, sortByCatalogTitle]; NSSortDescriptor *sortByCondition = [NSSortDescriptor sortDescriptorWithKey:@"munki_condition" ascending:YES selector:@selector(localizedStandardCompare:)]; NSSortDescriptor *sortByTitleWithParentTitle = [NSSortDescriptor sortDescriptorWithKey:@"titleWithParentTitle" ascending:YES selector:@selector(localizedStandardCompare:)]; [self.conditionalItemsArrayController setSortDescriptors:@[sortByTitleWithParentTitle, sortByCondition]]; NSSortDescriptor *sortByTitle = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES selector:@selector(localizedStandardCompare:)]; self.managedInstallsArrayController.sortDescriptors = @[sortByTitle]; self.managedUpdatesArrayController.sortDescriptors = @[sortByTitle]; self.managedUninstallsArrayController.sortDescriptors = @[sortByTitle]; self.optionalInstallsArrayController.sortDescriptors = @[sortByTitle]; self.featuredItemsArrayController.sortDescriptors = @[sortByTitle]; self.includedManifestsArrayController.sortDescriptors = @[sortByTitle]; NSSortDescriptor *sortByReferenceTitle = [NSSortDescriptor sortDescriptorWithKey:@"manifestReference.title" ascending:YES selector:@selector(localizedStandardCompare:)]; NSSortDescriptor *sortByTitleOrDisplayName = [NSSortDescriptor sortDescriptorWithKey:@"manifestReference.titleOrDisplayName" ascending:YES selector:@selector(localizedStandardCompare:)]; self.referencingManifestsArrayController.sortDescriptors = @[sortByTitleOrDisplayName, sortByReferenceTitle]; self.referencingManifestsTableView.target = self; self.referencingManifestsTableView.doubleAction = @selector(referencingManifestDoubleClick:); self.includedManifestsTableView.target = self; self.includedManifestsTableView.doubleAction = @selector(includedManifestDoubleClick:); NSManagedObjectContext *moc = [(MAMunkiAdmin_AppDelegate *)[NSApp delegate] managedObjectContext]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ConditionalItem" inManagedObjectContext:moc]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entityDescription]; NSArray *fetchResults = [moc executeFetchRequest:fetchRequest error:nil]; self.conditionalItemsAllArrayController.content = fetchResults; [self.conditionalItemsAllArrayController setSortDescriptors:@[sortByTitleWithParentTitle, sortByCondition]]; [self.conditionsTreeController setSortDescriptors:@[sortByTitleWithParentTitle, sortByCondition]]; [self.conditionsOutlineView expandItem:nil expandChildren:YES]; self.conditionsOutlineView.target = self; self.conditionsOutlineView.doubleAction = @selector(editConditionalItemAction:); NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults boolForKey:@"showConditionsFromOtherManifests"]) { [[self.conditionsFromOtherManifestsMenuItem submenu] removeAllItems]; NSArray *distinctConditions = [[fetchResults valueForKeyPath:@"@distinctUnionOfObjects.munki_condition"] sortedArrayUsingSelector:@selector(localizedStandardCompare:)]; for (NSString *condition in distinctConditions) { NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:condition action:@selector(newConditionFromTemplate:) keyEquivalent:@""]; [[self.conditionsFromOtherManifestsMenuItem submenu] addItem:menuItem]; } } else { [self.conditionsFromOtherManifestsMenuItem setHidden:YES]; } [[self.conditionTemplatesMenuItem submenu] removeAllItems]; for (NSString *templateCondition in [defaults arrayForKey:@"templateConditionsUser"]) { NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:templateCondition action:@selector(newConditionFromTemplate:) keyEquivalent:@""]; [[self.conditionTemplatesMenuItem submenu] addItem:menuItem]; } if ([defaults boolForKey:@"showBuiltinTemplateConditions"]) { [[self.conditionTemplatesMenuItem submenu] addItem:[NSMenuItem separatorItem]]; for (NSString *templateCondition in [defaults arrayForKey:@"templateConditions"]) { NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:templateCondition action:@selector(newConditionFromTemplate:) keyEquivalent:@""]; [[self.conditionTemplatesMenuItem submenu] addItem:menuItem]; } } [self setupSourceList]; } - (void)newConditionFromTemplate:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); NSString *thePredicateString = [(NSMenuItem *)sender title]; NSArray *selectedConditionalItems = [self.conditionsTreeController selectedObjects]; ManifestMO *selectedManifest = self.manifestToEdit; NSManagedObjectContext *moc = self.manifestToEdit.managedObjectContext; if ([selectedConditionalItems count] == 0) { ConditionalItemMO *newConditionalItem = [NSEntityDescription insertNewObjectForEntityForName:@"ConditionalItem" inManagedObjectContext:moc]; newConditionalItem.munki_condition = thePredicateString; [self.manifestToEdit addConditionalItemsObject:newConditionalItem]; } else { for (id selectedConditionalItem in selectedConditionalItems) { ConditionalItemMO *newConditionalItem = [NSEntityDescription insertNewObjectForEntityForName:@"ConditionalItem" inManagedObjectContext:moc]; newConditionalItem.munki_condition = thePredicateString; [self.manifestToEdit addConditionalItemsObject:newConditionalItem]; newConditionalItem.parent = selectedConditionalItem; } } [moc refreshObject:selectedManifest mergeChanges:YES]; } - (void)includedManifestDoubleClick:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); for (StringObjectMO *clickedObject in self.includedManifestsArrayController.selectedObjects) { ManifestMO *manifest; if (clickedObject.originalManifest) { //DDLogError(@"Double clicked: %@", [clickedObject.originalManifest description]); manifest = clickedObject.originalManifest; MAManifestEditor *editor = [self.delegate editorForManifest:manifest]; [editor showWindow:nil]; } else { DDLogError(@"Double clicked object has no originalManifest reference"); DDLogError(@"%@", [clickedObject description]); } } } - (void)referencingManifestDoubleClick:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); for (StringObjectMO *clickedObject in self.referencingManifestsArrayController.selectedObjects) { ManifestMO *manifest; if (clickedObject.manifestReference) { //DDLogError(@"Double clicked: %@", [clickedObject.manifestReference description]); manifest = clickedObject.manifestReference; } else { //DDLogError(@"Double clicked: %@", [clickedObject.includedManifestConditionalReference.manifest description]); manifest = clickedObject.includedManifestConditionalReference.manifest; } MAManifestEditor *editor = [self.delegate editorForManifest:manifest]; [editor showWindow:nil]; } } - (void)awakeFromNib { /* Setup the main window */ //[self.window setBackgroundColor:[NSColor whiteColor]]; [self.window bind:@"title" toObject:self withKeyPath:@"manifestToEdit.title" options:nil]; self.currentDetailView = self.generalView; [self.catalogInfosTableView registerForDraggedTypes:@[NSURLPboardType]]; [self.catalogInfosTableView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:NO]; [self.conditionsOutlineView registerForDraggedTypes:@[MAConditionalItemType]]; [self.conditionsOutlineView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:YES]; self.addItemsWindowController = [[MASelectPkginfoItemsWindow alloc] initWithWindowNibName:@"MASelectPkginfoItemsWindow"]; self.selectManifestsWindowController = [[MASelectManifestItemsWindow alloc] initWithWindowNibName:@"MASelectManifestItemsWindow"]; self.predicateEditor = [[MAPredicateEditor alloc] initWithWindowNibName:@"MAPredicateEditor"]; self.requestStringValue = [[MARequestStringValueController alloc] initWithWindowNibName:@"MARequestStringValueController"]; } - (IBAction)addNewReferencingManifestAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); if ([NSWindow instancesRespondToSelector:@selector(beginSheet:completionHandler:)]) { [self.window beginSheet:[self.selectManifestsWindowController window] completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSModalResponseOK) { [self processAddItemsAction]; } }]; } else { [self.window beginSheet:[self.selectManifestsWindowController window] completionHandler:^(NSModalResponse returnCode) { [self addNewItemSheetDidEnd:[self.selectManifestsWindowController window] returnCode:returnCode contextInfo:nil]; }]; } NSMutableArray *tempPredicates = [[NSMutableArray alloc] init]; for (StringObjectMO *referencingManifest in self.manifestToEdit.referencingManifests) { NSPredicate *newPredicate; if (referencingManifest.manifestReference) { newPredicate = [NSPredicate predicateWithFormat:@"title != %@", referencingManifest.manifestReference.title]; } else { newPredicate = [NSPredicate predicateWithFormat:@"title != %@", referencingManifest.includedManifestConditionalReference.manifest.title]; } [tempPredicates addObject:newPredicate]; } NSPredicate *denySelfPred = [NSPredicate predicateWithFormat:@"title != %@", self.manifestToEdit.title]; [tempPredicates addObject:denySelfPred]; NSPredicate *compPred = [NSCompoundPredicate andPredicateWithSubpredicates:tempPredicates]; [self.selectManifestsWindowController setOriginalPredicate:compPred]; [self.selectManifestsWindowController updateSearchPredicate]; } - (IBAction)addNewIncludedManifestAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); if ([NSWindow instancesRespondToSelector:@selector(beginSheet:completionHandler:)]) { [self.window beginSheet:[self.selectManifestsWindowController window] completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSModalResponseOK) { [self processAddItemsAction]; } }]; } else { [self.window beginSheet:[self.selectManifestsWindowController window] completionHandler:^(NSModalResponse returnCode) { [self addNewItemSheetDidEnd:[self.selectManifestsWindowController window] returnCode:returnCode contextInfo:nil]; }]; } ManifestMO *selectedManifest = self.manifestToEdit; NSMutableArray *tempPredicates = [[NSMutableArray alloc] init]; for (StringObjectMO *aNestedManifest in selectedManifest.includedManifestsFaster) { NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"title != %@", aNestedManifest.title]; [tempPredicates addObject:newPredicate]; } for (ConditionalItemMO *conditional in selectedManifest.conditionalItems) { for (StringObjectMO *aNestedManifest in conditional.includedManifests) { NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"title != %@", aNestedManifest.title]; [tempPredicates addObject:newPredicate]; } } NSPredicate *denySelfPred = [NSPredicate predicateWithFormat:@"title != %@", selectedManifest.title]; [tempPredicates addObject:denySelfPred]; NSPredicate *compPred = [NSCompoundPredicate andPredicateWithSubpredicates:tempPredicates]; [self.selectManifestsWindowController setOriginalPredicate:compPred]; [self.selectManifestsWindowController updateSearchPredicate]; } - (void)processAddItemsAction { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); NSArray *selectedItems = [self.addItemsWindowController selectionAsStringObjects]; MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; switch (selected.tag) { case MAEditorSectionTagManagedInstalls: for (StringObjectMO *selectedItem in selectedItems) { [self.manifestToEdit addManagedInstallsFasterObject:selectedItem]; } break; case MAEditorSectionTagManagedUninstalls: for (StringObjectMO *selectedItem in selectedItems) { [self.manifestToEdit addManagedUninstallsFasterObject:selectedItem]; } break; case MAEditorSectionTagManagedUpdates: for (StringObjectMO *selectedItem in selectedItems) { [self.manifestToEdit addManagedUpdatesFasterObject:selectedItem]; } break; case MAEditorSectionTagOptionalInstalls: for (StringObjectMO *selectedItem in selectedItems) { [self.manifestToEdit addOptionalInstallsFasterObject:selectedItem]; } break; case MAEditorSectionTagFeaturedItems: for (StringObjectMO *selectedItem in selectedItems) { [self.manifestToEdit addFeaturedItemsObject:selectedItem]; } break; case MAEditorSectionTagIncludedManifests: for (ManifestMO *manifestToAdd in [self.selectManifestsWindowController.manifestsArrayController selectedObjects]) { StringObjectMO *manifestToAddAsStringObject = [NSEntityDescription insertNewObjectForEntityForName:@"StringObject" inManagedObjectContext:manifestToAdd.managedObjectContext]; manifestToAddAsStringObject.title = manifestToAdd.title; manifestToAddAsStringObject.typeString = @"includedManifest"; manifestToAddAsStringObject.originalIndex = [NSNumber numberWithUnsignedInteger:999]; manifestToAddAsStringObject.indexInNestedManifest = [NSNumber numberWithUnsignedInteger:999]; manifestToAddAsStringObject.originalManifest = manifestToAdd; [self.manifestToEdit addIncludedManifestsFasterObject:manifestToAddAsStringObject]; [self.manifestToEdit.managedObjectContext refreshObject:manifestToAdd mergeChanges:YES]; } break; case MAEditorSectionTagReferencingManifests: for (ManifestMO *aManifest in [self.selectManifestsWindowController.manifestsArrayController selectedObjects]) { StringObjectMO *manifestToEditAsStringObject = [NSEntityDescription insertNewObjectForEntityForName:@"StringObject" inManagedObjectContext:aManifest.managedObjectContext]; manifestToEditAsStringObject.title = self.manifestToEdit.title; manifestToEditAsStringObject.typeString = @"includedManifest"; manifestToEditAsStringObject.originalIndex = [NSNumber numberWithUnsignedInteger:999]; manifestToEditAsStringObject.indexInNestedManifest = [NSNumber numberWithUnsignedInteger:999]; manifestToEditAsStringObject.originalManifest = self.manifestToEdit; [aManifest addIncludedManifestsFasterObject:manifestToEditAsStringObject]; [self.manifestToEdit.managedObjectContext refreshObject:aManifest mergeChanges:YES]; } break; default: DDLogError(@"processAddItemsAction: tag %ld not handled...", (long)selected.tag); break; } // Need to refresh fetched properties [self.manifestToEdit.managedObjectContext refreshObject:self.manifestToEdit mergeChanges:YES]; } - (IBAction)removeIncludedManifestAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); ManifestMO *selectedManifest = self.manifestToEdit; for (StringObjectMO *anIncludedManifest in [self.includedManifestsArrayController selectedObjects]) { ManifestMO *originalManifest = anIncludedManifest.originalManifest; [self.manifestToEdit.managedObjectContext deleteObject:anIncludedManifest]; [self.manifestToEdit.managedObjectContext refreshObject:originalManifest mergeChanges:YES]; } [self.manifestToEdit.managedObjectContext refreshObject:selectedManifest mergeChanges:YES]; } - (void)addNewItemSheetDidEnd:(NSWindow *)sheet returnCode:(NSModalResponse)returnCode contextInfo:(void *)contextInfo { DDLogError(@"%@", NSStringFromSelector(_cmd)); if (returnCode == NSModalResponseCancel) return; [self processAddItemsAction]; } - (IBAction)addNewItemsAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); if ([[self.editorSectionsArrayController selectedObjects] count] == 0) { return; } /* Figure out what kind of items we're adding */ MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; NSSet *existingObjects = nil; NSSet *conditionalObjects = nil; switch (selected.tag) { case MAEditorSectionTagManagedInstalls: existingObjects = self.manifestToEdit.managedInstallsFaster; conditionalObjects = [self.manifestToEdit.conditionalItems valueForKeyPath:@"@distinctUnionOfSets.managedInstalls"]; break; case MAEditorSectionTagManagedUninstalls: existingObjects = self.manifestToEdit.managedUninstallsFaster; conditionalObjects = [self.manifestToEdit.conditionalItems valueForKeyPath:@"@distinctUnionOfSets.managedUninstalls"]; break; case MAEditorSectionTagManagedUpdates: existingObjects = self.manifestToEdit.managedUpdatesFaster; conditionalObjects = [self.manifestToEdit.conditionalItems valueForKeyPath:@"@distinctUnionOfSets.managedUpdates"]; break; case MAEditorSectionTagOptionalInstalls: existingObjects = self.manifestToEdit.optionalInstallsFaster; conditionalObjects = [self.manifestToEdit.conditionalItems valueForKeyPath:@"@distinctUnionOfSets.optionalInstalls"]; break; case MAEditorSectionTagFeaturedItems: existingObjects = self.manifestToEdit.featuredItems; conditionalObjects = [self.manifestToEdit.conditionalItems valueForKeyPath:@"@distinctUnionOfSets.featuredItems"]; break; default: DDLogError(@"addNewItemsAction: tag %ld not handled...", (long)selected.tag); break; } NSMutableArray *tempPredicates = [[NSMutableArray alloc] init]; for (StringObjectMO *object in existingObjects) { NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"munki_name != %@", object.title]; [tempPredicates addObject:newPredicate]; } for (StringObjectMO *object in conditionalObjects) { NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"munki_name != %@", object.title]; [tempPredicates addObject:newPredicate]; } NSPredicate *compPred = [NSCompoundPredicate andPredicateWithSubpredicates:tempPredicates]; [self.addItemsWindowController setHideAddedPredicate:compPred]; [self.addItemsWindowController updateGroupedSearchPredicate]; [self.addItemsWindowController updateIndividualSearchPredicate]; if ([NSWindow instancesRespondToSelector:@selector(beginSheet:completionHandler:)]) { [self.window beginSheet:[self.addItemsWindowController window] completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSModalResponseOK) { [self processAddItemsAction]; } }]; } else { [self.window beginSheet:[self.addItemsWindowController window] completionHandler:^(NSModalResponse returnCode) { [self addNewItemSheetDidEnd:[self.addItemsWindowController window] returnCode:returnCode contextInfo:nil]; }]; } } - (IBAction)removeItemsAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; switch (selected.tag) { case MAEditorSectionTagManagedInstalls: for (StringObjectMO *selectedItem in [self.managedInstallsArrayController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; } break; case MAEditorSectionTagManagedUninstalls: for (StringObjectMO *selectedItem in [self.managedUninstallsArrayController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; } break; case MAEditorSectionTagManagedUpdates: for (StringObjectMO *selectedItem in [self.managedUpdatesArrayController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; } break; case MAEditorSectionTagOptionalInstalls: for (StringObjectMO *selectedItem in [self.optionalInstallsArrayController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; } break; case MAEditorSectionTagFeaturedItems: for (StringObjectMO *selectedItem in [self.featuredItemsArrayController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; } break; case MAEditorSectionTagReferencingManifests: for (StringObjectMO *selectedItem in [self.referencingManifestsArrayController selectedObjects]) { ManifestMO *originalManifest; if (selectedItem.manifestReference) { originalManifest = selectedItem.manifestReference; } else { originalManifest = selectedItem.includedManifestConditionalReference.manifest; } [self.manifestToEdit.managedObjectContext deleteObject:selectedItem]; [self.manifestToEdit.managedObjectContext refreshObject:originalManifest mergeChanges:YES]; } break; default: DDLogError(@"removeItemsAction: tag %ld not handled...", (long)selected.tag); break; } [self.manifestToEdit.managedObjectContext refreshObject:self.manifestToEdit mergeChanges:YES]; } - (void)newPredicateSheetDidEnd:(id)sheet returnCode:(NSModalResponse)returnCode object:(id)object { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); if (returnCode == NSModalResponseCancel) return; NSString *thePredicateString = nil; if ([self.predicateEditor.tabView selectedTabViewItem] == self.predicateEditor.predicateEditorTabViewItem) { thePredicateString = [self.predicateEditor.predicateEditor.objectValue description]; } else { thePredicateString = [self.predicateEditor.customTextField stringValue]; } NSArray *selectedConditionalItems = [self.conditionsTreeController selectedObjects]; ManifestMO *selectedManifest = self.manifestToEdit; NSManagedObjectContext *moc = self.manifestToEdit.managedObjectContext; if ([selectedConditionalItems count] == 0) { ConditionalItemMO *newConditionalItem = [NSEntityDescription insertNewObjectForEntityForName:@"ConditionalItem" inManagedObjectContext:moc]; newConditionalItem.munki_condition = thePredicateString; [self.manifestToEdit addConditionalItemsObject:newConditionalItem]; } else { for (id selectedConditionalItem in selectedConditionalItems) { ConditionalItemMO *newConditionalItem = [NSEntityDescription insertNewObjectForEntityForName:@"ConditionalItem" inManagedObjectContext:moc]; newConditionalItem.munki_condition = thePredicateString; [self.manifestToEdit addConditionalItemsObject:newConditionalItem]; newConditionalItem.parent = selectedConditionalItem; } } [moc refreshObject:selectedManifest mergeChanges:YES]; } - (void)editPredicateSheetDidEnd:(id)sheet returnCode:(NSModalResponse)returnCode object:(id)object { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); if (returnCode == NSModalResponseCancel) return; NSString *thePredicateString = nil; if ([self.predicateEditor.tabView selectedTabViewItem] == self.predicateEditor.predicateEditorTabViewItem) { thePredicateString = [self.predicateEditor.predicateEditor.objectValue description]; } else { thePredicateString = [self.predicateEditor.customTextField stringValue]; } NSManagedObjectContext *moc = self.manifestToEdit.managedObjectContext; self.predicateEditor.conditionToEdit.munki_condition = thePredicateString; [moc refreshObject:self.manifestToEdit mergeChanges:YES]; } - (IBAction)addNewConditionalItemAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); [self.window beginSheet:[self.predicateEditor window] completionHandler:^(NSModalResponse returnCode) { [self newPredicateSheetDidEnd:self.predicateEditor returnCode:returnCode object:nil]; }]; self.predicateEditor.conditionToEdit = nil; [self.predicateEditor resetPredicateToDefault]; } - (IBAction)editConditionalItemAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); ConditionalItemMO *selectedCondition = [[self.conditionsTreeController selectedObjects] lastObject]; @try { NSPredicate *predicateToEdit = [NSPredicate predicateWithFormat:selectedCondition.munki_condition]; if (predicateToEdit != nil) { [self.window beginSheet:[self.predicateEditor window] completionHandler:^(NSModalResponse returnCode) { [self editPredicateSheetDidEnd:self.predicateEditor returnCode:returnCode object:nil]; }]; self.predicateEditor.conditionToEdit = selectedCondition; self.predicateEditor.customPredicateString = selectedCondition.munki_condition; self.predicateEditor.predicateEditor.objectValue = [NSPredicate predicateWithFormat:selectedCondition.munki_condition]; } } @catch (NSException *exception) { DDLogError(@"Caught exception while trying to open predicate editor. This usually means that the predicate is valid but the editor can not edit it. Showing the text field editor instead..."); [self.window beginSheet:[self.predicateEditor window] completionHandler:^(NSModalResponse returnCode) { [self editPredicateSheetDidEnd:self.predicateEditor returnCode:returnCode object:nil]; }]; [self.predicateEditor resetPredicateToDefault]; self.predicateEditor.conditionToEdit = selectedCondition; self.predicateEditor.customPredicateString = selectedCondition.munki_condition; [self.predicateEditor.tabView selectTabViewItemAtIndex:1]; } @finally { } } - (IBAction)removeConditionalItemAction:(id)sender { DDLogVerbose(@"%@", NSStringFromSelector(_cmd)); ManifestMO *selectedManifest = self.manifestToEdit; for (ConditionalItemMO *aConditionalItem in [self.conditionsTreeController selectedObjects]) { [self.manifestToEdit.managedObjectContext deleteObject:aConditionalItem]; } [self.manifestToEdit.managedObjectContext refreshObject:selectedManifest mergeChanges:YES]; } - (IBAction)renameManifestAction:(id)sender { /* Get the manifest item that was right-clicked */ DDLogVerbose(@"%s", __PRETTY_FUNCTION__); ManifestMO *selectedManifest = self.manifestToEdit; NSString *originalFilename = [selectedManifest.manifestURL lastPathComponent]; /* Ask for a new title */ [self.requestStringValue setDefaultValues]; self.requestStringValue.windowTitleText = @""; self.requestStringValue.titleText = [NSString stringWithFormat:@"Rename \"%@\"?", originalFilename]; self.requestStringValue.okButtonTitle = @"Rename"; self.requestStringValue.labelText = @"New Name:"; self.requestStringValue.descriptionText = [NSString stringWithFormat:@"Enter a new name for the manifest \"%@\".", originalFilename]; self.requestStringValue.stringValue = originalFilename; NSWindow *window = [self.requestStringValue window]; NSInteger result = [NSApp runModalForWindow:window]; /* Perform the actual rename */ if (result == NSModalResponseOK) { MAMunkiRepositoryManager *repoManager = [MAMunkiRepositoryManager sharedManager]; NSString *newTitle = self.requestStringValue.stringValue; if (![originalFilename isEqualToString:newTitle]) { NSURL *newURL = [selectedManifest.manifestParentDirectoryURL URLByAppendingPathComponent:newTitle]; [repoManager moveManifest:selectedManifest toURL:newURL cascade:YES]; } else { DDLogError(@"Old name and new name are the same. Skipping rename..."); } } [self.manifestToEdit.managedObjectContext refreshObject:selectedManifest mergeChanges:YES]; [self.requestStringValue setDefaultValues]; } - (void)setupSourceList { NSView *sourceListView = self.sourceListView; [sourceListView setIdentifier:@"sourceListView"]; //[sourceListView setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)]; [sourceListView setTranslatesAutoresizingMaskIntoConstraints:NO]; [sourceListView setAutoresizesSubviews:YES]; [self.sourceListPlaceHolder addSubview:sourceListView]; NSDictionary *views = NSDictionaryOfVariableBindings(sourceListView); [self.sourceListPlaceHolder addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[sourceListView(>=100)]|" options:NSLayoutFormatAlignAllTop metrics:nil views:views]]; [self.sourceListPlaceHolder addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[sourceListView(>=100)]|" options:NSLayoutFormatAlignAllLeading metrics:nil views:views]]; /* Create source list items */ NSDictionary *bindOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSContinuouslyUpdatesValueBindingOption, nil]; NSMutableArray *newSourceListItems = [NSMutableArray new]; NSImage *generalIcon; if (@available(macOS 11.0, *)) { generalIcon = [NSImage imageWithSystemSymbolName:@"doc.text" accessibilityDescription:@"Doc icon"]; } else { generalIcon = [NSImage imageNamed:@"doc.text"]; [generalIcon setTemplate:YES]; } NSImage *managedInstallsIcon; if (@available(macOS 11.0, *)) { managedInstallsIcon = [NSImage imageWithSystemSymbolName:@"lock.doc" accessibilityDescription:@"Lock icon"]; } else { managedInstallsIcon = [NSImage imageNamed:@"lock.doc"]; [managedInstallsIcon setTemplate:YES]; } NSImage *managedUninstallsIcon; if (@available(macOS 11.0, *)) { managedUninstallsIcon = [NSImage imageWithSystemSymbolName:@"arrow.up.doc" accessibilityDescription:@"Arrow up icon"]; } else { managedUninstallsIcon = [NSImage imageNamed:@"arrow.up.doc"]; [managedUninstallsIcon setTemplate:YES]; } NSImage *managedUpdatesIcon; if (@available(macOS 11.0, *)) { managedUpdatesIcon = [NSImage imageWithSystemSymbolName:@"arrow.down.doc" accessibilityDescription:@"Arrow down icon"]; } else { managedUpdatesIcon = [NSImage imageNamed:@"arrow.down.doc"]; [managedUpdatesIcon setTemplate:YES]; } NSImage *optionalInstallsIcon; if (@available(macOS 11.0, *)) { optionalInstallsIcon = [NSImage imageWithSystemSymbolName:@"cart" accessibilityDescription:@"Cart icon"]; } else { optionalInstallsIcon = [NSImage imageNamed:@"cart"]; [optionalInstallsIcon setTemplate:YES]; } NSImage *featuredItemsIcon; if (@available(macOS 11.0, *)) { featuredItemsIcon = [NSImage imageWithSystemSymbolName:@"star" accessibilityDescription:@"Star icon"]; } else { featuredItemsIcon = [NSImage imageNamed:@"star"]; [featuredItemsIcon setTemplate:YES]; } NSImage *includedManifestsIcon; if (@available(macOS 11.0, *)) { includedManifestsIcon = [NSImage imageWithSystemSymbolName:@"doc.on.doc" accessibilityDescription:@"Doc icon"]; } else { includedManifestsIcon = [NSImage imageNamed:@"doc.on.doc"]; [includedManifestsIcon setTemplate:YES]; } NSImage *referencingManifestsIcon; if (@available(macOS 11.0, *)) { referencingManifestsIcon = [NSImage imageWithSystemSymbolName:@"doc.on.doc" accessibilityDescription:@"Doc icon"]; } else { referencingManifestsIcon = [NSImage imageNamed:@"doc.on.doc"]; [referencingManifestsIcon setTemplate:YES]; } NSImage *conditionsIcon; if (@available(macOS 11.0, *)) { conditionsIcon = [NSImage imageWithSystemSymbolName:@"arrow.triangle.branch" accessibilityDescription:@"Branch icon"]; } else { conditionsIcon = [NSImage imageNamed:@"arrow.triangle.branch"]; [conditionsIcon setTemplate:YES]; } MAManifestEditorSection *generalSection = [MAManifestEditorSection new]; generalSection.title = @"General"; generalSection.tag = MAEditorSectionTagGeneral; generalSection.icon = generalIcon; [generalSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.catalogsCountDescriptionString" options:bindOptions]; generalSection.view = self.generalView; [newSourceListItems addObject:generalSection]; /* MAManifestEditorSection *combinedSection = [MAManifestEditorSection new]; combinedSection.title = @"Combined"; combinedSection.icon = [NSImage imageNamed:NSImageNamePreferencesGeneral]; [newSourceListItems addObject:combinedSection]; */ MAManifestEditorSection *managedInstallsSection = [MAManifestEditorSection new]; managedInstallsSection.title = @"Managed Installs"; managedInstallsSection.tag = MAEditorSectionTagManagedInstalls; managedInstallsSection.icon = managedInstallsIcon; [managedInstallsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.managedInstallsCountDescription" options:bindOptions]; managedInstallsSection.view = self.contentItemsListView; [newSourceListItems addObject:managedInstallsSection]; MAManifestEditorSection *managedUninstallsSection = [MAManifestEditorSection new]; managedUninstallsSection.title = @"Managed Uninstalls"; managedUninstallsSection.tag = MAEditorSectionTagManagedUninstalls; managedUninstallsSection.icon = managedUninstallsIcon; [managedUninstallsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.managedUninstallsCountDescription" options:bindOptions]; managedUninstallsSection.view = self.contentItemsListView; [newSourceListItems addObject:managedUninstallsSection]; MAManifestEditorSection *managedUpdatesSection = [MAManifestEditorSection new]; managedUpdatesSection.title = @"Managed Updates"; managedUpdatesSection.tag = MAEditorSectionTagManagedUpdates; managedUpdatesSection.icon = managedUpdatesIcon; [managedUpdatesSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.managedUpdatesCountDescription" options:bindOptions]; managedUpdatesSection.view = self.contentItemsListView; [newSourceListItems addObject:managedUpdatesSection]; MAManifestEditorSection *optionalInstallsSection = [MAManifestEditorSection new]; optionalInstallsSection.title = @"Optional Installs"; optionalInstallsSection.tag = MAEditorSectionTagOptionalInstalls; optionalInstallsSection.icon = optionalInstallsIcon; [optionalInstallsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.optionalInstallsCountDescription" options:bindOptions]; optionalInstallsSection.view = self.contentItemsListView; [newSourceListItems addObject:optionalInstallsSection]; MAManifestEditorSection *featuredItemsSection = [MAManifestEditorSection new]; featuredItemsSection.title = @"Featured Items"; featuredItemsSection.tag = MAEditorSectionTagFeaturedItems; featuredItemsSection.icon = featuredItemsIcon; [featuredItemsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.featuredItemsCountDescription" options:bindOptions]; featuredItemsSection.view = self.contentItemsListView; [newSourceListItems addObject:featuredItemsSection]; MAManifestEditorSection *includedManifestsSection = [MAManifestEditorSection new]; includedManifestsSection.title = @"Included Manifests"; includedManifestsSection.tag = MAEditorSectionTagIncludedManifests; includedManifestsSection.icon = includedManifestsIcon; [includedManifestsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.includedManifestsCountDescription" options:bindOptions]; includedManifestsSection.view = self.includedManifestsListView; [newSourceListItems addObject:includedManifestsSection]; MAManifestEditorSection *referencingManifestsSection = [MAManifestEditorSection new]; referencingManifestsSection.title = @"Referencing Manifests"; referencingManifestsSection.tag = MAEditorSectionTagReferencingManifests; referencingManifestsSection.icon = referencingManifestsIcon; [referencingManifestsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.referencingManifestsCountDescription" options:bindOptions]; referencingManifestsSection.view = self.referencingManifestsListView; [newSourceListItems addObject:referencingManifestsSection]; MAManifestEditorSection *conditionsSection = [MAManifestEditorSection new]; conditionsSection.title = @"Conditions"; conditionsSection.tag = MAEditorSectionTagConditions; conditionsSection.icon = conditionsIcon; [conditionsSection bind:@"subtitle" toObject:self withKeyPath:@"manifestToEdit.conditionsCountDescription" options:bindOptions]; conditionsSection.view = self.conditionalsListView; [newSourceListItems addObject:conditionsSection]; self.sourceListItems = [NSArray arrayWithArray:newSourceListItems]; } - (NSTextField *)addTextFieldWithidentifier:(NSString *)identifier superView:(NSView *)superview { NSTextField *textField = [[NSTextField alloc] init]; [textField setIdentifier:identifier]; [[textField cell] setControlSize:NSControlSizeRegular]; [textField setBordered:NO]; [textField setBezeled:NO]; [textField setSelectable:YES]; [textField setEditable:NO]; [textField setFont:[NSFont systemFontOfSize:13.0]]; [textField setAutoresizingMask:NSViewMaxXMargin|NSViewMinYMargin]; [textField setTranslatesAutoresizingMaskIntoConstraints:NO]; [superview addSubview:textField]; return textField; } - (NSTextField *)addLabelFieldWithTitle:(NSString *)title identifier:(NSString *)identifier superView:(NSView *)superview { NSTextField *textField = [[NSTextField alloc] init]; [textField setIdentifier:identifier]; [textField setStringValue:title]; [[textField cell] setControlSize:NSControlSizeRegular]; [textField setAlignment:NSTextAlignmentRight]; [textField setBordered:NO]; [textField setBezeled:NO]; [textField setSelectable:NO]; [textField setEditable:NO]; [textField setDrawsBackground:NO]; [textField setFont:[NSFont boldSystemFontOfSize:13.0]]; [textField setAutoresizingMask:NSViewMaxXMargin|NSViewMinYMargin]; [textField setTranslatesAutoresizingMaskIntoConstraints:NO]; [superview addSubview:textField]; return textField; } - (void)setupProductInfoView:(NSView *)parentView { } #pragma mark - #pragma mark NSTableView Delegate - (id<NSPasteboardWriting>)tableView:(NSTableView *)tableView pasteboardWriterForRow:(NSInteger)row { if (tableView == self.catalogInfosTableView) { CatalogInfoMO *aCatalogInfo = [[self.catalogInfosArrayController arrangedObjects] objectAtIndex:(NSUInteger)row]; NSURL *objectURL = [[aCatalogInfo objectID] URIRepresentation]; return objectURL; } else { return nil; } } - (NSDragOperation)tableView:(NSTableView*)theTableView validateDrop:(id <NSDraggingInfo>)theDraggingInfo proposedRow:(NSInteger)theRow proposedDropOperation:(NSTableViewDropOperation)theDropOperation { NSDragOperation result = NSDragOperationNone; if (theTableView == self.catalogInfosTableView) { if (theDropOperation == NSTableViewDropAbove) { result = NSDragOperationMove; } } return result; } - (void)makeRoomForCatalogsAtIndex:(NSInteger)index { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"indexInManifest >= %@", [NSNumber numberWithInteger:index]]; for (CatalogInfoMO *catalogInfo in [self.manifestToEdit.catalogInfos filteredSetUsingPredicate:predicate]) { NSInteger currentIndex = [catalogInfo.indexInManifest integerValue]; catalogInfo.indexInManifest = [NSNumber numberWithInteger:currentIndex + 1]; } } - (void)renumberCatalogItems { NSInteger index = 0; for (CatalogInfoMO *aCatalogInfo in [self.catalogInfosArrayController arrangedObjects]) { aCatalogInfo.indexInManifest = [NSNumber numberWithInteger:index]; index++; } } - (BOOL)tableView:(NSTableView *)theTableView acceptDrop:(id <NSDraggingInfo>)draggingInfo row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation { NSPasteboard *draggingPasteboard = [draggingInfo draggingPasteboard]; if (theTableView == self.catalogInfosTableView) { NSArray *dragTypes = [draggingPasteboard types]; if ([dragTypes containsObject:NSURLPboardType]) { NSPasteboard *pasteboard = draggingPasteboard; NSArray *classes = @[[NSURL class]]; NSDictionary *options = @{NSPasteboardURLReadingFileURLsOnlyKey : @NO}; NSArray *urls = [pasteboard readObjectsForClasses:classes options:options]; for (NSURL *uri in urls) { NSManagedObjectContext *moc = self.manifestToEdit.managedObjectContext; NSManagedObjectID *objectID = [[moc persistentStoreCoordinator] managedObjectIDForURIRepresentation:uri]; CatalogInfoMO *mo = (CatalogInfoMO *)[moc objectRegisteredForID:objectID]; [self makeRoomForCatalogsAtIndex:row]; mo.indexInManifest = @(row); } } [self renumberCatalogItems]; return YES; } else { return NO; } } - (void)setContentView:(NSView *)newContentView { for (id view in [self.contentViewPlaceHolder subviews]) { [view removeFromSuperview]; } [self.contentViewPlaceHolder addSubview:newContentView]; [newContentView setFrame:[self.contentViewPlaceHolder frame]]; // make sure our added subview is placed and resizes correctly [newContentView setFrameOrigin:NSMakePoint(0,0)]; [newContentView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [newContentView setTranslatesAutoresizingMaskIntoConstraints:YES]; [newContentView setAutoresizesSubviews:YES]; } - (void)tableViewSelectionDidChange:(NSNotification *)aNotification { NSTableView *tableView = [aNotification object]; if (tableView == self.sourceListTableView) { if ([[self.editorSectionsArrayController selectedObjects] count] == 0) { return; } MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; if (selected.tag == MAEditorSectionTagManagedInstalls) { [self.contentItemsTableView bind:NSContentBinding toObject:self.managedInstallsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.contentItemsTableView bind:NSSelectionIndexesBinding toObject:self.managedInstallsArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if ([selected.title isEqualToString:@"Managed Uninstalls"]) { [self.contentItemsTableView bind:NSContentBinding toObject:self.managedUninstallsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.contentItemsTableView bind:NSSelectionIndexesBinding toObject:self.managedUninstallsArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if ([selected.title isEqualToString:@"Managed Updates"]) { [self.contentItemsTableView bind:NSContentBinding toObject:self.managedUpdatesArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.contentItemsTableView bind:NSSelectionIndexesBinding toObject:self.managedUpdatesArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if ([selected.title isEqualToString:@"Optional Installs"]) { [self.contentItemsTableView bind:NSContentBinding toObject:self.optionalInstallsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.contentItemsTableView bind:NSSelectionIndexesBinding toObject:self.optionalInstallsArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if (selected.tag == MAEditorSectionTagFeaturedItems) { [self.contentItemsTableView bind:NSContentBinding toObject:self.featuredItemsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.contentItemsTableView bind:NSSelectionIndexesBinding toObject:self.featuredItemsArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if (selected.tag == MAEditorSectionTagIncludedManifests) { [self.includedManifestsTableView bind:NSContentBinding toObject:self.includedManifestsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.includedManifestsTableView bind:NSSelectionIndexesBinding toObject:self.includedManifestsArrayController withKeyPath:@"selectionIndexes" options:nil]; } else if (selected.tag == MAEditorSectionTagReferencingManifests) { [self.referencingManifestsTableView bind:NSContentBinding toObject:self.referencingManifestsArrayController withKeyPath:@"arrangedObjects" options:nil]; [self.referencingManifestsTableView bind:NSSelectionIndexesBinding toObject:self.referencingManifestsArrayController withKeyPath:@"selectionIndexes" options:nil]; } [self setContentView:selected.view]; self.currentDetailView = selected.view; } } - (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row { id view = [tableView makeViewWithIdentifier:tableColumn.identifier owner:nil]; if (tableView == self.contentItemsTableView) { /* Create the correct bindings for the condition column */ if ([tableColumn.identifier isEqualToString:@"tableColumnCondition"]) { NSDictionary *bindOptions = @{NSInsertsNullPlaceholderBindingOption: @YES, NSNullPlaceholderBindingOption: @"--"}; ItemCellView *itemCellView = (ItemCellView *)view; [itemCellView.popupButton bind:NSContentBinding toObject:self.conditionalItemsArrayController withKeyPath:@"arrangedObjects" options:bindOptions]; [itemCellView.popupButton bind:NSContentValuesBinding toObject:self.conditionalItemsArrayController withKeyPath:@"arrangedObjects.titleWithParentTitle" options:bindOptions]; MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; if ([selected.title isEqualToString:@"Managed Installs"]) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.managedInstallConditionalReference" options:nil]; } else if ([selected.title isEqualToString:@"Managed Uninstalls"]) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.managedUninstallConditionalReference" options:nil]; } else if ([selected.title isEqualToString:@"Managed Updates"]) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.managedUpdateConditionalReference" options:nil]; } else if ([selected.title isEqualToString:@"Optional Installs"]) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.optionalInstallConditionalReference" options:nil]; } else if (selected.tag == MAEditorSectionTagFeaturedItems) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.featuredItemConditionalReference" options:nil]; } else if (selected.tag == MAEditorSectionTagIncludedManifests) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.includedManifestConditionalReference" options:nil]; } } } else if (tableView == self.includedManifestsTableView) { /* Create the correct bindings for the condition column */ if ([tableColumn.identifier isEqualToString:@"tableColumnCondition"]) { NSDictionary *bindOptions = @{NSInsertsNullPlaceholderBindingOption: @YES, NSNullPlaceholderBindingOption: @"--"}; ItemCellView *itemCellView = (ItemCellView *)view; [itemCellView.popupButton bind:NSContentBinding toObject:self.conditionalItemsArrayController withKeyPath:@"arrangedObjects" options:bindOptions]; [itemCellView.popupButton bind:NSContentValuesBinding toObject:self.conditionalItemsArrayController withKeyPath:@"arrangedObjects.titleWithParentTitle" options:bindOptions]; MAManifestEditorSection *selected = [self.editorSectionsArrayController selectedObjects][0]; if (selected.tag == MAEditorSectionTagIncludedManifests) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.includedManifestConditionalReference" options:nil]; } else if (selected.tag == MAEditorSectionTagReferencingManifests) { [itemCellView.popupButton bind:NSSelectedObjectBinding toObject:itemCellView withKeyPath:@"objectValue.originalManifestConditionalReference" options:nil]; } } else if ([tableColumn.identifier isEqualToString:@"tableColumnManifestTitle"]) { NSTableCellView *tableCellView = (NSTableCellView *)view; StringObjectMO *current = [self.includedManifestsArrayController.arrangedObjects objectAtIndex:(NSUInteger)row]; //[tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.manifestTitleOrDisplayName" options:nil]; if (current.originalManifest) { [tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.originalManifest.titleOrDisplayName" options:nil]; } else { // } } } else if (tableView == self.referencingManifestsTableView) { /* Create the correct bindings for the condition column */ if ([tableColumn.identifier isEqualToString:@"tableColumnConditionTitle"]) { NSDictionary *bindOptions = @{NSInsertsNullPlaceholderBindingOption: @YES, NSNullPlaceholderBindingOption: @"--"}; NSTableCellView *tableCellView = (NSTableCellView *)view; [tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.includedManifestConditionalReference.munki_condition" options:bindOptions]; } else if ([tableColumn.identifier isEqualToString:@"tableColumnManifestTitle"]) { NSTableCellView *tableCellView = (NSTableCellView *)view; StringObjectMO *current = [self.referencingManifestsArrayController.arrangedObjects objectAtIndex:(NSUInteger)row]; //[tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.manifestTitleOrDisplayName" options:nil]; if (current.manifestReference) { [tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.manifestReference.titleOrDisplayName" options:nil]; } else { [tableCellView.textField bind:NSValueBinding toObject:tableCellView withKeyPath:@"objectValue.includedManifestConditionalReference.manifest.titleOrDisplayName" options:nil]; } } } return view; } - (void)menuWillOpen:(NSMenu *)menu { } # pragma mark - NSOutlineView delegates - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard { [pboard declareTypes:[NSArray arrayWithObject:MAConditionalItemType] owner:self]; [pboard setData:[NSKeyedArchiver archivedDataWithRootObject:[items valueForKey:@"indexPath"]] forType:MAConditionalItemType]; return YES; } - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)proposedParentItem childIndex:(NSInteger)index { NSArray *droppedIndexPaths = [NSKeyedUnarchiver unarchiveObjectWithData:[[info draggingPasteboard] dataForType:MAConditionalItemType]]; NSMutableArray *draggedNodes = [NSMutableArray array]; for (NSIndexPath *indexPath in droppedIndexPaths) { id treeRoot = [self.conditionsTreeController arrangedObjects]; NSTreeNode *node = [treeRoot descendantNodeAtIndexPath:indexPath]; [draggedNodes addObject:node]; } for (NSTreeNode *aNode in draggedNodes) { ConditionalItemMO *droppedConditional = [aNode representedObject]; NSTreeNode *parent = proposedParentItem; ConditionalItemMO *parentConditional = [parent representedObject]; if (!proposedParentItem) { droppedConditional.parent = nil; } else { droppedConditional.parent = parentConditional; } [[(MAMunkiAdmin_AppDelegate *)[NSApp delegate] managedObjectContext] refreshObject:droppedConditional.manifest mergeChanges:YES]; } [self.conditionsTreeController rearrangeObjects]; [self.conditionalItemsArrayController rearrangeObjects]; return YES; } - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index { // Deny drag and drop reordering if (index != -1) { return NSDragOperationNone; } NSArray *draggedIndexPaths = [NSKeyedUnarchiver unarchiveObjectWithData:[[info draggingPasteboard] dataForType:MAConditionalItemType]]; for (NSIndexPath *indexPath in draggedIndexPaths) { id treeRoot = [self.conditionsTreeController arrangedObjects]; NSTreeNode *node = [treeRoot descendantNodeAtIndexPath:indexPath]; ConditionalItemMO *droppedConditional = [node representedObject]; NSTreeNode *parent = item; ConditionalItemMO *parentConditional = [parent representedObject]; // Dragging a 1st level item so deny dropping to root if ((droppedConditional.parent == nil) && (parentConditional == nil)) { return NSDragOperationNone; } // Can't drop on child items while (parent != nil) { if (parent == node) { return NSDragOperationNone; } parent = [parent parentNode]; } } return NSDragOperationGeneric; } # pragma mark - NSSplitView delegates - (void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize { if (sender == self.mainSplitView) { /* Main split view Resize only the right side of the splitview */ NSView *left = [sender subviews][0]; NSView *right = [sender subviews][1]; CGFloat dividerThickness = [sender dividerThickness]; NSRect newFrame = [sender frame]; NSRect leftFrame = [left frame]; NSRect rightFrame = [right frame]; rightFrame.size.height = newFrame.size.height; rightFrame.size.width = newFrame.size.width - leftFrame.size.width - dividerThickness; rightFrame.origin = NSMakePoint(leftFrame.size.width + dividerThickness, 0); leftFrame.size.height = newFrame.size.height; leftFrame.origin.x = 0; [left setFrame:leftFrame]; [right setFrame:rightFrame]; } } @end
{ "content_hash": "fb05f285f78e0d923eb0fbbd9c942bef", "timestamp": "", "source": "github", "line_count": 1227, "max_line_length": 200, "avg_line_length": 48.972290138549305, "alnum_prop": 0.7304664747291517, "repo_name": "chrisgrande/munkiadmin", "id": "0de948d7654d5cb777428a1ba8717d4ccc6f63c4", "size": "60089", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MunkiAdmin/UI Controllers/MAManifestEditor.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1297565" }, { "name": "Python", "bytes": "6376" }, { "name": "Ruby", "bytes": "334" } ], "symlink_target": "" }
package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.io.OIOUtils; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.serialization.types.OByteSerializer; import com.orientechnologies.common.serialization.types.OIntegerSerializer; import com.orientechnologies.common.serialization.types.OLongSerializer; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OStorageConfigurationImpl; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.storage.disk.OLocalPaginatedStorage; import com.orientechnologies.orient.core.storage.fs.OFile; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.zip.CRC32; /** Handles the database configuration in one big record. */ public class OStorageConfigurationSegment extends OStorageConfigurationImpl { private static final int VERSION_OFFSET = 48; // This class uses "double write" pattern. // Whenever we want to update configuration, first we write data in backup file and make fsync. // Then we write the same data // in primary file and make fsync. Then we remove backup file. So does not matter if we have error // on any of this stages // we always will have consistent storage configuration. // Downside of this approach is the double overhead during write of configuration, but it was // chosen to keep binary compatibility // between versions. /** Name of primary file */ private static final String NAME = "database.ocf"; /** * Name of backup file which is used when we update storage configuration using double write * pattern */ private static final String BACKUP_NAME = "database.ocf2"; private static final long ENCODING_FLAG_1 = 128975354756545L; private static final long ENCODING_FLAG_2 = 587138568122547L; private static final long ENCODING_FLAG_3 = 812587836547249L; private static final int CRC_32_OFFSET = 100; private static final byte FORMAT_VERSION = (byte) 42; private final String storageName; private final Path storagePath; public OStorageConfigurationSegment(final OLocalPaginatedStorage storage) { super(storage, Charset.forName("UTF-8")); this.storageName = storage.getName(); this.storagePath = storage.getStoragePath(); } @Override public void delete() throws IOException { lock.writeLock().lock(); try { super.delete(); clearConfigurationFiles(); } finally { lock.writeLock().unlock(); } } /** * Remove both backup and primary configuration files on delete * * @see #update() */ private void clearConfigurationFiles() throws IOException { final Path file = storagePath.resolve(NAME); Files.deleteIfExists(file); final Path backupFile = storagePath.resolve(BACKUP_NAME); Files.deleteIfExists(backupFile); } @Override public void create() throws IOException { lock.writeLock().lock(); try { clearConfigurationFiles(); super.create(); } finally { lock.writeLock().unlock(); } } @Override public OStorageConfigurationImpl load(final OContextConfiguration configuration) throws OSerializationException { lock.writeLock().lock(); try { initConfiguration(configuration); final Path file = storagePath.resolve(NAME); final Path backupFile = storagePath.resolve(BACKUP_NAME); if (Files.exists(file)) { if (readData(file)) { return this; } OLogManager.instance() .warnNoDb( this, "Main storage configuration file %s is broken in storage %s, try to read from backup file %s", file, storageName, backupFile); if (Files.exists(backupFile)) { if (readData(backupFile)) { return this; } OLogManager.instance() .errorNoDb(this, "Backup configuration file %s is broken too", null); throw new OStorageException( "Invalid format for configuration file " + file + " for storage" + storageName); } else { OLogManager.instance() .errorNoDb(this, "Backup configuration file %s does not exist", null, backupFile); throw new OStorageException( "Invalid format for configuration file " + file + " for storage" + storageName); } } else if (Files.exists(backupFile)) { OLogManager.instance() .warn( this, "Seems like previous update to the storage '%s' configuration was finished incorrectly, " + "main configuration file %s is absent, reading from backup", backupFile, file); if (readData(backupFile)) { return this; } OLogManager.instance() .errorNoDb(this, "Backup configuration file %s is broken", null, backupFile); throw new OStorageException( "Invalid format for configuration file " + backupFile + " for storage" + storageName); } else { throw new OStorageException("Can not find configuration file for storage " + storageName); } } catch (IOException e) { throw OException.wrapException( new OSerializationException( "Cannot load database configuration. The database seems corrupted"), e); } finally { lock.writeLock().unlock(); } } @Override public void update() throws OSerializationException { lock.writeLock().lock(); try { final Charset utf8 = Charset.forName("UTF-8"); final byte[] buffer = toStream(utf8); final ByteBuffer byteBuffer = ByteBuffer.allocate(buffer.length + OIntegerSerializer.INT_SIZE); byteBuffer.putInt(buffer.length); byteBuffer.put(buffer); try { if (!Files.exists(storagePath)) { Files.createDirectories(storagePath); } final Path backupFile = storagePath.resolve(BACKUP_NAME); Files.deleteIfExists(backupFile); try (FileChannel channel = FileChannel.open(backupFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { writeConfigFile(buffer, byteBuffer, channel); } final Path file = storagePath.resolve(NAME); Files.deleteIfExists(file); try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { writeConfigFile(buffer, byteBuffer, channel); } Files.delete(backupFile); } catch (Exception e) { throw OException.wrapException( new OSerializationException("Error on update storage configuration"), e); } } finally { lock.writeLock().unlock(); } } private void writeConfigFile(byte[] buffer, ByteBuffer byteBuffer, FileChannel channel) throws IOException { final ByteBuffer versionBuffer = ByteBuffer.allocate(1); versionBuffer.put(FORMAT_VERSION); versionBuffer.position(0); OIOUtils.writeByteBuffer(versionBuffer, channel, VERSION_OFFSET); final ByteBuffer crc32buffer = ByteBuffer.allocate(OIntegerSerializer.INT_SIZE); final CRC32 crc32 = new CRC32(); crc32.update(buffer); crc32buffer.putInt((int) crc32.getValue()); crc32buffer.position(0); OIOUtils.writeByteBuffer(crc32buffer, channel, CRC_32_OFFSET); channel.force(true); byteBuffer.position(0); OIOUtils.writeByteBuffer(byteBuffer, channel, OFile.HEADER_SIZE); channel.force(true); } private boolean readData(Path file) throws IOException { final ByteBuffer byteBuffer; final byte fileVersion; final int crc32content; try (final FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) { // file header + size of content + at least one byte of content if (channel.size() < OFile.HEADER_SIZE + OIntegerSerializer.INT_SIZE + OByteSerializer.BYTE_SIZE) { return false; } final ByteBuffer versionBuffer = ByteBuffer.allocate(1); OIOUtils.readByteBuffer(versionBuffer, channel, VERSION_OFFSET, true); versionBuffer.position(0); fileVersion = versionBuffer.get(); if (fileVersion >= 42) { final ByteBuffer crc32buffer = ByteBuffer.allocate(OIntegerSerializer.INT_SIZE); OIOUtils.readByteBuffer(crc32buffer, channel, CRC_32_OFFSET, true); crc32buffer.position(0); crc32content = crc32buffer.getInt(); } else { crc32content = 0; } byteBuffer = ByteBuffer.allocate((int) channel.size() - OFile.HEADER_SIZE); OIOUtils.readByteBuffer(byteBuffer, channel, OFile.HEADER_SIZE, true); } byteBuffer.position(0); final int size = byteBuffer.getInt(); // size of string which contains database configuration byte[] buffer = new byte[size]; byteBuffer.get(buffer); if (fileVersion < 42) { if (byteBuffer.limit() >= size + 2 * OIntegerSerializer.INT_SIZE + 3 * OLongSerializer.LONG_SIZE) { final long encodingFagOne = byteBuffer.getLong(); final long encodingFagTwo = byteBuffer.getLong(); final long encodingFagThree = byteBuffer.getLong(); final Charset streamEncoding; // those flags are added to distinguish between old version of configuration file and new // one. if (encodingFagOne == ENCODING_FLAG_1 && encodingFagTwo == ENCODING_FLAG_2 && encodingFagThree == ENCODING_FLAG_3) { final byte[] utf8Encoded = "UTF-8".getBytes(Charset.forName("UTF-8")); final int encodingNameLength = byteBuffer.getInt(); if (encodingNameLength == utf8Encoded.length) { final byte[] binaryEncodingName = new byte[encodingNameLength]; byteBuffer.get(binaryEncodingName); final String encodingName = new String(binaryEncodingName, "UTF-8"); if (encodingName.equals("UTF-8")) { streamEncoding = Charset.forName("UTF-8"); } else { return false; } try { fromStream(buffer, 0, buffer.length, streamEncoding); } catch (Exception e) { OLogManager.instance() .errorNoDb( this, "Error during reading of configuration %s of storage %s", e, file, storageName); return false; } } else { return false; } } else { try { fromStream(buffer, 0, buffer.length, Charset.defaultCharset()); } catch (Exception e) { OLogManager.instance() .errorNoDb( this, "Error during reading of configuration %s of storage %s", e, file, storageName); return false; } } } else { try { fromStream(buffer, 0, buffer.length, Charset.defaultCharset()); } catch (Exception e) { OLogManager.instance() .errorNoDb( this, "Error during reading of configuration %s of storage %s", e, file, storageName); return false; } } } else { CRC32 crc32 = new CRC32(); crc32.update(buffer); if (crc32content != (int) crc32.getValue()) { return false; } try { fromStream(buffer, 0, buffer.length, Charset.forName("UTF-8")); } catch (Exception e) { OLogManager.instance() .errorNoDb( this, "Error during reading of configuration %s of storage %s", e, file, storageName); return false; } } return true; } }
{ "content_hash": "731f24f3829696646e3d4820de151098", "timestamp": "", "source": "github", "line_count": 372, "max_line_length": 110, "avg_line_length": 33.513440860215056, "alnum_prop": 0.6340739552418384, "repo_name": "orientechnologies/orientdb", "id": "c783d78f775b6df922ae3733fb479fe600137190", "size": "13199", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageConfigurationSegment.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "19302" }, { "name": "Dockerfile", "bytes": "705" }, { "name": "Gnuplot", "bytes": "1245" }, { "name": "Groovy", "bytes": "7913" }, { "name": "HTML", "bytes": "5750" }, { "name": "Java", "bytes": "26588383" }, { "name": "JavaScript", "bytes": "259" }, { "name": "PLpgSQL", "bytes": "54881" }, { "name": "Shell", "bytes": "33650" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Lecidea hypopta f. ruficeps Vain. ### Remarks null
{ "content_hash": "6b2c19bbfa175a21f9effcfdd4da9721", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 33, "avg_line_length": 10.615384615384615, "alnum_prop": 0.7028985507246377, "repo_name": "mdoering/backbone", "id": "92e1e2fd56c206485c4d8910784149297fe64493", "size": "204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Biatora/Biatora hypopta/Biatora hypopta ruficeps/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#if defined(__GNUC__) #warning "Inclusion of header files from include/Qt is deprecated." #elif defined(_MSC_VER) #pragma message("WARNING: Inclusion of header files from include/Qt is deprecated.") #endif #endif #include "../Qt3Support/q3sqleditorfactory.h"
{ "content_hash": "9495406a489563595a69f2a72cdebfef", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 92, "avg_line_length": 36, "alnum_prop": 0.6840277777777778, "repo_name": "kzhong1991/Flight-AR.Drone-2", "id": "4e537f517a1e2f2e0d0671887fa4bab507f890e0", "size": "318", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "src/3rdparty/Qt4.8.4/include/Qt/q3sqleditorfactory.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8366" }, { "name": "C++", "bytes": "172001" }, { "name": "Objective-C", "bytes": "7651" }, { "name": "QMake", "bytes": "1293" } ], "symlink_target": "" }
subroutine brkpt(nbrkpt,mxint) c****************************************************************** c * c This subroutine is called from SR STMGET to read in rainfall * c breakpoint data. The first column of data read in is time * c after midnight in hours(f4.2) and the second column is the * c accumulated rainfall in mm(f6.2). Irrigation is not an option * c when breakpoint input is used. * c * c****************************************************************** c * c Arguments * c nbrkpt - number of rainfall breakpoints * c mxint - maximum rainfall intensity (m/s) * c * c****************************************************************** c * c Argument Declarations * c * integer nbrkpt real mxint c****************************************************************** c * c Parameters * c mxplan : maximum number of over land flow elements * c mxtlsq : maximum number of tillage sequences * c mxtill : maximum number of tillage operations per tillage * c * c****************************************************************** c include 'pmxelm.inc' include 'pmxpln.inc' include 'pmxtil.inc' include 'pmxtls.inc' include 'pmxhil.inc' c c****************************************************************** c * c Common Blocks * c * c****************************************************************** c include 'cdiss1.inc' include 'cdiss3.inc' include 'chydrol.inc' include 'cupdate.inc' c Added by S. Dun, Feb 20, 2008 c for record storm start time for breakpoint data include 'cclim.inc' c End adding c c****************************************************************** c c c local variables c real pptcum(100), drain, dtime,pktime integer i c c read in break points and convert into seconds and meters do 10 i = 1, nbrkpt read (13,*,end=20) timem(i), pptcum(i) if (i.eq.1) stmstr = timem(1) timem(i) = (timem(i)-stmstr) * 3600. pptcum(i) = pptcum(i) / 1000. 10 continue 20 continue c stmdur = 0.0 mxint = 0.0 pktime = 0.0 c compute rainfall intensity in m/s do 30 i = 1, nbrkpt - 1 c drain = pptcum(i+1) - pptcum(i) if (drain.eq.0.0) then c c XXX Commented out following line - The time value should not be c zero according to Jeff Stone - even for periods of zero c intensity within a storm. c dtime = 0.0 dtime = timem(i+1) - timem(i) intsty(i) = 0.0 else if (drain.lt.0.0) then write (6,1000) day, mon, year stop else dtime = timem(i+1) - timem(i) if (dtime.le.0.0) then write (6,1100) day, mon, year stop end if intsty(i) = drain / dtime end if c c compute storm duration stmdur = stmdur + dtime dur = stmdur if (intsty(i).gt.mxint) then mxint = intsty(i) pktime = stmdur - dtime / 2. end if c write (6,*)timem(i)/3600.,intsty(i)*3.6e+06 30 continue c c compute normalized peak intensity and time to peak c XXX Commented out following 2 lines because these parameter values c are not needed in breakpoint simulations - and now their values c will be incorrectly estimated since STMDUR computation above c has been corrected. dcf 9/19/94 c timep = pktime / stmdur c ip = mxint / (pptcum(nbrkpt)/stmdur) c c set rainfall intensity of last interval equal to zero intsty(nbrkpt) = 0.0 prcp = pptcum(nbrkpt) p = prcp c return 1000 format (/1x,'*** Error in breakpoint input data. ***',//1x, 1 'Date of precipitation : ',i2,1x,i2,1x,i4,/,1x, 1 'The cumulative precipitation volume decreased. Check',/1x, 1 'climate input file and restart simulation.') 1100 format (/1x,'*** Error in breakpoint input data. ***',//1x, 1 'Date of precipitation : ',i2,1x,i2,1x,i4,/,1x, 1 'The breakpoint time is less than the preceeding time.',/, 1 1x,'Check climate input file and restart simulation.') end
{ "content_hash": "2f61c87e2e99f4eb5620eaca4c804502", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 69, "avg_line_length": 40.8203125, "alnum_prop": 0.4233492822966507, "repo_name": "akrherz/idep", "id": "64ae44fe2ee5d42931ca8183936a7f37d8e94598", "size": "5225", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "src/wepp2010.1/brkpt.for", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "666" }, { "name": "Assembly", "bytes": "12185" }, { "name": "C++", "bytes": "259853" }, { "name": "CSS", "bytes": "219995" }, { "name": "FORTRAN", "bytes": "4328628" }, { "name": "HTML", "bytes": "35117" }, { "name": "JavaScript", "bytes": "35179" }, { "name": "Makefile", "bytes": "101440" }, { "name": "PHP", "bytes": "31418" }, { "name": "Pascal", "bytes": "215035" }, { "name": "Prolog", "bytes": "862" }, { "name": "Python", "bytes": "154467" }, { "name": "Shell", "bytes": "1740" }, { "name": "xBase", "bytes": "22234" } ], "symlink_target": "" }
"""Implements vlans, bridges, and iptables rules using linux utilities.""" import calendar import inspect import netaddr import os from nova import db from nova import exception from nova import flags from nova.openstack.common import cfg from nova.openstack.common import importutils from nova.openstack.common import log as logging from nova import utils LOG = logging.getLogger(__name__) linux_net_opts = [ cfg.StrOpt('dhcpbridge_flagfile', default='/etc/nova/nova-dhcpbridge.conf', help='location of flagfile for dhcpbridge'), cfg.StrOpt('networks_path', default='$state_path/networks', help='Location to keep network config files'), cfg.StrOpt('public_interface', default='eth0', help='Interface for public IP addresses'), cfg.StrOpt('network_device_mtu', default=None, help='MTU setting for vlan'), cfg.StrOpt('dhcpbridge', default='$bindir/nova-dhcpbridge', help='location of nova-dhcpbridge'), cfg.StrOpt('routing_source_ip', default='$my_ip', help='Public IP of network host'), cfg.IntOpt('dhcp_lease_time', default=120, help='Lifetime of a DHCP lease in seconds'), cfg.StrOpt('dns_server', default=None, help='if set, uses specific dns server for dnsmasq'), cfg.ListOpt('dmz_cidr', default=[], help='A list of dmz range that should be accepted'), cfg.StrOpt('dnsmasq_config_file', default='', help='Override the default dnsmasq settings with this file'), cfg.StrOpt('linuxnet_interface_driver', default='nova.network.linux_net.LinuxBridgeInterfaceDriver', help='Driver used to create ethernet devices.'), cfg.StrOpt('linuxnet_ovs_integration_bridge', default='br-int', help='Name of Open vSwitch bridge used with linuxnet'), cfg.BoolOpt('send_arp_for_ha', default=False, help='send gratuitous ARPs for HA setup'), cfg.IntOpt('send_arp_for_ha_count', default=3, help='send this many gratuitous ARPs for HA setup'), cfg.BoolOpt('use_single_default_gateway', default=False, help='Use single default gateway. Only first nic of vm will ' 'get default gateway from dhcp server'), ] FLAGS = flags.FLAGS FLAGS.register_opts(linux_net_opts) # NOTE(vish): Iptables supports chain names of up to 28 characters, and we # add up to 12 characters to binary_name which is used as a prefix, # so we limit it to 16 characters. # (max_chain_name_length - len('-POSTROUTING') == 16) def get_binary_name(): """Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16] binary_name = get_binary_name() class IptablesRule(object): """An iptables rule. You shouldn't need to use this class directly, it's only used by IptablesManager. """ def __init__(self, chain, rule, wrap=True, top=False): self.chain = chain self.rule = rule self.wrap = wrap self.top = top def __eq__(self, other): return ((self.chain == other.chain) and (self.rule == other.rule) and (self.top == other.top) and (self.wrap == other.wrap)) def __ne__(self, other): return not self == other def __str__(self): if self.wrap: chain = '%s-%s' % (binary_name, self.chain) else: chain = self.chain # new rules should have a zero [packet: byte] count return '[0:0] -A %s %s' % (chain, self.rule) class IptablesTable(object): """An iptables table.""" def __init__(self): self.rules = [] self.remove_rules = [] self.chains = set() self.unwrapped_chains = set() self.remove_chains = set() def add_chain(self, name, wrap=True): """Adds a named chain to the table. The chain name is wrapped to be unique for the component creating it, so different components of Nova can safely create identically named chains without interfering with one another. At the moment, its wrapped name is <binary name>-<chain name>, so if nova-compute creates a chain named 'OUTPUT', it'll actually end up named 'nova-compute-OUTPUT'. """ if wrap: self.chains.add(name) else: self.unwrapped_chains.add(name) def remove_chain(self, name, wrap=True): """Remove named chain. This removal "cascades". All rule in the chain are removed, as are all rules in other chains that jump to it. If the chain is not found, this is merely logged. """ if wrap: chain_set = self.chains else: chain_set = self.unwrapped_chains if name not in chain_set: LOG.warn(_('Attempted to remove chain %s which does not exist'), name) return # non-wrapped chains and rules need to be dealt with specially, # so we keep a list of them to be iterated over in apply() if not wrap: self.remove_chains.add(name) chain_set.remove(name) if not wrap: self.remove_rules += filter(lambda r: r.chain == name, self.rules) self.rules = filter(lambda r: r.chain != name, self.rules) if wrap: jump_snippet = '-j %s-%s' % (binary_name, name) else: jump_snippet = '-j %s' % (name,) if not wrap: self.remove_rules += filter(lambda r: jump_snippet in r.rule, self.rules) self.rules = filter(lambda r: jump_snippet not in r.rule, self.rules) def add_rule(self, chain, rule, wrap=True, top=False): """Add a rule to the table. This is just like what you'd feed to iptables, just without the '-A <chain name>' bit at the start. However, if you need to jump to one of your wrapped chains, prepend its name with a '$' which will ensure the wrapping is applied correctly. """ if wrap and chain not in self.chains: raise ValueError(_('Unknown chain: %r') % chain) if '$' in rule: rule = ' '.join(map(self._wrap_target_chain, rule.split(' '))) self.rules.append(IptablesRule(chain, rule, wrap, top)) def _wrap_target_chain(self, s): if s.startswith('$'): return '%s-%s' % (binary_name, s[1:]) return s def remove_rule(self, chain, rule, wrap=True, top=False): """Remove a rule from a chain. Note: The rule must be exactly identical to the one that was added. You cannot switch arguments around like you can with the iptables CLI tool. """ try: self.rules.remove(IptablesRule(chain, rule, wrap, top)) if not wrap: self.remove_rules.append(IptablesRule(chain, rule, wrap, top)) except ValueError: LOG.warn(_('Tried to remove rule that was not there:' ' %(chain)r %(rule)r %(wrap)r %(top)r'), {'chain': chain, 'rule': rule, 'top': top, 'wrap': wrap}) def empty_chain(self, chain, wrap=True): """Remove all rules from a chain.""" chained_rules = [rule for rule in self.rules if rule.chain == chain and rule.wrap == wrap] for rule in chained_rules: self.rules.remove(rule) class IptablesManager(object): """Wrapper for iptables. See IptablesTable for some usage docs A number of chains are set up to begin with. First, nova-filter-top. It's added at the top of FORWARD and OUTPUT. Its name is not wrapped, so it's shared between the various nova workers. It's intended for rules that need to live at the top of the FORWARD and OUTPUT chains. It's in both the ipv4 and ipv6 set of tables. For ipv4 and ipv6, the built-in INPUT, OUTPUT, and FORWARD filter chains are wrapped, meaning that the "real" INPUT chain has a rule that jumps to the wrapped INPUT chain, etc. Additionally, there's a wrapped chain named "local" which is jumped to from nova-filter-top. For ipv4, the built-in PREROUTING, OUTPUT, and POSTROUTING nat chains are wrapped in the same was as the built-in filter chains. Additionally, there's a snat chain that is applied after the POSTROUTING chain. """ def __init__(self, execute=None): if not execute: self.execute = _execute else: self.execute = execute self.ipv4 = {'filter': IptablesTable(), 'nat': IptablesTable()} self.ipv6 = {'filter': IptablesTable()} self.iptables_apply_deferred = False # Add a nova-filter-top chain. It's intended to be shared # among the various nova components. It sits at the very top # of FORWARD and OUTPUT. for tables in [self.ipv4, self.ipv6]: tables['filter'].add_chain('nova-filter-top', wrap=False) tables['filter'].add_rule('FORWARD', '-j nova-filter-top', wrap=False, top=True) tables['filter'].add_rule('OUTPUT', '-j nova-filter-top', wrap=False, top=True) tables['filter'].add_chain('local') tables['filter'].add_rule('nova-filter-top', '-j $local', wrap=False) # Wrap the built-in chains builtin_chains = {4: {'filter': ['INPUT', 'OUTPUT', 'FORWARD'], 'nat': ['PREROUTING', 'OUTPUT', 'POSTROUTING']}, 6: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']}} for ip_version in builtin_chains: if ip_version == 4: tables = self.ipv4 elif ip_version == 6: tables = self.ipv6 for table, chains in builtin_chains[ip_version].iteritems(): for chain in chains: tables[table].add_chain(chain) tables[table].add_rule(chain, '-j $%s' % (chain,), wrap=False) # Add a nova-postrouting-bottom chain. It's intended to be shared # among the various nova components. We set it as the last chain # of POSTROUTING chain. self.ipv4['nat'].add_chain('nova-postrouting-bottom', wrap=False) self.ipv4['nat'].add_rule('POSTROUTING', '-j nova-postrouting-bottom', wrap=False) # We add a snat chain to the shared nova-postrouting-bottom chain # so that it's applied last. self.ipv4['nat'].add_chain('snat') self.ipv4['nat'].add_rule('nova-postrouting-bottom', '-j $snat', wrap=False) # And then we add a float-snat chain and jump to first thing in # the snat chain. self.ipv4['nat'].add_chain('float-snat') self.ipv4['nat'].add_rule('snat', '-j $float-snat') def defer_apply_on(self): self.iptables_apply_deferred = True def defer_apply_off(self): self.iptables_apply_deferred = False self._apply() def apply(self): if self.iptables_apply_deferred: return self._apply() @utils.synchronized('iptables', external=True) def _apply(self): """Apply the current in-memory set of iptables rules. This will blow away any rules left over from previous runs of the same component of Nova, and replace them with our current set of rules. This happens atomically, thanks to iptables-restore. """ s = [('iptables', self.ipv4)] if FLAGS.use_ipv6: s += [('ip6tables', self.ipv6)] for cmd, tables in s: for table in tables: current_table, _err = self.execute('%s-save' % (cmd,), '-c', '-t', '%s' % (table,), run_as_root=True, attempts=5) current_lines = current_table.split('\n') new_filter = self._modify_rules(current_lines, tables[table]) self.execute('%s-restore' % (cmd,), '-c', run_as_root=True, process_input='\n'.join(new_filter), attempts=5) LOG.debug(_("IPTablesManager.apply completed with success")) def _modify_rules(self, current_lines, table, binary=None): unwrapped_chains = table.unwrapped_chains chains = table.chains remove_chains = table.remove_chains rules = table.rules remove_rules = table.remove_rules # Remove any trace of our rules new_filter = filter(lambda line: binary_name not in line, current_lines) seen_chains = False rules_index = 0 for rules_index, rule in enumerate(new_filter): if not seen_chains: if rule.startswith(':'): seen_chains = True else: if not rule.startswith(':'): break our_rules = [] bot_rules = [] for rule in rules: rule_str = str(rule) if rule.top: # rule.top == True means we want this rule to be at the top. # Further down, we weed out duplicates from the bottom of the # list, so here we remove the dupes ahead of time. # We don't want to remove an entry if it has non-zero # [packet:byte] counts and replace it with [0:0], so let's # go look for a duplicate, and over-ride our table rule if # found. # ignore [packet:byte] counts at beginning of line if rule_str.startswith('['): rule_str = rule_str.split(']', 1)[1] dup_filter = filter(lambda s: rule_str.strip() in s.strip(), new_filter) new_filter = filter(lambda s: rule_str.strip() not in s.strip(), new_filter) # if no duplicates, use original rule if dup_filter: # grab the last entry, if there is one dup = dup_filter[-1] rule_str = str(dup) else: rule_str = str(rule) rule_str.strip() our_rules += [rule_str] else: bot_rules += [rule_str] our_rules += bot_rules new_filter[rules_index:rules_index] = our_rules new_filter[rules_index:rules_index] = [':%s - [0:0]' % (name,) for name in unwrapped_chains] new_filter[rules_index:rules_index] = [':%s-%s - [0:0]' % (binary_name, name,) for name in chains] seen_lines = set() def _weed_out_duplicates(line): # ignore [packet:byte] counts at beginning of lines if line.startswith('['): line = line.split(']', 1)[1] line = line.strip() if line in seen_lines: return False else: seen_lines.add(line) return True def _weed_out_removes(line): # We need to find exact matches here if line.startswith(':'): # it's a chain, for example, ":nova-billing - [0:0]" # strip off everything except the chain name line = line.split(':')[1] line = line.split('- [')[0] line = line.strip() for chain in remove_chains: if chain == line: remove_chains.remove(chain) return False elif line.startswith('['): # it's a rule # ignore [packet:byte] counts at beginning of lines line = line.split(']', 1)[1] line = line.strip() for rule in remove_rules: # ignore [packet:byte] counts at beginning of rules rule_str = str(rule) rule_str = rule_str.split(' ', 1)[1] rule_str = rule_str.strip() if rule_str == line: remove_rules.remove(rule) return False # Leave it alone return True # We filter duplicates, letting the *last* occurrence take # precendence. We also filter out anything in the "remove" # lists. new_filter.reverse() new_filter = filter(_weed_out_duplicates, new_filter) new_filter = filter(_weed_out_removes, new_filter) new_filter.reverse() # flush lists, just in case we didn't find something remove_chains.clear() for rule in remove_rules: remove_rules.remove(rule) return new_filter # NOTE(jkoelker) This is just a nice little stub point since mocking # builtins with mox is a nightmare def write_to_file(file, data, mode='w'): with open(file, mode) as f: f.write(data) def metadata_forward(): """Create forwarding rule for metadata.""" if FLAGS.metadata_host != '127.0.0.1': iptables_manager.ipv4['nat'].add_rule('PREROUTING', '-s 0.0.0.0/0 -d 169.254.169.254/32 ' '-p tcp -m tcp --dport 80 -j DNAT ' '--to-destination %s:%s' % (FLAGS.metadata_host, FLAGS.metadata_port)) else: iptables_manager.ipv4['nat'].add_rule('PREROUTING', '-s 0.0.0.0/0 -d 169.254.169.254/32 ' '-p tcp -m tcp --dport 80 ' '-j REDIRECT --to-ports %s' % FLAGS.metadata_port) iptables_manager.apply() def metadata_accept(): """Create the filter accept rule for metadata.""" iptables_manager.ipv4['filter'].add_rule('INPUT', '-s 0.0.0.0/0 -d %s ' '-p tcp -m tcp --dport %s ' '-j ACCEPT' % (FLAGS.metadata_host, FLAGS.metadata_port)) iptables_manager.apply() def add_snat_rule(ip_range): if FLAGS.routing_source_ip: rule = '-s %s -j SNAT --to-source %s' % (ip_range, FLAGS.routing_source_ip) if FLAGS.public_interface: rule += ' -o %s' % FLAGS.public_interface iptables_manager.ipv4['nat'].add_rule('snat', rule) iptables_manager.apply() def init_host(ip_range=None): """Basic networking setup goes here.""" # NOTE(devcamcar): Cloud public SNAT entries and the default # SNAT rule for outbound traffic. if not ip_range: ip_range = FLAGS.fixed_range add_snat_rule(ip_range) iptables_manager.ipv4['nat'].add_rule('POSTROUTING', '-s %s -d %s/32 -j ACCEPT' % (ip_range, FLAGS.metadata_host)) for dmz in FLAGS.dmz_cidr: iptables_manager.ipv4['nat'].add_rule('POSTROUTING', '-s %s -d %s -j ACCEPT' % (ip_range, dmz)) iptables_manager.ipv4['nat'].add_rule('POSTROUTING', '-s %(range)s -d %(range)s ' '-m conntrack ! --ctstate DNAT ' '-j ACCEPT' % {'range': ip_range}) iptables_manager.apply() def send_arp_for_ip(ip, device, count): out, err = _execute('arping', '-U', ip, '-A', '-I', device, '-c', str(count), run_as_root=True, check_exit_code=False) if err: LOG.debug(_('arping error for ip %s'), ip) def bind_floating_ip(floating_ip, device): """Bind ip to public interface.""" _execute('ip', 'addr', 'add', str(floating_ip) + '/32', 'dev', device, run_as_root=True, check_exit_code=[0, 2, 254]) if FLAGS.send_arp_for_ha and FLAGS.send_arp_for_ha_count > 0: send_arp_for_ip(floating_ip, device, FLAGS.send_arp_for_ha_count) def unbind_floating_ip(floating_ip, device): """Unbind a public ip from public interface.""" _execute('ip', 'addr', 'del', str(floating_ip) + '/32', 'dev', device, run_as_root=True, check_exit_code=[0, 2, 254]) def ensure_metadata_ip(): """Sets up local metadata ip.""" _execute('ip', 'addr', 'add', '169.254.169.254/32', 'scope', 'link', 'dev', 'lo', run_as_root=True, check_exit_code=[0, 2, 254]) def ensure_vpn_forward(public_ip, port, private_ip): """Sets up forwarding rules for vlan.""" iptables_manager.ipv4['filter'].add_rule('FORWARD', '-d %s -p udp ' '--dport 1194 ' '-j ACCEPT' % private_ip) iptables_manager.ipv4['nat'].add_rule('PREROUTING', '-d %s -p udp ' '--dport %s -j DNAT --to %s:1194' % (public_ip, port, private_ip)) iptables_manager.ipv4['nat'].add_rule('OUTPUT', '-d %s -p udp ' '--dport %s -j DNAT --to %s:1194' % (public_ip, port, private_ip)) iptables_manager.apply() def ensure_floating_forward(floating_ip, fixed_ip, device): """Ensure floating ip forwarding rule.""" for chain, rule in floating_forward_rules(floating_ip, fixed_ip, device): iptables_manager.ipv4['nat'].add_rule(chain, rule) iptables_manager.apply() def remove_floating_forward(floating_ip, fixed_ip, device): """Remove forwarding for floating ip.""" for chain, rule in floating_forward_rules(floating_ip, fixed_ip, device): iptables_manager.ipv4['nat'].remove_rule(chain, rule) iptables_manager.apply() def floating_forward_rules(floating_ip, fixed_ip, device): rule = '-s %s -j SNAT --to %s' % (fixed_ip, floating_ip) if device: rule += ' -o %s' % device return [('PREROUTING', '-d %s -j DNAT --to %s' % (floating_ip, fixed_ip)), ('OUTPUT', '-d %s -j DNAT --to %s' % (floating_ip, fixed_ip)), ('float-snat', rule)] def initialize_gateway_device(dev, network_ref): if not network_ref: return _execute('sysctl', '-w', 'net.ipv4.ip_forward=1', run_as_root=True) # NOTE(vish): The ip for dnsmasq has to be the first address on the # bridge for it to respond to reqests properly full_ip = '%s/%s' % (network_ref['dhcp_server'], network_ref['cidr'].rpartition('/')[2]) new_ip_params = [[full_ip, 'brd', network_ref['broadcast']]] old_ip_params = [] out, err = _execute('ip', 'addr', 'show', 'dev', dev, 'scope', 'global', run_as_root=True) for line in out.split('\n'): fields = line.split() if fields and fields[0] == 'inet': ip_params = fields[1:-1] old_ip_params.append(ip_params) if ip_params[0] != full_ip: new_ip_params.append(ip_params) if not old_ip_params or old_ip_params[0][0] != full_ip: old_routes = [] result = _execute('ip', 'route', 'show', 'dev', dev, run_as_root=True) if result: out, err = result for line in out.split('\n'): fields = line.split() if fields and 'via' in fields: old_routes.append(fields) _execute('ip', 'route', 'del', fields[0], 'dev', dev, run_as_root=True) for ip_params in old_ip_params: _execute(*_ip_bridge_cmd('del', ip_params, dev), run_as_root=True, check_exit_code=[0, 2, 254]) for ip_params in new_ip_params: _execute(*_ip_bridge_cmd('add', ip_params, dev), run_as_root=True, check_exit_code=[0, 2, 254]) for fields in old_routes: _execute('ip', 'route', 'add', *fields, run_as_root=True) if FLAGS.send_arp_for_ha and FLAGS.send_arp_for_ha_count > 0: send_arp_for_ip(network_ref['dhcp_server'], dev, FLAGS.send_arp_for_ha_count) if(FLAGS.use_ipv6): _execute('ip', '-f', 'inet6', 'addr', 'change', network_ref['cidr_v6'], 'dev', dev, run_as_root=True) def get_dhcp_leases(context, network_ref): """Return a network's hosts config in dnsmasq leasefile format.""" hosts = [] host = None if network_ref['multi_host']: host = FLAGS.host for data in db.network_get_associated_fixed_ips(context, network_ref['id'], host=host): hosts.append(_host_lease(data)) return '\n'.join(hosts) def get_dhcp_hosts(context, network_ref): """Get network's hosts config in dhcp-host format.""" hosts = [] host = None if network_ref['multi_host']: host = FLAGS.host for data in db.network_get_associated_fixed_ips(context, network_ref['id'], host=host): hosts.append(_host_dhcp(data)) return '\n'.join(hosts) def _add_dnsmasq_accept_rules(dev): """Allow DHCP and DNS traffic through to dnsmasq.""" table = iptables_manager.ipv4['filter'] for port in [67, 53]: for proto in ['udp', 'tcp']: args = {'dev': dev, 'port': port, 'proto': proto} table.add_rule('INPUT', '-i %(dev)s -p %(proto)s -m %(proto)s ' '--dport %(port)s -j ACCEPT' % args) iptables_manager.apply() def get_dhcp_opts(context, network_ref): """Get network's hosts config in dhcp-opts format.""" hosts = [] host = None if network_ref['multi_host']: host = FLAGS.host data = db.network_get_associated_fixed_ips(context, network_ref['id'], host=host) if data: instance_set = set([datum['instance_uuid'] for datum in data]) default_gw_vif = {} for instance_uuid in instance_set: vifs = db.virtual_interface_get_by_instance(context, instance_uuid) if vifs: #offer a default gateway to the first virtual interface default_gw_vif[instance_uuid] = vifs[0]['id'] for datum in data: if instance_uuid in default_gw_vif: # we don't want default gateway for this fixed ip if default_gw_vif[instance_uuid] != datum['vif_id']: hosts.append(_host_dhcp_opts(datum)) return '\n'.join(hosts) def release_dhcp(dev, address, mac_address): utils.execute('dhcp_release', dev, address, mac_address, run_as_root=True) def update_dhcp(context, dev, network_ref): conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, get_dhcp_hosts(context, network_ref)) restart_dhcp(context, dev, network_ref) def update_dhcp_hostfile_with_text(dev, hosts_text): conffile = _dhcp_file(dev, 'conf') write_to_file(conffile, hosts_text) def kill_dhcp(dev): pid = _dnsmasq_pid_for(dev) if pid: # Check that the process exists and looks like a dnsmasq process conffile = _dhcp_file(dev, 'conf') out, _err = _execute('cat', '/proc/%d/cmdline' % pid, check_exit_code=False) if conffile.split('/')[-1] in out: _execute('kill', '-9', pid, run_as_root=True) else: LOG.debug(_('Pid %d is stale, skip killing dnsmasq'), pid) # NOTE(ja): Sending a HUP only reloads the hostfile, so any # configuration options (like dchp-range, vlan, ...) # aren't reloaded. @utils.synchronized('dnsmasq_start') def restart_dhcp(context, dev, network_ref): """(Re)starts a dnsmasq server for a given network. If a dnsmasq instance is already running then send a HUP signal causing it to reload, otherwise spawn a new instance. """ conffile = _dhcp_file(dev, 'conf') if FLAGS.use_single_default_gateway: # NOTE(vish): this will have serious performance implications if we # are not in multi_host mode. optsfile = _dhcp_file(dev, 'opts') write_to_file(optsfile, get_dhcp_opts(context, network_ref)) os.chmod(optsfile, 0644) # Make sure dnsmasq can actually read it (it setuid()s to "nobody") os.chmod(conffile, 0644) pid = _dnsmasq_pid_for(dev) # if dnsmasq is already running, then tell it to reload if pid: out, _err = _execute('cat', '/proc/%d/cmdline' % pid, check_exit_code=False) # Using symlinks can cause problems here so just compare the name # of the file itself if conffile.split('/')[-1] in out: try: _execute('kill', '-HUP', pid, run_as_root=True) _add_dnsmasq_accept_rules(dev) return except Exception as exc: # pylint: disable=W0703 LOG.error(_('Hupping dnsmasq threw %s'), exc) else: LOG.debug(_('Pid %d is stale, relaunching dnsmasq'), pid) cmd = ['FLAGFILE=%s' % FLAGS.dhcpbridge_flagfile, 'NETWORK_ID=%s' % str(network_ref['id']), 'dnsmasq', '--strict-order', '--bind-interfaces', '--conf-file=%s' % FLAGS.dnsmasq_config_file, '--domain=%s' % FLAGS.dhcp_domain, '--pid-file=%s' % _dhcp_file(dev, 'pid'), '--listen-address=%s' % network_ref['dhcp_server'], '--except-interface=lo', '--dhcp-range=set:\'%s\',%s,static,%ss' % (network_ref['label'], network_ref['dhcp_start'], FLAGS.dhcp_lease_time), '--dhcp-lease-max=%s' % len(netaddr.IPNetwork(network_ref['cidr'])), '--dhcp-hostsfile=%s' % _dhcp_file(dev, 'conf'), '--dhcp-script=%s' % FLAGS.dhcpbridge, '--leasefile-ro'] if FLAGS.dns_server: cmd += ['-h', '-R', '--server=%s' % FLAGS.dns_server] if FLAGS.use_single_default_gateway: cmd += ['--dhcp-optsfile=%s' % _dhcp_file(dev, 'opts')] _execute(*cmd, run_as_root=True) _add_dnsmasq_accept_rules(dev) @utils.synchronized('radvd_start') def update_ra(context, dev, network_ref): conffile = _ra_file(dev, 'conf') conf_str = """ interface %s { AdvSendAdvert on; MinRtrAdvInterval 3; MaxRtrAdvInterval 10; prefix %s { AdvOnLink on; AdvAutonomous on; }; }; """ % (dev, network_ref['cidr_v6']) write_to_file(conffile, conf_str) # Make sure radvd can actually read it (it setuid()s to "nobody") os.chmod(conffile, 0644) pid = _ra_pid_for(dev) # if radvd is already running, then tell it to reload if pid: out, _err = _execute('cat', '/proc/%d/cmdline' % pid, check_exit_code=False) if conffile in out: try: _execute('kill', pid, run_as_root=True) except Exception as exc: # pylint: disable=W0703 LOG.error(_('killing radvd threw %s'), exc) else: LOG.debug(_('Pid %d is stale, relaunching radvd'), pid) cmd = ['radvd', '-C', '%s' % _ra_file(dev, 'conf'), '-p', '%s' % _ra_file(dev, 'pid')] _execute(*cmd, run_as_root=True) def _host_lease(data): """Return a host string for an address in leasefile format.""" if data['instance_updated']: timestamp = data['instance_updated'] else: timestamp = data['instance_created'] seconds_since_epoch = calendar.timegm(timestamp.utctimetuple()) return '%d %s %s %s *' % (seconds_since_epoch + FLAGS.dhcp_lease_time, data['vif_address'], data['address'], data['instance_hostname'] or '*') def _host_dhcp_network(data): return 'NW-%s' % data['vif_id'] def _host_dhcp(data): """Return a host string for an address in dhcp-host format.""" if FLAGS.use_single_default_gateway: return '%s,%s.%s,%s,%s' % (data['vif_address'], data['instance_hostname'], FLAGS.dhcp_domain, data['address'], 'net:' + _host_dhcp_network(data)) else: return '%s,%s.%s,%s' % (data['vif_address'], data['instance_hostname'], FLAGS.dhcp_domain, data['address']) def _host_dhcp_opts(data): """Return an empty gateway option.""" return '%s,%s' % (_host_dhcp_network(data), 3) def _execute(*cmd, **kwargs): """Wrapper around utils._execute for fake_network.""" if FLAGS.fake_network: LOG.debug('FAKE NET: %s', ' '.join(map(str, cmd))) return 'fake', 0 else: return utils.execute(*cmd, **kwargs) def _device_exists(device): """Check if ethernet device exists.""" (_out, err) = _execute('ip', 'link', 'show', 'dev', device, check_exit_code=False, run_as_root=True) return not err def _dhcp_file(dev, kind): """Return path to a pid, leases or conf file for a bridge/device.""" utils.ensure_tree(FLAGS.networks_path) return os.path.abspath('%s/nova-%s.%s' % (FLAGS.networks_path, dev, kind)) def _ra_file(dev, kind): """Return path to a pid or conf file for a bridge/device.""" utils.ensure_tree(FLAGS.networks_path) return os.path.abspath('%s/nova-ra-%s.%s' % (FLAGS.networks_path, dev, kind)) def _dnsmasq_pid_for(dev): """Returns the pid for prior dnsmasq instance for a bridge/device. Returns None if no pid file exists. If machine has rebooted pid might be incorrect (caller should check). """ pid_file = _dhcp_file(dev, 'pid') if os.path.exists(pid_file): try: with open(pid_file, 'r') as f: return int(f.read()) except (ValueError, IOError): return None def _ra_pid_for(dev): """Returns the pid for prior radvd instance for a bridge/device. Returns None if no pid file exists. If machine has rebooted pid might be incorrect (caller should check). """ pid_file = _ra_file(dev, 'pid') if os.path.exists(pid_file): with open(pid_file, 'r') as f: return int(f.read()) def _ip_bridge_cmd(action, params, device): """Build commands to add/del ips to bridges/devices.""" cmd = ['ip', 'addr', action] cmd.extend(params) cmd.extend(['dev', device]) return cmd def _create_veth_pair(dev1_name, dev2_name): """Create a pair of veth devices with the specified names, deleting any previous devices with those names. """ for dev in [dev1_name, dev2_name]: if _device_exists(dev): try: utils.execute('ip', 'link', 'delete', dev1_name, run_as_root=True, check_exit_code=[0, 2, 254]) except exception.ProcessExecutionError: LOG.exception("Error clearing stale veth %s" % dev) utils.execute('ip', 'link', 'add', dev1_name, 'type', 'veth', 'peer', 'name', dev2_name, run_as_root=True) for dev in [dev1_name, dev2_name]: utils.execute('ip', 'link', 'set', dev, 'up', run_as_root=True) utils.execute('ip', 'link', 'set', dev, 'promisc', 'on', run_as_root=True) # Similar to compute virt layers, the Linux network node # code uses a flexible driver model to support different ways # of creating ethernet interfaces and attaching them to the network. # In the case of a network host, these interfaces # act as gateway/dhcp/vpn/etc. endpoints not VM interfaces. interface_driver = None def _get_interface_driver(): global interface_driver if not interface_driver: interface_driver = importutils.import_object( FLAGS.linuxnet_interface_driver) return interface_driver def plug(network, mac_address, gateway=True): return _get_interface_driver().plug(network, mac_address, gateway) def unplug(network): return _get_interface_driver().unplug(network) def get_dev(network): return _get_interface_driver().get_dev(network) class LinuxNetInterfaceDriver(object): """Abstract class that defines generic network host API""" """ for for all Linux interface drivers.""" def plug(self, network, mac_address): """Create Linux device, return device name""" raise NotImplementedError() def unplug(self, network): """Destory Linux device, return device name""" raise NotImplementedError() def get_dev(self, network): """Get device name""" raise NotImplementedError() # plugs interfaces using Linux Bridge class LinuxBridgeInterfaceDriver(LinuxNetInterfaceDriver): def plug(self, network, mac_address, gateway=True): if network.get('vlan', None) is not None: iface = FLAGS.vlan_interface or network['bridge_interface'] LinuxBridgeInterfaceDriver.ensure_vlan_bridge( network['vlan'], network['bridge'], iface, network, mac_address) else: iface = FLAGS.flat_interface or network['bridge_interface'] LinuxBridgeInterfaceDriver.ensure_bridge( network['bridge'], iface, network, gateway) # NOTE(vish): applying here so we don't get a lock conflict iptables_manager.apply() return network['bridge'] def unplug(self, network): return self.get_dev(network) def get_dev(self, network): return network['bridge'] @classmethod def ensure_vlan_bridge(_self, vlan_num, bridge, bridge_interface, net_attrs=None, mac_address=None): """Create a vlan and bridge unless they already exist.""" interface = LinuxBridgeInterfaceDriver.ensure_vlan(vlan_num, bridge_interface, mac_address) LinuxBridgeInterfaceDriver.ensure_bridge(bridge, interface, net_attrs) return interface @classmethod @utils.synchronized('ensure_vlan', external=True) def ensure_vlan(_self, vlan_num, bridge_interface, mac_address=None): """Create a vlan unless it already exists.""" interface = 'vlan%s' % vlan_num if not _device_exists(interface): LOG.debug(_('Starting VLAN inteface %s'), interface) _execute('ip', 'link', 'add', 'link', bridge_interface, 'name', interface, 'type', 'vlan', 'id', vlan_num, run_as_root=True, check_exit_code=[0, 2, 254]) # (danwent) the bridge will inherit this address, so we want to # make sure it is the value set from the NetworkManager if mac_address: _execute('ip', 'link', 'set', interface, 'address', mac_address, run_as_root=True, check_exit_code=[0, 2, 254]) _execute('ip', 'link', 'set', interface, 'up', run_as_root=True, check_exit_code=[0, 2, 254]) if FLAGS.network_device_mtu: _execute('ip', 'link', 'set', interface, 'mtu', FLAGS.network_device_mtu, run_as_root=True, check_exit_code=[0, 2, 254]) return interface @classmethod @utils.synchronized('ensure_bridge', external=True) def ensure_bridge(_self, bridge, interface, net_attrs=None, gateway=True): """Create a bridge unless it already exists. :param interface: the interface to create the bridge on. :param net_attrs: dictionary with attributes used to create bridge. If net_attrs is set, it will add the net_attrs['gateway'] to the bridge using net_attrs['broadcast'] and net_attrs['cidr']. It will also add the ip_v6 address specified in net_attrs['cidr_v6'] if use_ipv6 is set. The code will attempt to move any ips that already exist on the interface onto the bridge and reset the default gateway if necessary. """ if not _device_exists(bridge): LOG.debug(_('Starting Bridge interface for %s'), interface) _execute('brctl', 'addbr', bridge, run_as_root=True) _execute('brctl', 'setfd', bridge, 0, run_as_root=True) # _execute('brctl setageing %s 10' % bridge, run_as_root=True) _execute('brctl', 'stp', bridge, 'off', run_as_root=True) # (danwent) bridge device MAC address can't be set directly. # instead it inherits the MAC address of the first device on the # bridge, which will either be the vlan interface, or a # physical NIC. _execute('ip', 'link', 'set', bridge, 'up', run_as_root=True) if interface: out, err = _execute('brctl', 'addif', bridge, interface, check_exit_code=False, run_as_root=True) # NOTE(vish): This will break if there is already an ip on the # interface, so we move any ips to the bridge # NOTE(danms): We also need to copy routes to the bridge so as # not to break existing connectivity on the interface old_routes = [] out, err = _execute('ip', 'route', 'show', 'dev', interface) for line in out.split('\n'): fields = line.split() if fields and 'via' in fields: old_routes.append(fields) _execute('ip', 'route', 'del', *fields, run_as_root=True) out, err = _execute('ip', 'addr', 'show', 'dev', interface, 'scope', 'global', run_as_root=True) for line in out.split('\n'): fields = line.split() if fields and fields[0] == 'inet': params = fields[1:-1] _execute(*_ip_bridge_cmd('del', params, fields[-1]), run_as_root=True, check_exit_code=[0, 2, 254]) _execute(*_ip_bridge_cmd('add', params, bridge), run_as_root=True, check_exit_code=[0, 2, 254]) for fields in old_routes: _execute('ip', 'route', 'add', *fields, run_as_root=True) if (err and err != "device %s is already a member of a bridge;" "can't enslave it to bridge %s.\n" % (interface, bridge)): msg = _('Failed to add interface: %s') % err raise exception.NovaException(msg) # Don't forward traffic unless we were told to be a gateway ipv4_filter = iptables_manager.ipv4['filter'] if gateway: ipv4_filter.add_rule('FORWARD', '--in-interface %s -j ACCEPT' % bridge) ipv4_filter.add_rule('FORWARD', '--out-interface %s -j ACCEPT' % bridge) else: ipv4_filter.add_rule('FORWARD', '--in-interface %s -j DROP' % bridge) ipv4_filter.add_rule('FORWARD', '--out-interface %s -j DROP' % bridge) # plugs interfaces using Open vSwitch class LinuxOVSInterfaceDriver(LinuxNetInterfaceDriver): def plug(self, network, mac_address, gateway=True): dev = self.get_dev(network) if not _device_exists(dev): bridge = FLAGS.linuxnet_ovs_integration_bridge _execute('ovs-vsctl', '--', '--may-exist', 'add-port', bridge, dev, '--', 'set', 'Interface', dev, 'type=internal', '--', 'set', 'Interface', dev, 'external-ids:iface-id=%s' % dev, '--', 'set', 'Interface', dev, 'external-ids:iface-status=active', '--', 'set', 'Interface', dev, 'external-ids:attached-mac=%s' % mac_address, run_as_root=True) _execute('ip', 'link', 'set', dev, 'address', mac_address, run_as_root=True) if FLAGS.network_device_mtu: _execute('ip', 'link', 'set', dev, 'mtu', FLAGS.network_device_mtu, run_as_root=True) _execute('ip', 'link', 'set', dev, 'up', run_as_root=True) if not gateway: # If we weren't instructed to act as a gateway then add the # appropriate flows to block all non-dhcp traffic. _execute('ovs-ofctl', 'add-flow', bridge, 'priority=1,actions=drop', run_as_root=True) _execute('ovs-ofctl', 'add-flow', bridge, 'udp,tp_dst=67,dl_dst=%s,priority=2,actions=normal' % mac_address, run_as_root=True) # .. and make sure iptbles won't forward it as well. iptables_manager.ipv4['filter'].add_rule('FORWARD', '--in-interface %s -j DROP' % bridge) iptables_manager.ipv4['filter'].add_rule('FORWARD', '--out-interface %s -j DROP' % bridge) else: iptables_manager.ipv4['filter'].add_rule('FORWARD', '--in-interface %s -j ACCEPT' % bridge) iptables_manager.ipv4['filter'].add_rule('FORWARD', '--out-interface %s -j ACCEPT' % bridge) return dev def unplug(self, network): dev = self.get_dev(network) bridge = FLAGS.linuxnet_ovs_integration_bridge _execute('ovs-vsctl', '--', '--if-exists', 'del-port', bridge, dev, run_as_root=True) return dev def get_dev(self, network): dev = 'gw-' + str(network['uuid'][0:11]) return dev # plugs interfaces using Linux Bridge when using QuantumManager class QuantumLinuxBridgeInterfaceDriver(LinuxNetInterfaceDriver): BRIDGE_NAME_PREFIX = 'brq' GATEWAY_INTERFACE_PREFIX = 'gw-' def plug(self, network, mac_address, gateway=True): dev = self.get_dev(network) bridge = self.get_bridge(network) if not gateway: # If we weren't instructed to act as a gateway then add the # appropriate flows to block all non-dhcp traffic. # .. and make sure iptbles won't forward it as well. iptables_manager.ipv4['filter'].add_rule('FORWARD', '--in-interface %s -j DROP' % bridge) iptables_manager.ipv4['filter'].add_rule('FORWARD', '--out-interface %s -j DROP' % bridge) return bridge else: iptables_manager.ipv4['filter'].add_rule('FORWARD', '--in-interface %s -j ACCEPT' % bridge) iptables_manager.ipv4['filter'].add_rule('FORWARD', '--out-interface %s -j ACCEPT' % bridge) QuantumLinuxBridgeInterfaceDriver.create_tap_dev(dev, mac_address) if not _device_exists(bridge): LOG.debug(_("Starting bridge %s "), bridge) utils.execute('brctl', 'addbr', bridge, run_as_root=True) utils.execute('brctl', 'setfd', bridge, str(0), run_as_root=True) utils.execute('brctl', 'stp', bridge, 'off', run_as_root=True) utils.execute('ip', 'link', 'set', bridge, 'address', mac_address, run_as_root=True, check_exit_code=[0, 2, 254]) utils.execute('ip', 'link', 'set', bridge, 'up', run_as_root=True, check_exit_code=[0, 2, 254]) LOG.debug(_("Done starting bridge %s"), bridge) full_ip = '%s/%s' % (network['dhcp_server'], network['cidr'].rpartition('/')[2]) utils.execute('ip', 'address', 'add', full_ip, 'dev', bridge, run_as_root=True, check_exit_code=[0, 2, 254]) return dev def unplug(self, network): dev = self.get_dev(network) if not _device_exists(dev): return None else: try: utils.execute('ip', 'link', 'delete', dev, run_as_root=True, check_exit_code=[0, 2, 254]) except exception.ProcessExecutionError: LOG.error(_("Failed unplugging gateway interface '%s'"), dev) raise LOG.debug(_("Unplugged gateway interface '%s'"), dev) return dev @classmethod def create_tap_dev(_self, dev, mac_address=None): if not _device_exists(dev): try: # First, try with 'ip' utils.execute('ip', 'tuntap', 'add', dev, 'mode', 'tap', run_as_root=True, check_exit_code=[0, 2, 254]) except exception.ProcessExecutionError: # Second option: tunctl utils.execute('tunctl', '-b', '-t', dev, run_as_root=True) if mac_address: utils.execute('ip', 'link', 'set', dev, 'address', mac_address, run_as_root=True, check_exit_code=[0, 2, 254]) utils.execute('ip', 'link', 'set', dev, 'up', run_as_root=True, check_exit_code=[0, 2, 254]) def get_dev(self, network): dev = self.GATEWAY_INTERFACE_PREFIX + str(network['uuid'][0:11]) return dev def get_bridge(self, network): bridge = self.BRIDGE_NAME_PREFIX + str(network['uuid'][0:11]) return bridge iptables_manager = IptablesManager()
{ "content_hash": "1fea03fb65ba6922d9fff22e789bfc48", "timestamp": "", "source": "github", "line_count": 1341, "max_line_length": 79, "avg_line_length": 38.956002982848624, "alnum_prop": 0.5266653905053599, "repo_name": "savi-dev/nova", "id": "f991b36594137307013ed25c8de7d3a42fefe13d", "size": "53079", "binary": false, "copies": "3", "ref": "refs/heads/silver", "path": "nova/network/linux_net.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16002" }, { "name": "JavaScript", "bytes": "7403" }, { "name": "Python", "bytes": "7168734" }, { "name": "Shell", "bytes": "16910" } ], "symlink_target": "" }
package com.lottery.utils; import android.util.Log; /** * Created by Administrator on 2017/5/15 0015. */ public class LogUtils { private static final String TAG = "DSH -> LogUtils"; public static final int VERBOSE = 1; public static final int DEBUG = 2; public static final int INFO = 3; public static final int WARN = 4; public static final int ERROR = 5; public static final int NOTHING = 6; public static int level = VERBOSE; /** * 默认 * @param msg */ public static void v( String msg) { if (level <= VERBOSE) { Log.v(TAG, msg); } } public static void d(String msg) { if (level <= DEBUG) { Log.d(TAG, msg); } } public static void i(String msg) { if (level <= INFO) { Log.i(TAG, msg); } } public static void w(String msg) { if (level <= WARN) { Log.w(TAG, msg); } } public static void e(String msg) { if (level <= ERROR) { Log.e(TAG, msg); } } /** * 自定义tag * @param tag * @param msg */ public static void v(String tag, String msg) { if (level <= VERBOSE) { Log.v(tag, msg); } } public static void d(String tag, String msg) { if (level <= DEBUG) { Log.d(tag, msg); } } public static void i(String tag, String msg) { if (level <= INFO) { Log.i(TAG, msg); } } public static void w(String tag, String msg) { if (level <= WARN) { Log.w(tag, msg); } } public static void e(String tag, String msg) { if (level <= ERROR) { Log.e(tag, msg); } } }
{ "content_hash": "40e5dc880428de6efa03a55262c1c34b", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 56, "avg_line_length": 22.544303797468356, "alnum_prop": 0.4918585064570466, "repo_name": "dsh923713/lottery", "id": "c75e272a875f25e513d732c4ae0c43d9210bcd95", "size": "1791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/lottery/utils/LogUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "191522" } ], "symlink_target": "" }
/** * Deconstructs a template into tokens. * * @module tokenizer */ define(function(require, exports, module) { "use strict"; // Support. require("./support/array/some"); /** * Represents a Tokenizer. * * @class * @memberOf module:tokenizer * @param {string} template - The template string to tokenize. * @param {array} grammar - The specified grammar to test against. */ function Tokenizer(template, grammar) { this.template = template; this.grammar = grammar; this.stack = []; } /** * Loop through the grammar and return on the first source match. Remove * matches from the source, after pushing to the stack. * * @private * @param {string} template that is searched on till its length is 0. * @param {array} grammar array of test regexes. * @param {array} stack to push found tokens to. * @returns {string} template that has been truncated. */ function parseNextToken(template, grammar, stack) { grammar.some(function(token) { var capture = token.test.exec(template); // Ignore empty captures. if (capture && capture[0]) { template = template.replace(token.test, ""); stack.push({ name: token.name, capture: capture }); return true; } }); return template; } /** * Parses the template into a series of tokens. * * @memberOf module:tokenizer.Tokenizer * @returns {array} The series of tokens. */ Tokenizer.prototype.parse = function() { var template = this.template; var grammar = this.grammar; var stack = this.stack; var stackLen = 0; // While the template still needs to be parsed, loop. while (template.length) { template = parseNextToken(template, grammar, stack); stackLen = stack.length; // Add the previous token, if it exists. if (stackLen - 2 >= 0) { stack[stackLen - 1].previous = stack[stackLen - 2]; } } return stack; }; module.exports = Tokenizer; });
{ "content_hash": "84dedb1069e3b6f65e6826c048a0462e", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 75, "avg_line_length": 25.807692307692307, "alnum_prop": 0.6279185295578739, "repo_name": "kadamwhite/combyne", "id": "2377181ea2c309dd501c1c7765042cd41da501c6", "size": "2013", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/tokenizer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "4382" }, { "name": "HTML", "bytes": "906" }, { "name": "JavaScript", "bytes": "116186" } ], "symlink_target": "" }
package org.scalatest import SharedHelpers.thisLineNumber import exceptions.TestFailedException import org.scalactic.Prettifier import org.scalatest.funspec.AnyFunSpec import org.scalatest.matchers.should.Matchers._ class ListShouldBeEmptyLogicalOrSpec extends AnyFunSpec { private val prettifier = Prettifier.default //ADDITIONAL// val fileName: String = "ListShouldBeEmptyLogicalOrSpec.scala" def wasEqualTo(left: Any, right: Any): String = FailureMessages.wasEqualTo(prettifier, left, right) def wasNotEqualTo(left: Any, right: Any): String = { val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right) FailureMessages.wasNotEqualTo(prettifier, leftee, rightee) } def equaled(left: Any, right: Any): String = FailureMessages.equaled(prettifier, left, right) def didNotEqual(left: Any, right: Any): String = { val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, right) FailureMessages.didNotEqual(prettifier, leftee, rightee) } def wasNotEmpty(left: Any): String = FailureMessages.wasNotEmpty(prettifier, left) def wasEmpty(left: Any): String = FailureMessages.wasEmpty(prettifier, left) def allError(message: String, lineNumber: Int, left: Any): String = { val messageWithIndex = UnquotedString(" " + FailureMessages.forAssertionsGenTraversableMessageWithStackDepth(prettifier, 0, UnquotedString(message), UnquotedString(fileName + ":" + lineNumber))) FailureMessages.allShorthandFailed(prettifier, messageWithIndex, left) } val nonEmptyList = List(1, 2, 3) val emptyList = List.empty[Int] describe("Sorted matcher") { describe("when work with 'list should be (empty)'") { it("should do nothing when list is empty") { emptyList should (be (empty) or be (emptyList)) nonEmptyList should (be (empty) or be (nonEmptyList)) emptyList should (be (empty) or be (nonEmptyList)) emptyList should (be (emptyList) or be (empty)) emptyList should (be (nonEmptyList) or be (empty)) nonEmptyList should (be (nonEmptyList) or be (empty)) emptyList should (be (empty) or equal (emptyList)) nonEmptyList should (be (empty) or equal (nonEmptyList)) emptyList should (be (empty) or equal (nonEmptyList)) emptyList should (equal (emptyList) or be (empty)) emptyList should (equal (nonEmptyList) or be (empty)) nonEmptyList should (equal (nonEmptyList) or be (empty)) } it("should throw TestFailedException with correct stack depth when file is not empty") { val caught1 = intercept[TestFailedException] { nonEmptyList should (be (empty) or be (emptyList)) } assert(caught1.message === Some(wasNotEmpty(nonEmptyList) + ", and " + wasNotEqualTo(nonEmptyList, emptyList))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { nonEmptyList should (be (emptyList) or be (empty)) } assert(caught2.message === Some(wasNotEqualTo(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList))) assert(caught2.failedCodeFileName === Some(fileName)) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { nonEmptyList should (be (empty) or equal (emptyList)) } assert(caught3.message === Some(wasNotEmpty(nonEmptyList) + ", and " + didNotEqual(nonEmptyList, emptyList))) assert(caught3.failedCodeFileName === Some(fileName)) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { nonEmptyList should (equal (emptyList) or be (empty)) } assert(caught4.message === Some(didNotEqual(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList))) assert(caught4.failedCodeFileName === Some(fileName)) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } } describe("when work with 'file should not be empty'") { it("should do nothing when file is not empty") { nonEmptyList should (not be empty or not be emptyList) emptyList should (not be empty or not be nonEmptyList) nonEmptyList should (not be empty or not be nonEmptyList) nonEmptyList should (not be emptyList or not be empty) nonEmptyList should (not be nonEmptyList or not be empty) emptyList should (not be nonEmptyList or not be empty) nonEmptyList should (not be empty or not equal emptyList) emptyList should (not be empty or not equal nonEmptyList) nonEmptyList should (not be empty or not equal nonEmptyList) nonEmptyList should (not equal emptyList or not be empty) nonEmptyList should (not equal nonEmptyList or not be empty) emptyList should (not equal nonEmptyList or not be empty) } it("should throw TestFailedException with correct stack depth when file is empty") { val caught1 = intercept[TestFailedException] { emptyList should (not be empty or not be emptyList) } assert(caught1.message === Some(wasEmpty(emptyList) + ", and " + wasEqualTo(emptyList, emptyList))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { emptyList should (not be emptyList or not be empty) } assert(caught2.message === Some(wasEqualTo(emptyList, emptyList) + ", and " + wasEmpty(emptyList))) assert(caught2.failedCodeFileName === Some(fileName)) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { emptyList should (not be empty or not equal emptyList) } assert(caught3.message === Some(wasEmpty(emptyList) + ", and " + equaled(emptyList, emptyList))) assert(caught3.failedCodeFileName === Some(fileName)) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { emptyList should (not equal emptyList or not be empty) } assert(caught4.message === Some(equaled(emptyList, emptyList) + ", and " + wasEmpty(emptyList))) assert(caught4.failedCodeFileName === Some(fileName)) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } } describe("when work with 'all(xs) should be (empty)'") { it("should do nothing when all(xs) is empty") { all(List(emptyList)) should (be (empty) or be (emptyList)) all(List(nonEmptyList)) should (be (empty) or be (nonEmptyList)) all(List(emptyList)) should (be (empty) or be (nonEmptyList)) all(List(emptyList)) should (be (emptyList) or be (empty)) all(List(emptyList)) should (be (nonEmptyList) or be (empty)) all(List(nonEmptyList)) should (be (nonEmptyList) or be (empty)) all(List(emptyList)) should (be (empty) or equal (emptyList)) all(List(nonEmptyList)) should (be (empty) or equal (nonEmptyList)) all(List(emptyList)) should (be (empty) or equal (nonEmptyList)) all(List(emptyList)) should (equal (emptyList) or be (empty)) all(List(emptyList)) should (equal (nonEmptyList) or be (empty)) all(List(nonEmptyList)) should (equal (nonEmptyList) or be (empty)) } it("should throw TestFailedException with correct stack depth when xs is not sorted") { val left1 = List(nonEmptyList) val caught1 = intercept[TestFailedException] { all(left1) should (be (emptyList) or be (empty)) } assert(caught1.message === Some(allError(wasNotEqualTo(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList), thisLineNumber - 2, left1))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val left2 = List(nonEmptyList) val caught2 = intercept[TestFailedException] { all(left2) should (be (empty) or be (emptyList)) } assert(caught2.message === Some(allError(wasNotEmpty(nonEmptyList) + ", and " + wasNotEqualTo(nonEmptyList, emptyList), thisLineNumber - 2, left2))) assert(caught2.failedCodeFileName === Some(fileName)) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val left3 = List(nonEmptyList) val caught3 = intercept[TestFailedException] { all(left3) should (equal (emptyList) or be (empty)) } assert(caught3.message === Some(allError(didNotEqual(nonEmptyList, emptyList) + ", and " + wasNotEmpty(nonEmptyList), thisLineNumber - 2, left3))) assert(caught3.failedCodeFileName === Some(fileName)) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val left4 = List(nonEmptyList) val caught4 = intercept[TestFailedException] { all(left4) should (be (empty) or equal (emptyList)) } assert(caught4.message === Some(allError(wasNotEmpty(nonEmptyList) + ", and " + didNotEqual(nonEmptyList, emptyList), thisLineNumber - 2, left4))) assert(caught4.failedCodeFileName === Some(fileName)) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } } describe("when work with 'all(xs) should not be sorted'") { it("should do nothing when xs is not sorted") { all(List(nonEmptyList)) should (not be empty or not be emptyList) all(List(emptyList)) should (not be empty or not be nonEmptyList) all(List(nonEmptyList)) should (not be empty or not be nonEmptyList) all(List(nonEmptyList)) should (not be emptyList or not be empty) all(List(nonEmptyList)) should (not be nonEmptyList or not be empty) all(List(emptyList)) should (not be nonEmptyList or not be empty) all(List(nonEmptyList)) should (not be empty or not equal emptyList) all(List(emptyList)) should (not be empty or not equal nonEmptyList) all(List(nonEmptyList)) should (not be empty or not equal nonEmptyList) all(List(nonEmptyList)) should (not equal emptyList or not be empty) all(List(nonEmptyList)) should (not equal nonEmptyList or not be empty) all(List(emptyList)) should (not equal nonEmptyList or not be empty) } it("should throw TestFailedException with correct stack depth when xs is not sorted") { val left1 = List(emptyList) val caught1 = intercept[TestFailedException] { all(left1) should (not be emptyList or not be empty) } assert(caught1.message === Some(allError(wasEqualTo(emptyList, emptyList) + ", and " + wasEmpty(emptyList), thisLineNumber - 2, left1))) assert(caught1.failedCodeFileName === Some(fileName)) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val left2 = List(emptyList) val caught2 = intercept[TestFailedException] { all(left2) should (not be empty or not be emptyList) } assert(caught2.message === Some(allError(wasEmpty(emptyList) + ", and " + wasEqualTo(emptyList, emptyList), thisLineNumber - 2, left2))) assert(caught2.failedCodeFileName === Some(fileName)) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val left3 = List(emptyList) val caught3 = intercept[TestFailedException] { all(left3) should (not equal emptyList or not be empty) } assert(caught3.message === Some(allError(equaled(emptyList, emptyList) + ", and " + wasEmpty(emptyList), thisLineNumber - 2, left3))) assert(caught3.failedCodeFileName === Some(fileName)) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val left4 = List(emptyList) val caught4 = intercept[TestFailedException] { all(left4) should (not be empty or not equal emptyList) } assert(caught4.message === Some(allError(wasEmpty(emptyList) + ", and " + equaled(emptyList, emptyList), thisLineNumber - 2, left4))) assert(caught4.failedCodeFileName === Some(fileName)) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } }
{ "content_hash": "ecafe161fe1f11aa775a50f9b26cfc06", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 199, "avg_line_length": 48.85496183206107, "alnum_prop": 0.659609375, "repo_name": "cheeseng/scalatest", "id": "2cacd86299379add01c1e516a22699397029b6d8", "size": "13400", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "jvm/scalatest-test/src/test/scala/org/scalatest/ListShouldBeEmptyLogicalOrSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14110" }, { "name": "Java", "bytes": "48211" }, { "name": "JavaScript", "bytes": "19211" }, { "name": "Roff", "bytes": "518" }, { "name": "Scala", "bytes": "30044843" }, { "name": "Shell", "bytes": "11837" } ], "symlink_target": "" }
namespace lldb_private { // For cases in which there are multiple classes of types that are not // interchangeable, to allow static type checking. template <unsigned int C> class TaggedASTType : public CompilerType { public: TaggedASTType(const CompilerType &compiler_type) : CompilerType(compiler_type) {} TaggedASTType(lldb::opaque_compiler_type_t type, TypeSystem *type_system) : CompilerType(type_system, type) {} TaggedASTType(const TaggedASTType<C> &tw) : CompilerType(tw) {} TaggedASTType() : CompilerType() {} virtual ~TaggedASTType() {} TaggedASTType<C> &operator=(const TaggedASTType<C> &tw) { CompilerType::operator=(tw); return *this; } }; // Commonly-used tagged types, so code using them is interoperable typedef TaggedASTType<0> TypeFromParser; typedef TaggedASTType<1> TypeFromUser; } #endif
{ "content_hash": "aa8e5b26f5b275d1d25a72c449c9620d", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 28.333333333333332, "alnum_prop": 0.7329411764705882, "repo_name": "endlessm/chromium-browser", "id": "f02f99258a3fbd22f4dc975e1e74e2a0c9ab4a88", "size": "1332", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "third_party/llvm/lldb/include/lldb/Symbol/TaggedASTType.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
echo "Delete the Security Policies related config..." kubectl delete -f "${LOCAL_OUTPUT_DIR}/largeSecurityAuthzPathPolicy.yaml" rm "${LOCAL_OUTPUT_DIR}/generator" rm "${LOCAL_OUTPUT_DIR}/largeSecurityAuthzPathPolicy.yaml"
{ "content_hash": "04809a8e4117ba435fe236ea0dfdd408", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 73, "avg_line_length": 44.6, "alnum_prop": 0.7847533632286996, "repo_name": "istio/tools", "id": "2c1f49566d669219730aef75ce92fd0688344654", "size": "808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "perf/benchmark/configs/istio/security_authz_path/postrun.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "115589" }, { "name": "CUE", "bytes": "3068" }, { "name": "Dockerfile", "bytes": "38122" }, { "name": "Go", "bytes": "398382" }, { "name": "HTML", "bytes": "147062" }, { "name": "JavaScript", "bytes": "110592" }, { "name": "Makefile", "bytes": "21013" }, { "name": "Mustache", "bytes": "851" }, { "name": "Python", "bytes": "270525" }, { "name": "Ruby", "bytes": "317" }, { "name": "Shell", "bytes": "236598" } ], "symlink_target": "" }
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CLogicalSequence.cpp // // @doc: // Implementation of logical sequence operator //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpopt/base/CColRefSet.h" #include "gpopt/operators/CExpression.h" #include "gpopt/operators/CExpressionHandle.h" #include "gpopt/operators/CLogicalSequence.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CLogicalSequence::CLogicalSequence // // @doc: // ctor // //--------------------------------------------------------------------------- CLogicalSequence::CLogicalSequence ( IMemoryPool *pmp ) : CLogical(pmp) { GPOS_ASSERT(NULL != pmp); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::FMatch // // @doc: // Match function on operator level // //--------------------------------------------------------------------------- BOOL CLogicalSequence::FMatch ( COperator *pop ) const { return pop->Eopid() == Eopid(); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PxfsCandidates // // @doc: // Get candidate xforms // //--------------------------------------------------------------------------- CXformSet * CLogicalSequence::PxfsCandidates ( IMemoryPool *pmp ) const { CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp); (void) pxfs->FExchangeSet(CXform::ExfImplementSequence); return pxfs; } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PcrsDeriveOutput // // @doc: // Derive output columns // //--------------------------------------------------------------------------- CColRefSet * CLogicalSequence::PcrsDeriveOutput ( IMemoryPool *, // pmp CExpressionHandle &exprhdl ) { GPOS_ASSERT(1 <= exprhdl.UlArity()); // get output columns of last child CColRefSet *pcrs = exprhdl.Pdprel(exprhdl.UlArity() - 1)->PcrsOutput(); pcrs->AddRef(); return pcrs; } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PkcDeriveKeys // // @doc: // Derive key collection // //--------------------------------------------------------------------------- CKeyCollection * CLogicalSequence::PkcDeriveKeys ( IMemoryPool *, // pmp CExpressionHandle &exprhdl ) const { // return key of last child const ULONG ulArity = exprhdl.UlArity(); return PkcDeriveKeysPassThru(exprhdl, ulArity - 1 /* ulChild */); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::Maxcard // // @doc: // Derive max card // //--------------------------------------------------------------------------- CMaxCard CLogicalSequence::Maxcard ( IMemoryPool *, // pmp CExpressionHandle &exprhdl ) const { // pass on max card of last child return exprhdl.Pdprel(exprhdl.UlArity() - 1)->Maxcard(); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PpartinfoDerive // // @doc: // Derive part consumers // //--------------------------------------------------------------------------- CPartInfo * CLogicalSequence::PpartinfoDerive ( IMemoryPool *pmp, CExpressionHandle &exprhdl ) const { return PpartinfoDeriveCombine(pmp, exprhdl); } // EOF
{ "content_hash": "cd2edccb497837d54956ac5e4ff5227b", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 77, "avg_line_length": 21.118343195266274, "alnum_prop": 0.4519473241804427, "repo_name": "PengJi/gporca-comments", "id": "227e833c463f480e43001b6d52c703902794ad54", "size": "3569", "binary": false, "copies": "1", "ref": "refs/heads/comments", "path": "libgpopt/src/operators/CLogicalSequence.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "36220" }, { "name": "C++", "bytes": "9938687" }, { "name": "CMake", "bytes": "121401" }, { "name": "Makefile", "bytes": "32166" }, { "name": "PLSQL", "bytes": "7716" }, { "name": "PLpgSQL", "bytes": "5718" }, { "name": "Perl", "bytes": "2546" }, { "name": "Python", "bytes": "5623" }, { "name": "Shell", "bytes": "14535" } ], "symlink_target": "" }
Unconstrained for Active Record converts exceptions raised because of underlying database constraints to appropriate ActiveModel::Errors ## Usage In your Gemfile: ```ruby gem 'unconstrained' ``` ## Notes Only constraints that have to do with referential integrity are handled. This is intentional, as these require a roundrip to the database anyway. Constraints that can be enforced using validations in the application should be checked that way. Currently only handles PostgreSQL. ## Reasoning Rails supports the `dependent` option on `has_one` / `has_many` associations, which can be used to a similar effect, ie: ```ruby has_many :children, dependent: :restrict_with_error ``` However, this has drawbacks. In the simple case, it offers no particular advantage, since it still needs a roundrip to the database, and since no locking takes place, there exists the possibility of an error in a system under heavy use. In more complex scenarios, errors are bound to occur. For example, consider the following scenario: ``` parents | | <- dependent: :destroy | ---children | | <- dependent: :restrict_with_error | ---grandchildren ``` Here ActiveRecord will never have an efficient way to proceed. It would either have to delete the children en masse, leading to database errors such as: ``` ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "children" violates foreign key constraint "fk_rails_xxxxxxxxxx" on table "grandchildren" DETAIL: Key (id)=(xxxxxxxxxx) is still referenced from table "grandchildren". ``` Otherwise ActiveRecord would need to load and check every child record, which would be extremely inefficient. On the other hand, a relational database, with the appropriate constraints defined, would handle the operation swiftly and efficiently. Now that Rails 4.2 supports foreign key constraints, one would simply define in the migration: ```ruby add_foreign_key :children, :parents, on_delete: :cascade add_foreign_key :grandchildren, :children ``` and then the database exceptions would be handled by Unconstrained.
{ "content_hash": "dca3ce2dcec8aa0e1dadf151cc5db60b", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 78, "avg_line_length": 28.82191780821918, "alnum_prop": 0.7756653992395437, "repo_name": "agios/unconstrained", "id": "a7931f8e993fb9eeea57ad11a3f2fb9e37ec2258", "size": "2121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "14808" } ], "symlink_target": "" }
#include "TestClass.h" using namespace std; CPPDLL_API void WriteToConsoleGlobal() { cout << "Hello world!" << endl; } //CPPDLL_API void WriteStringToConsoleGlobal(string value) //{ // cout << value << endl; //} CPPDLL_API void WriteCharArrayToConsoleGlobal(char* value) { cout << value << endl; } void TestClass::WriteToConsole() { cout << "Hello world!" << endl; } void TestClass::WriteToConsole(string value) { cout << value << endl; }
{ "content_hash": "598e0918e08bc55eccb23d41ff7c4b17", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 58, "avg_line_length": 15.09375, "alnum_prop": 0.6376811594202898, "repo_name": "MinexAutomation/Public", "id": "e2bdb6fc5b1b1a741818e09abc2674f5e2057750", "size": "504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Experiments/Experiments/PInvoke/Cpp/CppDLL/TestClass.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1084" }, { "name": "C", "bytes": "2792" }, { "name": "C#", "bytes": "2155762" }, { "name": "C++", "bytes": "4246" }, { "name": "CSS", "bytes": "46" }, { "name": "HTML", "bytes": "5117" }, { "name": "JavaScript", "bytes": "2540" }, { "name": "MATLAB", "bytes": "14209" }, { "name": "Python", "bytes": "7682" }, { "name": "TypeScript", "bytes": "5152" } ], "symlink_target": "" }
package edu.wustl.catissuecore.action; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.actionForm.CTRPEntityForm; import edu.wustl.catissuecore.ctrp.COPPAServiceClient; import edu.wustl.catissuecore.ctrp.COPPAUtil; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.common.action.BaseAction; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.coppa.po.Person; import gov.nih.nci.coppa.services.pa.StudyProtocol; public class CTRPStudyProtocolAction extends BaseAction { /** * logger. */ private transient final Logger logger = Logger .getCommonLogger(CTRPStudyProtocolAction.class); /** * Overrides the executeSecureAction method of SecureAction class. * * @param mapping * object of ActionMapping * @param form * object of ActionForm * @param request * object of HttpServletRequest * @param response * : response obj * @throws Exception * generic exception * @return ActionForward : ActionForward */ @Override public ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CTRPEntityForm ctrpEntityForm = (CTRPEntityForm) form; COPPAServiceClient client = new COPPAServiceClient(); String title = request.getParameter("entityName"); if (AppUtility.isNotEmpty(ctrpEntityForm.getEntityName())) { // Use email address from search form title = ctrpEntityForm.getEntityName(); } COPPAServiceClient coppaClient = new COPPAServiceClient(); CollectionProtocol searchCollectionProtocol = new CollectionProtocol(); StudyProtocol[] protocolList = null; // searchUser.setEmailAddress(ctrpEntityForm.getEntityName()); searchCollectionProtocol.setTitle(title); protocolList = coppaClient .searchSutdyProtocol(searchCollectionProtocol); if (AppUtility.isNotEmpty(protocolList)) { request.setAttribute("COPPA_MATCH_FOUND", "true"); request.setAttribute("COPPA_STUDY_PROTOCOLS", protocolList); } return mapping.findForward("displayMatches"); } }
{ "content_hash": "90729c9968174e4fc4bd1554d47ac3d9", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 75, "avg_line_length": 34.148648648648646, "alnum_prop": 0.7467352592006332, "repo_name": "NCIP/catissue-core", "id": "880a1cb97b1520de421258b1d176d7fac58e93ef", "size": "2809", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/CTRPStudyProtocolAction.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "263825" }, { "name": "CSS", "bytes": "355520" }, { "name": "Java", "bytes": "11570343" }, { "name": "JavaScript", "bytes": "957613" }, { "name": "Shell", "bytes": "1912" }, { "name": "XSLT", "bytes": "256376" } ], "symlink_target": "" }
<textarea> Pre-formatted &lt;em&gt;tags&lt;/em&gt; are used here. So need to &lt;strong&gt;escape&lt;/strong&gt; special characters in textarea, etc. </textarea> <div data-prop="Should be &gt;&gt;escaped&lt;&lt; in properties."></div>
{ "content_hash": "76a834a08e5b6f99aa6ef11eda861c2f", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 84, "avg_line_length": 39.5, "alnum_prop": 0.7088607594936709, "repo_name": "team-aries/htttml", "id": "6d90974afd35e31bc4fdb18436d601cd31d7257c", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/string/dst/syntaxEscapingVariableContent.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "164" }, { "name": "CSS", "bytes": "15114" }, { "name": "HTML", "bytes": "2645" }, { "name": "PHP", "bytes": "46077" } ], "symlink_target": "" }
var browserify = require('gulp-browserify'), concat = require('gulp-concat'), Config = require('./gulpfile.config'), config = new Config(), connect = require('gulp-connect'), del = require('del'), eventStream = require('event-stream'), gulp = require('gulp'); insert = require('gulp-insert'), path = require('path'), rename = require('gulp-rename'), requireDir = require('require-dir'), runSequence = require('run-sequence'), tasks = requireDir('./tasks'), ts = require('gulp-typescript'), uglify = require('gulp-uglify'); gulp.task('build', function() { var tsResult = gulp.src(['src/*.ts', '!src/*.d.ts']) .pipe(ts({ declarationFiles: true, noExternalResolve: true, module: 'amd', sortOutput: true })); return eventStream.merge( tsResult.dts.pipe(gulp.dest(config.dist)), tsResult.js.pipe(gulp.dest(config.dist)) ); }); gulp.task('browserify', function (cb) { return gulp.src(['./*.js'], { cwd: config.dist }) .pipe(browserify({ transform: ['deamdify'], standalone: config.standalone })) .pipe(rename(config.out)) .pipe(gulp.dest(config.dist)); }); gulp.task('clean:dist', function (cb) { del([ config.dist + '/*' ], cb); }); gulp.task('concat', function() { gulp.src(['./lib/*.js', config.dist + '/' + config.out]).pipe(concat(config.out)).pipe(gulp.dest(config.dist)); }); gulp.task('minify', function() { return gulp.src([config.out], { cwd: config.dist }) .pipe(rename(function (path) { path.extname = ".min" + path.extname; })) .pipe(uglify()) .pipe(insert.prepend(config.header)) .pipe(gulp.dest(config.dist)); }); function mount(connect, dir) { return connect.static(path.resolve(dir)); } gulp.task('test', function() { connect.server({ root: './test', middleware: function(connect, opt) { return [ // serve contents of the dist folder mount(connect, config.dist) ] } }); }); gulp.task('default', function(cb) { runSequence('clean:dist', 'build', 'browserify', 'concat', cb); });
{ "content_hash": "d7d07e4d2544a0ded319f6db3c0964e4", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 115, "avg_line_length": 28.160493827160494, "alnum_prop": 0.5589653660675142, "repo_name": "edsilv/pixelpalette", "id": "9d5aa99e589983c8d4afcda2804f026aa9b99445", "size": "2281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "630" }, { "name": "HTML", "bytes": "4255" }, { "name": "JavaScript", "bytes": "40057" }, { "name": "TypeScript", "bytes": "1419" } ], "symlink_target": "" }
package sandbox_test import ( "testing" "time" "github.com/cri-o/cri-o/internal/hostport" "github.com/cri-o/cri-o/internal/lib/sandbox" . "github.com/cri-o/cri-o/test/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" ) // TestSandbox runs the created specs func TestSandbox(t *testing.T) { RegisterFailHandler(Fail) RunFrameworkSpecs(t, "Sandbox") } var ( t *TestFramework testSandbox *sandbox.Sandbox ) var _ = BeforeSuite(func() { t = NewTestFramework(NilFunc, NilFunc) t.Setup() logrus.SetLevel(logrus.PanicLevel) }) var _ = AfterSuite(func() { t.Teardown() }) func beforeEach() { // Setup test vars var err error testSandbox, err = sandbox.New("sandboxID", "", "", "", "", make(map[string]string), make(map[string]string), "", "", &sandbox.Metadata{}, "", "", false, "", "", "", []*hostport.PortMapping{}, false, time.Now(), "") Expect(err).To(BeNil()) Expect(testSandbox).NotTo(BeNil()) }
{ "content_hash": "00da03903ffcb02fc816364753156e24", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 60, "avg_line_length": 21.369565217391305, "alnum_prop": 0.6632756866734486, "repo_name": "kubernetes-incubator/cri-o", "id": "5bf15cb61380501884aa4ddb6a85dbdb39bf818e", "size": "983", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "internal/lib/sandbox/suite_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "55743" }, { "name": "Dockerfile", "bytes": "8011" }, { "name": "Go", "bytes": "421420" }, { "name": "Makefile", "bytes": "10175" }, { "name": "Python", "bytes": "6483" }, { "name": "Shell", "bytes": "112484" } ], "symlink_target": "" }
@interface FBLikeButtonBackgroundSelectedPNG : NSObject { } + (id)image; @end
{ "content_hash": "3c43f53586a0c1018209546e460c8c02", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 55, "avg_line_length": 10.125, "alnum_prop": 0.7407407407407407, "repo_name": "Tatsh/tynder", "id": "db717a729519a40622005560dffc8f0aad9fed25", "size": "242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "headers/3rdparty/FBLikeButtonBackgroundSelectedPNG.h", "mode": "33188", "license": "mit", "language": [ { "name": "Logos", "bytes": "623" }, { "name": "Makefile", "bytes": "228" }, { "name": "Objective-C", "bytes": "646164" } ], "symlink_target": "" }
import type { Theme } from '../../common/themes/types'; import type { ButtonProps } from '../../common/components/Button'; import React from 'react'; import { Button } from '../../common/components'; import { Match } from 'react-router'; type LinkProps = ButtonProps & { activeStyle?: (theme: Theme) => Object, exactly?: boolean, to: string | Object, }; type LinkContext = { router: any, }; const Link = ( { activeStyle, boxStyle, exactly, onPress, to, ...props }: LinkProps, { router, }: LinkContext, ) => ( <Match exactly={exactly} pattern={to}> {({ matched }) => ( <Button onPress={() => { router.transitionTo(to); if (!onPress) return; onPress(); }} boxStyle={theme => ({ ...(boxStyle && boxStyle(theme)), ...(matched && activeStyle ? activeStyle(theme) : null), })} {...props} /> )} </Match> ); Link.contextTypes = { router: React.PropTypes.object, }; export default Link;
{ "content_hash": "6bcc2f1cf2cbd0332b8dcfe785ae3dbe", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 66, "avg_line_length": 20.057692307692307, "alnum_prop": 0.5465004793863855, "repo_name": "chad099/react-native-boilerplate", "id": "0928d79b80a1e71d48ca68951723657f5ca12506", "size": "1052", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/native/components/Link.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2475" }, { "name": "JavaScript", "bytes": "1203027" }, { "name": "Objective-C", "bytes": "5352" }, { "name": "Python", "bytes": "1633" } ], "symlink_target": "" }
package org.web3j.utils; import java.math.BigDecimal; import org.junit.Test; import org.web3j.utils.Convert; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class ConvertTest { @Test public void testFromWei() { assertThat(Convert.fromWei("21000000000000", Convert.Unit.WEI), is(new BigDecimal("21000000000000"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.KWEI), is(new BigDecimal("21000000000"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.MWEI), is(new BigDecimal("21000000"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.GWEI), is(new BigDecimal("21000"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.SZABO), is(new BigDecimal("21"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.FINNEY), is(new BigDecimal("0.021"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.ETHER), is(new BigDecimal("0.000021"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.KETHER), is(new BigDecimal("0.000000021"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.METHER), is(new BigDecimal("0.000000000021"))); assertThat(Convert.fromWei("21000000000000", Convert.Unit.GETHER), is(new BigDecimal("0.000000000000021"))); } @Test public void testToWei() { assertThat(Convert.toWei("21", Convert.Unit.WEI), is(new BigDecimal("21"))); assertThat(Convert.toWei("21", Convert.Unit.KWEI), is(new BigDecimal("21000"))); assertThat(Convert.toWei("21", Convert.Unit.MWEI), is(new BigDecimal("21000000"))); assertThat(Convert.toWei("21", Convert.Unit.GWEI), is(new BigDecimal("21000000000"))); assertThat(Convert.toWei("21", Convert.Unit.SZABO), is(new BigDecimal("21000000000000"))); assertThat(Convert.toWei("21", Convert.Unit.FINNEY), is(new BigDecimal("21000000000000000"))); assertThat(Convert.toWei("21", Convert.Unit.ETHER), is(new BigDecimal("21000000000000000000"))); assertThat(Convert.toWei("21", Convert.Unit.KETHER), is(new BigDecimal("21000000000000000000000"))); assertThat(Convert.toWei("21", Convert.Unit.METHER), is(new BigDecimal("21000000000000000000000000"))); assertThat(Convert.toWei("21", Convert.Unit.GETHER), is(new BigDecimal("21000000000000000000000000000"))); } @Test public void testUnit() { assertThat(Convert.Unit.fromString("ether"), is(Convert.Unit.ETHER)); assertThat(Convert.Unit.fromString("ETHER"), is(Convert.Unit.ETHER)); assertThat(Convert.Unit.fromString("wei"), is(Convert.Unit.WEI)); } }
{ "content_hash": "abeba4ea4217b4a7719a151f91ea91d8", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 98, "avg_line_length": 45.953125, "alnum_prop": 0.6473988439306358, "repo_name": "saulbein/web3j", "id": "ffa6605d17c2a050fc911fbe06d9a8898e14aacf", "size": "2941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/test/java/org/web3j/utils/ConvertTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1586727" }, { "name": "Shell", "bytes": "647" } ], "symlink_target": "" }
#include "rsys/common.h" #define Point NeXT_Point #import <drivers/event_status_driver.h> #undef Point #include "rsys/keyboards.h" keyboard_enum_t ROMlib_get_keyboard_type( void ) { NXEventHandle handle; NXEventSystemDevice dev[NX_EVS_DEVICE_MAX]; unsigned int cnt, i; int interface, id, retval; if ( (handle = NXOpenEventStatus()) == NULL ) /*-->*/ return NO; cnt = NX_EVS_DEVICE_INFO_COUNT; NXEventSystemInfo( handle, NX_EVS_DEVICE_INFO, (int *)dev, &cnt ); NXCloseEventStatus( handle ); interface = -1; id = 0; for (i = 0; i < cnt/(sizeof (NXEventSystemDevice)/sizeof (int)); ++i) { if ( dev[i].dev_type == NX_EVS_DEVICE_TYPE_KEYBOARD ) { interface = dev[i].interface; id = dev[i].id; break; } } switch (interface) { default: retval = default_keyboard; break; case NX_EVS_DEVICE_INTERFACE_ADB: retval = adb_keyboard; break; case NX_EVS_DEVICE_INTERFACE_ACE: retval = pc_keyboard; break; } return retval; }
{ "content_hash": "3bc53d5ef679d4a0f191537d97f1e71d", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 70, "avg_line_length": 23.261904761904763, "alnum_prop": 0.6591606960081884, "repo_name": "ctm/executor", "id": "08bef7c9f3553a902a5119a86bc603f3e0fbb70f", "size": "977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/config/front-ends/nextstep/NEXTkeyboard.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6224431" }, { "name": "Objective-C", "bytes": "181438" }, { "name": "Perl", "bytes": "36360" }, { "name": "Shell", "bytes": "31111" } ], "symlink_target": "" }
Script to capture prometheus DB from the running prometheus pods to local file system. This can be used to look at the metrics later by running prometheus locally with the backed up DB. ## Run ``` $ ./prometheus_dump.sh <output_dir> ``` ## Visualize the captured data locally on prometheus server ``` $ ./prometheus_view.sh <db_tarball_url> ``` This installs prometheus server and loads up the DB, the server can be accessed at https://localhost:9090.
{ "content_hash": "a7c68ef507db986cbd780272993c2405", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 143, "avg_line_length": 34.92307692307692, "alnum_prop": 0.751101321585903, "repo_name": "mffiedler/svt", "id": "b8b4085301a9f9613495a6c08bbff19109d9ee75", "size": "475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openshift_tooling/prometheus_db_dump/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "2409" }, { "name": "Awk", "bytes": "6973" }, { "name": "DIGITAL Command Language", "bytes": "1375" }, { "name": "Dockerfile", "bytes": "18989" }, { "name": "Go", "bytes": "3048" }, { "name": "Groovy", "bytes": "1206" }, { "name": "Jinja", "bytes": "12917" }, { "name": "Makefile", "bytes": "328" }, { "name": "Python", "bytes": "361874" }, { "name": "Shell", "bytes": "367619" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0) on Wed Apr 02 16:16:41 CEST 2014 --> <title>RL_abstract_type (RL-Glue Java Codec 2.07)</title> <meta name="date" content="2014-04-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="RL_abstract_type (RL-Glue Java Codec 2.07)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":9,"i10":10,"i11":10,"i12":10,"i13":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/RL_abstract_type.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/rlcommunity/rlglue/codec/types/Reward_observation_terminal.html" title="class in org.rlcommunity.rlglue.codec.types"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" target="_top">Frames</a></li> <li><a href="RL_abstract_type.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.rlcommunity.rlglue.codec.types</div> <h2 title="Class RL_abstract_type" class="title">Class RL_abstract_type</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.rlcommunity.rlglue.codec.types.RL_abstract_type</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.Comparable</dd> </dl> <dl> <dt>Direct Known Subclasses:</dt> <dd><a href="../../../../../org/rlcommunity/rlglue/codec/types/Action.html" title="class in org.rlcommunity.rlglue.codec.types">Action</a>, <a href="../../../../../org/rlcommunity/rlglue/codec/types/Observation.html" title="class in org.rlcommunity.rlglue.codec.types">Observation</a></dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">RL_abstract_type</span> extends java.lang.Object implements java.lang.Comparable</pre> <div class="block">Common superclass for all of the Java RL-Glue types. Try to keep handles to the objects and not their arrays, because there is no guarantee that the arrays will not be reallocated during certain operations.</div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>btanner</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>char[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#charArray">charArray</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#doubleArray">doubleArray</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>int[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#intArray">intArray</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#RL_abstract_type-int-int-int-">RL_abstract_type</a></span>(int&nbsp;numInts, int&nbsp;numDoubles, int&nbsp;numChars)</code> <div class="block">Create a RL_abstract_type with arrays allocated according to numInts, numDoubles, and numChars</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#RL_abstract_type-org.rlcommunity.rlglue.codec.types.RL_abstract_type-">RL_abstract_type</a></span>(<a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;src)</code> <div class="block">Create a new RL_abstract_type that is a deep, independent copy of src.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#compareTo-java.lang.Object-">compareTo</a></span>(java.lang.Object&nbsp;cObject)</code> <div class="block">Allows us to easily compare abstract types so that we can put them in maps and stuff.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>char</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getChar-int-">getChar</a></span>(int&nbsp;which)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getDouble-int-">getDouble</a></span>(int&nbsp;which)</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getInt-int-">getInt</a></span>(int&nbsp;which)</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getNumChars--">getNumChars</a></span>()</code>&nbsp;</td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getNumDoubles--">getNumDoubles</a></span>()</code>&nbsp;</td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#getNumInts--">getNumInts</a></span>()</code>&nbsp;</td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#RLStructCopy-org.rlcommunity.rlglue.codec.types.RL_abstract_type-org.rlcommunity.rlglue.codec.types.RL_abstract_type-">RLStructCopy</a></span>(<a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;src, <a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;dest)</code> <div class="block">Useful (maybe?) utility method for deep copying one RL_Abstract_type into another.</div> </td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#setChar-int-char-">setChar</a></span>(int&nbsp;which, char&nbsp;value)</code>&nbsp;</td> </tr> <tr id="i11" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#setDouble-int-double-">setDouble</a></span>(int&nbsp;which, double&nbsp;value)</code>&nbsp;</td> </tr> <tr id="i12" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#setInt-int-int-">setInt</a></span>(int&nbsp;which, int&nbsp;value)</code>&nbsp;</td> </tr> <tr id="i13" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html#toString--">toString</a></span>()</code> <div class="block">Prints out a human-readable format of the RL_abstract_type, which is useful for debugging.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="intArray"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>intArray</h4> <pre>public&nbsp;int[] intArray</pre> </li> </ul> <a name="doubleArray"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>doubleArray</h4> <pre>public&nbsp;double[] doubleArray</pre> </li> </ul> <a name="charArray"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>charArray</h4> <pre>public&nbsp;char[] charArray</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="RL_abstract_type-int-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RL_abstract_type</h4> <pre>public&nbsp;RL_abstract_type(int&nbsp;numInts, int&nbsp;numDoubles, int&nbsp;numChars)</pre> <div class="block">Create a RL_abstract_type with arrays allocated according to numInts, numDoubles, and numChars</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>numInts</code> - Size of int array to allocate.</dd> <dd><code>numDoubles</code> - Size of double array to allocate.</dd> <dd><code>numChars</code> - Size of char array to allocate.</dd> </dl> </li> </ul> <a name="RL_abstract_type-org.rlcommunity.rlglue.codec.types.RL_abstract_type-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>RL_abstract_type</h4> <pre>public&nbsp;RL_abstract_type(<a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;src)</pre> <div class="block">Create a new RL_abstract_type that is a deep, independent copy of src.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>src</code> - </dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getInt-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInt</h4> <pre>public&nbsp;int&nbsp;getInt(int&nbsp;which)</pre> </li> </ul> <a name="getDouble-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDouble</h4> <pre>public&nbsp;double&nbsp;getDouble(int&nbsp;which)</pre> </li> </ul> <a name="getChar-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getChar</h4> <pre>public&nbsp;char&nbsp;getChar(int&nbsp;which)</pre> </li> </ul> <a name="setInt-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setInt</h4> <pre>public&nbsp;void&nbsp;setInt(int&nbsp;which, int&nbsp;value)</pre> </li> </ul> <a name="setDouble-int-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDouble</h4> <pre>public&nbsp;void&nbsp;setDouble(int&nbsp;which, double&nbsp;value)</pre> </li> </ul> <a name="setChar-int-char-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setChar</h4> <pre>public&nbsp;void&nbsp;setChar(int&nbsp;which, char&nbsp;value)</pre> </li> </ul> <a name="getNumInts--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNumInts</h4> <pre>public&nbsp;int&nbsp;getNumInts()</pre> </li> </ul> <a name="getNumDoubles--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNumDoubles</h4> <pre>public&nbsp;int&nbsp;getNumDoubles()</pre> </li> </ul> <a name="getNumChars--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNumChars</h4> <pre>public&nbsp;int&nbsp;getNumChars()</pre> </li> </ul> <a name="RLStructCopy-org.rlcommunity.rlglue.codec.types.RL_abstract_type-org.rlcommunity.rlglue.codec.types.RL_abstract_type-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RLStructCopy</h4> <pre>public static&nbsp;void&nbsp;RLStructCopy(<a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;src, <a href="../../../../../org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" title="class in org.rlcommunity.rlglue.codec.types">RL_abstract_type</a>&nbsp;dest)</pre> <div class="block">Useful (maybe?) utility method for deep copying one RL_Abstract_type into another.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>src</code> - </dd> <dd><code>dest</code> - </dd> </dl> </li> </ul> <a name="toString--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">Prints out a human-readable format of the RL_abstract_type, which is useful for debugging.</div> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="compareTo-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compareTo</h4> <pre>public&nbsp;int&nbsp;compareTo(java.lang.Object&nbsp;cObject)</pre> <div class="block">Allows us to easily compare abstract types so that we can put them in maps and stuff.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>compareTo</code>&nbsp;in interface&nbsp;<code>java.lang.Comparable</code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>cObject</code> - </dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>-1 if this is 'smaller' then cObject, +1 if this is 'bigger' than cObject, 0 if they are identical.</dd> </dl> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/RL_abstract_type.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/rlcommunity/rlglue/codec/types/Reward_observation_terminal.html" title="class in org.rlcommunity.rlglue.codec.types"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li>Next&nbsp;Class</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/rlcommunity/rlglue/codec/types/RL_abstract_type.html" target="_top">Frames</a></li> <li><a href="RL_abstract_type.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "4d1c08ecb2a8d1c087f80067391b5ace", "timestamp": "", "source": "github", "line_count": 601, "max_line_length": 524, "avg_line_length": 37.86189683860233, "alnum_prop": 0.648560755877829, "repo_name": "adamse/rl-glue-java-codec", "id": "ec40ac61a3da3ea632c9c99fdb777a628c604aaf", "size": "22755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadocs/org/rlcommunity/rlglue/codec/types/RL_abstract_type.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2282" }, { "name": "Java", "bytes": "317967" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Perl", "bytes": "3617" }, { "name": "Shell", "bytes": "625" }, { "name": "TeX", "bytes": "37917" } ], "symlink_target": "" }
"""Tests for tf.keras models using DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.contrib.distribute.python import combinations from tensorflow.contrib.distribute.python import mirrored_strategy from tensorflow.contrib.distribute.python import tpu_strategy from tensorflow.python import keras from tensorflow.python.data.ops import dataset_ops from tensorflow.python.distribute import distribute_lib from tensorflow.python.eager import test from tensorflow.python.framework import random_seed from tensorflow.python.keras import testing_utils from tensorflow.python.keras.engine import distributed_training_utils from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras from tensorflow.python.ops.parsing_ops import gen_parsing_ops from tensorflow.python.training import gradient_descent from tensorflow.python.training import rmsprop _RANDOM_SEED = 1337 _TRAIN_SIZE = 200 _INPUT_SIZE = (10,) _NUM_CLASS = 2 # TODO(anjalisridhar): Add a decorator that will allow us to run these tests as # part of the tf.keras unit tests suite. def simple_sequential_model(): model = keras.models.Sequential() model.add(keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE)) model.add(keras.layers.Dropout(0.1)) model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax')) return model def simple_functional_model(): a = keras.layers.Input(shape=_INPUT_SIZE) b = keras.layers.Dense(16, activation='relu')(a) b = keras.layers.Dropout(0.1)(b) b = keras.layers.Dense(_NUM_CLASS, activation='softmax')(b) model = keras.models.Model(inputs=[a], outputs=[b]) return model def multi_inputs_multi_outputs_model(): input_a = keras.layers.Input(shape=(16,), name='input_a') input_b = keras.layers.Input(shape=(16,), name='input_b') input_m = keras.layers.Input(shape=(8,), dtype='string', name='input_m') dense = keras.layers.Dense(8, name='dense_1') interm_a = dense(input_a) # Read m interm_m = keras.layers.Lambda(gen_parsing_ops.string_to_number)(input_m) interm_s = keras.layers.Lambda(lambda k: k[0] * k[1])([interm_m, interm_a]) interm_b = dense(input_b) merged = keras.layers.concatenate([interm_s, interm_b], name='merge') output_c = keras.layers.Dense(3, activation='softmax', name='dense_2')(merged) output_d = keras.layers.Dense(2, activation='softmax', name='dense_3')(merged) model = keras.models.Model( inputs=[input_a, input_b, input_m], outputs=[output_c, output_d]) model.compile( loss='categorical_crossentropy', optimizer=gradient_descent.GradientDescentOptimizer(0.001), metrics={ 'dense_2': 'categorical_accuracy', 'dense_3': 'categorical_accuracy' }) return model def get_ds_train_input_fn(): np.random.seed(_RANDOM_SEED) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=_INPUT_SIZE, num_classes=_NUM_CLASS) y_train = keras.utils.to_categorical(y_train) dataset = dataset_ops.Dataset.from_tensor_slices((x_train, y_train)) dataset = dataset.batch(32) return dataset def get_ds_test_input_fn(): np.random.seed(_RANDOM_SEED) _, (x_test, y_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=_INPUT_SIZE, num_classes=_NUM_CLASS) y_test = keras.utils.to_categorical(y_test) dataset = dataset_ops.Dataset.from_tensor_slices((x_test, y_test)) dataset = dataset.batch(32) return dataset def get_multi_inputs_multi_outputs_data(): (a_train, c_train), (a_test, c_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=3, random_seed=_RANDOM_SEED) (b_train, d_train), (b_test, d_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=2, random_seed=_RANDOM_SEED) (m_train, _), (m_test, _) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(8,), num_classes=2, random_seed=_RANDOM_SEED) c_train = keras.utils.to_categorical(c_train) c_test = keras.utils.to_categorical(c_test) d_train = keras.utils.to_categorical(d_train) d_test = keras.utils.to_categorical(d_test) train_data = { 'input_a': a_train, 'input_b': b_train, 'input_m': m_train, 'output_c': c_train, 'output_d': d_train } test_data = { 'input_a': a_test, 'input_b': b_test, 'input_m': m_test, 'output_c': c_test, 'output_d': d_test } return (train_data, test_data) def batch_wrapper(dataset, batch_size, distribution, repeat=None): if repeat: dataset = dataset.repeat(repeat) # TPUs currently require fully defined input shapes, drop_remainder ensures # the input will have fully defined shapes. if isinstance(distribution, tpu_strategy.TPUStrategy): return dataset.batch(batch_size, drop_remainder=True) else: return dataset.batch(batch_size) def get_model(): x = keras.layers.Input(shape=(3,), name='input') y = keras.layers.Dense(4, name='dense')(x) model = keras.Model(x, y) return model def get_dataset(distribution): inputs = np.zeros((10, 3), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 10, distribution) return dataset def get_predict_dataset(distribution): inputs = np.zeros((10, 3), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices(inputs) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 10, distribution) return dataset def multi_input_output_model(): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(5,), name='input_b') # TODO(anjalisridhar): Change the output dimension of the second Dense layer # once the iterator output validation issue has been fixed. dense_1 = keras.layers.Dense(7, name='dense_1') dense_2 = keras.layers.Dense(7, name='dense_2') c = dense_1(a) d = dense_2(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) return model def get_correctness_test_inputs(use_numpy, use_validation_data, with_distribution, x_train, y_train, x_predict): """Generates the inputs for correctness check when enable Keras with DS.""" training_epochs = 2 global_batch_size = 64 batch_size = global_batch_size # TODO(b/118776054): Use global batch size for Keras/DS support. use_per_core_batch_size = ( with_distribution and not distributed_training_utils.global_batch_size_supported( with_distribution)) if use_per_core_batch_size: batch_size //= with_distribution.num_replicas_in_sync if use_numpy: training_inputs = { 'batch_size': batch_size, 'x': x_train, 'y': y_train, 'epochs': training_epochs, 'shuffle': False, } if use_validation_data: eval_inputs = None training_inputs['validation_data'] = (x_train, y_train) else: eval_inputs = { 'batch_size': batch_size, 'x': x_train, 'y': y_train, } predict_inputs = { 'x': np.array(x_predict, dtype=np.float32), } else: # For dataset inputs, we do not pass batch_size to # keras.fit/evaluate/predict. The batch size is part of the dataset. train_dataset = dataset_ops.Dataset.from_tensor_slices( (x_train, y_train)) x = batch_wrapper( train_dataset, batch_size, with_distribution, repeat=training_epochs) training_inputs = { 'batch_size': None, 'x': x, 'y': None, 'epochs': training_epochs, 'shuffle': False, 'steps_per_epoch': len(x_train) // global_batch_size, } if use_validation_data: eval_inputs = None # Remove the eval_inputs eval_dataset = dataset_ops.Dataset.from_tensor_slices( (x_train, y_train)) x = batch_wrapper(eval_dataset, batch_size, with_distribution) training_inputs['validation_data'] = x training_inputs['validation_steps'] = 5 else: eval_inputs = { 'batch_size': None, 'x': x, 'y': None, 'steps': 20, } predict_batch_size = len(x_predict) if use_per_core_batch_size: predict_batch_size //= with_distribution.num_replicas_in_sync predict_dataset = dataset_ops.Dataset.from_tensor_slices(x_predict) predict_dataset = batch_wrapper(predict_dataset, predict_batch_size, with_distribution) predict_inputs = { 'steps': 1, 'x': predict_dataset, } return training_inputs, eval_inputs, predict_inputs strategies_minus_tpu = [ combinations.default_strategy, combinations.one_device_strategy, combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus] tpu_strategies = [ combinations.tpu_strategy, # steps_per_run=2 combinations.tpu_strategy_one_step] def strategy_minus_tpu_combinations(): return combinations.combine( distribution=strategies_minus_tpu, mode=['graph', 'eager']) def tpu_strategy_combinations(): return combinations.combine( distribution=tpu_strategies, mode=['graph']) def all_strategy_combinations(): return strategy_minus_tpu_combinations() + tpu_strategy_combinations() # TODO(priyag): Add v2 optimizers here. def strategy_and_optimizer_combinations(): return combinations.times( all_strategy_combinations(), combinations.combine( optimizer=[combinations.adagrad_optimizer_v1_fn, combinations.adam_optimizer_v1_fn, combinations.gradient_descent_optimizer_v1_fn, combinations.rmsprop_optimizer_v1_fn])) def strategy_and_input_combinations(): return ( combinations.times( combinations.combine(distribution=strategies_minus_tpu), combinations.combine(mode=['graph'], use_numpy=[True, False], use_validation_data=[True, False]) + combinations.combine(mode=['eager'], use_numpy=[False], use_validation_data=[False])) + combinations.times( combinations.combine(distribution=tpu_strategies), combinations.combine(mode=['graph'], use_numpy=[True, False], use_validation_data=[True, False]))) def strategy_for_numpy_input_combinations(): return combinations.combine( distribution=strategies_minus_tpu + tpu_strategies, mode=['graph']) class TestDistributionStrategyWithNumpyArrays(test.TestCase, parameterized.TestCase): @combinations.generate(strategy_for_numpy_input_combinations()) def test_calling_model_with_numpy_arrays(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) inputs = np.zeros((64, 3), dtype=np.float32) targets = np.zeros((64, 4), dtype=np.float32) # Call fit with validation data model.fit(inputs, targets, epochs=1, batch_size=2, verbose=0, validation_data=(inputs, targets)) # TODO(anjalisridhar): We need tests for when the batch size and steps are # smaller and results in a 0 batch_size and steps value. model.evaluate(inputs, targets) # with steps model.evaluate(inputs, targets, steps=2) # with batch_size model.evaluate(inputs, targets, batch_size=8) model.predict(inputs) # with steps model.predict(inputs, steps=2) # with batch_size model.predict(inputs, batch_size=8) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calling_model_with_nested_numpy_arrays(self, distribution): with self.cached_session(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) input_a_np = np.asarray(np.random.random((64, 3)), dtype=np.float32) input_b_np = np.asarray(np.random.random((64, 5)), dtype=np.float32) inputs = [input_a_np, input_b_np] output_d_np = np.asarray(np.random.random((64, 7)), dtype=np.float32) output_e_np = np.asarray(np.random.random((64, 7)), dtype=np.float32) targets = [output_d_np, output_e_np] # Call fit with validation data model.fit(inputs, targets, epochs=1, batch_size=8, verbose=0) # TODO(anjalisridhar): We need tests for when the batch size and steps are # smaller and results in a 0 batch_size and steps value. model.evaluate(inputs, targets) # with steps model.evaluate(inputs, targets, steps=2) # with batch_size model.evaluate(inputs, targets, batch_size=8) model.predict(inputs) # with steps model.predict(inputs, steps=2) # with batch_size model.predict(inputs, batch_size=8) @combinations.generate(combinations.combine( distribution=strategies_minus_tpu, mode=['graph'])) def test_numpy_with_sample_weights(self, distribution): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) inputs = np.zeros((20, 3), np.float32) targets = np.zeros((20, 4), np.float32) sample_weights = np.ones((20), np.float32) model.fit(inputs, targets, sample_weight=sample_weights, epochs=1, steps_per_epoch=2, verbose=1) @combinations.generate(strategy_for_numpy_input_combinations()) def test_flatten_predict_outputs(self, distribution): with self.cached_session(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) # We take 6 input samples with each input having a dimension of 3 or 5. input_a_np = np.asarray(np.random.random((6, 3)), dtype=np.float32) input_b_np = np.asarray(np.random.random((6, 5)), dtype=np.float32) inputs = [input_a_np, input_b_np] outs = model.predict(inputs, steps=1) # `predict` a list that is equal in length to the number of model outputs. # In this test our model has two outputs and each element of `outs` # corresponds to all the samples of one of the model outputs. self.assertLen(outs, 2) # Each of the output samples have a dimension of 7. We should process all # the available input samples(6). self.assertAllEqual([6, 7], outs[0].shape) self.assertAllEqual([6, 7], outs[1].shape) class TestDistributionStrategyWithDatasets(test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_calling_model_on_same_dataset(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) dataset = get_dataset(distribution) # Call fit with validation data model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_data=dataset, validation_steps=2) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_data=dataset, validation_steps=2) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(all_strategy_combinations()) def test_model_interleaved_eval_same_as_direct_eval(self, distribution): with self.cached_session(): user_controlled_model = get_model() user_controlled_model.compile( gradient_descent.GradientDescentOptimizer(0.001), loss='mse', metrics=['mae', keras.metrics.CategoricalAccuracy()], distribute=distribution) interleaved_model = get_model() interleaved_model.set_weights(user_controlled_model.get_weights()) interleaved_model.compile( gradient_descent.GradientDescentOptimizer(0.001), loss='mse', metrics=['mae', keras.metrics.CategoricalAccuracy()], distribute=distribution) dataset = get_dataset(distribution) # Call fit with validation interleaved interleaved_output = interleaved_model.fit( dataset, epochs=2, steps_per_epoch=2, verbose=1, validation_data=dataset, validation_steps=2, shuffle=False) # Manually control the validation running after each epoch. user_controlled_output = [] for _ in range(2): user_controlled_model.fit( dataset, epochs=1, steps_per_epoch=2, verbose=1, shuffle=False) user_controlled_output.append( user_controlled_model.evaluate(dataset, steps=2)) self.assertEqual(interleaved_output.history['val_loss'], [x[0] for x in user_controlled_output]) self.assertEqual(interleaved_output.history['val_mean_absolute_error'], [x[1] for x in user_controlled_output]) self.assertEqual(interleaved_output.history['val_categorical_accuracy'], [x[2] for x in user_controlled_output]) # TODO(priyag): Enable this test for TPU. Currently tuples/dict don't work # as clone_model's input_tensors argument only seems to accept list and not # tuples or dict. @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_fit_with_tuple_and_dict_dataset_inputs(self, distribution): with self.cached_session(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 5)) output_d_np = np.random.random((10, 7)) output_e_np = np.random.random((10, 7)) # Test with tuples dataset_tuple = dataset_ops.Dataset.from_tensor_slices(( (input_a_np, input_b_np), (output_d_np, output_e_np))) dataset_tuple = dataset_tuple.repeat(100) dataset_tuple = dataset_tuple.batch(10) model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1) # Test with dict dataset_dict = dataset_ops.Dataset.from_tensor_slices(( {'input_a': input_a_np, 'input_b': input_b_np}, (output_d_np, output_e_np))) dataset_dict = dataset_dict.repeat(100) dataset_dict = dataset_dict.batch(10) model.fit(dataset_dict, epochs=1, steps_per_epoch=2, verbose=1) @combinations.generate(all_strategy_combinations()) def test_fit_eval_and_predict_methods_on_dataset(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) dataset = get_dataset(distribution) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(strategy_and_optimizer_combinations()) def test_fit_eval_and_predict_with_optimizer(self, distribution, optimizer): with self.cached_session(): model = get_model() loss = 'mse' model.compile(optimizer(), loss, distribute=distribution) dataset = get_dataset(distribution) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(strategy_minus_tpu_combinations()) def test_dataset_with_sample_weights(self, distribution): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) inputs = np.zeros((10, 3), np.float32) targets = np.zeros((10, 4), np.float32) sample_weights = np.ones((10), np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets, sample_weights)) dataset = dataset.repeat() dataset = dataset.batch(10) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(dataset, steps=2) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) # TODO(b/120943676, b/120957836): Re-enable once the validation code is # restored. def DISABLED_test_dataset_wrong_input_shape(self, distribution): with self.cached_session(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) # Wrong input shape inputs = np.zeros((10, 5), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) dataset = dataset.batch(10) with self.assertRaisesRegexp(ValueError, 'expected input to have shape'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[combinations.mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) # TODO(b/120943676, b/120957836): Re-enable once the validation code is # restored. def DISABLED_test_dataset_no_batch_input_validation(self, distribution): with self.cached_session(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) # User forgets to batch the dataset inputs = np.zeros((10, 3), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) with self.assertRaisesRegexp(ValueError, 'expected input to have shape'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[combinations.tpu_strategy_one_step], mode=['graph'])) def test_dataset_input_shape_fully_defined(self, distribution): with self.cached_session(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) dataset = get_dataset(distribution) # Input shapes are not fully known. Batch dimension is unknown as we are # not using the drop_remainder argument. dataset = dataset.repeat(100).batch(10) with self.assertRaisesRegexp(ValueError, 'requires fully defined shapes'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus], mode=['graph', 'eager'])) def test_learning_phase_value(self, distribution): # TODO(anjalisridhar): Modify this test to use Lambdas since we can compare # meaningful values. Currently we don't pass the learning phase if the # Lambda layer uses the learning phase. with self.cached_session(): x = keras.layers.Input(shape=(1,), name='input') y = keras.layers.Dense(1, kernel_initializer='ones')(x) z = keras.layers.Dropout(0.9999)(y) model = keras.Model(x, z) initial_weights = model.get_weights() optimizer = gradient_descent.GradientDescentOptimizer(0.005) loss = 'mse' metrics = ['acc'] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) batch_size = 8 if isinstance(distribution, mirrored_strategy.CoreMirroredStrategy): # CoreMirroredStrategy uses global batch size. batch_size = 8 * distribution.num_replicas_in_sync inputs = np.ones((10, 1), dtype=np.float32) targets = np.ones((10, 1), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat().batch(batch_size) hist = model.fit(dataset, epochs=1, steps_per_epoch=20, verbose=1) self.assertAlmostEqual(hist.history['acc'][0], 0, 0) model.set_weights(initial_weights) # TODO(psv/anjalisridhar): Enable these lines after we fix b/117431185. # evaluate_output = model.evaluate(dataset, steps=20) # self.assertAlmostEqual(evaluate_output[1], 1, 0) inputs = np.ones((10, 1), dtype=np.float32) predict_dataset = dataset_ops.Dataset.from_tensor_slices(inputs) predict_dataset = predict_dataset.repeat().batch(batch_size) output = model.predict(predict_dataset, steps=10) # `predict` runs for 10 steps ref_output = np.ones((160, 1), dtype=np.float32) self.assertArrayNear(output, ref_output, 1e-1) @combinations.generate(strategy_minus_tpu_combinations()) def testOptimizerWithCallbacks(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent_keras.SGD(0.01) loss = 'mse' model.compile(optimizer, loss, distribute=distribution) dataset = get_dataset(distribution) def schedule(_): return 0.001 model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.LearningRateScheduler(schedule)]) grouped_models = distribution.unwrap(model._distributed_model) with distribution.scope(): for m in grouped_models: self.assertAllClose(0.001, keras.backend.get_value( m.optimizer.lr), atol=1e-05, rtol=1e-05) class TestDistributionStrategyErrorCases(test.TestCase, parameterized.TestCase): @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_unsupported_features(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) dataset = get_dataset(distribution) # Test with validation split with self.assertRaisesRegexp( ValueError, '`validation_split` argument is not ' 'supported when input `x` is a dataset or a ' 'dataset iterator.+'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_split=0.5, validation_steps=2) # Test with sample weight. sample_weight = np.random.random((10,)) with self.assertRaisesRegexp( ValueError, '`sample_weight` argument is not supported when input ' '`x` is a dataset or a dataset iterator.'): model.fit( dataset, epochs=1, steps_per_epoch=2, verbose=0, sample_weight=sample_weight) # Test with not specifying the `steps` argument. with self.assertRaisesRegexp( ValueError, 'the `steps_per_epoch` argument'): model.fit(dataset, epochs=1, verbose=0) with self.assertRaisesRegexp(ValueError, 'the `steps` argument'): model.evaluate(dataset, verbose=0) with self.assertRaisesRegexp(ValueError, 'the `steps` argument'): model.predict(dataset, verbose=0) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_calling_with_unsupported_predefined_callbacks(self, distribution): with self.cached_session(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics, distribute=distribution) dataset = get_dataset(distribution) def schedule(_): return 0.001 with self.assertRaisesRegexp(ValueError, 'You must specify a Keras Optimizer V2 when ' 'using'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.LearningRateScheduler(schedule)]) with self.assertRaisesRegexp(ValueError, 'You must specify a Keras Optimizer V2 when ' 'using'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.ReduceLROnPlateau()]) class TestDistributionStrategyWithLossMasking(test.TestCase, parameterized.TestCase): # TODO(priyag): Enable all strategies for this test. Currently it does not # work for TPU due to some invalid datatype. @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_masking(self, distribution): with self.cached_session(): np.random.seed(1337) x = np.array([[[1], [1]], [[0], [0]]]) model = keras.models.Sequential() model.add(keras.layers.Masking(mask_value=0, input_shape=(2, 1))) model.add( keras.layers.TimeDistributed( keras.layers.Dense(1, kernel_initializer='one'))) model.compile(loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01), distribute=distribution) y = np.array([[[1], [1]], [[1], [1]]]) dataset = dataset_ops.Dataset.from_tensor_slices((x, y)) dataset = dataset.repeat(100) dataset = dataset.batch(10) hist = model.fit(x=dataset, epochs=1, steps_per_epoch=2) self.assertEqual(hist.history['loss'][0], 0) class TestDistributionStrategyWithNormalizationLayer( test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_batchnorm_correctness(self, distribution): with self.cached_session(): model = keras.models.Sequential() norm = keras.layers.BatchNormalization(input_shape=(10,), momentum=0.8) model.add(norm) model.compile(loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01), distribute=distribution) # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10)) x = x.astype('float32') dataset = dataset_ops.Dataset.from_tensor_slices((x, x)) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 32, distribution) predict_dataset = dataset_ops.Dataset.from_tensor_slices(x) predict_dataset = predict_dataset.repeat(100) predict_dataset = batch_wrapper(predict_dataset, 32, distribution) model.fit(dataset, epochs=4, verbose=0, steps_per_epoch=10) out = model.predict(predict_dataset, steps=2) out -= keras.backend.eval(norm.beta) out /= keras.backend.eval(norm.gamma) np.testing.assert_allclose(out.mean(), 0.0, atol=1e-1) np.testing.assert_allclose(out.std(), 1.0, atol=1e-1) class TestDistributionStrategyCorrectness(test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_metric_correctness(self, distribution): with self.cached_session(): keras.backend.set_image_data_format('channels_last') num_samples = 10000 x_train = np.random.randint(0, 2, num_samples) x_train = np.reshape(x_train, (num_samples, 1)) y_train = x_train x_train = x_train.astype('float32') y_train = y_train.astype('float32') # Create identity model. model = keras.Sequential() model.add( keras.layers.Dense(1, input_shape=(1,), kernel_initializer='ones')) model.compile( loss=keras.losses.mean_squared_error, optimizer=gradient_descent.GradientDescentOptimizer(0.5), metrics=[keras.metrics.BinaryAccuracy()], distribute=distribution) batch_size = 64 if not distributed_training_utils.global_batch_size_supported( distribution): batch_size //= distribution.num_replicas_in_sync train_dataset = dataset_ops.Dataset.from_tensor_slices((x_train, y_train)) train_dataset = batch_wrapper(train_dataset, batch_size, distribution) history = model.fit(x=train_dataset, epochs=2, steps_per_epoch=10) self.assertEqual(history.history['binary_accuracy'], [1.0, 1.0]) @combinations.generate(all_strategy_combinations()) def test_eval_metrics_correctness(self, distribution): with self.cached_session(): model = keras.Sequential() model.add( keras.layers.Dense( 3, activation='relu', input_dim=4, kernel_initializer='ones')) model.add( keras.layers.Dense( 1, activation='sigmoid', kernel_initializer='ones')) model.compile( loss='mae', metrics=['accuracy', keras.metrics.BinaryAccuracy()], optimizer=gradient_descent.GradientDescentOptimizer(0.001), distribute=distribution) # verify correctness of stateful and stateless metrics. x = np.ones((100, 4)).astype('float32') y = np.ones((100, 1)).astype('float32') dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).repeat() dataset = batch_wrapper(dataset, 4, distribution) outs = model.evaluate(dataset, steps=10) self.assertEqual(outs[1], 1.) self.assertEqual(outs[2], 1.) y = np.zeros((100, 1)).astype('float32') dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).repeat() dataset = batch_wrapper(dataset, 4, distribution) outs = model.evaluate(dataset, steps=10) self.assertEqual(outs[1], 0.) self.assertEqual(outs[2], 0.) @combinations.generate(strategy_and_input_combinations()) def test_correctness(self, distribution, use_numpy, use_validation_data): with self.cached_session(): default_tolerance = 1e-5 tol_table = {} if isinstance(distribution, ( mirrored_strategy.MirroredStrategy, mirrored_strategy.CoreMirroredStrategy, distribute_lib._DefaultDistributionStrategy)): # pylint: disable=protected-access # TODO(b/119257215): Weights are not exactly the same, so use larger # tolerance for now. Predict should be related to weights. tol_table = { 'weights_1': 1e-4, 'weights_2': 1e-4, 'predict_result_1': 1e-4, } keras.backend.set_image_data_format('channels_last') np.random.seed(_RANDOM_SEED) random_seed.set_random_seed(_RANDOM_SEED) # Train, eval, and predict datasets are created with the same input numpy # arrays. # TODO(xiejw): Change this back to 10000, once we support final partial # batch. num_samples = 9984 x_train = np.random.rand(num_samples, 1) y_train = 3 * x_train x_train = x_train.astype('float32') y_train = y_train.astype('float32') x_predict = [[1.], [2.], [3.], [4.]] # The model is built once and the initial weights are saved. # This is used to initialize the model for both the distribution and # non-distribution run. In addition, we add few non-linear layers to make # it non-trivial. def _create_model(): model = keras.Sequential() model.add(keras.layers.Dense(10, activation='relu', input_shape=(1,))) model.add(keras.layers.Dense(10, activation='relu')) model.add(keras.layers.Dense(10, activation='relu')) model.add(keras.layers.Dense(1)) return model model = _create_model() initial_weights = model.get_weights() del model # avoid accident usage. def fit_eval_and_predict(with_distribution=None): model = _create_model() # We have initialized the model to the same weight for the distribution # and non-distribution run. model.set_weights(initial_weights) model.compile( loss=keras.losses.mean_squared_error, optimizer=gradient_descent_keras.SGD(0.5), metrics=['mse'], distribute=with_distribution) training_inputs, eval_inputs, predict_inputs = ( get_correctness_test_inputs(use_numpy, use_validation_data, with_distribution, x_train, y_train, x_predict)) result = {} result['training_history_1'] = model.fit(**training_inputs).history if eval_inputs is not None: result['eval_result_1'] = model.evaluate(**eval_inputs) result['weights_1'] = model.get_weights() result['predict_result_1'] = model.predict(**predict_inputs) # Train and eval again to mimic user's flow. result['training_history_2'] = model.fit(**training_inputs).history if eval_inputs is not None: result['eval_result_2'] = model.evaluate(**eval_inputs) result['weights_2'] = model.get_weights() return result results_with_ds = fit_eval_and_predict(with_distribution=distribution) results_without_ds = fit_eval_and_predict(with_distribution=None) # Verify that the weights, training history, eval results, predict outputs # are the same within some limits of tolerance. for key in results_with_ds: if (key.startswith('training_history') and isinstance(distribution, tpu_strategy.TPUStrategy) and distribution.extended.steps_per_run > 1): # TODO(b/119894254): Enable this test for all cases once the # underlying bug is fixed. continue tolerance = tol_table.get(key, default_tolerance) self.assertAllClose( results_with_ds[key], results_without_ds[key], atol=tolerance, rtol=tolerance, msg='Fail to assert {}.'.format(key)) if __name__ == '__main__': test.main()
{ "content_hash": "9120081aa40f7d7cd1aea99f49ab237b", "timestamp": "", "source": "github", "line_count": 1057, "max_line_length": 92, "avg_line_length": 38.23084200567644, "alnum_prop": 0.6515466468695867, "repo_name": "apark263/tensorflow", "id": "92de8e643e7588365c23dc8513e197c0869c9ecf", "size": "41099", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tensorflow/contrib/distribute/python/keras_backward_compat_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2867" }, { "name": "Batchfile", "bytes": "14734" }, { "name": "C", "bytes": "561314" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "54581021" }, { "name": "CMake", "bytes": "207169" }, { "name": "Dockerfile", "bytes": "39024" }, { "name": "Go", "bytes": "1373561" }, { "name": "HTML", "bytes": "4680118" }, { "name": "Java", "bytes": "899393" }, { "name": "Jupyter Notebook", "bytes": "2618454" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "75994" }, { "name": "Objective-C", "bytes": "16140" }, { "name": "Objective-C++", "bytes": "102889" }, { "name": "PHP", "bytes": "14340" }, { "name": "Pascal", "bytes": "399" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "44616385" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "838" }, { "name": "Shell", "bytes": "504099" }, { "name": "Smarty", "bytes": "10072" } ], "symlink_target": "" }
/* Title: YouTube Bots Description: Bots for youtube.com. Nav: hidden */ ![This is EXACTLY what YouTube is like.](/content/images/illustrations/battle-nile.jpg){.float-right} ***This is a fairly new section: [would you like to contribute](https://github.com/botwiki/botwiki.org)?*** Bots for [YouTube](https://www.youtube.com/), *"a video-sharing website"* [<sup>[Wikipedia]</sup>](https://en.wikipedia.org/wiki/YouTube). Some examples include: - [Treasure Column](/bots/youtube-bots/treasurecolumn) -- footage from unsecured network cameras presented as aesthetic, rather than intrusive Browse [more YouTube bots](/tag/youtubebot), learn [how to make one](/tutorials/youtube-bots), or [return to the **Bots** page](/bots).
{ "content_hash": "ae81e89de3bd15e823e587f29b22c0b9", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 142, "avg_line_length": 40.611111111111114, "alnum_prop": 0.7359781121751026, "repo_name": "tullyhansen/botwiki.org", "id": "3e9811d6f40d65361c38c3bd380beaa093a0f189", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/bots/youtube-bots/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "768" }, { "name": "CSS", "bytes": "18505" }, { "name": "HTML", "bytes": "20523" }, { "name": "JavaScript", "bytes": "14055" }, { "name": "PHP", "bytes": "36230" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `POSIX_FADV_WILLNEED` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, POSIX_FADV_WILLNEED"> <title>libc::POSIX_FADV_WILLNEED - Rust</title> <link rel="stylesheet" type="text/css" href="../normalize.css"> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc constant"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'POSIX_FADV_WILLNEED', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"> <h1 class='fqn'><span class='in-band'>Constant <a href='index.html'>libc</a>::<wbr><a class="constant" href=''>POSIX_FADV_WILLNEED</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../src/libc/unix/notbsd/mod.rs.html#728' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const POSIX_FADV_WILLNEED: <a class="type" href="../libc/type.c_int.html" title="type libc::c_int">c_int</a><code> = </code><code>3</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
{ "content_hash": "b1691eb8f1e22f45195a1e5419121901", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 207, "avg_line_length": 38.50442477876106, "alnum_prop": 0.5143645139048495, "repo_name": "nitro-devs/nitro-game-engine", "id": "d47fb8a49ddc25db7814a0c50822dbcfddc851f0", "size": "4361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/libc/constant.POSIX_FADV_WILLNEED.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ], "symlink_target": "" }
'use strict'; describe('require test', function () { it('should require args in order', function () { var req = global.required; expect(req.indexOf('a.js')).to.equal(0); expect(req.indexOf('b.coffee')).to.equal(1); expect(req.indexOf('c.js')).to.equal(2); expect(req.indexOf('d.coffee')).to.equal(3); }); });
{ "content_hash": "280a1b73612e0c222c1293eae41d2f08", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 50, "avg_line_length": 30.363636363636363, "alnum_prop": 0.6167664670658682, "repo_name": "sul4bh/mocha", "id": "f959a859a814ecbbd5c35ee15df99ef7022e7ec5", "size": "334", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "test/acceptance/require/require.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5616" }, { "name": "CoffeeScript", "bytes": "212" }, { "name": "HTML", "bytes": "7143" }, { "name": "JavaScript", "bytes": "861775" }, { "name": "Makefile", "bytes": "4775" }, { "name": "Shell", "bytes": "2944" } ], "symlink_target": "" }
<?php class TestCase extends Illuminate\Foundation\Testing\TestCase { /** * Default preparation for each test */ public function setUp() { parent::setUp(); Artisan::call('migrate'); Session::start(); Mail::pretend(true); Route::enableFilters(); } public function tearDown() { parent::tearDown(); Artisan::call('migrate:reset'); } /** * Creates the application. * * @return Symfony\Component\HttpKernel\HttpKernelInterface */ public function createApplication() { $unitTesting = true; $testEnvironment = 'testing'; return require __DIR__ . '/../../bootstrap/start.php'; } }
{ "content_hash": "a2441f6e1a7136952c4ce543b3ece599", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 63, "avg_line_length": 23.322580645161292, "alnum_prop": 0.5698478561549101, "repo_name": "TransComics/TransBubbles", "id": "6bbc0e085da0910327de7fba441cfec8248343d3", "size": "723", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/tests/TestCase.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "15219" }, { "name": "JavaScript", "bytes": "744969" }, { "name": "PHP", "bytes": "1123895" } ], "symlink_target": "" }
package org.onosproject.net.flowobjective; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableList; import org.onosproject.core.ApplicationId; import org.onosproject.net.flow.criteria.Criteria; import org.onosproject.net.flow.criteria.Criterion; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Default implementation of a filtering objective. */ @Beta public final class DefaultFilteringObjective implements FilteringObjective { private final Type type; private final boolean permanent; private final int timeout; private final ApplicationId appId; private final int priority; private final Criterion key; private final List<Criterion> conditions; private final int id; private final Operation op; private final Optional<ObjectiveContext> context; private DefaultFilteringObjective(Type type, boolean permanent, int timeout, ApplicationId appId, int priority, Criterion key, List<Criterion> conditions, Operation op) { this.key = key; this.type = type; this.permanent = permanent; this.timeout = timeout; this.appId = appId; this.priority = priority; this.conditions = conditions; this.op = op; this.context = Optional.empty(); this.id = Objects.hash(type, key, conditions, permanent, timeout, appId, priority); } public DefaultFilteringObjective(Type type, boolean permanent, int timeout, ApplicationId appId, int priority, Criterion key, List<Criterion> conditions, ObjectiveContext context, Operation op) { this.key = key; this.type = type; this.permanent = permanent; this.timeout = timeout; this.appId = appId; this.priority = priority; this.conditions = conditions; this.op = op; this.context = Optional.ofNullable(context); this.id = Objects.hash(type, key, conditions, permanent, timeout, appId, priority); } @Override public Criterion key() { return key; } @Override public Type type() { return this.type; } @Override public Collection<Criterion> conditions() { return conditions; } @Override public int id() { return id; } @Override public int priority() { return priority; } @Override public ApplicationId appId() { return appId; } @Override public int timeout() { return timeout; } @Override public boolean permanent() { return permanent; } @Override public Operation op() { return op; } @Override public Optional<ObjectiveContext> context() { return context; } /** * Returns a new builder. * * @return new builder */ public static Builder builder() { return new Builder(); } public static final class Builder implements FilteringObjective.Builder { private final ImmutableList.Builder<Criterion> listBuilder = ImmutableList.builder(); private Type type; private boolean permanent = DEFAULT_PERMANENT; private int timeout = DEFAULT_TIMEOUT; private ApplicationId appId; private int priority = DEFAULT_PRIORITY; private Criterion key = Criteria.dummy(); @Override public Builder withKey(Criterion key) { this.key = key; return this; } @Override public Builder addCondition(Criterion criterion) { listBuilder.add(criterion); return this; } @Override public Builder permit() { this.type = Type.PERMIT; return this; } @Override public Builder deny() { this.type = Type.DENY; return this; } @Override public Builder makeTemporary(int timeout) { this.timeout = timeout; permanent = false; return this; } @Override public Builder makePermanent() { permanent = true; return this; } @Override public Builder fromApp(ApplicationId appId) { this.appId = appId; return this; } @Override public Builder withPriority(int priority) { this.priority = priority; return this; } @Override public FilteringObjective add() { List<Criterion> conditions = listBuilder.build(); checkNotNull(type, "Must have a type."); checkArgument(!conditions.isEmpty(), "Must have at least one condition."); checkNotNull(appId, "Must supply an application id"); return new DefaultFilteringObjective(type, permanent, timeout, appId, priority, key, conditions, Operation.ADD); } @Override public FilteringObjective remove() { List<Criterion> conditions = listBuilder.build(); checkNotNull(type, "Must have a type."); checkArgument(!conditions.isEmpty(), "Must have at least one condition."); checkNotNull(appId, "Must supply an application id"); return new DefaultFilteringObjective(type, permanent, timeout, appId, priority, key, conditions, Operation.REMOVE); } @Override public FilteringObjective add(ObjectiveContext context) { List<Criterion> conditions = listBuilder.build(); checkNotNull(type, "Must have a type."); checkArgument(!conditions.isEmpty(), "Must have at least one condition."); checkNotNull(appId, "Must supply an application id"); return new DefaultFilteringObjective(type, permanent, timeout, appId, priority, key, conditions, context, Operation.ADD); } @Override public FilteringObjective remove(ObjectiveContext context) { List<Criterion> conditions = listBuilder.build(); checkNotNull(type, "Must have a type."); checkArgument(!conditions.isEmpty(), "Must have at least one condition."); checkNotNull(appId, "Must supply an application id"); return new DefaultFilteringObjective(type, permanent, timeout, appId, priority, key, conditions, context, Operation.REMOVE); } } }
{ "content_hash": "b3b93f56eb413d9f84da706fe25e5fb4", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 87, "avg_line_length": 29.491869918699187, "alnum_prop": 0.5714679531357685, "repo_name": "CNlukai/onos-gerrit-test", "id": "e5589b4b1b0b97c6d5896d71e6d278dd62b6bb90", "size": "7864", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/api/src/main/java/org/onosproject/net/flowobjective/DefaultFilteringObjective.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "63372" }, { "name": "HTML", "bytes": "450778" }, { "name": "Java", "bytes": "8660456" }, { "name": "JavaScript", "bytes": "584872" }, { "name": "Shell", "bytes": "2625" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "af3496e87d707d0a8e4d7953baaa22f3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "0b342c7726c1b9542b4bc80de5112903d60a8505", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Liliales/Liliaceae/Gagea/Gagea villosa/ Syn. Gagea villosa hybrida/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package services.application import connectors.OnlineTestEmailClient import model.EvaluationResults.{ Green, Red } import model._ import model.exchange.FsbScoresAndFeedback import model.persisted.fsb.ScoresAndFeedback import model.persisted.{ ContactDetails, FsbTestGroup, SchemeEvaluationResult } import org.mockito.ArgumentMatchers.{ eq => eqTo, _ } import org.mockito.Mockito._ import repositories.SchemeRepository import repositories.application.GeneralApplicationMongoRepository import repositories.contactdetails.ContactDetailsRepository import repositories.fsb.FsbRepository import services.scheme.SchemePreferencesService import testkit.MockitoImplicits._ import testkit.{ ExtendedTimeout, UnitSpec } import uk.gov.hmrc.http.HeaderCarrier import scala.concurrent.Await import scala.concurrent.duration._ class FsbServiceSpec extends UnitSpec with ExtendedTimeout { "find scores and feedback" must { "handle no data" in new TestFixture { when(mockFsbRepo.findScoresAndFeedback(any[String])).thenReturnAsync(None) val result = service.findScoresAndFeedback(appId).futureValue result mustBe None } "handle data" in new TestFixture { when(mockFsbRepo.findScoresAndFeedback(any[String])).thenReturnAsync(Some(ScoresAndFeedback(1.12, "feedback"))) val result = service.findScoresAndFeedback(appId).futureValue result mustBe Some(FsbScoresAndFeedback(1.12, "feedback")) } } "fsb evaluation" must { "evaluate scheme to Eligible for Job Offer if results are Green" in new TestFixture { val res = FsbTestGroup(List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString))) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(res)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(res.evaluation.result) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_PASSED)).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER)).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER) } "evaluate scheme to Final FAILED if results are red and no more schemes selected" in new TestFixture { val curSchemeStatus = List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString)) val res = FsbTestGroup(List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString))) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(res)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), res.evaluation.result)).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED) } "fail to evaluate scheme GES_DS if FCO results were not submitted" in new TestFixture { val curSchemeStatus = List( SchemeEvaluationResult(SchemeId("DigitalDataTechnologyAndCyber"), Red.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString) ) val res = FsbTestGroup(List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString))) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(res)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), res.evaluation.result)).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() intercept[IllegalArgumentException] { Await.result(service.evaluateFsbCandidate(uid)(hc), 1.second) } } "evaluate DS as failed, and then GES_DS as failed too, but do not evaluate GES as EAC evaluation hasn't happened yet" in new TestFixture { val curSchemeStatus = List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) ) val res = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString) )) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(res)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) // DS when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) ) )).thenReturnAsync() // GES_DS when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) ) )).thenReturnAsync() // more fsb required when(mockApplicationRepo.find(uid.toString())).thenReturnAsync(Some(cand1)) when(mockContactDetailsRepo.find(cand1.userId)).thenReturnAsync(cd1) when(mockEmailClient.notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any())).thenReturnAsync() Await.result(service.evaluateFsbCandidate(uid)(hc), 2.seconds) verify(mockApplicationRepo, times(2)).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED) } "evaluate scheme GES_DS as failed, and then GES as failed, but finally DS passed" in new TestFixture { val curSchemeStatus = List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString), SchemeEvaluationResult(SchemeId("DigitalDataTechnologyAndCyber"), Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString) ) val res = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Red.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString) )) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(res)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) // GES_DS when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Red.toString), SchemeEvaluationResult(SchemeId("DigitalDataTechnologyAndCyber"), Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString) ) )).thenReturnAsync() // GES when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(uid.toString(), List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Red.toString), SchemeEvaluationResult(SchemeId("DigitalDataTechnologyAndCyber"), Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Red.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString) ) )).thenReturnAsync() // DS when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_PASSED)).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER)).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER) } /** * DiplomaticAndDevelopmentEconomics (code: GES-DS, fsbType: EAC_DS) TODO: clarify with Paul to rename fsbType to EAC_FCO * - GovernmentEconomicsService (code: GES, fsbType: EAC) * - DiplomaticAndDevelopment (code: DS, fsbType: FCO) * * At FSB the separate parts are named correctly: * EAC pass/fail FCO pass/fail previous actual outcome expected outcome (now fixed) * pass fail offered a job fail * */ "Pass the candidate who is only in the running for GES-DS if the candidate passes " + "both the EAC and FCO parts of the fsb" in new TestFixture { val fsbResult = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) )) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(fsbResult)) override val schemes = List(DSSchemeIds.DiplomaticAndDevelopmentEconomics) override val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) // This is the css after FSAC and before FSB evaluation val curSchemeStatus = List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_PASSED)).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER)).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ELIGIBLE_FOR_JOB_OFFER) } "Fail the candidate who is only in the running for GES-DS if the candidate passes " + "the EAC part but fails the DS (FCO) part of the GES_DS fsb" in new TestFixture { val fsbResult = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) )) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(fsbResult)) override val schemes = List(DSSchemeIds.DiplomaticAndDevelopmentEconomics) override val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) // This is the css after FSAC and before FSB evaluation val curSchemeStatus = List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(any[String], any[List[SchemeEvaluationResult]])).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() // Mocking required to send the failure email when(mockApplicationRepo.find(uid.toString())).thenReturnAsync(Some(cand1)) when(mockContactDetailsRepo.find(cand1.userId)).thenReturnAsync(cd1) when(mockEmailClient.notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any())).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED) // verify the failure email is sent out verify(mockEmailClient).notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any[HeaderCarrier]) } "Fail the candidate who is only in the running for GES-DS if the candidate fails the EAC part but passes " + "the DS (FCO) part of the GES_DS fsb. Note the candidate should not be invited to the DS part " + "if they fail the EAC part (so this should never happen unless they also have DS as a separate scheme)" in new TestFixture { val fsbResult = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Red.toString) )) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(fsbResult)) override val schemes = List(DSSchemeIds.DiplomaticAndDevelopmentEconomics) override val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) // This is the css after FSAC and before FSB evaluation val curSchemeStatus = List(SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString)) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(any[String], any[List[SchemeEvaluationResult]])).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() // Mocking required to send the failure email when(mockApplicationRepo.find(uid.toString())).thenReturnAsync(Some(cand1)) when(mockContactDetailsRepo.find(cand1.userId)).thenReturnAsync(cd1) when(mockEmailClient.notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any())).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED) // verify the failure email is sent out verify(mockEmailClient).notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any[HeaderCarrier]) } "Fail the candidate who is in the running for GES-DS and DS schemes who passes the EAC part but fails the FCO part of " + "the GES_DS fsb" in new TestFixture { val fsbResult = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Red.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) )) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(fsbResult)) override val schemes = List(DSSchemeIds.DiplomaticAndDevelopmentEconomics, DSSchemeIds.DiplomaticAndDevelopment) override val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) // This is the css after FSAC and before FSB evaluation val curSchemeStatus = List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString), SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString) ) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(any[String], any[List[SchemeEvaluationResult]])).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() // Mocking required to send the failure email when(mockApplicationRepo.find(uid.toString())).thenReturnAsync(Some(cand1)) when(mockContactDetailsRepo.find(cand1.userId)).thenReturnAsync(cd1) when(mockEmailClient.notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any())).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED) // verify the failure email is sent out verify(mockEmailClient).notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any[HeaderCarrier]) } "Fail the candidate who is in the running for GES-DS and GES schemes who fails the EAC part and passes the FCO part of " + "the GES_DS fsb" in new TestFixture { val fsbResult = FsbTestGroup(List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopment, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Red.toString) )) when(mockFsbRepo.findByApplicationId(uid.toString())).thenReturnAsync(Some(fsbResult)) override val schemes = List(DSSchemeIds.DiplomaticAndDevelopmentEconomics, DSSchemeIds.GovernmentEconomicsService) override val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) when(mockSchemePreferencesService.find(uid.toString())).thenReturnAsync(selectedSchemes) // This is the css after FSAC and before FSB evaluation val curSchemeStatus = List( SchemeEvaluationResult(DSSchemeIds.DiplomaticAndDevelopmentEconomics, Green.toString), SchemeEvaluationResult(DSSchemeIds.GovernmentEconomicsService, Green.toString) ) when(mockApplicationRepo.getCurrentSchemeStatus(uid.toString())).thenReturnAsync(curSchemeStatus) when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.FSB_FAILED)).thenReturnAsync() when(mockFsbRepo.updateCurrentSchemeStatus(any[String], any[List[SchemeEvaluationResult]])).thenReturnAsync() when(mockApplicationRepo.addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED)).thenReturnAsync() // Mocking required to send the failure email when(mockApplicationRepo.find(uid.toString())).thenReturnAsync(Some(cand1)) when(mockContactDetailsRepo.find(cand1.userId)).thenReturnAsync(cd1) when(mockEmailClient.notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any())).thenReturnAsync() service.evaluateFsbCandidate(uid)(hc).futureValue verify(mockApplicationRepo).addProgressStatusAndUpdateAppStatus(uid.toString(), ProgressStatuses.ALL_FSBS_AND_FSACS_FAILED) // verify the failure email is sent out verify(mockEmailClient).notifyCandidateOnFinalFailure(eqTo(cd1.email), eqTo(cand1.name))(any[HeaderCarrier]) } } trait TestFixture { val hc = HeaderCarrier() val uid = UniqueIdentifier.randomUniqueIdentifier val appId = "appId" val mockApplicationRepo = mock[GeneralApplicationMongoRepository] val mockContactDetailsRepo = mock[ContactDetailsRepository] val mockFsbRepo = mock[FsbRepository] val mockSchemeRepo = mock[SchemeRepository] val mockSchemePreferencesService = mock[SchemePreferencesService] val mockEmailClient = mock[OnlineTestEmailClient] //TODO:changed type was EmailClient val cand1 = Candidate("123", None, None, Some("t@t.com"), Some("Leia"), Some("Amadala"), None, None, None, None, None, None, None) val cd1 = ContactDetails(outsideUk = false, Address("line1a"), Some("123"), Some("UK"), "t@t.com", "12345") val service = new FsbService( mockApplicationRepo, mockContactDetailsRepo, mockFsbRepo, mockSchemeRepo, mockSchemePreferencesService, mockEmailClient ) val schemes = List( SchemeId("DigitalDataTechnologyAndCyber"), SchemeId("DiplomaticAndDevelopment"), SchemeId("DiplomaticAndDevelopmentEconomics"), SchemeId("GovernmentEconomicsService") ) val selectedSchemes = SelectedSchemes(schemes, orderAgreed = true, eligible = true) } }
{ "content_hash": "c8091ddd4c0b2c2538092b088ef777c0", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 145, "avg_line_length": 60.2027027027027, "alnum_prop": 0.7716273849607183, "repo_name": "hmrc/fset-faststream", "id": "76b87034af2341d7212215b72a53d7892145aa2e", "size": "22878", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/services/application/FsbServiceSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "15185" }, { "name": "Scala", "bytes": "3419747" }, { "name": "Shell", "bytes": "268" } ], "symlink_target": "" }
<?php namespace Nwidart\Modules\Lumen; use Illuminate\Support\Str; use Nwidart\Modules\Module as BaseModule; class Module extends BaseModule { /** * {@inheritdoc} */ public function getCachedServicesPath(): string { return Str::replaceLast('services.php', $this->getSnakeName() . '_module.php', $this->app->basePath('storage/app/') . 'services.php'); } /** * {@inheritdoc} */ public function registerProviders(): void { foreach ($this->get('providers', []) as $provider) { $this->app->register($provider); } } /** * {@inheritdoc} */ public function registerAliases(): void { } }
{ "content_hash": "b8d34d70edda2ff8fbe1c3d3ac50bb4e", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 142, "avg_line_length": 20.529411764705884, "alnum_prop": 0.5787965616045845, "repo_name": "nWidart/laravel-modules", "id": "a250136069ffc4f0cd648075ac9f15105a8ab5b1", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Lumen/Module.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "13619" }, { "name": "PHP", "bytes": "485465" } ], "symlink_target": "" }
from oslo_log import log as logging from heat.common.i18n import _LE LOG = logging.getLogger(__name__) from zaqarclient.queues.v1 import client as zaqarclient from zaqarclient.transport import errors as zaqar_errors from heat.engine.clients import client_plugin class ZaqarClientPlugin(client_plugin.ClientPlugin): exceptions_module = zaqar_errors service_types = [MESSAGING] = ['messaging'] DEFAULT_TTL = 3600 def _create(self): return self.create_for_tenant(self.context.tenant_id) def create_for_tenant(self, tenant_id): con = self.context if self.auth_token is None: LOG.error(_LE("Zaqar connection failed, no auth_token!")) return None opts = { 'os_auth_token': con.auth_token, 'os_auth_url': con.auth_url, 'os_project_id': tenant_id, 'os_service_type': self.MESSAGING, } auth_opts = {'backend': 'keystone', 'options': opts} conf = {'auth_opts': auth_opts} endpoint = self.url_for(service_type=self.MESSAGING) client = zaqarclient.Client(url=endpoint, conf=conf, version=1.1) return client def is_not_found(self, ex): return isinstance(ex, zaqar_errors.ResourceNotFound)
{ "content_hash": "acb4085b49c150e479a9e7dccf23dedb", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 73, "avg_line_length": 28.17391304347826, "alnum_prop": 0.6319444444444444, "repo_name": "srznew/heat", "id": "ba81c4db7a754a09a3f17aee49798774e4ff1514", "size": "1871", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "heat/engine/clients/os/zaqar.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "6529810" }, { "name": "Shell", "bytes": "33395" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_252) on Fri Aug 20 17:47:57 BST 2021 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class psidev.psi.mi.jami.tab.io.writer.LightMitab27BinaryWriter (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title> <meta name="date" content="2021-08-20"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class psidev.psi.mi.jami.tab.io.writer.LightMitab27BinaryWriter (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../psidev/psi/mi/jami/tab/io/writer/LightMitab27BinaryWriter.html" title="class in psidev.psi.mi.jami.tab.io.writer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?psidev/psi/mi/jami/tab/io/writer/class-use/LightMitab27BinaryWriter.html" target="_top">Frames</a></li> <li><a href="LightMitab27BinaryWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class psidev.psi.mi.jami.tab.io.writer.LightMitab27BinaryWriter" class="title">Uses of Class<br>psidev.psi.mi.jami.tab.io.writer.LightMitab27BinaryWriter</h2> </div> <div class="classUseContainer">No usage of psidev.psi.mi.jami.tab.io.writer.LightMitab27BinaryWriter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../psidev/psi/mi/jami/tab/io/writer/LightMitab27BinaryWriter.html" title="class in psidev.psi.mi.jami.tab.io.writer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?psidev/psi/mi/jami/tab/io/writer/class-use/LightMitab27BinaryWriter.html" target="_top">Frames</a></li> <li><a href="LightMitab27BinaryWriter.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </body> </html>
{ "content_hash": "6a7c2a151f159b8a1371cb663b7c496b", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 177, "avg_line_length": 39.857142857142854, "alnum_prop": 0.6097172441258463, "repo_name": "MICommunity/psi-jami", "id": "921ae8dadeac40ed7e79b290898166c4d74195c7", "size": "5022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/psidev/psi/mi/jami/tab/io/writer/class-use/LightMitab27BinaryWriter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3953" }, { "name": "HTML", "bytes": "2996" }, { "name": "Java", "bytes": "20488264" }, { "name": "JavaScript", "bytes": "22224" }, { "name": "XSLT", "bytes": "25595" } ], "symlink_target": "" }
<resources> <string name="app_name">GyroWiFiServer</string> </resources>
{ "content_hash": "f5ac0d047aa06a8e95617f04abd1db3f", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 51, "avg_line_length": 25.666666666666668, "alnum_prop": 0.7142857142857143, "repo_name": "zll5267/gyro", "id": "6a64f61a324b3acee4e8aaefc700f31bd0188afa", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GyroWiFiServer/app/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "31117" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using BlueSheep.Common.Protocol.Types; using BlueSheep.Common.IO; using BlueSheep.Engine.Types; namespace BlueSheep.Common.Protocol.Messages { public class ExchangeGoldPaymentForCraftMessage : Message { public new const uint ID =5833; public override uint ProtocolID { get { return ID; } } public bool onlySuccess; public int goldSum; public ExchangeGoldPaymentForCraftMessage() { } public ExchangeGoldPaymentForCraftMessage(bool onlySuccess, int goldSum) { this.onlySuccess = onlySuccess; this.goldSum = goldSum; } public override void Serialize(BigEndianWriter writer) { writer.WriteBoolean(onlySuccess); writer.WriteVarInt(goldSum); } public override void Deserialize(BigEndianReader reader) { onlySuccess = reader.ReadBoolean(); goldSum = reader.ReadVarInt(); if (goldSum < 0) throw new Exception("Forbidden value on goldSum = " + goldSum + ", it doesn't respect the following condition : goldSum < 0"); } } }
{ "content_hash": "3686510e9fc61a7abb4e8f22a9b91060", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 142, "avg_line_length": 27.829787234042552, "alnum_prop": 0.595565749235474, "repo_name": "Sadikk/BlueSheep", "id": "3dff9d4faf39bdac22ff20af43b10bef2e738496", "size": "1354", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "BlueSheep/Common/Protocol/messages/game/inventory/exchanges/ExchangeGoldPaymentForCraftMessage.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2826218" }, { "name": "Visual Basic", "bytes": "9784" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in J. Bot. 4: 313 (1845) #### Original name Sphaeria rhodomphala Berk., 1845 ### Remarks null
{ "content_hash": "f20a070c3f59d50500bf639aebe0aff1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 13.692307692307692, "alnum_prop": 0.6910112359550562, "repo_name": "mdoering/backbone", "id": "06eeeb9b68cfebfdbf38a7e6bfef29f4e3769103", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Melanommataceae/Byssosphaeria/Byssosphaeria rhodomphala/ Syn. Sphaeria rhodomphala/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ce3e30aa68339326406f6bd96abcf7b5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d007948c00d51e83f345b9b84c4dd1053c3c6a68", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Protozoa/Dinophyta/Dinophyceae/Gonyaulacales/Mendicodinium/Mendicodinium granulatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.WordApi.Enums { /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.WdRelativeVerticalPosition"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsEnum)] public enum WdRelativeVerticalPosition { /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] wdRelativeVerticalPositionMargin = 0, /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] wdRelativeVerticalPositionPage = 1, /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] wdRelativeVerticalPositionParagraph = 2, /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>3</remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] wdRelativeVerticalPositionLine = 3, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>4</remarks> [SupportByVersion("Word", 12,14,15,16)] wdRelativeVerticalPositionTopMarginArea = 4, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>5</remarks> [SupportByVersion("Word", 12,14,15,16)] wdRelativeVerticalPositionBottomMarginArea = 5, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>6</remarks> [SupportByVersion("Word", 12,14,15,16)] wdRelativeVerticalPositionInnerMarginArea = 6, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>7</remarks> [SupportByVersion("Word", 12,14,15,16)] wdRelativeVerticalPositionOuterMarginArea = 7 } }
{ "content_hash": "a2593c9cc00da0c6e59ca03e93942dd6", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 146, "avg_line_length": 30.042857142857144, "alnum_prop": 0.6419400855920114, "repo_name": "NetOfficeFw/NetOffice", "id": "a55fff00b105389a08458517aa0ac2f10ecad7df", "size": "2105", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "Source/Word/Enums/WdRelativeVerticalPosition.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "951" }, { "name": "C#", "bytes": "47700257" }, { "name": "Rich Text Format", "bytes": "230731" }, { "name": "VBA", "bytes": "1389" }, { "name": "Visual Basic .NET", "bytes": "212815" } ], "symlink_target": "" }
#ifndef _POLARIS10_THERMAL_H_ #define _POLARIS10_THERMAL_H_ #include "hwmgr.h" #define POLARIS10_THERMAL_HIGH_ALERT_MASK 0x1 #define POLARIS10_THERMAL_LOW_ALERT_MASK 0x2 #define POLARIS10_THERMAL_MINIMUM_TEMP_READING -256 #define POLARIS10_THERMAL_MAXIMUM_TEMP_READING 255 #define POLARIS10_THERMAL_MINIMUM_ALERT_TEMP 0 #define POLARIS10_THERMAL_MAXIMUM_ALERT_TEMP 255 #define FDO_PWM_MODE_STATIC 1 #define FDO_PWM_MODE_STATIC_RPM 5 extern int tf_polaris10_thermal_initialize(struct pp_hwmgr *hwmgr, void *input, void *output, void *storage, int result); extern int tf_polaris10_thermal_set_temperature_range(struct pp_hwmgr *hwmgr, void *input, void *output, void *storage, int result); extern int tf_polaris10_thermal_enable_alert(struct pp_hwmgr *hwmgr, void *input, void *output, void *storage, int result); extern int polaris10_thermal_get_temperature(struct pp_hwmgr *hwmgr); extern int polaris10_thermal_stop_thermal_controller(struct pp_hwmgr *hwmgr); extern int polaris10_fan_ctrl_get_fan_speed_info(struct pp_hwmgr *hwmgr, struct phm_fan_speed_info *fan_speed_info); extern int polaris10_fan_ctrl_get_fan_speed_percent(struct pp_hwmgr *hwmgr, uint32_t *speed); extern int polaris10_fan_ctrl_set_default_mode(struct pp_hwmgr *hwmgr); extern int polaris10_fan_ctrl_set_static_mode(struct pp_hwmgr *hwmgr, uint32_t mode); extern int polaris10_fan_ctrl_set_fan_speed_percent(struct pp_hwmgr *hwmgr, uint32_t speed); extern int polaris10_fan_ctrl_reset_fan_speed_to_default(struct pp_hwmgr *hwmgr); extern int pp_polaris10_thermal_initialize(struct pp_hwmgr *hwmgr); extern int polaris10_thermal_ctrl_uninitialize_thermal_controller(struct pp_hwmgr *hwmgr); extern int polaris10_fan_ctrl_set_fan_speed_rpm(struct pp_hwmgr *hwmgr, uint32_t speed); extern int polaris10_fan_ctrl_get_fan_speed_rpm(struct pp_hwmgr *hwmgr, uint32_t *speed); extern int polaris10_fan_ctrl_stop_smc_fan_control(struct pp_hwmgr *hwmgr); extern uint32_t tonga_get_xclk(struct pp_hwmgr *hwmgr); #endif
{ "content_hash": "cb4b8027191276cfe1a0b1d10180be3a", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 132, "avg_line_length": 49.4390243902439, "alnum_prop": 0.772076961026147, "repo_name": "AlbandeCrevoisier/ldd-athens", "id": "62f8cbc2d59069d1cd337f51dfa099380becb9d5", "size": "3163", "binary": false, "copies": "96", "ref": "refs/heads/master", "path": "linux-socfpga/drivers/gpu/drm/amd/powerplay/hwmgr/polaris10_thermal.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10184236" }, { "name": "Awk", "bytes": "40418" }, { "name": "Batchfile", "bytes": "81753" }, { "name": "C", "bytes": "566858455" }, { "name": "C++", "bytes": "21399133" }, { "name": "Clojure", "bytes": "971" }, { "name": "Cucumber", "bytes": "5998" }, { "name": "FORTRAN", "bytes": "11832" }, { "name": "GDB", "bytes": "18113" }, { "name": "Groff", "bytes": "2686457" }, { "name": "HTML", "bytes": "34688334" }, { "name": "Lex", "bytes": "56961" }, { "name": "Logos", "bytes": "133810" }, { "name": "M4", "bytes": "3325" }, { "name": "Makefile", "bytes": "1685015" }, { "name": "Objective-C", "bytes": "920162" }, { "name": "Perl", "bytes": "752477" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "533352" }, { "name": "Shell", "bytes": "468244" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "12824" }, { "name": "XC", "bytes": "33970" }, { "name": "XS", "bytes": "34909" }, { "name": "Yacc", "bytes": "113516" } ], "symlink_target": "" }
using Umbraco.Cms.Core; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Dtos; namespace Umbraco.Cms.Infrastructure.Migrations.Upgrade.V_8_0_0; public class AddLockObjects : MigrationBase { public AddLockObjects(IMigrationContext context) : base(context) { } internal static void EnsureLockObject(IUmbracoDatabase db, int id, string name) { // not if it already exists var exists = db.Exists<LockDto>(id); if (exists) { return; } // be safe: delete old umbracoNode lock objects if any db.Execute($"DELETE FROM umbracoNode WHERE id={id};"); // then create umbracoLock object db.Execute($"INSERT umbracoLock (id, name, value) VALUES ({id}, '{name}', 1);"); } protected override void Migrate() { // some may already exist, just ensure everything we need is here EnsureLockObject(Constants.Locks.Servers, "Servers"); EnsureLockObject(Constants.Locks.ContentTypes, "ContentTypes"); EnsureLockObject(Constants.Locks.ContentTree, "ContentTree"); EnsureLockObject(Constants.Locks.MediaTree, "MediaTree"); EnsureLockObject(Constants.Locks.MemberTree, "MemberTree"); EnsureLockObject(Constants.Locks.MediaTypes, "MediaTypes"); EnsureLockObject(Constants.Locks.MemberTypes, "MemberTypes"); EnsureLockObject(Constants.Locks.Domains, "Domains"); } private void EnsureLockObject(int id, string name) => EnsureLockObject(Database, id, name); }
{ "content_hash": "3c5a0c6c0d8d7ec2b761430d60d2e5d0", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 95, "avg_line_length": 35.95454545454545, "alnum_prop": 0.6826801517067004, "repo_name": "arknu/Umbraco-CMS", "id": "96937d399123cd8f5e9338dc7607885c1acc9bf5", "size": "1582", "binary": false, "copies": "4", "ref": "refs/heads/v10/contrib", "path": "src/Umbraco.Infrastructure/Migrations/Upgrade/V_8_0_0/AddLockObjects.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "16182634" }, { "name": "CSS", "bytes": "20943" }, { "name": "Dockerfile", "bytes": "1349" }, { "name": "HTML", "bytes": "1376922" }, { "name": "JavaScript", "bytes": "4774243" }, { "name": "Less", "bytes": "744095" }, { "name": "Smalltalk", "bytes": "1" }, { "name": "TypeScript", "bytes": "186621" } ], "symlink_target": "" }
from datetime import datetime, date, timedelta import pytest import pytz from icalendar import vRecur from khal.khalendar.event import Event, AllDayEvent, LocalizedEvent, FloatingEvent from .aux import normalize_component, _get_text BERLIN = pytz.timezone('Europe/Berlin') # the lucky people in Bogota don't know the pain that is DST BOGOTA = pytz.timezone('America/Bogota') LOCALE = { 'default_timezone': BERLIN, 'local_timezone': BERLIN, 'dateformat': '%d.%m.', 'timeformat': '%H:%M', 'longdateformat': '%d.%m.%Y', 'datetimeformat': '%d.%m. %H:%M', 'longdatetimeformat': '%d.%m.%Y %H:%M', 'unicode_symbols': True, } BOGOTA_LOCALE = LOCALE.copy() BOGOTA_LOCALE['local_timezone'] = BOGOTA BOGOTA_LOCALE['default_timezone'] = BOGOTA MIXED_LOCALE = LOCALE.copy() MIXED_LOCALE['local_timezone'] = BOGOTA EVENT_KWARGS = {'calendar': 'foobar', 'locale': LOCALE} def test_no_initialization(): with pytest.raises(ValueError): Event('', '') def test_invalid_keyword_argument(): with pytest.raises(TypeError): Event.fromString(_get_text('event_dt_simple'), keyword='foo') def test_raw_dt(): event_dt = _get_text('event_dt_simple') start = BERLIN.localize(datetime(2014, 4, 9, 9, 30)) end = BERLIN.localize(datetime(2014, 4, 9, 10, 30)) event = Event.fromString(event_dt, start=start, end=end, **EVENT_KWARGS) assert normalize_component(event.raw) == \ normalize_component(_get_text('event_dt_simple_inkl_vtimezone')) assert event.relative_to(date(2014, 4, 9)) == '09:30-10:30: An Event' event = Event.fromString(event_dt, **EVENT_KWARGS) assert event.relative_to(date(2014, 4, 9)) == '09:30-10:30: An Event' assert event.event_description == '09:30-10:30 09.04.2014: An Event' assert event.recurring is False assert event.duration == timedelta(hours=1) assert event.uid == 'V042MJ8B3SJNFXQOJL6P53OFMHJE8Z3VZWOU' assert event.ident == 'V042MJ8B3SJNFXQOJL6P53OFMHJE8Z3VZWOU' assert event.organizer == '' def test_update_simple(): event = Event.fromString(_get_text('event_dt_simple'), **EVENT_KWARGS) event_updated = Event.fromString(_get_text('event_dt_simple_updated'), **EVENT_KWARGS) event.update_summary('A not so simple Event') event.update_description('Everything has changed') event.update_location('anywhere') assert normalize_component(event.raw) == normalize_component(event_updated.raw) def test_raw_d(): event_d = _get_text('event_d') event = Event.fromString(event_d, **EVENT_KWARGS) assert event.raw.split('\r\n') == _get_text('cal_d').split('\n') assert event.relative_to(date(2014, 4, 9)) == 'An Event' assert event.event_description == '09.04.2014: An Event' def test_update_sequence(): event = Event.fromString(_get_text('event_dt_simple'), **EVENT_KWARGS) event.increment_sequence() assert event._vevents['PROTO']['SEQUENCE'] == 0 event.increment_sequence() assert event._vevents['PROTO']['SEQUENCE'] == 1 def test_event_organizer(): event = _get_text('event_dt_duration') event = Event.fromString(event, **EVENT_KWARGS) assert event.organizer == 'Frank Nord (frank@nord.tld)' def test_transform_event(): """test if transformation between different event types works""" event_d = _get_text('event_d') event = Event.fromString(event_d, **EVENT_KWARGS) assert isinstance(event, AllDayEvent) start = BERLIN.localize(datetime(2014, 4, 9, 9, 30)) end = BERLIN.localize(datetime(2014, 4, 9, 10, 30)) event.update_start_end(start, end) assert isinstance(event, LocalizedEvent) assert event.event_description == '09:30-10:30 09.04.2014: An Event' analog_event = Event.fromString(_get_text('event_dt_simple'), **EVENT_KWARGS) assert normalize_component(event.raw) == normalize_component(analog_event.raw) with pytest.raises(ValueError): event.update_start_end(start, date(2014, 4, 9)) def test_update_event_d(): event_d = _get_text('event_d') event = Event.fromString(event_d, **EVENT_KWARGS) event.update_start_end(date(2014, 4, 20), date(2014, 4, 22)) assert event.event_description == '20.04. - 22.04.2014: An Event' assert 'DTSTART;VALUE=DATE:20140420' in event.raw.split('\r\n') assert 'DTEND;VALUE=DATE:20140423' in event.raw.split('\r\n') def test_update_event_duration(): event_dur = _get_text('event_dt_duration') event = Event.fromString(event_dur, **EVENT_KWARGS) assert event.start == BERLIN.localize(datetime(2014, 4, 9, 9, 30)) assert event.end == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) assert event.duration == timedelta(hours=1) event.update_start_end(BERLIN.localize(datetime(2014, 4, 9, 8, 0)), BERLIN.localize(datetime(2014, 4, 9, 12, 0))) assert event.start == BERLIN.localize(datetime(2014, 4, 9, 8, 0)) assert event.end == BERLIN.localize(datetime(2014, 4, 9, 12, 0)) assert event.duration == timedelta(hours=4) def test_dt_two_tz(): event_dt_two_tz = _get_text('event_dt_two_tz') cal_dt_two_tz = _get_text('cal_dt_two_tz') event = Event.fromString(event_dt_two_tz, **EVENT_KWARGS) assert normalize_component(cal_dt_two_tz) == normalize_component(event.raw) # local (Berlin) time! assert event.relative_to(date(2014, 4, 9)) == '09:30-16:30: An Event' assert event.event_description == '09:30-16:30 09.04.2014: An Event' def test_event_dt_duration(): """event has no end, but duration""" event_dt_duration = _get_text('event_dt_duration') event = Event.fromString(event_dt_duration, **EVENT_KWARGS) assert event.relative_to(date(2014, 4, 9)) == '09:30-10:30: An Event' assert event.end == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) assert event.event_description == '09:30-10:30 09.04.2014: An Event' def test_event_dt_floating(): """start and end time have no timezone, i.e. a floating event""" event_str = _get_text('event_dt_floating') event = Event.fromString(event_str, **EVENT_KWARGS) assert isinstance(event, FloatingEvent) assert event.relative_to(date(2014, 4, 9)) == '09:30-10:30: An Event' assert event.event_description == '09:30-10:30 09.04.2014: An Event' assert event.start == datetime(2014, 4, 9, 9, 30) assert event.end == datetime(2014, 4, 9, 10, 30) assert event.start_local == BERLIN.localize(datetime(2014, 4, 9, 9, 30)) assert event.end_local == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) event = Event.fromString(event_str, calendar='foobar', locale=MIXED_LOCALE) assert event.start == datetime(2014, 4, 9, 9, 30) assert event.end == datetime(2014, 4, 9, 10, 30) assert event.start_local == BOGOTA.localize(datetime(2014, 4, 9, 9, 30)) assert event.end_local == BOGOTA.localize(datetime(2014, 4, 9, 10, 30)) def test_event_dt_tz_missing(): """localized event DTSTART;TZID=foo, but VTIMEZONE components missing""" event_str = _get_text('event_dt_local_missing_tz') event = Event.fromString(event_str, **EVENT_KWARGS) assert event.start == BERLIN.localize(datetime(2014, 4, 9, 9, 30)) assert event.end == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) assert event.start_local == BERLIN.localize(datetime(2014, 4, 9, 9, 30)) assert event.end_local == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) event = Event.fromString(event_str, calendar='foobar', locale=MIXED_LOCALE) assert event.start == BERLIN.localize(datetime(2014, 4, 9, 9, 30)) assert event.end == BERLIN.localize(datetime(2014, 4, 9, 10, 30)) assert event.start_local == BOGOTA.localize(datetime(2014, 4, 9, 2, 30)) assert event.end_local == BOGOTA.localize(datetime(2014, 4, 9, 3, 30)) def test_event_dt_rr(): event_dt_rr = _get_text('event_dt_rr') event = Event.fromString(event_dt_rr, **EVENT_KWARGS) assert event.recurring is True desc = '09:30-10:30: An Event ⟳' assert event.relative_to(date(2014, 4, 9)) == desc assert event.event_description == \ '09:30-10:30 09.04.2014: An Event\nRepeat: FREQ=DAILY;COUNT=10' def test_event_d_rr(): event_d_rr = _get_text('event_d_rr') event = Event.fromString(event_d_rr, **EVENT_KWARGS) assert event.recurring is True desc = 'Another Event ⟳' assert event.relative_to(date(2014, 4, 9)) == desc assert event.event_description == '09.04.2014: Another Event\nRepeat: FREQ=DAILY;COUNT=10' start = date(2014, 4, 10) end = date(2014, 4, 11) event = Event.fromString(event_d_rr, start=start, end=end, **EVENT_KWARGS) assert event.recurring is True desc = 'Another Event ⟳' assert event.relative_to(date(2014, 4, 10)) == desc assert event.event_description == '10.04.2014: Another Event\nRepeat: FREQ=DAILY;COUNT=10' def test_event_rd(): event_dt_rd = _get_text('event_dt_rd') event = Event.fromString(event_dt_rd, **EVENT_KWARGS) assert event.recurring is True def test_event_d_long(): event_d_long = _get_text('event_d_long') event = Event.fromString(event_d_long, **EVENT_KWARGS) with pytest.raises(ValueError): event.relative_to(date(2014, 4, 8)) assert event.relative_to(date(2014, 4, 9)) == '↦ Another Event' assert event.relative_to(date(2014, 4, 10)) == '↔ Another Event' assert event.relative_to(date(2014, 4, 11)) == '⇥ Another Event' with pytest.raises(ValueError): event.relative_to(date(2014, 4, 12)) assert event.event_description == '09.04. - 11.04.2014: Another Event' def test_event_dt_long(): event_dt_long = _get_text('event_dt_long') event = Event.fromString(event_dt_long, **EVENT_KWARGS) assert event.relative_to(date(2014, 4, 9)) == '09:30→ : An Event' # FIXME ugly! replace with one arrow assert event.relative_to(date(2014, 4, 10)) == '→ → : An Event' assert event.relative_to(date(2014, 4, 12)) == '→ 10:30: An Event' assert event.event_description == '09.04.2014 09:30 - 12.04.2014 10:30: An Event' def test_event_no_dst(): """test the creation of a corect VTIMEZONE for timezones with no dst""" event_no_dst = _get_text('event_no_dst') cal_no_dst = _get_text('cal_no_dst') event = Event.fromString(event_no_dst, calendar='foobar', locale=BOGOTA_LOCALE) assert normalize_component(event.raw) == normalize_component(cal_no_dst) assert event.event_description == '09:30-10:30 09.04.2014: An Event' def test_event_raw_UTC(): """test .raw() on events which are localized in UTC""" event_utc = _get_text('event_dt_simple_zulu') event = Event.fromString(event_utc, **EVENT_KWARGS) assert event.raw == '\r\n'.join([ '''BEGIN:VCALENDAR''', '''VERSION:2.0''', '''PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN''', '''BEGIN:VEVENT''', '''SUMMARY:An Event''', '''DTSTART:20140409T093000Z''', '''DTEND:20140409T103000Z''', '''DTSTAMP;VALUE=DATE-TIME:20140401T234817Z''', '''UID:V042MJ8B3SJNFXQOJL6P53OFMHJE8Z3VZWOU''', '''END:VEVENT''', '''END:VCALENDAR\r\n''']) def test_dtend_equals_dtstart(): event = Event.fromString(_get_text('event_d_same_start_end'), calendar='foobar', locale=LOCALE) assert event.end == event.start def test_multi_uid(): """test for support for events with consist of several sub events with the same uid""" orig_event_str = _get_text('event_rrule_recuid') event = Event.fromString(orig_event_str, **EVENT_KWARGS) for line in orig_event_str.split('\n'): assert line in event.raw.split('\r\n') def test_recur(): event = Event.fromString(_get_text('event_dt_rr'), **EVENT_KWARGS) assert event.recurring is True assert event.recurpattern == 'FREQ=DAILY;COUNT=10' assert event.recurobject == vRecur({'COUNT': [10], 'FREQ': ['DAILY']}) def test_type_inference(): event = Event.fromString(_get_text('event_dt_simple'), **EVENT_KWARGS) assert type(event) == LocalizedEvent event = Event.fromString(_get_text('event_dt_simple_zulu'), **EVENT_KWARGS) assert type(event) == LocalizedEvent def test_duplicate_event(): event = Event.fromString(_get_text('event_dt_simple'), **EVENT_KWARGS) dupe = event.duplicate() assert dupe._vevents['PROTO']['UID'].to_ical() != 'V042MJ8B3SJNFXQOJL6P53OFMHJE8Z3VZWOU' def test_remove_instance_from_rrule(): """removing an instance from a recurring event""" event = Event.fromString(_get_text('event_dt_rr'), **EVENT_KWARGS) event.delete_instance(datetime(2014, 4, 10, 9, 30)) assert 'EXDATE:20140410T093000' in event.raw.split('\r\n') event.delete_instance(datetime(2014, 4, 12, 9, 30)) assert 'EXDATE:20140410T093000,20140412T093000' in event.raw.split('\r\n') def test_remove_instance_from_rdate(): """removing an instance from a recurring event""" event = Event.fromString(_get_text('event_dt_rd'), **EVENT_KWARGS) assert 'RDATE' in event.raw event.delete_instance(datetime(2014, 4, 10, 9, 30)) assert 'RDATE' not in event.raw def test_remove_instance_from_two_rdate(): """removing an instance from a recurring event which has two RDATE props""" event = Event.fromString(_get_text('event_dt_two_rd'), **EVENT_KWARGS) assert event.raw.count('RDATE') == 2 event.delete_instance(datetime(2014, 4, 10, 9, 30)) assert event.raw.count('RDATE') == 1 assert 'RDATE:20140411T093000,20140412T093000' in event.raw.split('\r\n') def test_remove_instance_from_recuid(): """remove an istane from an event which is specified via an additional VEVENT with the same UID (which we call `recuid` here""" event = Event.fromString(_get_text('event_rrule_recuid'), **EVENT_KWARGS) assert event.raw.split('\r\n').count('UID:event_rrule_recurrence_id') == 2 event.delete_instance(BERLIN.localize(datetime(2014, 7, 7, 7, 0))) assert event.raw.split('\r\n').count('UID:event_rrule_recurrence_id') == 1 assert 'EXDATE;TZID=Europe/Berlin:20140707T070000' in event.raw.split('\r\n')
{ "content_hash": "ed7fd0298e9ba9113c25cc978d1ef9e2", "timestamp": "", "source": "github", "line_count": 341, "max_line_length": 94, "avg_line_length": 41.225806451612904, "alnum_prop": 0.6650305875657988, "repo_name": "dzoep/khal", "id": "244516a5f34574df13df9516de3e5fddfc1b4ffc", "size": "14078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/event_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "1152" }, { "name": "Python", "bytes": "365652" } ], "symlink_target": "" }
// Karma configuration // Generated on 2016-04-03 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) // as well as any additional frameworks (requirejs/chai/sinon/...) frameworks: [ 'jasmine' ], // list of files / patterns to load in the browser files: [ // bower:js 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-aria/angular-aria.js', 'bower_components/angular-messages/angular-messages.js', 'bower_components/angular-material/angular-material.js', 'bower_components/angular-ui-router/release/angular-ui-router.js', 'bower_components/angular-material-icons/angular-material-icons.min.js', 'bower_components/angular-mocks/angular-mocks.js', // endbower 'bower_components/angular-material/angular-material-mocks.js', 'app/scripts/**/module.js', 'app/scripts/app.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [ ], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
{ "content_hash": "94455f4bd0cd97000c82c9f5137829c2", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 85, "avg_line_length": 28.048192771084338, "alnum_prop": 0.6207044673539519, "repo_name": "levinmr/homepage", "id": "6a821f16c11209b792e7d9924b985e124626611d", "size": "2328", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "test/karma.conf.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1625" }, { "name": "HTML", "bytes": "2554" }, { "name": "JavaScript", "bytes": "19122" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using APE.Umbraco.Core.DTO; using System.Data.SqlServerCe; using System.Configuration; using APE.Umbraco.Core.Models; namespace APE.Umbraco.Core { public class DBConnection { private readonly ProxyHelpers _Helpers; private readonly ConnectionStringContainer _ConnectionString; private ILookup<int, PropertyPreValue> _PreValues; public DBConnection(ProxyHelpers helpers, ConnectionStringContainer connectionString) { _Helpers = helpers; _ConnectionString = connectionString; } internal IEnumerable<T> GetContentTypes<T>(Guid contentTypeGuid) where T : ContentTypeDTO, new() { List<T> tList = new List<T>(); string getAllSql = Properties.Resources.ContentTypeSql; using (IDbConnection conn = GetDbConnection()) { conn.Open(); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = getAllSql; var parm = cmd.CreateParameter(); parm.ParameterName = "contentTypeGuid"; parm.Value = contentTypeGuid; cmd.Parameters.Add(parm); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { T t = new T(); var contentTypeAlias = reader["ContentTypeAlias"].ToString(); var contentTypeAliasText = _Helpers.GetValidCSharpIdentifier(contentTypeAlias); var contentTypeDescription = reader["ContentTypeDescription"].ToString(); t.ContentTypeAlias = contentTypeAlias; t.ContentType = contentTypeAliasText[0].ToString().ToUpper() + contentTypeAliasText.Substring(1); t.ContentTypeDescription = contentTypeDescription; t.Id = (int)reader["Id"]; tList.Add(t); } } } foreach (T t in tList) { var ids = new List<int>(); GetAllInheritedContentTypeIds(ids, conn, t.Id, contentTypeGuid); GetContentTypeProperties(t, ids, conn, t.Id, contentTypeGuid); } } return tList; } internal ILookup<int, PropertyPreValue> GetPreValues() { if (_PreValues!= null && _PreValues.Any()) { return _PreValues; } List<DataTypePreValue> tList = new List<DataTypePreValue>(); string getAllSql = Properties.Resources.CMSDataTypePreValuesSql; using (IDbConnection conn = GetDbConnection()) { conn.Open(); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = getAllSql; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataTypePreValue t = new DataTypePreValue(); t.Alias = reader["Alias"].ToString(); t.DataTypeId = (int)reader["DatatypeNodeId"]; t.Value = reader["Value"].ToString(); tList.Add(t); } } } } return _PreValues = tList.ToLookup(k => k.DataTypeId, v => (PropertyPreValue)v); } // Recursively get all inherited content types. private void GetAllInheritedContentTypeIds(ICollection<int> ids, IDbConnection conn, int id, Guid contentTypeGuid) { if (id == -1) return; ids.Add(id); string getPropSql = Properties.Resources.InheritedContentTypeSql; List<int> parentIds = new List<int>(); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = getPropSql; var parm = cmd.CreateParameter(); parm.ParameterName = "contentTypeGuid"; parm.Value = contentTypeGuid; cmd.Parameters.Add(parm); parm = cmd.CreateParameter(); parm.ParameterName = "id"; parm.Value = id; cmd.Parameters.Add(parm); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var record = reader; var contentTypePropertyDTO = new ContentTypePropertyDTO(); int parentId = -1; if (record["ParentId"] is int) parentId = (int)record["ParentId"]; parentIds.Add(parentId); } } } foreach (int parentId in parentIds) { GetAllInheritedContentTypeIds(ids, conn, parentId, contentTypeGuid); } } private void GetContentTypeProperties<T>(T t, IEnumerable<int> ids, IDbConnection conn, int parentId, Guid contentTypeGuid) where T : ContentTypeDTO { if (parentId == -1) return; // string getPropSql = @" //select un.Id, un.[Text] as ContentType, //cpt.Alias as PropertyAlias, //cpt.Description as PropertyDescription, //un3.Text as PropertyType, //cdt.PropertyEditorAlias as PropertyEditorAlias //from umbracoNode un // inner join cmspropertytype cpt on un.id = cpt.contentTypeId // left join cmsdatatype cdt on cpt.dataTypeId = cdt.nodeId // left join umbracoNode un3 on cpt.dataTypeId = un3.id //where un.NodeObjectType = '{0}' //and un.Id in ({1})"; string getPropSql = Properties.Resources.ContentTypePropertiesSql; IDbCommand cmd = conn.CreateCommand(); StringBuilder sb = new StringBuilder(); var parm = cmd.CreateParameter(); parm.ParameterName = "contentTypeGuid"; parm.Value = contentTypeGuid; cmd.Parameters.Add(parm); var parameters = new string[ids.Count()]; for (int i = 0; i < ids.Count(); i++) { parm = cmd.CreateParameter(); parm.ParameterName = string.Format("@ids{0}", i); parm.Value = ids.ElementAt(i); cmd.Parameters.Add(parm); if (sb.Length > 0) sb.Append(','); sb.Append(parm.ParameterName); } cmd.CommandText = string.Format(getPropSql, sb.ToString()); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var record = reader; var contentTypePropertyDTO = new ContentTypePropertyDTO(); contentTypePropertyDTO.DataTypeId = (int)record["DataTypeId"]; contentTypePropertyDTO.PropertyAlias = record["PropertyAlias"].ToString(); contentTypePropertyDTO.PropertyAliasText = _Helpers.GetValidCSharpIdentifier(contentTypePropertyDTO.PropertyAlias); if (!string.IsNullOrWhiteSpace(contentTypePropertyDTO.PropertyAliasText)) contentTypePropertyDTO.PropertyAliasText = contentTypePropertyDTO.PropertyAliasText[0].ToString().ToUpper() + contentTypePropertyDTO.PropertyAliasText.Substring(1); contentTypePropertyDTO.PropertyDescription = record["PropertyDescription"].ToString(); contentTypePropertyDTO.PropertyType = record["PropertyType"].ToString(); contentTypePropertyDTO.EditorAlias = record["PropertyEditorAlias"].ToString(); t.Properties.Add(contentTypePropertyDTO); } } } public IEnumerable<DictionaryItemDTO> GetDictionary() { using (IDbConnection conn = GetDbConnection()) { conn.Open(); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = Properties.Resources.DictionarySql; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var record = reader; var dictionaryAlias = record[0].ToString(); yield return new DictionaryItemDTO { Name = _Helpers.GetValidCSharpIdentifier(dictionaryAlias), Alias = dictionaryAlias }; } } } } } private IDbConnection GetDbConnection() { var connString = _ConnectionString.ConnectionString.Replace("|DataDirectory|", _ConnectionString.DataDir); if (_ConnectionString.ProviderName.Contains("SqlServerCe")) // Is SQL CE { return new SqlCeConnection(connString); } return new SqlConnection(connString); } } }
{ "content_hash": "6f2f995dad6aff932605ec19a640b883", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 188, "avg_line_length": 39.023715415019765, "alnum_prop": 0.5126101488909146, "repo_name": "LAITDK/AwesomePropertyExtractor", "id": "ecbf71c8fceb07508929bf6707210f2edf1126f8", "size": "9875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/APE.Umbraco/Core/DBConnection.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "326729" }, { "name": "C#", "bytes": "132805" }, { "name": "CSS", "bytes": "280630" }, { "name": "HTML", "bytes": "766888" }, { "name": "JavaScript", "bytes": "4606835" }, { "name": "PowerShell", "bytes": "852" }, { "name": "XSLT", "bytes": "48541" } ], "symlink_target": "" }
Building Litecoin Core with Visual Studio ======================================== Introduction --------------------- Solution and project files to build the Litecoin Core applications (except Qt dependent ones) with Visual Studio 2017 can be found in the build_msvc directory. Building with Visual Studio is an alternative to the Linux based [cross-compiler build](https://github.com/litecoin-project/litecoin/blob/master/doc/build-windows.md). Dependencies --------------------- A number of [open source libraries](https://github.com/litecoin-project/litecoin/blob/master/doc/dependencies.md) are required in order to be able to build Litecoin. Options for installing the dependencies in a Visual Studio compatible manner are: - Use Microsoft's [vcpkg](https://docs.microsoft.com/en-us/cpp/vcpkg) to download the source packages and build locally. This is the recommended approach. - Download the source code, build each dependency, add the required include paths, link libraries and binary tools to the Visual Studio project files. - Use [nuget](https://www.nuget.org/) packages with the understanding that any binary files have been compiled by an untrusted third party. The external dependencies required for the Visual Studio build are (see the [dependencies doc](https://github.com/litecoin-project/litecoin/blob/master/doc/dependencies.md) for versions): - Berkeley DB, - OpenSSL, - Boost, - libevent, - ZeroMQ Additional dependencies required from the [bitcoin-core](https://github.com/bitcoin-core) github repository are: - SECP256K1, - LevelDB Building --------------------- The instructions below use `vcpkg` to install the dependencies. - Clone `vcpkg` from the [github repository](https://github.com/Microsoft/vcpkg) and install as per the instructions in the main README.md. - Install the required packages (replace x64 with x86 as required): ``` PS >.\vcpkg install --triplet x64-windows-static boost-filesystem boost-signals2 boost-test libevent openssl zeromq berkeleydb secp256k1 leveldb ``` - Use Python to generate *.vcxproj from Makefile ``` PS >python msvc-autogen.py ``` - Build in Visual Studio.
{ "content_hash": "1a631ebbcb07752f9fc7058b49a645aa", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 187, "avg_line_length": 43.734693877551024, "alnum_prop": 0.7456836210919272, "repo_name": "bespike/litecoin", "id": "a6e97f7665507bd1990a6b64671ac1a580160bba", "size": "2143", "binary": false, "copies": "2", "ref": "refs/heads/0.18", "path": "build_msvc/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "7639" }, { "name": "C", "bytes": "391114" }, { "name": "C++", "bytes": "3517453" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18043" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "Makefile", "bytes": "66797" }, { "name": "Objective-C", "bytes": "2023" }, { "name": "Objective-C++", "bytes": "7246" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "211872" }, { "name": "QMake", "bytes": "2019" }, { "name": "Shell", "bytes": "40504" } ], "symlink_target": "" }
/** * Run integration tests * * Uses the `waterline-adapter-tests` module to * run mocha tests against the appropriate version * of Waterline. Only the interfaces explicitly * declared in this adapter's `package.json` file * are tested. (e.g. `queryable`, `semantic`, etc.) */ /** * Module dependencies */ var util = require('util'); var mocha = require('mocha'); var log = require('captains-log')(); var TestRunner = require('waterline-adapter-tests'); var Adapter = require('../../lib/adapter'); // Grab targeted interfaces from this adapter's `package.json` file: var package = {}, interfaces = [], features = []; try { package = require('../../package.json'); interfaces = package.waterlineAdapter.interfaces; features = package.waterlineAdapter.features; } catch (e) { throw new Error( '\n' + 'Could not read supported interfaces from `waterlineAdapter.interfaces`' + '\n' + 'in this adapter\'s `package.json` file ::' + '\n' + util.inspect(e) ); } log.info('Testing `' + package.name + '`, a Sails/Waterline adapter.'); log.info('Running `waterline-adapter-tests` against ' + interfaces.length + ' interfaces...'); log.info('( ' + interfaces.join(', ') + ' )'); console.log(); log('Latest draft of Waterline adapter interface spec:'); log('http://links.sailsjs.org/docs/plugins/adapters/interfaces'); console.log(); /** * Integration Test Runner * * Uses the `waterline-adapter-tests` module to * run mocha tests against the specified interfaces * of the currently-implemented Waterline adapter API. */ new TestRunner({ // Mocha opts mocha: { bail: false }, // Load the adapter module. adapter: Adapter, // Default connection config to use. config: { host: 'localhost', port: 6379, schema: true, poolSize: 1 }, // The set of adapter interfaces to test against. // (grabbed these from this adapter's package.json file above) interfaces: interfaces, // The set of adapter features to test against. // (grabbed these from this adapter's package.json file above) features: features, // Return non-zero code if any test failed failOnError: true // Most databases implement 'semantic' and 'queryable'. // // As of Sails/Waterline v0.10, the 'associations' interface // is also available. If you don't implement 'associations', // it will be polyfilled for you by Waterline core. The core // implementation will always be used for cross-adapter / cross-connection // joins. // // In future versions of Sails/Waterline, 'queryable' may be also // be polyfilled by core. // // These polyfilled implementations can usually be further optimized at the // adapter level, since most databases provide optimizations for internal // operations. // // Full interface reference: // https://github.com/balderdashy/sails-docs/blob/master/adapter-specification.md });
{ "content_hash": "1e98d830e49a8391eb99fa5ebeade818", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 94, "avg_line_length": 27.685714285714287, "alnum_prop": 0.6848985208118336, "repo_name": "jpwilliams/sails-aerospike", "id": "aa23e0613bff01d6a1ace416aaf9a3a72851f9ab", "size": "2907", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "test/integration/runner.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "72568" }, { "name": "Makefile", "bytes": "256" } ], "symlink_target": "" }
function Callback_mouseMove(src, evnt) plotFig = src; plotPluginObj = plotFig.UserData.pluginObj; imagePluginObj = plotPluginObj.controller.guiPlugins.image; if plotPluginObj.checkWindowExists() && plotPluginObj.view.dynamic.nViewDims > 0 mousePosPx = get(plotFig, 'CurrentPoint'); %pixels figPos = plotFig.Position; % mousePosRel = mousePosPx ./ figPos(3:4); %relative % Get all axes ax = findobj(plotFig.Children,'type','axes'); axPos = cat(1,ax.Position); % Find Positions of LL and UR corners for each ax axLLx = axPos(:,1)*figPos(3); axLLy = axPos(:,2)*figPos(4); axURx = (axPos(:,1)+axPos(:,3))*figPos(3); axURy = (axPos(:,2)+axPos(:,4))*figPos(4); % determine which axis axInd = find((mousePosPx(1)>=axLLx) .* (mousePosPx(1)<=axURx) .* (mousePosPx(2)>=axLLy) .* (mousePosPx(2)<=axURy)); if ~isempty(axInd) currAx = ax(axInd); % get mouse position mouseAxPosIndScale = get(currAx, 'CurrentPoint'); %in axis scale % Dev note: returns the points into and out of the plot volume % to find 3d point, need to use camera angle and ray trace mouseAxPosIndScale = mouseAxPosIndScale(1,:); if mouseAxPosIndScale(3) ~= 1 %in 3d scale return end mouseAxPosIndScale = mouseAxPosIndScale(1:2); mouseAxPosIndScale = round(mouseAxPosIndScale); % round try plotDims = currAx.UserData.plotDims; nPlotDims = length(plotDims); catch return % in case axis is deleted end if nPlotDims > 2 %only 1d or 2d return % strategy % filter all points based on range of x, y, z and next point around it % this gives cube of points around line % then find distance by finding e = b - p = b - (a.*b)/a.^2 .* a or make b a % but need to find front point a = diff(mouseAxPosIndScale); objVals = size(hypercubeObj); objVals = objVals(plotDims); objVals = arrayfun(@(x) 1:x, objVals, 'uni',0); [bx, by, bz] = meshgrid(objVals{:}); bx = bx(:); by = by(:); bz = bz(:); b = [bx, by, bz]; bVec = bsxfun(@minus, b, mouseAxPosIndScale(1,:)); proj = bVec - bsxfun(@times, bsxfun(@times, a, bVec)./a.^2, a); proj = sum(proj .* proj, 2); [~, ind] = min(proj); vals = b(ind, :); end % get hypercube data hypercubeObj = plotPluginObj.controller.activeHypercube; axesType = gvGetAxisType(hypercubeObj); if ~isempty(axesType) % check for axisType = 'dataType' dataTypeAxInd = find(strcmp(axesType, 'dataType'), 1); if isempty(dataTypeAxInd) plotPluginObj.vprintf('[gvImageWindowPlugin] Cannot find dataType axis.\n'); return end else plotPluginObj.vprintf('[gvImageWindowPlugin] Cannot find any axis types.\n'); return end % find corresponding index indexAxInd = find(strcmp(plotPluginObj.controller.activeHypercube.axis(dataTypeAxInd).axismeta.dataType, 'index'),1); sliderVals = plotPluginObj.view.dynamic.sliderVals; sliderVals(dataTypeAxInd) = indexAxInd; % set sliderVals dataType axis number to axis position for hypercube index. if length(plotDims) == 3 % 3D sliderVals(plotDims) = mouseAxPosIndScale; % set sliderVals plot dims to closest point to mouse elseif length(plotDims) == 2 % 2D sliderVals(plotDims) = mouseAxPosIndScale(1:2); % set sliderVals plot dims to closest point to mouse else % 1D sliderVals(plotDims) = mouseAxPosIndScale(1); % set sliderVals plot dims to closest point to mouse end % get image index from slider vals sliderVals = num2cell(sliderVals); % convert to cell for indexing try imageIndex = hypercubeObj.data(sliderVals{:}); if iscell(imageIndex) imageIndex = imageIndex{1}; end if ischar(imageIndex) imageIndex = str2double(imageIndex); end % store image index plotPluginObj.metadata.imageIndex = imageIndex; try % show image if ~isempty(imageIndex) imagePluginObj.showImage(imageIndex); end end end % TODO: % check if distance to nearest point is < x% of axis size end end end
{ "content_hash": "0a4d07fbcde0a3bcc253a5537bf85a94", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 121, "avg_line_length": 33.116279069767444, "alnum_prop": 0.6371722846441947, "repo_name": "erik-roberts/GIMBL-Vis", "id": "26f54f7b97cee5bdee0163f151b748f689408257", "size": "4272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/plugins/@gvImageWindowPlugin/Callback_mouseMove.m", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1948" }, { "name": "HTML", "bytes": "396864" }, { "name": "MATLAB", "bytes": "652210" } ], "symlink_target": "" }