text
stringlengths
2
1.04M
meta
dict
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace PlayStation_App.Models.Authentication { public class Tokens { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonProperty("scope")] public string Scope { get; set; } } }
{ "content_hash": "7c61ba212f0808481111d8793cc05fed", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 48, "avg_line_length": 23.925925925925927, "alnum_prop": 0.6393188854489165, "repo_name": "drasticactions/Pureisuteshon-App", "id": "718214ca342b517460a608599fa736f0ea915064", "size": "648", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "PSX-App/Models/Authentication/Tokens.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1980" }, { "name": "C#", "bytes": "966001" }, { "name": "HTML", "bytes": "274" }, { "name": "PowerShell", "bytes": "151" } ], "symlink_target": "" }
<?php use \Ns\Formula as Formula1; use \Ns\Hello as Hello; Formula1::do_something(); Hello::do_something();
{ "content_hash": "d6011e7d82217fed68018c84e8da68f2", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 28, "avg_line_length": 21.6, "alnum_prop": 0.7129629629629629, "repo_name": "yanggg1133/js2php", "id": "b8111271a0990b92fe5c23de5b04619c8f3e8118", "size": "108", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/fixtures/namespaces_use.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "36214" } ], "symlink_target": "" }
package org.apache.camel.component.activemq; import java.util.HashMap; import java.util.Map; import javax.jms.Destination; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Headers; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.activemq.support.ActiveMQTestSupport; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.component.activemq.ActiveMQComponent.activeMQComponent; import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf; import static org.apache.camel.test.junit5.TestSupport.assertMessageHeader; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.junit.jupiter.api.Assertions.assertEquals; /** * */ public class InvokeRequestReplyUsingJmsReplyToHeaderTest extends ActiveMQTestSupport { private static final transient Logger LOG = LoggerFactory .getLogger(InvokeRequestReplyUsingJmsReplyToHeaderTest.class); protected String replyQueueName = "queue://test.reply"; protected Object correlationID = "ABC-123"; protected Object groupID = "GROUP-XYZ"; private MyServer myBean = new MyServer(); @Test public void testPerformRequestReplyOverJms() { Map<String, Object> headers = new HashMap<>(); headers.put("cheese", 123); headers.put("JMSReplyTo", replyQueueName); headers.put("JMSCorrelationID", correlationID); headers.put("JMSXGroupID", groupID); Exchange reply = template.request("activemq:test.server?replyTo=queue:test.reply", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("James"); Map<String, Object> headers = new HashMap<>(); headers.put("cheese", 123); headers.put("JMSReplyTo", replyQueueName); headers.put("JMSCorrelationID", correlationID); headers.put("JMSXGroupID", groupID); exchange.getIn().setHeaders(headers); } }); Message in = reply.getIn(); Object replyTo = in.getHeader("JMSReplyTo"); LOG.info("Reply to is: {}", replyTo); LOG.info("Received headers: {}", in.getHeaders()); LOG.info("Received body: {}", in.getBody()); assertMessageHeader(in, "JMSCorrelationID", correlationID); Map<String, Object> receivedHeaders = myBean.getHeaders(); assertThat(receivedHeaders, hasKey("JMSReplyTo")); assertThat(receivedHeaders, hasEntry("JMSXGroupID", groupID)); assertThat(receivedHeaders, hasEntry("JMSCorrelationID", correlationID)); replyTo = receivedHeaders.get("JMSReplyTo"); LOG.info("Reply to is: {}", replyTo); Destination destination = assertIsInstanceOf(Destination.class, replyTo); assertEquals(replyQueueName, destination.toString(), "ReplyTo"); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); // START SNIPPET: example camelContext.addComponent("activemq", activeMQComponent(vmUri("?broker.persistent=false"))); // END SNIPPET: example return camelContext; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("activemq:test.server").bean(myBean); } }; } protected static class MyServer { private Map<String, Object> headers; public String process(@Headers Map<String, Object> headers, String body) { this.headers = headers; LOG.info("process() invoked with headers: {}", headers); return "Hello " + body; } public Map<String, Object> getHeaders() { return headers; } } }
{ "content_hash": "9bc7a99289353a651f37605cdac74775", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 108, "avg_line_length": 36.50442477876106, "alnum_prop": 0.6768484848484848, "repo_name": "tadayosi/camel", "id": "e448adec48e50da063432be5a7c3b0fab75cedc8", "size": "4927", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "components/camel-activemq/src/test/java/org/apache/camel/component/activemq/InvokeRequestReplyUsingJmsReplyToHeaderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6695" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Dockerfile", "bytes": "5676" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "405043" }, { "name": "HTML", "bytes": "212954" }, { "name": "Java", "bytes": "114726986" }, { "name": "JavaScript", "bytes": "103655" }, { "name": "Jsonnet", "bytes": "1734" }, { "name": "Kotlin", "bytes": "41869" }, { "name": "Mustache", "bytes": "525" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Ruby", "bytes": "88" }, { "name": "Shell", "bytes": "15327" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "699" }, { "name": "XSLT", "bytes": "276597" } ], "symlink_target": "" }
package com.pearson.statsagg.database_objects.alerts; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Objects; import com.pearson.statsagg.database_engine.DatabaseObject; import com.pearson.statsagg.database_objects.DatabaseObjectCommon; import com.pearson.statsagg.database_objects.metric_group.MetricGroup; import com.pearson.statsagg.database_objects.metric_group_tags.MetricGroupTag; import com.pearson.statsagg.database_objects.notifications.NotificationGroup; import com.pearson.statsagg.utilities.math_utils.MathUtilities; import com.pearson.statsagg.utilities.core_utils.StackTrace; import com.pearson.statsagg.utilities.json_utils.JsonBigDecimal; import java.util.Calendar; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.builder.EqualsBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ public class Alert extends DatabaseObject<Alert> { private static final Logger logger = LoggerFactory.getLogger(Alert.class.getName()); public static final int CAUTION = 61; public static final int DANGER = 62; public static final int TYPE_AVAILABILITY = 1001; public static final int TYPE_THRESHOLD = 1002; public static final int OPERATOR_GREATER = 1; public static final int OPERATOR_GREATER_EQUALS = 2; public static final int OPERATOR_LESS = 3; public static final int OPERATOR_LESS_EQUALS = 4; public static final int OPERATOR_EQUALS = 5; public static final int COMBINATION_ANY = 101; public static final int COMBINATION_ALL = 102; public static final int COMBINATION_AVERAGE = 103; public static final int COMBINATION_AT_MOST_COUNT = 105; public static final int COMBINATION_AT_LEAST_COUNT = 106; @SerializedName("id") private Integer id_; @SerializedName("name") private String name_ = null; private transient String uppercaseName_ = null; @SerializedName("description") private String description_ = null; @SerializedName("metric_group_id") private Integer metricGroupId_ = null; @SerializedName("enabled") private Boolean isEnabled_ = null; @SerializedName("caution_enabled") private Boolean isCautionEnabled_ = null; @SerializedName("danger_enabled") private Boolean isDangerEnabled_ = null; @SerializedName("alert_type") private Integer alertType_ = null; @SerializedName("alert_on_positive") private Boolean alertOnPositive_ = null; @SerializedName("allow_resend_alert") private Boolean allowResendAlert_ = null; @SerializedName("resend_alert_every") private Long resendAlertEvery_ = null; @SerializedName("resend_alert_every_time_unit") private Integer resendAlertEveryTimeUnit_ = null; @SerializedName("caution_notification_group_id") private Integer cautionNotificationGroupId_ = null; @SerializedName("caution_positive_notification_group_id") private Integer cautionPositiveNotificationGroupId_ = null; @SerializedName("caution_operator") private Integer cautionOperator_ = null; @SerializedName("caution_combination") private Integer cautionCombination_ = null; @SerializedName("caution_combination_count") private Integer cautionCombinationCount_ = null; @SerializedName("caution_threshold") private BigDecimal cautionThreshold_ = null; @SerializedName("caution_window_duration") private Long cautionWindowDuration_ = null; // native timeunit is milliseconds @SerializedName("caution_window_duration_time_unit") private Integer cautionWindowDurationTimeUnit_ = null; @SerializedName("caution_stop_tracking_after") private Long cautionStopTrackingAfter_ = null; @SerializedName("caution_stop_tracking_after_time_unit") private Integer cautionStopTrackingAfterTimeUnit_ = null; @SerializedName("caution_minimum_sample_count") private Integer cautionMinimumSampleCount_ = null; @SerializedName("caution_alert_active") private Boolean isCautionAlertActive_ = null; @SerializedName("caution_alert_last_sent_timestamp") private Timestamp cautionAlertLastSentTimestamp_ = null; @SerializedName("caution_alert_acknowledged_status") private Boolean isCautionAlertAcknowledged_ = null; private transient String cautionActiveAlertsSet_ = null; @SerializedName("caution_first_active_at") private Timestamp cautionFirstActiveAt_ = null; @SerializedName("danger_notification_group_id") private Integer dangerNotificationGroupId_ = null; @SerializedName("danger_positive_notification_group_id") private Integer dangerPositiveNotificationGroupId_ = null; @SerializedName("danger_operator") private Integer dangerOperator_ = null; @SerializedName("danger_combination") private Integer dangerCombination_ = null; @SerializedName("danger_combination_count") private Integer dangerCombinationCount_ = null; @SerializedName("danger_threshold") private BigDecimal dangerThreshold_ = null; @SerializedName("danger_window_duration") private Long dangerWindowDuration_ = null; // native timeunit is milliseconds @SerializedName("danger_window_duration_time_unit") private Integer dangerWindowDurationTimeUnit_ = null; @SerializedName("danger_stop_tracking_after") private Long dangerStopTrackingAfter_ = null; @SerializedName("danger_stop_tracking_after_time_unit") private Integer dangerStopTrackingAfterTimeUnit_ = null; @SerializedName("danger_minimum_sample_count") private Integer dangerMinimumSampleCount_ = null; @SerializedName("danger_alert_active") private Boolean isDangerAlertActive_ = null; @SerializedName("danger_alert_last_sent_timestamp") private Timestamp dangerAlertLastSentTimestamp_ = null; @SerializedName("danger_alert_acknowledged_status") private Boolean isDangerAlertAcknowledged_ = null; private transient String dangerActiveAlertsSet_ = null; @SerializedName("danger_first_active_at") private Timestamp dangerFirstActiveAt_ = null; public Alert() { this.id_ = -1; } public Alert(Integer id, String name, String description, Integer metricGroupId, Boolean isEnabled, Boolean isCautionEnabled, Boolean isDangerEnabled, Integer alertType, Boolean alertOnPositive, Boolean allowResendAlert, Long resendAlertEvery, Integer resendAlertEveryTimeUnit, Integer cautionNotificationGroupId, Integer cautionPositiveNotificationGroupId, Integer cautionOperator, Integer cautionCombination, Integer cautionCombinationCount, BigDecimal cautionThreshold, Long cautionWindowDuration, Integer cautionWindowDurationTimeUnit, Long cautionStopTrackingAfter, Integer cautionStopTrackingAfterTimeUnit, Integer cautionMinimumSampleCount, Boolean isCautionAlertActive, Timestamp cautionAlertLastSentTimestamp, Boolean isCautionAlertAcknowledged, String cautionActiveAlertsSet, Timestamp cautionFirstActiveAt, Integer dangerNotificationGroupId, Integer dangerPositiveNotificationGroupId, Integer dangerOperator, Integer dangerCombination, Integer dangerCombinationCount, BigDecimal dangerThreshold, Long dangerWindowDuration, Integer dangerWindowDurationTimeUnit, Long dangerStopTrackingAfter, Integer dangerStopTrackingAfterTimeUnit, Integer dangerMinimumSampleCount, Boolean isDangerAlertActive, Timestamp dangerAlertLastSentTimestamp, Boolean isDangerAlertAcknowledged, String dangerActiveAlertsSet, Timestamp dangerFirstActiveAt) { this(id, name, ((name == null) ? null : name.toUpperCase()), description, metricGroupId, isEnabled, isCautionEnabled, isDangerEnabled, alertType, alertOnPositive, allowResendAlert, resendAlertEvery, resendAlertEveryTimeUnit, cautionNotificationGroupId, cautionPositiveNotificationGroupId, cautionOperator, cautionCombination, cautionCombinationCount, cautionThreshold, cautionWindowDuration, cautionWindowDurationTimeUnit, cautionStopTrackingAfter, cautionStopTrackingAfterTimeUnit, cautionMinimumSampleCount, isCautionAlertActive, cautionAlertLastSentTimestamp, isCautionAlertAcknowledged, cautionActiveAlertsSet, cautionFirstActiveAt, dangerNotificationGroupId, dangerPositiveNotificationGroupId, dangerOperator, dangerCombination, dangerCombinationCount, dangerThreshold, dangerWindowDuration, dangerWindowDurationTimeUnit, dangerStopTrackingAfter, dangerStopTrackingAfterTimeUnit, dangerMinimumSampleCount, isDangerAlertActive, dangerAlertLastSentTimestamp, isDangerAlertAcknowledged, dangerActiveAlertsSet, dangerFirstActiveAt); } public Alert(Integer id, String name, String uppercaseName, String description, Integer metricGroupId, Boolean isEnabled, Boolean isCautionEnabled, Boolean isDangerEnabled, Integer alertType, Boolean alertOnPositive, Boolean allowResendAlert, Long resendAlertEvery, Integer resendAlertEveryTimeUnit, Integer cautionNotificationGroupId, Integer cautionPositiveNotificationGroupId, Integer cautionOperator, Integer cautionCombination, Integer cautionCombinationCount, BigDecimal cautionThreshold, Long cautionWindowDuration, Integer cautionWindowDurationTimeUnit, Long cautionStopTrackingAfter, Integer cautionStopTrackingAfterTimeUnit, Integer cautionMinimumSampleCount, Boolean isCautionAlertActive, Timestamp cautionAlertLastSentTimestamp, Boolean isCautionAlertAcknowledged, String cautionActiveAlertsSet, Timestamp cautionFirstActiveAt, Integer dangerNotificationGroupId, Integer dangerPositiveNotificationGroupId, Integer dangerOperator, Integer dangerCombination, Integer dangerCombinationCount, BigDecimal dangerThreshold, Long dangerWindowDuration, Integer dangerWindowDurationTimeUnit, Long dangerStopTrackingAfter, Integer dangerStopTrackingAfterTimeUnit, Integer dangerMinimumSampleCount, Boolean isDangerAlertActive, Timestamp dangerAlertLastSentTimestamp, Boolean isDangerAlertAcknowledged, String dangerActiveAlertsSet, Timestamp dangerFirstActiveAt) { this.id_ = id; this.name_ = name; this.uppercaseName_ = uppercaseName; this.description_ = description; this.metricGroupId_ = metricGroupId; this.isEnabled_ = isEnabled; this.isCautionEnabled_ = isCautionEnabled; this.isDangerEnabled_ = isDangerEnabled; this.alertType_ = alertType; this.alertOnPositive_ = alertOnPositive; this.allowResendAlert_ = allowResendAlert; this.resendAlertEvery_ = resendAlertEvery; this.resendAlertEveryTimeUnit_ = resendAlertEveryTimeUnit; this.cautionNotificationGroupId_ = cautionNotificationGroupId; this.cautionPositiveNotificationGroupId_ = cautionPositiveNotificationGroupId; this.cautionOperator_ = cautionOperator; this.cautionCombination_ = cautionCombination; this.cautionCombinationCount_ = cautionCombinationCount; this.cautionThreshold_ = cautionThreshold; this.cautionWindowDuration_ = cautionWindowDuration; this.cautionWindowDurationTimeUnit_ = cautionWindowDurationTimeUnit; this.cautionStopTrackingAfter_ = cautionStopTrackingAfter; this.cautionStopTrackingAfterTimeUnit_ = cautionStopTrackingAfterTimeUnit; this.cautionMinimumSampleCount_ = cautionMinimumSampleCount; this.isCautionAlertActive_ = isCautionAlertActive; if (cautionAlertLastSentTimestamp == null) this.cautionAlertLastSentTimestamp_ = null; else this.cautionAlertLastSentTimestamp_ = (Timestamp) cautionAlertLastSentTimestamp.clone(); this.isCautionAlertAcknowledged_ = isCautionAlertAcknowledged; this.cautionActiveAlertsSet_ = cautionActiveAlertsSet; this.cautionFirstActiveAt_ = cautionFirstActiveAt; this.dangerNotificationGroupId_ = dangerNotificationGroupId; this.dangerPositiveNotificationGroupId_ = dangerPositiveNotificationGroupId; this.dangerOperator_ = dangerOperator; this.dangerCombination_ = dangerCombination; this.dangerCombinationCount_ = dangerCombinationCount; this.dangerThreshold_ = dangerThreshold; this.dangerWindowDuration_ = dangerWindowDuration; this.dangerWindowDurationTimeUnit_ = dangerWindowDurationTimeUnit; this.dangerStopTrackingAfter_ = dangerStopTrackingAfter; this.dangerStopTrackingAfterTimeUnit_ = dangerStopTrackingAfterTimeUnit; this.dangerMinimumSampleCount_ = dangerMinimumSampleCount; this.isDangerAlertActive_ = isDangerAlertActive; if (dangerAlertLastSentTimestamp == null) this.dangerAlertLastSentTimestamp_ = null; else this.dangerAlertLastSentTimestamp_ = (Timestamp) dangerAlertLastSentTimestamp.clone(); this.isDangerAlertAcknowledged_ = isDangerAlertAcknowledged; this.dangerActiveAlertsSet_ = dangerActiveAlertsSet; this.dangerFirstActiveAt_ = dangerFirstActiveAt; } public static Alert copy(Alert alert) { if (alert == null) { return null; } Alert alertCopy = new Alert(); alertCopy.setId(alert.getId()); alertCopy.setName(alert.getName()); alertCopy.setUppercaseName(alert.getUppercaseName()); alertCopy.setDescription(alert.getDescription()); alertCopy.setMetricGroupId(alert.getMetricGroupId()); alertCopy.setIsEnabled(alert.isEnabled()); alertCopy.setIsCautionEnabled(alert.isCautionEnabled()); alertCopy.setIsDangerEnabled(alert.isDangerEnabled()); alertCopy.setAlertType(alert.getAlertType()); alertCopy.setAlertOnPositive(alert.isAlertOnPositive()); alertCopy.setAllowResendAlert(alert.isAllowResendAlert()); alertCopy.setResendAlertEvery(alert.getResendAlertEvery()); alertCopy.setResendAlertEveryTimeUnit(alert.getResendAlertEveryTimeUnit()); alertCopy.setCautionNotificationGroupId(alert.getCautionNotificationGroupId()); alertCopy.setCautionPositiveNotificationGroupId(alert.getCautionPositiveNotificationGroupId()); alertCopy.setCautionOperator(alert.getCautionOperator()); alertCopy.setCautionCombination(alert.getCautionCombination()); alertCopy.setCautionCombinationCount(alert.getCautionCombinationCount()); alertCopy.setCautionThreshold(alert.getCautionThreshold()); alertCopy.setCautionWindowDuration(alert.getCautionWindowDuration()); alertCopy.setCautionWindowDurationTimeUnit(alert.getCautionWindowDurationTimeUnit()); alertCopy.setCautionStopTrackingAfter(alert.getCautionStopTrackingAfter()); alertCopy.setCautionStopTrackingAfterTimeUnit(alert.getCautionStopTrackingAfterTimeUnit()); alertCopy.setCautionMinimumSampleCount(alert.getCautionMinimumSampleCount()); alertCopy.setIsCautionAlertActive(alert.isCautionAlertActive()); if (alert.getCautionAlertLastSentTimestamp() == null) alertCopy.setCautionAlertLastSentTimestamp(null); else alertCopy.setCautionAlertLastSentTimestamp(new Timestamp(alert.getCautionAlertLastSentTimestamp().getTime())); alertCopy.setIsCautionAlertAcknowledged(alert.isCautionAlertAcknowledged()); alertCopy.setCautionActiveAlertsSet(alert.getCautionActiveAlertsSet()); alertCopy.setCautionFirstActiveAt(alert.getCautionFirstActiveAt()); alertCopy.setDangerNotificationGroupId(alert.getDangerNotificationGroupId()); alertCopy.setDangerPositiveNotificationGroupId(alert.getDangerPositiveNotificationGroupId()); alertCopy.setDangerOperator(alert.getDangerOperator()); alertCopy.setDangerCombination(alert.getDangerCombination()); alertCopy.setDangerCombinationCount(alert.getDangerCombinationCount()); alertCopy.setDangerThreshold(alert.getDangerThreshold()); alertCopy.setDangerWindowDuration(alert.getDangerWindowDuration()); alertCopy.setDangerWindowDurationTimeUnit(alert.getDangerWindowDurationTimeUnit()); alertCopy.setDangerStopTrackingAfter(alert.getDangerStopTrackingAfter()); alertCopy.setDangerStopTrackingAfterTimeUnit(alert.getDangerStopTrackingAfterTimeUnit()); alertCopy.setDangerMinimumSampleCount(alert.getDangerMinimumSampleCount()); alertCopy.setIsDangerAlertActive(alert.isDangerAlertActive()); if (alert.getDangerAlertLastSentTimestamp() == null) alertCopy.setDangerAlertLastSentTimestamp(null); else alertCopy.setDangerAlertLastSentTimestamp(new Timestamp(alert.getDangerAlertLastSentTimestamp().getTime())); alertCopy.setIsDangerAlertAcknowledged(alert.isDangerAlertAcknowledged()); alertCopy.setDangerActiveAlertsSet(alert.getDangerActiveAlertsSet()); alertCopy.setDangerFirstActiveAt(alert.getDangerFirstActiveAt()); return alertCopy; } @Override public boolean isEqual(Alert alert) { if (alert == null) return false; if (alert == this) return true; if (alert.getClass() != getClass()) return false; boolean isCautionThresholdValueEqual = MathUtilities.areBigDecimalsNumericallyEqual(cautionThreshold_, alert.getCautionThreshold()); boolean isDangerThresholdValueEqual = MathUtilities.areBigDecimalsNumericallyEqual(dangerThreshold_, alert.getDangerThreshold()); return new EqualsBuilder() .append(id_, alert.getId()) .append(name_, alert.getName()) .append(uppercaseName_, alert.getUppercaseName()) .append(description_, alert.getDescription()) .append(metricGroupId_, alert.getMetricGroupId()) .append(isEnabled_, alert.isEnabled()) .append(isCautionEnabled_, alert.isCautionEnabled()) .append(isDangerEnabled_, alert.isDangerEnabled()) .append(alertType_, alert.getAlertType()) .append(alertOnPositive_, alert.isAlertOnPositive()) .append(allowResendAlert_, alert.isAllowResendAlert()) .append(resendAlertEvery_, alert.getResendAlertEvery()) .append(resendAlertEveryTimeUnit_, alert.getResendAlertEveryTimeUnit()) .append(cautionNotificationGroupId_, alert.getCautionNotificationGroupId()) .append(cautionPositiveNotificationGroupId_, alert.getCautionPositiveNotificationGroupId()) .append(cautionOperator_, alert.getCautionOperator()) .append(cautionCombination_, alert.getCautionCombination()) .append(cautionCombinationCount_, alert.getCautionCombinationCount()) .append(isCautionThresholdValueEqual, true) .append(cautionWindowDuration_, alert.getCautionWindowDuration()) .append(cautionWindowDurationTimeUnit_, alert.getCautionWindowDurationTimeUnit()) .append(cautionStopTrackingAfter_, alert.getCautionStopTrackingAfter()) .append(cautionStopTrackingAfterTimeUnit_, alert.getCautionStopTrackingAfterTimeUnit()) .append(cautionMinimumSampleCount_, alert.getCautionMinimumSampleCount()) .append(isCautionAlertActive_, alert.isCautionAlertActive()) .append(cautionAlertLastSentTimestamp_, alert.getCautionAlertLastSentTimestamp()) .append(isCautionAlertAcknowledged_, alert.isCautionAlertAcknowledged()) .append(cautionActiveAlertsSet_, alert.getCautionActiveAlertsSet()) .append(cautionFirstActiveAt_, alert.getCautionFirstActiveAt()) .append(dangerNotificationGroupId_, alert.getDangerNotificationGroupId()) .append(dangerPositiveNotificationGroupId_, alert.getDangerPositiveNotificationGroupId()) .append(dangerOperator_, alert.getDangerOperator()) .append(dangerCombination_, alert.getDangerCombination()) .append(dangerCombinationCount_, alert.getDangerCombinationCount()) .append(isDangerThresholdValueEqual, true) .append(dangerWindowDuration_, alert.getDangerWindowDuration()) .append(dangerWindowDurationTimeUnit_, alert.getDangerWindowDurationTimeUnit()) .append(dangerStopTrackingAfter_, alert.getDangerStopTrackingAfter()) .append(dangerStopTrackingAfterTimeUnit_, alert.getDangerStopTrackingAfterTimeUnit()) .append(dangerMinimumSampleCount_, alert.getDangerMinimumSampleCount()) .append(isDangerAlertActive_, alert.isDangerAlertActive()) .append(dangerAlertLastSentTimestamp_, alert.getDangerAlertLastSentTimestamp()) .append(isDangerAlertAcknowledged_, alert.isDangerAlertAcknowledged()) .append(dangerActiveAlertsSet_, alert.getDangerActiveAlertsSet()) .append(dangerFirstActiveAt_, alert.getDangerFirstActiveAt()) .isEquals(); } /* If the caution criteria 'core' fields in 'this' alert are same as the comparison alert, then return true. Caution criteria 'core' fields are considered to be any field that would be worth resetting an alert's status if the field changed. For example, the triggered status of an alert is no longer valid if the danger-operator changes. This makes threshold a 'core' criteria field. */ public boolean isCautionCriteriaEqual(Alert alert) { if (alert == null) return false; if (alert == this) return true; if (alert.getClass() != getClass()) return false; boolean isCautionThresholdValueEqual = MathUtilities.areBigDecimalsNumericallyEqual(cautionThreshold_, alert.getCautionThreshold()); return new EqualsBuilder() .append(id_, alert.getId()) .append(metricGroupId_, alert.getMetricGroupId()) .append(isEnabled_, alert.isEnabled()) .append(isCautionEnabled_, alert.isCautionEnabled()) .append(alertType_, alert.getAlertType()) .append(cautionOperator_, alert.getCautionOperator()) .append(cautionCombination_, alert.getCautionCombination()) .append(cautionCombinationCount_, alert.getCautionCombinationCount()) .append(isCautionThresholdValueEqual, true) .append(cautionWindowDuration_, alert.getCautionWindowDuration()) .append(cautionWindowDurationTimeUnit_, alert.getCautionWindowDurationTimeUnit()) .append(cautionStopTrackingAfter_, alert.getCautionStopTrackingAfter()) .append(cautionStopTrackingAfterTimeUnit_, alert.getCautionStopTrackingAfterTimeUnit()) .append(cautionMinimumSampleCount_, alert.getCautionMinimumSampleCount()) .isEquals(); } /* If the danger criteria 'core' fields in 'this' alert are same as the comparison alert, then return true. Danger criteria 'core' fields are considered to be any field that would be worth resetting an alert's status if the field changed. For example, the triggered status of an alert is no longer valid if the danger-operator changes. This makes threshold a 'core' criteria field. */ public boolean isDangerCriteriaEqual(Alert alert) { if (alert == null) return false; if (alert == this) return true; if (alert.getClass() != getClass()) return false; boolean isDangerThresholdValueEqual = MathUtilities.areBigDecimalsNumericallyEqual(dangerThreshold_, alert.getDangerThreshold()); return new EqualsBuilder() .append(id_, alert.getId()) .append(metricGroupId_, alert.getMetricGroupId()) .append(isEnabled_, alert.isEnabled()) .append(isDangerEnabled_, alert.isDangerEnabled()) .append(alertType_, alert.getAlertType()) .append(dangerOperator_, alert.getDangerOperator()) .append(dangerCombination_, alert.getDangerCombination()) .append(dangerCombinationCount_, alert.getDangerCombinationCount()) .append(isDangerThresholdValueEqual, true) .append(dangerWindowDuration_, alert.getDangerWindowDuration()) .append(dangerWindowDurationTimeUnit_, alert.getDangerWindowDurationTimeUnit()) .append(dangerStopTrackingAfter_, alert.getDangerStopTrackingAfter()) .append(dangerStopTrackingAfterTimeUnit_, alert.getDangerStopTrackingAfterTimeUnit()) .append(dangerMinimumSampleCount_, alert.getDangerMinimumSampleCount()) .isEquals(); } /* Copies all caution 'metadata' fields from 'this' alert into 'alertToModify'. 'Metadata' fields are fields are not visable/settable directly via user-input */ public Alert copyCautionMetadataFields(Alert alertToModify) { if (alertToModify == null) { return null; } alertToModify.setIsCautionAlertActive(isCautionAlertActive_); alertToModify.setCautionAlertLastSentTimestamp(getCautionAlertLastSentTimestamp()); alertToModify.setCautionActiveAlertsSet(cautionActiveAlertsSet_); alertToModify.setCautionFirstActiveAt(getCautionFirstActiveAt()); return alertToModify; } /* Copies all danger 'metadata' fields from 'this' alert into 'alertToModify'. 'Metadata' fields are fields do not have a direct effect on the criteria of the alert, and aren't set via the user-interface */ public Alert copyDangerMetadataFields(Alert alertToModify) { if (alertToModify == null) { return null; } alertToModify.setIsDangerAlertActive(isDangerAlertActive_); alertToModify.setDangerAlertLastSentTimestamp(getDangerAlertLastSentTimestamp()); alertToModify.setDangerActiveAlertsSet(dangerActiveAlertsSet_); alertToModify.setDangerFirstActiveAt(getDangerFirstActiveAt()); return alertToModify; } public Long getLongestWindowDuration() { if ((cautionWindowDuration_ == null) && (dangerWindowDuration_ == null)) return null; if ((cautionWindowDuration_ != null) && (dangerWindowDuration_ == null)) return cautionWindowDuration_; if ((cautionWindowDuration_ == null) && (dangerWindowDuration_ != null)) return dangerWindowDuration_; if (cautionWindowDuration_ > dangerWindowDuration_) { return cautionWindowDuration_; } else { return dangerWindowDuration_; } } public boolean isCautionAlertCriteriaValid() { if (alertType_ == null) return false; if (alertType_ == TYPE_AVAILABILITY) { if (!isValid_CautionWindowDuration()) return false; if (!isValid_CautionStopTrackingAfter()) return false; } else if (alertType_ == TYPE_THRESHOLD) { if (!isValid_CautionOperation()) return false; if (!isValid_CautionCombination()) return false; if (getCautionThreshold() == null) return false; if (!isValid_CautionWindowDuration()) return false; if (!isValid_CautionMinimumSampleCount()) return false; } return true; } public boolean isDangerAlertCriteriaValid() { if (alertType_ == null) return false; if (alertType_ == TYPE_AVAILABILITY) { if (!isValid_DangerWindowDuration()) return false; if (!isValid_DangerStopTrackingAfter()) return false; } else if (alertType_ == TYPE_THRESHOLD) { if (!isValid_DangerOperation()) return false; if (!isValid_DangerCombination()) return false; if (getDangerThreshold() == null) return false; if (!isValid_DangerWindowDuration()) return false; if (!isValid_DangerMinimumSampleCount()) return false; } return true; } public boolean isValid_CautionOperation() { if (cautionOperator_ == null) { return false; } return (cautionOperator_ >= 1) && (cautionOperator_ <= 5); } public boolean isValid_DangerOperation() { if (dangerOperator_ == null) { return false; } return (dangerOperator_ >= 1) && (dangerOperator_ <= 5); } public boolean isValid_CautionCombination() { if (cautionCombination_ == null) { return false; } if ((cautionCombination_ >= 101) && (cautionCombination_ <= 106) && (cautionCombination_ != 104)) { if ((Objects.equals(cautionCombination_, COMBINATION_AT_LEAST_COUNT)) || (Objects.equals(cautionCombination_, COMBINATION_AT_MOST_COUNT))) { if ((cautionCombinationCount_ == null) || (cautionCombinationCount_ < 0)) { return false; } } return true; } return false; } public boolean isValid_DangerCombination() { if (dangerCombination_ == null) { return false; } if ((dangerCombination_ >= 101) && (dangerCombination_ <= 106) && (dangerCombination_ != 104)) { if ((Objects.equals(dangerCombination_, COMBINATION_AT_LEAST_COUNT)) || (Objects.equals(dangerCombination_, COMBINATION_AT_MOST_COUNT))) { if ((dangerCombinationCount_ == null) || (dangerCombinationCount_ < 0)) { return false; } } return true; } return false; } public boolean isValid_CautionWindowDuration() { if (cautionWindowDuration_ == null) { return false; } return cautionWindowDuration_ >= 1; } public boolean isValid_CautionStopTrackingAfter() { if (cautionStopTrackingAfter_ == null) { return false; } return cautionStopTrackingAfter_ >= 1; } public boolean isValid_DangerWindowDuration() { if (dangerWindowDuration_ == null) { return false; } return dangerWindowDuration_ >= 1; } public boolean isValid_DangerStopTrackingAfter() { if (dangerStopTrackingAfter_ == null) { return false; } return dangerStopTrackingAfter_ >= 1; } public boolean isValid_CautionMinimumSampleCount() { if (cautionMinimumSampleCount_ == null) { return false; } return cautionMinimumSampleCount_ >= 1; } public boolean isValid_DangerMinimumSampleCount() { if (dangerMinimumSampleCount_ == null) { return false; } return dangerMinimumSampleCount_ >= 1; } public String getOperatorString(int alertLevel, boolean includeSymbol, boolean includeEnglish) { if ((alertLevel == Alert.CAUTION) && (cautionOperator_ == null)) return null; if ((alertLevel == Alert.DANGER) && (dangerOperator_ == null)) return null; int operator = -1; if (alertLevel == Alert.CAUTION) operator = cautionOperator_; else if (alertLevel == Alert.DANGER) operator = dangerOperator_; if (includeSymbol && includeEnglish) { if (operator == OPERATOR_GREATER) return "> (greater than)"; else if (operator == OPERATOR_GREATER_EQUALS) return ">= (greater than or equal to)"; else if (operator == OPERATOR_LESS) return "< (less than)"; else if (operator == OPERATOR_LESS_EQUALS) return "<= (less than or equal to)"; else if (operator == OPERATOR_EQUALS) return "= (equal to)"; else logger.warn("Unrecognized operator code"); } else if (includeSymbol) { if (operator == OPERATOR_GREATER) return ">"; else if (operator == OPERATOR_GREATER_EQUALS) return ">="; else if (operator == OPERATOR_LESS) return "<"; else if (operator == OPERATOR_LESS_EQUALS) return "<="; else if (operator == OPERATOR_EQUALS) return "="; else logger.warn("Unrecognized operator code"); } else if (includeEnglish) { if (operator == OPERATOR_GREATER) return "greater than"; else if (operator == OPERATOR_GREATER_EQUALS) return "greater than or equal to"; else if (operator == OPERATOR_LESS) return "less than"; else if (operator == OPERATOR_LESS_EQUALS) return "less than or equal to"; else if (operator == OPERATOR_EQUALS) return "equal to"; else logger.warn("Unrecognized operator code"); } return null; } public static Integer getOperatorCodeFromOperatorString(String operator) { if ((operator == null) || operator.isEmpty()) { return null; } if (operator.equals(">") || operator.contains("(greater than)")) return OPERATOR_GREATER; else if (operator.equals(">=") || operator.contains("(greater than or equal to)")) return OPERATOR_GREATER_EQUALS; else if (operator.equals("<") || operator.contains("(less than)")) return OPERATOR_LESS; else if (operator.equals("<=") || operator.contains("(less than or equal to)")) return OPERATOR_LESS_EQUALS; else if (operator.equals("=") || operator.contains("(equal to)")) return OPERATOR_EQUALS; else logger.warn("Unrecognized operator string"); return null; } public String getCombinationString(int alertLevel) { if ((alertLevel == Alert.CAUTION) && (cautionCombination_ == null)) return null; if ((alertLevel == Alert.DANGER) && (dangerCombination_ == null)) return null; int combination = -1; if (alertLevel == Alert.CAUTION) combination = cautionCombination_; else if (alertLevel == Alert.DANGER) combination = dangerCombination_; if (combination == COMBINATION_ANY) return "Any"; else if (combination == COMBINATION_ALL) return "All"; else if (combination == COMBINATION_AVERAGE) return "Average"; else if (combination == COMBINATION_AT_MOST_COUNT) return "At most"; else if (combination == COMBINATION_AT_LEAST_COUNT) return "At least"; else logger.warn("Unrecognized combination code"); return null; } public static Integer getCombinationCodeFromString(String combination) { if ((combination == null) || combination.isEmpty()) { return null; } if (combination.equalsIgnoreCase("Any")) return COMBINATION_ANY; else if (combination.equalsIgnoreCase("All")) return COMBINATION_ALL; else if (combination.equalsIgnoreCase("Average")) return COMBINATION_AVERAGE; else if (combination.equalsIgnoreCase("At most")) return COMBINATION_AT_MOST_COUNT; else if (combination.equalsIgnoreCase("At least")) return COMBINATION_AT_LEAST_COUNT; else logger.warn("Unrecognized combination string"); return null; } public static String getMetricValueString_WithLabel(int alertLevel, Alert alert, BigDecimal metricValue) { if ((alert == null) || (metricValue == null) || (alert.getAlertType() == null)) { return null; } String outputString = null; if (alert.getAlertType() == Alert.TYPE_THRESHOLD) { int combination = -1; if (alertLevel == Alert.CAUTION) combination = alert.getCautionCombination(); else if (alertLevel == Alert.DANGER) combination = alert.getDangerCombination(); String metricValueString = metricValue.stripTrailingZeros().toPlainString(); if (Alert.COMBINATION_ALL == combination) outputString = metricValueString + " (recent value)"; else if (Alert.COMBINATION_ANY == combination) outputString = metricValueString + " (recent value)"; else if (Alert.COMBINATION_AVERAGE == combination) outputString = metricValueString + " (avg value)"; else if (Alert.COMBINATION_AT_LEAST_COUNT == combination) outputString = metricValueString + " (count)"; else if (Alert.COMBINATION_AT_MOST_COUNT == combination) outputString = metricValueString + " (count)"; else logger.warn("Unrecognized combination code"); } else if (alert.getAlertType() == Alert.TYPE_AVAILABILITY) { BigDecimal metricValue_Seconds = metricValue.divide(new BigDecimal(1000)); String metricValueString = metricValue_Seconds.stripTrailingZeros().toPlainString(); outputString = metricValueString + " (seconds since last data point received)"; } return outputString; } public String getHumanReadable_AlertCriteria_MinimumSampleCount(int alertLevel) { if ((alertLevel == Alert.CAUTION) && (getCautionMinimumSampleCount() == null)) return null; else if ((alertLevel == Alert.DANGER) && (getDangerMinimumSampleCount() == null)) return null; else if ((alertLevel != Alert.CAUTION) && (alertLevel != Alert.DANGER)) return null; if (alertLevel == Alert.CAUTION) return "A minimum of " + getCautionMinimumSampleCount() + " sample(s)"; else if (alertLevel == Alert.DANGER) return "A minimum of " + getDangerMinimumSampleCount() + " sample(s)"; else return null; } public String getHumanReadable_AlertCriteria_AvailabilityCriteria(int alertLevel) { if ((alertLevel != Alert.CAUTION) && (alertLevel != Alert.DANGER)) { return null; } try { if (alertLevel == Alert.CAUTION) { if ((getCautionWindowDuration() == null) || (getCautionWindowDurationTimeUnit() == null)) return null; BigDecimal cautionWindowDuration = DatabaseObjectCommon.getValueForTimeFromMilliseconds(getCautionWindowDuration(), getCautionWindowDurationTimeUnit()); String cautionWindowDurationTimeUnit = ""; if (getCautionWindowDurationTimeUnit() != null) cautionWindowDurationTimeUnit = DatabaseObjectCommon.getTimeUnitStringFromCode(getCautionWindowDurationTimeUnit(), true); StringBuilder humanReadableAvailabilityCriteria = new StringBuilder(); humanReadableAvailabilityCriteria.append("No new data points were received during the last ") .append(cautionWindowDuration.stripTrailingZeros().toPlainString()) .append(" ").append(cautionWindowDurationTimeUnit); return humanReadableAvailabilityCriteria.toString(); } else if (alertLevel == Alert.DANGER) { if ((getDangerWindowDuration() == null) || (getDangerWindowDurationTimeUnit() == null)) return null; BigDecimal dangerWindowDuration = DatabaseObjectCommon.getValueForTimeFromMilliseconds(getDangerWindowDuration(), getDangerWindowDurationTimeUnit()); String dangerWindowDurationTimeUnit = ""; if (getDangerWindowDurationTimeUnit() != null) dangerWindowDurationTimeUnit = DatabaseObjectCommon.getTimeUnitStringFromCode(getDangerWindowDurationTimeUnit(), true); StringBuilder humanReadableAvailabilityCriteria = new StringBuilder(); humanReadableAvailabilityCriteria.append("No new data points were received during the last ") .append(dangerWindowDuration.stripTrailingZeros().toPlainString()) .append(" ").append(dangerWindowDurationTimeUnit); return humanReadableAvailabilityCriteria.toString(); } else return null; } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); return null; } } public String getHumanReadable_AlertCriteria_ThresholdCriteria(int alertLevel) { if ((alertLevel != Alert.CAUTION) && (alertLevel != Alert.DANGER)) { return null; } try { if (alertLevel == Alert.CAUTION) { if ((getCautionWindowDuration() == null) || (getCautionWindowDurationTimeUnit() == null) || (getCautionThreshold() == null) || (getCautionOperator() == null)) return null; BigDecimal cautionWindowDuration = DatabaseObjectCommon.getValueForTimeFromMilliseconds(getCautionWindowDuration(), getCautionWindowDurationTimeUnit()); String cautionWindowDurationTimeUnit = ""; if (getCautionWindowDurationTimeUnit() != null) cautionWindowDurationTimeUnit = DatabaseObjectCommon.getTimeUnitStringFromCode(getCautionWindowDurationTimeUnit(), true); StringBuilder humanReadableThresholdCriteria = new StringBuilder(); humanReadableThresholdCriteria.append(getHumanReadable_ThresholdCriteria_Combination(Alert.CAUTION)).append(" ").append(getOperatorString(Alert.CAUTION, false, true)) .append(" ").append(getCautionThreshold().stripTrailingZeros().toPlainString()) .append(" during the last ").append(cautionWindowDuration.stripTrailingZeros().toPlainString()).append(" ").append(cautionWindowDurationTimeUnit); return humanReadableThresholdCriteria.toString(); } else if (alertLevel == Alert.DANGER) { if ((getDangerWindowDuration() == null) || (getDangerWindowDurationTimeUnit() == null) || (getDangerThreshold() == null) || (getDangerOperator() == null)) return null; BigDecimal dangerWindowDuration = DatabaseObjectCommon.getValueForTimeFromMilliseconds(getDangerWindowDuration(), getDangerWindowDurationTimeUnit()); String dangerWindowDurationTimeUnit = ""; if (getDangerWindowDurationTimeUnit() != null) dangerWindowDurationTimeUnit = DatabaseObjectCommon.getTimeUnitStringFromCode(getDangerWindowDurationTimeUnit(), true); StringBuilder humanReadableThresholdCriteria = new StringBuilder(); humanReadableThresholdCriteria.append(getHumanReadable_ThresholdCriteria_Combination(Alert.DANGER)).append(" ").append(getOperatorString(Alert.DANGER, false, true)) .append(" ").append(getDangerThreshold().stripTrailingZeros().toPlainString()) .append(" during the last ").append(dangerWindowDuration.stripTrailingZeros().toPlainString()).append(" ").append(dangerWindowDurationTimeUnit); return humanReadableThresholdCriteria.toString(); } else return null; } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); return null; } } private String getHumanReadable_ThresholdCriteria_Combination(int alertLevel) { if ((alertLevel != Alert.CAUTION) && (alertLevel != Alert.DANGER)) { return null; } Integer combination = null; if (alertLevel == Alert.CAUTION) combination = getCautionCombination(); else if (alertLevel == Alert.DANGER) combination = getDangerCombination(); Integer combinationCount = null; if (alertLevel == Alert.CAUTION) combinationCount = getCautionCombinationCount(); else if (alertLevel == Alert.DANGER) combinationCount = getDangerCombinationCount(); if (combination != null) { if (Objects.equals(combination, Alert.COMBINATION_ANY)) return "Any metric value was"; else if (Objects.equals(combination, Alert.COMBINATION_ALL)) return "All metric values were"; else if (Objects.equals(combination, Alert.COMBINATION_AVERAGE)) return "The average metric value was"; else if (Objects.equals(combination, Alert.COMBINATION_AT_MOST_COUNT) && (combinationCount != null)) return "At most " + combinationCount + " metric values were"; else if (Objects.equals(combination, Alert.COMBINATION_AT_LEAST_COUNT) && (combinationCount != null)) return "At least " + combinationCount + " metric values were"; else return null; } else return null; } public String getHumanReadable_AmountOfTimeAlertIsTriggered(int alertLevel, Calendar currentDateAndTime) { if ((alertLevel != Alert.CAUTION) && (alertLevel != Alert.DANGER)) return null; if (currentDateAndTime == null) return null; Long secondsBetweenNowAndFirstAlerted = null; if ((alertLevel == Alert.CAUTION) && (getCautionFirstActiveAt() != null)) secondsBetweenNowAndFirstAlerted = (long) ((currentDateAndTime.getTimeInMillis() - getCautionFirstActiveAt().getTime()) / 1000); else if ((alertLevel == Alert.DANGER) && (getDangerFirstActiveAt() != null)) secondsBetweenNowAndFirstAlerted = (long) ((currentDateAndTime.getTimeInMillis() - getDangerFirstActiveAt().getTime()) / 1000); if (secondsBetweenNowAndFirstAlerted != null) { StringBuilder alertTriggeredAt = new StringBuilder(); long days = TimeUnit.SECONDS.toDays(secondsBetweenNowAndFirstAlerted); long hours = TimeUnit.SECONDS.toHours(secondsBetweenNowAndFirstAlerted) - (days * 24); long minutes = TimeUnit.SECONDS.toMinutes(secondsBetweenNowAndFirstAlerted) - (TimeUnit.SECONDS.toHours(secondsBetweenNowAndFirstAlerted) * 60); long seconds = TimeUnit.SECONDS.toSeconds(secondsBetweenNowAndFirstAlerted) - (TimeUnit.SECONDS.toMinutes(secondsBetweenNowAndFirstAlerted) * 60); String daysString = ""; if (days == 1) daysString = days + " day, "; else if (days > 1) daysString = days + " days, "; alertTriggeredAt.append(daysString); String hoursString = ""; if (hours == 1) hoursString = hours + " hour, "; else if ((hours > 1) || ((alertTriggeredAt.length() > 0) && (hours == 0))) hoursString = hours + " hours, "; alertTriggeredAt.append(hoursString); String minutesString = ""; if (minutes == 1) minutesString = minutes + " minute, "; else if ((minutes > 1) || ((alertTriggeredAt.length() > 0) && (minutes == 0))) minutesString = minutes + " minutes, "; alertTriggeredAt.append(minutesString); String secondsString = ""; if (seconds == 1) secondsString = seconds + " second"; else if ((seconds > 1) || (seconds == 0)) secondsString = seconds + " seconds"; alertTriggeredAt.append(secondsString); return alertTriggeredAt.toString(); } else { return null; } } public static JsonObject getJsonObject_ApiFriendly(Alert alert) { return getJsonObject_ApiFriendly(alert, null, null, null, null, null, null); } public static JsonObject getJsonObject_ApiFriendly(Alert alert, MetricGroup metricGroup, List<MetricGroupTag> metricGroupTags, NotificationGroup cautionNotificationGroup, NotificationGroup cautionPositiveNotificationGroup, NotificationGroup dangerNotificationGroup, NotificationGroup dangerPositiveNotificationGroup) { if (alert == null) { return null; } try { Alert alert_Local = Alert.copy(alert); // ensures that alert acknowledgement statuses are output if ((alert_Local.isDangerAlertActive() != null) && alert_Local.isDangerAlertActive() && (alert_Local.isDangerAlertAcknowledged() == null)) alert_Local.setIsDangerAlertAcknowledged(false); if ((alert_Local.isCautionAlertActive() != null) && alert_Local.isCautionAlertActive() && (alert_Local.isCautionAlertAcknowledged() == null)) alert_Local.setIsCautionAlertAcknowledged(false); Gson alert_Gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); JsonElement alert_JsonElement = alert_Gson.toJsonTree(alert_Local); JsonObject jsonObject = new Gson().toJsonTree(alert_JsonElement).getAsJsonObject(); String currentFieldToAlter; JsonElement currentField_JsonElement; if ((metricGroup != null) && (metricGroup.getId() != null) && (alert_Local.getMetricGroupId() != null) && (metricGroup.getId().intValue() == alert_Local.getMetricGroupId().intValue())) { jsonObject.addProperty("metric_group_name", metricGroup.getName()); } else if ((metricGroup != null) && (metricGroup.getId() != null) && (alert_Local.getMetricGroupId() != null)) { logger.error("'Metric Group Id' from the 'metricGroup' object must match the Alert's 'Metric Group Id'"); } JsonArray metricGroupTags_JsonArray = new JsonArray(); if ((metricGroupTags != null) && !metricGroupTags.isEmpty()) { for (MetricGroupTag metricGroupTag : metricGroupTags) { if ((metricGroupTag.getTag() != null) && (metricGroupTag.getMetricGroupId() != null) && (alert_Local.getMetricGroupId() != null) && (metricGroupTag.getMetricGroupId().intValue() == alert_Local.getMetricGroupId().intValue())) { metricGroupTags_JsonArray.add(metricGroupTag.getTag()); } } } jsonObject.add("metric_group_tags", metricGroupTags_JsonArray); if ((cautionNotificationGroup != null) && (cautionNotificationGroup.getId() != null) && (alert_Local.getCautionNotificationGroupId() != null) && (cautionNotificationGroup.getId().intValue() == alert_Local.getCautionNotificationGroupId().intValue())) { jsonObject.addProperty("caution_notification_group_name", cautionNotificationGroup.getName()); } else if ((cautionNotificationGroup != null) && (cautionNotificationGroup.getId() != null) && (alert_Local.getCautionNotificationGroupId() != null)) { logger.error("'Caution Notification Group Id' from the 'cautionNotificationGroup' object must match the Alert's 'Caution Notification Group Id'"); } if ((cautionPositiveNotificationGroup != null) && (cautionPositiveNotificationGroup.getId() != null) && (alert_Local.getCautionPositiveNotificationGroupId() != null) && (cautionPositiveNotificationGroup.getId().intValue() == alert_Local.getCautionPositiveNotificationGroupId().intValue())) { jsonObject.addProperty("caution_positive_notification_group_name", cautionPositiveNotificationGroup.getName()); } else if ((cautionPositiveNotificationGroup != null) && (cautionPositiveNotificationGroup.getId() != null) && (alert_Local.getCautionPositiveNotificationGroupId() != null)) { logger.error("'Caution Positive Notification Group Id' from the 'cautionPositiveNotificationGroup' object must match the Alert's 'Caution Positive Notification Group Id'"); } if ((dangerNotificationGroup != null) && (dangerNotificationGroup.getId() != null) && (alert_Local.getDangerNotificationGroupId() != null) && (dangerNotificationGroup.getId().intValue() == alert_Local.getDangerNotificationGroupId().intValue())) { jsonObject.addProperty("danger_notification_group_name", dangerNotificationGroup.getName()); } else if ((dangerNotificationGroup != null) && (dangerNotificationGroup.getId() != null) && (alert_Local.getDangerNotificationGroupId() != null)) { logger.error("'Danger Notification Group Id' from the 'dangerNotificationGroup' object must match the Alert's 'Danger Notification Group Id'"); } if ((dangerPositiveNotificationGroup != null) && (dangerPositiveNotificationGroup.getId() != null) && (alert_Local.getDangerPositiveNotificationGroupId() != null) && (dangerPositiveNotificationGroup.getId().intValue() == alert_Local.getDangerPositiveNotificationGroupId().intValue())) { jsonObject.addProperty("danger_positive_notification_group_name", dangerPositiveNotificationGroup.getName()); } else if ((dangerPositiveNotificationGroup != null) && (dangerPositiveNotificationGroup.getId() != null) && (alert_Local.getDangerPositiveNotificationGroupId() != null)) { logger.error("'Danger Positive Notification Group Id' from the 'dangerPositiveNotificationGroup' object must match the Alert's 'Danger Positive Notification Group Id'"); } currentFieldToAlter = "alert_type"; if (alert_Local.getAlertType() == Alert.TYPE_THRESHOLD) { jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, "Threshold"); } else if (alert_Local.getAlertType() == Alert.TYPE_AVAILABILITY) { jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, "Availability"); } else jsonObject.remove(currentFieldToAlter); DatabaseObjectCommon.getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(jsonObject, "resend_alert_every", "resend_alert_every_time_unit"); currentFieldToAlter = "caution_operator"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { String operatorString = alert_Local.getOperatorString(Alert.CAUTION, true, false); jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, operatorString); } currentFieldToAlter = "caution_combination"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { String combinationString = alert_Local.getCombinationString(Alert.CAUTION); jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, combinationString); } currentFieldToAlter = "caution_threshold"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { jsonObject.remove(currentFieldToAlter); JsonBigDecimal jsonBigDecimal = new JsonBigDecimal(alert_Local.getCautionThreshold()); jsonObject.addProperty(currentFieldToAlter, jsonBigDecimal); } DatabaseObjectCommon.getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(jsonObject, "caution_window_duration", "caution_window_duration_time_unit"); DatabaseObjectCommon.getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(jsonObject, "caution_stop_tracking_after", "caution_stop_tracking_after_time_unit"); currentFieldToAlter = "danger_operator"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { String operatorString = alert_Local.getOperatorString(Alert.DANGER, true, false); jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, operatorString); } currentFieldToAlter = "danger_combination"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { String combinationString = alert_Local.getCombinationString(Alert.DANGER); jsonObject.remove(currentFieldToAlter); jsonObject.addProperty(currentFieldToAlter, combinationString); } currentFieldToAlter = "danger_threshold"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if (currentField_JsonElement != null) { jsonObject.remove(currentFieldToAlter); JsonBigDecimal jsonBigDecimal = new JsonBigDecimal(alert_Local.getDangerThreshold()); jsonObject.addProperty(currentFieldToAlter, jsonBigDecimal); } DatabaseObjectCommon.getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(jsonObject, "danger_window_duration", "danger_window_duration_time_unit"); DatabaseObjectCommon.getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(jsonObject, "danger_stop_tracking_after", "danger_stop_tracking_after_time_unit"); currentFieldToAlter = "allow_resend_alert"; currentField_JsonElement = jsonObject.get(currentFieldToAlter); if ((currentField_JsonElement == null) || (alert_Local.isAllowResendAlert() == null) || !alert_Local.isAllowResendAlert()) { jsonObject.remove("resend_alert_every"); jsonObject.remove("resend_alert_every_time_unit"); } if ((alert_Local.isCautionEnabled() == null) || !alert_Local.isCautionEnabled()) { jsonObject.remove("caution_notification_group_id"); jsonObject.remove("caution_positive_notification_group_id"); jsonObject.remove("caution_minimum_sample_count"); jsonObject.remove("caution_combination"); jsonObject.remove("caution_window_duration"); jsonObject.remove("caution_window_duration_time_unit"); jsonObject.remove("caution_stop_tracking_after"); jsonObject.remove("caution_stop_tracking_after_time_unit"); jsonObject.remove("caution_operator"); jsonObject.remove("caution_threshold"); jsonObject.remove("caution_alert_active"); jsonObject.remove("caution_alert_acknowledged_status"); jsonObject.remove("caution_alert_last_sent_timestamp"); jsonObject.remove("caution_first_active_at"); } if ((alert_Local.isDangerEnabled() == null) || !alert_Local.isDangerEnabled()) { jsonObject.remove("danger_notification_group_id"); jsonObject.remove("danger_positive_notification_group_id"); jsonObject.remove("danger_minimum_sample_count"); jsonObject.remove("danger_combination"); jsonObject.remove("danger_window_duration"); jsonObject.remove("danger_window_duration_time_unit"); jsonObject.remove("danger_stop_tracking_after"); jsonObject.remove("danger_stop_tracking_after_time_unit"); jsonObject.remove("danger_operator"); jsonObject.remove("danger_threshold"); jsonObject.remove("danger_alert_active"); jsonObject.remove("danger_alert_acknowledged_status"); jsonObject.remove("danger_alert_last_sent_timestamp"); jsonObject.remove("danger_first_active_at"); } if (alert_Local.getAlertType() == Alert.TYPE_AVAILABILITY) { jsonObject.remove("caution_minimum_sample_count"); jsonObject.remove("caution_combination"); jsonObject.remove("caution_operator"); jsonObject.remove("caution_threshold"); jsonObject.remove("danger_minimum_sample_count"); jsonObject.remove("danger_combination"); jsonObject.remove("danger_operator"); jsonObject.remove("danger_threshold"); } if (alert_Local.getAlertType() == Alert.TYPE_THRESHOLD) { jsonObject.remove("caution_stop_tracking_after"); jsonObject.remove("caution_stop_tracking_after_time_unit"); jsonObject.remove("danger_stop_tracking_after"); jsonObject.remove("danger_stop_tracking_after_time_unit"); } if ((alert_Local.isAlertOnPositive() != null) && !alert_Local.isAlertOnPositive()) { jsonObject.remove("caution_notification_group_name"); jsonObject.remove("caution_notification_group_id"); jsonObject.remove("caution_positive_notification_group_name"); jsonObject.remove("caution_positive_notification_group_id"); jsonObject.remove("danger_notification_group_name"); jsonObject.remove("danger_notification_group_id"); jsonObject.remove("danger_positive_notification_group_name"); jsonObject.remove("danger_positive_notification_group_id"); } return jsonObject; } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); return null; } } public static String getJsonString_ApiFriendly(Alert alert) { return getJsonString_ApiFriendly(alert, null, null, null, null, null, null); } public static String getJsonString_ApiFriendly(Alert alert, MetricGroup metricGroup, List<MetricGroupTag> metricGroupTags, NotificationGroup cautionNotificationGroup, NotificationGroup cautionPositiveNotificationGroup, NotificationGroup dangerNotificationGroup, NotificationGroup dangerPositiveNotificationGroup) { if (alert == null) { return null; } try { JsonObject jsonObject = getJsonObject_ApiFriendly(alert, metricGroup, metricGroupTags, cautionNotificationGroup, cautionPositiveNotificationGroup, dangerNotificationGroup, dangerPositiveNotificationGroup); if (jsonObject == null) return null; Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); return gson.toJson(jsonObject); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); return null; } } public Integer getId() { return id_; } public void setId(Integer id) { this.id_ = id; } public String getName() { return name_; } public void setName(String name) { this.name_ = name; } public String getUppercaseName() { return uppercaseName_; } public void setUppercaseName(String uppercaseName) { this.uppercaseName_ = uppercaseName; } public String getDescription() { return description_; } public void setDescription(String description) { this.description_ = description; } public Integer getMetricGroupId() { return metricGroupId_; } public void setMetricGroupId(Integer metricGroupId) { this.metricGroupId_ = metricGroupId; } public Boolean isEnabled() { return isEnabled_; } public void setIsEnabled(Boolean isEnabled) { this.isEnabled_ = isEnabled; } public Boolean isCautionEnabled() { return isCautionEnabled_; } public void setIsCautionEnabled(Boolean isCautionEnabled) { this.isCautionEnabled_ = isCautionEnabled; } public Boolean isDangerEnabled() { return isDangerEnabled_; } public void setIsDangerEnabled(Boolean isDangerEnabled) { this.isDangerEnabled_ = isDangerEnabled; } public Integer getAlertType() { return alertType_; } public void setAlertType(Integer alertType) { this.alertType_ = alertType; } public Boolean isAlertOnPositive() { return alertOnPositive_; } public void setAlertOnPositive(Boolean alertOnPositive) { this.alertOnPositive_ = alertOnPositive; } public Boolean isAllowResendAlert() { return allowResendAlert_; } public void setAllowResendAlert(Boolean allowResendAlert) { this.allowResendAlert_ = allowResendAlert; } public Long getResendAlertEvery() { return resendAlertEvery_; } public void setResendAlertEvery(Long resendAlertEvery) { this.resendAlertEvery_ = resendAlertEvery; } public Integer getResendAlertEveryTimeUnit() { return resendAlertEveryTimeUnit_; } public void setResendAlertEveryTimeUnit(Integer resendAlertEveryTimeUnit) { this.resendAlertEveryTimeUnit_ = resendAlertEveryTimeUnit; } public Integer getCautionNotificationGroupId() { return cautionNotificationGroupId_; } public void setCautionNotificationGroupId(Integer cautionNotificationGroupId) { this.cautionNotificationGroupId_ = cautionNotificationGroupId; } public Integer getCautionPositiveNotificationGroupId() { return cautionPositiveNotificationGroupId_; } public void setCautionPositiveNotificationGroupId(Integer cautionPositiveNotificationGroupId) { this.cautionPositiveNotificationGroupId_ = cautionPositiveNotificationGroupId; } public Integer getCautionOperator() { return cautionOperator_; } public void setCautionOperator(Integer cautionOperator) { this.cautionOperator_ = cautionOperator; } public Integer getCautionCombination() { return cautionCombination_; } public void setCautionCombination(Integer cautionCombination) { this.cautionCombination_ = cautionCombination; } public Integer getCautionCombinationCount() { return cautionCombinationCount_; } public void setCautionCombinationCount(Integer cautionCombinationCount) { this.cautionCombinationCount_ = cautionCombinationCount; } public BigDecimal getCautionThreshold() { return cautionThreshold_; } public void setCautionThreshold(BigDecimal cautionThreshold) { this.cautionThreshold_ = cautionThreshold; } public Long getCautionWindowDuration() { return cautionWindowDuration_; } public void setCautionWindowDuration(Long cautionWindowDuration) { this.cautionWindowDuration_ = cautionWindowDuration; } public Integer getCautionWindowDurationTimeUnit() { return cautionWindowDurationTimeUnit_; } public void setCautionWindowDurationTimeUnit(Integer cautionWindowDurationTimeUnit) { this.cautionWindowDurationTimeUnit_ = cautionWindowDurationTimeUnit; } public Long getCautionStopTrackingAfter() { return cautionStopTrackingAfter_; } public void setCautionStopTrackingAfter(Long cautionStopTrackingAfter) { this.cautionStopTrackingAfter_ = cautionStopTrackingAfter; } public Integer getCautionStopTrackingAfterTimeUnit() { return cautionStopTrackingAfterTimeUnit_; } public void setCautionStopTrackingAfterTimeUnit(Integer cautionStopTrackingAfterTimeUnit) { this.cautionStopTrackingAfterTimeUnit_ = cautionStopTrackingAfterTimeUnit; } public Integer getCautionMinimumSampleCount() { return cautionMinimumSampleCount_; } public void setCautionMinimumSampleCount(Integer cautionMinimumSampleCount) { this.cautionMinimumSampleCount_ = cautionMinimumSampleCount; } public Boolean isCautionAlertActive() { return isCautionAlertActive_; } public void setIsCautionAlertActive(Boolean isCautionAlertActive) { this.isCautionAlertActive_ = isCautionAlertActive; } public Timestamp getCautionAlertLastSentTimestamp() { if (cautionAlertLastSentTimestamp_ == null) return null; else return (Timestamp) cautionAlertLastSentTimestamp_.clone(); } public void setCautionAlertLastSentTimestamp(Timestamp cautionAlertLastSentTimestamp) { if (cautionAlertLastSentTimestamp == null) this.cautionAlertLastSentTimestamp_ = null; else this.cautionAlertLastSentTimestamp_ = (Timestamp) cautionAlertLastSentTimestamp.clone(); } public Boolean isCautionAlertAcknowledged() { return isCautionAlertAcknowledged_; } public void setIsCautionAlertAcknowledged(Boolean isCautionAlertAcknowledged) { this.isCautionAlertAcknowledged_ = isCautionAlertAcknowledged; } public String getCautionActiveAlertsSet() { return cautionActiveAlertsSet_; } public void setCautionActiveAlertsSet(String cautionActiveAlertsSet) { this.cautionActiveAlertsSet_ = cautionActiveAlertsSet; } public Timestamp getCautionFirstActiveAt() { if (cautionFirstActiveAt_ == null) return null; else return (Timestamp) cautionFirstActiveAt_.clone(); } public void setCautionFirstActiveAt(Timestamp cautionFirstActiveAt) { if (cautionFirstActiveAt == null) this.cautionFirstActiveAt_ = null; else this.cautionFirstActiveAt_ = (Timestamp) cautionFirstActiveAt.clone(); } public Integer getDangerNotificationGroupId() { return dangerNotificationGroupId_; } public void setDangerNotificationGroupId(Integer dangerNotificationGroupId) { this.dangerNotificationGroupId_ = dangerNotificationGroupId; } public Integer getDangerPositiveNotificationGroupId() { return dangerPositiveNotificationGroupId_; } public void setDangerPositiveNotificationGroupId(Integer dangerPositiveNotificationGroupId) { this.dangerPositiveNotificationGroupId_ = dangerPositiveNotificationGroupId; } public Integer getDangerOperator() { return dangerOperator_; } public void setDangerOperator(Integer dangerOperator) { this.dangerOperator_ = dangerOperator; } public Integer getDangerCombination() { return dangerCombination_; } public void setDangerCombination(Integer dangerCombination) { this.dangerCombination_ = dangerCombination; } public Integer getDangerCombinationCount() { return dangerCombinationCount_; } public void setDangerCombinationCount(Integer dangerCombinationCount) { this.dangerCombinationCount_ = dangerCombinationCount; } public BigDecimal getDangerThreshold() { return dangerThreshold_; } public void setDangerThreshold(BigDecimal dangerThreshold) { this.dangerThreshold_ = dangerThreshold; } public Long getDangerWindowDuration() { return dangerWindowDuration_; } public void setDangerWindowDuration(Long dangerWindowDuration) { this.dangerWindowDuration_ = dangerWindowDuration; } public Integer getDangerWindowDurationTimeUnit() { return dangerWindowDurationTimeUnit_; } public void setDangerWindowDurationTimeUnit(Integer dangerWindowDurationTimeUnit) { this.dangerWindowDurationTimeUnit_ = dangerWindowDurationTimeUnit; } public Long getDangerStopTrackingAfter() { return dangerStopTrackingAfter_; } public void setDangerStopTrackingAfter(Long dangerStopTrackingAfter) { this.dangerStopTrackingAfter_ = dangerStopTrackingAfter; } public Integer getDangerStopTrackingAfterTimeUnit() { return dangerStopTrackingAfterTimeUnit_; } public void setDangerStopTrackingAfterTimeUnit(Integer dangerStopTrackingAfterTimeUnit) { this.dangerStopTrackingAfterTimeUnit_ = dangerStopTrackingAfterTimeUnit; } public Integer getDangerMinimumSampleCount() { return dangerMinimumSampleCount_; } public void setDangerMinimumSampleCount(Integer dangerMinimumSampleCount) { this.dangerMinimumSampleCount_ = dangerMinimumSampleCount; } public Boolean isDangerAlertActive() { return isDangerAlertActive_; } public void setIsDangerAlertActive(Boolean isDangerAlertActive) { this.isDangerAlertActive_ = isDangerAlertActive; } public Timestamp getDangerAlertLastSentTimestamp() { if (dangerAlertLastSentTimestamp_ == null) return null; else return (Timestamp) dangerAlertLastSentTimestamp_.clone(); } public void setDangerAlertLastSentTimestamp(Timestamp dangerAlertLastSentTimestamp) { if (dangerAlertLastSentTimestamp == null) this.dangerAlertLastSentTimestamp_ = null; else this.dangerAlertLastSentTimestamp_ = (Timestamp) dangerAlertLastSentTimestamp.clone(); } public Boolean isDangerAlertAcknowledged() { return isDangerAlertAcknowledged_; } public void setIsDangerAlertAcknowledged(Boolean isDangerAlertAcknowledged) { this.isDangerAlertAcknowledged_ = isDangerAlertAcknowledged; } public String getDangerActiveAlertsSet() { return dangerActiveAlertsSet_; } public void setDangerActiveAlertsSet(String dangerActiveAlertsSet) { this.dangerActiveAlertsSet_ = dangerActiveAlertsSet; } public Timestamp getDangerFirstActiveAt() { if (dangerFirstActiveAt_ == null) return null; else return (Timestamp) dangerFirstActiveAt_.clone(); } public void setDangerFirstActiveAt(Timestamp dangerFirstActiveAt) { if (dangerFirstActiveAt == null) this.dangerFirstActiveAt_ = null; else this.dangerFirstActiveAt_ = (Timestamp) dangerFirstActiveAt.clone(); } }
{ "content_hash": "6d06e328c1a0401547c76c6ba663952e", "timestamp": "", "source": "github", "line_count": 1478, "max_line_length": 217, "avg_line_length": 50.61299052774019, "alnum_prop": 0.6775124989974066, "repo_name": "PearsonEducation/StatsAgg", "id": "d74ad9d84a5eb612ca1a6aa9044d3f841ac17deb", "size": "74806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/pearson/statsagg/database_objects/alerts/Alert.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "69847" }, { "name": "HTML", "bytes": "918294" }, { "name": "Java", "bytes": "2248082" }, { "name": "JavaScript", "bytes": "372161" } ], "symlink_target": "" }
const fs = require('fs'); const { spawn, spawnSync, exec, execSync } = require('child_process'); let nginx_v = spawnSync('nginx',['-v']); nginx_v = nginx_v.stdout.toString().trim() || nginx_v.stderr.toString().trim(); const php_v = execSync('php -v').toString().trim(); const mysql_v = execSync('mysql -V').toString().trim(); // console.log(nginx_v); const index = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>LEMP in docker test</title> <style> body{ text-align:center} .version{ margin:0 auto; border:1px solid #F00} </style> </head> <body> lemp versions: <div class="version"> ${nginx_v}<br> ${php_v}<br> ${mysql_v} </div> <br> <?php echo phpinfo(); ?> </body> </html> `; // console.log(index); fs.writeFileSync('index.html', index);
{ "content_hash": "10920e4b50298929d820c203eacb14d4", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 79, "avg_line_length": 23.5, "alnum_prop": 0.6132665832290363, "repo_name": "novice79/lemp", "id": "5805b7beab6c3aa22621b4555e0a8c1e60ec6ea0", "size": "799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "t.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1880" }, { "name": "JavaScript", "bytes": "6844" }, { "name": "Shell", "bytes": "2800" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.8"/> <title>Thecallr .NET SDK: ThecallrApi.Exception.LocalApiException Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Thecallr .NET SDK &#160;<span id="projectnumber">1.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.8 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Properties</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespace_thecallr_api.html">ThecallrApi</a></li><li class="navelem"><a class="el" href="namespace_thecallr_api_1_1_exception.html">Exception</a></li><li class="navelem"><a class="el" href="class_thecallr_api_1_1_exception_1_1_local_api_exception.html">LocalApiException</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="class_thecallr_api_1_1_exception_1_1_local_api_exception-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">ThecallrApi.Exception.LocalApiException Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>This class represents an internal library error. <a href="class_thecallr_api_1_1_exception_1_1_local_api_exception.html#details">More...</a></p> <div class="dynheader"> Inheritance diagram for ThecallrApi.Exception.LocalApiException:</div> <div class="dyncontent"> <div class="center"> <img src="class_thecallr_api_1_1_exception_1_1_local_api_exception.png" usemap="#ThecallrApi.Exception.LocalApiException_map" alt=""/> <map id="ThecallrApi.Exception.LocalApiException_map" name="ThecallrApi.Exception.LocalApiException_map"> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a52d746b68d7ec64f280d9775c4499340"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_thecallr_api_1_1_exception_1_1_local_api_exception.html#a52d746b68d7ec64f280d9775c4499340">LocalApiException</a> (string message, System.Exception innerException)</td></tr> <tr class="memdesc:a52d746b68d7ec64f280d9775c4499340"><td class="mdescLeft">&#160;</td><td class="mdescRight">Constructor. <a href="#a52d746b68d7ec64f280d9775c4499340">More...</a><br /></td></tr> <tr class="separator:a52d746b68d7ec64f280d9775c4499340"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac7b33f253c30ef0900bb83e46e29c8d8"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_thecallr_api_1_1_exception_1_1_local_api_exception.html#ac7b33f253c30ef0900bb83e46e29c8d8">LocalApiException</a> (string message)</td></tr> <tr class="memdesc:ac7b33f253c30ef0900bb83e46e29c8d8"><td class="mdescLeft">&#160;</td><td class="mdescRight">Constructor. <a href="#ac7b33f253c30ef0900bb83e46e29c8d8">More...</a><br /></td></tr> <tr class="separator:ac7b33f253c30ef0900bb83e46e29c8d8"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>This class represents an internal library error. </p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="a52d746b68d7ec64f280d9775c4499340"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ThecallrApi.Exception.LocalApiException.LocalApiException </td> <td>(</td> <td class="paramtype">string&#160;</td> <td class="paramname"><em>message</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">System.Exception&#160;</td> <td class="paramname"><em>innerException</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Constructor. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">message</td><td><a class="el" href="namespace_thecallr_api_1_1_exception.html">Exception</a> message.</td></tr> <tr><td class="paramname">innerException</td><td>Inner exception.</td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="ac7b33f253c30ef0900bb83e46e29c8d8"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">ThecallrApi.Exception.LocalApiException.LocalApiException </td> <td>(</td> <td class="paramtype">string&#160;</td> <td class="paramname"><em>message</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Constructor. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">message</td><td><a class="el" href="namespace_thecallr_api_1_1_exception.html">Exception</a> message.</td></tr> </table> </dd> </dl> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>Exception/LocalApiException.cs</li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Sep 17 2014 10:42:58 for Thecallr .NET SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.8 </small></address> </body> </html>
{ "content_hash": "37614cae1a7dcc41765c5e4e35564027", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 828, "avg_line_length": 50, "alnum_prop": 0.6693684210526316, "repo_name": "THECALLR/sdk-dotnet", "id": "fe4bcdea39bf1d5bbd9180a718f910a0b3e13b60", "size": "9500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/class_thecallr_api_1_1_exception_1_1_local_api_exception.html", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "247990" } ], "symlink_target": "" }
FROM balenalib/up-core-plus-debian:stretch-build # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.15 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \ && echo "363447510565fe95ceb59ab3b11473c5ddc27b8b646ba02f7892c37174be1696 Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-amd64-libffi3.2.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libdbus-1-dev \ libdbus-glib-1-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get -y autoremove # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Stretch \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "5bdb2360e3acec2c212f08dffe92e4fb", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 727, "avg_line_length": 50.98947368421052, "alnum_prop": 0.7029314616019818, "repo_name": "resin-io-library/base-images", "id": "73dd7a88ff55121972bc3c8f259506027a9c070e", "size": "4865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/up-core-plus/debian/stretch/3.6.15/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <metadataProfile xmlns="http://www.nkp.cz/pspValidator/2.2.1/metadataProfile" name="MODS internal part - picture (AACR2)" validatorVersion="2.2.1" dmf="monograph_1.4" > <info> <text>DMF Monografie 1.4 očekává MODS verze 3.6. Dále se zde upřesňují očekávaná metadata pro vnitřní část typu obraz pro záznamy zpracované podle katalogizačních pravidel AACR2. </text> <url>http://www.loc.gov/standards/mods/</url> <url description="XSD pro MODS 3.6">http://www.loc.gov/standards/mods/v3/mods-3-6.xsd</url> <url description="popis MODS 3.6">http://www.loc.gov/standards/mods/mods-outline-3-6.html</url> </info> <namespaces> <namespace prefix="mods">http://www.loc.gov/mods/v3</namespace> </namespaces> <dictionaries> <dictionary name="marcRelatorCodes" description="kódy rolí podle MARC21" url="http://www.loc.gov/marc/relators/relaterm.html"/> <dictionary name="iso6392languageCodes" description="kódy jazyků podle ISO 639-2" url="http://www.loc.gov/standards/iso639-2/php/code_list.php"/> <dictionary name="siglaInstitutionCodes" description="sigly knihoven"/> </dictionaries> <rootElement name="mods:mods"> <expectedAttributes> <attribute name="ID"> <expectedContent> <!--V kapitolo 7.3.1 se uvádí právě a pouze MODS_CHAP_*, MODS_PICT_* a nic dalšího--> <regexp>MODS_PICT_[0-9]{4}</regexp>> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:titleInfo"> <expectedElements> <element name="mods:nonSort" mandatory="false"> <expectedContent/> </element> <element name="mods:title"> <expectedContent/> </element> <element name="mods:subTitle" mandatory="false"> <expectedContent/> </element> <element name="mods:partNumber" mandatory="false"> <expectedContent/> </element> <element name="mods:partName" mandatory="false"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:name" specification="not(mods:etal)" mandatory="false"> <expectedAttributes> <attribute name="type" mandatory="false"> <expectedContent> <oneOf> <value>personal</value> <value>corporate</value> <value>conference</value> <value>family</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:namePart" specification="@type='date'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='family'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='given'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='termsOfAddress'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <!--namePart obsahující celé jméno, nebo se nejedná o osobu--> <element name="mods:namePart" specification="not(@type)" mandatory="false"> <expectedContent/> </element> <element name="mods:nameIdentifier" mandatory="false"> <expectedContent/> </element> <element name="mods:role" mandatory="false"> <expectedElements> <element name="mods:roleTerm" mandatory="false"> <expectedAttributes> <attribute name="type"> <expectedContent> <value>code</value> </expectedContent> </attribute> <attribute name="authority"> <recommendedContent> <value>marcrelator</value> </recommendedContent> </attribute> </expectedAttributes> <recommendedContent> <fromDictionary name="marcRelatorCodes"/> </recommendedContent> </element> </expectedElements> </element> </expectedElements> </element> <element name="mods:name" specification="mods:etal" mandatory="false"> <expectedElements> <element name="mods:etal"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:genre" specification="text()='picture' or text()='PICTURE'"> <expectedAttributes> <attribute name="type" mandatory="false"> <expectedContent> <oneOf> <value>table</value> <value>illustration</value> <value>chart</value> <value>photograph</value> <value>graphic</value> <value>map</value> <value>advertisement</value> <value>cover</value> <value>unspecified</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <recommendedContent> <value>picture</value> </recommendedContent> </element> <element name="mods:language" mandatory="false"> <expectedElements> <element name="mods:languageTerm"> <expectedAttributes> <attribute name="type"> <expectedContent> <value>code</value> </expectedContent> </attribute> <attribute name="authority"> <expectedContent> <value>iso639-2b</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <fromDictionary name="iso6392languageCodes"/> </expectedContent> </element> </expectedElements> <extraRules> <!-- V rámci elementu mods:language musí existovat nejvýše jeden element mods:languageTerm s atributy type='code' a authority='iso639-2b' --> <existsAtMostOnce xpath="mods:languageTerm[@type='code' and @authority='iso639-2b']/text()" description="Pokud je potřeba zaznamenat více jazyků, musí být každý ve vlastním elementu mods:language" /> </extraRules> </element> <element name="mods:physicalDescription" mandatory="false"> <expectedElements> <element name="mods:form" mandatory="false"> <expectedAttributes> <!--v DMF chybi informace o povinnosti, nechavam nepovinne--> <attribute name="authority" mandatory="false"> <expectedContent> <oneOf> <value>marcform</value> <value>marcsmd</value> <value>gmd</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> </expectedElements> </element> <element name="mods:abstract" mandatory="false"> <expectedContent/> </element> <element name="mods:note" mandatory="false"> <expectedContent/> </element> <element name="mods:subject" mandatory="false"> <expectedElements> <element name="mods:topic"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <oneOf> <value>czenas</value> <value>eczenas</value> <value>czmesh</value> <value>mednas</value> <value>msvkth</value> <value>agrovoc</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:cartographics" mandatory="false"> <expectedElements> <element name="mods:coordinates" mandatory="false"> <expectedContent/> </element> <element name="mods:scale" mandatory="false"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:geographic" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <value>czenas</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> </expectedContent> </element> <element name="mods:temporal" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <value>czenas</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> </expectedContent> </element> <element name="mods:name" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <!--v DNF není vyplněné, jestli je atribut povinný, nechávám tedy nepovinný--> <expectedContent> <value>czenas</value> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:namePart" mandatory="false"> <!--v DNF není vyplněné, jestli je element povinný, nechávám tedy nepovinný--> <expectedContent> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> </expectedContent> </element> </expectedElements> </element> </expectedElements> </element> <element name="mods:classification" mandatory="false"> <!--Mezinarodni desetinne trideni--> <expectedAttributes> <!--NOTE: DMF neuvadi, jestli je authority povinny atribut, nechavam nepovinny--> <attribute name="authority" mandatory="true"> <recommendedContent> <value>udc</value> </recommendedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <!-- identifier--> <element name="mods:identifier" specification="@type='uuid'"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <regexp>^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$</regexp> </expectedContent> </element> <element name="mods:identifier" specification="@type='urnnbn'" mandatory="false"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <regexp>(?i)urn:nbn:cz:[a-z0-9]{2,6}-[a-z0-9]{6}</regexp> </expectedContent> </element> <element name="mods:identifier" specification="@type!='uuid' and @type!='urnnbn'" mandatory="false"> <expectedAttributes> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> <attribute name="type" mandatory="false"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:recordInfo"> <expectedElements> <element name="mods:recordContentSource" mandatory="false"> <expectedContent/> </element> <element name="mods:recordCreationDate"> <expectedAttributes> <attribute name="encoding" mandatory="false"> <!-- DMF neuvadi, jestli je atribut povinny, nechavam nepovinny https://github.com/NLCR/Standard_NDK/issues/160 --> <expectedContent> <value>iso8601</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <oneOf> <!--ISO 8601 na úroveň alespoň minut (basic format): např. 20190830T1535+01, 20190830T153544-23:30, 20190830T153559.123--> <regexp>^(?&lt;year&gt;[0-9]{4})(?&lt;month&gt;1[0-2]|0[1-9])(?&lt;day&gt;3[01]|0[1-9]|[12][0-9])T(?&lt;hour&gt;2[0-3]|[01][0-9])(?&lt;minute&gt;[0-5][0-9])(?&lt;second&gt;[0-5][0-9](.(?&lt;millis&gt;[0-9]{3}))?)?(?&lt;timezone&gt;Z|[+-](2[0-3]|[01][0-9])([0-5][0-9])?)?$</regexp> <!--ISO 8601 na úroveň alespoň minut (extended format): např. 2019-08-30T15:35+01:00, 2019-08-30T15:35:44-23:30, 2019-08-30T15:35:59.123Z --> <regexp>^(?&lt;year&gt;[0-9]{4})-(?&lt;month&gt;1[0-2]|0[1-9])-(?&lt;day&gt;3[01]|0[1-9]|[12][0-9])T(?&lt;hour&gt;2[0-3]|[01][0-9]):(?&lt;minute&gt;[0-5][0-9])(:(?&lt;second&gt;[0-5][0-9])(.(?&lt;millis&gt;[0-9]{3}))?)?(?&lt;timezone&gt;Z|[+-](2[0-3]|[01][0-9])(:([0-5][0-9])?)?)?$</regexp> </oneOf> </expectedContent> </element> <element name="mods:recordChangeDate" mandatory="false"> <expectedAttributes> <attribute name="encoding" mandatory="false"> <!-- DMF neuvadi, jestli je atribut povinny, nechavam nepovinny https://github.com/NLCR/Standard_NDK/issues/160 --> <expectedContent> <value>iso8601</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <oneOf> <!--ISO 8601 na úroveň alespoň minut (basic format): např. 20190830T1535+01, 20190830T153544-23:30, 20190830T153559.123--> <regexp>^(?&lt;year&gt;[0-9]{4})(?&lt;month&gt;1[0-2]|0[1-9])(?&lt;day&gt;3[01]|0[1-9]|[12][0-9])T(?&lt;hour&gt;2[0-3]|[01][0-9])(?&lt;minute&gt;[0-5][0-9])(?&lt;second&gt;[0-5][0-9](.(?&lt;millis&gt;[0-9]{3}))?)?(?&lt;timezone&gt;Z|[+-](2[0-3]|[01][0-9])([0-5][0-9])?)?$</regexp> <!--ISO 8601 na úroveň alespoň minut (extended format): např. 2019-08-30T15:35+01:00, 2019-08-30T15:35:44-23:30, 2019-08-30T15:35:59.123Z --> <regexp>^(?&lt;year&gt;[0-9]{4})-(?&lt;month&gt;1[0-2]|0[1-9])-(?&lt;day&gt;3[01]|0[1-9]|[12][0-9])T(?&lt;hour&gt;2[0-3]|[01][0-9]):(?&lt;minute&gt;[0-5][0-9])(:(?&lt;second&gt;[0-5][0-9])(.(?&lt;millis&gt;[0-9]{3}))?)?(?&lt;timezone&gt;Z|[+-](2[0-3]|[01][0-9])(:([0-5][0-9])?)?)?$</regexp> </oneOf> </expectedContent> </element> <element name="mods:recordIdentifier" mandatory="false"> <expectedAttributes> <attribute name="source" mandatory="false"/> <attribute name="encoding" mandatory="false"> <expectedContent> <value>iso8601</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:recordOrigin" mandatory="false"> <recommendedContent> <oneOf> <value>machine generated</value> <value>human prepared</value> </oneOf> </recommendedContent> </element> </expectedElements> </element> </expectedElements> </rootElement> </metadataProfile>
{ "content_hash": "e35052cce093062885762a338c9f1745", "timestamp": "", "source": "github", "line_count": 446, "max_line_length": 322, "avg_line_length": 49.05156950672646, "alnum_prop": 0.418613155368652, "repo_name": "rzeh4n/psp-validator", "id": "52073cc5a03e2bd3584034101ae1f3a5186515ea", "size": "21985", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sharedModule/src/main/resources/nkp/pspValidator/shared/validatorConfig/fDMF/monograph_1.4/biblioProfiles/mods/internalpart_picture_aacr2.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5001" }, { "name": "Java", "bytes": "719126" }, { "name": "XSLT", "bytes": "17921" } ], "symlink_target": "" }
package com.platut.scripts; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.engine.core.BaseScript; import com.engine.core.SceneManager; /** * Created by conor on 11/08/17. */ public class CameraController extends BaseScript { public CameraController(SceneManager sceneManager, Entity entity) { super(sceneManager, entity); } @Override public void start() { } @Override public void update(float deltaTime) { } @Override public void draw(SpriteBatch batch) { } }
{ "content_hash": "c04f0f354e036fef88356a46e32a3c36", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 71, "avg_line_length": 18.64516129032258, "alnum_prop": 0.698961937716263, "repo_name": "VIGameStudio/Platut", "id": "2ed686e30d08c2f58ed91e61904be775695491a0", "size": "578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/com/platut/scripts/CameraController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "79107" } ], "symlink_target": "" }
<?php namespace Presta\Db\Adapter; use Presta\Db\DbCore; /** * Class DbPDOCore * * @since 1.5.0.1 */ class PDO extends DbCore { /** @var PDO */ protected $link; /* @var PDOStatement */ protected $result; /** * Returns a new PDO object (database link) * * @param string $host * @param string $user * @param string $password * @param string $dbname * @param int $timeout * @return \PDO */ protected static function _getPDO($host, $user, $password, $dbname, $timeout = 5) { $dsn = 'mysql:'; if ($dbname) { $dsn .= 'dbname=' . $dbname . ';'; } if (preg_match('/^(.*):([0-9]+)$/', $host, $matches)) { $dsn .= 'host=' . $matches[1] . ';port=' . $matches[2]; } elseif (preg_match('#^.*:(/.*)$#', $host, $matches)) { $dsn .= 'unix_socket=' . $matches[1]; } else { $dsn .= 'host=' . $host; } return new \PDO($dsn, $user, $password, array(\PDO::ATTR_TIMEOUT => $timeout, \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true)); } /** * Tries to connect and create a new database * * @param string $host * @param string $user * @param string $password * @param string $dbname * @param bool $dropit If true, drops the created database. * @return bool|int */ public static function createDatabase($host, $user, $password, $dbname, $dropit = false) { try { $link = self::_getPDO($host, $user, $password, false); $success = $link->exec('CREATE DATABASE `' . str_replace('`', '\\`', $dbname) . '`'); if ($dropit && ($link->exec('DROP DATABASE `' . str_replace('`', '\\`', $dbname) . '`') !== false)) { return true; } } catch (\PDOException $e) { return false; } return $success; } /** * Tries to connect to the database * * @see DbCore::connect() * @return PDO */ public function connect() { try { $this->link = self::_getPDO($this->server, $this->user, $this->password, $this->database, 5); } catch (\PDOException $e) { die(sprintf('Link to database cannot be established: %s', utf8_encode($e->getMessage()))); } // UTF-8 support if ($this->link->exec('SET NAMES \'utf8\'') === false) { die('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'); } return $this->link; } /** * Destroys the database connection link * * @see DbCore::disconnect() */ public function disconnect() { unset($this->link); } /** * Executes an SQL statement, returning a result set as a PDOStatement object or true/false. * * @see DbCore::_query() * @param string $sql * @return PDOStatement */ protected function _query($sql) { return $this->link->query($sql); } /** * Returns the next row from the result set. * * @see DbCore::nextRow() * @param bool $result * @return array|false|null */ public function nextRow($result = false) { if (!$result) { $result = $this->result; } if (!is_object($result)) { return false; } return $result->fetch(\PDO::FETCH_ASSOC); } /** * Returns all rows from the result set. * * @see DbCore::getAll() * @param bool $result * @return array|false|null */ protected function getAll($result = false) { if (!$result) { $result = $this->result; } if (!is_object($result)) { return false; } return $result->fetchAll(\PDO::FETCH_ASSOC); } /** * Returns row count from the result set. * * @see DbCore::_numRows() * @param PDOStatement $result * @return int */ protected function _numRows($result) { return $result->rowCount(); } /** * Returns ID of the last inserted row. * * @see DbCore::Insert_ID() * @return string|int */ public function Insert_ID() { return $this->link->lastInsertId(); } /** * Return the number of rows affected by the last SQL query. * * @see DbCore::Affected_Rows() * @return int */ public function Affected_Rows() { return $this->result->rowCount(); } /** * Returns error message. * * @see DbCore::getMsgError() * @param bool $query * @return string */ public function getMsgError($query = false) { $error = $this->link->errorInfo(); return ($error[0] == '00000') ? '' : $error[2]; } /** * Returns error code. * * @see DbCore::getNumberError() * @return int */ public function getNumberError() { $error = $this->link->errorInfo(); return isset($error[1]) ? $error[1] : 0; } /** * Returns database server version. * * @see DbCore::getVersion() * @return string */ public function getVersion() { return $this->getValue('SELECT VERSION()'); } /** * Escapes illegal characters in a string. * * @see DbCore::_escape() * @param string $str * @return string */ public function _escape($str) { $search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"'); $replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"'); return str_replace($search, $replace, $str); } /** * Switches to a different database. * * @see DbCore::set_db() * @param string $db_name * @return int */ public function set_db($db_name) { return $this->link->exec('USE ' . $this->escape($db_name)); } /** * Try a connection to the database and check if at least one table with same prefix exists * * @see Db::hasTableWithSamePrefix() * @param string $server Server address * @param string $user Login for database connection * @param string $pwd Password for database connection * @param string $db Database name * @param string $prefix Tables prefix * @return bool */ public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix) { try { $link = self::_getPDO($server, $user, $pwd, $db, 5); } catch (\PDOException $e) { return false; } $sql = 'SHOW TABLES LIKE \'' . $prefix . '%\''; $result = $link->query($sql); return (bool) $result->fetch(); } /** * Tries to connect to the database and create a table (checking creation privileges) * * @param string $server * @param string $user * @param string $pwd * @param string $db * @param string $prefix * @param string|null $engine Table engine * @return bool|string True, false or error */ public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine = null) { try { $link = self::_getPDO($server, $user, $pwd, $db, 5); } catch (\PDOException $e) { return false; } if ($engine === null) { $engine = 'MyISAM'; } $result = $link->query(' CREATE TABLE `' . $prefix . 'test` ( `test` tinyint(1) unsigned NOT NULL ) ENGINE=' . $engine); if (!$result) { $error = $link->errorInfo(); return $error[2]; } $link->query('DROP TABLE `' . $prefix . 'test`'); return true; } /** * Try a connection to the database * * @see Db::checkConnection() * @param string $server Server address * @param string $user Login for database connection * @param string $pwd Password for database connection * @param string $db Database name * @param bool $newDbLink * @param string|bool $engine * @param int $timeout * @return int Error code or 0 if connection was successful */ public static function tryToConnect($server, $user, $pwd, $db, $new_db_link = true, $engine = null, $timeout = 5) { try { $link = self::_getPDO($server, $user, $pwd, $db, $timeout); } catch (\PDOException $e) { // hhvm wrongly reports error status 42000 when the database does not exist - might change in the future return ($e->getCode() == 1049 || (defined('HHVM_VERSION') && $e->getCode() == 42000)) ? 2 : 1; } unset($link); return 0; } /** * Selects best table engine. * * @return string */ public function getBestEngine() { $value = 'InnoDB'; $sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\''; $result = $this->link->query($sql); if (!$result) { $value = 'MyISAM'; } $row = $result->fetch(); if (!$row || strtolower($row['Value']) != 'yes') { $value = 'MyISAM'; } /* MySQL >= 5.6 */ $sql = 'SHOW ENGINES'; $result = $this->link->query($sql); while ($row = $result->fetch()) { if ($row['Engine'] == 'InnoDB') { if (in_array($row['Support'], array('DEFAULT', 'YES'))) { $value = 'InnoDB'; } break; } } return $value; } /** * Try a connection to the database and set names to UTF-8 * * @see Db::checkEncoding() * @param string $server Server address * @param string $user Login for database connection * @param string $pwd Password for database connection * @return bool */ public static function tryUTF8($server, $user, $pwd) { try { $link = self::_getPDO($server, $user, $pwd, false, 5); } catch (\PDOException $e) { return false; } $result = $link->exec('SET NAMES \'utf8\''); unset($link); return ($result === false) ? false : true; } /** * Checks if auto increment value and offset is 1 * * @param string $server * @param string $user * @param string $pwd * @return bool */ public static function checkAutoIncrement($server, $user, $pwd) { try { $link = self::_getPDO($server, $user, $pwd, false, 5); } catch (\PDOException $e) { return false; } $ret = (bool) (($result = $link->query('SELECT @@auto_increment_increment as aii')) && ($row = $result->fetch()) && $row['aii'] == 1); $ret &= (bool) (($result = $link->query('SELECT @@auto_increment_offset as aio')) && ($row = $result->fetch()) && $row['aio'] == 1); unset($link); return $ret; } }
{ "content_hash": "b32c831733796687b4ca92aa5aa8a1df", "timestamp": "", "source": "github", "line_count": 393, "max_line_length": 142, "avg_line_length": 27.83715012722646, "alnum_prop": 0.513345521023766, "repo_name": "web3d/Presta", "id": "614a75d5b450dc9d92f6970cbd2a4df5e666700d", "size": "11931", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Presta/Db/Adapter/PDO.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "259327" } ], "symlink_target": "" }
import { GridOptionsWrapper } from "../../gridOptionsWrapper"; export interface RowContainerComponentParams { eContainer: HTMLElement; eViewport?: HTMLElement; eWrapper?: HTMLElement; hideWhenNoChildren?: boolean; } /** * There are many instances of this component covering each of the areas a row can be entered * eg body, pinned left, fullWidth. The component differs from others in that it's given the * elements, there is no template. All of the elements are part of the GridPanel. */ export declare class RowContainerComponent { gridOptionsWrapper: GridOptionsWrapper; private readonly eContainer; private readonly eViewport; private readonly eWrapper; private readonly hideWhenNoChildren; private childCount; private visible; private rowTemplatesToAdd; private afterGuiAttachedCallbacks; private scrollTop; private lastMadeVisibleTime; private domOrder; private lastPlacedElement; constructor(params: RowContainerComponentParams); setVerticalScrollPosition(verticalScrollPosition: number): void; private postConstruct; private checkDomOrder; getRowElement(compId: number): HTMLElement; setHeight(height: number): void; flushRowTemplates(): void; appendRowTemplate(rowTemplate: string, callback: () => void): void; ensureDomOrder(eRow: HTMLElement): void; removeRowElement(eRow: HTMLElement): void; private checkVisibility; isMadeVisibleRecently(): boolean; }
{ "content_hash": "4804185cd9664caa719376a499cff56c", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 93, "avg_line_length": 38.07692307692308, "alnum_prop": 0.7535353535353535, "repo_name": "ceolter/angular-grid", "id": "4fe683769caa0b3164c5bc0752adb0d515a2fe40", "size": "1485", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "community-modules/core/typings/rendering/row/rowContainerComponent.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67272" }, { "name": "JavaScript", "bytes": "2291855" }, { "name": "TypeScript", "bytes": "671875" } ], "symlink_target": "" }
#import "ElasticLoadBalancingSetLoadBalancerPoliciesForBackendServerResponse.h" @implementation ElasticLoadBalancingSetLoadBalancerPoliciesForBackendServerResponse -(id)init { if (self = [super init]) { } return self; } -(void)setException:(AmazonServiceException *)theException { AmazonServiceException *newException = nil; if ([[theException errorCode] isEqualToString:@"PolicyNotFound"]) { [newException release]; newException = [[ElasticLoadBalancingPolicyNotFoundException alloc] initWithMessage:@""]; } if ([[theException errorCode] isEqualToString:@"LoadBalancerNotFound"]) { [newException release]; newException = [[ElasticLoadBalancingLoadBalancerNotFoundException alloc] initWithMessage:@""]; } if ([[theException errorCode] isEqualToString:@"InvalidConfigurationRequest"]) { [newException release]; newException = [[ElasticLoadBalancingInvalidConfigurationRequestException alloc] initWithMessage:@""]; } if (newException != nil) { [newException setPropertiesWithException:theException]; [exception release]; exception = newException; } else { [exception release]; exception = [theException retain]; } } -(NSString *)description { NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256]; [buffer appendString:@"{"]; [buffer appendString:[super description]]; [buffer appendString:@"}"]; return [buffer autorelease]; } -(void)dealloc { [super dealloc]; } @end
{ "content_hash": "86e0bda57305c2519594f01805206c73", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 110, "avg_line_length": 22.542857142857144, "alnum_prop": 0.6958174904942965, "repo_name": "abovelabs/aws-ios-sdk", "id": "d876d10059697ba635a771e4d0cef4c836ec66d5", "size": "2162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Amazon.ElasticLoadBalancing/Model/ElasticLoadBalancingSetLoadBalancerPoliciesForBackendServerResponse.m", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
PYTHON_VERSION_COMPATIBILITY = "PY3" DEPS = [ 'builder_name_schema', 'depot_tools/bot_update', 'recipe_engine/context', 'recipe_engine/json', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/step', ]
{ "content_hash": "f46d0deeaa7dc974be129754ee4bab72", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 36, "avg_line_length": 21.76923076923077, "alnum_prop": 0.6819787985865724, "repo_name": "aosp-mirror/platform_external_skia", "id": "f19553a605b88d6b402f9dddaf8b476a22160f7b", "size": "446", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "infra/bots/recipe_modules/vars/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "12716940" }, { "name": "Batchfile", "bytes": "904" }, { "name": "C", "bytes": "620774" }, { "name": "C#", "bytes": "4683" }, { "name": "C++", "bytes": "27394853" }, { "name": "GLSL", "bytes": "67013" }, { "name": "Go", "bytes": "80137" }, { "name": "HTML", "bytes": "1002516" }, { "name": "Java", "bytes": "32794" }, { "name": "JavaScript", "bytes": "51666" }, { "name": "Lex", "bytes": "4372" }, { "name": "Lua", "bytes": "70974" }, { "name": "Makefile", "bytes": "2295" }, { "name": "Objective-C", "bytes": "35223" }, { "name": "Objective-C++", "bytes": "34410" }, { "name": "PHP", "bytes": "120845" }, { "name": "Python", "bytes": "1002226" }, { "name": "Shell", "bytes": "49974" } ], "symlink_target": "" }
'use strict'; import { ApiFeaturesConfig } from '../config/gateway'; import { ApiCircuitBreakerConfig } from '../config/circuit-breaker'; import { ApiConfig } from '../config/api'; import * as express from 'express'; import * as _ from 'lodash'; import { CircuitBreaker } from './express-circuit-breaker'; import * as Groups from '../group'; import { RedisStateHandler } from './redis-state-handler'; import { Logger } from '../logger'; import { AutoWired, Inject, Container } from 'typescript-ioc'; import { RequestLog, RequestLogger } from '../stats/request'; import { getMilisecondsInterval } from '../utils/time-intervals'; import { MiddlewareLoader } from '../utils/middleware-loader'; import { Gateway } from '../gateway'; interface BreakerInfo { circuitBreaker?: CircuitBreaker; groupValidator?: (req: express.Request, res: express.Response) => boolean; } @AutoWired export class ApiCircuitBreaker { @Inject private logger: Logger; @Inject private middlewareLoader: MiddlewareLoader; @Inject private requestLogger: RequestLogger; private activeBreakers: Map<string, CircuitBreaker> = new Map<string, CircuitBreaker>(); circuitBreaker(apiRouter: express.Router, api: ApiConfig, gatewayFeatures: ApiFeaturesConfig) { const breakerInfos: Array<BreakerInfo> = new Array<BreakerInfo>(); const sortedBreakers = this.sortBreakers(api.circuitBreaker, api.path); const breakersSize = sortedBreakers.length; sortedBreakers.forEach((cbConfig: ApiCircuitBreakerConfig, index: number) => { cbConfig = this.resolveReferences(cbConfig, gatewayFeatures); const breakerInfo: BreakerInfo = {}; const cbStateID = (breakersSize > 1 ? `${api.id}:${index}` : api.id); const cbOptions: any = { id: cbStateID, maxFailures: (cbConfig.maxFailures || 10), rejectMessage: (cbConfig.rejectMessage || 'Service unavailable'), rejectStatusCode: (cbConfig.rejectStatusCode || 503), stateHandler: new RedisStateHandler(cbStateID, getMilisecondsInterval(cbConfig.resetTimeout, 120000), getMilisecondsInterval(cbConfig.timeWindow)), timeout: getMilisecondsInterval(cbConfig.timeout, 30000), timeoutMessage: (cbConfig.timeoutMessage || 'Operation timeout'), timeoutStatusCode: (cbConfig.timeoutStatusCode || 504) }; if (this.logger.isDebugEnabled()) { this.logger.debug(`Configuring Circuit Breaker for path [${api.path}].`); } breakerInfo.circuitBreaker = new CircuitBreaker(cbOptions); this.configureCircuitBreakerEventListeners(breakerInfo, api.path, cbConfig, api); if (cbConfig.group) { if (this.logger.isDebugEnabled()) { const groups = Groups.filter(api.group, cbConfig.group); this.logger.debug(`Configuring Group filters for Circuit Breaker on path [${api.path}]. Groups [${JSON.stringify(groups)}]`); } breakerInfo.groupValidator = Groups.buildGroupAllowFilter(api.group, cbConfig.group); } breakerInfos.push(breakerInfo); }); this.setupMiddlewares(apiRouter, breakerInfos); this.addStopListeners(); } onStateChanged(id: string, state: string) { const breaker: CircuitBreaker = this.activeBreakers.get(id); if (breaker) { breaker.onStateChanged(state); } } removeAllBreakers() { this.activeBreakers.forEach(breaker => breaker.destroy()); this.activeBreakers.clear(); } private resolveReferences(circuitBreaker: ApiCircuitBreakerConfig, features: ApiFeaturesConfig) { if (circuitBreaker.use && features.circuitBreaker) { if (features.circuitBreaker[circuitBreaker.use]) { circuitBreaker = _.defaults(circuitBreaker, features.circuitBreaker[circuitBreaker.use]); } else { throw new Error(`Invalid reference ${circuitBreaker.use}. There is no configuration for this id.`); } } return circuitBreaker; } private configureCircuitBreakerEventListeners(breakerInfo: BreakerInfo, path: string, config: ApiCircuitBreakerConfig, api: ApiConfig) { if (this.requestLogger.isRequestLogEnabled(api)) { breakerInfo.circuitBreaker.on('open', (req: express.Request) => { const requestLog: RequestLog = this.requestLogger.getRequestLog(req); if (requestLog) { requestLog.circuitbreaker = 'open'; } }); breakerInfo.circuitBreaker.on('close', (req: express.Request) => { const requestLog: RequestLog = this.requestLogger.getRequestLog(req); if (requestLog) { requestLog.circuitbreaker = 'close'; } }); breakerInfo.circuitBreaker.on('rejected', (req: express.Request) => { const requestLog: RequestLog = this.requestLogger.getRequestLog(req); if (requestLog) { requestLog.circuitbreaker = 'rejected'; } }); } if (config.onOpen) { const openHandler = this.middlewareLoader.loadMiddleware('circuitbreaker', config.onOpen); breakerInfo.circuitBreaker.on('open', () => { openHandler(path, 'open', api.id); }); } if (config.onClose) { const closeHandler = this.middlewareLoader.loadMiddleware('circuitbreaker', config.onClose); breakerInfo.circuitBreaker.on('close', () => { closeHandler(path, 'close', api.id); }); } if (config.onRejected) { const rejectedHandler = this.middlewareLoader.loadMiddleware('circuitbreaker', config.onRejected); breakerInfo.circuitBreaker.on('rejected', () => { rejectedHandler(path, 'rejected', api.id); }); } } private setupMiddlewares(apiRouter: express.Router, breakerInfos: Array<BreakerInfo>) { breakerInfos.forEach((breakerInfo: BreakerInfo) => { this.activeBreakers.set(breakerInfo.circuitBreaker.id, breakerInfo.circuitBreaker); apiRouter.use(this.buildMiddleware(breakerInfo)); }); } private buildMiddleware(breakerInfo: BreakerInfo) { const circuitBreakerMiddleware = breakerInfo.circuitBreaker.middleware(); return (req: express.Request, res: express.Response, next: express.NextFunction) => { if (breakerInfo.groupValidator) { if (breakerInfo.groupValidator(req, res)) { circuitBreakerMiddleware(req, res, next); } else { next(); } } else { circuitBreakerMiddleware(req, res, next); } }; } private sortBreakers(breakers: Array<ApiCircuitBreakerConfig>, path: string): Array<ApiCircuitBreakerConfig> { const generalBreakers = _.filter(breakers, (value) => { if (value.group) { return true; } return false; }); if (generalBreakers.length > 1) { this.logger.error(`Invalid circuit breaker configuration for api [${path}]. Conflicting configurations for default group`); return []; } if (generalBreakers.length > 0) { const index = breakers.indexOf(generalBreakers[0]); if (index < breakers.length - 1) { const gen = breakers.splice(index, 1); breakers.push(gen[0]); } } return breakers; } private addStopListeners() { const gateway: Gateway = Container.get(Gateway); const stop = () => { if (this.logger.isDebugEnabled()) { this.logger.debug('API stopped. Removing circuitbreakers handlers.'); } this.removeAllBreakers(); gateway.removeListener('stop', stop); gateway.removeListener('api-reload', stop); }; gateway.on('stop', stop); gateway.on('api-reload', stop); } }
{ "content_hash": "9f09a7da6bd058fac5f321ea44dcbf7a", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 145, "avg_line_length": 43.72538860103627, "alnum_prop": 0.6038630169451357, "repo_name": "jairelton/tree-gateway", "id": "e9662bc8a8a273b72696d16ad71c0cfa45a58521", "size": "8439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/circuitbreaker/circuit-breaker.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "34297" }, { "name": "Shell", "bytes": "200" }, { "name": "TypeScript", "bytes": "457576" } ], "symlink_target": "" }
System::Threading::ThreadLocal<any> __enumerable__;
{ "content_hash": "c7202429f4cfb13fff3d1b57d210b135", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 51, "avg_line_length": 52, "alnum_prop": 0.75, "repo_name": "gammasoft71/Switch", "id": "c821130f7ffd30dd77525d3c533082be7e4c6037", "size": "186", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Switch.Core/src/Switch/System/Linq/Linq.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2177" }, { "name": "C++", "bytes": "8948450" }, { "name": "CMake", "bytes": "74730" }, { "name": "Objective-C++", "bytes": "133364" }, { "name": "Shell", "bytes": "15337" } ], "symlink_target": "" }
class CreateFeedbacks < ActiveRecord::Migration def change create_table :feedbacks do |t| t.text :body, null: false t.boolean :anonymous, default: false t.integer :project_id, null: false # identify the user with one of these t.integer :user_id t.string :session_id t.timestamps null: false end # TODO: need some indexes here end end
{ "content_hash": "e8b8aecfc7c881e65f386b6cab6f2521", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 47, "avg_line_length": 22, "alnum_prop": 0.648989898989899, "repo_name": "OpenHunting/openhunt", "id": "015d4df79d6ab6c8c00487f0688da02318da19a5", "size": "396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20151217054927_create_feedbacks.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "44475" }, { "name": "HTML", "bytes": "35325" }, { "name": "JavaScript", "bytes": "9290" }, { "name": "Ruby", "bytes": "104550" } ], "symlink_target": "" }
<div class="option-section find-replace-options" style="display:none;"> <div class="header-expand-collapse find-replace-options-toggle clearfix" data-next=".table-options, .exclude-post-types-options, .advanced-options"> <div class="expand-collapse-arrow">&#x25BC;</div> <div class="option-heading tables-header"><?php _e( 'Find & Replace Options', 'wp-migrate-db' ); ?></div> </div> </div>
{ "content_hash": "b115ee2371c06ef9a4ccd3554293d0b0", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 149, "avg_line_length": 66, "alnum_prop": 0.7146464646464646, "repo_name": "smpetrey/acredistilling.com", "id": "c47a1a6bd51868d492b5335a9f614b306dc90065", "size": "396", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "web/app/plugins/wp-migrate-db-pro/template/pro/find-replace-options.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1704461" }, { "name": "HTML", "bytes": "112826" }, { "name": "JavaScript", "bytes": "3119675" }, { "name": "PHP", "bytes": "14507343" }, { "name": "Shell", "bytes": "1145" }, { "name": "Smarty", "bytes": "33" }, { "name": "XSLT", "bytes": "9704" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | ChartJS</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.5 --> <link rel="stylesheet" href="../../bootstrap/css/bootstrap-rtl.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../../dist/css/AdminLTE-rtl.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="../../dist/css/skins/_all-skins-rtl.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>A</b>LT</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>Admin</b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">You have 4 messages</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <h4> Support Team <small><i class="fa fa-clock-o"></i> 5 mins</small> </h4> <p>Why not buy a new awesome theme?</p> </a> </li> <!-- end message --> </ul> </li> <li class="footer"><a href="#">See All Messages</a></li> </ul> </li> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- Tasks: style can be found in dropdown.less --> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- Task item --> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> <!-- end task item --> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="../../dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <span class="hidden-xs">Alexander Pierce</span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> Alexander Pierce - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="row"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </div> <!-- /.row --> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <!-- search form --> <form action="#" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="header">MAIN NAVIGATION</li> <li class="treeview"> <a href="#"> <i class="fa fa-dashboard"></i> <span>Dashboard</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="../../index.html"><i class="fa fa-circle-o"></i> Dashboard v1</a></li> <li><a href="../../index2.html"><i class="fa fa-circle-o"></i> Dashboard v2</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-files-o"></i> <span>Layout Options</span> <span class="label label-primary pull-right">4</span> </a> <ul class="treeview-menu"> <li><a href="../layout/top-nav.html"><i class="fa fa-circle-o"></i> Top Navigation</a></li> <li><a href="../layout/boxed.html"><i class="fa fa-circle-o"></i> Boxed</a></li> <li><a href="../layout/fixed.html"><i class="fa fa-circle-o"></i> Fixed</a></li> <li><a href="../layout/collapsed-sidebar.html"><i class="fa fa-circle-o"></i> Collapsed Sidebar</a></li> </ul> </li> <li> <a href="../widgets.html"> <i class="fa fa-th"></i> <span>Widgets</span> <small class="label pull-right bg-green">new</small> </a> </li> <li class="treeview active"> <a href="#"> <i class="fa fa-pie-chart"></i> <span>Charts</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li class="active"><a href="chartjs.html"><i class="fa fa-circle-o"></i> ChartJS</a></li> <li><a href="morris.html"><i class="fa fa-circle-o"></i> Morris</a></li> <li><a href="flot.html"><i class="fa fa-circle-o"></i> Flot</a></li> <li><a href="inline.html"><i class="fa fa-circle-o"></i> Inline charts</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop"></i> <span>UI Elements</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="../UI/general.html"><i class="fa fa-circle-o"></i> General</a></li> <li><a href="../UI/icons.html"><i class="fa fa-circle-o"></i> Icons</a></li> <li><a href="../UI/buttons.html"><i class="fa fa-circle-o"></i> Buttons</a></li> <li><a href="../UI/sliders.html"><i class="fa fa-circle-o"></i> Sliders</a></li> <li><a href="../UI/timeline.html"><i class="fa fa-circle-o"></i> Timeline</a></li> <li><a href="../UI/modals.html"><i class="fa fa-circle-o"></i> Modals</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-edit"></i> <span>Forms</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="../forms/general.html"><i class="fa fa-circle-o"></i> General Elements</a></li> <li><a href="../forms/advanced.html"><i class="fa fa-circle-o"></i> Advanced Elements</a></li> <li><a href="../forms/editors.html"><i class="fa fa-circle-o"></i> Editors</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-table"></i> <span>Tables</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="../tables/simple.html"><i class="fa fa-circle-o"></i> Simple tables</a></li> <li><a href="../tables/data.html"><i class="fa fa-circle-o"></i> Data tables</a></li> </ul> </li> <li> <a href="../calendar.html"> <i class="fa fa-calendar"></i> <span>Calendar</span> <small class="label pull-right bg-red">3</small> </a> </li> <li> <a href="../mailbox/mailbox.html"> <i class="fa fa-envelope"></i> <span>Mailbox</span> <small class="label pull-right bg-yellow">12</small> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-folder"></i> <span>Examples</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="../examples/invoice.html"><i class="fa fa-circle-o"></i> Invoice</a></li> <li><a href="../examples/profile.html"><i class="fa fa-circle-o"></i> Profile</a></li> <li><a href="../examples/login.html"><i class="fa fa-circle-o"></i> Login</a></li> <li><a href="../examples/register.html"><i class="fa fa-circle-o"></i> Register</a></li> <li><a href="../examples/lockscreen.html"><i class="fa fa-circle-o"></i> Lockscreen</a></li> <li><a href="../examples/404.html"><i class="fa fa-circle-o"></i> 404 Error</a></li> <li><a href="../examples/500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li> <li><a href="../examples/blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li> <li><a href="../examples/pace.html"><i class="fa fa-circle-o"></i> Pace Page</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-share"></i> <span>Multilevel</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level One <i class="fa fa-angle-left pull-right"></i></a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Two</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> Level Two <i class="fa fa-angle-left pull-right"></i></a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li> </ul> </li> </ul> </li> <li><a href="#"><i class="fa fa-circle-o"></i> Level One</a></li> </ul> </li> <li><a href="../../documentation/index.html"><i class="fa fa-book"></i> <span>Documentation</span></a></li> <li class="header">LABELS</li> <li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>Important</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>Warning</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>Information</span></a></li> </ul> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> ChartJS <small>Preview sample</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Charts</a></li> <li class="active">ChartJS</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-6"> <!-- AREA CHART --> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Area Chart</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <div class="chart"> <canvas id="areaChart" style="height:250px"></canvas> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> <!-- DONUT CHART --> <div class="box box-danger"> <div class="box-header with-border"> <h3 class="box-title">Donut Chart</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <canvas id="pieChart" style="height:250px"></canvas> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col (LEFT) --> <div class="col-md-6"> <!-- LINE CHART --> <div class="box box-info"> <div class="box-header with-border"> <h3 class="box-title">Line Chart</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <div class="chart"> <canvas id="lineChart" style="height:250px"></canvas> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> <!-- BAR CHART --> <div class="box box-success"> <div class="box-header with-border"> <h3 class="box-title">Bar Chart</h3> <div class="box-tools pull-right"> <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i> </button> <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <div class="chart"> <canvas id="barChart" style="height:230px"></canvas> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col (RIGHT) --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.3.2 </div> <strong>Copyright &copy; 2014-2015 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Create the tabs --> <ul class="nav nav-tabs nav-justified control-sidebar-tabs"> <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li> <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <!-- Home tab content --> <div class="tab-pane" id="control-sidebar-home-tab"> <h3 class="control-sidebar-heading">Recent Activity</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript::;"> <i class="menu-icon fa fa-birthday-cake bg-red"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Langdon's Birthday</h4> <p>Will be 23 on April 24th</p> </div> </a> </li> <li> <a href="javascript::;"> <i class="menu-icon fa fa-user bg-yellow"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4> <p>New phone +1(800)555-1234</p> </div> </a> </li> <li> <a href="javascript::;"> <i class="menu-icon fa fa-envelope-o bg-light-blue"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4> <p>nora@example.com</p> </div> </a> </li> <li> <a href="javascript::;"> <i class="menu-icon fa fa-file-code-o bg-green"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4> <p>Execution time 5 seconds</p> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> <h3 class="control-sidebar-heading">Tasks Progress</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript::;"> <h4 class="control-sidebar-subheading"> Custom Template Design <span class="label label-danger pull-right">70%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-danger" style="width: 70%"></div> </div> </a> </li> <li> <a href="javascript::;"> <h4 class="control-sidebar-subheading"> Update Resume <span class="label label-success pull-right">95%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-success" style="width: 95%"></div> </div> </a> </li> <li> <a href="javascript::;"> <h4 class="control-sidebar-subheading"> Laravel Integration <span class="label label-warning pull-right">50%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-warning" style="width: 50%"></div> </div> </a> </li> <li> <a href="javascript::;"> <h4 class="control-sidebar-subheading"> Back End Framework <span class="label label-primary pull-right">68%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-primary" style="width: 68%"></div> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> </div> <!-- /.tab-pane --> <!-- Stats tab content --> <div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> <!-- /.tab-pane --> <!-- Settings tab content --> <div class="tab-pane" id="control-sidebar-settings-tab"> <form method="post"> <h3 class="control-sidebar-heading">General Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Report panel usage <input type="checkbox" class="pull-right" checked> </label> <p> Some information about this general settings option </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Allow mail redirect <input type="checkbox" class="pull-right" checked> </label> <p> Other sets of options are available </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Expose author name in posts <input type="checkbox" class="pull-right" checked> </label> <p> Allow the user to show his name in blog posts </p> </div> <!-- /.form-group --> <h3 class="control-sidebar-heading">Chat Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Show me as online <input type="checkbox" class="pull-right" checked> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Turn off notifications <input type="checkbox" class="pull-right"> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> Delete chat history <a href="javascript::;" class="text-red pull-right"><i class="fa fa-trash-o"></i></a> </label> </div> <!-- /.form-group --> </form> </div> <!-- /.tab-pane --> </div> </aside> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.1.4 --> <script src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script> <!-- Bootstrap 3.3.5 --> <script src="../../bootstrap/js/bootstrap.min.js"></script> <!-- ChartJS 1.0.1 --> <script src="../../plugins/chartjs/Chart.min.js"></script> <!-- FastClick --> <script src="../../plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="../../dist/js/app.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="../../dist/js/demo.js"></script> <!-- page script --> <script> $(function () { /* ChartJS * ------- * Here we will create a few charts using ChartJS */ //-------------- //- AREA CHART - //-------------- // Get context with jQuery - using jQuery's .get() method. var areaChartCanvas = $("#areaChart").get(0).getContext("2d"); // This will get the first returned node in the jQuery collection. var areaChart = new Chart(areaChartCanvas); var areaChartData = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "Electronics", fillColor: "rgba(210, 214, 222, 1)", strokeColor: "rgba(210, 214, 222, 1)", pointColor: "rgba(210, 214, 222, 1)", pointStrokeColor: "#c1c7d1", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [65, 59, 80, 81, 56, 55, 40] }, { label: "Digital Goods", fillColor: "rgba(60,141,188,0.9)", strokeColor: "rgba(60,141,188,0.8)", pointColor: "#3b8bba", pointStrokeColor: "rgba(60,141,188,1)", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(60,141,188,1)", data: [28, 48, 40, 19, 86, 27, 90] } ] }; var areaChartOptions = { //Boolean - If we should show the scale at all showScale: true, //Boolean - Whether grid lines are shown across the chart scaleShowGridLines: false, //String - Colour of the grid lines scaleGridLineColor: "rgba(0,0,0,.05)", //Number - Width of the grid lines scaleGridLineWidth: 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - Whether the line is curved between points bezierCurve: true, //Number - Tension of the bezier curve between points bezierCurveTension: 0.3, //Boolean - Whether to show a dot for each point pointDot: false, //Number - Radius of each point dot in pixels pointDotRadius: 4, //Number - Pixel width of point dot stroke pointDotStrokeWidth: 1, //Number - amount extra to add to the radius to cater for hit detection outside the drawn point pointHitDetectionRadius: 20, //Boolean - Whether to show a stroke for datasets datasetStroke: true, //Number - Pixel width of dataset stroke datasetStrokeWidth: 2, //Boolean - Whether to fill the dataset with a color datasetFill: true, //String - A legend template legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>", //Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container maintainAspectRatio: true, //Boolean - whether to make the chart responsive to window resizing responsive: true }; //Create the line chart areaChart.Line(areaChartData, areaChartOptions); //------------- //- LINE CHART - //-------------- var lineChartCanvas = $("#lineChart").get(0).getContext("2d"); var lineChart = new Chart(lineChartCanvas); var lineChartOptions = areaChartOptions; lineChartOptions.datasetFill = false; lineChart.Line(areaChartData, lineChartOptions); //------------- //- PIE CHART - //------------- // Get context with jQuery - using jQuery's .get() method. var pieChartCanvas = $("#pieChart").get(0).getContext("2d"); var pieChart = new Chart(pieChartCanvas); var PieData = [ { value: 700, color: "#f56954", highlight: "#f56954", label: "Chrome" }, { value: 500, color: "#00a65a", highlight: "#00a65a", label: "IE" }, { value: 400, color: "#f39c12", highlight: "#f39c12", label: "FireFox" }, { value: 600, color: "#00c0ef", highlight: "#00c0ef", label: "Safari" }, { value: 300, color: "#3c8dbc", highlight: "#3c8dbc", label: "Opera" }, { value: 100, color: "#d2d6de", highlight: "#d2d6de", label: "Navigator" } ]; var pieOptions = { //Boolean - Whether we should show a stroke on each segment segmentShowStroke: true, //String - The colour of each segment stroke segmentStrokeColor: "#fff", //Number - The width of each segment stroke segmentStrokeWidth: 2, //Number - The percentage of the chart that we cut out of the middle percentageInnerCutout: 50, // This is 0 for Pie charts //Number - Amount of animation steps animationSteps: 100, //String - Animation easing effect animationEasing: "easeOutBounce", //Boolean - Whether we animate the rotation of the Doughnut animateRotate: true, //Boolean - Whether we animate scaling the Doughnut from the centre animateScale: false, //Boolean - whether to make the chart responsive to window resizing responsive: true, // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container maintainAspectRatio: true, //String - A legend template legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>" }; //Create pie or douhnut chart // You can switch between pie and douhnut using the method below. pieChart.Doughnut(PieData, pieOptions); //------------- //- BAR CHART - //------------- var barChartCanvas = $("#barChart").get(0).getContext("2d"); var barChart = new Chart(barChartCanvas); var barChartData = areaChartData; barChartData.datasets[1].fillColor = "#00a65a"; barChartData.datasets[1].strokeColor = "#00a65a"; barChartData.datasets[1].pointColor = "#00a65a"; var barChartOptions = { //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value scaleBeginAtZero: true, //Boolean - Whether grid lines are shown across the chart scaleShowGridLines: true, //String - Colour of the grid lines scaleGridLineColor: "rgba(0,0,0,.05)", //Number - Width of the grid lines scaleGridLineWidth: 1, //Boolean - Whether to show horizontal lines (except X axis) scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except Y axis) scaleShowVerticalLines: true, //Boolean - If there is a stroke on each bar barShowStroke: true, //Number - Pixel width of the bar stroke barStrokeWidth: 2, //Number - Spacing between each of the X value sets barValueSpacing: 5, //Number - Spacing between data sets within X values barDatasetSpacing: 1, //String - A legend template legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>", //Boolean - whether to make the chart responsive responsive: true, maintainAspectRatio: true }; barChartOptions.datasetFill = false; barChart.Bar(barChartData, barChartOptions); }); </script> </body> </html>
{ "content_hash": "2486f7d1187b8d014eb872fba8f9eb02", "timestamp": "", "source": "github", "line_count": 883, "max_line_length": 252, "avg_line_length": 39.359003397508495, "alnum_prop": 0.5042009552857225, "repo_name": "vakili722/AdminLTE-RTL", "id": "a791702bca565c7280159cd576263bdfa1e46d91", "size": "34754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/charts/chartjs.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "774152" }, { "name": "HTML", "bytes": "3151349" }, { "name": "JavaScript", "bytes": "2871601" }, { "name": "PHP", "bytes": "1684" } ], "symlink_target": "" }
package org.axway.grapes.jongo.datamodel; import com.fasterxml.jackson.annotation.JsonProperty; import org.axway.grapes.model.datamodel.License; import org.jongo.marshall.jackson.oid.Id; /** * Database License * <p> * <p>Class that define the representation of licenses stored in the database. * The name (short name) is use as an ID. A database index is created on org.axway.grapes.jongo.it.</p> * * @author jdcoffre */ public class DbLicense extends License { public static final String DATA_MODEL_VERSION = "datamodelVersion"; private String datamodelVersion = DbCollections.datamodelVersion; @Id private String name = ""; public DbLicense(License license) { this.name = license.getName(); setName(license.getName()); setApproved(license.isApproved()); setComments(license.getComments()); setLongName(license.getLongName()); setRegexp(license.getRegexp()); setUnknown(license.isUnknown()); setUrl(license.getUrl()); } public DbLicense() { } public void setDataModelVersion(final String newVersion) { this.datamodelVersion = newVersion; } public String getDataModelVersion() { return datamodelVersion; } @JsonProperty("name") public final String getName() { return name; } @JsonProperty("name") public final void setName(final String name) { this.name = name; } }
{ "content_hash": "d74f15d45338188e669f37f754fe60db", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 103, "avg_line_length": 26.4, "alnum_prop": 0.6749311294765841, "repo_name": "jfry-axway/Grapes", "id": "73fc489088c0b300ba4bace20e718c6ae0665d48", "size": "1452", "binary": false, "copies": "1", "ref": "refs/heads/v2", "path": "grapes-jongo/src/main/java/org/axway/grapes/jongo/datamodel/DbLicense.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4975" }, { "name": "HTML", "bytes": "205687" }, { "name": "Java", "bytes": "551555" }, { "name": "JavaScript", "bytes": "77999" }, { "name": "Shell", "bytes": "7119" } ], "symlink_target": "" }
'use strict' const mongoose = require('mongoose') const SongSchema = new mongoose.Schema({ title: String, track: String, artworkUrl: String, duration: Number, scId: Number }) module.exports = mongoose.model('Song', SongSchema)
{ "content_hash": "333461dfa536a90655ee142a32073de0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 18.46153846153846, "alnum_prop": 0.7125, "repo_name": "bmacheski/open-tracks", "id": "261b3c6d1e1e29db34359a7032049c0fc7e4e2f6", "size": "240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/db/song.model.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2205" }, { "name": "HTML", "bytes": "474" }, { "name": "JavaScript", "bytes": "34132" } ], "symlink_target": "" }
#ifndef CGAL_AFF_TRANSFORMATION_TAGS_H #define CGAL_AFF_TRANSFORMATION_TAGS_H #include <CGAL/basic.h> namespace CGAL { class Translation {}; class Rotation {}; class Scaling {}; class Reflection {}; class Identity_transformation {}; CGAL_EXPORT extern Translation TRANSLATION; CGAL_EXPORT extern Rotation ROTATION; CGAL_EXPORT extern Scaling SCALING; CGAL_EXPORT extern Reflection REFLECTION; CGAL_EXPORT extern Identity_transformation IDENTITY; } //namespace CGAL #endif // CGAL_AFF_TRANSFORMATION_TAGS_H
{ "content_hash": "a5514d527c0145d601d8642d420fabc7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 57, "avg_line_length": 24.208333333333332, "alnum_prop": 0.693631669535284, "repo_name": "alexandrustaetu/natural_editor", "id": "f950814c9b3a0263776e5b6ee5e8f4d7a0b6f236", "size": "1459", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "external/CGAL-4.4-beta1/include/CGAL/aff_transformation_tags.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "85830" }, { "name": "C++", "bytes": "341100" }, { "name": "Shell", "bytes": "2362" } ], "symlink_target": "" }
# Makefile.in generated by automake 1.11.3 from Makefile.am. # lib/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. pkgdatadir = $(datadir)/testdynamic pkgincludedir = $(includedir)/testdynamic pkglibdir = $(libdir)/testdynamic pkglibexecdir = $(libexecdir)/testdynamic am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux-gnu host_triplet = x86_64-unknown-linux-gnu subdir = lib DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) libhello_la_LIBADD = am_libhello_la_OBJECTS = hello.lo libhello_la_OBJECTS = $(am_libhello_la_OBJECTS) DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libhello_la_SOURCES) DIST_SOURCES = $(libhello_la_SOURCES) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/missing --run aclocal-1.11 AMTAR = $${TAR-tar} AR = ar AUTOCONF = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/missing --run autoconf AUTOHEADER = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/missing --run autoheader AUTOMAKE = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/missing --run automake-1.11 AWK = mawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 CPP = gcc -E CPPFLAGS = CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DLLTOOL = false DSYMUTIL = DUMPBIN = ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = FGREP = /bin/grep -F GREP = /bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LD = /usr/bin/ld -m elf_x86_64 LDFLAGS = LIBOBJS = LIBS = LIBTOOL = $(SHELL) $(top_builddir)/libtool LIPO = LN_S = ln -s LTLIBOBJS = MAKEINFO = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/missing --run makeinfo MANIFEST_TOOL = : MKDIR_P = /bin/mkdir -p NM = /usr/bin/nm -B NMEDIT = OBJDUMP = objdump OBJEXT = o OTOOL = OTOOL64 = PACKAGE = testdynamic PACKAGE_BUGREPORT = cyuyan22844@126.com PACKAGE_NAME = testDynamic PACKAGE_STRING = testDynamic 1.0 PACKAGE_TARNAME = testdynamic PACKAGE_URL = PACKAGE_VERSION = 1.0 PATH_SEPARATOR = : RANLIB = ranlib SED = /bin/sed SET_MAKE = SHELL = /bin/sh STRIP = strip VERSION = 1.0 abs_builddir = /home/zww/githubWork/LinuxProject/exampleDynamic/lib abs_srcdir = /home/zww/githubWork/LinuxProject/exampleDynamic/lib abs_top_builddir = /home/zww/githubWork/LinuxProject/exampleDynamic abs_top_srcdir = /home/zww/githubWork/LinuxProject/exampleDynamic ac_ct_AR = ar ac_ct_CC = gcc ac_ct_DUMPBIN = am__include = include am__leading_dot = . am__quote = am__tar = $${TAR-tar} chof - "$$tardir" am__untar = $${TAR-tar} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /home/zww/githubWork/LinuxProject/exampleDynamic/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../ top_builddir = .. top_srcdir = .. AUTOMAKE_OPTIONS = foreign lib_LTLIBRARIES = libhello.la libhello_la_SOURCES = hello.c all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign lib/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libhello.la: $(libhello_la_OBJECTS) $(libhello_la_DEPENDENCIES) $(EXTRA_libhello_la_DEPENDENCIES) $(LINK) -rpath $(libdir) $(libhello_la_OBJECTS) $(libhello_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/hello.Plo .c.o: $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(COMPILE) -c $< .c.obj: $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo # source='$<' object='$@' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags uninstall uninstall-am uninstall-libLTLIBRARIES # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
{ "content_hash": "5cabd38b7b10e48dac01202b22ca3133", "timestamp": "", "source": "github", "line_count": 525, "max_line_length": 137, "avg_line_length": 31.325714285714287, "alnum_prop": 0.6279946491548096, "repo_name": "weiwei22844/LinuxProject", "id": "64b5394b0791b9d13f1f46578a95ee6eca000166", "size": "16446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "exampleDynamic/lib/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "947" }, { "name": "C++", "bytes": "27" }, { "name": "Shell", "bytes": "44678" } ], "symlink_target": "" }
body { font-family: "Palatino Linotype", "Book Antiqua", Palatino, FreeSerif, serif; font-size: 15px; line-height: 22px; margin: 0; padding: 0; } p, h1, h2, h3, h4, h5, h6 { margin: 0 0 15px 0; } h1 { margin-top: 40px; } #tree, #headings { position: absolute; top: 30px; left: 0; bottom: 0; width: 290px; padding: 10px 0; overflow: auto; } #sidebar_wrapper { position: fixed; top: 0; left: 0; bottom: 0; width: 0; overflow: hidden; } #sidebar_switch { position: absolute; top: 0; left: 0; width: 290px; height: 29px; border-bottom: 1px solid; } #sidebar_switch span { display: block; float: left; width: 50%; text-align: center; line-height: 29px; cursor: pointer; } #sidebar_switch .selected { font-weight: bold; } .slidey #sidebar_wrapper { -webkit-transition: width 250ms linear; -moz-transition: width 250ms linear; -ms-transition: width 250ms linear; -o-transition: width 250ms linear; transition: width 250ms linear; } .sidebar #sidebar_wrapper { width: 290px; } #tree .nodename { text-indent: 12px; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAg0lEQVQYlWNIS0tbAcSK////Z8CHGTIzM7+mp6d/ASouwqswKyvrO1DRfyg+CcRaxCgE4Z9A3AjEbIQUgjHQOQvwKgS6+ffChQt3AiUDcCqsra29d/v27R6ghCVWN2ZnZ/9YuXLlRqBAPBALYvVMR0fHmQcPHrQBOUZ4gwfqFj5CAQ4Al6wLIYDwo9QAAAAASUVORK5CYII=); background-repeat: no-repeat; background-position: left center; cursor: pointer; } #tree .open > .nodename { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAlElEQVQYlWNIS0tbCsT/8eCN////Z2B49OhRfHZ29jdsioDiP27evJkNVggkONeuXbscm8Jly5atA8rzwRSCsG5DQ8MtZEU1NTUPgOLGUHm4QgaQFVlZWT9BijIzM39fuHChDCaHohBkBdCq9SCF8+bN2wHkC+FSCMLGkyZNOvb9+3dbNHEMhSDsDsRMxCjEiolWCADeUBHgU/IGQQAAAABJRU5ErkJggg==); background-position: left 7px; } #tree .dir, #tree .file { position: relative; min-height: 20px; line-height: 20px; padding-left: 12px; } #tree .dir > .children, #tree .file > .children { display: none; } #tree .dir.open > .children, #tree .file.open > .children { display: block; } #tree .file { padding-left: 24px; display: block; text-decoration: none; } #tree > .dir { padding-left: 0; } #headings .heading a { text-decoration: none; padding-left: 10px; display: block; } #headings .h1 { padding-left: 0; margin-top: 10px; font-size: 1.3em; } #headings .h2 { padding-left: 10px; margin-top: 8px; font-size: 1.1em; } #headings .h3 { padding-left: 20px; margin-top: 5px; font-size: 1em; } #headings .h4 { padding-left: 30px; margin-top: 3px; font-size: 0.9em; } #headings .h5 { padding-left: 40px; margin-top: 1px; font-size: 0.8em; } #headings .h6 { padding-left: 50px; font-size: 0.75em; } #sidebar-toggle { position: fixed; top: 0; left: 0; width: 5px; bottom: 0; z-index: 2; cursor: pointer; } #sidebar-toggle:hover { width: 10px; } .slidey #sidebar-toggle, .slidey #container { -webkit-transition: all 250ms linear; -moz-transition: all 250ms linear; -ms-transition: all 250ms linear; -o-transition: all 250ms linear; transition: all 250ms linear; } .sidebar #sidebar-toggle { left: 290px; } #container { position: fixed; left: 5px; right: 0; top: 0; bottom: 0; overflow: auto; } .sidebar #container { left: 295px; } .no-sidebar #sidebar_wrapper, .no-sidebar #sidebar-toggle { display: none; } .no-sidebar #container { left: 0; } #page { padding-top: 40px; } table td { border: 0; outline: 0; } .docs.markdown { padding: 10px 50px; } td.docs { max-width: 450px; min-width: 450px; min-height: 5px; padding: 10px 25px 1px 50px; overflow-x: hidden; vertical-align: top; text-align: left; } .docs pre { margin: 15px 0 15px; padding: 5px; padding-left: 10px; border: 1px solid; font-size: 12px; overflow: auto; } .docs pre.code_stats { font-size: 60%; } .docs p tt, .docs p code, .docs li tt, .docs li code { border: 1px solid; font-size: 12px; padding: 0 0.2em; } .dox { border-top: 1px solid; padding-top: 10px; padding-bottom: 10px; } .dox .details { padding: 10px; border: 1px solid; margin-bottom: 10px; } .dox .dox_tag_title { font-weight: bold; } .dox .dox_tag_detail { margin-left: 10px; } .dox .dox_tag_detail span { margin-right: 5px; } .dox .dox_type { font-style: italic; } .dox .dox_tag_name { font-weight: bold; } .pilwrap { position: relative; padding-top: 1px; } .pilwrap .pilcrow { font: 12px Arial; text-decoration: none; color: #454545; position: absolute; top: 3px; left: -20px; padding: 1px 2px; opacity: 0; -webkit-transition: opacity 0.2s linear; -moz-transition: opacity 0.2s linear; -ms-transition: opacity 0.2s linear; -o-transition: opacity 0.2s linear; transition: opacity 0.2s linear; } .pilwrap:hover .pilcrow { opacity: 1; } td.code { padding: 8px 15px 8px 25px; width: 100%; vertical-align: top; border-left: 1px solid; } .background { border-left: 1px solid; position: absolute; z-index: -1; top: 0; right: 0; bottom: 0; left: 525px; } pre, tt, code { font-size: 12px; line-height: 18px; font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; margin: 0; padding: 0; } .line-num { display: inline-block; width: 50px; text-align: right; opacity: 0.3; margin-left: -20px; text-decoration: none; } /* All the stuff that can depend on colour scheme goes below here: */ body { background: white; color: #2f2f24; } a { color: #261a3b; } a:visited { color: #261a3b; } #sidebar_wrapper { background: #f4f4f3; } #sidebar_switch { background: #ededec; border-bottom-color: #dededc; } #sidebar_switch span { color: #2d2d22; } #sidebar_switch span:hover { background: #f4f4f3; } #sidebar_switch .selected { background: #fafafa; color: #252519; } #tree .file { color: #252519; } #headings .heading a { color: #252519; } #sidebar-toggle { background: #e9e9e8; } #sidebar-toggle:hover { background: #dededc; } .docs.markdown { background: white; } .docs pre { border-color: #dededc; } .docs p tt, .docs p code, .docs li tt, .docs li code { border-color: #dededc; background: #f4f4f3; } .highlight { background: #f4f4f3; color: auto; } .dox { border-top-color: #e6e6e4; } .dox .details { background: #f4f4f3; border-color: #dededc; } .pilwrap .pilcrow { color: #3a3a2f; } td.code, .background { border-left-color: #dededc; } body .highlight .hll { background-color: #ffffcc } body .highlight { background: #f8f8f8; } body .highlight .c { color: #408080; font-style: italic } /* Comment */ body .highlight .err { border: 1px solid #FF0000 } /* Error */ body .highlight .k { color: #008000; font-weight: bold } /* Keyword */ body .highlight .o { color: #666666 } /* Operator */ body .highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */ body .highlight .cp { color: #BC7A00 } /* Comment.Preproc */ body .highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */ body .highlight .cs { color: #408080; font-style: italic } /* Comment.Special */ body .highlight .gd { color: #A00000 } /* Generic.Deleted */ body .highlight .ge { font-style: italic } /* Generic.Emph */ body .highlight .gr { color: #FF0000 } /* Generic.Error */ body .highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ body .highlight .gi { color: #00A000 } /* Generic.Inserted */ body .highlight .go { color: #808080 } /* Generic.Output */ body .highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ body .highlight .gs { font-weight: bold } /* Generic.Strong */ body .highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ body .highlight .gt { color: #0040D0 } /* Generic.Traceback */ body .highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ body .highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ body .highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ body .highlight .kp { color: #008000 } /* Keyword.Pseudo */ body .highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ body .highlight .kt { color: #B00040 } /* Keyword.Type */ body .highlight .m { color: #666666 } /* Literal.Number */ body .highlight .s { color: #BA2121 } /* Literal.String */ body .highlight .na { color: #7D9029 } /* Name.Attribute */ body .highlight .nb { color: #008000 } /* Name.Builtin */ body .highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */ body .highlight .no { color: #880000 } /* Name.Constant */ body .highlight .nd { color: #AA22FF } /* Name.Decorator */ body .highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */ body .highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ body .highlight .nf { color: #0000FF } /* Name.Function */ body .highlight .nl { color: #A0A000 } /* Name.Label */ body .highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ body .highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */ body .highlight .nv { color: #19177C } /* Name.Variable */ body .highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ body .highlight .w { color: #bbbbbb } /* Text.Whitespace */ body .highlight .mf { color: #666666 } /* Literal.Number.Float */ body .highlight .mh { color: #666666 } /* Literal.Number.Hex */ body .highlight .mi { color: #666666 } /* Literal.Number.Integer */ body .highlight .mo { color: #666666 } /* Literal.Number.Oct */ body .highlight .sb { color: #BA2121 } /* Literal.String.Backtick */ body .highlight .sc { color: #BA2121 } /* Literal.String.Char */ body .highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ body .highlight .s2 { color: #BA2121 } /* Literal.String.Double */ body .highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ body .highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */ body .highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ body .highlight .sx { color: #008000 } /* Literal.String.Other */ body .highlight .sr { color: #BB6688 } /* Literal.String.Regex */ body .highlight .s1 { color: #BA2121 } /* Literal.String.Single */ body .highlight .ss { color: #19177C } /* Literal.String.Symbol */ body .highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */ body .highlight .vc { color: #19177C } /* Name.Variable.Class */ body .highlight .vg { color: #19177C } /* Name.Variable.Global */ body .highlight .vi { color: #19177C } /* Name.Variable.Instance */ body .highlight .il { color: #666666 } /* Literal.Number.Integer.Long */
{ "content_hash": "87c0e85e6e975f44587c360f85e1dc87", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 324, "avg_line_length": 29.420054200542005, "alnum_prop": 0.6606484893146647, "repo_name": "Zolmeister/multiversi", "id": "1c8296e986346171db97073941662682e84625e4", "size": "10856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/doc-style.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6873" }, { "name": "JavaScript", "bytes": "84093" } ], "symlink_target": "" }
/** * @fileoverview This file is generated by the Angular template compiler. * Do not edit. * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride} * tslint:disable */ import * as i0 from "@angular/core"; import * as i1 from "./accordion.module"; import * as i2 from "@angular/common"; var NgbAccordionModuleNgFactory = i0.ɵcmf(i1.NgbAccordionModule, [], function (_l) { return i0.ɵmod([i0.ɵmpd(512, i0.ComponentFactoryResolver, i0.ɵCodegenComponentFactoryResolver, [[8, []], [3, i0.ComponentFactoryResolver], i0.NgModuleRef]), i0.ɵmpd(4608, i2.NgLocalization, i2.NgLocaleLocalization, [i0.LOCALE_ID, [2, i2.ɵa]]), i0.ɵmpd(512, i2.CommonModule, i2.CommonModule, []), i0.ɵmpd(512, i1.NgbAccordionModule, i1.NgbAccordionModule, [])]); }); export { NgbAccordionModuleNgFactory as NgbAccordionModuleNgFactory }; //# sourceMappingURL=accordion.module.ngfactory.js.map
{ "content_hash": "2aa6029ba02b23ea0e44fc1775108639", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 450, "avg_line_length": 73.5, "alnum_prop": 0.7596371882086168, "repo_name": "CatsPoo/ShiftOnline", "id": "787cc68fae28bb4417aa9876f6208f3ea20e738f", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "angular.src/node_modules/@ng-bootstrap/ng-bootstrap/accordion/accordion.module.ngfactory.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "161" }, { "name": "CSS", "bytes": "5541" }, { "name": "HTML", "bytes": "14617" }, { "name": "JavaScript", "bytes": "11827" }, { "name": "TypeScript", "bytes": "50158" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2083657ed46ca4997371b98328285ded", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "ed60a95031bb145ad8c011af9348ba073f22f677", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Sycomorus/Sycomorus gnaphalocarpus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import React from 'react' import { Container, Row, Col } from 'reactstrap' import classnames from 'classnames' import { translate } from 'react-i18next' import { Link } from '../../routes' export default translate(['common'])(({t, product = {}, url, active}) => { const navs = [ { key: 'overview', route: 'product_overview', text: t('feature/overview') }, { key: 'specs', route: 'product_specs', text: t('feature/specs') }, { key: 'gallery', route: 'product_gallery', text: t('feature/gallery') }, { key: 'buy', route: 'product_buy', text: t('feature/buy') } ] return ( <Container> <Row> <Col xs={12} sm={6} className='text-center text-md-left'> <h3>{product.name}</h3> </Col> <Col xs={12} sm={6} className='text-center text-md-right'> <ul className='list-inline'> {navs.map(nav => ( <li key={nav.key} className='list-inline-item'> <Link route={nav.route} params={{slug: url.query.slug}}> <a className={classnames({active: active === nav.key})}> {nav.text}<span className='centerer' /> </a> </Link> </li> ))} </ul> </Col> </Row> </Container> ) })
{ "content_hash": "e103ce75e9ad95dee980da2c179525a6", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 80, "avg_line_length": 35.94444444444444, "alnum_prop": 0.5224111282843895, "repo_name": "garbin/koapp", "id": "694ff0b0d22ebe87d1e9ab88c0df3dc0a780b46d", "size": "1294", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/clients/next/components/features/header.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15425" }, { "name": "HTML", "bytes": "9667" }, { "name": "JavaScript", "bytes": "115781" } ], "symlink_target": "" }
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import {UserModule} from './user/user.module'; import {NotifyModule} from 'notify-angular'; import {RouterModule, Routes} from '@angular/router'; import {LoginComponent} from './user/login/login.component'; import {AuthGuardService} from './user/auth-guard.service'; import {SignUpComponent} from './user/sign-up/sign-up.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { LandingComponent } from './landing/landing.component'; import {ResourceModule} from '@tsmean/resource'; const appRoutes: Routes = [ { path: '', component: LandingComponent, canActivate: [AuthGuardService]}, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuardService]} ]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes) ], exports: [ RouterModule ], providers: [ AuthGuardService ] }) export class AppRoutingModule { } @NgModule({ declarations: [ AppComponent, DashboardComponent, LandingComponent ], imports: [ BrowserModule, BrowserAnimationsModule, ResourceModule.forRoot('http://demo.tsmean.com:4242/api/v1'), AppRoutingModule, NotifyModule.forRoot(), UserModule.forRoot('http://demo.tsmean.com:4242/api/v1'), ], providers: [ AuthGuardService ], bootstrap: [AppComponent] }) export class AppModule { }
{ "content_hash": "de2ee96bbd44df601a893dba7ea25bd6", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 86, "avg_line_length": 27.45614035087719, "alnum_prop": 0.7188498402555911, "repo_name": "alejandromdz/bit-shop", "id": "284cb644714f028aab6180ad4d92f6cfa466ead7", "size": "1565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "frontend/user/src/app/app.module.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4641" }, { "name": "HTML", "bytes": "11078" }, { "name": "JavaScript", "bytes": "7532" }, { "name": "Shell", "bytes": "1573" }, { "name": "TypeScript", "bytes": "143782" } ], "symlink_target": "" }
__requires__ = 'setuptools==0.9.8' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('setuptools==0.9.8', 'console_scripts', 'easy_install-2.7')() )
{ "content_hash": "9027bd893e0f881f10c3ca29a81df69e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 86, "avg_line_length": 28, "alnum_prop": 0.6116071428571429, "repo_name": "t-rodynenko/simplequiz", "id": "5424967687b50ef0155b998ea84b658251a763d7", "size": "360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "venv/Scripts/easy_install-2.7-script.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_19) on Mon Feb 03 12:19:29 CET 2014 --> <TITLE> Uses of Class org.openxava.model.impl.HibernatePersistenceProvider (OpenXava 4.9.1 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.openxava.model.impl.HibernatePersistenceProvider (OpenXava 4.9.1 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/openxava/model/impl/HibernatePersistenceProvider.html" title="class in org.openxava.model.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/openxava/model/impl/class-use/HibernatePersistenceProvider.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="HibernatePersistenceProvider.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.openxava.model.impl.HibernatePersistenceProvider</B></H2> </CENTER> No usage of org.openxava.model.impl.HibernatePersistenceProvider <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/openxava/model/impl/HibernatePersistenceProvider.html" title="class in org.openxava.model.impl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/openxava/model/impl/class-use/HibernatePersistenceProvider.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="HibernatePersistenceProvider.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "c39e4e4e5cc64c4ab44501272841b531", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 232, "avg_line_length": 42.84285714285714, "alnum_prop": 0.6222074024674892, "repo_name": "jecuendet/maven4openxava", "id": "978217d589b9d083816c80c6797c7f2cdc8e0b88", "size": "5998", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/openxava/doc/apidocs/org/openxava/model/impl/class-use/HibernatePersistenceProvider.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1695359" }, { "name": "Groovy", "bytes": "105862" }, { "name": "Java", "bytes": "4269286" }, { "name": "JavaScript", "bytes": "4897092" }, { "name": "Shell", "bytes": "65963" }, { "name": "XSLT", "bytes": "3987" } ], "symlink_target": "" }
namespace seasocks { struct ZlibContext::Impl { }; ZlibContext::ZlibContext() { } ZlibContext::~ZlibContext() { } void ZlibContext::initialise(int, int, int) { throw std::runtime_error("Not compiled with zlib support"); } void ZlibContext::deflate(const uint8_t*, size_t, std::vector<uint8_t>&) { throw std::runtime_error("Not compiled with zlib support"); } bool ZlibContext::inflate(std::vector<uint8_t>&, std::vector<uint8_t>&, int&) { throw std::runtime_error("Not compiled with zlib support"); } }
{ "content_hash": "d76dbea7decf68e92e35c73d9400ea09", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 79, "avg_line_length": 21.708333333333332, "alnum_prop": 0.6948176583493282, "repo_name": "mattgodbolt/seasocks", "id": "744d024ca88eb4bc9a7510ccbe2d23f3519e3f32", "size": "1937", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/c/seasocks/ZlibContextDisabled.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "112291" }, { "name": "C++", "bytes": "991377" }, { "name": "CMake", "bytes": "10254" }, { "name": "CSS", "bytes": "743" }, { "name": "HTML", "bytes": "2768" }, { "name": "JavaScript", "bytes": "2031" }, { "name": "Makefile", "bytes": "786" }, { "name": "Python", "bytes": "6010" }, { "name": "Shell", "bytes": "687" } ], "symlink_target": "" }
<?php namespace DoctrineORMModule\Proxy\__CG__\Blog\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class Article extends \Blog\Entity\Article implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = array(); /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return array('__isInitialized__', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'id', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'title', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'article', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'shortArticle', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'isPublic', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'category', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'comments'); } return array('__isInitialized__', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'id', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'title', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'article', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'shortArticle', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'isPublic', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'category', '' . "\0" . 'Blog\\Entity\\Article' . "\0" . 'comments'); } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (Article $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array()); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array()); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function getComments() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getComments', array()); return parent::getComments(); } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array()); return parent::getId(); } /** * {@inheritDoc} */ public function setTitle($title) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setTitle', array($title)); return parent::setTitle($title); } /** * {@inheritDoc} */ public function getTitle() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getTitle', array()); return parent::getTitle(); } /** * {@inheritDoc} */ public function setArticle($article) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setArticle', array($article)); return parent::setArticle($article); } /** * {@inheritDoc} */ public function getArticle() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getArticle', array()); return parent::getArticle(); } /** * {@inheritDoc} */ public function setShortArticle($shortArticle) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setShortArticle', array($shortArticle)); return parent::setShortArticle($shortArticle); } /** * {@inheritDoc} */ public function getShortArticle() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getShortArticle', array()); return parent::getShortArticle(); } /** * {@inheritDoc} */ public function setIsPublic($isPublic) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setIsPublic', array($isPublic)); return parent::setIsPublic($isPublic); } /** * {@inheritDoc} */ public function getIsPublic() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getIsPublic', array()); return parent::getIsPublic(); } /** * {@inheritDoc} */ public function setCategory(\Blog\Entity\Category $category = NULL) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setCategory', array($category)); return parent::setCategory($category); } /** * {@inheritDoc} */ public function getCategory() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getCategory', array()); return parent::getCategory(); } /** * {@inheritDoc} */ public function getArticleForTAble() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getArticleForTAble', array()); return parent::getArticleForTAble(); } /** * {@inheritDoc} */ public function getShortArticleForTAble() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getShortArticleForTAble', array()); return parent::getShortArticleForTAble(); } /** * {@inheritDoc} */ public function getShortArticleForBlog() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getShortArticleForBlog', array()); return parent::getShortArticleForBlog(); } /** * {@inheritDoc} */ public function getFullArticle() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getFullArticle', array()); return parent::getFullArticle(); } /** * {@inheritDoc} */ public function __toString() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__toString', array()); return parent::__toString(); } }
{ "content_hash": "8abb5071b565eec3a49faa619235eac5", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 439, "avg_line_length": 25.74659400544959, "alnum_prop": 0.5465128585035454, "repo_name": "DimaSmile/zend", "id": "c2a1dc86d0a28562de3f330a06bba13ddc074e2e", "size": "9449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/DoctrineORMModule/Proxy/__CG__BlogEntityArticle.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "1042" }, { "name": "HTML", "bytes": "39577" }, { "name": "PHP", "bytes": "85133" } ], "symlink_target": "" }
.yui3-overlay{position:absolute}.yui3-overlay-hidden{visibility:hidden}.yui3-widget-tmp-forcesize .yui3-overlay-content{overflow:hidden!important}#yui3-css-stamp.skin-sam-overlay{display:none}
{ "content_hash": "61db95de875c6f96e439ac459ab4befd", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 192, "avg_line_length": 97, "alnum_prop": 0.8247422680412371, "repo_name": "spadin/coverphoto", "id": "222ebdeb2a4bef3b23fedf1d1ad67e174c614a67", "size": "333", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/assets/skins/sam/overlay.css", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "5206" }, { "name": "JavaScript", "bytes": "69266" } ], "symlink_target": "" }
layout: post tags: - debugging - performance - smokeping - soap redirect_from: /smokeping-and-measuring-soap-requests/ --- We've had an issue with performance of a SOAP interface, and here's how you go about setting up smokeping to time it:- ```bash extraargs = -H Content-Type:text/xml --data @/srv/scripts/soap_check/soap-test.xml urlformat = http://server.name.com/url/soap_url ``` The only annoying problem is that the SOAP payload cannot be included as part of the command line, so any slaves would require the file manually copied into the same location
{ "content_hash": "ec7ebe8d00afc1b75fd3896c0aabafaf", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 30, "alnum_prop": 0.7526315789473684, "repo_name": "asnaedae/asnaedae.github.io", "id": "e30a37287c8b132e7d9bb0dbcb978a5e178ad500", "size": "574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2009-09-28-smokeping-and-measuring-soap-requests.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "52031" }, { "name": "HTML", "bytes": "31059" }, { "name": "JavaScript", "bytes": "1712" }, { "name": "Ruby", "bytes": "3358" } ], "symlink_target": "" }
package com.orange.clara.cloud.servicedbdumper.integrations; import com.orange.clara.cloud.servicedbdumper.cloudfoundry.CloudFoundryClientFactory; import com.orange.clara.cloud.servicedbdumper.exception.CannotFindDatabaseDumperException; import com.orange.clara.cloud.servicedbdumper.exception.DatabaseExtractionException; import com.orange.clara.cloud.servicedbdumper.exception.ServiceKeyException; import com.orange.clara.cloud.servicedbdumper.integrations.model.DatabaseAccess; import com.orange.clara.cloud.servicedbdumper.model.DatabaseRef; import com.orange.clara.cloud.servicedbdumper.model.DatabaseType; import org.cloudfoundry.client.lib.CloudFoundryClient; import org.cloudfoundry.client.lib.domain.CloudService; import org.cloudfoundry.client.lib.domain.CloudServiceKey; import org.cloudfoundry.client.lib.domain.CloudServiceOffering; import org.cloudfoundry.client.lib.domain.CloudServicePlan; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerAsyncRequiredException; import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException; import org.junit.After; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.client.HttpServerErrorException; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.List; import java.util.UUID; import java.util.concurrent.*; import static org.fest.assertions.Fail.fail; import static org.junit.Assume.assumeTrue; abstract public class AbstractIntegrationWithRealCfClientTest extends AbstractIntegrationTest { @Value("${int.cf.service.name.mysql:cleardb}") protected String serviceNameMysql; @Value("${int.cf.service.plan.mysql:spark}") protected String servicePlanMysql; @Value("${int.cf.service.instance.source.mysql:mysql-db-dumper-src-int}") protected String serviceSourceInstanceMysql; @Value("${int.cf.service.instance.target.mysql:mysql-db-dumper-dest-int}") protected String serviceTargetInstanceMysql; @Value("${int.cf.service.name.postgresql:elephantsql}") protected String serviceNamePostgres; @Value("${int.cf.service.plan.postgresql:turtle}") protected String servicePlanPostgres; @Value("${int.cf.service.instance.source.postgresql:postgres-db-dumper-src-int}") protected String serviceSourceInstancePostgres; @Value("${int.cf.service.instance.target.postgresql:postgres-db-dumper-dest-int}") protected String serviceTargetInstancePostgres; @Value("${int.cf.service.name.mongodb:mongolab}") protected String serviceNameMongo; @Value("${int.cf.service.plan.mongodb:sandbox}") protected String servicePlanMongo; @Value("${int.cf.service.instance.source.mongodb:mongodb-db-dumper-src-int}") protected String serviceSourceInstanceMongo; @Value("${int.cf.service.instance.target.mongodb:mongodb-db-dumper-dest-int}") protected String serviceTargetInstanceMongo; @Value("${int.cf.service.name.redis:rediscloud}") protected String serviceNameRedis; @Value("${int.cf.service.plan.redis:30mb}") protected String servicePlanRedis; @Value("${int.cf.service.instance.source.redis:redis-db-dumper-src-int}") protected String serviceSourceInstanceRedis; @Value("${int.cf.service.instance.target.redis:redis-db-dumper-dest-int}") protected String serviceTargetInstanceRedis; protected CloudFoundryClient cfClientToPopulate; @Autowired protected CloudFoundryClientFactory clientFactory; @Autowired @Qualifier("cfAdminUser") protected String cfAdminUser; @Autowired @Qualifier("cfAdminPassword") protected String cfAdminPassword; @Autowired @Qualifier("cloudControllerUrl") protected String cloudControllerUrl; @Value("${test.cf.admin.org:#{null}}") protected String org; @Value("${test.cf.admin.space:#{null}}") protected String space; @Value("${test.timeout.creating.service:5}") protected int timeoutCreatingService; @Autowired @Qualifier("cloudFoundryClientAsAdmin") protected CloudFoundryClient cfAdminClient; @Override @Before public void init() throws DatabaseExtractionException { super.init(); } @Override public void doBeforeTest(DatabaseType databaseType) throws DatabaseExtractionException, CannotFindDatabaseDumperException, InterruptedException, IOException { if (this.cfAdminUser == null || this.cfAdminUser.isEmpty() || this.cfAdminPassword == null || this.cfAdminPassword.isEmpty() || this.cloudControllerUrl == null || this.cloudControllerUrl.isEmpty()) { String skipMessage = "Please define properties: cf.admin.user, cf.admin.password, cloud.controller.url to run this test. This test is skipped."; this.reportIntegration.setSkipped(true); this.reportIntegration.setSkippedReason(skipMessage); assumeTrue(skipMessage, false); } cfClientToPopulate = this.clientFactory.createCloudFoundryClient(cfAdminUser, cfAdminPassword, cloudControllerUrl, org, space); DatabaseAccess databaseAccess = this.databaseAccessMap.get(databaseType); boolean isServiceExists = isServiceExist(databaseAccess.getServiceName(), databaseAccess.getServicePlan()); if (!isServiceExists) { this.skipCleaning = true; String skipMessage = String.format("The service %s with plan %s doesn't exists please set properties 'test.cf.service.name.%s' and 'test.cf.service.plan.%s'", databaseAccess.getServiceName(), databaseAccess.getServicePlan(), databaseAccess.generateDatabaseRef().getType().toString().toLowerCase(), databaseAccess.generateDatabaseRef().getType().toString().toLowerCase() ); this.reportIntegration.setSkipped(true); this.reportIntegration.setSkippedReason(skipMessage); assumeTrue(skipMessage, false); } CloudService cloudServiceSource = new CloudService(null, databaseAccess.getServiceSourceInstanceName()); cloudServiceSource.setPlan(databaseAccess.getServicePlan()); cloudServiceSource.setLabel(databaseAccess.getServiceName()); this.createService(cloudServiceSource); if (!databaseAccess.getServiceTargetInstanceName().equals(databaseAccess.getServiceSourceInstanceName())) { CloudService cloudServiceTarget = new CloudService(null, databaseAccess.getServiceTargetInstanceName()); cloudServiceTarget.setPlan(databaseAccess.getServicePlan()); cloudServiceTarget.setLabel(databaseAccess.getServiceName()); this.createService(cloudServiceTarget); } OAuth2AccessToken accessToken = cfClientToPopulate.login(); this.requestForge.setUserToken(accessToken.getValue()); this.requestForge.setOrg(org); this.requestForge.setSpace(space); super.doBeforeTest(databaseType); } @Override public void cleanDatabase(DatabaseType databaseType) throws DatabaseExtractionException, CannotFindDatabaseDumperException, InterruptedException, IOException { } @Override @After public void cleanAfterTest() throws DatabaseExtractionException, CannotFindDatabaseDumperException, InterruptedException, IOException, ServiceBrokerAsyncRequiredException, ServiceBrokerException { if (this.cfAdminUser == null || this.cfAdminUser.isEmpty() || this.cfAdminPassword == null || this.cfAdminPassword.isEmpty() || this.cloudControllerUrl == null || this.cloudControllerUrl.isEmpty()) { return; } loadBeforeAction(); for (DatabaseType databaseType : this.databaseAccessMap.keySet()) { DatabaseAccess databaseAccess = this.databaseAccessMap.get(databaseType); List<CloudServiceKey> cloudServiceKeys = this.cfClientToPopulate.getServiceKeys(); for (CloudServiceKey cloudServiceKey : cloudServiceKeys) { if (cloudServiceKey.getService().getName().equals(databaseAccess.getServiceSourceInstanceName()) || cloudServiceKey.getService().getName().equals(databaseAccess.getServiceTargetInstanceName())) { this.cfClientToPopulate.deleteServiceKey(cloudServiceKey); } } this.cfClientToPopulate.deleteService(databaseAccess.getServiceSourceInstanceName()); this.cfClientToPopulate.deleteService(databaseAccess.getServiceTargetInstanceName()); } if (this.skipCleaning) { return; } this.requestForge.createDefaultData(); super.cleanAfterTest(); } @Override protected void loadBeforeAction() { //action like restore, dump or populating data can be long, we ask to have a new token try { cfClientToPopulate = this.clientFactory.createCloudFoundryClient(cfAdminUser, cfAdminPassword, cloudControllerUrl, org, space); } catch (MalformedURLException e) { //can't happens here } OAuth2AccessToken accessToken = cfClientToPopulate.login(); this.requestForge.setUserToken(accessToken.getValue()); this.requestForge.setOrg(org); this.requestForge.setSpace(space); super.loadBeforeAction(); } @Override protected boolean isServerListening(DatabaseType databaseType) throws DatabaseExtractionException { DatabaseAccess databaseAccess = this.databaseAccessMap.get(databaseType); DatabaseRef sourceDatabase = null; DatabaseRef targetDatabase = null; try { sourceDatabase = this.databaseRefManager.getDatabaseRef(databaseAccess.getServiceSourceInstanceName(), requestForge.getUserToken(), requestForge.getOrg(), requestForge.getSpace()); targetDatabase = this.databaseRefManager.getDatabaseRef(databaseAccess.getServiceTargetInstanceName(), requestForge.getUserToken(), requestForge.getOrg(), requestForge.getSpace()); } catch (ServiceKeyException e) { throw new DatabaseExtractionException(e.getMessage(), e); } boolean result = this.isSocketOpen(sourceDatabase.getHost(), sourceDatabase.getPort()) && this.isSocketOpen(targetDatabase.getHost(), targetDatabase.getPort()); this.databaseRefManager.deleteServiceKey(sourceDatabase); this.databaseRefManager.deleteServiceKey(targetDatabase); return result; } @Override public void populateData(DatabaseType databaseType) throws DatabaseExtractionException, CannotFindDatabaseDumperException, IOException, InterruptedException { DatabaseAccess databaseAccess = this.databaseAccessMap.get(databaseType); File fakeData = databaseAccess.getFakeDataFile(); if (fakeData == null) { fail("Cannot find file for database: " + databaseType); return; } DatabaseRef sourceDatabase = null; try { sourceDatabase = this.databaseRefManager.getDatabaseRef(databaseAccess.getServiceSourceInstanceName(), requestForge.getUserToken(), requestForge.getOrg(), requestForge.getSpace()); } catch (ServiceKeyException e) { throw new DatabaseExtractionException(e.getMessage(), e); } this.populateDataToDatabaseRefFromFile(fakeData, sourceDatabase); this.databaseRefManager.deleteServiceKey(sourceDatabase); } @Override protected void populateDatabaseAccessMap() throws DatabaseExtractionException { super.populateDatabaseAccessMap(); DatabaseAccess mysqlAccess = this.databaseAccessMap.get(DatabaseType.MYSQL); mysqlAccess.setServiceName(serviceNameMysql); mysqlAccess.setServicePlan(servicePlanMysql); mysqlAccess.setServiceSourceInstanceName(this.generateServiceName(serviceSourceInstanceMysql)); mysqlAccess.setServiceTargetInstanceName(this.generateServiceName(serviceTargetInstanceMysql)); DatabaseAccess postgresAccess = this.databaseAccessMap.get(DatabaseType.POSTGRESQL); postgresAccess.setServiceName(serviceNamePostgres); postgresAccess.setServicePlan(servicePlanPostgres); postgresAccess.setServiceSourceInstanceName(this.generateServiceName(serviceSourceInstancePostgres)); postgresAccess.setServiceTargetInstanceName(this.generateServiceName(serviceTargetInstancePostgres)); DatabaseAccess mongoAccess = this.databaseAccessMap.get(DatabaseType.MONGODB); mongoAccess.setServiceName(serviceNameMongo); mongoAccess.setServicePlan(servicePlanMongo); mongoAccess.setServiceSourceInstanceName(this.generateServiceName(serviceSourceInstanceMongo)); mongoAccess.setServiceTargetInstanceName(this.generateServiceName(serviceTargetInstanceMongo)); DatabaseAccess redisAccess = this.databaseAccessMap.get(DatabaseType.REDIS); redisAccess.setServiceName(serviceNameRedis); redisAccess.setServicePlan(servicePlanRedis); String generatedSourceInstanceRedis = this.generateServiceName(serviceSourceInstanceRedis); redisAccess.setServiceSourceInstanceName(generatedSourceInstanceRedis); if (serviceNameRedis.equals("rediscloud")) { redisAccess.setServiceTargetInstanceName(generatedSourceInstanceRedis); } else { redisAccess.setServiceTargetInstanceName(this.generateServiceName(serviceTargetInstanceRedis)); } } protected String generateServiceName(String serviceName) { String randomUUID = UUID.randomUUID().toString(); randomUUID = randomUUID.replace("-", ""); return serviceName + "-" + randomUUID.substring(0, 5); } protected void createService(CloudService cloudService) { try { logger.info("Creating service {} from {} with plan {} ", cloudService.getName(), cloudService.getLabel(), cloudService.getPlan()); cfClientToPopulate.createService(cloudService); if (!this.isFinishedCreatingService(cloudService)) { fail("Cannot create service '" + cloudService.getName() + "'"); } } catch (HttpServerErrorException e) { if (!e.getStatusCode().equals(HttpStatus.BAD_GATEWAY)) { throw e; } else { String skipMessage = "Bad gateway error, skipping test"; this.reportIntegration.setSkipped(true); this.reportIntegration.setSkippedReason(skipMessage); assumeTrue(skipMessage, false); } } } public boolean isFinishedCreatingService(CloudService cloudService) { ExecutorService executor = Executors.newCachedThreadPool(); Callable<Boolean> task = () -> { while (true) { CloudService cloudServiceFound = cfClientToPopulate.getService(cloudService.getName()); if (cloudServiceFound.getCloudServiceLastOperation() == null) { return true; } logger.info("State for service '{}' : {}", cloudServiceFound, cloudServiceFound.getCloudServiceLastOperation().getState()); switch (cloudServiceFound.getCloudServiceLastOperation().getState()) { case "succeeded": return true; case "in progress": break; case "failed": case "internal error": return false; } Thread.sleep(5000L);// we yield the task for 5seconds to let the service do is work (actually, Cloud Controller hit getServiceInstance every 30sec) } }; Future<Boolean> future = executor.submit(task); try { Boolean result = future.get(timeoutCreatingService, TimeUnit.MINUTES); return result; } catch (Exception ex) { ex.printStackTrace(); future.cancel(true); fail("Timeout reached.", ex); } return false; } public boolean isServiceExist(String serviceName, String plan) { List<CloudServiceOffering> offeringList = cfClientToPopulate.getServiceOfferings(); for (CloudServiceOffering offering : offeringList) { if (!offering.getName().equals(serviceName)) { continue; } for (CloudServicePlan servicePlan : offering.getCloudServicePlans()) { if (servicePlan.getName().equals(plan)) { return true; } } } return false; } }
{ "content_hash": "f41462f597c34f020d4e1c431e0a67b7", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 200, "avg_line_length": 48.92285714285714, "alnum_prop": 0.7051334462418969, "repo_name": "orange-cloudfoundry/db-dumper-service", "id": "e24271a93464036197a68371e3301b9dbfdbeec5", "size": "17436", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/com/orange/clara/cloud/servicedbdumper/integrations/AbstractIntegrationWithRealCfClientTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3660" }, { "name": "Dockerfile", "bytes": "1813" }, { "name": "HTML", "bytes": "23155" }, { "name": "Java", "bytes": "671687" }, { "name": "JavaScript", "bytes": "19737" }, { "name": "Shell", "bytes": "14176" } ], "symlink_target": "" }
from django.db import models class Orderable(models.Model): """ Add extra field and default ordering column for and inline orderable model """ order = models.IntegerField(default=0) class Meta: abstract = True ordering = ('order',)
{ "content_hash": "299b5710490cc1bf605a7116fa67c779", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 82, "avg_line_length": 22.46153846153846, "alnum_prop": 0.6061643835616438, "repo_name": "marcofucci/django-inline-orderable", "id": "df80f55925016bfddb5f808e923edecfa58d425d", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inline_orderable/models.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "3842" }, { "name": "Python", "bytes": "1481" } ], "symlink_target": "" }
dpkg-deb -bZgzip projects/LS.Widgets/cxls1 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls2 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls3 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls4 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls5 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls6 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls7 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls8 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls9 debs dpkg-deb -bZgzip projects/LS.Widgets/cxls10 debs dpkg-deb -bZgzip projects/HS.Widgets/cxhs7 debs dpkg-deb -bZgzip projects/HS.Widgets/cxhs8 debs dpkg-deb -bZgzip projects/HS.Widgets/cxhs4 debs dpkg-deb -bZgzip projects/HS.Widgets/cxhs5 debs
{ "content_hash": "cec5942e05650d82efde016c7144f936", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 48, "avg_line_length": 48.07142857142857, "alnum_prop": 0.812778603268945, "repo_name": "classicxiirepo/classicxiirepo.github.io", "id": "87babd86631263295a5f81a885e216ea853d4645", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7382" }, { "name": "HTML", "bytes": "76301" }, { "name": "JavaScript", "bytes": "102088" }, { "name": "Shell", "bytes": "860" } ], "symlink_target": "" }
""" generate_graphs.py ------------------ Generate small synthetic graphs whose complete CLD will be computed. """ import cycles import numpy as np import networkx as nx from numpy import arange def is_valid(graph): """Return whether the graph is valid to run experiments on.""" rank = cycles.fundamental_group_rank(graph) # return nx.density(graph) < 0.3 and nx.is_connected(graph) and rank < 50 return nx.is_connected(graph) and rank < 50 def save_graph(graph, filename): """Save the graph to the given path. filename should be the name of the target file, without the format extension. """ component = max(nx.connected_component_subgraphs(graph), key=len) matrix = nx.adjacency_matrix(component).A np.savetxt(filename + '.txt', matrix, fmt='%1.1f') def generate_erdos_renyi(): """Generate small synthetic ER graphs.""" for num_nodes in range(10, 31, 5): for prob in arange(0.05, 0.4, 0.05): for i in range(20): graph = nx.erdos_renyi_graph(num_nodes, prob) if is_valid(graph): rank = cycles.fundamental_group_rank(graph) name = 'data/ER_N={}_p={}_R={}_i={}'.format(num_nodes, int(prob * 1000), rank, i) save_graph(graph, name) def generate_barabasi_albert(): """Generate small synthetic BA graphs.""" for num_nodes in range(10, 31, 5): for edges_per_step in range(2, 6): for i in range(20): graph = nx.barabasi_albert_graph(num_nodes, edges_per_step) if is_valid(graph): rank = cycles.fundamental_group_rank(graph) name = 'data/BA_N={}_m={}_R={}_i={}'.format(num_nodes, edges_per_step, rank, i) save_graph(graph, name) def generate_watts_strogatz(): """Generate small synthetic WS graphs.""" for num_nodes in range(10, 31, 5): for degree in [2, 4]: for prob in arange(0.05, 0.4, 0.05): for i in range(20): graph = nx.watts_strogatz_graph(num_nodes, degree, prob) if is_valid(graph): rank = cycles.fundamental_group_rank(graph) name = 'data/WS_N={}_d={}_p={}_R={}_i={}'.format(num_nodes, degree, int(prob * 1000), rank, i) save_graph(graph, name) def generate_other(): """Generate other small graphs.""" graph = nx.florentine_families_graph() if is_valid(graph): rank = cycles.fundamental_group_rank(graph) filename = 'data/{}_N={}_R={}'.format('florentine', len(graph), rank) save_graph(graph, filename) graph = nx.karate_club_graph() if is_valid(graph): rank = cycles.fundamental_group_rank(graph) filename = 'data/{}_N={}_R={}'.format('karate', len(graph), rank) save_graph(graph, filename) def main(): """Generate small graphs of different kinds.""" generate_erdos_renyi() generate_barabasi_albert() generate_watts_strogatz() generate_other() if __name__ == '__main__': main()
{ "content_hash": "84727440c3bba6ab8fef91cfb69a85a1", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 118, "avg_line_length": 33.02105263157895, "alnum_prop": 0.5773031558814153, "repo_name": "leotrs/graph_homotopy", "id": "b191af64d44ef32bc54ee859144141e877534ae8", "size": "3137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generate_graphs.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Matlab", "bytes": "9561" }, { "name": "Python", "bytes": "33231" } ], "symlink_target": "" }
package org.ovirt.engine.ui.uicommonweb.models.vms; import org.ovirt.engine.core.common.businessentities.BootSequence; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.InstanceType; import org.ovirt.engine.core.common.businessentities.MigrationSupport; import org.ovirt.engine.core.common.businessentities.UsbPolicy; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.ui.uicompat.ConstantsManager; import java.util.List; /** * Null object for instance types */ public class CustomInstanceType implements InstanceType { public static final CustomInstanceType INSTANCE = new CustomInstanceType(); @Override public String getDescription() { return ConstantsManager.getInstance().getConstants().customInstanceTypeDescription(); } @Override public String getName() { return ConstantsManager.getInstance().getConstants().customInstanceTypeName(); } @Override public Guid getId() { return null; } @Override public void setName(String value) { } @Override public void setDescription(String value) { } @Override public int getMemSizeMb() { return 0; } @Override public void setMemSizeMb(int value) { } @Override public int getNumOfSockets() { return 0; } @Override public void setNumOfSockets(int value) { } @Override public int getCpuPerSocket() { return 0; } @Override public void setCpuPerSocket(int value) { } @Override public List<VmNetworkInterface> getInterfaces() { return null; } @Override public void setInterfaces(List<VmNetworkInterface> value) { } @Override public int getNumOfMonitors() { return 0; } @Override public void setNumOfMonitors(int value) { } @Override public UsbPolicy getUsbPolicy() { return null; } @Override public void setUsbPolicy(UsbPolicy value) { } @Override public boolean isAutoStartup() { return false; } @Override public void setAutoStartup(boolean value) { } @Override public BootSequence getDefaultBootSequence() { // default boot sequence return BootSequence.C; } @Override public void setDefaultBootSequence(BootSequence value) { } @Override public DisplayType getDefaultDisplayType() { return null; } @Override public void setDefaultDisplayType(DisplayType value) { } @Override public int getPriority() { return 0; } @Override public void setPriority(int value) { } @Override public int getMinAllocatedMem() { return 0; } @Override public void setMinAllocatedMem(int value) { } @Override public Boolean getTunnelMigration() { return Boolean.FALSE; } @Override public void setTunnelMigration(Boolean value) { } @Override public void setSingleQxlPci(boolean value) { } @Override public boolean getSingleQxlPci() { return false; } @Override public boolean isSmartcardEnabled() { return false; } @Override public void setSmartcardEnabled(boolean smartcardEnabled) { } @Override public MigrationSupport getMigrationSupport() { return null; } @Override public void setMigrationSupport(MigrationSupport migrationSupport) { } @Override public void setMigrationDowntime(Integer migrationDowntime) { } @Override public Integer getMigrationDowntime() { return null; } @Override public void setId(Guid id) { } }
{ "content_hash": "4e88a1fec20febd2530e6868657b68f9", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 93, "avg_line_length": 18.407582938388625, "alnum_prop": 0.6583419155509783, "repo_name": "halober/ovirt-engine", "id": "1ba62f15f6bc6e084349a7c172258eb032511cfd", "size": "3884", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/CustomInstanceType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "251848" }, { "name": "Java", "bytes": "26541598" }, { "name": "JavaScript", "bytes": "890" }, { "name": "Python", "bytes": "698283" }, { "name": "Shell", "bytes": "105362" }, { "name": "XSLT", "bytes": "54683" } ], "symlink_target": "" }
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Tests.EditModeTests")] [assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Tests.PlayModeTests")]
{ "content_hash": "ab263ce796e91eb41dc3e031d6ca5f3c", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 84, "avg_line_length": 52.5, "alnum_prop": 0.8476190476190476, "repo_name": "killerantz/HoloToolkit-Unity", "id": "ca42dc6fc1f4b40b333daa892523dad29eeabb20", "size": "286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/MRTK/Core/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "10228041" }, { "name": "CSS", "bytes": "771" }, { "name": "GLSL", "bytes": "44693" }, { "name": "HLSL", "bytes": "856" }, { "name": "HTML", "bytes": "203" }, { "name": "JavaScript", "bytes": "2818" }, { "name": "PowerShell", "bytes": "123810" }, { "name": "Python", "bytes": "9153" }, { "name": "ShaderLab", "bytes": "130983" } ], "symlink_target": "" }
// <copyright file="InternetExplorerOptions.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2011 Software Freedom Conservancy // // 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. // </copyright> using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.IE { /// <summary> /// Specifies the scroll behavior of elements scrolled into view in the IE driver. /// </summary> public enum InternetExplorerElementScrollBehavior { /// <summary> /// Scrolls elements to align with the top of the viewport. /// </summary> Top, /// <summary> /// Scrolls elements to align with the bottom of the viewport. /// </summary> Bottom } /// <summary> /// Specifies the behavior of handling unexpected alerts in the IE driver. /// </summary> public enum InternetExplorerUnexpectedAlertBehavior { /// <summary> /// Indicates the behavior is not set. /// </summary> Default, /// <summary> /// Ignore unexpected alerts, such that the user must handle them. /// </summary> Ignore, /// <summary> /// Accept unexpected alerts. /// </summary> Accept, /// <summary> /// Dismiss unexpected alerts. /// </summary> Dismiss } /// <summary> /// Class to manage options specific to <see cref="InternetExplorerDriver"/> /// </summary> /// <example> /// <code> /// InternetExplorerOptions options = new InternetExplorerOptions(); /// options.IntroduceInstabilityByIgnoringProtectedModeSettings = true; /// </code> /// <para></para> /// <para>For use with InternetExplorerDriver:</para> /// <para></para> /// <code> /// InternetExplorerDriver driver = new InternetExplorerDriver(options); /// </code> /// <para></para> /// <para>For use with RemoteWebDriver:</para> /// <para></para> /// <code> /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities()); /// </code> /// </example> public class InternetExplorerOptions { private const string IgnoreProtectedModeSettingsCapability = "ignoreProtectedModeSettings"; private const string IgnoreZoomSettingCapability = "ignoreZoomSetting"; private const string InitialBrowserUrlCapability = "initialBrowserUrl"; private const string EnableNativeEventsCapability = "nativeEvents"; private const string ElementScrollBehaviorCapability = "elementScrollBehavior"; private const string UnexpectedAlertBehaviorCapability = "unexpectedAlertBehaviour"; private bool ignoreProtectedModeSettings; private bool ignoreZoomLevel; private bool enableNativeEvents = true; private string initialBrowserUrl = string.Empty; private InternetExplorerElementScrollBehavior elementScrollBehavior = InternetExplorerElementScrollBehavior.Top; private InternetExplorerUnexpectedAlertBehavior unexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Default; /// <summary> /// Gets or sets a value indicating whether to ignore the settings of the Internet Explorer Protected Mode. /// </summary> public bool IntroduceInstabilityByIgnoringProtectedModeSettings { get { return this.ignoreProtectedModeSettings; } set { this.ignoreProtectedModeSettings = value; } } /// <summary> /// Gets or sets a value indicating whether to ignore the zoom level of Internet Explorer . /// </summary> public bool IgnoreZoomLevel { get { return this.ignoreZoomLevel; } set { this.ignoreZoomLevel = value; } } /// <summary> /// Gets or sets a value indicating whether to use native events in interacting with elements. /// </summary> public bool EnableNativeEvents { get { return this.enableNativeEvents; } set { this.enableNativeEvents = value; } } /// <summary> /// Gets or sets the initial URL displayed when IE is launched. If not set, the browser launches /// with the internal startup page for the WebDriver server. /// </summary> /// <remarks> /// By setting the <see cref="IntroduceInstabilityByIgnoringProtectedModeSettings"/> to <see langword="true"/> /// and this property to a correct URL, you can launch IE in the Internet Protected Mode zone. This can be helpful /// to avoid the flakiness introduced by ignoring the Protected Mode settings. Nevertheless, setting Protected Mode /// zone settings to the same value in the IE configuration is the preferred method. /// </remarks> public string InitialBrowserUrl { get { return this.initialBrowserUrl; } set { this.initialBrowserUrl = value; } } /// <summary> /// Gets or sets the value for describing how elements are scrolled into view in the IE driver. Defaults /// to scrolling the element to the top of the viewport. /// </summary> public InternetExplorerElementScrollBehavior ElementScrollBehavior { get { return this.elementScrollBehavior; } set { this.elementScrollBehavior = value; } } /// <summary> /// Gets or sets the value for describing how unexpected alerts are to be handled in the IE driver. /// Defaults to <see cref="InternetExplorerUnexpectedAlertBehavior.Default"/>. /// </summary> public InternetExplorerUnexpectedAlertBehavior UnexpectedAlertBehavior { get { return this.unexpectedAlertBehavior; } set { this.unexpectedAlertBehavior = value; } } /// <summary> /// Returns DesiredCapabilities for IE with these options included as /// capabilities. This copies the options. Further changes will not be /// reflected in the returned capabilities. /// </summary> /// <returns>The DesiredCapabilities for IE with these options.</returns> public ICapabilities ToCapabilities() { DesiredCapabilities capabilities = DesiredCapabilities.InternetExplorer(); capabilities.SetCapability(EnableNativeEventsCapability, this.enableNativeEvents); if (this.ignoreProtectedModeSettings) { capabilities.SetCapability(IgnoreProtectedModeSettingsCapability, true); } if (this.ignoreZoomLevel) { capabilities.SetCapability(IgnoreZoomSettingCapability, true); } if (!string.IsNullOrEmpty(this.initialBrowserUrl)) { capabilities.SetCapability(InitialBrowserUrlCapability, this.initialBrowserUrl); } if (this.elementScrollBehavior == InternetExplorerElementScrollBehavior.Bottom) { capabilities.SetCapability(ElementScrollBehaviorCapability, 1); } if (this.unexpectedAlertBehavior != InternetExplorerUnexpectedAlertBehavior.Default) { string unexpectedAlertBehaviorSetting = "dismiss"; switch (this.unexpectedAlertBehavior) { case InternetExplorerUnexpectedAlertBehavior.Ignore: unexpectedAlertBehaviorSetting = "ignore"; break; case InternetExplorerUnexpectedAlertBehavior.Accept: unexpectedAlertBehaviorSetting = "accept"; break; } capabilities.SetCapability(UnexpectedAlertBehaviorCapability, unexpectedAlertBehaviorSetting); } return capabilities; } } }
{ "content_hash": "431a5a126c30c59505a821ccb61f645a", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 130, "avg_line_length": 39.61009174311926, "alnum_prop": 0.640880138969311, "repo_name": "bwp/SeleniumWebDriver", "id": "5341ac7ad36d51ea38bda0b6baf91610b03d2193", "size": "8637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dotnet/src/WebDriver/IE/InternetExplorerOptions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22162" }, { "name": "C", "bytes": "302788" }, { "name": "C#", "bytes": "2090580" }, { "name": "C++", "bytes": "771128" }, { "name": "Java", "bytes": "7874195" }, { "name": "JavaScript", "bytes": "14218193" }, { "name": "Objective-C", "bytes": "368823" }, { "name": "Python", "bytes": "634315" }, { "name": "Ruby", "bytes": "757466" }, { "name": "Shell", "bytes": "6429" } ], "symlink_target": "" }
var mysql = require('mysql'); var redis = require("redis"), client = redis.createClient(); var db_config = { host : 'localhost', user : 'ner', password : 'ner', database: 'ner' }; var connection; function handleDisconnect() { connection = mysql.createConnection(db_config); // Recreate the connection, // since // the old one cannot be reused. connection.connect(function(err) { // The server is either down if (err) { // or restarting (takes a while sometimes). console.log('error when connecting to db:', err); setTimeout(handleDisconnect, 2000); // We introduce a delay before // attempting to reconnect, } // to avoid a hot loop, and to allow our node script to }); // process asynchronous requests in the meantime. // If you're also serving http, display a 503 error. connection.on('error', function(err) { console.log('db error', err); if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the // MySQL server is // usually handleDisconnect(); // lost due to either server restart, or a } else { // connnection idle timeout (the wait_timeout throw err; // server variable configures this) } }); } handleDisconnect(); var query = connection.query('SELECT SQL_NO_CACHE * FROM page'); client.on("error", function (err) { console.log("Redis error " + err); }); var results = 0; query .on('error', function(err) { console.log("MySQL error: " + err); }) .on('result', function(row) { results++; connection.pause(); if ((results % 10000) === 0) { console.log("Processed " + results + " results"); } client.set(row.page_title, row.page_is_redirect); connection.resume(); }) .on('end', function() { console.log("All lines read"); });
{ "content_hash": "f332a38cffe0142872e3278a9a14ef4e", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 84, "avg_line_length": 32.32835820895522, "alnum_prop": 0.5249307479224377, "repo_name": "KIZI/Semitags", "id": "71bd73cff1e75143f0ddba7861c2007204481533", "size": "2166", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "NerIndexingSupport/fillRedisWithPages.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2180" }, { "name": "Erlang", "bytes": "4859" }, { "name": "Groovy", "bytes": "103" }, { "name": "HTML", "bytes": "2777" }, { "name": "Java", "bytes": "230287" }, { "name": "JavaScript", "bytes": "238051" }, { "name": "PHP", "bytes": "2554" }, { "name": "Perl", "bytes": "40112663" }, { "name": "Prolog", "bytes": "8263" }, { "name": "Python", "bytes": "19903" }, { "name": "R", "bytes": "3447" }, { "name": "Scala", "bytes": "9949" }, { "name": "Shell", "bytes": "59538" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#"> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-156274734-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-156274734-1'); </script> <meta property="og.image" content="https://github.com/tedszy/tedszy.github.io/tree/master/assets/img/love_math.png" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gallery</title> <meta name="description" content="mathematics and computer science teaching"> <!-- Google Fonts loaded here depending on setting in _data/options.yml true loads font, blank does not--> <link href='//fonts.googleapis.com/css?family=Lato:400,400italic' rel='stylesheet' type='text/css'> <!-- Load up MathJax script if needed ... specify in /_data/options.yml file--> <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="stylesheet" type="text/css" href="/css/tufte.css"> <!-- <link rel="stylesheet" type="text/css" href="/css/print.css" media="print"> --> <link rel="canonical" href="http://localhost:4000/page/gallery"> <link rel="alternate" type="application/rss+xml" title="tedszy" href="http://localhost:4000/feed.xml" /> </head> <body class="full-width"> <!--- Header and nav template site-wide --> <header> <nav class="group"> <a href="/"><img class="badge" src="/assets/img/love_math_mini.png" alt="t.sz"></a> <a href="/css/print.css"></a> <a href="/">Creative Math!</a> <a href="/page/blog">blog</a> <a href="/page/get_started">start</a> <a href="/page/code">code</a> <a href="/page/docs">Docs</a> <a href="/page/training">Training</a> <a href="/page/videos">videos</a> <a class="active" href="/page/gallery" class="active">Gallery</a> <a href="/page/contact">contact</a> </nav> </header> <article> <h1 class="content-listing-header sans">GALLERY</h1> <h2 id="brilliant-work-done-by-my-students">Brilliant work done by my students.</h2> <p><br /></p> <figure><figcaption>Beautiful group theory notes by grade 8 girl.</figcaption><img src="/assets/portfolio/m2-groups-notebook.jpg" /></figure> <figure><figcaption>Highlight of an incredible combinatorics test paper. Grade 7</figcaption><img src="/assets/portfolio/m1-combinatorics-test.jpg" /></figure> <figure><figcaption>The layout and organization of this number theory computation is a model of mathematical handwriting beauty. Grade 8 girl.</figcaption><img src="/assets/portfolio/m2-number-theory.jpg" /></figure> <figure><figcaption>Proof of Ptolemy's second theorem on cyclic quadrilaterals. Grade 8.</figcaption><img src="/assets/portfolio/m2-ptolemy2.jpg" /></figure> <figure><figcaption>Ruler-compass construction of huge polygon by grade 6 boy.</figcaption><img src="/assets/portfolio/p6-polygon.jpg" /></figure> <figure><figcaption>Visualization of 4D hypercube by grade 7 girl.</figcaption><img src="/assets/portfolio/m1-rucker.jpg" /></figure> </article> <span class="print-footer">Gallery - ted szylowiec</span> <footer> <hr class="slender"> <ul class="footer-links"> <li><a href="mailto:tedszy@gmail.com"><span class="icon-mail"></span></a></li> <li> <a href="//github.com/tedszy"><span class="icon-github"></span></a> </li> </ul> <div class="credits"> <span>&copy; 2020 &nbsp;&nbsp;TED SZYLOWIEC</span></br> <br> <span>This site created with the <a href="//github.com/clayh53/tufte-jekyll">Tufte theme for math and informatics </a> in <a href="//jekyllrb.com">Jekyll</a>.</span> </div> </footer> </body> </html>
{ "content_hash": "c375a23a870c7bc02a30c811e5ffa6e6", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 166, "avg_line_length": 26.99375, "alnum_prop": 0.6193563324843714, "repo_name": "tedszy/tedszy.github.io", "id": "b54c24d681ee92cbe9f075f1a4ab0f18858feb3f", "size": "4319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "page/gallery.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "80952" }, { "name": "Makefile", "bytes": "109" } ], "symlink_target": "" }
/** * @author Igor Polevoy: 12/18/13 4:32 PM */ package app.models; import org.javalite.activejdbc.Model; import org.javalite.activejdbc.annotations.Table; @Table("World") public class World extends Model { }
{ "content_hash": "2aceb194e0534e31e59f6bbffa4f0d27", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 49, "avg_line_length": 13.625, "alnum_prop": 0.7201834862385321, "repo_name": "kellabyte/FrameworkBenchmarks", "id": "cf495cf23ad7b6f9607dc58a18bd57746e669ff1", "size": "787", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "frameworks/Java/activeweb/src/main/java/app/models/World.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "838" }, { "name": "ApacheConf", "bytes": "21246" }, { "name": "Batchfile", "bytes": "1462" }, { "name": "C", "bytes": "39790" }, { "name": "C#", "bytes": "128594" }, { "name": "C++", "bytes": "36418" }, { "name": "CSS", "bytes": "216684" }, { "name": "Clojure", "bytes": "18787" }, { "name": "DIGITAL Command Language", "bytes": "34" }, { "name": "Dart", "bytes": "36763" }, { "name": "Elixir", "bytes": "1912" }, { "name": "Erlang", "bytes": "8219" }, { "name": "Go", "bytes": "35309" }, { "name": "Groff", "bytes": "49" }, { "name": "Groovy", "bytes": "18153" }, { "name": "HTML", "bytes": "69208" }, { "name": "Handlebars", "bytes": "242" }, { "name": "Haskell", "bytes": "10926" }, { "name": "Java", "bytes": "294508" }, { "name": "JavaScript", "bytes": "390011" }, { "name": "Lua", "bytes": "7396" }, { "name": "Makefile", "bytes": "1257" }, { "name": "MoonScript", "bytes": "2373" }, { "name": "Nginx", "bytes": "124707" }, { "name": "Nimrod", "bytes": "5120" }, { "name": "PHP", "bytes": "2527527" }, { "name": "Perl", "bytes": "11344" }, { "name": "PowerShell", "bytes": "35514" }, { "name": "Python", "bytes": "229697" }, { "name": "QMake", "bytes": "2056" }, { "name": "Racket", "bytes": "5298" }, { "name": "Ruby", "bytes": "74327" }, { "name": "Scala", "bytes": "63712" }, { "name": "Shell", "bytes": "177636" }, { "name": "Smarty", "bytes": "436" }, { "name": "Volt", "bytes": "677" } ], "symlink_target": "" }
package org.drools.workbench.services.verifier.plugin.client; import java.util.Set; import com.google.gwtmockito.GwtMockitoTestRunner; import org.drools.verifier.api.reporting.CheckType; import org.drools.verifier.api.reporting.Issue; import org.drools.workbench.services.verifier.plugin.client.testutil.AnalyzerConfigurationMock; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.drools.workbench.services.verifier.plugin.client.testutil.TestUtil.assertOnlyContains; @RunWith(GwtMockitoTestRunner.class) public class DecisionTableAnalyzerAllowListTest extends AnalyzerUpdateTestBase { @Override @Before public void setUp() throws Exception { super.setUp(); table52 = analyzerProvider.makeAnalyser() .withPersonAgeColumn(">") .withPersonApprovedActionSetField() .withData(DataBuilderProvider .row(0, true) .row(0, true) .row(null, null) .end()) .buildTable(); } @Test public void defaultAllowList() throws Exception { analyzerProvider.setConfiguration(new AnalyzerConfigurationMock()); fireUpAnalyzer(); final Set<Issue> analysisReport = analyzerProvider.getAnalysisReport(); assertOnlyContains(analysisReport, CheckType.REDUNDANT_ROWS, CheckType.SINGLE_HIT_LOST, CheckType.EMPTY_RULE); } @Test public void noRedundantRows() throws Exception { final AnalyzerConfigurationMock analyzerConfiguration = new AnalyzerConfigurationMock(); analyzerConfiguration.getCheckConfiguration() .getCheckConfiguration() .remove(CheckType.REDUNDANT_ROWS); analyzerConfiguration.getCheckConfiguration() .getCheckConfiguration() .remove(CheckType.SUBSUMPTANT_ROWS); analyzerProvider.setConfiguration(analyzerConfiguration); fireUpAnalyzer(); final Set<Issue> analysisReport = analyzerProvider.getAnalysisReport(); assertOnlyContains(analysisReport, CheckType.SINGLE_HIT_LOST, CheckType.EMPTY_RULE); } @Test public void noEmptyRule() throws Exception { final AnalyzerConfigurationMock analyzerConfiguration = new AnalyzerConfigurationMock(); analyzerConfiguration.getCheckConfiguration() .getCheckConfiguration() .remove(CheckType.EMPTY_RULE); analyzerProvider.setConfiguration(analyzerConfiguration); fireUpAnalyzer(); final Set<Issue> analysisReport = analyzerProvider.getAnalysisReport(); assertOnlyContains(analysisReport, CheckType.REDUNDANT_ROWS, CheckType.SINGLE_HIT_LOST); } }
{ "content_hash": "0a25e04678b9d3af811e779536304ca2", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 104, "avg_line_length": 33.98936170212766, "alnum_prop": 0.6078247261345853, "repo_name": "droolsjbpm/drools-wb", "id": "be4d858a7663de78441c49122a983192369bfc9c", "size": "3814", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "drools-wb-services/drools-wb-verifier/drools-wb-verifier-guided-decision-table-adapter/src/test/java/org/drools/workbench/services/verifier/plugin/client/DecisionTableAnalyzerAllowListTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3526" }, { "name": "CSS", "bytes": "26827" }, { "name": "HTML", "bytes": "20175" }, { "name": "Java", "bytes": "7411734" }, { "name": "JavaScript", "bytes": "58517" }, { "name": "Shell", "bytes": "3890" } ], "symlink_target": "" }
package ru.job4j.loop; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author edzabarov * @version $Id$ * @since 7.05.2017 */ public class CounterTest { /** *Test add. */ @Test public void whenSumEvenNumbersFromOneToTenThenThirty() { Counter counter = new Counter(); int result = counter.add(1, 10); int expected = 30; assertThat(result, is(expected)); } }
{ "content_hash": "ab977fb9bb67230d9bf06683e67eb9fb", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 60, "avg_line_length": 17.76923076923077, "alnum_prop": 0.6731601731601732, "repo_name": "eldar258/edzabarov", "id": "2c224991a852fac6ca7ceea452b6fb305f5a7dbe", "size": "462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_001/src/test/java/ru/job4j/loop/CounterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "297" }, { "name": "Java", "bytes": "282425" }, { "name": "XSLT", "bytes": "658" } ], "symlink_target": "" }
package org.nutz.mvc; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class ActionInfo { private String inputEncoding; private String outputEncoding; private String pathKey; private String[] paths; private Map<String, String> pathMap; private String chainName; private ObjectInfo<? extends HttpAdaptor> adaptorInfo; private ViewMaker[] viewMakers; private String okView; private String failView; private Set<String> httpMethods; private ObjectInfo<? extends ActionFilter>[] filterInfos; private String injectName; private Class<?> moduleType; private Method method; private boolean pathTop; public ActionInfo() { httpMethods = new HashSet<String>(); } public ActionInfo mergeWith(ActionInfo parent) { // 组合路径 - 与父路径做一个笛卡尔积 if (!pathTop && null != paths && null != parent.paths && parent.paths.length > 0) { List<String> myPaths = new ArrayList<String>(paths.length * parent.paths.length); for (int i = 0; i < parent.paths.length; i++) { String pp = parent.paths[i]; for (int x = 0; x < paths.length; x++) { myPaths.add(pp + paths[x]); } } paths = myPaths.toArray(new String[myPaths.size()]); } if (null == pathMap) { pathMap = parent.pathMap; } else { for (Entry<String, String> en : parent.pathMap.entrySet()) { if (pathMap.containsKey(en.getKey())) { continue; } pathMap.put(en.getKey(), en.getValue()); } } // 填充默认值 inputEncoding = null == inputEncoding ? parent.inputEncoding : inputEncoding; outputEncoding = null == outputEncoding ? parent.outputEncoding : outputEncoding; adaptorInfo = null == adaptorInfo ? parent.adaptorInfo : adaptorInfo; okView = null == okView ? parent.okView : okView; failView = null == failView ? parent.failView : failView; filterInfos = null == filterInfos ? parent.filterInfos : filterInfos; injectName = null == injectName ? parent.injectName : injectName; moduleType = null == moduleType ? parent.moduleType : moduleType; chainName = null == chainName ? parent.chainName : chainName; return this; } /** * @return 这个入口函数是不是只匹配特殊的 http 方法。 */ public boolean isForSpecialHttpMethod() { return httpMethods.size() > 0; } /** * 接受各种标准和非标准的Http Method * * @return 特殊的 HTTP 方法列表 */ public Set<String> getHttpMethods() { return httpMethods; } public String getPathKey() { return pathKey; } public void setPathKey(String pathKey) { this.pathKey = pathKey; } public String getInputEncoding() { return inputEncoding; } public void setInputEncoding(String inputEncoding) { this.inputEncoding = inputEncoding; } public String getOutputEncoding() { return outputEncoding; } public void setOutputEncoding(String outputEncoding) { this.outputEncoding = outputEncoding; } public String[] getPaths() { return paths; } public void setPaths(String[] paths) { this.paths = paths; } public Map<String, String> getPathMap() { return pathMap; } public void setPathMap(Map<String, String> pathMap) { this.pathMap = pathMap; } public ObjectInfo<? extends HttpAdaptor> getAdaptorInfo() { return adaptorInfo; } public void setAdaptorInfo(ObjectInfo<? extends HttpAdaptor> adaptorInfo) { this.adaptorInfo = adaptorInfo; } public String getChainName() { return chainName; } public void setChainName(String chainName) { this.chainName = chainName; } public ViewMaker[] getViewMakers() { return viewMakers; } public void setViewMakers(ViewMaker[] makers) { this.viewMakers = makers; } public String getOkView() { return okView; } public void setOkView(String okView) { this.okView = okView; } public String getFailView() { return failView; } public void setFailView(String failView) { this.failView = failView; } public ObjectInfo<? extends ActionFilter>[] getFilterInfos() { return filterInfos; } public void setFilterInfos(ObjectInfo<? extends ActionFilter>[] filterInfos) { this.filterInfos = filterInfos; } public String getInjectName() { return injectName; } public void setInjectName(String injectName) { this.injectName = injectName; } public Class<?> getModuleType() { return moduleType; } public void setModuleType(Class<?> moduleType) { this.moduleType = moduleType; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } public void setPathTop(boolean pathTop) { this.pathTop = pathTop; } public boolean isPathTop() { return pathTop; } }
{ "content_hash": "7ea7b528f27291231e4d4f9dc1e309a9", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 93, "avg_line_length": 24.269058295964125, "alnum_prop": 0.6075388026607539, "repo_name": "s24963386/nutz", "id": "025510dc45a9edd95dfec07e055f47fc1a9c120e", "size": "5524", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "src/org/nutz/mvc/ActionInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "202" }, { "name": "Batchfile", "bytes": "302" }, { "name": "Java", "bytes": "3353181" }, { "name": "JavaScript", "bytes": "6620" }, { "name": "Shell", "bytes": "263" } ], "symlink_target": "" }
package com.aspose.imaging.examples.images; import com.aspose.imaging.Image; import com.aspose.imaging.examples.Utils; import com.aspose.imaging.fileformats.png.PngColorType; import com.aspose.imaging.fileformats.psd.PsdImage; import com.aspose.imaging.imageloadoptions.PsdLoadOptions; import com.aspose.imaging.imageoptions.PngOptions; public class MissingFonts { public static void main(String[] args) { //ExStart:MissingFonts // The path to the documents directory. String dataDir = Utils.getSharedDataDir() + "images/"; String fileName = dataDir + "testReplacementNotAvailableFonts.psd"; PsdImage image = (PsdImage) Image.load(fileName, new PsdLoadOptions() {{ setDefaultReplacementFont("Arial"); }}); try { image.save(dataDir + "result.png", new PngOptions() {{ setColorType(PngColorType.TruecolorWithAlpha); }}); } finally { image.dispose(); } //ExEnd:MissingFonts } }
{ "content_hash": "cb01b40493baf66cca10627fbd07262d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 77, "avg_line_length": 29.564102564102566, "alnum_prop": 0.5975715524718127, "repo_name": "asposeimaging/Aspose_Imaging_Java", "id": "1b51d31b0d020eb747527a56315a15075d8dd8f4", "size": "1153", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Examples/src/main/java/com/aspose/imaging/examples/images/MissingFonts.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "134226" }, { "name": "PHP", "bytes": "42006" }, { "name": "Ruby", "bytes": "57735" } ], "symlink_target": "" }
package com.documents4j.conversion.msoffice; import org.junit.BeforeClass; public class MicrosoftExcelStartStopTest extends AbstractMicrosoftOfficeStartStopTest { public MicrosoftExcelStartStopTest() { super(MicrosoftExcelBridge.class); } @BeforeClass public static void setUpConverter() throws Exception { AbstractMicrosoftOfficeStartStopTest.setUp(MicrosoftExcelScript.ASSERTION, MicrosoftExcelScript.SHUTDOWN); } }
{ "content_hash": "f4e8252e606943e865b0ee9d9edd1d25", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 114, "avg_line_length": 30.533333333333335, "alnum_prop": 0.7903930131004366, "repo_name": "documents4j/documents4j", "id": "7fc7d369c5b7d70f123b201cdd70a0f56135420f", "size": "458", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "documents4j-transformer-msoffice/documents4j-transformer-msoffice-excel/src/test/java/com/documents4j/conversion/msoffice/MicrosoftExcelStartStopTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "5936" }, { "name": "HTML", "bytes": "3761" }, { "name": "Java", "bytes": "523318" }, { "name": "Rich Text Format", "bytes": "4055001" }, { "name": "VBScript", "bytes": "10946" } ], "symlink_target": "" }
package org.apache.olingo.client.core.domain; import org.apache.olingo.client.api.domain.ClientAnnotatable; import org.apache.olingo.client.api.domain.ClientAnnotation; import org.apache.olingo.client.api.domain.ClientCollectionValue; import org.apache.olingo.client.api.domain.ClientComplexValue; import org.apache.olingo.client.api.domain.ClientEnumValue; import org.apache.olingo.client.api.domain.ClientPrimitiveValue; import org.apache.olingo.client.api.domain.ClientProperty; import org.apache.olingo.client.api.domain.ClientValuable; import org.apache.olingo.client.api.domain.ClientValue; import java.util.ArrayList; import java.util.List; public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatable, ClientValuable { private final List<ClientAnnotation> annotations = new ArrayList<ClientAnnotation>(); private final String name; private final ClientValue value; private final ClientValuable valuable; public ClientPropertyImpl(final String name, final ClientValue value) { this.name = name; this.value = value; this.valuable = new ClientValuableImpl(value); } /** * Returns property name. * * @return property name. */ @Override public String getName() { return name; } /** * Returns property value. * * @return property value. */ @Override public ClientValue getValue() { return value; } /** * Checks if has null value. * * @return 'TRUE' if has null value; 'FALSE' otherwise. */ @Override public boolean hasNullValue() { return value == null || value.isPrimitive() && value.asPrimitive().toValue() == null; } /** * Checks if has primitive value. * * @return 'TRUE' if has primitive value; 'FALSE' otherwise. */ @Override public boolean hasPrimitiveValue() { return !hasNullValue() && value.isPrimitive(); } /** * Gets primitive value. * * @return primitive value if exists; null otherwise. */ @Override public ClientPrimitiveValue getPrimitiveValue() { return hasPrimitiveValue() ? value.asPrimitive() : null; } /** * Checks if has complex value. * * @return 'TRUE' if has complex value; 'FALSE' otherwise. */ @Override public boolean hasComplexValue() { return !hasNullValue() && value.isComplex(); } /** * Checks if has collection value. * * @return 'TRUE' if has collection value; 'FALSE' otherwise. */ @Override public boolean hasCollectionValue() { return !hasNullValue() && value.isCollection(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ClientPropertyImpl)) { return false; } ClientPropertyImpl other = (ClientPropertyImpl) obj; if (annotations == null) { if (other.annotations != null) { return false; } } else if (!annotations.equals(other.annotations)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (valuable == null) { if (other.valuable != null) { return false; } } else if (!valuable.equals(other.valuable)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((annotations == null) ? 0 : annotations.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((valuable == null) ? 0 : valuable.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean hasEnumValue() { return valuable.hasEnumValue(); } @Override public ClientEnumValue getEnumValue() { return valuable.getEnumValue(); } @Override public ClientComplexValue getComplexValue() { return valuable.getComplexValue(); } @Override public ClientCollectionValue<ClientValue> getCollectionValue() { return valuable.getCollectionValue(); } @Override public List<ClientAnnotation> getAnnotations() { return annotations; } @Override public String toString() { return "ODataPropertyImpl{" + "name=" + getName() + ",valuable=" + valuable + ", annotations=" + annotations + '}'; } }
{ "content_hash": "0de0fbd331af6efe51b60221fc60e3fc", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 100, "avg_line_length": 24.74866310160428, "alnum_prop": 0.6486603284356093, "repo_name": "AperIati/olingo-odata4", "id": "f78c506fa6af2c11f0c687cd4f85fa9a735530f2", "size": "5431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPropertyImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "36742" }, { "name": "CSS", "bytes": "1731" }, { "name": "Groovy", "bytes": "5831" }, { "name": "HTML", "bytes": "1289" }, { "name": "Java", "bytes": "7851238" }, { "name": "XSLT", "bytes": "1824" } ], "symlink_target": "" }
package org.apache.maven.cli; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.inject.AbstractModule; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.UnrecognizedOptionException; import org.apache.maven.BuildAbort; import org.apache.maven.InternalErrorException; import org.apache.maven.Maven; import org.apache.maven.building.FileSource; import org.apache.maven.building.Problem; import org.apache.maven.building.Source; import org.apache.maven.cli.configuration.ConfigurationProcessor; import org.apache.maven.cli.configuration.SettingsXmlConfigurationProcessor; import org.apache.maven.cli.event.DefaultEventSpyContext; import org.apache.maven.cli.event.ExecutionEventLogger; import org.apache.maven.cli.internal.BootstrapCoreExtensionManager; import org.apache.maven.cli.internal.extension.model.CoreExtension; import org.apache.maven.cli.internal.extension.model.io.xpp3.CoreExtensionsXpp3Reader; import org.apache.maven.cli.logging.Slf4jConfiguration; import org.apache.maven.cli.logging.Slf4jConfigurationFactory; import org.apache.maven.cli.logging.Slf4jLoggerManager; import org.apache.maven.cli.logging.Slf4jStdoutLogger; import org.apache.maven.cli.transfer.ConsoleMavenTransferListener; import org.apache.maven.cli.transfer.QuietMavenTransferListener; import org.apache.maven.cli.transfer.Slf4jMavenTransferListener; import org.apache.maven.eventspy.internal.EventSpyDispatcher; import org.apache.maven.exception.DefaultExceptionHandler; import org.apache.maven.exception.ExceptionHandler; import org.apache.maven.exception.ExceptionSummary; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.ExecutionListener; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequestPopulationException; import org.apache.maven.execution.MavenExecutionRequestPopulator; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.extension.internal.CoreExports; import org.apache.maven.extension.internal.CoreExtensionEntry; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.project.MavenProject; import org.apache.maven.properties.internal.EnvironmentUtils; import org.apache.maven.properties.internal.SystemProperties; import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest; import org.apache.maven.toolchain.building.ToolchainsBuilder; import org.apache.maven.toolchain.building.ToolchainsBuildingResult; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.logging.LoggerManager; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.transfer.TransferListener; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; import java.io.BufferedInputStream; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; // TODO: push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs /** * @author Jason van Zyl * @noinspection UseOfSystemOutOrSystemErr, ACCESS_STATIC_VIA_INSTANCE */ public class MavenCli { public static final String LOCAL_REPO_PROPERTY = "maven.repo.local"; public static final String THREADS_DEPRECATED = "maven.threads.experimental"; public static final String MULTIMODULE_PROJECT_DIRECTORY = "maven.multiModuleProjectDirectory"; @SuppressWarnings( "checkstyle:constantname" ) public static final String userHome = System.getProperty( "user.home" ); @SuppressWarnings( "checkstyle:constantname" ) public static final File userMavenConfigurationHome = new File( userHome, ".m2" ); /** * @deprecated use {@link SettingsXmlConfigurationProcessor#DEFAULT_USER_SETTINGS_FILE} */ public static final File DEFAULT_USER_SETTINGS_FILE = SettingsXmlConfigurationProcessor.DEFAULT_USER_SETTINGS_FILE; /** * @deprecated use {@link SettingsXmlConfigurationProcessor#DEFAULT_GLOBAL_SETTINGS_FILE} */ public static final File DEFAULT_GLOBAL_SETTINGS_FILE = SettingsXmlConfigurationProcessor.DEFAULT_GLOBAL_SETTINGS_FILE; public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File( userMavenConfigurationHome, "toolchains.xml" ); public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE = new File( System.getProperty( "maven.home", System.getProperty( "user.dir", "" ) ), "conf/toolchains.xml" ); private static final String EXT_CLASS_PATH = "maven.ext.class.path"; private static final String EXTENSIONS_FILENAME = ".mvn/extensions.xml"; private ClassWorld classWorld; private LoggerManager plexusLoggerManager; private ILoggerFactory slf4jLoggerFactory; private Logger slf4jLogger; private EventSpyDispatcher eventSpyDispatcher; private ModelProcessor modelProcessor; private Maven maven; private MavenExecutionRequestPopulator executionRequestPopulator; private ToolchainsBuilder toolchainsBuilder; private DefaultSecDispatcher dispatcher; private Map<String, ConfigurationProcessor> configurationProcessors; public MavenCli() { this( null ); } // This supports painless invocation by the Verifier during embedded execution of the core ITs public MavenCli( ClassWorld classWorld ) { this.classWorld = classWorld; } public static void main( String[] args ) { int result = main( args, null ); System.exit( result ); } /** * @noinspection ConfusingMainMethod */ public static int main( String[] args, ClassWorld classWorld ) { MavenCli cli = new MavenCli(); return cli.doMain( new CliRequest( args, classWorld ) ); } // TODO: need to externalize CliRequest public static int doMain( String[] args, ClassWorld classWorld ) { MavenCli cli = new MavenCli(); return cli.doMain( new CliRequest( args, classWorld ) ); } // This supports painless invocation by the Verifier during embedded execution of the core ITs public int doMain( String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr ) { PrintStream oldout = System.out; PrintStream olderr = System.err; final Set<String> realms; if ( classWorld != null ) { realms = new HashSet<>(); for ( ClassRealm realm : classWorld.getRealms() ) { realms.add( realm.getId() ); } } else { realms = Collections.emptySet(); } try { if ( stdout != null ) { System.setOut( stdout ); } if ( stderr != null ) { System.setErr( stderr ); } CliRequest cliRequest = new CliRequest( args, classWorld ); cliRequest.workingDirectory = workingDirectory; return doMain( cliRequest ); } finally { if ( classWorld != null ) { for ( ClassRealm realm : new ArrayList<>( classWorld.getRealms() ) ) { String realmId = realm.getId(); if ( !realms.contains( realmId ) ) { try { classWorld.disposeRealm( realmId ); } catch ( NoSuchRealmException ignored ) { // can't happen } } } } System.setOut( oldout ); System.setErr( olderr ); } } // TODO: need to externalize CliRequest public int doMain( CliRequest cliRequest ) { PlexusContainer localContainer = null; try { initialize( cliRequest ); cli( cliRequest ); logging( cliRequest ); version( cliRequest ); properties( cliRequest ); localContainer = container( cliRequest ); commands( cliRequest ); configure( cliRequest ); toolchains( cliRequest ); populateRequest( cliRequest ); encryption( cliRequest ); repository( cliRequest ); return execute( cliRequest ); } catch ( ExitException e ) { return e.exitCode; } catch ( UnrecognizedOptionException e ) { // pure user error, suppress stack trace return 1; } catch ( BuildAbort e ) { CLIReportingUtils.showError( slf4jLogger, "ABORTED", e, cliRequest.showErrors ); return 2; } catch ( Exception e ) { CLIReportingUtils.showError( slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors ); return 1; } finally { if ( localContainer != null ) { localContainer.dispose(); } } } void initialize( CliRequest cliRequest ) throws ExitException { if ( cliRequest.workingDirectory == null ) { cliRequest.workingDirectory = System.getProperty( "user.dir" ); } if ( cliRequest.multiModuleProjectDirectory == null ) { String basedirProperty = System.getProperty( MULTIMODULE_PROJECT_DIRECTORY ); if ( basedirProperty == null ) { System.err.format( "-D%s system property is not set." + " Check $M2_HOME environment variable and mvn script match.", MULTIMODULE_PROJECT_DIRECTORY ); throw new ExitException( 1 ); } File basedir = basedirProperty != null ? new File( basedirProperty ) : new File( "" ); try { cliRequest.multiModuleProjectDirectory = basedir.getCanonicalFile(); } catch ( IOException e ) { cliRequest.multiModuleProjectDirectory = basedir.getAbsoluteFile(); } } // // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative // Windows paths. // String mavenHome = System.getProperty( "maven.home" ); if ( mavenHome != null ) { System.setProperty( "maven.home", new File( mavenHome ).getAbsolutePath() ); } } void cli( CliRequest cliRequest ) throws Exception { // // Parsing errors can happen during the processing of the arguments and we prefer not having to check if // the logger is null and construct this so we can use an SLF4J logger everywhere. // slf4jLogger = new Slf4jStdoutLogger(); CLIManager cliManager = new CLIManager(); List<String> args = new ArrayList<>(); try { File configFile = new File( cliRequest.multiModuleProjectDirectory, ".mvn/maven.config" ); if ( configFile.isFile() ) { for ( String arg : Files.toString( configFile, Charsets.UTF_8 ).split( "\\s+" ) ) { if ( !arg.isEmpty() ) { args.add( arg ); } } CommandLine config = cliManager.parse( args.toArray( new String[args.size()] ) ); List<?> unrecongized = config.getArgList(); if ( !unrecongized.isEmpty() ) { throw new ParseException( "Unrecognized maven.config entries: " + unrecongized ); } } } catch ( ParseException e ) { System.err.println( "Unable to parse maven.config: " + e.getMessage() ); cliManager.displayHelp( System.out ); throw e; } try { args.addAll( 0, Arrays.asList( cliRequest.args ) ); cliRequest.commandLine = cliManager.parse( args.toArray( new String[args.size()] ) ); } catch ( ParseException e ) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); cliManager.displayHelp( System.out ); throw e; } if ( cliRequest.commandLine.hasOption( CLIManager.HELP ) ) { cliManager.displayHelp( System.out ); throw new ExitException( 0 ); } if ( cliRequest.commandLine.hasOption( CLIManager.VERSION ) ) { System.out.println( CLIReportingUtils.showVersion() ); throw new ExitException( 0 ); } } /** * configure logging */ private void logging( CliRequest cliRequest ) { cliRequest.debug = cliRequest.commandLine.hasOption( CLIManager.DEBUG ); cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption( CLIManager.QUIET ); cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.ERRORS ); slf4jLoggerFactory = LoggerFactory.getILoggerFactory(); Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration( slf4jLoggerFactory ); if ( cliRequest.debug ) { cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_DEBUG ); slf4jConfiguration.setRootLoggerLevel( Slf4jConfiguration.Level.DEBUG ); } else if ( cliRequest.quiet ) { cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_ERROR ); slf4jConfiguration.setRootLoggerLevel( Slf4jConfiguration.Level.ERROR ); } // else fall back to default log level specified in conf // see http://jira.codehaus.org/browse/MNG-2570 if ( cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) ) { File logFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.LOG_FILE ) ); logFile = resolveFile( logFile, cliRequest.workingDirectory ); // redirect stdout and stderr to file try { PrintStream ps = new PrintStream( new FileOutputStream( logFile ) ); System.setOut( ps ); System.setErr( ps ); } catch ( FileNotFoundException e ) { // // Ignore // } } slf4jConfiguration.activate(); plexusLoggerManager = new Slf4jLoggerManager(); slf4jLogger = slf4jLoggerFactory.getLogger( this.getClass().getName() ); } private void version( CliRequest cliRequest ) { if ( cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.SHOW_VERSION ) ) { System.out.println( CLIReportingUtils.showVersion() ); } } private void commands( CliRequest cliRequest ) { if ( cliRequest.showErrors ) { slf4jLogger.info( "Error stacktraces are turned on." ); } if ( MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { slf4jLogger.info( "Disabling strict checksum verification on all artifact downloads." ); } else if ( MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { slf4jLogger.info( "Enabling strict checksum verification on all artifact downloads." ); } } private void properties( CliRequest cliRequest ) { populateProperties( cliRequest.commandLine, cliRequest.systemProperties, cliRequest.userProperties ); } private PlexusContainer container( CliRequest cliRequest ) throws Exception { if ( cliRequest.classWorld == null ) { cliRequest.classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() ); } ClassRealm coreRealm = cliRequest.classWorld.getClassRealm( "plexus.core" ); if ( coreRealm == null ) { coreRealm = cliRequest.classWorld.getRealms().iterator().next(); } List<File> extClassPath = parseExtClasspath( cliRequest ); CoreExtensionEntry coreEntry = CoreExtensionEntry.discoverFrom( coreRealm ); List<CoreExtensionEntry> extensions = loadCoreExtensions( cliRequest, coreRealm, coreEntry.getExportedArtifacts() ); ClassRealm containerRealm = setupContainerRealm( cliRequest.classWorld, coreRealm, extClassPath, extensions ); ContainerConfiguration cc = new DefaultContainerConfiguration().setClassWorld( cliRequest.classWorld ).setRealm( containerRealm ).setClassPathScanning( PlexusConstants.SCANNING_INDEX ).setAutoWiring( true ).setName( "maven" ); Set<String> exportedArtifacts = new HashSet<>( coreEntry.getExportedArtifacts() ); Set<String> exportedPackages = new HashSet<>( coreEntry.getExportedPackages() ); for ( CoreExtensionEntry extension : extensions ) { exportedArtifacts.addAll( extension.getExportedArtifacts() ); exportedPackages.addAll( extension.getExportedPackages() ); } final CoreExports exports = new CoreExports( containerRealm, exportedArtifacts, exportedPackages ); DefaultPlexusContainer container = new DefaultPlexusContainer( cc, new AbstractModule() { @Override protected void configure() { bind( ILoggerFactory.class ).toInstance( slf4jLoggerFactory ); bind( CoreExports.class ).toInstance( exports ); } } ); // NOTE: To avoid inconsistencies, we'll use the TCCL exclusively for lookups container.setLookupRealm( null ); container.setLoggerManager( plexusLoggerManager ); for ( CoreExtensionEntry extension : extensions ) { container.discoverComponents( extension.getClassRealm() ); } customizeContainer( container ); container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() ); Thread.currentThread().setContextClassLoader( container.getContainerRealm() ); eventSpyDispatcher = container.lookup( EventSpyDispatcher.class ); DefaultEventSpyContext eventSpyContext = new DefaultEventSpyContext(); Map<String, Object> data = eventSpyContext.getData(); data.put( "plexus", container ); data.put( "workingDirectory", cliRequest.workingDirectory ); data.put( "systemProperties", cliRequest.systemProperties ); data.put( "userProperties", cliRequest.userProperties ); data.put( "versionProperties", CLIReportingUtils.getBuildProperties() ); eventSpyDispatcher.init( eventSpyContext ); // refresh logger in case container got customized by spy slf4jLogger = slf4jLoggerFactory.getLogger( this.getClass().getName() ); maven = container.lookup( Maven.class ); executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); modelProcessor = createModelProcessor( container ); configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); toolchainsBuilder = container.lookup( ToolchainsBuilder.class ); dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class, "maven" ); return container; } private List<CoreExtensionEntry> loadCoreExtensions( CliRequest cliRequest, ClassRealm containerRealm, Set<String> providedArtifacts ) { if ( cliRequest.multiModuleProjectDirectory == null ) { return Collections.emptyList(); } File extensionsFile = new File( cliRequest.multiModuleProjectDirectory, EXTENSIONS_FILENAME ); if ( !extensionsFile.isFile() ) { return Collections.emptyList(); } try { List<CoreExtension> extensions = readCoreExtensionsDescriptor( extensionsFile ); if ( extensions.isEmpty() ) { return Collections.emptyList(); } ContainerConfiguration cc = new DefaultContainerConfiguration() // .setClassWorld( cliRequest.classWorld ) // .setRealm( containerRealm ) // .setClassPathScanning( PlexusConstants.SCANNING_INDEX ) // .setAutoWiring( true ) // .setName( "maven" ); DefaultPlexusContainer container = new DefaultPlexusContainer( cc, new AbstractModule() { @Override protected void configure() { bind( ILoggerFactory.class ).toInstance( slf4jLoggerFactory ); } } ); try { container.setLookupRealm( null ); container.setLoggerManager( plexusLoggerManager ); container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() ); Thread.currentThread().setContextClassLoader( container.getContainerRealm() ); executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); configurationProcessors = container.lookupMap( ConfigurationProcessor.class ); configure( cliRequest ); MavenExecutionRequest request = DefaultMavenExecutionRequest.copy( cliRequest.request ); request = populateRequest( cliRequest, request ); request = executionRequestPopulator.populateDefaults( request ); BootstrapCoreExtensionManager resolver = container.lookup( BootstrapCoreExtensionManager.class ); return resolver.loadCoreExtensions( request, providedArtifacts, extensions ); } finally { executionRequestPopulator = null; container.dispose(); } } catch ( RuntimeException e ) { // runtime exceptions are most likely bugs in maven, let them bubble up to the user throw e; } catch ( Exception e ) { slf4jLogger.warn( "Failed to read extensions descriptor " + extensionsFile + ": " + e.getMessage() ); } return Collections.emptyList(); } private List<CoreExtension> readCoreExtensionsDescriptor( File extensionsFile ) throws IOException, XmlPullParserException { CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader(); try ( InputStream is = new BufferedInputStream( new FileInputStream( extensionsFile ) ) ) { return parser.read( is ).getExtensions(); } } private ClassRealm setupContainerRealm( ClassWorld classWorld, ClassRealm coreRealm, List<File> extClassPath, List<CoreExtensionEntry> extensions ) throws Exception { if ( !extClassPath.isEmpty() || !extensions.isEmpty() ) { ClassRealm extRealm = classWorld.newRealm( "maven.ext", null ); extRealm.setParentRealm( coreRealm ); slf4jLogger.debug( "Populating class realm " + extRealm.getId() ); for ( File file : extClassPath ) { slf4jLogger.debug( " Included " + file ); extRealm.addURL( file.toURI().toURL() ); } for ( CoreExtensionEntry entry : reverse( extensions ) ) { Set<String> exportedPackages = entry.getExportedPackages(); ClassRealm realm = entry.getClassRealm(); for ( String exportedPackage : exportedPackages ) { extRealm.importFrom( realm, exportedPackage ); } if ( exportedPackages.isEmpty() ) { // sisu uses realm imports to establish component visibility extRealm.importFrom( realm, realm.getId() ); } } return extRealm; } return coreRealm; } private static <T> List<T> reverse( List<T> list ) { List<T> copy = new ArrayList<>( list ); Collections.reverse( copy ); return copy; } private List<File> parseExtClasspath( CliRequest cliRequest ) { String extClassPath = cliRequest.userProperties.getProperty( EXT_CLASS_PATH ); if ( extClassPath == null ) { extClassPath = cliRequest.systemProperties.getProperty( EXT_CLASS_PATH ); } List<File> jars = new ArrayList<>(); if ( StringUtils.isNotEmpty( extClassPath ) ) { for ( String jar : StringUtils.split( extClassPath, File.pathSeparator ) ) { File file = resolveFile( new File( jar ), cliRequest.workingDirectory ); slf4jLogger.debug( " Included " + file ); jars.add( file ); } } return jars; } // // This should probably be a separate tool and not be baked into Maven. // private void encryption( CliRequest cliRequest ) throws Exception { if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_MASTER_PASSWORD ) ) { String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_MASTER_PASSWORD ); if ( passwd == null ) { Console cons = System.console(); char[] password = ( cons == null ) ? null : cons.readPassword( "Master password: " ); if ( password != null ) { // Cipher uses Strings passwd = String.copyValueOf( password ); // Sun/Oracle advises to empty the char array java.util.Arrays.fill( password, ' ' ); } } DefaultPlexusCipher cipher = new DefaultPlexusCipher(); System.out.println( cipher.encryptAndDecorate( passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); throw new ExitException( 0 ); } else if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_PASSWORD ) ) { String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_PASSWORD ); if ( passwd == null ) { Console cons = System.console(); char[] password = ( cons == null ) ? null : cons.readPassword( "Password: " ); if ( password != null ) { // Cipher uses Strings passwd = String.copyValueOf( password ); // Sun/Oracle advises to empty the char array java.util.Arrays.fill( password, ' ' ); } } String configurationFile = dispatcher.getConfigurationFile(); if ( configurationFile.startsWith( "~" ) ) { configurationFile = System.getProperty( "user.home" ) + configurationFile.substring( 1 ); } String file = System.getProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile ); String master = null; SettingsSecurity sec = SecUtil.read( file, true ); if ( sec != null ) { master = sec.getMaster(); } if ( master == null ) { throw new IllegalStateException( "Master password is not set in the setting security file: " + file ); } DefaultPlexusCipher cipher = new DefaultPlexusCipher(); String masterPasswd = cipher.decryptDecorated( master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ); System.out.println( cipher.encryptAndDecorate( passwd, masterPasswd ) ); throw new ExitException( 0 ); } } private void repository( CliRequest cliRequest ) throws Exception { if ( cliRequest.commandLine.hasOption( CLIManager.LEGACY_LOCAL_REPOSITORY ) || Boolean.getBoolean( "maven.legacyLocalRepo" ) ) { cliRequest.request.setUseLegacyLocalRepository( true ); } } private int execute( CliRequest cliRequest ) throws MavenExecutionRequestPopulationException { MavenExecutionRequest request = executionRequestPopulator.populateDefaults( cliRequest.request ); eventSpyDispatcher.onEvent( request ); MavenExecutionResult result = maven.execute( request ); eventSpyDispatcher.onEvent( result ); eventSpyDispatcher.close(); if ( result.hasExceptions() ) { ExceptionHandler handler = new DefaultExceptionHandler(); Map<String, String> references = new LinkedHashMap<>(); MavenProject project = null; for ( Throwable exception : result.getExceptions() ) { ExceptionSummary summary = handler.handleException( exception ); logSummary( summary, references, "", cliRequest.showErrors ); if ( project == null && exception instanceof LifecycleExecutionException ) { project = ( (LifecycleExecutionException) exception ).getProject(); } } slf4jLogger.error( "" ); if ( !cliRequest.showErrors ) { slf4jLogger.error( "To see the full stack trace of the errors, re-run Maven with the -e switch." ); } if ( !slf4jLogger.isDebugEnabled() ) { slf4jLogger.error( "Re-run Maven using the -X switch to enable full debug logging." ); } if ( !references.isEmpty() ) { slf4jLogger.error( "" ); slf4jLogger.error( "For more information about the errors and possible solutions" + ", please read the following articles:" ); for ( Map.Entry<String, String> entry : references.entrySet() ) { slf4jLogger.error( entry.getValue() + " " + entry.getKey() ); } } if ( project != null && !project.equals( result.getTopologicallySortedProjects().get( 0 ) ) ) { slf4jLogger.error( "" ); slf4jLogger.error( "After correcting the problems, you can resume the build with the command" ); slf4jLogger.error( " mvn <goals> -rf :" + project.getArtifactId() ); } if ( MavenExecutionRequest.REACTOR_FAIL_NEVER.equals( cliRequest.request.getReactorFailureBehavior() ) ) { slf4jLogger.info( "Build failures were ignored." ); return 0; } else { return 1; } } else { return 0; } } private void logSummary( ExceptionSummary summary, Map<String, String> references, String indent, boolean showErrors ) { String referenceKey = ""; if ( StringUtils.isNotEmpty( summary.getReference() ) ) { referenceKey = references.get( summary.getReference() ); if ( referenceKey == null ) { referenceKey = "[Help " + ( references.size() + 1 ) + "]"; references.put( summary.getReference(), referenceKey ); } } String msg = summary.getMessage(); if ( StringUtils.isNotEmpty( referenceKey ) ) { if ( msg.indexOf( '\n' ) < 0 ) { msg += " -> " + referenceKey; } else { msg += "\n-> " + referenceKey; } } String[] lines = msg.split( "(\r\n)|(\r)|(\n)" ); for ( int i = 0; i < lines.length; i++ ) { String line = indent + lines[i].trim(); if ( ( i == lines.length - 1 ) && ( showErrors || ( summary.getException() instanceof InternalErrorException ) ) ) { slf4jLogger.error( line, summary.getException() ); } else { slf4jLogger.error( line ); } } indent += " "; for ( ExceptionSummary child : summary.getChildren() ) { logSummary( child, references, indent, showErrors ); } } @SuppressWarnings( "checkstyle:methodlength" ) private void configure( CliRequest cliRequest ) throws Exception { // // This is not ideal but there are events specifically for configuration from the CLI which I don't // believe are really valid but there are ITs which assert the right events are published so this // needs to be supported so the EventSpyDispatcher needs to be put in the CliRequest so that // it can be accessed by configuration processors. // cliRequest.request.setEventSpyDispatcher( eventSpyDispatcher ); // // We expect at most 2 implementations to be available. The SettingsXmlConfigurationProcessor implementation // is always available in the core and likely always will be, but we may have another ConfigurationProcessor // present supplied by the user. The rule is that we only allow the execution of one ConfigurationProcessor. // If there is more than one then we execute the one supplied by the user, otherwise we execute the // the default SettingsXmlConfigurationProcessor. // int userSuppliedConfigurationProcessorCount = configurationProcessors.size() - 1; if ( userSuppliedConfigurationProcessorCount == 0 ) { // // Our settings.xml source is historically how we have configured Maven from the CLI so we are going to // have to honour its existence forever. So let's run it. // configurationProcessors.get( SettingsXmlConfigurationProcessor.HINT ).process( cliRequest ); } else if ( userSuppliedConfigurationProcessorCount == 1 ) { // // Run the user supplied ConfigurationProcessor // for ( Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet() ) { String hint = entry.getKey(); if ( !hint.equals( SettingsXmlConfigurationProcessor.HINT ) ) { ConfigurationProcessor configurationProcessor = entry.getValue(); configurationProcessor.process( cliRequest ); } } } else if ( userSuppliedConfigurationProcessorCount > 1 ) { // // There are too many ConfigurationProcessors so we don't know which one to run so report the error. // StringBuilder sb = new StringBuilder( String.format( "\nThere can only be one user supplied ConfigurationProcessor, there are %s:\n\n", userSuppliedConfigurationProcessorCount ) ); for ( Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet() ) { String hint = entry.getKey(); if ( !hint.equals( SettingsXmlConfigurationProcessor.HINT ) ) { ConfigurationProcessor configurationProcessor = entry.getValue(); sb.append( String.format( "%s\n", configurationProcessor.getClass().getName() ) ); } } sb.append( String.format( "\n" ) ); throw new Exception( sb.toString() ); } } @SuppressWarnings( "checkstyle:methodlength" ) private void toolchains( CliRequest cliRequest ) throws Exception { File userToolchainsFile; if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ) { userToolchainsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ); userToolchainsFile = resolveFile( userToolchainsFile, cliRequest.workingDirectory ); if ( !userToolchainsFile.isFile() ) { throw new FileNotFoundException( "The specified user toolchains file does not exist: " + userToolchainsFile ); } } else { userToolchainsFile = DEFAULT_USER_TOOLCHAINS_FILE; } File globalToolchainsFile; if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS ) ) { globalToolchainsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS ) ); globalToolchainsFile = resolveFile( globalToolchainsFile, cliRequest.workingDirectory ); if ( !globalToolchainsFile.isFile() ) { throw new FileNotFoundException( "The specified global toolchains file does not exist: " + globalToolchainsFile ); } } else { globalToolchainsFile = DEFAULT_GLOBAL_TOOLCHAINS_FILE; } cliRequest.request.setGlobalToolchainsFile( globalToolchainsFile ); cliRequest.request.setUserToolchainsFile( userToolchainsFile ); DefaultToolchainsBuildingRequest toolchainsRequest = new DefaultToolchainsBuildingRequest(); if ( globalToolchainsFile.isFile() ) { toolchainsRequest.setGlobalToolchainsSource( new FileSource( globalToolchainsFile ) ); } if ( userToolchainsFile.isFile() ) { toolchainsRequest.setUserToolchainsSource( new FileSource( userToolchainsFile ) ); } eventSpyDispatcher.onEvent( toolchainsRequest ); slf4jLogger.debug( "Reading global toolchains from " + getLocation( toolchainsRequest.getGlobalToolchainsSource(), globalToolchainsFile ) ); slf4jLogger.debug( "Reading user toolchains from " + getLocation( toolchainsRequest.getUserToolchainsSource(), userToolchainsFile ) ); ToolchainsBuildingResult toolchainsResult = toolchainsBuilder.build( toolchainsRequest ); eventSpyDispatcher.onEvent( toolchainsRequest ); executionRequestPopulator.populateFromToolchains( cliRequest.request, toolchainsResult.getEffectiveToolchains() ); if ( !toolchainsResult.getProblems().isEmpty() && slf4jLogger.isWarnEnabled() ) { slf4jLogger.warn( "" ); slf4jLogger.warn( "Some problems were encountered while building the effective toolchains" ); for ( Problem problem : toolchainsResult.getProblems() ) { slf4jLogger.warn( problem.getMessage() + " @ " + problem.getLocation() ); } slf4jLogger.warn( "" ); } } private Object getLocation( Source source, File defaultLocation ) { if ( source != null ) { return source.getLocation(); } return defaultLocation; } private MavenExecutionRequest populateRequest( CliRequest cliRequest ) { return populateRequest( cliRequest, cliRequest.request ); } private MavenExecutionRequest populateRequest( CliRequest cliRequest, MavenExecutionRequest request ) { CommandLine commandLine = cliRequest.commandLine; String workingDirectory = cliRequest.workingDirectory; boolean quiet = cliRequest.quiet; boolean showErrors = cliRequest.showErrors; String[] deprecatedOptions = { "up", "npu", "cpu", "npr" }; for ( String deprecatedOption : deprecatedOptions ) { if ( commandLine.hasOption( deprecatedOption ) ) { slf4jLogger.warn( "Command line option -" + deprecatedOption + " is deprecated and will be removed in future Maven versions." ); } } // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { request.setInteractiveMode( false ); } boolean noSnapshotUpdates = false; if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) ) { noSnapshotUpdates = true; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @SuppressWarnings( "unchecked" ) List<String> goals = commandLine.getArgList(); boolean recursive = true; // this is the default behavior. String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { request.setOffline( true ); } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( workingDirectory, "" ).getAbsoluteFile(); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List<String> activeProfiles = new ArrayList<>(); List<String> inactiveProfiles = new ArrayList<>(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String[] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( String profileOptionValue : profileOptionValues ) { StringTokenizer profileTokens = new StringTokenizer( profileOptionValue, "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) || profileAction.startsWith( "!" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else { activeProfiles.add( profileAction ); } } } } } TransferListener transferListener; if ( quiet ) { transferListener = new QuietMavenTransferListener(); } else if ( request.isInteractiveMode() && !cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) ) { // // If we're logging to a file then we don't want the console transfer listener as it will spew // download progress all over the place // transferListener = getConsoleTransferListener(); } else { transferListener = getBatchTransferListener(); } ExecutionListener executionListener = new ExecutionEventLogger(); if ( eventSpyDispatcher != null ) { executionListener = eventSpyDispatcher.chainListener( executionListener ); } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } File userToolchainsFile; if ( commandLine.hasOption( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ) { userToolchainsFile = new File( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_TOOLCHAINS ) ); userToolchainsFile = resolveFile( userToolchainsFile, workingDirectory ); } else { userToolchainsFile = MavenCli.DEFAULT_USER_TOOLCHAINS_FILE; } request.setBaseDirectory( baseDirectory ).setGoals( goals ).setSystemProperties( cliRequest.systemProperties ).setUserProperties( cliRequest.userProperties ).setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setShowErrors( showErrors ) // default: false .addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional .setExecutionListener( executionListener ).setTransferListener( transferListener ) // default: batch mode which goes along with interactive .setUpdateSnapshots( updateSnapshots ) // default: false .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false .setGlobalChecksumPolicy( globalChecksumPolicy ) // default: warn .setMultiModuleProjectDirectory( cliRequest.multiModuleProjectDirectory ); if ( alternatePomFile != null ) { File pom = resolveFile( new File( alternatePomFile ), workingDirectory ); if ( pom.isDirectory() ) { pom = new File( pom, "pom.xml" ); } request.setPom( pom ); } else if ( modelProcessor != null ) { File pom = modelProcessor.locatePom( baseDirectory ); if ( pom.isFile() ) { request.setPom( pom ); } } if ( ( request.getPom() != null ) && ( request.getPom().getParentFile() != null ) ) { request.setBaseDirectory( request.getPom().getParentFile() ); } if ( commandLine.hasOption( CLIManager.RESUME_FROM ) ) { request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) ); } if ( commandLine.hasOption( CLIManager.PROJECT_LIST ) ) { String[] projectOptionValues = commandLine.getOptionValues( CLIManager.PROJECT_LIST ); List<String> inclProjects = new ArrayList<>(); List<String> exclProjects = new ArrayList<>(); if ( projectOptionValues != null ) { for ( String projectOptionValue : projectOptionValues ) { StringTokenizer projectTokens = new StringTokenizer( projectOptionValue, "," ); while ( projectTokens.hasMoreTokens() ) { String projectAction = projectTokens.nextToken().trim(); if ( projectAction.startsWith( "-" ) || projectAction.startsWith( "!" ) ) { exclProjects.add( projectAction.substring( 1 ) ); } else if ( projectAction.startsWith( "+" ) ) { inclProjects.add( projectAction.substring( 1 ) ); } else { inclProjects.add( projectAction ); } } } } request.setSelectedProjects( inclProjects ); request.setExcludedProjects( exclProjects ); } if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && !commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_UPSTREAM ); } else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM ); } else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_BOTH ); } String localRepoProperty = request.getUserProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY ); if ( localRepoProperty == null ) { localRepoProperty = request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY ); } if ( localRepoProperty != null ) { request.setLocalRepositoryPath( localRepoProperty ); } request.setCacheNotFound( true ); request.setCacheTransferError( false ); // // Builder, concurrency and parallelism // // We preserve the existing methods for builder selection which is to look for various inputs in the threading // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to // extend the command line to accept its own configuration parameters. // final String threadConfiguration = commandLine.hasOption( CLIManager.THREADS ) ? commandLine.getOptionValue( CLIManager.THREADS ) : request.getSystemProperties().getProperty( MavenCli.THREADS_DEPRECATED ); // TODO: Remove this setting. Note that the int-tests use it if ( threadConfiguration != null ) { // // Default to the standard multithreaded builder // request.setBuilderId( "multithreaded" ); if ( threadConfiguration.contains( "C" ) ) { request.setDegreeOfConcurrency( calculateDegreeOfConcurrencyWithCoreMultiplier( threadConfiguration ) ); } else { request.setDegreeOfConcurrency( Integer.valueOf( threadConfiguration ) ); } } // // Allow the builder to be overriden by the user if requested. The builders are now pluggable. // if ( commandLine.hasOption( CLIManager.BUILDER ) ) { request.setBuilderId( commandLine.getOptionValue( CLIManager.BUILDER ) ); } return request; } int calculateDegreeOfConcurrencyWithCoreMultiplier( String threadConfiguration ) { int procs = Runtime.getRuntime().availableProcessors(); return (int) ( Float.valueOf( threadConfiguration.replace( "C", "" ) ) * procs ); } static File resolveFile( File file, String workingDirectory ) { if ( file == null ) { return null; } else if ( file.isAbsolute() ) { return file; } else if ( file.getPath().startsWith( File.separator ) ) { // drive-relative Windows path return file.getAbsoluteFile(); } else { return new File( workingDirectory, file.getPath() ).getAbsoluteFile(); } } // ---------------------------------------------------------------------- // System properties handling // ---------------------------------------------------------------------- static void populateProperties( CommandLine commandLine, Properties systemProperties, Properties userProperties ) { EnvironmentUtils.addEnvVars( systemProperties ); // ---------------------------------------------------------------------- // Options that are set on the command line become system properties // and therefore are set in the session properties. System properties // are most dominant. // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) ) { String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY ); if ( defStrs != null ) { for ( String defStr : defStrs ) { setCliProperty( defStr, userProperties ); } } } SystemProperties.addSystemProperties( systemProperties ); // ---------------------------------------------------------------------- // Properties containing info about the currently running version of Maven // These override any corresponding properties set on the command line // ---------------------------------------------------------------------- Properties buildProperties = CLIReportingUtils.getBuildProperties(); String mavenVersion = buildProperties.getProperty( CLIReportingUtils.BUILD_VERSION_PROPERTY ); systemProperties.setProperty( "maven.version", mavenVersion ); String mavenBuildVersion = CLIReportingUtils.createMavenVersionString( buildProperties ); systemProperties.setProperty( "maven.build.version", mavenBuildVersion ); } private static void setCliProperty( String property, Properties properties ) { String name; String value; int i = property.indexOf( "=" ); if ( i <= 0 ) { name = property.trim(); value = "true"; } else { name = property.substring( 0, i ).trim(); value = property.substring( i + 1 ); } properties.setProperty( name, value ); // ---------------------------------------------------------------------- // I'm leaving the setting of system properties here as not to break // the SystemPropertyProfileActivator. This won't harm embedding. jvz. // ---------------------------------------------------------------------- System.setProperty( name, value ); } static class ExitException extends Exception { @SuppressWarnings( "checkstyle:visibilitymodifier" ) public int exitCode; public ExitException( int exitCode ) { this.exitCode = exitCode; } } // // Customizations available via the CLI // protected TransferListener getConsoleTransferListener() { return new ConsoleMavenTransferListener( System.out ); } protected TransferListener getBatchTransferListener() { return new Slf4jMavenTransferListener(); } protected void customizeContainer( PlexusContainer container ) { } protected ModelProcessor createModelProcessor( PlexusContainer container ) throws ComponentLookupException { return container.lookup( ModelProcessor.class ); } }
{ "content_hash": "9433d33816349d1260381ca15043899f", "timestamp": "", "source": "github", "line_count": 1591, "max_line_length": 120, "avg_line_length": 36.89943431803897, "alnum_prop": 0.5899296506379137, "repo_name": "dsyer/maven", "id": "034cb004a1f431089de5c66aab15ddbf5b784c30", "size": "59513", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7371" }, { "name": "HTML", "bytes": "2421" }, { "name": "Java", "bytes": "4420831" }, { "name": "Shell", "bytes": "11883" } ], "symlink_target": "" }
from distutils.core import setup setup( name='rq_test1', packages=['rq_test1'], version='0.3.0', description='Simple statistical functions implemented in readable Python.', author='Sherif Soliman', author_email='sherif@ssoliman.com', copyright='Copyright (c) 2016 Sherif Soliman', url='https://github.com/rquirozr/Test-Package2', # download_url='https://github.com/sheriferson/simplestatistics/tarball/0.3.0', keywords=['statistics', 'math'], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Mathematics', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Science/Research', 'Operating System :: MacOS', 'Operating System :: Unix', 'Topic :: Education', 'Topic :: Utilities' ] )
{ "content_hash": "568ecb5a7ce5f9f1ed3661a21f1cec35", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 82, "avg_line_length": 36.07142857142857, "alnum_prop": 0.6108910891089109, "repo_name": "rquirozr/Test-Package2", "id": "9cc7bd9d339432a3e2e9ed3e11c2e4efb6bae1a1", "size": "2920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "31887" } ], "symlink_target": "" }
import { useButton } from '@react-aria/button'; import { useFocus, useHover } from '@react-aria/interactions'; import { mergeProps } from '@react-aria/utils'; import { getStylesObject, mergeRefs } from '@sajari/react-sdk-utils'; import classnames from 'classnames'; import React, { useRef } from 'react'; import Box from '../Box'; import useButtonStyles from './styles'; import { ButtonProps } from './types'; const Button = React.forwardRef((props: ButtonProps, ref?: React.Ref<HTMLElement>) => { const { // TODO: handle the state later as we might need a Spinner/Icon component loading = false, as = 'button', appearance = 'default', size = 'md', spacing = 'default', disabled, fullWidth = false, onClick, children, className, styles: stylesProps, pressedClassName = '', disableDefaultStyles = false, ...rest } = props; const [focused, setFocused] = React.useState(false); const buttonRef = useRef<HTMLElement | null>(null); const ownRef = mergeRefs(buttonRef, ref); const { buttonProps, isPressed: pressed } = useButton( { ...rest, isDisabled: disabled, elementType: as, onPress: onClick }, buttonRef, ); const { hoverProps, isHovered: hovered } = useHover({ isDisabled: disabled, }); const { focusProps } = useFocus({ isDisabled: disabled, onFocus: () => setFocused(true), onBlur: () => setFocused(false), }); const { styles: containerStyles, focusRingProps } = useButtonStyles({ pressed, appearance, disabled, fullWidth, loading, size, spacing, focused, hovered, }); const customProps = mergeProps(buttonProps, focusProps, hoverProps, focusRingProps); const styles = getStylesObject({ container: containerStyles }, disableDefaultStyles); return ( <Box as={as} ref={ownRef} {...customProps} css={[styles.container, stylesProps]} className={classnames(className, { [pressedClassName]: pressed, })} > {children} </Box> ); }); export default Button; export type { ButtonProps };
{ "content_hash": "bcec801d6389d8a770e4588a89991d1a", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 87, "avg_line_length": 26.632911392405063, "alnum_prop": 0.6506653992395437, "repo_name": "sajari/sajari-sdk-react", "id": "3071ebc7508d011b59039981ccc13cbdca933faf", "size": "2104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/components/src/Button/index.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2097" }, { "name": "TypeScript", "bytes": "137586" } ], "symlink_target": "" }
/* * 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 io.prestosql.proxy; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import static io.airlift.configuration.ConfigBinder.configBinder; import static io.airlift.http.client.HttpClientBinder.httpClientBinder; import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder; public class ProxyModule implements Module { @Override public void configure(Binder binder) { httpClientBinder(binder).bindHttpClient("proxy", ForProxy.class); configBinder(binder).bindConfig(ProxyConfig.class); configBinder(binder).bindConfig(JwtHandlerConfig.class, "proxy"); jaxrsBinder(binder).bind(ProxyResource.class); binder.bind(JsonWebTokenHandler.class).in(Scopes.SINGLETON); } }
{ "content_hash": "d1fffdeb485d921648bc697dfc01611a", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 75, "avg_line_length": 34.43589743589744, "alnum_prop": 0.7505584512285927, "repo_name": "sopel39/presto", "id": "71f5eb368366b617a2073e145744b883c5eef771", "size": "1343", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "presto-proxy/src/main/java/io/prestosql/proxy/ProxyModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26917" }, { "name": "CSS", "bytes": "12957" }, { "name": "HTML", "bytes": "28832" }, { "name": "Java", "bytes": "31249883" }, { "name": "JavaScript", "bytes": "211244" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7811" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29857" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
(function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); ed.forcedHighContrastMode = ed.settings.detect_highcontrast && t._isHighContrast(); ed.settings.skin = ed.forcedHighContrastMode ? 'highcontrast' : ed.settings.skin; // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'bottom', theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap", theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "center", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", theme_advanced_font_selector : "span", theme_advanced_show_current_color: 0, readonly : ed.settings.readonly }, ed.settings); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } if (/^\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; if (ed.settings.content_css !== false) ed.contentCSS.push(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css")); // Init editor ed.onInit.add(function() { if (!ed.settings.readonly) { ed.onNodeChange.add(t._nodeChanged, t); ed.onKeyUp.add(t._updateUndoStatus, t); ed.onMouseUp.add(t._updateUndoStatus, t); ed.dom.bind(ed.dom.getRoot(), 'dragend', function() { t._updateUndoStatus(ed); }); } }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, _isHighContrast : function() { var actualColor, div = DOM.add(DOM.getRoot(), 'div', {'style': 'background-color: rgb(171,239,86);'}); actualColor = (DOM.getStyle(div, 'background-color', true) + '').toLowerCase().replace(/ /g, ''); DOM.remove(div); return actualColor != 'rgb(171,239,86)' && actualColor != '#abef56'; }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, ctrl = ed.controlManager.get('styleselect'); if (ctrl.getLength() == 0) { each(ed.dom.getClasses(), function(o, idx) { var name = 'style_' + idx; ed.formatter.register(name, { inline : 'span', attributes : {'class' : o['class']}, selector : '*' }); ctrl.add(o['class'], name); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl; // Setup style select box ctrl = ctrlMan.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(name) { var matches, formatNames = []; each(ctrl.items, function(item) { formatNames.push(item.value); }); ed.focus(); ed.undoManager.add(); // Toggle off the current format matches = ed.formatter.matchAll(formatNames); if (!name || matches[0] == name) { if (matches[0]) ed.formatter.remove(matches[0]); } else ed.formatter.apply(name); ed.undoManager.add(); ed.nodeChanged(); return false; // No auto select } }); // Handle specified format ed.onInit.add(function() { var counter = 0, formats = ed.getParam('style_formats'); if (formats) { each(formats, function(fmt) { var name, keys = 0; each(fmt, function() {keys++;}); if (keys > 1) { name = fmt.name = fmt.name || 'style_' + (counter++); ed.formatter.register(name, fmt); ctrl.add(fmt.title, name); } else ctrl.add(fmt.title); }); } else { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) { var name; if (val) { name = 'style_' + (counter++); ed.formatter.register(name, { inline : 'span', classes : val, selector : '*' }); ctrl.add(t.editor.translate(key), name); } }); } }); // Auto import classes if the ctrl box is empty if (ctrl.getLength() == 0) { ctrl.onPostRender.add(function(ed, n) { if (!ctrl.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return ctrl; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', { title : 'advanced.fontdefault', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { ed.execCommand('FontName', false, cur.value); return; } ed.execCommand('FontName', false, v); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && cur.value == v) { c.select(null); } return false; // No auto select } }); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { cur = cur.value; if (cur['class']) { ed.formatter.toggle('fontsize_class', {value : cur['class']}); ed.undoManager.add(); ed.nodeChanged(); } else { ed.execCommand('FontSize', false, cur.fontSize); } return; } if (v['class']) { ed.focus(); ed.undoManager.add(); ed.formatter.toggle('fontsize_class', {value : v['class']}); ed.undoManager.add(); ed.nodeChanged(); } else ed.execCommand('FontSize', false, v.fontSize); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && (cur.value.fontSize == v.fontSize || cur.value['class'] == v['class'])) { c.select(null); } return false; // No auto select }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', onselect : function(v) { t.editor.execCommand('FormatBlock', false, v); return false; }}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; if (ed.settings) { ed.settings.aria_label = s.aria_label + ed.getLang('advanced.help_shortcut'); } // TODO: ACC Should have an aria-describedby attribute which is user-configurable to describe what this field is actually for. // Maybe actually inherit it from the original textara? n = p = DOM.create('span', {role : 'application', 'aria-labelledby' : ed.id + '_voice', id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '')}); DOM.add(n, 'span', {'class': 'mceVoiceLabel', 'style': 'display:none;', id: ed.id + '_voice'}, s.aria_label); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {role : "presentation", id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = sc.rows; DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return Event.cancel(e); } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; ed.onKeyDown.add(function(ed, evt) { var DOM_VK_F10 = 121, DOM_VK_F11 = 122; if (evt.altKey) { if (evt.keyCode === DOM_VK_F10) { t.toolbarGroup.focus(); return Event.cancel(evt); } else if (evt.keyCode === DOM_VK_F11) { DOM.get(ed.id + '_path_row').focus(); return Event.cancel(evt); } } }); // alt+0 is the UK recommended shortcut for accessing the list of access controls. ed.addShortcut('alt+0', '', 'mceShortcuts', t); return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_ifr'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h, store) { var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'); // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Resize iframe and container DOM.setStyle(e, 'height', ''); DOM.setStyle(ifr, 'height', h); if (s.theme_advanced_resize_horizontal) { DOM.setStyle(e, 'width', ''); DOM.setStyle(ifr, 'width', w); // Make sure that the size is never smaller than the over all ui if (w < e.clientWidth) { w = e.clientWidth; DOM.setStyle(ifr, 'width', e.clientWidth); } } // Store away the size if (store && s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : w, ch : h }); } }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (c.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a, toolbarGroup; toolbarGroup = cf.createToolbarGroup('toolbargroup', { 'name': ed.getLang('advanced.toolbar'), 'tab_focus_toolbar':ed.getParam('theme_advanced_tab_focus_toolbar') }); t.toolbarGroup = toolbarGroup; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr', {role: 'presentation'}), 'td', {'class' : 'mceToolbar ' + a, "role":"presentation"}); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); toolbarGroup.add(tb); o.deltaHeight -= s.theme_advanced_row_height; } h.push(toolbarGroup.renderHTML()); h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row', 'role': 'group', 'aria-labelledby': ed.id + '_path_voice'}); if (s.theme_advanced_path) { DOM.add(n, 'span', {id: ed.id + '_path_voice'}, ed.translate('advanced.path')); DOM.add(n, 'span', {}, ': '); } else { DOM.add(n, 'span', {}, '&#160;'); } if (s.theme_advanced_resizing) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize'}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; t.resizeTo(o.cw, o.ch); }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'click', function(e) { e.preventDefault(); }); Event.add(ed.id + '_resize', 'mousedown', function(e) { var mouseMoveHandler1, mouseMoveHandler2, mouseUpHandler1, mouseUpHandler2, startX, startY, startWidth, startHeight, width, height, ifrElm; function resizeOnMove(e) { e.preventDefault(); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height); }; function endResize(e) { // Stop listening Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1); Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2); Event.remove(DOM.doc, 'mouseup', mouseUpHandler1); Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height, true); }; e.preventDefault(); // Get the current rect size startX = e.screenX; startY = e.screenY; ifrElm = DOM.get(t.editor.id + '_ifr'); startWidth = width = ifrElm.clientWidth; startHeight = height = ifrElm.clientHeight; // Register envent handlers mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove); mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove); mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize); mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize); }); }); } o.deltaHeight -= 21; n = tb = null; }, _updateUndoStatus : function(ed) { var cm = ed.controlManager; cm.setDisabled('undo', !ed.undoManager.hasUndo() && !ed.typing); cm.setDisabled('redo', !ed.undoManager.hasRedo()); }, _nodeChanged : function(ed, cm, n, co, ob) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, fc, bc, formatNames, matches; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); function getParent(name) { var i, parents = ob.parents, func = name; if (typeof(name) == 'string') { func = function(node) { return node.nodeName == name; }; } for (i = 0; i < parents.length; i++) { if (func(parents[i])) return parents[i]; } }; cm.setActive('visualaid', ed.hasVisual); t._updateUndoStatus(ed); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = getParent('A'); if (c = cm.get('link')) { if (!p || !p.name) { c.setDisabled(!p && co); c.setActive(!!p); } } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name); } if (c = cm.get('anchor')) { c.setActive(!co && !!p && p.name); } p = getParent('IMG'); if (c = cm.get('image')) c.setActive(!co && !!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { t._importClasses(); formatNames = []; each(c.items, function(item) { formatNames.push(item.value); }); matches = ed.formatter.matchAll(formatNames); c.select(matches[0]); } if (c = cm.get('formatselect')) { p = getParent(DOM.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } // Find out current fontSize, fontFamily and fontClass getParent(function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; } if (ed.dom.is(n, s.theme_advanced_font_selector)) { if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); if (!fc && n.style.color) fc = n.style.color; if (!bc && n.style.backgroundColor) bc = n.style.backgroundColor; } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } // Select font size if (c = cm.get('fontsizeselect')) { // Use computed style if (s.theme_advanced_runtime_fontsize && !fz && !cl) fz = ed.dom.getStyle(n, 'fontSize', true); c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } } updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } }; updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); if (t.statusKeyboardNavigation) { t.statusKeyboardNavigation.destroy(); t.statusKeyboardNavigation = null; } DOM.setHTML(p, ''); getParent(function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; if (n.getAttribute('data-mce-bogus')) return; // Ignore non element and hidden elements if (n.nodeType != 1 || n.nodeName === 'BR' || (DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved'))) return; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML') na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, '') if (v) { ti += 'class: ' + v + ' '; if (DOM.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", role: 'button', onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.create('span', {'aria-hidden': 'true'}, '\u00a0\u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); if (DOM.select('a', p).length > 0) { t.statusKeyboardNavigation = new tinymce.ui.KeyboardNavigation({ root: ed.id + "_path_row", items: DOM.select('a', p), excludeFromTabOrder: true, onCancel: function() { ed.focus(); } }, DOM); } } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceShortcuts : function() { var ed = this.editor; ed.windowManager.open({ url: this.url + '/shortcuts.htm', width: 480, height: 380, inline: true }, { theme_url: this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : this.url + '/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : this.url + '/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }(tinymce));
{ "content_hash": "77fae43090e12c3b9eafcf6a96fe7b86", "timestamp": "", "source": "github", "line_count": 1352, "max_line_length": 527, "avg_line_length": 27.939349112426036, "alnum_prop": 0.5745486313337216, "repo_name": "a7medelgendy/learn-git", "id": "0564baf9202c3075553eecb26b0970f752208190", "size": "37993", "binary": false, "copies": "39", "ref": "refs/heads/master", "path": "themes/admin/javascript/tinymce/jscripts/tiny_mce/themes/advanced/editor_template_src.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1762554" }, { "name": "PHP", "bytes": "4644262" } ], "symlink_target": "" }
import * as types from '../constants/ActionTypes.js' import * as pageTypes from '../constants/PageTypes.js' function parseSecond(val) { var result = false var tmp = [] var items = location.search.substr(1).split("&") for (var index = 0; index < items.length; index++) { tmp = items[index].split("=") if (tmp[0] === val) result = decodeURIComponent(tmp[1]) } return result } var val = parseSecond('singlePageView') var singlePageView = val === 'true' || val === '1' || val === true const initialState = { page: 'LOADING', loaded: false, loadState: { entry: false, sideBar: false, views: false }, config: ['config.json'], singlePageView: singlePageView, endpoints: { }, customizations: { appName: 'BAUHAUS UI', title: 'BAUHAUS UI', logo: 'media/logo.svg' } } export default function config(state = initialState, action) { switch (action.type) { case types.CONFIG_SET_PAGE: if (pageTypes[action.page] != null) { var newState = Object.assign({}, state) newState.page = action.page return newState } else { return state } case types.CONFIG_REMOVE_FIRST_URL: var newState = Object.assign({}, state) newState.config.shift() return newState case types.CONFIG_LOADED: var newState = Object.assign({}, state) newState.loaded = true //newState.page = pageTypes.LOGIN return newState case types.CONFIG_FATAL_ERROR: var newState = Object.assign({}, state) console.error('Fatal Error:', action.err) newState.page = pageTypes.ERROR return newState case types.CONFIG_LOAD_ERROR: var newState = Object.assign({}, state) newState.page = pageTypes.ERROR return newState case types.CONFIG_ADD_URLS: var newState = Object.assign({}, state) newState.config = newState.config.concat(action.configUrls) return newState case types.CONFIG_SET_ENDPOINTS: var newState = Object.assign({}, state, {}) for (var i in action.endpoints) { newState.endpoints[i] = action.endpoints[i] } return newState case types.CONFIG_SET_CUSTOMIZATIONS: var newState = Object.assign({}, state) newState.customizations = Object.assign({}, newState.customizations, action.customizations) return newState default: return state } }
{ "content_hash": "34e0c050cdafb4fa46e1620f65ac470e", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 97, "avg_line_length": 28.607142857142858, "alnum_prop": 0.636287973366625, "repo_name": "dustin-H/bauhaus-ui", "id": "4ad05df5e8d9fce5c48222d6418f5754d6027059", "size": "2403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/reducers/config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8199" }, { "name": "HTML", "bytes": "1033" }, { "name": "JavaScript", "bytes": "178659" } ], "symlink_target": "" }
package org.hl7.fhir.instance.model.valuesets; // Generated on Tue, Jul 14, 2015 17:35-0400 for FHIR v0.5.0 import org.hl7.fhir.instance.model.EnumFactory; public class CarePlanGoalStatusEnumFactory implements EnumFactory<CarePlanGoalStatus> { public CarePlanGoalStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) return null; if ("in-progress".equals(codeString)) return CarePlanGoalStatus.INPROGRESS; if ("achieved".equals(codeString)) return CarePlanGoalStatus.ACHIEVED; if ("sustaining".equals(codeString)) return CarePlanGoalStatus.SUSTAINING; if ("cancelled".equals(codeString)) return CarePlanGoalStatus.CANCELLED; throw new IllegalArgumentException("Unknown CarePlanGoalStatus code '"+codeString+"'"); } public String toCode(CarePlanGoalStatus code) { if (code == CarePlanGoalStatus.INPROGRESS) return "in-progress"; if (code == CarePlanGoalStatus.ACHIEVED) return "achieved"; if (code == CarePlanGoalStatus.SUSTAINING) return "sustaining"; if (code == CarePlanGoalStatus.CANCELLED) return "cancelled"; return "?"; } }
{ "content_hash": "eb839c6f49363eb174d6dc40e00c449c", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 91, "avg_line_length": 31.275, "alnum_prop": 0.697841726618705, "repo_name": "lcamilo15/hapi-fhir", "id": "04d5e8c10a1a581cd2626f14a37900efbbe6ea55", "size": "2828", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/CarePlanGoalStatusEnumFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "228150" }, { "name": "Eagle", "bytes": "5514957" }, { "name": "HTML", "bytes": "148446" }, { "name": "Java", "bytes": "18948354" }, { "name": "JavaScript", "bytes": "23709" }, { "name": "KiCad", "bytes": "12030" }, { "name": "Ruby", "bytes": "208400" }, { "name": "Shell", "bytes": "5394" } ], "symlink_target": "" }
<?php /** * sfGuardFormSignin for sfGuardAuth signin action * * @package sfDoctrineGuardPlugin * @subpackage form * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: sfGuardFormSignin.class.php 23536 2009-11-02 21:41:21Z Kris.Wallsmith $ */ class sfMooDooFormSignin extends BasesfGuardFormSignin { /** * @see sfForm */ public function configure() { $this->setWidgets(array( 'username' => new sfWidgetFormInputText(), 'password' => new sfWidgetFormInputPassword(array('type' => 'password')), 'remember' => new sfWidgetFormInputCheckbox(), )); $this->setValidators(array( 'username' => new sfValidatorString(), 'password' => new sfValidatorString(), 'remember' => new sfValidatorBoolean(), )); $this->validatorSchema->setPostValidator(new sfGuardValidatorUser()); $this->widgetSchema->setLabel('remember', 'Remember User?'); $this->widgetSchema->setNameFormat('signin[%s]'); } }
{ "content_hash": "51c70659a8ff15da47a68e9320ba51c1", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 96, "avg_line_length": 28.885714285714286, "alnum_prop": 0.6716122650840751, "repo_name": "lauramelos/sfDoctrineMooDooPlugin", "id": "fe67de82550512ce9a913064c4221bc5ada49ece", "size": "1011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/form/sfMooDooFormSignin.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3957" }, { "name": "PHP", "bytes": "168864" }, { "name": "Shell", "bytes": "327" } ], "symlink_target": "" }
package main import ( "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/ghodss/yaml" "github.com/spf13/cobra" "k8s.io/helm/pkg/chartutil" "k8s.io/helm/pkg/lint" "k8s.io/helm/pkg/lint/support" "k8s.io/helm/pkg/strvals" ) var longLintHelp = ` This command takes a path to a chart and runs a series of tests to verify that the chart is well-formed. If the linter encounters things that will cause the chart to fail installation, it will emit [ERROR] messages. If it encounters issues that break with convention or recommendation, it will emit [WARNING] messages. ` type lintCmd struct { valueFiles valueFiles values []string sValues []string fValues []string namespace string strict bool paths []string out io.Writer } func newLintCmd(out io.Writer) *cobra.Command { l := &lintCmd{ paths: []string{"."}, out: out, } cmd := &cobra.Command{ Use: "lint [flags] PATH", Short: "examines a chart for possible issues", Long: longLintHelp, RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { l.paths = args } return l.run() }, } cmd.Flags().VarP(&l.valueFiles, "values", "f", "specify values in a YAML file (can specify multiple)") cmd.Flags().StringArrayVar(&l.values, "set", []string{}, "set values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)") cmd.Flags().StringArrayVar(&l.sValues, "set-string", []string{}, "set STRING values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)") cmd.Flags().StringArrayVar(&l.fValues, "set-file", []string{}, "set values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)") cmd.Flags().StringVar(&l.namespace, "namespace", "default", "namespace to put the release into") cmd.Flags().BoolVar(&l.strict, "strict", false, "fail on lint warnings") return cmd } var errLintNoChart = errors.New("No chart found for linting (missing Chart.yaml)") func (l *lintCmd) run() error { var lowestTolerance int if l.strict { lowestTolerance = support.WarningSev } else { lowestTolerance = support.ErrorSev } // Get the raw values rvals, err := l.vals() if err != nil { return err } var total int var failures int for _, path := range l.paths { if linter, err := lintChart(path, rvals, l.namespace, l.strict); err != nil { fmt.Println("==> Skipping", path) fmt.Println(err) if err == errLintNoChart { failures = failures + 1 } } else { fmt.Println("==> Linting", path) if len(linter.Messages) == 0 { fmt.Println("Lint OK") } for _, msg := range linter.Messages { fmt.Println(msg) } total = total + 1 if linter.HighestSeverity >= lowestTolerance { failures = failures + 1 } } fmt.Println("") } msg := fmt.Sprintf("%d chart(s) linted", total) if failures > 0 { return fmt.Errorf("%s, %d chart(s) failed", msg, failures) } fmt.Fprintf(l.out, "%s, no failures\n", msg) return nil } func lintChart(path string, vals []byte, namespace string, strict bool) (support.Linter, error) { var chartPath string linter := support.Linter{} if strings.HasSuffix(path, ".tgz") { tempDir, err := ioutil.TempDir("", "helm-lint") if err != nil { return linter, err } defer os.RemoveAll(tempDir) file, err := os.Open(path) if err != nil { return linter, err } defer file.Close() if err = chartutil.Expand(tempDir, file); err != nil { return linter, err } lastHyphenIndex := strings.LastIndex(filepath.Base(path), "-") if lastHyphenIndex <= 0 { return linter, fmt.Errorf("unable to parse chart archive %q, missing '-'", filepath.Base(path)) } base := filepath.Base(path)[:lastHyphenIndex] chartPath = filepath.Join(tempDir, base) } else { chartPath = path } // Guard: Error out of this is not a chart. if _, err := os.Stat(filepath.Join(chartPath, "Chart.yaml")); err != nil { return linter, errLintNoChart } return lint.All(chartPath, vals, namespace, strict), nil } // vals merges values from files specified via -f/--values and // directly via --set or --set-string or --set-file, marshaling them to YAML // // This func is implemented intentionally and separately from the `vals` func for the `install` and `upgrade` comammdsn. // Compared to the alternative func, this func lacks the parameters for tls opts - ca key, cert, and ca cert. // That's because this command, `lint`, is explicitly forbidden from making server connections. func (l *lintCmd) vals() ([]byte, error) { base := map[string]interface{}{} // User specified a values files via -f/--values for _, filePath := range l.valueFiles { currentMap := map[string]interface{}{} bytes, err := ioutil.ReadFile(filePath) if err != nil { return []byte{}, err } if err := yaml.Unmarshal(bytes, &currentMap); err != nil { return []byte{}, fmt.Errorf("failed to parse %s: %s", filePath, err) } // Merge with the previous map base = mergeValues(base, currentMap) } // User specified a value via --set for _, value := range l.values { if err := strvals.ParseInto(value, base); err != nil { return []byte{}, fmt.Errorf("failed parsing --set data: %s", err) } } // User specified a value via --set-string for _, value := range l.sValues { if err := strvals.ParseIntoString(value, base); err != nil { return []byte{}, fmt.Errorf("failed parsing --set-string data: %s", err) } } // User specified a value via --set-file for _, value := range l.fValues { reader := func(rs []rune) (interface{}, error) { bytes, err := ioutil.ReadFile(string(rs)) return string(bytes), err } if err := strvals.ParseIntoFile(value, base, reader); err != nil { return []byte{}, fmt.Errorf("failed parsing --set-file data: %s", err) } } return yaml.Marshal(base) }
{ "content_hash": "fb1c509354af9f084f060291daf5d501", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 207, "avg_line_length": 27.863849765258216, "alnum_prop": 0.6668913226621735, "repo_name": "SlickNik/helm", "id": "d0159d34b098ba3f9783bc78bcef7e6f33d0f1b7", "size": "6493", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "cmd/helm/lint.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "770" }, { "name": "Go", "bytes": "1348117" }, { "name": "Makefile", "bytes": "8628" }, { "name": "Shell", "bytes": "63977" }, { "name": "Smarty", "bytes": "793" } ], "symlink_target": "" }
<!-- Copyright 2015 Google 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. --> <animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/tutorial_icon_emanate"> <target android:name="wave1" android:animation="@animator/tutorial_icon_emanate_wave1" /> <target android:name="wave1_path" android:animation="@animator/tutorial_icon_emanate_wave1_path" /> <target android:name="wave2" android:animation="@animator/tutorial_icon_emanate_wave2" /> <target android:name="wave2_path" android:animation="@animator/tutorial_icon_emanate_wave2_path" /> </animated-vector>
{ "content_hash": "85d4ee9ce630a3f01f3a3bdd9b76c1c9", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 75, "avg_line_length": 38.516129032258064, "alnum_prop": 0.711892797319933, "repo_name": "ITVlab/neodash", "id": "a3278f693426841d90487d0849bca65e1bd62b8c", "size": "1194", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "module-muzei/src/main/res/drawable-v21/avd_tutorial_icon_emanate.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1404" }, { "name": "CSS", "bytes": "7726" }, { "name": "HTML", "bytes": "2309" }, { "name": "Java", "bytes": "1572533" }, { "name": "Python", "bytes": "5528" }, { "name": "Shell", "bytes": "1350" } ], "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_25) on Mon Apr 13 12:03:28 EDT 2015 --> <title>Uses of Class io.branch.referral.ServerRequestQueue</title> <meta name="date" content="2015-04-13"> <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 io.branch.referral.ServerRequestQueue"; } } 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="../../../../io/branch/referral/package-summary.html">Package</a></li> <li><a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral">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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?io/branch/referral/class-use/ServerRequestQueue.html" target="_top">Frames</a></li> <li><a href="ServerRequestQueue.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 io.branch.referral.ServerRequestQueue" class="title">Uses of Class<br>io.branch.referral.ServerRequestQueue</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="io.branch.referral"> <!-- --> </a> <h3>Uses of <a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral">ServerRequestQueue</a> in <a href="../../../../io/branch/referral/package-summary.html">io.branch.referral</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../io/branch/referral/package-summary.html">io.branch.referral</a> that return <a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral">ServerRequestQueue</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral">ServerRequestQueue</a></code></td> <td class="colLast"><span class="typeNameLabel">ServerRequestQueue.</span><code><span class="memberNameLink"><a href="../../../../io/branch/referral/ServerRequestQueue.html#getInstance-Context-">getInstance</a></span>(Context&nbsp;c)</code> <div class="block">Singleton method to return the pre-initialised, or newly initialise and return, a singleton object of the type <a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral"><code>ServerRequestQueue</code></a>.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </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="../../../../io/branch/referral/package-summary.html">Package</a></li> <li><a href="../../../../io/branch/referral/ServerRequestQueue.html" title="class in io.branch.referral">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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?io/branch/referral/class-use/ServerRequestQueue.html" target="_top">Frames</a></li> <li><a href="ServerRequestQueue.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 ======= --> </body> </html>
{ "content_hash": "1f6d219adb466e11d74c96bd39ca8ab2", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 297, "avg_line_length": 39.36, "alnum_prop": 0.6417682926829268, "repo_name": "BranchMetrics/Android-Deferred-Deep-Linking-SDK", "id": "ca7226758eab5f56da0ad3f45bd54c86452ad87d", "size": "5904", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Branch-SDK/doc/io/branch/referral/class-use/ServerRequestQueue.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12801" }, { "name": "HTML", "bytes": "1412077" }, { "name": "Java", "bytes": "593821" }, { "name": "JavaScript", "bytes": "827" }, { "name": "Shell", "bytes": "916" } ], "symlink_target": "" }
This is the Play portion of a [benchmarking test suite](../) comparing a variety of web development platforms. ### JSON Encoding Test * [JSON test source](app/controllers/Application.java) ### Data-Store/Database Mapping Test * [Database test controller](app/controllers/Application.java) * [Database test model](app/models/World.java) ## Infrastructure Software Versions The tests were run with: * [Java OpenJDK 1.7](http://openjdk.java.net/) * [Play 2.3.3](http://http://www.playframework.com/) ## Test URLs ### JSON Encoding Test http://localhost/json ### Data-Store/Database Mapping Test http://localhost/db http://localhost/queries?queries=10
{ "content_hash": "183d6fc83f3e3f87b9b14766a1ed6444", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 110, "avg_line_length": 25.26923076923077, "alnum_prop": 0.7397260273972602, "repo_name": "torhve/FrameworkBenchmarks", "id": "1d2b8844f4ba52ed4bae562c6434f8a5b62fe2e9", "size": "682", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "frameworks/Java/play2-java/play2-java-jpa/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "838" }, { "name": "C", "bytes": "39732" }, { "name": "C#", "bytes": "128703" }, { "name": "C++", "bytes": "402630" }, { "name": "CSS", "bytes": "234858" }, { "name": "Clojure", "bytes": "18787" }, { "name": "Dart", "bytes": "35966" }, { "name": "Elixir", "bytes": "1912" }, { "name": "Erlang", "bytes": "7670" }, { "name": "Go", "bytes": "35314" }, { "name": "Groovy", "bytes": "15587" }, { "name": "Haskell", "bytes": "10926" }, { "name": "Java", "bytes": "264212" }, { "name": "JavaScript", "bytes": "395155" }, { "name": "Lua", "bytes": "7477" }, { "name": "MoonScript", "bytes": "2217" }, { "name": "Nimrod", "bytes": "32032" }, { "name": "PHP", "bytes": "17587921" }, { "name": "Perl", "bytes": "18774" }, { "name": "PowerShell", "bytes": "35514" }, { "name": "Prolog", "bytes": "317" }, { "name": "Python", "bytes": "411334" }, { "name": "Racket", "bytes": "5298" }, { "name": "Ruby", "bytes": "73849" }, { "name": "Scala", "bytes": "62267" }, { "name": "Shell", "bytes": "115133" }, { "name": "Volt", "bytes": "677" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Exceptions; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.Firebird; using FluentMigrator.Runner.Processors.MySql; using FluentMigrator.Runner.Processors.Postgres; using FluentMigrator.Runner.Processors.SqlAnywhere; using FluentMigrator.Runner.Processors.SQLite; using FluentMigrator.Runner.Processors.SqlServer; using FluentMigrator.Tests.Integration.Migrations; using FluentMigrator.Tests.Integration.Migrations.Tagged; using FluentMigrator.Tests.Unit; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Integration { [TestFixture] [Category("Integration")] [Obsolete] public class ObsoleteMigrationRunnerTests : ObsoleteIntegrationTestBase { private IRunnerContext _runnerContext; [SetUp] public void SetUp() { _runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = "FluentMigrator.Tests.Integration.Migrations" }; } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRunMigration() { ExecuteWithSupportedProcessors(processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable").ShouldBeTrue(); // This is a hack until MigrationVersionRunner and MigrationRunner are refactored and merged together //processor.CommitTransaction(); runner.Down(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable").ShouldBeFalse(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanSilentlyFail() { try { var processorOptions = new Mock<IMigrationProcessorOptions>(); processorOptions.SetupGet(x => x.PreviewOnly).Returns(false); var processor = new Mock<IMigrationProcessor>(); processor.Setup(x => x.Process(It.IsAny<CreateForeignKeyExpression>())).Throws(new Exception("Error")); processor.Setup(x => x.Process(It.IsAny<DeleteForeignKeyExpression>())).Throws(new Exception("Error")); processor.Setup(x => x.Options).Returns(processorOptions.Object); var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor.Object) { SilentlyFail = true }; runner.Up(new TestForeignKeySilentFailure()); runner.CaughtExceptions.Count.ShouldBeGreaterThan(0); runner.Down(new TestForeignKeySilentFailure()); runner.CaughtExceptions.Count.ShouldBeGreaterThan(0); } finally { ExecuteWithSupportedProcessors(processor => { MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.RollbackToVersion(0); }, false); } } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanApplyForeignKeyConvention() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestForeignKeyNamingConvention()); processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue(); runner.Down(new TestForeignKeyNamingConvention()); processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeFalse(); }, false, typeof(SQLiteProcessor)); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanApplyForeignKeyConventionWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestForeignKeyNamingConventionWithSchema()); processor.ConstraintExists("TestSchema", "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue(); runner.Down(new TestForeignKeyNamingConventionWithSchema()); }, false, new []{typeof(SQLiteProcessor), typeof(FirebirdProcessor)}); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanApplyIndexConvention() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestIndexNamingConvention()); processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); runner.Down(new TestIndexNamingConvention()); processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeFalse(); processor.TableExists(null, "Users").ShouldBeFalse(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanApplyUniqueConvention() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestUniqueConstraintNamingConvention()); processor.ConstraintExists(null, "Users", "UC_Users_GroupId").ShouldBeTrue(); processor.ConstraintExists(null, "Users", "UC_Users_AccountId").ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); runner.Down(new TestUniqueConstraintNamingConvention()); processor.ConstraintExists(null, "Users", "UC_Users_GroupId").ShouldBeFalse(); processor.ConstraintExists(null, "Users", "UC_Users_AccountId").ShouldBeFalse(); processor.TableExists(null, "Users").ShouldBeFalse(); }, false, typeof(SQLiteProcessor)); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanApplyIndexConventionWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestIndexNamingConventionWithSchema()); processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeTrue(); processor.TableExists("TestSchema", "Users").ShouldBeTrue(); runner.Down(new TestIndexNamingConventionWithSchema()); processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeFalse(); processor.TableExists("TestSchema", "Users").ShouldBeFalse(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanCreateAndDropIndex() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Up(new TestCreateAndDropIndexMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropIndexMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); //processor.CommitTransaction(); }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanCreateAndDropIndexWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Up(new TestCreateAndDropIndexMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropIndexMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateSchema()); //processor.CommitTransaction(); }, false, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRenameTable() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeTrue(); runner.Up(new TestRenameTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeFalse(); processor.TableExists(null, "TestTable'3").ShouldBeTrue(); runner.Down(new TestRenameTableMigration()); processor.TableExists(null, "TestTable'3").ShouldBeFalse(); processor.TableExists(null, "TestTable2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeFalse(); //processor.CommitTransaction(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRenameTableWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue(); runner.Up(new TestRenameTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse(); processor.TableExists("TestSchema", "TestTable'3").ShouldBeTrue(); runner.Down(new TestRenameTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable'3").ShouldBeFalse(); processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse(); runner.Down(new TestCreateSchema()); //processor.CommitTransaction(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRenameColumn() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue(); runner.Up(new TestRenameColumnMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse(); processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeTrue(); runner.Down(new TestRenameColumnMigration()); processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeFalse(); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse(); }, true, typeof(SQLiteProcessor)); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRenameColumnWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue(); runner.Up(new TestRenameColumnMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse(); processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeTrue(); runner.Down(new TestRenameColumnMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeFalse(); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse(); runner.Down(new TestCreateSchema()); }, true, typeof(SQLiteProcessor), typeof(FirebirdProcessor)); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanLoadMigrations() { ExecuteWithSupportedProcessors(processor => { var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TestMigration).Namespace, }; var runner = new MigrationRunner(typeof(MigrationRunnerTests).Assembly, runnerContext, processor); //runner.Processor.CommitTransaction(); runner.MigrationLoader.LoadMigrations().ShouldNotBeNull(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanLoadVersion() { ExecuteWithSupportedProcessors(processor => { var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TestMigration).Namespace, }; var runner = new MigrationRunner(typeof(TestMigration).Assembly, runnerContext, processor); //runner.Processor.CommitTransaction(); runner.VersionLoader.VersionInfo.ShouldNotBeNull(); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanRunMigrations() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(2).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(3).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(4).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(5).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(6).ShouldBeTrue(); runner.VersionLoader.VersionInfo.Latest().ShouldBe(6); runner.RollbackToVersion(0, false); }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanMigrateASpecificVersion() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); try { runner.MigrateUp(1, false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); } finally { runner.RollbackToVersion(0, false); } }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanMigrateASpecificVersionDown() { try { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(1, false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.MigrateDown(0, false); testRunner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeFalse(); processor.TableExists(null, "Users").ShouldBeFalse(); }, false, typeof(SQLiteProcessor)); } finally { ExecuteWithSupportedProcessors(processor => { MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.RollbackToVersion(0, false); }, false); } } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void RollbackAllShouldRemoveVersionInfoTable() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(2); processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeTrue(); }); ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.RollbackToVersion(0); processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeFalse(); }); } [Test] [Category("SqlServer2008")] public void MigrateUpWithSqlServerProcessorShouldCommitItsTransaction() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processor = new SqlServerProcessor(new[] { "SqlServer2008" }, connection, new SqlServer2008Generator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(); try { processor.WasCommitted.ShouldBeTrue(); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] [Category("SqlServer2008")] public void MigrateUpSpecificVersionWithSqlServerProcessorShouldCommitItsTransaction() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processor = new SqlServerProcessor(new[] { "SqlServer2008" }, connection, new SqlServer2008Generator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(1); try { processor.WasCommitted.ShouldBeTrue(); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void MigrateUpWithTaggedMigrationsShouldOnlyApplyMatchedMigrations() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TenantATable).Namespace, Tags = new[] { "TenantA" } }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); } finally { runner.RollbackToVersion(0); } }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void MigrateUpWithTaggedMigrationsAndUsingMultipleTagsShouldOnlyApplyMatchedMigrations() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TenantATable).Namespace, Tags = new[] { "TenantA", "TenantB" } }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeFalse(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); } finally { new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0); } }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void MigrateUpWithDifferentTaggedShouldIgnoreConcreteOfTagged() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TenantATable).Namespace, Tags = new[] { "TenantB" } }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeFalse(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeTrue(); } finally { new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0); } }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void MigrateDownWithDifferentTagsToMigrateUpShouldApplyMatchedMigrations() { var assembly = typeof(TenantATable).Assembly; var migrationsNamespace = typeof(TenantATable).Namespace; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = migrationsNamespace, }; // Excluded SqliteProcessor as it errors on DB cleanup (RollbackToVersion). ExecuteWithSupportedProcessors(processor => { try { runnerContext.Tags = new[] { "TenantA" }; new MigrationRunner(assembly, runnerContext, processor).MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); runnerContext.Tags = new[] { "TenantB" }; new MigrationRunner(assembly, runnerContext, processor).MigrateDown(0, false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeFalse(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeFalse(); } finally { runnerContext.Tags = new[] { "TenantA" }; new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0, false); } }, true, typeof(SQLiteProcessor)); } [Test] [Category("SqlServer2008")] public void VersionInfoCreationScriptsOnlyGeneratedOnceInPreviewMode() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processorOptions = new ProcessorOptions { PreviewOnly = true }; var outputSql = new StringWriter(); var announcer = new TextWriterAnnouncer(outputSql){ ShowSql = true }; var processor = new SqlServerProcessor(new[] { "SqlServer2008" }, connection, new SqlServer2008Generator(), announcer, processorOptions, new SqlServerDbFactory()); try { var versionTableMetaData = new TestVersionTableMetaData(); var asm = typeof(MigrationRunnerTests).Assembly; var runnerContext = new RunnerContext(announcer) { Namespace = "FluentMigrator.Tests.Integration.Migrations", PreviewOnly = true }; var runner = new MigrationRunner(new SingleAssembly(asm), runnerContext, processor, versionTableMetaData); runner.MigrateUp(1, false); processor.CommitTransaction(); string schemaName = versionTableMetaData.SchemaName; var schemaAndTableName = string.Format("[{0}].[{1}]", schemaName, TestVersionTableMetaData.TABLE_NAME); var outputSqlString = outputSql.ToString(); var createSchemaMatches = new Regex(Regex.Escape(string.Format("CREATE SCHEMA [{0}]", schemaName))) .Matches(outputSqlString).Count; var createTableMatches = new Regex(Regex.Escape("CREATE TABLE " + schemaAndTableName)) .Matches(outputSqlString).Count; var createIndexMatches = new Regex(Regex.Escape("CREATE UNIQUE CLUSTERED INDEX [" + TestVersionTableMetaData.UNIQUE_INDEX_NAME + "] ON " + schemaAndTableName)) .Matches(outputSqlString).Count; var alterTableMatches = new Regex(Regex.Escape("ALTER TABLE " + schemaAndTableName)) .Matches(outputSqlString).Count; System.Console.WriteLine(outputSqlString); createSchemaMatches.ShouldBe(1); createTableMatches.ShouldBe(1); alterTableMatches.ShouldBe(2); createIndexMatches.ShouldBe(1); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] [Category("Firebird")] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void MigrateUpWithTaggedMigrationsShouldNotApplyAnyMigrationsIfNoTagsParameterIsPassedIntoTheRunner() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(TenantATable).Namespace }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeFalse(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeFalse(); } finally { runner.RollbackToVersion(0); } }); } [Test] [Category("Firebird")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void ValidateVersionOrderShouldDoNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration() { // Using SqlServer instead of SQLite as versions not deleted from VersionInfo table when using Sqlite. var excludedProcessors = new[] { typeof(SQLiteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) }; var assembly = typeof(Migrations.Interleaved.Pass3.User).Assembly; var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace }; var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace }; try { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor); migrationRunner.MigrateUp(3); }, false, excludedProcessors); ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); Assert.DoesNotThrow(migrationRunner.ValidateVersionOrder); }, false, excludedProcessors); } finally { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.RollbackToVersion(0); }, true, excludedProcessors); } } [Test] [Category("Firebird")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void ValidateVersionOrderShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanLatestAppliedMigration() { // Using SqlServer instead of SQLite as versions not deleted from VersionInfo table when using Sqlite. var excludedProcessors = new[] { typeof(MySqlProcessor), typeof(SQLiteProcessor) }; var assembly = typeof(Migrations.Interleaved.Pass3.User).Assembly; var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace }; var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace }; VersionOrderInvalidException caughtException = null; try { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor); migrationRunner.MigrateUp(); }, false, excludedProcessors); ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.ValidateVersionOrder(); }, false, excludedProcessors); } catch (VersionOrderInvalidException ex) { caughtException = ex; } finally { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.RollbackToVersion(0); }, true, excludedProcessors); } caughtException.ShouldNotBeNull(); caughtException.InvalidMigrations.Count().ShouldBe(1); var keyValuePair = caughtException.InvalidMigrations.First(); keyValuePair.Key.ShouldBe(200909060935); keyValuePair.Value.Migration.ShouldBeOfType<Migrations.Interleaved.Pass3.UserEmail>(); } [Test] [Category("SqlServer2016")] public void CanCreateSequence() { if (!IntegrationTestOptions.SqlServer2016.IsEnabled) { Assert.Ignore("No processor found for the given action."); } ExecuteWithSqlServer2016( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSequence()); processor.SequenceExists(null, "TestSequence"); runner.Down(new TestCreateSequence()); processor.SequenceExists(null, "TestSequence").ShouldBeFalse(); }, true, IntegrationTestOptions.SqlServer2016); } [Test] [Category("Postgres")] [Category("SqlServer2012")] public void CanCreateSequenceWithSchema() { if (!IntegrationTestOptions.SqlServer2012.IsEnabled && !IntegrationTestOptions.Postgres.IsEnabled) { Assert.Ignore("No processor found for the given action."); } Action<IMigrationProcessor> action = processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateSequenceWithSchema()); processor.SequenceExists("TestSchema", "TestSequence").ShouldBeTrue(); runner.Down(new TestCreateSequenceWithSchema()); runner.Down(new TestCreateSchema()); processor.SequenceExists("TestSchema", "TestSequence").ShouldBeFalse(); }; if (IntegrationTestOptions.SqlServer2012.IsEnabled) { ExecuteWithSqlServer2012( action, true, IntegrationTestOptions.SqlServer2012); } if (IntegrationTestOptions.Postgres.IsEnabled) { ExecuteWithPostgres(action, true, IntegrationTestOptions.Postgres); } } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanAlterColumnWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); processor.DefaultValueExists("TestSchema", "TestTable", "Name", "Anonymous").ShouldBeTrue(); runner.Up(new TestAlterColumnWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); runner.Down(new TestAlterColumnWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor), typeof(SqlAnywhereProcessor) }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanAlterTableWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse(); runner.Up(new TestAlterTableWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeTrue(); runner.Down(new TestAlterTableWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanAlterTablesSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable").ShouldBeTrue(); runner.Up(new TestAlterSchema()); processor.TableExists("NewSchema", "TestTable").ShouldBeTrue(); runner.Down(new TestAlterSchema()); processor.TableExists("TestSchema", "TestTable").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor), typeof(SqlAnywhereProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanCreateUniqueConstraint() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Up(new TestCreateUniqueConstraint()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraint()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); }, true, typeof(SQLiteProcessor), typeof(SqlAnywhereProcessor)); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanCreateUniqueConstraintWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Up(new TestCreateUniqueConstraintWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor), typeof(SqlAnywhereProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanInsertData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); DataSet ds = processor.ReadTableData(null, "TestTable"); ds.Tables[0].Rows.Count.ShouldBe(1); ds.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanInsertDataWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); DataSet ds = processor.ReadTableData("TestSchema", "TestTable"); ds.Tables[0].Rows.Count.ShouldBe(1); ds.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanUpdateData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestUpdateData()); DataSet upDs = processor.ReadTableData("TestSchema", "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(1); upDs.Tables[0].Rows[0][1].ShouldBe("Updated"); runner.Down(new TestUpdateData()); DataSet downDs = processor.ReadTableData("TestSchema", "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanDeleteData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); runner.Up(new TestDeleteData()); DataSet upDs = processor.ReadTableData(null, "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(0); runner.Down(new TestDeleteData()); DataSet downDs = processor.ReadTableData(null, "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanDeleteDataWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestDeleteDataWithSchema()); DataSet upDs = processor.ReadTableData("TestSchema", "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(0); runner.Down(new TestDeleteDataWithSchema()); DataSet downDs = processor.ReadTableData("TestSchema", "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanReverseCreateIndex() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestCreateIndexWithReversing()); processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeTrue(); runner.Down(new TestCreateIndexWithReversing()); processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanReverseCreateUniqueConstraint() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); runner.Up(new TestCreateUniqueConstraintWithReversing()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithReversing()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor), typeof(SqlAnywhereProcessor) }); } [Test] [Category("Firebird")] [Category("MySql")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] public void CanReverseCreateUniqueConstraintWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestCreateUniqueConstraintWithSchemaWithReversing()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithSchemaWithReversing()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(SqlAnywhereProcessor) }); } [Test] [Category("MySql")] [Category("SQLite")] [Category("Postgres")] [Category("SqlServer2005")] [Category("SqlServer2008")] [Category("SqlServer2012")] [Category("SqlServer2014")] [Category("SqlServer2016")] [Category("SqlAnywhere16")] public void CanExecuteSql() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestExecuteSql()); runner.Down(new TestExecuteSql()); }, true, new[] { typeof(FirebirdProcessor) }); } private static MigrationRunner SetupMigrationRunner(IMigrationProcessor processor) { Assembly asm = typeof(MigrationRunnerTests).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(TestContext.Out)) { Namespace = "FluentMigrator.Tests.Integration.Migrations", AllowBreakingChange = true, }; return new MigrationRunner(asm, runnerContext, processor); } private static void CleanupTestSqlServerDatabase(SqlConnection connection, SqlServerProcessor origProcessor) { if (origProcessor.WasCommitted) { connection.Close(); var dbTypes = new List<string> { origProcessor.DatabaseType }; dbTypes.AddRange(origProcessor.DatabaseTypeAliases); var cleanupProcessor = new SqlServerProcessor(dbTypes, connection, new SqlServer2008Generator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner cleanupRunner = SetupMigrationRunner(cleanupProcessor); cleanupRunner.RollbackToVersion(0); } else { origProcessor.RollbackTransaction(); } } } }
{ "content_hash": "e0a0c7350a4178d33c44acd452b1f8fa", "timestamp": "", "source": "github", "line_count": 1616, "max_line_length": 212, "avg_line_length": 39.63737623762376, "alnum_prop": 0.573734661379461, "repo_name": "igitur/fluentmigrator", "id": "a17ff195b69fcfd85907ddea201d5b4589b6bc94", "size": "64746", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/FluentMigrator.Tests/Integration/ObsoleteMigrationRunnerTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "4300039" }, { "name": "Shell", "bytes": "325" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "58fb94755f51916ad1b08bddefe21037", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "368bd558a3d5591542f04f30a940e840771a7478", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium bolanderi/ Syn. Allium bolanderi stenanthum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import ButtonDropdownComponent from '../lib/button-dropdown-component'; import {expect, beforeEach, describe, it, jest} from '@jest/globals'; import React from 'react'; import {render, cleanup, fireEvent} from '@testing-library/react'; describe('Button Dropdown', function () { let buttonDropdownElement, parentEventHandler; beforeEach(function () { parentEventHandler = jest.fn(); buttonDropdownElement = render( <ButtonDropdownComponent buttonSelected={parentEventHandler} /> ); }); afterEach(function () { jest.resetAllMocks(); cleanup(); }); it('should be a button', function () { expect(buttonDropdownElement.getAllByRole('button')).toHaveLength(1); }); it('should notify a consumer that the button was clicked', function () { expect(parentEventHandler).toHaveBeenCalledTimes(0); fireEvent.click(buttonDropdownElement.getByRole('button')); expect(parentEventHandler).toHaveBeenCalledTimes(1); }); });
{ "content_hash": "1cd0fd7dd5f10c2cd3ab57e23bad6bc4", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 77, "avg_line_length": 29.72222222222222, "alnum_prop": 0.6514018691588785, "repo_name": "zpratt/react-tdd-guide", "id": "88afd315cd6147b5e91dc708384356ee58cf6c96", "size": "1070", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "event-handling/test/button-dropdown.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6526" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>TODO</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'> <link href="css/todo.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="todoApp"> <h1 class="app-title">Todo-list<span>(beta)</span></h1> <form id="addItemForm" class="item-form"> <input type="text" placeholder="Add your item" id="itemName" name="itemName" class="input-text" data-selected-item="" /> </form> <ul id="itemList" class="item-list"></ul> </div> </body> <script type="text/javascript" src="javascript/jquery.min.js"></script> <script type="text/javascript" src="javascript/todoApp.js"></script> <script type="text/javascript" src="javascript/scripts.js"></script> </html>
{ "content_hash": "ca5a91ac0dcf9aa92b75ce6f82205a9c", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 124, "avg_line_length": 32.55555555555556, "alnum_prop": 0.6632536973833902, "repo_name": "iernie/todoapp", "id": "756059be6d8dafbeebac2de185afeea5932802ba", "size": "879", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9061" }, { "name": "JavaScript", "bytes": "96017" } ], "symlink_target": "" }
<?php namespace JavierEguiluz\Bundle\EasyAdminBundle\Tests\Fixtures\AppTestBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class OverridingEasyAdminController extends Controller { /** * @Route("/override_layout", name="override_layout") * * @return Response */ public function overrideLayout() { return $this->render('override_templates/layout.html.twig'); } }
{ "content_hash": "5162c18e1c57e2c80ca55e91d8faf27b", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 87, "avg_line_length": 27.2, "alnum_prop": 0.7426470588235294, "repo_name": "gabiudrescu/EasyAdminBundle", "id": "3f44768dae1951073d7cb15b8081f4bb68fe10bb", "size": "544", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Tests/Fixtures/AppTestBundle/Controller/OverridingEasyAdminController.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "90497" }, { "name": "JavaScript", "bytes": "655" }, { "name": "PHP", "bytes": "299483" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4d4b2cd5e4fb5eaa65ff98fdb2aa0f29", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "846370ff72b4f84408011f79bfe88c2b451263a7", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Lycopodiophyta/Lycopodiopsida/Lycopodiales/Lycopodiaceae/Huperzia/Huperzia polycarpos/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include <grpc/support/port_platform.h> #if !defined(GPR_LINUX) && !defined(GPR_WINDOWS) #include "src/core/lib/security/credentials/alts/check_gcp_environment.h" #include <grpc/support/log.h> bool grpc_alts_is_running_on_gcp() { gpr_log(GPR_ERROR, "Platforms other than Linux and Windows are not supported"); return false; } #endif // !defined(LINUX) && !defined(GPR_WINDOWS)
{ "content_hash": "b615c0dc3aebc14e8c7826d1215255ca", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 73, "avg_line_length": 23.470588235294116, "alnum_prop": 0.7017543859649122, "repo_name": "dslomov/bazel-windows", "id": "d97681b86d29d85688ebfada29d97f1963c2ec08", "size": "1001", "binary": false, "copies": "22", "ref": "refs/heads/master", "path": "third_party/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "48918" }, { "name": "C++", "bytes": "286241" }, { "name": "HTML", "bytes": "16151" }, { "name": "Java", "bytes": "15985177" }, { "name": "Objective-C", "bytes": "5420" }, { "name": "Protocol Buffer", "bytes": "80377" }, { "name": "Python", "bytes": "249909" }, { "name": "Shell", "bytes": "436107" } ], "symlink_target": "" }
namespace blink { struct MarkerPosition; struct PaintInfo; class FloatPoint; class GraphicsContext; class Path; class LayoutSVGResourceMarker; class LayoutSVGShape; class SVGShapePainter { public: SVGShapePainter(LayoutSVGShape& renderSVGShape) : m_renderSVGShape(renderSVGShape) { } void paint(const PaintInfo&); private: void fillShape(GraphicsContext*); void strokeShape(GraphicsContext*); void paintMarkers(const PaintInfo&); void paintMarker(const PaintInfo&, LayoutSVGResourceMarker&, const MarkerPosition&, float); void strokeZeroLengthLineCaps(GraphicsContext*); Path* zeroLengthLinecapPath(const FloatPoint&) const; LayoutSVGShape& m_renderSVGShape; }; } // namespace blink #endif // SVGShapePainter_h
{ "content_hash": "27a7e0fe29d95f62293fdaa0648c96c8", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 95, "avg_line_length": 24.35483870967742, "alnum_prop": 0.7735099337748345, "repo_name": "kurli/blink-crosswalk", "id": "1f2b9b23e2d315136e5fcf15afe6181d4be888fe", "size": "974", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Source/core/paint/SVGShapePainter.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1835" }, { "name": "Assembly", "bytes": "14768" }, { "name": "Batchfile", "bytes": "35" }, { "name": "Bison", "bytes": "64588" }, { "name": "C", "bytes": "124323" }, { "name": "C++", "bytes": "44371388" }, { "name": "CSS", "bytes": "565212" }, { "name": "CoffeeScript", "bytes": "163" }, { "name": "GLSL", "bytes": "11578" }, { "name": "Groff", "bytes": "28067" }, { "name": "HTML", "bytes": "58015328" }, { "name": "Java", "bytes": "109391" }, { "name": "JavaScript", "bytes": "24469331" }, { "name": "Objective-C", "bytes": "47687" }, { "name": "Objective-C++", "bytes": "301733" }, { "name": "PHP", "bytes": "184068" }, { "name": "Perl", "bytes": "585293" }, { "name": "Python", "bytes": "3817314" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "10037" }, { "name": "XSLT", "bytes": "49926" } ], "symlink_target": "" }
Zulip has a cool analytics system for tracking various useful statistics that currently power the `/stats` page, and over time will power other features, like showing usage statistics for the various streams. It is designed around the following goals: - Minimal impact on scalability and service complexity. - Well-tested so that we can count on the results being correct. - Efficient to query so that we can display data in-app (e.g. on the streams page) with minimum impact on the overall performance of those pages. - Storage size smaller than the size of the main Message/UserMessage database tables, so that we can store the data in the main PostgreSQL database rather than using a specialized database platform. There are a few important things you need to understand in order to effectively modify the system. ## Analytics backend overview There are three main components: - models: The UserCount, StreamCount, RealmCount, and InstallationCount tables (analytics/models.py) collect and store time series data. - stat definitions: The CountStat objects in the COUNT_STATS dictionary (analytics/lib/counts.py) define the set of stats Zulip collects. - accounting: The FillState table (analytics/models.py) keeps track of what has been collected for which CountStats. The next several sections will dive into the details of these components. ## The \*Count database tables The Zulip analytics system is built around collecting time series data in a set of database tables. Each of these tables has the following fields: - property: A human readable string uniquely identifying a CountStat object. Example: "active_users:is_bot:hour" or "messages_sent:client:day". - subgroup: Almost all CountStats are further sliced by subgroup. For "active_users:is_bot:day", this column will be False for measurements of humans, and True for measurements of bots. For "messages_sent:client:day", this column is the client_id of the client under consideration. - end_time: A datetime indicating the end of a time interval. It will be on an hour (or UTC day) boundary for stats collected at hourly (or daily) frequency. The time interval is determined by the CountStat. - various "id" fields: Foreign keys into Realm, UserProfile, Stream, or nothing. E.g. the RealmCount table has a foreign key into Realm. - value: The integer counts. For "active_users:is_bot:hour" in the RealmCount table, this is the number of active humans or bots (depending on subgroup) in a particular realm at a particular end_time. For "messages_sent:client:day" in the UserCount table, this is the number of messages sent by a particular user, from a particular client, on the day ending at end_time. There are four tables: UserCount, StreamCount, RealmCount, and InstallationCount. Every CountStat is initially collected into UserCount, StreamCount, or RealmCount. Every stat in UserCount and StreamCount is aggregated into RealmCount, and then all stats are aggregated from RealmCount into InstallationCount. So for example, "messages_sent:client:day" has rows in UserCount corresponding to (user, end_time, client) triples. These are summed to rows in RealmCount corresponding to triples of (realm, end_time, client). And then these are summed to rows in InstallationCount with totals for pairs of (end_time, client). Note: In most cases, we do not store rows with value 0. See [Performance strategy](#performance-strategy) below. ## CountStats CountStats declare what analytics data should be generated and stored. The CountStat class definition and instances live in `analytics/lib/counts.py`. These declarations specify at a high level which tables should be populated by the system and with what data. ## The FillState table The default Zulip production configuration runs a cron job once an hour that updates the \*Count tables for each of the CountStats in the COUNT_STATS dictionary. The FillState table simply keeps track of the last end_time that we successfully updated each stat. It also enables the analytics system to recover from errors (by retrying) and to monitor that the cron job is running and running to completion. ## Performance strategy An important consideration with any analytics system is performance, since it's easy to end up processing a huge amount of data inefficiently and needing a system like Hadoop to manage it. For the built-in analytics in Zulip, we've designed something lightweight and fast that can be available on any Zulip server without any extra dependencies through the carefully designed set of tables in PostgreSQL. This requires some care to avoid making the analytics tables larger than the rest of the Zulip database or adding a ton of computational load, but with careful design, we can make the analytics system very low cost to operate. Also, note that a Zulip application database has 2 huge tables: Message and UserMessage, and everything else is small and thus not performance or space-sensitive, so it's important to optimize how many expensive queries we do against those 2 tables. There are a few important principles that we use to make the system efficient: - Not repeating work to keep things up to date (via FillState) - Storing data in the \*Count tables to avoid our endpoints hitting the core Message/UserMessage tables is key, because some queries could take minutes to calculate. This allows any expensive operations to run offline, and then the endpoints to server data to users can be fast. - Doing expensive operations inside the database, rather than fetching data to Python and then sending it back to the database (which can be far slower if there's a lot of data involved). The Django ORM currently doesn't support the "insert into .. select" type SQL query that's needed for this, which is why we use raw database queries (which we usually avoid in Zulip) rather than the ORM. - Aggregating where possible to avoid unnecessary queries against the Message and UserMessage tables. E.g. rather than querying the Message table both to generate sent message counts for each realm and again for each user, we just query for each user, and then add up the numbers for the users to get the totals for the realm. - Not storing rows when the value is 0. An hourly user stat would otherwise collect 24 \* 365 \* roughly .5MB per db row = 4GB of data per user per year, most of whose values are 0. A related note is to be cautious about adding queries that are typically non-0 instead of being typically 0. ## Backend testing There are a few types of automated tests that are important for this sort of system: - Most important: Tests for the code path that actually populates data into the analytics tables. These are most important, because it can be very expensive to fix bugs in the logic that generates these tables (one basically needs to regenerate all of history for those tables), and these bugs are hard to discover. It's worth taking the time to think about interesting corner cases and add them to the test suite. - Tests for the backend views code logic for extracting data from the database and serving it to clients. For manual backend testing, it sometimes can be valuable to use `./manage.py dbshell` to inspect the tables manually to check that things look right; but usually anything you feel the need to check manually, you should add some sort of assertion for to the backend analytics tests, to make sure it stays that way as we refactor. ## LoggingCountStats The system discussed above is designed primarily around the technical problem of showing useful analytics about things where the raw data is already stored in the database (e.g. Message, UserMessage). This is great because we can always backfill that data to the beginning of time, but of course sometimes one wants to do analytics on things that aren't worth storing every data point for (e.g. activity data, request performance statistics, etc.). There is currently a reference implementation of a "LoggingCountStat" that shows how to handle such a situation. ## Analytics UI development and testing ### Setup and testing The main testing approach for the /stats page UI is manual testing. For most UI testing, you can visit `/stats/realm/analytics` while logged in as Iago (this is the server administrator view of stats for a given realm). The only piece that you can't test here is the "Me" buttons, which won't have any data. For those, you can instead log in as the `shylock@analytics.ds` in the `analytics` realm and visit `/stats` there (which is only a bit more work). Note that the `analytics` realm is a shell with no streams, so you'll only want to use it for testing the graphs. If you're adding a new stat/table, you'll want to edit `analytics/management/commands/populate_analytics_db.py` and add code to generate fake data of the form needed for your new stat/table; you'll then run `./manage.py populate_analytics_db` before looking at the updated graphs. ### Adding or editing /stats graphs The relevant files are: - analytics/views.py: All chart data requests from the /stats page call get_chart_data in this file. The bottom half of this file (with all the raw sql queries) is for a different page (/activity), not related to /stats. - static/js/stats/stats.js: The JavaScript and Plotly code. - templates/analytics/stats.html - static/styles/stats.css and static/styles/portico.css: We are in the process of re-styling this page to use in-app css instead of portico css, but there is currently still a lot of portico influence. - analytics/urls.py: Has the URL routes; it's unlikely you will have to modify this, including for adding a new graph. Most of the code is self-explanatory, and for adding say a new graph, the answer to most questions is to copy what the other graphs do. It is easy when writing this sort of code to have a lot of semi-repeated code blocks (especially in stats.js); it's good to do what you can to reduce this. Tips and tricks: - Use `$.get` to fetch data from the backend. You can grep through stats.js to find examples of this. - The Plotly documentation is at <https://plot.ly/javascript/> (check out the full reference, event reference, and function reference). The documentation pages seem to work better in Chrome than in Firefox, though this hasn't been extensively verified. - Unless a graph has a ton of data, it is typically better to just redraw it when something changes (e.g. in the various aggregation click handlers) rather than to use retrace or relayout or do other complicated things. Performance on the /stats page is nice but not critical, and we've run into a lot of small bugs when trying to use Plotly's retrace/relayout. - There is a way to access raw d3 functionality through Plotly, though it isn't documented well. - 'paper' as a Plotly option refers to the bounding box of the graph (or something related to that). - You can't right click and inspect the elements of a Plotly graph (e.g. the bars in a bar graph) in your browser, since there is an interaction layer on top of it. But if you hunt around the document tree you should be able to find it. ### /activity page - There's a somewhat less developed /activity page, for server administrators, showing data on all the realms on a server. To access it, you need to have the `is_staff` bit set on your UserProfile object. You can set it using `manage.py shell` and editing the UserProfile object directly. A great future project is to clean up that page's data sources, and make this a documented interface.
{ "content_hash": "561fbdddb2a12db1a5f40d628b5a97d7", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 76, "avg_line_length": 51.20704845814978, "alnum_prop": 0.7804542326221611, "repo_name": "zulip/zulip", "id": "fa38bbfae5793d81a8349ce05ad4910eaba4556b", "size": "11637", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "docs/subsystems/analytics.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "509211" }, { "name": "Dockerfile", "bytes": "4219" }, { "name": "Emacs Lisp", "bytes": "157" }, { "name": "HTML", "bytes": "696430" }, { "name": "Handlebars", "bytes": "384277" }, { "name": "JavaScript", "bytes": "4098367" }, { "name": "Perl", "bytes": "10163" }, { "name": "Puppet", "bytes": "112433" }, { "name": "Python", "bytes": "10336945" }, { "name": "Ruby", "bytes": "3166" }, { "name": "Shell", "bytes": "147162" }, { "name": "TypeScript", "bytes": "286785" } ], "symlink_target": "" }
{% extends "base.html" %} {% block content %} <h2>Register</h2> <form action="/accounts/register/" method="post">{% csrf_token %} {{ form }} <input type="submit" value="Register" /> </form> {% endblock content %}
{ "content_hash": "3c4c25fdd623745e9c05e020536f2b96", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 67, "avg_line_length": 19, "alnum_prop": 0.5921052631578947, "repo_name": "pyjosh/djangoprojects", "id": "d90f2858919808b83b6464bcee0eacb59c69a33d", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django_test/templates/register.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "296980" }, { "name": "JavaScript", "bytes": "81690" }, { "name": "Python", "bytes": "32575" } ], "symlink_target": "" }
package com.javapapers.android.androidsmsapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SendSmsActivity extends Activity { Button sendSMSBtn; EditText toPhoneNumberET; EditText smsMessageET; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_sms); sendSMSBtn = (Button) findViewById(R.id.btnSendSMS); toPhoneNumberET = (EditText) findViewById(R.id.editTextPhoneNo); smsMessageET = (EditText) findViewById(R.id.editTextSMS); sendSMSBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { sendSMS(); } }); } protected void sendSMS() { String toPhoneNumber = toPhoneNumberET.getText().toString(); String smsMessage = smsMessageET.getText().toString(); try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(toPhoneNumber, null, smsMessage, null, null); Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Sending SMS failed.", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } public void goToInbox(View view) { Intent intent = new Intent(SendSmsActivity.this, ReceiveSmsActivity.class); startActivity(intent); } }
{ "content_hash": "a2fc77f2d7f7a8d9db8ce3a39ebc3ef5", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 84, "avg_line_length": 35.15384615384615, "alnum_prop": 0.637855579868709, "repo_name": "ricardobaumann/sms_send_receive", "id": "4981df403d64da0d8505aa377b87ee827a3be84c", "size": "1828", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "AndroidSMSApp/app/src/main/java/com/javapapers/android/androidsmsapp/SendSmsActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "9078" } ], "symlink_target": "" }
package org.olat.repository; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.olat.core.CoreSpringFactory; import org.olat.core.gui.components.table.ColumnDescriptor; import org.olat.core.gui.components.table.CustomCellRenderer; import org.olat.core.gui.components.table.CustomRenderColumnDescriptor; import org.olat.core.gui.components.table.DateCellRenderer; import org.olat.core.gui.components.table.DefaultColumnDescriptor; import org.olat.core.gui.components.table.DefaultTableDataModel; import org.olat.core.gui.components.table.StaticColumnDescriptor; import org.olat.core.gui.components.table.TableController; import org.olat.core.gui.translator.PackageTranslator; import org.olat.core.gui.translator.Translator; import org.olat.core.util.StringHelper; import org.olat.login.LoginModule; import org.olat.repository.manager.RepositoryEntryLifecycleDAO; import org.olat.repository.model.RepositoryEntryLifecycle; import org.olat.repository.ui.RepositoryEntryAccessColumnDescriptor; import org.olat.resource.accesscontrol.ACService; import org.olat.resource.accesscontrol.AccessControlModule; import org.olat.resource.accesscontrol.model.OLATResourceAccess; import org.olat.user.UserManager; /** * Initial Date: Mar 31, 2004 * * @author Mike Stock * * Comment: * */ public class RepositoryTableModel extends DefaultTableDataModel<RepositoryEntry> { /** * Identifies a table selection event (outer-left column) */ public static final String TABLE_ACTION_SELECT_LINK = "rtbSelectLink"; /** * Identifies a table launch event (if clicked on an item in the name column). */ public static final String TABLE_ACTION_SELECT_ENTRY = "rtbSelectEntry"; /** * Identifies a multi selection */ public static final String TABLE_ACTION_SELECT_ENTRIES = "rtbSelectEntrIES"; //fxdiff VCRP-1,2: access control of resources private static final int COLUMN_COUNT = 7; private final Translator translator; // package-local to avoid synthetic accessor method. private final ACService acService; private final AccessControlModule acModule; private final RepositoryModule repositoryModule; private final RepositoryEntryLifecycleDAO lifecycleDao; private final UserManager userManager; private final Map<Long,OLATResourceAccess> repoEntriesWithOffer = new HashMap<Long,OLATResourceAccess>();; private final Map<String,String> fullNames = new HashMap<String, String>(); /** * Default constructor. * @param translator */ public RepositoryTableModel(Translator translator) { super(new ArrayList<RepositoryEntry>()); this.translator = translator; acService = CoreSpringFactory.getImpl(ACService.class); acModule = CoreSpringFactory.getImpl(AccessControlModule.class); repositoryModule = CoreSpringFactory.getImpl(RepositoryModule.class); lifecycleDao = CoreSpringFactory.getImpl(RepositoryEntryLifecycleDAO.class); userManager = CoreSpringFactory.getImpl(UserManager.class); } /** * @param tableCtr * @param selectButtonLabel Label of action row or null if no action row should be used * @param enableDirectLaunch * @return the position of the display name column */ public ColumnDescriptor addColumnDescriptors(TableController tableCtr, String selectButtonLabel, boolean enableDirectLaunch) { Locale loc = translator.getLocale(); //fxdiff VCRP-1,2: access control of resources CustomCellRenderer acRenderer = new RepositoryEntryACColumnDescriptor(); tableCtr.addColumnDescriptor(new CustomRenderColumnDescriptor("table.header.ac", RepoCols.ac.ordinal(), null, loc, ColumnDescriptor.ALIGNMENT_LEFT, acRenderer) { @Override public int compareTo(int rowa, int rowb) { Object o1 = table.getTableDataModel().getObject(rowa); Object o2 = table.getTableDataModel().getObject(rowb); if(o1 == null || !(o1 instanceof RepositoryEntry)) return -1; if(o2 == null || !(o2 instanceof RepositoryEntry)) return 1; RepositoryEntry re1 = (RepositoryEntry)o1; RepositoryEntry re2 = (RepositoryEntry)o2; if(re1.isMembersOnly()) { if(!re2.isMembersOnly()) { return 1; } } else if(re2.isMembersOnly()) { return -1; } OLATResourceAccess ac1 = repoEntriesWithOffer.get(re1.getOlatResource().getKey()); OLATResourceAccess ac2 = repoEntriesWithOffer.get(re2.getOlatResource().getKey()); if(ac1 == null && ac2 != null) return -1; if(ac1 != null && ac2 == null) return 1; if(ac1 != null && ac2 != null) return compareAccess(re1, ac1, re2, ac2); return super.compareString(re1.getDisplayname(), re2.getDisplayname()); } private int compareAccess(RepositoryEntry re1, OLATResourceAccess ac1, RepositoryEntry re2, OLATResourceAccess ac2) { int s1 = ac1.getMethods().size(); int s2 = ac2.getMethods().size(); int compare = s1 - s2; if(compare != 0) return compare; if(s1 > 0 && s2 > 0) { String t1 = ac1.getMethods().get(0).getMethod().getType(); String t2 = ac2.getMethods().get(0).getMethod().getType(); int compareType = super.compareString(t1, t2); if(compareType != 0) return compareType; } return super.compareString(re1.getDisplayname(), re2.getDisplayname()); } }); tableCtr.addColumnDescriptor(new RepositoryEntryTypeColumnDescriptor("table.header.typeimg", RepoCols.repoEntry.ordinal(), null, loc, ColumnDescriptor.ALIGNMENT_LEFT)); if(repositoryModule.isManagedRepositoryEntries()) { tableCtr.addColumnDescriptor(false, new DefaultColumnDescriptor("table.header.externalid", RepoCols.externalId.ordinal(), null, loc)); tableCtr.addColumnDescriptor(new DefaultColumnDescriptor("table.header.externalref", RepoCols.externalRef.ordinal(), null, loc)); } boolean lfVisible = lifecycleDao.countPublicLifecycle() > 0; tableCtr.addColumnDescriptor(lfVisible, new DefaultColumnDescriptor("table.header.lifecycle.label", RepoCols.lifecycleLabel.ordinal(), null, loc)); tableCtr.addColumnDescriptor(false, new DefaultColumnDescriptor("table.header.lifecycle.softkey", RepoCols.lifecycleSoftKey.ordinal(), null, loc)); ColumnDescriptor nameColDesc = new DefaultColumnDescriptor("table.header.displayname", RepoCols.displayname.ordinal(), enableDirectLaunch ? TABLE_ACTION_SELECT_ENTRY : null, loc) { @Override public int compareTo(int rowa, int rowb) { Object o1 = table.getTableDataModel().getValueAt(rowa, 1); Object o2 = table.getTableDataModel().getValueAt(rowb, 1); if(o1 == null || !(o1 instanceof RepositoryEntry)) return -1; if(o2 == null || !(o2 instanceof RepositoryEntry)) return 1; RepositoryEntry re1 = (RepositoryEntry)o1; RepositoryEntry re2 = (RepositoryEntry)o2; boolean c1 = RepositoryManager.getInstance().createRepositoryEntryStatus(re1.getStatusCode()).isClosed(); boolean c2 = RepositoryManager.getInstance().createRepositoryEntryStatus(re2.getStatusCode()).isClosed(); int result = (c2 == c1 ? 0 : (c1 ? 1 : -1));//same as Boolean compare if(result == 0) { Object a = table.getTableDataModel().getValueAt(rowa, dataColumn); Object b = table.getTableDataModel().getValueAt(rowb, dataColumn); if(a == null || !(a instanceof String)) return -1; if(b == null || !(b instanceof String)) return 1; String s1 = (String)a; String s2 = (String)b; result = compareString(s1, s2); } return result; } }; tableCtr.addColumnDescriptor(nameColDesc); CustomCellRenderer dateRenderer = new DateCellRenderer(loc); tableCtr.addColumnDescriptor(false, new CustomRenderColumnDescriptor("table.header.lifecycle.start", RepoCols.lifecycleStart.ordinal(), null, loc, ColumnDescriptor.ALIGNMENT_LEFT, dateRenderer)); tableCtr.addColumnDescriptor(false, new CustomRenderColumnDescriptor("table.header.lifecycle.end", RepoCols.lifecycleEnd.ordinal(), null, loc, ColumnDescriptor.ALIGNMENT_LEFT, dateRenderer)); tableCtr.addColumnDescriptor(new DefaultColumnDescriptor("table.header.author", RepoCols.author.ordinal(), null, loc)); CustomCellRenderer accessRenderer = new RepositoryEntryAccessColumnDescriptor(translator); tableCtr.addColumnDescriptor(new CustomRenderColumnDescriptor("table.header.access", RepoCols.repoEntry.ordinal(), null, loc, ColumnDescriptor.ALIGNMENT_LEFT, accessRenderer)); tableCtr.addColumnDescriptor(false, new DefaultColumnDescriptor("table.header.date", RepoCols.creationDate.ordinal(), null, loc)); tableCtr.addColumnDescriptor(false, new DefaultColumnDescriptor("table.header.lastusage", RepoCols.lastUsage.ordinal(), null, loc)); if (selectButtonLabel != null) { StaticColumnDescriptor desc = new StaticColumnDescriptor(TABLE_ACTION_SELECT_LINK, selectButtonLabel, selectButtonLabel); desc.setTranslateHeaderKey(false); tableCtr.addColumnDescriptor(desc); } return nameColDesc; } /** * @see org.olat.core.gui.components.table.TableDataModel#getColumnCount() */ public int getColumnCount() { return COLUMN_COUNT; } /** * @see org.olat.core.gui.components.table.TableDataModel#getValueAt(int, int) */ public Object getValueAt(int row, int col) { RepositoryEntry re = getObject(row); switch (RepoCols.values()[col]) { //fxdiff VCRP-1,2: access control of resources case ac: { if (re.isMembersOnly()) { // members only always show lock icon List<String> types = new ArrayList<String>(1); types.add("b_access_membersonly"); return types; } OLATResourceAccess access = repoEntriesWithOffer.get(re.getOlatResource().getKey()); if(access == null) { return null; } return access; } case repoEntry: return re; case displayname: return getDisplayName(re, translator.getLocale()); case author: return getFullname(re.getInitialAuthor()); case access: { //fxdiff VCRP-1,2: access control of resources if(re.isMembersOnly()) { return translator.translate("table.header.access.membersonly"); } switch (re.getAccess()) { case RepositoryEntry.ACC_OWNERS: return translator.translate("table.header.access.owner"); case RepositoryEntry.ACC_OWNERS_AUTHORS: return translator.translate("table.header.access.author"); case RepositoryEntry.ACC_USERS: return translator.translate("table.header.access.user"); case RepositoryEntry.ACC_USERS_GUESTS: { if(!LoginModule.isGuestLoginLinksEnabled()) { return translator.translate("table.header.access.user"); } return translator.translate("table.header.access.guest"); } default: // OLAT-6272 in case of broken repo entries with no access code // return error instead of nothing return "ERROR"; } } case creationDate: return re.getCreationDate(); case lastUsage: return re.getLastUsage(); case externalId: return re.getExternalId(); case externalRef: return re.getExternalRef(); case lifecycleLabel: { RepositoryEntryLifecycle lf = re.getLifecycle(); if(lf == null || lf.isPrivateCycle()) { return ""; } return lf.getLabel(); } case lifecycleSoftKey: { RepositoryEntryLifecycle lf = re.getLifecycle(); if(lf == null || lf.isPrivateCycle()) { return ""; } return lf.getSoftKey(); } case lifecycleStart: return re.getLifecycle() == null ? null : re.getLifecycle().getValidFrom(); case lifecycleEnd: return re.getLifecycle() == null ? null : re.getLifecycle().getValidTo(); default: return "ERROR"; } } public enum RepoCols { ac, repoEntry, displayname, author, access, creationDate, lastUsage, externalId, externalRef, lifecycleLabel, lifecycleSoftKey, lifecycleStart, lifecycleEnd } @Override //fxdiff VCRP-1,2: access control of resources public void setObjects(List<RepositoryEntry> objects) { super.setObjects(objects); repoEntriesWithOffer.clear(); secondaryInformations(objects); } public void addObject(RepositoryEntry object) { getObjects().add(object); List<RepositoryEntry> objects = Collections.singletonList(object); secondaryInformations(objects); } public void addObjects(List<RepositoryEntry> objects) { getObjects().addAll(objects); secondaryInformations(objects); } private void secondaryInformations(List<RepositoryEntry> repoEntries) { if(repoEntries == null || repoEntries.isEmpty()) return; secondaryInformationsAccessControl(repoEntries); secondaryInformationsUsernames(repoEntries); } private void secondaryInformationsAccessControl(List<RepositoryEntry> repoEntries) { if(repoEntries == null || repoEntries.isEmpty() || !acModule.isEnabled()) return; List<OLATResourceAccess> withOffers = acService.filterRepositoryEntriesWithAC(repoEntries); for(OLATResourceAccess withOffer:withOffers) { repoEntriesWithOffer.put(withOffer.getResource().getKey(), withOffer); } } private void secondaryInformationsUsernames(List<RepositoryEntry> repoEntries) { if(repoEntries == null || repoEntries.isEmpty()) return; Set<String> newNames = new HashSet<String>(); for(RepositoryEntry re:repoEntries) { final String author = re.getInitialAuthor(); if(StringHelper.containsNonWhitespace(author) && !fullNames.containsKey(author)) { newNames.add(author); } } if(!newNames.isEmpty()) { Map<String,String> newFullnames = userManager.getUserDisplayNamesByUserName(newNames); fullNames.putAll(newFullnames); } } public void removeObject(RepositoryEntry object) { getObjects().remove(object); repoEntriesWithOffer.remove(object.getOlatResource().getKey()); } private String getFullname(String author) { if(fullNames.containsKey(author)) { return fullNames.get(author); } return author; } /** * Get displayname of a repository entry. If repository entry a course * and is this course closed then add a prefix to the title. */ private String getDisplayName(RepositoryEntry repositoryEntry, Locale locale) { String displayName = repositoryEntry.getDisplayname(); if (repositoryEntry != null && RepositoryManager.getInstance().createRepositoryEntryStatus(repositoryEntry.getStatusCode()).isClosed()) { PackageTranslator pT = new PackageTranslator(RepositoryEntryStatus.class.getPackage().getName(), locale); displayName = "[" + pT.translate("title.prefix.closed") + "] ".concat(displayName); } return displayName; } public Object createCopyWithEmptyList() { RepositoryTableModel copy = new RepositoryTableModel(translator); return copy; } }
{ "content_hash": "fc482abb0a6cca2ff3dbd8bfb06b9404", "timestamp": "", "source": "github", "line_count": 376, "max_line_length": 182, "avg_line_length": 38.89627659574468, "alnum_prop": 0.7418119658119658, "repo_name": "stevenhva/InfoLearn_OpenOLAT", "id": "e3bdd586db9e8f964f4a2e787f5df1ccfcf98f01", "size": "15621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/olat/repository/RepositoryTableModel.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
local Evaluator = torch.class('Evaluator') --[[ Create a new Evaluator. ]] function Evaluator:__init() end --[[ Run the evaluator on a dataset. Parameters: * `model` - the model to evaluate. * `data` - the `Dataset` to evaluate on. * `saveFile` - optional filename to save the translation. Returns: the evaluation score. ]] function Evaluator:eval(_, _, _) error('Not implemented') end --[[ Return true if the evaluator can save the translation result. ]] function Evaluator:canSaveTranslation() return false end --[[ Compare two scores as returned by the evaluator. Also see `Evaluator.lowerIsBetter` and `Evaluator.higherIsBetter`. Parameters: * `a` - the score to compare. * `b` - the score to compare against. * `delta` - the error margin to tolerate. Returns: `true` if `a` is not worse than `b`, `false` otherwise. ]] function Evaluator:compare(_, _, _) error('Not implemented') end -- Predefine common comparison methods. function Evaluator.lowerIsBetter(a, b, delta) delta = delta or 0 return a - (b - delta) <= 0 end function Evaluator.higherIsBetter(a, b, delta) delta = delta or 0 return a - (b + delta) >= 0 end --[[ Return the name of the evaluation metric. ]] function Evaluator:__tostring__() error('Not implemented') end return Evaluator
{ "content_hash": "9e8450492b2634d7b019887799c80b25", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 69, "avg_line_length": 22, "alnum_prop": 0.6941448382126348, "repo_name": "da03/OpenNMT", "id": "bb58fcade7a405319041d0895fb00cff38842996", "size": "1333", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "onmt/evaluators/Evaluator.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "531609" }, { "name": "Perl", "bytes": "6984" }, { "name": "Python", "bytes": "7142" }, { "name": "Shell", "bytes": "1877" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: cpu/minor/pipeline.cc File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="classes.html"><span>Classes</span></a></li> <li id="current"><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul></div> <h1>cpu/minor/pipeline.cc File Reference</h1><code>#include &lt;algorithm&gt;</code><br> <code>#include &quot;<a class="el" href="minor_2decode_8hh-source.html">cpu/minor/decode.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="execute_8hh-source.html">cpu/minor/execute.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="fetch1_8hh-source.html">cpu/minor/fetch1.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="fetch2_8hh-source.html">cpu/minor/fetch2.hh</a>&quot;</code><br> <code>#include &quot;<a class="el" href="pipeline_8hh-source.html">cpu/minor/pipeline.hh</a>&quot;</code><br> <code>#include &quot;debug/Drain.hh&quot;</code><br> <code>#include &quot;debug/MinorCPU.hh&quot;</code><br> <code>#include &quot;debug/MinorTrace.hh&quot;</code><br> <code>#include &quot;debug/Quiesce.hh&quot;</code><br> <p> <a href="pipeline_8cc-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Namespaces</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">namespace &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceMinor.html">Minor</a></td></tr> </table> <hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:39:08 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
{ "content_hash": "747511c0b35643deb209ff4370f1198a", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 184, "avg_line_length": 51.48148148148148, "alnum_prop": 0.6420863309352518, "repo_name": "wnoc-drexel/gem5-stable", "id": "d2dc8b9ac19cc57d5236a58538201f74348ce676", "size": "2780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/doxygen/html/pipeline_8cc.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "239800" }, { "name": "C", "bytes": "957228" }, { "name": "C++", "bytes": "13915041" }, { "name": "CSS", "bytes": "9813" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Groff", "bytes": "11130043" }, { "name": "HTML", "bytes": "132838214" }, { "name": "Java", "bytes": "3096" }, { "name": "Makefile", "bytes": "20709" }, { "name": "PHP", "bytes": "10107" }, { "name": "Perl", "bytes": "36183" }, { "name": "Protocol Buffer", "bytes": "3246" }, { "name": "Python", "bytes": "3739380" }, { "name": "Shell", "bytes": "49333" }, { "name": "Visual Basic", "bytes": "2884" } ], "symlink_target": "" }
/* * selectable_events.js */ (function( $ ) { module("selectable: events"); test( "start", function() { expect( 2 ); var el = $("#selectable1"); el.selectable({ start: function() { ok( true, "drag fired start callback" ); equal( this, el[0], "context of callback" ); } }); el.simulate( "drag", { dx: 20, dy: 20 }); }); test( "stop", function() { expect( 2 ); var el = $("#selectable1"); el.selectable({ start: function() { ok( true, "drag fired stop callback" ); equal( this, el[0], "context of callback" ); } }); el.simulate( "drag", { dx: 20, dy: 20 }); }); test( "mousedown: initial position of helper", function() { expect( 2 ); var helperOffset, element = $( "#selectable1" ).selectable(), contentToForceScroll = $( "<div>" ).css({ height: "10000px", width: "10000px" }); contentToForceScroll.appendTo( "body" ); $( window ).scrollTop( 100 ).scrollLeft( 100 ); element.simulate( "mousedown", { clientX: 10, clientY: 10 }); // we do a GTE comparison here because IE7 erroneously subtracts // 2 pixels from a simulated mousedown for clientX/Y // Support: IE7 helperOffset = $( ".ui-selectable-helper" ).offset(); ok( helperOffset.top >= 99, "Scroll top should be accounted for." ); ok( helperOffset.left >= 99, "Scroll left should be accounted for." ); // Cleanup element.simulate( "mouseup" ); contentToForceScroll.remove(); $( window ).scrollTop( 0 ).scrollLeft( 0 ); }); })( jQuery );
{ "content_hash": "9c888b9b4dcb9508b8625f88fc5421bf", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 71, "avg_line_length": 22.3768115942029, "alnum_prop": 0.5887305699481865, "repo_name": "Kstro/sepas", "id": "e378ff379c5d1a9b9b8279562682fa474bb3ae55", "size": "1544", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Resources/jquery-ui/tests/unit/selectable/selectable_events.js", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "6994" }, { "name": "CSS", "bytes": "1030107" }, { "name": "HTML", "bytes": "14451422" }, { "name": "JavaScript", "bytes": "5822366" }, { "name": "PHP", "bytes": "3487756" } ], "symlink_target": "" }
package org.apache.hadoop.fs; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import org.junit.Test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; public class TestFileStatus { private static final Log LOG = LogFactory.getLog(TestFileStatus.class); @Test public void testFileStatusWritable() throws Exception { FileStatus[] tests = { new FileStatus(1,false,5,3,4,5,null,"","",new Path("/a/b")), new FileStatus(0,false,1,2,3,new Path("/")), new FileStatus(1,false,5,3,4,5,null,"","",new Path("/a/b")) }; LOG.info("Writing FileStatuses to a ByteArrayOutputStream"); // Writing input list to ByteArrayOutputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutput out = new DataOutputStream(baos); for (FileStatus fs : tests) { fs.write(out); } LOG.info("Creating ByteArrayInputStream object"); DataInput in = new DataInputStream(new ByteArrayInputStream(baos.toByteArray())); LOG.info("Testing if read objects are equal to written ones"); FileStatus dest = new FileStatus(); int iterator = 0; for (FileStatus fs : tests) { dest.readFields(in); assertEquals("Different FileStatuses in iteration " + iterator, dest, fs); iterator++; } } }
{ "content_hash": "472e55949bf13cd73c8272a91bf09579", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 72, "avg_line_length": 29, "alnum_prop": 0.6984326018808777, "repo_name": "mbrtargeting/hadoop-common", "id": "c6622d25890b2806935a01e41713f4f94e64cec7", "size": "2401", "binary": false, "copies": "6", "ref": "refs/heads/trunk", "path": "src/test/core/org/apache/hadoop/fs/TestFileStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "13288" }, { "name": "C", "bytes": "54136" }, { "name": "C++", "bytes": "3319" }, { "name": "CSS", "bytes": "9313" }, { "name": "HTML", "bytes": "68483" }, { "name": "Java", "bytes": "4432015" }, { "name": "Perl", "bytes": "18992" }, { "name": "Python", "bytes": "458381" }, { "name": "Shell", "bytes": "135919" }, { "name": "XSLT", "bytes": "8529" } ], "symlink_target": "" }
@extends(config('sentinel.layout')) {{-- Web site Title --}} @section('title') @parent Create New User @stop {{-- Content --}} @section('content') <div class="row"> <div class="col-md-4 col-md-offset-4"> <form method="POST" action="{{ route('sentinel.users.store') }}" accept-charset="UTF-8"> <h2>Create New User</h2> <div class="form-group {{ ($errors->has('username')) ? 'has-error' : '' }}"> <input class="form-control" placeholder="Username" name="username" type="text" value="{{ Input::old('username') }}"> {{ ($errors->has('username') ? $errors->first('username') : '') }} </div> <div class="form-group {{ ($errors->has('email')) ? 'has-error' : '' }}"> <input class="form-control" placeholder="E-mail" name="email" type="text" value="{{ Input::old('email') }}"> {{ ($errors->has('email') ? $errors->first('email') : '') }} </div> <div class="form-group {{ ($errors->has('password')) ? 'has-error' : '' }}"> <input class="form-control" placeholder="Password" name="password" value="" type="password"> {{ ($errors->has('password') ? $errors->first('password') : '') }} </div> <div class="form-group {{ ($errors->has('password_confirmation')) ? 'has-error' : '' }}"> <input class="form-control" placeholder="Confirm Password" name="password_confirmation" value="" type="password"> {{ ($errors->has('password_confirmation') ? $errors->first('password_confirmation') : '') }} </div> <div class="form-group"> <label class="checkbox"> <input name="activate" value="activate" type="checkbox"> Activate </label> </div> <input name="_token" value="{{ csrf_token() }}" type="hidden"> <input class="btn btn-primary" value="Create" type="submit"> </form> </div> </div> @stop
{ "content_hash": "033759cf110999bda1dbd11db9929de8", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 133, "avg_line_length": 40.07843137254902, "alnum_prop": 0.5181017612524462, "repo_name": "SimplyReactive/petrie", "id": "968d60587f406407249be75d5986a7c0cb67321b", "size": "2044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/sentinel/users/create.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "11269" }, { "name": "JavaScript", "bytes": "14621" }, { "name": "PHP", "bytes": "305225" } ], "symlink_target": "" }
package org.apache.avalon.excalibur.thread.impl; import org.apache.avalon.excalibur.pool.Poolable; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.logger.Logger; import org.apache.excalibur.thread.impl.AbstractThreadPool; import org.apache.excalibur.thread.impl.WorkerThread; /** * This class extends the Thread class to add recyclable functionalities. * * @author <a href="mailto:dev@avalon.apache.org">Avalon Development Team</a> */ class SimpleWorkerThread extends WorkerThread implements Poolable, LogEnabled { /** Log major events like uncaught exceptions and worker creation * and deletion. Stuff that is useful to be able to see over long * periods of time. */ private Logger m_logger; /** * Log minor detail events like */ private Logger m_detailLogger; /** * Allocates a new <code>Worker</code> object. */ protected SimpleWorkerThread( final AbstractThreadPool pool, final ThreadGroup group, final String name ) { super( pool, group, name ); } public void enableLogging( final Logger logger ) { m_logger = logger; m_detailLogger = logger.getChildLogger( "detail" ); // Log a created message here rather as we can't in the constructor // due to the lack of a logger. debug( "created." ); } /** * Used to log major events against the worker. Creation, deletion, * uncaught exceptions etc. * * @param message Message to log. */ protected void debug( final String message ) { if ( m_logger.isDebugEnabled() ) { // As we are dealing with threads where more than one thread is // always involved, log both the name of the thread that triggered // event along with the name of the worker involved. This // increases the likely hood of walking away sane after a // debugging session. m_logger.debug( "\"" + getName() + "\" " + "(in " + Thread.currentThread().getName() + ") : " + message ); } } /** * Used to log major events against the worker. Creation, deletion, * uncaught exceptions etc. * * @param message Message to log. * @param throwable Throwable to log with the message. */ protected void debug( final String message, final Throwable throwable ) { if ( m_logger.isDebugEnabled() ) { m_logger.debug( "\"" + getName() + "\" " + "(in " + Thread.currentThread().getName() + ") : " + message, throwable ); } } /** * Used to log minor events against the worker. Start and stop of * individual pieces of work etc. Separated from the major events * so that they are not lost in a sea of minor events. * * @param message Message to log. */ protected void detailDebug( final String message ) { if ( m_detailLogger.isDebugEnabled() ) { m_detailLogger.debug( "\"" + getName() + "\" " + "(in " + Thread.currentThread().getName() + ") : " + message ); } } /** * Used to log minor events against the worker. Start and stop of * individual pieces of work etc. Separated from the major events * so that they are not lost in a sea of minor events. * * @param message Message to log. * @param throwable Throwable to log with the message. */ protected void detailDebug( final String message, final Throwable throwable ) { if ( m_detailLogger.isDebugEnabled() ) { m_detailLogger.debug( "\"" + getName() + "\" " + "(in " + Thread.currentThread().getName() + ") : " + message, throwable ); } } }
{ "content_hash": "97d3593850e2b87eceae41ed261936ad", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 92, "avg_line_length": 32.75, "alnum_prop": 0.5916030534351145, "repo_name": "eva-xuyen/excalibur", "id": "31da394ef48eff91f52c15398d776d2a3eb95e1f", "size": "4745", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/thread/impl/src/main/java/org/apache/avalon/excalibur/thread/impl/SimpleWorkerThread.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "27094" }, { "name": "Java", "bytes": "5295685" }, { "name": "Shell", "bytes": "41355" } ], "symlink_target": "" }
require 'spec_helper' describe Rex11::Client do before do @client = Rex11::Client.new("the_username", "the_password", "the_web_address") end context "authenticate" do context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("authentication_token_get_request"))).and_return(xml_fixture("authentication_token_get_response_success")) @client.authenticate end end context "response" do context "success" do before do @client.should_receive(:commit).and_return(xml_fixture("authentication_token_get_response_success")) end it "should set auth_token" do @client.authenticate @client.auth_token.should == "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should return true" do @client.authenticate.should be_true end end context "error" do it "should raise error and not set auth_token" do @client.should_receive(:commit).and_return(xml_fixture("authentication_token_get_response_error")) lambda { @client.authenticate }.should raise_error("Failed Authentication due invalid username, password, or endpoint") @client.auth_token.should be_nil end end end end context "add_style" do before do @item = { :style => "the_style", :upc => "the_upc", :size => "the_size", :price => "the_price", :color => "the_color", :description => "the_description" } @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("style_master_product_add_response_success")) @client.should_receive(:require_auth_token) @client.add_style(@item) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("style_master_product_add_request"))).and_return(xml_fixture("style_master_product_add_response_success")) @client.add_style(@item) end end context "response" do context "when success" do it "should return true" do @client.should_receive(:commit).and_return(xml_fixture("style_master_product_add_response_success")) @client.add_style(@item).should == true end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("style_master_product_add_response_error")) lambda { @client.add_style(@item) }.should raise_error("Error 31: COLOR[item 1] is not valid. Error 43: PRICE[item 1] is not valid. Error 31: COLOR[item 2] is not valid. Error 31: COLOR[item 4] is not valid. ") end end end end context "create_pick_ticket" do before do @items = [ {:upc => "the_upc1", :quantity => 1}, {:upc => "the_upc2", :quantity => 2} ] @ship_to_address = {:first_name => "the_ship_to_first_name", :last_name => "the_ship_to_last_name", :company_name => "the_ship_to_company_name", :address1 => "the_ship_to_address1", :address2 => "the_ship_to_address2", :city => "the_ship_to_city", :state => "the_ship_to_state", :zip => "the_ship_to_zip", :country => "the_ship_to_country", :phone => "the_ship_to_phone", :email => "the_ship_to_email" } @pick_ticket_options = { :pick_ticket_id => "23022012012557", :warehouse => "the_warehouse", :payment_terms => "NET", :use_ups_account => "1", :ship_via_account_number => "1AB345", :ship_via => "UPS", :ship_service => "UPS GROUND - Commercial", :billing_option => "PREPAID", :bill_to_address => { :first_name => "the_bill_to_first_name", :last_name => "the_bill_to_last_name", :company_name => "the_bill_to_company_name", :address1 => "the_bill_to_address1", :address2 => "the_bill_to_address2", :city => "the_bill_to_city", :state => "the_bill_to_state", :zip => "the_bill_to_zip", :country => "the_bill_to_country", :phone => "the_bill_to_phone", :email => "the_bill_to_email" } } @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("pick_ticket_add_response_success")) @client.should_receive(:require_auth_token) @client.create_pick_ticket(@items, @ship_to_address, @pick_ticket_options) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("pick_ticket_add_request"))).and_return(xml_fixture("pick_ticket_add_response_success")) @client.create_pick_ticket(@items, @ship_to_address, @pick_ticket_options) end end context "response" do context "when success" do it "should return true" do @client.should_receive(:commit).and_return(xml_fixture("pick_ticket_add_response_success")) @client.create_pick_ticket(@items, @ship_to_address, @pick_ticket_options).should == true end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("pick_ticket_add_response_error")) lambda { @client.create_pick_ticket(@items, @ship_to_address, @pick_ticket_options) }.should raise_error("Error 56: PickTicket/ShipVia is not valid. Error 61: PickTicket/ShipService is not valid. Error 10: State for ShipToAddress is required for USA. ") end end end end context "cancel pick ticket" do before do @pick_ticket_id = "the_pick_ticket_id" @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("cancel_pick_ticket_response_success")) @client.should_receive(:require_auth_token) @client.cancel_pick_ticket(@pick_ticket_id) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("cancel_pick_ticket_request"))).and_return(xml_fixture("cancel_pick_ticket_response_success")) @client.cancel_pick_ticket(@pick_ticket_id) end end context "response" do context "when success" do it "should return hash" do @client.should_receive(:commit).and_return(xml_fixture("cancel_pick_ticket_response_success")) @client.cancel_pick_ticket(@pick_ticket_id).should == true end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("cancel_pick_ticket_response_error")) lambda { @client.cancel_pick_ticket(@pick_ticket_id) }.should raise_error("Error 45: PickTicket can not be cancelled. Error 45: PickTicket does not exist. ") end end end end context "pick_ticket_by_number" do before do @pick_ticket_id = "the_pick_ticket_id" @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("get_pick_ticket_object_by_bar_code_response_success")) @client.should_receive(:require_auth_token) @client.pick_ticket_by_number(@pick_ticket_id) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("get_pick_ticket_object_by_bar_code_request"))).and_return(xml_fixture("get_pick_ticket_object_by_bar_code_response_success")) @client.pick_ticket_by_number(@pick_ticket_id) end end context "response" do context "when success" do it "should return hash" do @client.should_receive(:commit).and_return(xml_fixture("get_pick_ticket_object_by_bar_code_response_success")) @client.pick_ticket_by_number(@pick_ticket_id).should == { :pick_ticket_id => "the_pick_ticket_id", :pick_ticket_status => "the_pick_ticket_status", :pick_ticket_status_code => "the_pick_ticket_status_code", :tracking_number => "the_tracking_number", :shipping_charge => nil } end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("get_pick_ticket_object_by_bar_code_response_error")) lambda { @client.pick_ticket_by_number(@pick_ticket_id) }.should raise_error("Error 83: BarCode doesn't exist. ") end end end end context "create_receiving_ticket" do before do @items = [{:style => "the_style1", :upc => "the_upc1", :size => "the_size1", :color => "the_color1", :description => "the_description1", :quantity => "the_quantity1", :comments => "the_comments1", :shipment_type => "the_shipment_type1" }, {:style => "the_style2", :upc => "the_upc2", :size => "the_size2", :color => "the_color2", :description => "the_description2", :quantity => "the_quantity2", :comments => "the_comments2", :shipment_type => "the_shipment_type2" } ] @receiving_ticket_options = { :warehouse => "the_warehouse", :carrier => "the_carrier", :memo => "the_memo", :supplier => {:company_name => "the_supplier_company_name", :address1 => "the_supplier_address1", :address2 => "the_supplier_address2", :city => "the_supplier_city", :state => "the_supplier_state", :zip => "the_supplier_zip", :country => "the_supplier_country", :phone => "the_supplier_phone", :email => "the_supplier_email" } } @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("receiving_ticket_add_response_success")) @client.should_receive(:require_auth_token) @client.create_receiving_ticket(@items, @receiving_ticket_options) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("receiving_ticket_add_request"))).and_return(xml_fixture("receiving_ticket_add_response_success")) @client.create_receiving_ticket(@items, @receiving_ticket_options) end end context "response" do context "when success" do it "should return the receiving ticket id" do @client.should_receive(:commit).and_return(xml_fixture("receiving_ticket_add_response_success")) @client.create_receiving_ticket(@items, @receiving_ticket_options).should == {:receiving_ticket_id => "the_receiving_ticket_id"} end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("receiving_ticket_add_response_error")) lambda { @client.create_receiving_ticket(@items, @receiving_ticket_options) }.should raise_error("Error 12: ReceivingTicket/SupplierDetails/Country is not valid. Error 32: ReceivingTicket/Shipmentitemslist/Size[item 1] is not valid. ") end end end end context "receiving_ticket_by_receiving_ticket_id" do before do @receiving_ticket_id = "the_receiving_ticket_id" @items = [{:style => "the_style1", :upc => "the_upc1", :size => "the_size1", :color => "the_color1", :description => "the_description1", :quantity => "the_quantity1", :comments => "the_comments1", :shipment_type => "the_shipment_type1" }, {:style => "the_style2", :upc => "the_upc2", :size => "the_size2", :color => "the_color2", :description => "the_description2", :quantity => "the_quantity2", :comments => "the_comments2", :shipment_type => "the_shipment_type2" } ] @receiving_ticket_options = { :warehouse => "the_warehouse", :carrier => "the_carrier", :memo => "the_memo", :supplier => {:company_name => "the_supplier_company_name", :address1 => "the_supplier_address1", :address2 => "the_supplier_address2", :city => "the_supplier_city", :state => "the_supplier_state", :zip => "the_supplier_zip", :country => "the_supplier_country", :phone => "the_supplier_phone", :email => "the_supplier_email" } } @client.auth_token = "4vxVebc3D1zwsXjH9fkFpgpOhewauJbVu25WXjQ1gOo=" end it "should require_auth_token" do @client.should_receive(:commit).and_return(xml_fixture("get_receiving_ticket_object_by_ticket_number_response_success")) @client.should_receive(:require_auth_token) @client.receiving_ticket_by_receiving_ticket_id(@receiving_ticket_id) end context "request" do it "should form correct request" do @client.should_receive(:commit).with(squeeze_xml(xml_fixture("get_receiving_ticket_object_by_ticket_number_request"))).and_return(xml_fixture("get_receiving_ticket_object_by_ticket_number_response_success")) @client.receiving_ticket_by_receiving_ticket_id(@receiving_ticket_id) end end context "response" do context "when success" do it "should return the receiving ticket id" do @client.should_receive(:commit).and_return(xml_fixture("get_receiving_ticket_object_by_ticket_number_response_success")) @client.receiving_ticket_by_receiving_ticket_id(@receiving_ticket_id).should == { :receiving_ticket_status=>"the_receiving_status1", :receiving_ticket_status_code=>"the_receiving_status_code1", :items => [ {:style=>"the_style1", :upc=>"the_upc1", :size => "the_size1", :color => "the_color1", :description => "the_description1", :quantity => "the_quantity1", :comments => "the_comments1", :shipment_type => "the_shipment_type1" }, {:style=>"the_style2", :upc=>"the_upc2", :size => "the_size2", :color => "the_color2", :description => "the_description2", :quantity => "the_quantity2", :comments => "the_comments2", :shipment_type => "the_shipment_type2" } ] } end end context "when error" do it "should raise error" do @client.should_receive(:commit).and_return(xml_fixture("get_receiving_ticket_object_by_ticket_number_response_error")) lambda { @client.receiving_ticket_by_receiving_ticket_id(@receiving_ticket_id) }.should raise_error("Error 41: Invalid ASN Ticket number. ") end end end end context "require_auth_token" do it "should raise error if auth_token is not set" do lambda { @client.send("require_auth_token") }.should raise_error("Authentication required for api call") end it "should not raise error if auth_token is set" do @client.auth_token = "something" lambda { @client.send("require_auth_token") }.should_not raise_error end end end
{ "content_hash": "b775a4bdb5d49ed529ca9b29c187de46", "timestamp": "", "source": "github", "line_count": 439, "max_line_length": 215, "avg_line_length": 38.569476082004556, "alnum_prop": 0.5726435152374203, "repo_name": "calicoder/rex11", "id": "97cd495287707b78158c8976bcf666b35acf52d9", "size": "16932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/lib/client_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "41378" } ], "symlink_target": "" }
SelectedKeywordView::SelectedKeywordView(const gfx::FontList& font_list, SkColor text_color, SkColor parent_background_color, Profile* profile) : IconLabelBubbleView(0, font_list, parent_background_color, false), text_color_(text_color), profile_(profile) { static const int kBackgroundImages[] = IMAGE_GRID(IDR_OMNIBOX_SELECTED_KEYWORD_BUBBLE); SetBackgroundImageGrid(kBackgroundImages); full_label_.SetFontList(font_list); full_label_.SetVisible(false); partial_label_.SetFontList(font_list); partial_label_.SetVisible(false); } SelectedKeywordView::~SelectedKeywordView() { } void SelectedKeywordView::ResetImage() { if (ui::MaterialDesignController::IsModeMaterial()) { SetImage(gfx::CreateVectorIcon(gfx::VectorIconId::OMNIBOX_SEARCH, 16, GetTextColor())); } else { SetImage(*GetThemeProvider()->GetImageSkiaNamed(IDR_OMNIBOX_SEARCH)); } } SkColor SelectedKeywordView::GetTextColor() const { if (!ui::MaterialDesignController::IsModeMaterial()) return text_color_; return GetNativeTheme()->GetSystemColor( color_utils::IsDark(GetParentBackgroundColor()) ? ui::NativeTheme::kColorId_TextfieldDefaultColor : ui::NativeTheme::kColorId_LinkEnabled); } SkColor SelectedKeywordView::GetBorderColor() const { DCHECK(ui::MaterialDesignController::IsModeMaterial()); return GetTextColor(); } gfx::Size SelectedKeywordView::GetPreferredSize() const { // Height will be ignored by the LocationBarView. return GetSizeForLabelWidth(full_label_.GetPreferredSize().width()); } gfx::Size SelectedKeywordView::GetMinimumSize() const { // Height will be ignored by the LocationBarView. return GetSizeForLabelWidth(partial_label_.GetMinimumSize().width()); } void SelectedKeywordView::Layout() { SetLabel(((width() == GetPreferredSize().width()) ? full_label_ : partial_label_).text()); IconLabelBubbleView::Layout(); } void SelectedKeywordView::SetKeyword(const base::string16& keyword) { keyword_ = keyword; if (keyword.empty()) return; DCHECK(profile_); TemplateURLService* model = TemplateURLServiceFactory::GetForProfile(profile_); if (!model) return; bool is_extension_keyword; const base::string16 short_name = model->GetKeywordShortName(keyword, &is_extension_keyword); int keyword_text_id = ui::MaterialDesignController::IsModeMaterial() ? IDS_OMNIBOX_KEYWORD_TEXT_MD : IDS_OMNIBOX_KEYWORD_TEXT; const base::string16 full_name = is_extension_keyword ? short_name : l10n_util::GetStringFUTF16( keyword_text_id, short_name); full_label_.SetText(full_name); const base::string16 min_string( location_bar_util::CalculateMinString(short_name)); const base::string16 partial_name = is_extension_keyword ? min_string : l10n_util::GetStringFUTF16( keyword_text_id, min_string); partial_label_.SetText(min_string.empty() ? full_label_.text() : partial_name); } const char* SelectedKeywordView::GetClassName() const { return "SelectedKeywordView"; }
{ "content_hash": "06719f0662ee49fe55604c4221c84908", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 75, "avg_line_length": 36.17204301075269, "alnum_prop": 0.6599286563614745, "repo_name": "danakj/chromium", "id": "f4bfc648e59c2a6fb1e472c1f95a222f37b11b1d", "size": "4467", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chrome/browser/ui/views/location_bar/selected_keyword_view.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php declare(strict_types=1); namespace Sylius\Bundle\ThemeBundle\Form\Type; use Sylius\Bundle\ThemeBundle\Repository\ThemeRepositoryInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * @author Kamil Kokot <kamil@kokot.me> */ final class ThemeNameChoiceType extends AbstractType { /** * @var ThemeRepositoryInterface */ private $themeRepository; /** * @param ThemeRepositoryInterface $themeRepository */ public function __construct(ThemeRepositoryInterface $themeRepository) { $this->themeRepository = $themeRepository; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'choices' => function (Options $options): array { $themes = $this->themeRepository->findAll(); $choices = []; foreach ($themes as $theme) { $choices[(string) $theme] = $theme->getName(); } return $choices; }, ]); } /** * {@inheritdoc} */ public function getParent(): string { return ChoiceType::class; } /** * {@inheritdoc} */ public function getBlockPrefix(): string { return 'sylius_theme_name_choice'; } }
{ "content_hash": "67451f9689b334e75616b1269c6cb36c", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 74, "avg_line_length": 22.597014925373134, "alnum_prop": 0.6043593130779392, "repo_name": "CoderMaggie/Sylius", "id": "aba5366a443b22c19ccfa1beeec396478c3bdeba", "size": "1725", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/Sylius/Bundle/ThemeBundle/Form/Type/ThemeNameChoiceType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "601" }, { "name": "CSS", "bytes": "2150" }, { "name": "Gherkin", "bytes": "791528" }, { "name": "HTML", "bytes": "303779" }, { "name": "JavaScript", "bytes": "71083" }, { "name": "PHP", "bytes": "6713464" }, { "name": "Shell", "bytes": "28860" } ], "symlink_target": "" }
/* @flow strict */ import React from 'react'; import { render } from '@testing-library/react'; import BpkTable from './BpkTable'; describe('BpkTable', () => { it('should render correctly', () => { const { asFragment } = render( <BpkTable> <tbody /> </BpkTable>, ); expect(asFragment()).toMatchSnapshot(); }); it('should render correctly with "alternate" attribute', () => { const { asFragment } = render( <BpkTable alternate> <tbody /> </BpkTable>, ); expect(asFragment()).toMatchSnapshot(); }); it('should render correctly with custom class', () => { const { asFragment } = render( <BpkTable className="my-table"> <tbody /> </BpkTable>, ); expect(asFragment()).toMatchSnapshot(); }); });
{ "content_hash": "140f616b04c1a98395c199c632f591b9", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 66, "avg_line_length": 21.72972972972973, "alnum_prop": 0.568407960199005, "repo_name": "Skyscanner/backpack", "id": "930e7ec2ea63ffd1c6c7390201e2c2b6920961f4", "size": "1443", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "packages/bpk-component-table/src/BpkTable-test.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "102246" }, { "name": "HTML", "bytes": "470" }, { "name": "JavaScript", "bytes": "1482027" }, { "name": "SCSS", "bytes": "171448" }, { "name": "Shell", "bytes": "5084" } ], "symlink_target": "" }
"""Provide the device automations for Vacuum.""" from typing import Dict, List import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, CONF_CONDITION, CONF_DOMAIN, CONF_TYPE, CONF_DEVICE_ID, CONF_ENTITY_ID, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import condition, config_validation as cv, entity_registry from homeassistant.helpers.typing import ConfigType, TemplateVarsType from homeassistant.helpers.config_validation import DEVICE_CONDITION_BASE_SCHEMA from . import DOMAIN, STATE_DOCKED, STATE_CLEANING, STATE_RETURNING CONDITION_TYPES = {"is_cleaning", "is_docked"} CONDITION_SCHEMA = DEVICE_CONDITION_BASE_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Required(CONF_TYPE): vol.In(CONDITION_TYPES), } ) async def async_get_conditions( hass: HomeAssistant, device_id: str ) -> List[Dict[str, str]]: """List device conditions for Vacuum devices.""" registry = await entity_registry.async_get_registry(hass) conditions = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_cleaning", } ) conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_docked", } ) return conditions def async_condition_from_config( config: ConfigType, config_validation: bool ) -> condition.ConditionCheckerType: """Create a function to test a device condition.""" if config_validation: config = CONDITION_SCHEMA(config) if config[CONF_TYPE] == "is_docked": test_states = [STATE_DOCKED] else: test_states = [STATE_CLEANING, STATE_RETURNING] def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if an entity is a certain state.""" state = hass.states.get(config[ATTR_ENTITY_ID]) return state is not None and state.state in test_states return test_is_state
{ "content_hash": "3d8db337ab42c3c9c7736145281e4ae3", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 85, "avg_line_length": 31.734177215189874, "alnum_prop": 0.6402074192261668, "repo_name": "joopert/home-assistant", "id": "6a41fe0490e13e79fa78f65ecd8988dd1792c9c6", "size": "2507", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "homeassistant/components/vacuum/device_condition.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "18670593" }, { "name": "Shell", "bytes": "6846" } ], "symlink_target": "" }
/** * \file * \brief contains definitions, macroses and function prototypes */ #pragma once #include <stdint.h> #define LED_1 LATGbits.LATG6 #define LED_2 LATDbits.LATD4 #define LED_3 LATBbits.LATB11 #define LED_4 LATGbits.LATG15 #define BTN_1 PORTAbits.RA5 #define BTN_2 PORTAbits.RA4 #define BTN_4_SCHLD PORTAbits.RA2 #define BTN_3_SCHLD PORTFbits.RF1 #define BTN_2_SCHLD PORTDbits.RD5 #define BTN_1_SCHLD PORTAbits.RA3 typedef enum states { RESET = 0, START, PAUSE } STATES; void DelayMs(int t); void delay(volatile uint32_t val); void init_app(void); void shift_str(uint8_t *str); volatile uint32_t cur_state_g; uint8_t msg_g[120] = "test msg "; extern uint32_t delay_g;
{ "content_hash": "52d4cc6ad703ec1d5ea6d682fc3b29be", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 65, "avg_line_length": 19.243243243243242, "alnum_prop": 0.7120786516853933, "repo_name": "kpi-keoa/TheConnectedMCU_Labs", "id": "d30ecd12def9fedf6b53a978f6941af0609daab2", "size": "712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mxdz/lab4_uart_spi/src/scrolling_text.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "408719" }, { "name": "Batchfile", "bytes": "5416" }, { "name": "C", "bytes": "2348811" }, { "name": "C++", "bytes": "158600" }, { "name": "CSS", "bytes": "373324" }, { "name": "HTML", "bytes": "2948072" }, { "name": "JavaScript", "bytes": "645545" }, { "name": "Makefile", "bytes": "894698" }, { "name": "Shell", "bytes": "30223" }, { "name": "TeX", "bytes": "1535934" } ], "symlink_target": "" }
_lcl_component(nntagging, "nntagging", "lib/NNTagging")
{ "content_hash": "5ac104f3f9c11bd521ee1ca2a18865b4", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 55, "avg_line_length": 28.5, "alnum_prop": 0.7368421052631579, "repo_name": "nudge-nudge/punakea", "id": "f4a3b8f4226da5401b8395074494cde7b206bac9", "size": "2346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Subprojects/NNTagging/Source/lcl_config_components.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "34167" }, { "name": "C++", "bytes": "61266" }, { "name": "Objective-C", "bytes": "1875833" }, { "name": "Python", "bytes": "1092" }, { "name": "Rebol", "bytes": "13727" }, { "name": "Ruby", "bytes": "220" }, { "name": "Shell", "bytes": "3561" } ], "symlink_target": "" }
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; const { Route } = Ember; export default Route.extend(AuthenticatedRouteMixin, { setupController(controller){ controller.get('searchForUsers').perform(); }, queryParams: { query: { replace: true }, searchTerms: { replace: true } } });
{ "content_hash": "4775aa570497004ebdcfb917efb0f871", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 89, "avg_line_length": 21.833333333333332, "alnum_prop": 0.6793893129770993, "repo_name": "stopfstedt/frontend", "id": "8aea83ed819a4f4f32ac603382a14743cdc67b30", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/routes/users.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "109569" }, { "name": "HTML", "bytes": "374852" }, { "name": "JavaScript", "bytes": "1622254" } ], "symlink_target": "" }
angular.module('CardTest', []) .factory('Hammer', function() { return { new: function(element, options) { return new Hammer(element, options); } } }) .factory('ImgurGrabber', function($http) { var images = []; var i = $http.get('images.json').then(function(result) { images = result.data.sort(function() { return Math.random() * 2 - 1; }); }); var index = 0; var increment = 6; return { images: i, next: function() { index += increment; return images.slice(index - increment, index); } }; }) .controller('MainCtrl', function($scope, ImgurGrabber) { $scope.next = function() { $scope.$broadcast('load next'); } }) .directive('stack', function(ImgurGrabber) { return { restrict: 'EA', template: '<card ng-repeat="card in cards" image="card" offset="cards.length - $index"></card>', controller: function($scope) { ImgurGrabber.images.then(function() { $scope.cards = ImgurGrabber.next(); }) $scope.$on('load next', function() { $scope.cards = ImgurGrabber.next(); }); $scope.$on('delete card', function() { $scope.$apply(function() { if ($scope.cards.length > 1) { $scope.cards.pop(); } else { $scope.cards = ImgurGrabber.next(); } }); }) } } }) .directive('card', function(Hammer) { return { restrict: 'E', scope: { card: '=image', offset: '=offset' }, link: function(scope, element, attrs) { var DRAG_SENSITIVITY = 2; var image = new Image(); image.onload = function() { scope.width = image.width; scope.height = image.height; if (scope.width > scope.height) { // Minus 2 for the border scope.ratio = (element[0].clientHeight - 2) / scope.height; } else { scope.ratio = (element[0].clientWidth - 2) / scope.width; } DRAG_SENSITIVITY *= scope.ratio; scope.hspace = Math.max((scope.width - scope.height) / 2, 0) * scope.ratio; scope.vspace = Math.max((scope.height - scope.width) / 2, 0) * scope.ratio; } image.src = scope.card; var startCoords = { x: 0, y: 0 } var lastCoords = { x: 0, y: 0 }; var listeners = []; element.css('background-image', 'url(' + scope.card + ')'); scope.$watch(function() { return scope.offset }, function(newVal, oldVal) { if (scope.offset == '1') { listeners.forEach(function(n) { n(); }) var touch = Hammer.new(element[0]); touch.on('panstart', function(e) { //startCoords = getCoords(); element.css('transition', ''); }) touch.on('panend', function(e) { var coords = getCoords(); scope.$parent.$parent.$broadcast('panend', coords); if ( (e.velocityX * e.deltaX < 0 && ( Math.abs(e.velocityX) > .5 || Math.abs(e.deltaX) > (window.innerWidth / 2) )) || Math.abs(e.velocityX) > 1.75 ) { element.css('transition', 'all 300ms ease'); // var xSign = Math.abs(e.deltaX) / e.deltaX; var ySign = Math.abs(e.deltaY) / e.deltaY; var xVel = Math.abs(e.velocityX) / e.velocityX; console.log('xVel', xVel) translate3d({ x: -xVel * window.innerWidth, y: -e.velocityY * window.innerHeight / 2 }, null, true) setTimeout(function() { scope.$emit('delete card', null); }, 300) } else { element.css('background-position', 'center center'); element.css('transition', 'all 300ms ease'); spring(null, null, true); } // scope.$parent.$parent.$broadcast('panend', coords); }); touch.on('pan', function(e) { // Parallax panning of bg-image var vdrift = -scope.vspace; var hdrift = -scope.hspace; if (scope.hspace > 0) { if (e.deltaX < 0) { hdrift = Math.round(Math.max(e.deltaX * DRAG_SENSITIVITY * (scope.hspace / window.innerWidth), -scope.hspace) - scope.hspace); } else { hdrift = Math.round(Math.min(e.deltaX * DRAG_SENSITIVITY * (scope.hspace / window.innerWidth), scope.hspace) - scope.hspace); } } if (scope.vspace > 0) { if (e.deltaY < 0) { vdrift = Math.round(Math.max(e.deltaY * DRAG_SENSITIVITY * (scope.vspace / window.innerHeight), -scope.vspace) - scope.vspace); } else { vdrift = Math.round(Math.min(e.deltaY * DRAG_SENSITIVITY * (scope.vspace / window.innerHeight), scope.vspace) - scope.vspace); } } element.css('background-position', hdrift + 'px ' + vdrift + 'px'); translate3d({ x: e.deltaX, y: e.deltaY }); }); } else { var startCoords = getCoords(); listeners.push(scope.$on('translate', function(event, data) { element.css('transition', ''); translate3d({ x: data[0].x / Math.pow(scope.offset, 1.5), y: data[0].y / Math.pow(scope.offset, 1.5) }, data[1], true); })) listeners.push(scope.$on('panend', function(event, data) { element.css('transition', 'all 300ms ease'); spring(data, null, true); })); } }) function translate3d(coords, start, broadcast) { var start = isNull(start, startCoords); var c = [ start.x + coords.x, start.y + coords.y, 0, ].join('px, ') + 'px'; element.css('transform', 'translate3d(' + c + ')'); if (!broadcast) scope.$parent.$parent.$broadcast('translate', [coords, start]); } var DAMPING = .44; var TIMESCALE = .88; function spring(coords, start, broadcast) { var time = Math.pow(Math.max(isNull(time, 350), 16), TIMESCALE); element.css('transition', 'all ' + time + 'ms linear'); var disCoords = coords || getCoords(); var x = disCoords.x; var y = disCoords.y; var xSign = (x / Math.abs(x)) || 0; var ySign = (y / Math.abs(y)) || 0; var adjX = Math.pow(Math.abs(x), DAMPING); var adjY = Math.pow(Math.abs(y), DAMPING); var newX = -1 * adjX * xSign; var newY = -1 * adjY * ySign; translate3d({ x: newX, y: newY }, start, broadcast) if (adjX > 5 || adjY > 5) { setTimeout(function() { spring({ x: newX, y: newY }, null, broadcast, time); }, time); } else { setTimeout(function() { translate3d({ x: 0, y: 0 }, null, broadcast); }, time); } } function getCoords() { var c = element.css('transform').match(/translate3d\((-?\d+)(?:px)?, ?(-?\d+)(?:px)?, ?(-?\d+)(?:px)?\)/); // startX = startingX && startingX.length > 1 ? Number(startingX[1]) : 0; var x = c && c[1] ? Number(c[1]) : 0; var y = c && c[2] ? Number(c[2]) : 0; return { x: x, y: y } } function getDist() { var coords = getCoords(); return Math.sqrt(Math.pow(coords.x, 2) + Math.pow(coords.y, 2)); } function isNull(a, b) { return a === null || a === undefined ? b : a; } } } })
{ "content_hash": "90edf5d60c9369e0fbabc06ee52d0f90", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 143, "avg_line_length": 25.964052287581698, "alnum_prop": 0.48219005663939585, "repo_name": "huttj/swipe-directive", "id": "629ac70588282ca6b83fee6ee8d7b0ab4a5b9599", "size": "7945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "script.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "985" }, { "name": "JavaScript", "bytes": "7945" } ], "symlink_target": "" }
package giraudsa.marshall.deserialisation.text.json.actions; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import giraudsa.marshall.deserialisation.ActionAbstrait; import giraudsa.marshall.deserialisation.Unmarshaller; import giraudsa.marshall.deserialisation.text.json.JsonUnmarshaller; import utils.Constants; import utils.champ.FakeChamp; import utils.champ.FieldInformations; @SuppressWarnings("rawtypes") public class ActionJsonCollectionType<T extends Collection> extends ActionJsonComplexeObject<T> { private static final Logger LOGGER = LoggerFactory.getLogger(ActionJsonCollectionType.class); public static ActionAbstrait<Collection> getInstance() { return new ActionJsonCollectionType<>(Collection.class, null); } private FakeChamp fakeChamp; private ActionJsonCollectionType(final Class<T> type, final JsonUnmarshaller<?> jsonUnmarshaller) { super(type, jsonUnmarshaller); Class<?> ttype = type; if (type.getName().toLowerCase().indexOf("hibernate") != -1 || type.isInterface()) ttype = ArrayList.class; try { obj = ttype.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.debug("impossible de créer une instance de " + ttype.getName(), e); obj = new ArrayList<>(); } } @Override protected void construitObjet() { // rien a faire } private FakeChamp getFakeChamp() { if (fakeChamp == null) { final Type[] types = fieldInformations.getParametreType(); Type typeGeneric = Object.class; if (types != null && types.length > 0) typeGeneric = types[0]; fakeChamp = new FakeChamp("V", typeGeneric, fieldInformations.getRelation(), fieldInformations.getAnnotations()); } return fakeChamp; } @Override protected FieldInformations getFieldInformationSpecialise(final String nomAttribut) { if (Constants.VALEUR.equals(nomAttribut)) return fieldInformations; return getFakeChamp(); } @Override public <U extends T> ActionAbstrait<U> getNewInstance(final Class<U> type, final Unmarshaller unmarshaller) { return new ActionJsonCollectionType<>(type, (JsonUnmarshaller<?>) unmarshaller); } @Override protected Class<?> getTypeAttribute(final String nomAttribut) { if (Constants.VALEUR.equals(nomAttribut)) return ArrayList.class; return getFakeChamp().getValueType(); } @SuppressWarnings("unchecked") @Override protected <W> void integreObjet(final String nomAttribut, final W objet) { if (nomAttribut == null) ((Collection) obj).add(objet); else for (final Object o : (ArrayList) objet) ((Collection) obj).add(o); } }
{ "content_hash": "7ee6ccf872065d6a884997de6a45a771", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 110, "avg_line_length": 30.701149425287355, "alnum_prop": 0.7547734930737552, "repo_name": "giraudsa/serialisation", "id": "06a1eb0e8c72ddee2ccfd5169b14a46590df5b3d", "size": "2672", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/giraudsa/marshall/deserialisation/text/json/actions/ActionJsonCollectionType.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "424744" } ], "symlink_target": "" }
title: Warm Moroccan Spiced Quinoa Salad with Apricots author: The Lagasse Girls layout: post song: "000000001" permalink: /recipes/warm-moroccan-spiced-quinoa-salad-with-apricots/ tagline: "If you like Moroccan spices and cuisine, we think you will fall in love with this heart-healthy salad. " categories: - 'Recipes &amp; More' tags: - almonds - apricots - chickpeas - moroccan - quinoa --- If you like Moroccan spices and cuisine, we think you will fall in love with this heart-healthy salad. We know it will leave you feeling satisfied and happy. We suggest serving it warm, but it is also delicious cold. You should be able to find the Moroccan spice mix ras el hanout in the spice aisle at most local grocery stores. If for some reason you can’t, try your local Whole Foods Market, specialty supermarkets, or Asian markets. You could also order it online; just have a look at our Resources section to see where. It really is a key component to the dish. This quinoa is a deliciously filling vegetarian option, but if you’re not a vegetarian, feel free to add any other form of protein you’d like—or try serving it with our delicious Moroccan Lamb Tagine (page 244). ### Makes 4 to 6 Servings <span style="text-decoration: underline;"><strong>Ingredients:</strong></span> 1 1/2 cups cooked quinoa, prepared per package instructions 3/4 cup vegetable stock 2 tablespoons freshly squeezed lemon juice 1 1/2 teaspoons ras el hanout Moroccan seasoning 1 (14-ounce) can chickpeas, drained and rinsed 1/2 cup julienned dried plump apricots (about 12 dried apricots) 1/3 cup sliced almonds 1/2 cup finely chopped fresh mint 1/4 cup finely chopped fresh parsley Pinch of salt and freshly ground black pepper &nbsp; **<span style="text-decoration: underline;">Steps:</span>** 1. In a medium saucepan, mix the cooked quinoa, stock, lemon juice, and ras el hanout seasoning and stir well. Heat the mixture over low heat for 4 to 6 minutes, or until the liquid is mostly absorbed. 2. Add all the remaining ingredients to the pan. Stir well and serve immediately. &nbsp;
{ "content_hash": "ed448a462ac6e7d66ffe305d4269ff15", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 778, "avg_line_length": 42.755102040816325, "alnum_prop": 0.7684964200477327, "repo_name": "sonnetmedia/lagassegirls.com", "id": "d70bafb689011d7f0e818a836f296521af58dc6a", "size": "2107", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_posts/2015-01-04-warm-moroccan-spiced-quinoa-salad-with-apricots.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59361" }, { "name": "HTML", "bytes": "13388" }, { "name": "JavaScript", "bytes": "1732" }, { "name": "Ruby", "bytes": "3089" } ], "symlink_target": "" }
There are two methods for getting started with this repo. #### Familiar with Git? Checkout this repo, install dependencies, then start the gulp process with the following: ``` > git clone https://github.com/MiguelRamBalt/Redux.git > cd ReduxSimpleStarter > npm install > npm start ```
{ "content_hash": "920f756ba98393fd0815456ddd8d5240", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 89, "avg_line_length": 26.09090909090909, "alnum_prop": 0.7560975609756098, "repo_name": "MiguelRamBalt/Redux", "id": "69cf7e13039945d5dd23fdc48d6a37e00af9eea6", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "474" }, { "name": "JavaScript", "bytes": "4586" } ], "symlink_target": "" }
// // keyvi - A key value store. // // Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com> // // 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. // /* * configuration_test.cpp * * Created on: Jan 21, 2017 * Author: hendrik */ #include <boost/test/unit_test.hpp> #include "dictionary/util/configuration.h" namespace keyvi { namespace dictionary { namespace util { BOOST_AUTO_TEST_SUITE(ConfigurationTests) BOOST_AUTO_TEST_CASE(memory) { std::map<std::string, std::string> memory_default({}); BOOST_CHECK_EQUAL(DEFAULT_MEMORY_LIMIT, util::mapGetMemory(memory_default, MEMORY_LIMIT_KEY, DEFAULT_MEMORY_LIMIT)); std::map<std::string, std::string> memory_bytes({{"memory_limit", "52428800"}}); BOOST_CHECK_EQUAL(std::size_t(52428800), util::mapGetMemory(memory_bytes, MEMORY_LIMIT_KEY, DEFAULT_MEMORY_LIMIT)); std::map<std::string, std::string> memory_kb({{"memory_limit_kb", "61440"}}); BOOST_CHECK_EQUAL(std::size_t(62914560), util::mapGetMemory(memory_kb, MEMORY_LIMIT_KEY, DEFAULT_MEMORY_LIMIT)); std::map<std::string, std::string> memory_mb({{"memory_limit_mb", "70"}}); BOOST_CHECK_EQUAL(std::size_t(73400320), util::mapGetMemory(memory_mb, MEMORY_LIMIT_KEY, DEFAULT_MEMORY_LIMIT)); std::map<std::string, std::string> memory_gb({{"memory_limit_gb", "2"}}); BOOST_CHECK_EQUAL(std::size_t(2147483648), util::mapGetMemory(memory_gb, MEMORY_LIMIT_KEY, DEFAULT_MEMORY_LIMIT)); } BOOST_AUTO_TEST_CASE(boolean) { std::map<std::string, std::string> bool_default({}); BOOST_CHECK_EQUAL(false, util::mapGetBool(bool_default, "some_bool", false)); BOOST_CHECK_EQUAL(true, util::mapGetBool(bool_default, "some_bool", true)); std::map<std::string, std::string> bool_false({{"some_bool", "fALse"}}); BOOST_CHECK_EQUAL(false, util::mapGetBool(bool_false, "some_bool", true)); std::map<std::string, std::string> bool_true({{"some_bool", "truE"}}); BOOST_CHECK_EQUAL(true, util::mapGetBool(bool_true, "some_bool", false)); std::map<std::string, std::string> bool_on({{"some_bool", "on"}}); BOOST_CHECK_EQUAL(true, util::mapGetBool(bool_on, "some_bool", false)); std::map<std::string, std::string> bool_off({{"some_bool", "off"}}); BOOST_CHECK_EQUAL(false, util::mapGetBool(bool_off, "some_bool", true)); } BOOST_AUTO_TEST_SUITE_END() } /* namespace util */ } /* namespace dictionary */ } /* namespace keyvi */
{ "content_hash": "f0a8622637dbf63eae767dd0d301aff5", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 79, "avg_line_length": 37.34782608695652, "alnum_prop": 0.5829452852153667, "repo_name": "cliqz-oss/keyvi", "id": "139b7df3dae19079a0f440062e6e1352b69930bd", "size": "3436", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "keyvi/tests/keyvi/dictionary/util/configuration_test.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4301" }, { "name": "C++", "bytes": "591443" }, { "name": "CMake", "bytes": "2106" }, { "name": "Makefile", "bytes": "628" }, { "name": "Python", "bytes": "94088" }, { "name": "Shell", "bytes": "11483" } ], "symlink_target": "" }
using System; using System.Configuration; namespace RevStack.Identity.Mvc.Settings { public static class RemoveLogin { public static string Success { get { var result = ConfigurationManager.AppSettings["Identity.RemoveLogin.Success"]; if (!string.IsNullOrEmpty(result)) return result; return "The social media login has been removed."; } } } }
{ "content_hash": "d078192bf74dc1420e180a858fd32a38", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 94, "avg_line_length": 25.57894736842105, "alnum_prop": 0.5576131687242798, "repo_name": "RevStack/Identity.Mvc", "id": "3230d860883efb0c2e2580faa0c9dc2857b18988", "size": "488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RevStack.Identity.Mvc/Settings/RemoveLogin.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "106662" } ], "symlink_target": "" }
<?php /** * TTCC layout format consists of <b>t</b>ime, <b>t</b>hread, <b>c</b>ategory and nested * diagnostic <b>c</b>ontext information, hence the name. * * <p>Each of the four fields can be individually enabled or * disabled. The time format depends on the <b>DateFormat</b> used.</p> * * <p>If no dateFormat is specified it defaults to '%c'. * See php {@link PHP_MANUAL#date} function for details.</p> * * Configurable parameters for this layout are: * - {@link $threadPrinting} (true|false) enable/disable pid reporting. * - {@link $categoryPrefixing} (true|false) enable/disable logger category reporting. * - {@link $contextPrinting} (true|false) enable/disable NDC reporting. * - {@link $microSecondsPrinting} (true|false) enable/disable micro seconds reporting in timestamp. * - {@link $dateFormat} (string) set date format. See php {@link PHP_MANUAL#date} function for details. * * An example how to use this layout: * * {@example ../../examples/php/layout_ttcc.php 19}<br> * * {@example ../../examples/resources/layout_ttcc.properties 18}<br> * * The above would print:<br> * <samp>02:28 [13714] INFO root - Hello World!</samp> * * @version $Revision: 883108 $ * @package log4php * @subpackage layouts */ class LoggerLayoutTTCC extends LoggerLayout { /** * String constant designating no time information. Current value of * this constant is <b>NULL</b>. */ // TODO: not used? const LOG4PHP_LOGGER_LAYOUT_NULL_DATE_FORMAT = 'NULL'; /** * String constant designating relative time. Current value of * this constant is <b>RELATIVE</b>. */ // TODO: not used? const LOG4PHP_LOGGER_LAYOUT_RELATIVE_TIME_DATE_FORMAT = 'RELATIVE'; // Internal representation of options protected $threadPrinting = true; protected $categoryPrefixing = true; protected $contextPrinting = true; protected $microSecondsPrinting = true; /** * @var string date format. See {@link PHP_MANUAL#strftime} for details */ protected $dateFormat = '%c'; /** * Constructor * * @param string date format * @see dateFormat */ public function __construct($dateFormat = '') { if (!empty($dateFormat)) { $this->dateFormat = $dateFormat; } return; } /** * The <b>ThreadPrinting</b> option specifies whether the name of the * current thread is part of log output or not. This is true by default. */ public function setThreadPrinting($threadPrinting) { $this->threadPrinting = is_bool($threadPrinting) ? $threadPrinting : (bool)(strtolower($threadPrinting) == 'true'); } /** * @return boolean Returns value of the <b>ThreadPrinting</b> option. */ public function getThreadPrinting() { return $this->threadPrinting; } /** * The <b>CategoryPrefixing</b> option specifies whether {@link Category} * name is part of log output or not. This is true by default. */ public function setCategoryPrefixing($categoryPrefixing) { $this->categoryPrefixing = LoggerOptionConverter::toBoolean($categoryPrefixing); } /** * @return boolean Returns value of the <b>CategoryPrefixing</b> option. */ public function getCategoryPrefixing() { return $this->categoryPrefixing; } /** * The <b>ContextPrinting</b> option specifies log output will include * the nested context information belonging to the current thread. * This is true by default. */ public function setContextPrinting($contextPrinting) { $this->contextPrinting = LoggerOptionConverter::toBoolean($contextPrinting); } /** * @return boolean Returns value of the <b>ContextPrinting</b> option. */ public function getContextPrinting() { return $this->contextPrinting; } /** * The <b>MicroSecondsPrinting</b> option specifies if microseconds infos * should be printed at the end of timestamp. * This is true by default. */ public function setMicroSecondsPrinting($microSecondsPrinting) { $this->microSecondsPrinting = is_bool($microSecondsPrinting) ? $microSecondsPrinting : (bool)(strtolower($microSecondsPrinting) == 'true'); } /** * @return boolean Returns value of the <b>MicroSecondsPrinting</b> option. */ public function getMicroSecondsPrinting() { return $this->microSecondsPrinting; } public function setDateFormat($dateFormat) { $this->dateFormat = $dateFormat; } /** * @return string */ public function getDateFormat() { return $this->dateFormat; } /** * In addition to the level of the statement and message, the * returned string includes time, thread, category. * <p>Time, thread, category are printed depending on options. * * @param LoggerLoggingEvent $event * @return string */ public function format(LoggerLoggingEvent $event) { $timeStamp = (float)$event->getTimeStamp(); $format = strftime($this->dateFormat, (int)$timeStamp); if ($this->microSecondsPrinting) { $usecs = floor(($timeStamp - (int)$timeStamp) * 1000); $format .= sprintf(',%03d', $usecs); } $format .= ' '; if ($this->threadPrinting) { $format .= '['.getmypid().'] '; } $level = $event->getLevel(); $format .= $level->toString().' '; if($this->categoryPrefixing) { $format .= $event->getLoggerName().' '; } if($this->contextPrinting) { $ndc = $event->getNDC(); if($ndc != null) { $format .= $ndc.' '; } } $format .= '- '.$event->getRenderedMessage(); $format .= PHP_EOL; return $format; } public function ignoresThrowable() { return true; } }
{ "content_hash": "31e5b4a3d9dcd6ab324db43ee11ad7d1", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 104, "avg_line_length": 30.696969696969695, "alnum_prop": 0.6095755182625864, "repo_name": "LowResourceLanguages/InuktitutComputing", "id": "23eba4a808144eee8d740c41629e9a7a61194ee3", "size": "6903", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "Inuktitut-PHP/lib/log4php/layouts/LoggerLayoutTTCC.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1552" }, { "name": "CSS", "bytes": "10818" }, { "name": "HTML", "bytes": "192562" }, { "name": "Java", "bytes": "4750024" }, { "name": "PHP", "bytes": "938066" }, { "name": "Perl", "bytes": "25957" } ], "symlink_target": "" }
<?xml version="1.0"?> <config> <tabs> <magentothem translate="label" module="themeoptions"> <label>Magentothem</label> <sort_order>205</sort_order> </magentothem> </tabs> <sections> <themeoptions translate="label" module="themeoptions"> <label>Theme Options</label> <tab>magentothem</tab> <sort_order>131</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <groups> <themeoptions_config translate="label"> <label>Theme Options Config</label> <frontend_type>text</frontend_type> <sort_order>1</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <fields> <theme_color translate="label"> <label>Theme Color: </label> <frontend_type>select</frontend_type> <source_model> themeoptions/config_color </source_model> <sort_order>0</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </theme_color> <new_label translate="label comment"> <label>New Label: </label> <frontend_type>select</frontend_type> <source_model> adminhtml/system_config_source_yesno </source_model> <sort_order>2</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </new_label> <sale_label translate="label comment"> <label>Sale Label: </label> <frontend_type>select</frontend_type> <source_model> adminhtml/system_config_source_yesno </source_model> <sort_order>3</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </sale_label> </fields> </themeoptions_config> </groups> </themeoptions> </sections> </config>
{ "content_hash": "d24751d6a51b731ab5d6851c28966ec8", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 65, "avg_line_length": 34.63235294117647, "alnum_prop": 0.5354564755838641, "repo_name": "cArLiiToX/dtstore", "id": "13e94a6c0b66f194bac8589d95b4eefd76352f1c", "size": "2355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/local/Magentothem/Themeoptions/etc/system.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19946" }, { "name": "ApacheConf", "bytes": "6723" }, { "name": "CSS", "bytes": "6407515" }, { "name": "Erlang", "bytes": "1088" }, { "name": "Groovy", "bytes": "10320" }, { "name": "HTML", "bytes": "7365239" }, { "name": "JavaScript", "bytes": "2660599" }, { "name": "PHP", "bytes": "53440797" }, { "name": "Perl", "bytes": "83695" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Prolog", "bytes": "2246" }, { "name": "R", "bytes": "1102" }, { "name": "Ruby", "bytes": "894" }, { "name": "Shell", "bytes": "65776" }, { "name": "XML", "bytes": "16526909" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
/*jslint evil: true */ 'use strict'; import * as React from 'react'; import * as ReactART from 'react-art'; import ARTSVGMode from 'art/modes/svg'; import ARTCurrentMode from 'art/modes/current'; // Since these are default exports, we need to import them using ESM. // Since they must be on top, we need to import this before ReactDOM. import Circle from 'react-art/Circle'; import Rectangle from 'react-art/Rectangle'; import Wedge from 'react-art/Wedge'; // Isolate DOM renderer. jest.resetModules(); const ReactDOM = require('react-dom'); const ReactTestUtils = require('react-dom/test-utils'); // Isolate test renderer. jest.resetModules(); const ReactTestRenderer = require('react-test-renderer'); // Isolate the noop renderer jest.resetModules(); const ReactNoop = require('react-noop-renderer'); const Scheduler = require('scheduler'); let Group; let Shape; let Surface; let TestComponent; const Missing = {}; function testDOMNodeStructure(domNode, expectedStructure) { expect(domNode).toBeDefined(); expect(domNode.nodeName).toBe(expectedStructure.nodeName); for (const prop in expectedStructure) { if (!expectedStructure.hasOwnProperty(prop)) { continue; } if (prop !== 'nodeName' && prop !== 'children') { if (expectedStructure[prop] === Missing) { expect(domNode.hasAttribute(prop)).toBe(false); } else { expect(domNode.getAttribute(prop)).toBe(expectedStructure[prop]); } } } if (expectedStructure.children) { expectedStructure.children.forEach(function(subTree, index) { testDOMNodeStructure(domNode.childNodes[index], subTree); }); } } describe('ReactART', () => { let container; beforeEach(() => { container = document.createElement('div'); document.body.appendChild(container); ARTCurrentMode.setCurrent(ARTSVGMode); Group = ReactART.Group; Shape = ReactART.Shape; Surface = ReactART.Surface; TestComponent = class extends React.Component { group = React.createRef(); render() { const a = ( <Shape d="M0,0l50,0l0,50l-50,0z" fill={new ReactART.LinearGradient(['black', 'white'])} key="a" width={50} height={50} x={50} y={50} opacity={0.1} /> ); const b = ( <Shape fill="#3C5A99" key="b" scale={0.5} x={50} y={50} title="This is an F" cursor="pointer"> M64.564,38.583H54l0.008-5.834c0-3.035,0.293-4.666,4.657-4.666 h5.833V16.429h-9.33c-11.213,0-15.159,5.654-15.159,15.16v6.994 h-6.99v11.652h6.99v33.815H54V50.235h9.331L64.564,38.583z </Shape> ); const c = <Group key="c" />; return ( <Surface width={150} height={200}> <Group ref={this.group}> {this.props.flipped ? [b, a, c] : [a, b, c]} </Group> </Surface> ); } }; }); afterEach(() => { document.body.removeChild(container); container = null; }); it('should have the correct lifecycle state', () => { let instance = <TestComponent />; instance = ReactTestUtils.renderIntoDocument(instance); const group = instance.group.current; // Duck type test for an ART group expect(typeof group.indicate).toBe('function'); }); it('should render a reasonable SVG structure in SVG mode', () => { let instance = <TestComponent />; instance = ReactTestUtils.renderIntoDocument(instance); const expectedStructure = { nodeName: 'svg', width: '150', height: '200', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ { nodeName: 'defs', children: [{nodeName: 'linearGradient'}], }, {nodeName: 'path'}, {nodeName: 'path'}, {nodeName: 'g'}, ], }, ], }; const realNode = ReactDOM.findDOMNode(instance); testDOMNodeStructure(realNode, expectedStructure); }); it('should be able to reorder components', () => { const instance = ReactDOM.render( <TestComponent flipped={false} />, container, ); const expectedStructure = { nodeName: 'svg', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ {nodeName: 'defs'}, {nodeName: 'path', opacity: '0.1'}, {nodeName: 'path', opacity: Missing}, {nodeName: 'g'}, ], }, ], }; const realNode = ReactDOM.findDOMNode(instance); testDOMNodeStructure(realNode, expectedStructure); ReactDOM.render(<TestComponent flipped={true} />, container); const expectedNewStructure = { nodeName: 'svg', children: [ {nodeName: 'defs'}, { nodeName: 'g', children: [ {nodeName: 'defs'}, {nodeName: 'path', opacity: Missing}, {nodeName: 'path', opacity: '0.1'}, {nodeName: 'g'}, ], }, ], }; testDOMNodeStructure(realNode, expectedNewStructure); }); it('should be able to reorder many components', () => { class Component extends React.Component { render() { const chars = this.props.chars.split(''); return ( <Surface> {chars.map(text => ( <Shape key={text} title={text} /> ))} </Surface> ); } } // Mini multi-child stress test: lots of reorders, some adds, some removes. const before = 'abcdefghijklmnopqrst'; const after = 'mxhpgwfralkeoivcstzy'; let instance = ReactDOM.render(<Component chars={before} />, container); const realNode = ReactDOM.findDOMNode(instance); expect(realNode.textContent).toBe(before); instance = ReactDOM.render(<Component chars={after} />, container); expect(realNode.textContent).toBe(after); ReactDOM.unmountComponentAtNode(container); }); it('renders composite with lifecycle inside group', () => { let mounted = false; class CustomShape extends React.Component { render() { return <Shape />; } componentDidMount() { mounted = true; } } ReactTestUtils.renderIntoDocument( <Surface> <Group> <CustomShape /> </Group> </Surface>, ); expect(mounted).toBe(true); }); it('resolves refs before componentDidMount', () => { class CustomShape extends React.Component { render() { return <Shape />; } } let ref = null; class Outer extends React.Component { test = React.createRef(); componentDidMount() { ref = this.test.current; } render() { return ( <Surface> <Group> <CustomShape ref={this.test} /> </Group> </Surface> ); } } ReactTestUtils.renderIntoDocument(<Outer />); expect(ref.constructor).toBe(CustomShape); }); it('resolves refs before componentDidUpdate', () => { class CustomShape extends React.Component { render() { return <Shape />; } } let ref = {}; class Outer extends React.Component { test = React.createRef(); componentDidMount() { ref = this.test.current; } componentDidUpdate() { ref = this.test.current; } render() { return ( <Surface> <Group> {this.props.mountCustomShape && <CustomShape ref={this.test} />} </Group> </Surface> ); } } ReactDOM.render(<Outer />, container); expect(ref).toBe(null); ReactDOM.render(<Outer mountCustomShape={true} />, container); expect(ref.constructor).toBe(CustomShape); }); it('adds and updates event handlers', () => { function render(onClick) { return ReactDOM.render( <Surface> <Shape onClick={onClick} /> </Surface>, container, ); } function doClick(instance) { const path = ReactDOM.findDOMNode(instance).querySelector('path'); path.dispatchEvent( new MouseEvent('click', { bubbles: true, }), ); } const onClick1 = jest.fn(); let instance = render(onClick1); doClick(instance); expect(onClick1).toBeCalled(); const onClick2 = jest.fn(); instance = render(onClick2); doClick(instance); expect(onClick2).toBeCalled(); }); // @gate !enableSyncDefaultUpdates it('can concurrently render with a "primary" renderer while sharing context', () => { const CurrentRendererContext = React.createContext(null); function Yield(props) { Scheduler.unstable_yieldValue(props.value); return null; } let ops = []; function LogCurrentRenderer() { return ( <CurrentRendererContext.Consumer> {currentRenderer => { ops.push(currentRenderer); return null; }} </CurrentRendererContext.Consumer> ); } // Using test renderer instead of the DOM renderer here because async // testing APIs for the DOM renderer don't exist. ReactNoop.render( <CurrentRendererContext.Provider value="Test"> <Yield value="A" /> <Yield value="B" /> <LogCurrentRenderer /> <Yield value="C" /> </CurrentRendererContext.Provider>, ); expect(Scheduler).toFlushAndYieldThrough(['A']); ReactDOM.render( <Surface> <LogCurrentRenderer /> <CurrentRendererContext.Provider value="ART"> <LogCurrentRenderer /> </CurrentRendererContext.Provider> </Surface>, container, ); expect(ops).toEqual([null, 'ART']); ops = []; expect(Scheduler).toFlushAndYield(['B', 'C']); expect(ops).toEqual(['Test']); }); }); describe('ReactARTComponents', () => { it('should generate a <Shape> with props for drawing the Circle', () => { const circle = ReactTestRenderer.create( <Circle radius={10} stroke="green" strokeWidth={3} fill="blue" />, ); expect(circle.toJSON()).toMatchSnapshot(); }); it('should warn if radius is missing on a Circle component', () => { expect(() => ReactTestRenderer.create( <Circle stroke="green" strokeWidth={3} fill="blue" />, ), ).toErrorDev( 'Warning: Failed prop type: The prop `radius` is marked as required in `Circle`, ' + 'but its value is `undefined`.' + '\n in Circle (at **)', ); }); it('should generate a <Shape> with props for drawing the Rectangle', () => { const rectangle = ReactTestRenderer.create( <Rectangle width={50} height={50} stroke="green" fill="blue" />, ); expect(rectangle.toJSON()).toMatchSnapshot(); }); it('should warn if width/height is missing on a Rectangle component', () => { expect(() => ReactTestRenderer.create(<Rectangle stroke="green" fill="blue" />), ).toErrorDev([ 'Warning: Failed prop type: The prop `width` is marked as required in `Rectangle`, ' + 'but its value is `undefined`.' + '\n in Rectangle (at **)', 'Warning: Failed prop type: The prop `height` is marked as required in `Rectangle`, ' + 'but its value is `undefined`.' + '\n in Rectangle (at **)', ]); }); it('should generate a <Shape> with props for drawing the Wedge', () => { const wedge = ReactTestRenderer.create( <Wedge outerRadius={50} startAngle={0} endAngle={360} fill="blue" />, ); expect(wedge.toJSON()).toMatchSnapshot(); }); it('should return null if startAngle equals to endAngle on Wedge', () => { const wedge = ReactTestRenderer.create( <Wedge outerRadius={50} startAngle={0} endAngle={0} fill="blue" />, ); expect(wedge.toJSON()).toBeNull(); }); it('should warn if outerRadius/startAngle/endAngle is missing on a Wedge component', () => { expect(() => ReactTestRenderer.create(<Wedge fill="blue" />)).toErrorDev([ 'Warning: Failed prop type: The prop `outerRadius` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', 'Warning: Failed prop type: The prop `startAngle` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', 'Warning: Failed prop type: The prop `endAngle` is marked as required in `Wedge`, ' + 'but its value is `undefined`.' + '\n in Wedge (at **)', ]); }); });
{ "content_hash": "c195d55610092b5fdf11bdcebac6ee8f", "timestamp": "", "source": "github", "line_count": 476, "max_line_length": 94, "avg_line_length": 26.930672268907564, "alnum_prop": 0.5735236757937436, "repo_name": "acdlite/react", "id": "950ec77bb1a6eda22aedc2e8c445499378f42c4e", "size": "13032", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "packages/react-art/src/__tests__/ReactART-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5225" }, { "name": "C++", "bytes": "44278" }, { "name": "CSS", "bytes": "70235" }, { "name": "CoffeeScript", "bytes": "16554" }, { "name": "HTML", "bytes": "115342" }, { "name": "JavaScript", "bytes": "5541727" }, { "name": "Makefile", "bytes": "189" }, { "name": "Python", "bytes": "259" }, { "name": "Shell", "bytes": "3829" }, { "name": "TypeScript", "bytes": "19904" } ], "symlink_target": "" }
import spotify import threading import json import os import nltk.metrics.agreement import api_keys # Get secret keys KEYS = api_keys.get_keys() logged_in_event = threading.Event() def pretty_print(obj): print json.dumps(obj, sort_keys=True, indent=4, separators=(',',': ')) def connection_state_listener(session): if session.connection.state is spotify.ConnectionState.LOGGED_IN: logged_in_event.set() # Specify configuration config = spotify.Config() config.user_agent = 'My awesome Spotify client' config.tracefile = b'/tmp/libspotify-trace.log' print "Opening session with user {}...".format(KEYS["SPOTIFY_USERNAME"]) # Open session and loop session = spotify.Session(config) loop = spotify.EventLoop(session) loop.start() session.on( spotify.SessionEvent.CONNECTION_STATE_UPDATED, connection_state_listener) session.login(KEYS["SPOTIFY_USERNAME"],KEYS["SPOTIFY_PASSWORD"]) logged_in_event.wait() print "Logged in and waiting..." # Return the greatest common suffix in a list of strings def greatest_common_suffix(list_of_strings): reversed_strings = [' '.join(s.split()[::-1]) for s in list_of_strings] reversed_gcs = os.path.commonprefix(reversed_strings) gcs = ' '.join(reversed_gcs.split()[::-1]) return gcs def score(target, item): target = target.lower() item = item.lower() return nltk.metrics.edit_distance(target, item)*1.0 / len(target) def match(target, candidate_list, distance_only=False): """ Given a target string and a list of candidate strings, return the best matching candidate. """ distances = [] for item in candidate_list: dist = score(target, item) distances.append(dist) if distance_only: return min(distances) # Get index of minimum distance return distances.index(min(distances)) def search_score(target_tracks, matching_tracks): """ Given a list of track names to be matched, and a list of matching tracks, returns a score that approximates the confidence that the match is valid. The score is based on the average of the edit distance between each target track and its best match, offset by the difference in the length of each list. """ distances = [] for target in target_tracks: dist = match(target, matching_tracks, distance_only=True) distances.append(dist) return (sum(distances) / len(distances)) + abs(len(target_tracks)- len(matching_tracks))/len(distances) def search_for_album(show): query = show["name"] search = session.search(query) # Execute search query search = search.load() album_results = search.albums print '\nSearching for "{}"'.format(query) # If we find no results, report error if len(album_results) == 0: raise StandardError("Error: no search results found.") scores = [] for album in album_results: album.load() # Obtain track list browser = album.browse().load() tracks = browser.tracks # Get lists of candidate album's track names and # the actual track names track_names = [clean_track_name(track.name, album, browser) for track in tracks] target_names = [song["name"] for song in show["songs"]] # Obtain a similarity score between the two lists score = search_score(target_names, track_names) # Save the score scores.append(score) # If none of the results have an acceptable score, report # an error if min(scores) > .3: raise StandardError("Error: no results above threshold") return album_results[scores.index(min(scores))] def ascii(s): return s.encode('ascii', 'ignore') def add_spotify_song_data(song, spotify_track): song["spotify_popularity"] = spotify_track.popularity song["spotify_duration"] = spotify_track.duration / 1000 song["spotify_track"] = str(spotify_track.link) song["spotify_track_name"] = spotify_track.name song["spotify_match_score"] = match_score artists= [str(artist.link) for artist in spotify_track.artists] artist_names = [ascii(artist.name) for artist in spotify_track.artists] song["spotify_artists"] = artists song["spotify_artist_names"] = artist_names song["spotify_track_index"] = spotify_track.index def add_spotify_album_data(album, spotify_album): # Save the cover art file found on Spotify cover_art_file = '../data/cover_art/'+str(spotify_album.link)+'.jpg' open(cover_art_file,'w+').write(spotify_album.cover().load().data) # Record album-specific data show["show_on_spotify"] = True show["spotify_album"] = str(spotify_album.link) show["spotify_album_year"] = spotify_album.year show["spotify_album_artist"] = ascii(spotify_album.artist.name) show["spotify_cover_art"] = cover_art_file def clean_track_name(track_name, album, browser): browser = album.browse().load() tracks = browser.tracks track_names = [track.name for track in tracks] gcs = greatest_common_suffix(track_names) track_name = ascii(track_name).lower() album_name = ascii(album.name).lower().replace(' the musical','') # Remove greatest common suffix if large enough if len(gcs) > 3: track_name = track_name.replace(gcs.lower(), '') # Remove "(From "[show_name]")" from track name if present track_name = track_name.replace('(from "{}")'.format(album_name),'') # Remove "- Musical "[show_name]"" from track name if present track_name = track_name.replace(' - musical "{}"'.format(album_name),'') # Remove " - feat.*" if present track_name = track_name.split(" - feat. ")[0] return track_name with open('../data/shows_combined.json.matched', 'r') as f: data = json.load(f) for show in data: show_name = show["name"] # Try to search Spotify for the album. If no suitable matches are found, # note that the album was not found on Spotify and move on. try: album = search_for_album(show) except StandardError as e: show["show_on_spotify"] = False print e continue # Load the album, get the track list, and produce a list of track names # on the Spotify album album.load() browser = album.browse().load() tracks = browser.tracks track_names = [clean_track_name(track.name, album, browser) for track in tracks] show["spotify_song_count"] = len(track_names) add_spotify_album_data(show, album) # Keep track of any songs that we find on spotify that we didn't have # saved before new_songs = [] # For each song in the show, find a match from the track list. for song in show["songs"]: track_index = match(song["name"], track_names) matching_track = tracks[track_index] matching_track_name = clean_track_name(matching_track.name, album, browser) song_name = ascii(song["name"]) match_score = score(song_name,matching_track_name) print '\t"{}", "{}": {}'.format( song_name, matching_track_name, match_score) if match_score < .7: song["song_on_allmusicals"] = True song["song_on_spotify"] = True add_spotify_song_data(song, matching_track) else: new_song = {} song["song_on_spotify"] = False song["song_on_allmusicals"] = True new_song["song_on_spotify"] = True new_song["song_on_allmusicals"] = False add_spotify_song_data(new_song, matching_track) collected = [s["spotify_track"] for s in new_songs] if new_song["spotify_track"] not in collected: new_songs.append(new_song) collected = [s["spotify_track"] for s in show["songs"] if "spotify_track" in s] new_songs = [s for s in new_songs if s["spotify_track"] not in collected] show["songs"].extend(new_songs) with open('../data/shows_w_spotify.json', 'w') as outfile: json.dump(data, outfile)
{ "content_hash": "70dbea1ead9603d63be789458c04a54c", "timestamp": "", "source": "github", "line_count": 256, "max_line_length": 82, "avg_line_length": 28.91796875, "alnum_prop": 0.7080913143320275, "repo_name": "willwest/broadwaydb", "id": "059f4e705407fd88b54870e000d121a2011c7e90", "size": "7403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "crawl/crawl_spotify.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9056" }, { "name": "HTML", "bytes": "5834" }, { "name": "JavaScript", "bytes": "536" }, { "name": "Makefile", "bytes": "29" }, { "name": "Python", "bytes": "33568" }, { "name": "R", "bytes": "5854" } ], "symlink_target": "" }
#include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/blkdev.h> #include <linux/sched.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/pci.h> #include "mpt3sas_base.h" /* local definitions */ /* Timeout for config page request (in seconds) */ #define MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT 15 /* Common sgl flags for READING a config page. */ #define MPT3_CONFIG_COMMON_SGLFLAGS ((MPI2_SGE_FLAGS_SIMPLE_ELEMENT | \ MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER \ | MPI2_SGE_FLAGS_END_OF_LIST) << MPI2_SGE_FLAGS_SHIFT) /* Common sgl flags for WRITING a config page. */ #define MPT3_CONFIG_COMMON_WRITE_SGLFLAGS ((MPI2_SGE_FLAGS_SIMPLE_ELEMENT | \ MPI2_SGE_FLAGS_LAST_ELEMENT | MPI2_SGE_FLAGS_END_OF_BUFFER \ | MPI2_SGE_FLAGS_END_OF_LIST | MPI2_SGE_FLAGS_HOST_TO_IOC) \ << MPI2_SGE_FLAGS_SHIFT) /** * struct config_request - obtain dma memory via routine * @sz: size * @page: virt pointer * @page_dma: phys pointer * */ struct config_request { u16 sz; void *page; dma_addr_t page_dma; }; #ifdef CONFIG_SCSI_MPT3SAS_LOGGING /** * _config_display_some_debug - debug routine * @ioc: per adapter object * @smid: system request message index * @calling_function_name: string pass from calling function * @mpi_reply: reply message frame * Context: none. * * Function for displaying debug info helpful when debugging issues * in this module. */ static void _config_display_some_debug(struct MPT3SAS_ADAPTER *ioc, u16 smid, char *calling_function_name, MPI2DefaultReply_t *mpi_reply) { Mpi2ConfigRequest_t *mpi_request; char *desc = NULL; if (!(ioc->logging_level & MPT_DEBUG_CONFIG)) return; mpi_request = mpt3sas_base_get_msg_frame(ioc, smid); switch (mpi_request->Header.PageType & MPI2_CONFIG_PAGETYPE_MASK) { case MPI2_CONFIG_PAGETYPE_IO_UNIT: desc = "io_unit"; break; case MPI2_CONFIG_PAGETYPE_IOC: desc = "ioc"; break; case MPI2_CONFIG_PAGETYPE_BIOS: desc = "bios"; break; case MPI2_CONFIG_PAGETYPE_RAID_VOLUME: desc = "raid_volume"; break; case MPI2_CONFIG_PAGETYPE_MANUFACTURING: desc = "manufaucturing"; break; case MPI2_CONFIG_PAGETYPE_RAID_PHYSDISK: desc = "physdisk"; break; case MPI2_CONFIG_PAGETYPE_EXTENDED: switch (mpi_request->ExtPageType) { case MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT: desc = "sas_io_unit"; break; case MPI2_CONFIG_EXTPAGETYPE_SAS_EXPANDER: desc = "sas_expander"; break; case MPI2_CONFIG_EXTPAGETYPE_SAS_DEVICE: desc = "sas_device"; break; case MPI2_CONFIG_EXTPAGETYPE_SAS_PHY: desc = "sas_phy"; break; case MPI2_CONFIG_EXTPAGETYPE_LOG: desc = "log"; break; case MPI2_CONFIG_EXTPAGETYPE_ENCLOSURE: desc = "enclosure"; break; case MPI2_CONFIG_EXTPAGETYPE_RAID_CONFIG: desc = "raid_config"; break; case MPI2_CONFIG_EXTPAGETYPE_DRIVER_MAPPING: desc = "driver_mapping"; break; } break; } if (!desc) return; pr_info(MPT3SAS_FMT "%s: %s(%d), action(%d), form(0x%08x), smid(%d)\n", ioc->name, calling_function_name, desc, mpi_request->Header.PageNumber, mpi_request->Action, le32_to_cpu(mpi_request->PageAddress), smid); if (!mpi_reply) return; if (mpi_reply->IOCStatus || mpi_reply->IOCLogInfo) pr_info(MPT3SAS_FMT "\tiocstatus(0x%04x), loginfo(0x%08x)\n", ioc->name, le16_to_cpu(mpi_reply->IOCStatus), le32_to_cpu(mpi_reply->IOCLogInfo)); } #endif /** * _config_alloc_config_dma_memory - obtain physical memory * @ioc: per adapter object * @mem: struct config_request * * A wrapper for obtaining dma-able memory for config page request. * * Returns 0 for success, non-zero for failure. */ static int _config_alloc_config_dma_memory(struct MPT3SAS_ADAPTER *ioc, struct config_request *mem) { int r = 0; if (mem->sz > ioc->config_page_sz) { mem->page = dma_alloc_coherent(&ioc->pdev->dev, mem->sz, &mem->page_dma, GFP_KERNEL); if (!mem->page) { pr_err(MPT3SAS_FMT "%s: dma_alloc_coherent failed asking for (%d) bytes!!\n", ioc->name, __func__, mem->sz); r = -ENOMEM; } } else { /* use tmp buffer if less than 512 bytes */ mem->page = ioc->config_page; mem->page_dma = ioc->config_page_dma; } return r; } /** * _config_free_config_dma_memory - wrapper to free the memory * @ioc: per adapter object * @mem: struct config_request * * A wrapper to free dma-able memory when using _config_alloc_config_dma_memory. * * Returns 0 for success, non-zero for failure. */ static void _config_free_config_dma_memory(struct MPT3SAS_ADAPTER *ioc, struct config_request *mem) { if (mem->sz > ioc->config_page_sz) dma_free_coherent(&ioc->pdev->dev, mem->sz, mem->page, mem->page_dma); } /** * mpt3sas_config_done - config page completion routine * @ioc: per adapter object * @smid: system request message index * @msix_index: MSIX table index supplied by the OS * @reply: reply message frame(lower 32bit addr) * Context: none. * * The callback handler when using _config_request. * * Return 1 meaning mf should be freed from _base_interrupt * 0 means the mf is freed from this function. */ u8 mpt3sas_config_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index, u32 reply) { MPI2DefaultReply_t *mpi_reply; if (ioc->config_cmds.status == MPT3_CMD_NOT_USED) return 1; if (ioc->config_cmds.smid != smid) return 1; ioc->config_cmds.status |= MPT3_CMD_COMPLETE; mpi_reply = mpt3sas_base_get_reply_virt_addr(ioc, reply); if (mpi_reply) { ioc->config_cmds.status |= MPT3_CMD_REPLY_VALID; memcpy(ioc->config_cmds.reply, mpi_reply, mpi_reply->MsgLength*4); } ioc->config_cmds.status &= ~MPT3_CMD_PENDING; #ifdef CONFIG_SCSI_MPT3SAS_LOGGING _config_display_some_debug(ioc, smid, "config_done", mpi_reply); #endif ioc->config_cmds.smid = USHRT_MAX; complete(&ioc->config_cmds.done); return 1; } /** * _config_request - main routine for sending config page requests * @ioc: per adapter object * @mpi_request: request message frame * @mpi_reply: reply mf payload returned from firmware * @timeout: timeout in seconds * @config_page: contents of the config page * @config_page_sz: size of config page * Context: sleep * * A generic API for config page requests to firmware. * * The ioc->config_cmds.status flag should be MPT3_CMD_NOT_USED before calling * this API. * * The callback index is set inside `ioc->config_cb_idx. * * Returns 0 for success, non-zero for failure. */ static int _config_request(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigRequest_t *mpi_request, Mpi2ConfigReply_t *mpi_reply, int timeout, void *config_page, u16 config_page_sz) { u16 smid; u32 ioc_state; unsigned long timeleft; Mpi2ConfigRequest_t *config_request; int r; u8 retry_count, issue_host_reset = 0; u16 wait_state_count; struct config_request mem; u32 ioc_status = UINT_MAX; mutex_lock(&ioc->config_cmds.mutex); if (ioc->config_cmds.status != MPT3_CMD_NOT_USED) { pr_err(MPT3SAS_FMT "%s: config_cmd in use\n", ioc->name, __func__); mutex_unlock(&ioc->config_cmds.mutex); return -EAGAIN; } retry_count = 0; memset(&mem, 0, sizeof(struct config_request)); mpi_request->VF_ID = 0; /* TODO */ mpi_request->VP_ID = 0; if (config_page) { mpi_request->Header.PageVersion = mpi_reply->Header.PageVersion; mpi_request->Header.PageNumber = mpi_reply->Header.PageNumber; mpi_request->Header.PageType = mpi_reply->Header.PageType; mpi_request->Header.PageLength = mpi_reply->Header.PageLength; mpi_request->ExtPageLength = mpi_reply->ExtPageLength; mpi_request->ExtPageType = mpi_reply->ExtPageType; if (mpi_request->Header.PageLength) mem.sz = mpi_request->Header.PageLength * 4; else mem.sz = le16_to_cpu(mpi_reply->ExtPageLength) * 4; r = _config_alloc_config_dma_memory(ioc, &mem); if (r != 0) goto out; if (mpi_request->Action == MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT || mpi_request->Action == MPI2_CONFIG_ACTION_PAGE_WRITE_NVRAM) { ioc->base_add_sg_single(&mpi_request->PageBufferSGE, MPT3_CONFIG_COMMON_WRITE_SGLFLAGS | mem.sz, mem.page_dma); memcpy(mem.page, config_page, min_t(u16, mem.sz, config_page_sz)); } else { memset(config_page, 0, config_page_sz); ioc->base_add_sg_single(&mpi_request->PageBufferSGE, MPT3_CONFIG_COMMON_SGLFLAGS | mem.sz, mem.page_dma); memset(mem.page, 0, min_t(u16, mem.sz, config_page_sz)); } } retry_config: if (retry_count) { if (retry_count > 2) { /* attempt only 2 retries */ r = -EFAULT; goto free_mem; } pr_info(MPT3SAS_FMT "%s: attempting retry (%d)\n", ioc->name, __func__, retry_count); } wait_state_count = 0; ioc_state = mpt3sas_base_get_iocstate(ioc, 1); while (ioc_state != MPI2_IOC_STATE_OPERATIONAL) { if (wait_state_count++ == MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT) { pr_err(MPT3SAS_FMT "%s: failed due to ioc not operational\n", ioc->name, __func__); ioc->config_cmds.status = MPT3_CMD_NOT_USED; r = -EFAULT; goto free_mem; } ssleep(1); ioc_state = mpt3sas_base_get_iocstate(ioc, 1); pr_info(MPT3SAS_FMT "%s: waiting for operational state(count=%d)\n", ioc->name, __func__, wait_state_count); } if (wait_state_count) pr_info(MPT3SAS_FMT "%s: ioc is operational\n", ioc->name, __func__); smid = mpt3sas_base_get_smid(ioc, ioc->config_cb_idx); if (!smid) { pr_err(MPT3SAS_FMT "%s: failed obtaining a smid\n", ioc->name, __func__); ioc->config_cmds.status = MPT3_CMD_NOT_USED; r = -EAGAIN; goto free_mem; } r = 0; memset(mpi_reply, 0, sizeof(Mpi2ConfigReply_t)); ioc->config_cmds.status = MPT3_CMD_PENDING; config_request = mpt3sas_base_get_msg_frame(ioc, smid); ioc->config_cmds.smid = smid; memcpy(config_request, mpi_request, sizeof(Mpi2ConfigRequest_t)); #ifdef CONFIG_SCSI_MPT3SAS_LOGGING _config_display_some_debug(ioc, smid, "config_request", NULL); #endif init_completion(&ioc->config_cmds.done); mpt3sas_base_put_smid_default(ioc, smid); timeleft = wait_for_completion_timeout(&ioc->config_cmds.done, timeout*HZ); if (!(ioc->config_cmds.status & MPT3_CMD_COMPLETE)) { pr_err(MPT3SAS_FMT "%s: timeout\n", ioc->name, __func__); _debug_dump_mf(mpi_request, sizeof(Mpi2ConfigRequest_t)/4); retry_count++; if (ioc->config_cmds.smid == smid) mpt3sas_base_free_smid(ioc, smid); if ((ioc->shost_recovery) || (ioc->config_cmds.status & MPT3_CMD_RESET) || ioc->pci_error_recovery) goto retry_config; issue_host_reset = 1; r = -EFAULT; goto free_mem; } if (ioc->config_cmds.status & MPT3_CMD_REPLY_VALID) { memcpy(mpi_reply, ioc->config_cmds.reply, sizeof(Mpi2ConfigReply_t)); /* Reply Frame Sanity Checks to workaround FW issues */ if ((mpi_request->Header.PageType & 0xF) != (mpi_reply->Header.PageType & 0xF)) { _debug_dump_mf(mpi_request, ioc->request_sz/4); _debug_dump_reply(mpi_reply, ioc->request_sz/4); panic(KERN_WARNING MPT3SAS_FMT "%s: Firmware BUG:" \ " mpi_reply mismatch: Requested PageType(0x%02x)" \ " Reply PageType(0x%02x)\n", \ ioc->name, __func__, (mpi_request->Header.PageType & 0xF), (mpi_reply->Header.PageType & 0xF)); } if (((mpi_request->Header.PageType & 0xF) == MPI2_CONFIG_PAGETYPE_EXTENDED) && mpi_request->ExtPageType != mpi_reply->ExtPageType) { _debug_dump_mf(mpi_request, ioc->request_sz/4); _debug_dump_reply(mpi_reply, ioc->request_sz/4); panic(KERN_WARNING MPT3SAS_FMT "%s: Firmware BUG:" \ " mpi_reply mismatch: Requested ExtPageType(0x%02x)" " Reply ExtPageType(0x%02x)\n", ioc->name, __func__, mpi_request->ExtPageType, mpi_reply->ExtPageType); } ioc_status = le16_to_cpu(mpi_reply->IOCStatus) & MPI2_IOCSTATUS_MASK; } if (retry_count) pr_info(MPT3SAS_FMT "%s: retry (%d) completed!!\n", \ ioc->name, __func__, retry_count); if ((ioc_status == MPI2_IOCSTATUS_SUCCESS) && config_page && mpi_request->Action == MPI2_CONFIG_ACTION_PAGE_READ_CURRENT) { u8 *p = (u8 *)mem.page; /* Config Page Sanity Checks to workaround FW issues */ if (p) { if ((mpi_request->Header.PageType & 0xF) != (p[3] & 0xF)) { _debug_dump_mf(mpi_request, ioc->request_sz/4); _debug_dump_reply(mpi_reply, ioc->request_sz/4); _debug_dump_config(p, min_t(u16, mem.sz, config_page_sz)/4); panic(KERN_WARNING MPT3SAS_FMT "%s: Firmware BUG:" \ " config page mismatch:" " Requested PageType(0x%02x)" " Reply PageType(0x%02x)\n", ioc->name, __func__, (mpi_request->Header.PageType & 0xF), (p[3] & 0xF)); } if (((mpi_request->Header.PageType & 0xF) == MPI2_CONFIG_PAGETYPE_EXTENDED) && (mpi_request->ExtPageType != p[6])) { _debug_dump_mf(mpi_request, ioc->request_sz/4); _debug_dump_reply(mpi_reply, ioc->request_sz/4); _debug_dump_config(p, min_t(u16, mem.sz, config_page_sz)/4); panic(KERN_WARNING MPT3SAS_FMT "%s: Firmware BUG:" \ " config page mismatch:" " Requested ExtPageType(0x%02x)" " Reply ExtPageType(0x%02x)\n", ioc->name, __func__, mpi_request->ExtPageType, p[6]); } } memcpy(config_page, mem.page, min_t(u16, mem.sz, config_page_sz)); } free_mem: if (config_page) _config_free_config_dma_memory(ioc, &mem); out: ioc->config_cmds.status = MPT3_CMD_NOT_USED; mutex_unlock(&ioc->config_cmds.mutex); if (issue_host_reset) mpt3sas_base_hard_reset_handler(ioc, CAN_SLEEP, FORCE_BIG_HAMMER); return r; } /** * mpt3sas_config_get_manufacturing_pg0 - obtain manufacturing page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_manufacturing_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2ManufacturingPage0_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_MANUFACTURING; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_MANUFACTURING0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_manufacturing_pg7 - obtain manufacturing page 7 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @sz: size of buffer passed in config_page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_manufacturing_pg7(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2ManufacturingPage7_t *config_page, u16 sz) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_MANUFACTURING; mpi_request.Header.PageNumber = 7; mpi_request.Header.PageVersion = MPI2_MANUFACTURING7_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); out: return r; } /** * mpt3sas_config_get_manufacturing_pg10 - obtain manufacturing page 10 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_manufacturing_pg10(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, struct Mpi2ManufacturingPage10_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_MANUFACTURING; mpi_request.Header.PageNumber = 10; mpi_request.Header.PageVersion = MPI2_MANUFACTURING0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_manufacturing_pg11 - obtain manufacturing page 11 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_manufacturing_pg11(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, struct Mpi2ManufacturingPage11_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_MANUFACTURING; mpi_request.Header.PageNumber = 11; mpi_request.Header.PageVersion = MPI2_MANUFACTURING0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_set_manufacturing_pg11 - set manufacturing page 11 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_set_manufacturing_pg11(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, struct Mpi2ManufacturingPage11_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_MANUFACTURING; mpi_request.Header.PageNumber = 11; mpi_request.Header.PageVersion = MPI2_MANUFACTURING0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_WRITE_NVRAM; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_bios_pg2 - obtain bios page 2 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_bios_pg2(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2BiosPage2_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_BIOS; mpi_request.Header.PageNumber = 2; mpi_request.Header.PageVersion = MPI2_BIOSPAGE2_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_bios_pg3 - obtain bios page 3 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_bios_pg3(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2BiosPage3_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_BIOS; mpi_request.Header.PageNumber = 3; mpi_request.Header.PageVersion = MPI2_BIOSPAGE3_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_iounit_pg0 - obtain iounit page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_iounit_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2IOUnitPage0_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_IO_UNIT; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_IOUNITPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_iounit_pg1 - obtain iounit page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2IOUnitPage1_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_IO_UNIT; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_IOUNITPAGE1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_set_iounit_pg1 - set iounit page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_set_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2IOUnitPage1_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_IO_UNIT; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_IOUNITPAGE1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_iounit_pg8 - obtain iounit page 8 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_iounit_pg8(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2IOUnitPage8_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_IO_UNIT; mpi_request.Header.PageNumber = 8; mpi_request.Header.PageVersion = MPI2_IOUNITPAGE8_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_ioc_pg8 - obtain ioc page 8 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_ioc_pg8(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2IOCPage8_t *config_page) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_IOC; mpi_request.Header.PageNumber = 8; mpi_request.Header.PageVersion = MPI2_IOCPAGE8_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_sas_device_pg0 - obtain sas device page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: device handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_sas_device_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasDevicePage0_t *config_page, u32 form, u32 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_DEVICE; mpi_request.Header.PageVersion = MPI2_SASDEVICE0_PAGEVERSION; mpi_request.Header.PageNumber = 0; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_sas_device_pg1 - obtain sas device page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: device handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_sas_device_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasDevicePage1_t *config_page, u32 form, u32 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_DEVICE; mpi_request.Header.PageVersion = MPI2_SASDEVICE1_PAGEVERSION; mpi_request.Header.PageNumber = 1; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_number_hba_phys - obtain number of phys on the host * @ioc: per adapter object * @num_phys: pointer returned with the number of phys * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_number_hba_phys(struct MPT3SAS_ADAPTER *ioc, u8 *num_phys) { Mpi2ConfigRequest_t mpi_request; int r; u16 ioc_status; Mpi2ConfigReply_t mpi_reply; Mpi2SasIOUnitPage0_t config_page; *num_phys = 0; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_SASIOUNITPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, &config_page, sizeof(Mpi2SasIOUnitPage0_t)); if (!r) { ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK; if (ioc_status == MPI2_IOCSTATUS_SUCCESS) *num_phys = config_page.NumPhys; } out: return r; } /** * mpt3sas_config_get_sas_iounit_pg0 - obtain sas iounit page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @sz: size of buffer passed in config_page * Context: sleep. * * Calling function should call config_get_number_hba_phys prior to * this function, so enough memory is allocated for config_page. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_sas_iounit_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage0_t *config_page, u16 sz) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_SASIOUNITPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); out: return r; } /** * mpt3sas_config_get_sas_iounit_pg1 - obtain sas iounit page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @sz: size of buffer passed in config_page * Context: sleep. * * Calling function should call config_get_number_hba_phys prior to * this function, so enough memory is allocated for config_page. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_sas_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage1_t *config_page, u16 sz) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_SASIOUNITPAGE1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); out: return r; } /** * mpt3sas_config_set_sas_iounit_pg1 - send sas iounit page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @sz: size of buffer passed in config_page * Context: sleep. * * Calling function should call config_get_number_hba_phys prior to * this function, so enough memory is allocated for config_page. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_set_sas_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage1_t *config_page, u16 sz) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_IO_UNIT; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_SASIOUNITPAGE1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT; _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_WRITE_NVRAM; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); out: return r; } /** * mpt3sas_config_get_expander_pg0 - obtain expander page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: expander handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_expander_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2ExpanderPage0_t *config_page, u32 form, u32 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_EXPANDER; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_SASEXPANDER0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_expander_pg1 - obtain expander page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @phy_number: phy number * @handle: expander handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_expander_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2ExpanderPage1_t *config_page, u32 phy_number, u16 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_EXPANDER; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_SASEXPANDER1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(MPI2_SAS_EXPAND_PGAD_FORM_HNDL_PHY_NUM | (phy_number << MPI2_SAS_EXPAND_PGAD_PHYNUM_SHIFT) | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_enclosure_pg0 - obtain enclosure page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: expander handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_enclosure_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasEnclosurePage0_t *config_page, u32 form, u32 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_ENCLOSURE; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_SASENCLOSURE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_phy_pg0 - obtain phy page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @phy_number: phy number * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_phy_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasPhyPage0_t *config_page, u32 phy_number) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_PHY; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_SASPHY0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(MPI2_SAS_PHY_PGAD_FORM_PHY_NUMBER | phy_number); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_phy_pg1 - obtain phy page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @phy_number: phy number * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_phy_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2SasPhyPage1_t *config_page, u32 phy_number) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_SAS_PHY; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_SASPHY1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(MPI2_SAS_PHY_PGAD_FORM_PHY_NUMBER | phy_number); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_raid_volume_pg1 - obtain raid volume page 1 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: volume handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_raid_volume_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2RaidVolPage1_t *config_page, u32 form, u32 handle) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_RAID_VOLUME; mpi_request.Header.PageNumber = 1; mpi_request.Header.PageVersion = MPI2_RAIDVOLPAGE1_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_number_pds - obtain number of phys disk assigned to volume * @ioc: per adapter object * @handle: volume handle * @num_pds: returns pds count * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_number_pds(struct MPT3SAS_ADAPTER *ioc, u16 handle, u8 *num_pds) { Mpi2ConfigRequest_t mpi_request; Mpi2RaidVolPage0_t config_page; Mpi2ConfigReply_t mpi_reply; int r; u16 ioc_status; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); *num_pds = 0; mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_RAID_VOLUME; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_RAIDVOLPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(MPI2_RAID_VOLUME_PGAD_FORM_HANDLE | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, &config_page, sizeof(Mpi2RaidVolPage0_t)); if (!r) { ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK; if (ioc_status == MPI2_IOCSTATUS_SUCCESS) *num_pds = config_page.NumPhysDisks; } out: return r; } /** * mpt3sas_config_get_raid_volume_pg0 - obtain raid volume page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_HANDLE or HANDLE * @handle: volume handle * @sz: size of buffer passed in config_page * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_raid_volume_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2RaidVolPage0_t *config_page, u32 form, u32 handle, u16 sz) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_RAID_VOLUME; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_RAIDVOLPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | handle); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sz); out: return r; } /** * mpt3sas_config_get_phys_disk_pg0 - obtain phys disk page 0 * @ioc: per adapter object * @mpi_reply: reply mf payload returned from firmware * @config_page: contents of the config page * @form: GET_NEXT_PHYSDISKNUM, PHYSDISKNUM, DEVHANDLE * @form_specific: specific to the form * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_phys_disk_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t *mpi_reply, Mpi2RaidPhysDiskPage0_t *config_page, u32 form, u32 form_specific) { Mpi2ConfigRequest_t mpi_request; int r; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_RAID_PHYSDISK; mpi_request.Header.PageNumber = 0; mpi_request.Header.PageVersion = MPI2_RAIDPHYSDISKPAGE0_PAGEVERSION; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.PageAddress = cpu_to_le32(form | form_specific); mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; r = _config_request(ioc, &mpi_request, mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, sizeof(*config_page)); out: return r; } /** * mpt3sas_config_get_volume_handle - returns volume handle for give hidden * raid components * @ioc: per adapter object * @pd_handle: phys disk handle * @volume_handle: volume handle * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_volume_handle(struct MPT3SAS_ADAPTER *ioc, u16 pd_handle, u16 *volume_handle) { Mpi2RaidConfigurationPage0_t *config_page = NULL; Mpi2ConfigRequest_t mpi_request; Mpi2ConfigReply_t mpi_reply; int r, i, config_page_sz; u16 ioc_status; int config_num; u16 element_type; u16 phys_disk_dev_handle; *volume_handle = 0; memset(&mpi_request, 0, sizeof(Mpi2ConfigRequest_t)); mpi_request.Function = MPI2_FUNCTION_CONFIG; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_HEADER; mpi_request.Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED; mpi_request.ExtPageType = MPI2_CONFIG_EXTPAGETYPE_RAID_CONFIG; mpi_request.Header.PageVersion = MPI2_RAIDCONFIG0_PAGEVERSION; mpi_request.Header.PageNumber = 0; ioc->build_zero_len_sge_mpi(ioc, &mpi_request.PageBufferSGE); r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, NULL, 0); if (r) goto out; mpi_request.Action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT; config_page_sz = (le16_to_cpu(mpi_reply.ExtPageLength) * 4); config_page = kmalloc(config_page_sz, GFP_KERNEL); if (!config_page) { r = -1; goto out; } config_num = 0xff; while (1) { mpi_request.PageAddress = cpu_to_le32(config_num + MPI2_RAID_PGAD_FORM_GET_NEXT_CONFIGNUM); r = _config_request(ioc, &mpi_request, &mpi_reply, MPT3_CONFIG_PAGE_DEFAULT_TIMEOUT, config_page, config_page_sz); if (r) goto out; r = -1; ioc_status = le16_to_cpu(mpi_reply.IOCStatus) & MPI2_IOCSTATUS_MASK; if (ioc_status != MPI2_IOCSTATUS_SUCCESS) goto out; for (i = 0; i < config_page->NumElements; i++) { element_type = le16_to_cpu(config_page-> ConfigElement[i].ElementFlags) & MPI2_RAIDCONFIG0_EFLAGS_MASK_ELEMENT_TYPE; if (element_type == MPI2_RAIDCONFIG0_EFLAGS_VOL_PHYS_DISK_ELEMENT || element_type == MPI2_RAIDCONFIG0_EFLAGS_OCE_ELEMENT) { phys_disk_dev_handle = le16_to_cpu(config_page->ConfigElement[i]. PhysDiskDevHandle); if (phys_disk_dev_handle == pd_handle) { *volume_handle = le16_to_cpu(config_page-> ConfigElement[i].VolDevHandle); r = 0; goto out; } } else if (element_type == MPI2_RAIDCONFIG0_EFLAGS_HOT_SPARE_ELEMENT) { *volume_handle = 0; r = 0; goto out; } } config_num = config_page->ConfigNum; } out: kfree(config_page); return r; } /** * mpt3sas_config_get_volume_wwid - returns wwid given the volume handle * @ioc: per adapter object * @volume_handle: volume handle * @wwid: volume wwid * Context: sleep. * * Returns 0 for success, non-zero for failure. */ int mpt3sas_config_get_volume_wwid(struct MPT3SAS_ADAPTER *ioc, u16 volume_handle, u64 *wwid) { Mpi2ConfigReply_t mpi_reply; Mpi2RaidVolPage1_t raid_vol_pg1; *wwid = 0; if (!(mpt3sas_config_get_raid_volume_pg1(ioc, &mpi_reply, &raid_vol_pg1, MPI2_RAID_VOLUME_PGAD_FORM_HANDLE, volume_handle))) { *wwid = le64_to_cpu(raid_vol_pg1.WWID); return 0; } else return -1; }
{ "content_hash": "0547a5201e3f247aff3fc6870882e32f", "timestamp": "", "source": "github", "line_count": 1644, "max_line_length": 80, "avg_line_length": 31.512165450121653, "alnum_prop": 0.7098405590086091, "repo_name": "publicloudapp/csrutil", "id": "e45c4613ef0c3a4a61aca89f5e18d3ba9f4d19d6", "size": "54016", "binary": false, "copies": "758", "ref": "refs/heads/master", "path": "linux-4.3/drivers/scsi/mpt3sas/mpt3sas_config.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3984" }, { "name": "Awk", "bytes": "29136" }, { "name": "C", "bytes": "532969471" }, { "name": "C++", "bytes": "3352303" }, { "name": "Clojure", "bytes": "1489" }, { "name": "Cucumber", "bytes": "4701" }, { "name": "Groff", "bytes": "46775" }, { "name": "Lex", "bytes": "55199" }, { "name": "Makefile", "bytes": "1576284" }, { "name": "Objective-C", "bytes": "521540" }, { "name": "Perl", "bytes": "715196" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "273092" }, { "name": "Shell", "bytes": "343618" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "12797" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "114559" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" /> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" /> <title>StructPollfd - Android SDK | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto+Condensed"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../assets/css/default.css?v=7" rel="stylesheet" type="text/css"> <!-- FULLSCREEN STYLESHEET --> <link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../"; var metaTags = []; var devsite = false; </script> <script src="../../../assets/js/docs.js?v=6" type="text/javascript"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-5831155-1', 'android.com'); ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker); ga('send', 'pageview'); ga('universal.send', 'pageview'); // Send page view for new tracker. </script> </head> <body class="gc-documentation develop reference" itemscope itemtype="http://schema.org/Article"> <div id="doc-api-level" class="21" style="display:none"></div> <a name="top"></a> <a name="top"></a> <!-- dialog to prompt lang pref change when loaded from hardcoded URL <div id="langMessage" style="display:none"> <div> <div class="lang en"> <p>You requested a page in English, would you like to proceed with this language setting?</p> </div> <div class="lang es"> <p>You requested a page in Spanish (Español), would you like to proceed with this language setting?</p> </div> <div class="lang ja"> <p>You requested a page in Japanese (日本語), would you like to proceed with this language setting?</p> </div> <div class="lang ko"> <p>You requested a page in Korean (한국어), would you like to proceed with this language setting?</p> </div> <div class="lang ru"> <p>You requested a page in Russian (Русский), would you like to proceed with this language setting?</p> </div> <div class="lang zh-cn"> <p>You requested a page in Simplified Chinese (简体中文), would you like to proceed with this language setting?</p> </div> <div class="lang zh-tw"> <p>You requested a page in Traditional Chinese (繁體中文), would you like to proceed with this language setting?</p> </div> <a href="#" class="button yes" onclick="return false;"> <span class="lang en">Yes</span> <span class="lang es">Sí</span> <span class="lang ja">Yes</span> <span class="lang ko">Yes</span> <span class="lang ru">Yes</span> <span class="lang zh-cn">是的</span> <span class="lang zh-tw">没有</span> </a> <a href="#" class="button" onclick="$('#langMessage').hide();return false;"> <span class="lang en">No</span> <span class="lang es">No</span> <span class="lang ja">No</span> <span class="lang ko">No</span> <span class="lang ru">No</span> <span class="lang zh-cn">没有</span> <span class="lang zh-tw">没有</span> </a> </div> </div> --> <!-- Header --> <div id="header-wrapper"> <div class="dac-header" id="header"> <div class="dac-header-inner"> <a class="dac-nav-toggle" data-dac-toggle-nav href="javascript:;" title="Open navigation"> <span class="dac-nav-hamburger"> <span class="dac-nav-hamburger-top"></span> <span class="dac-nav-hamburger-mid"></span> <span class="dac-nav-hamburger-bot"></span> </span> </a> <a class="dac-header-logo" href="../../../index.html"> <img class="dac-header-logo-image" src="../../../assets/images/android_logo.png" srcset="../../../assets/images/android_logo@2x.png 2x" width="32" height="36" alt="Android" /> Developers </a> <ul class="dac-header-crumbs"> <li class="dac-header-crumbs-item"><span class="dac-header-crumbs-link current ">StructPollfd - Android SDK</a></li> </ul> <div class="dac-header-search" id="search-container"> <div class="dac-header-search-inner"> <div class="dac-sprite dac-search dac-header-search-btn" id="search-btn"></div> <form class="dac-header-search-form" onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../')" onkeyup="return search_changed(event, false, '../../../')" class="dac-header-search-input" placeholder="Search" /> <a class="dac-header-search-close hide" id="search-close">close</a> </form> </div><!-- end dac-header-search-inner --> </div><!-- end dac-header-search --> <div class="search_filtered_wrapper"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> <div class="child-card samples no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> <a class="dac-header-console-btn" href="https://play.google.com/apps/publish/"> <span class="dac-sprite dac-google-play"></span> <span class="dac-visible-desktop-inline">Developer</span> Console </a> </div><!-- end header-wrap.wrap --> </div><!-- end header --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> </div> <!--end header-wrapper --> <!-- Navigation--> <nav class="dac-nav"> <div class="dac-nav-dimmer" data-dac-toggle-nav></div> <ul class="dac-nav-list" data-dac-nav> <li class="dac-nav-item dac-nav-head"> <a class="dac-nav-link dac-nav-logo" data-dac-toggle-nav href="javascript:;" title="Close navigation"> <img class="dac-logo-image" src="../../../assets/images/android_logo.png" srcset="../../../assets/images/android_logo@2x.png 2x" width="32" height="36" alt="Android" /> Developers </a> </li> <li class="dac-nav-item home"> <a class="dac-nav-link dac-visible-mobile-block" href="../../../index.html">Home</a> <ul class="dac-nav-secondary about"> <li class="dac-nav-item about"> <a class="dac-nav-link" href="../../../about/index.html">Android</a> </li> <li class="dac-nav-item wear"> <a class="dac-nav-link" href="../../../wear/index.html">Wear</a> </li> <li class="dac-nav-item tv"> <a class="dac-nav-link" href="../../../tv/index.html">TV</a> </li> <li class="dac-nav-item auto"> <a class="dac-nav-link" href="../../../auto/index.html">Auto</a> </li> </ul> </li> <li class="dac-nav-item design"> <a class="dac-nav-link" href="../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar">Design</a> </li> <li class="dac-nav-item develop"> <a class="dac-nav-link" href="../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar">Develop</a> <ul class="dac-nav-secondary develop"> <li class="dac-nav-item training"> <a class="dac-nav-link" href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación">Training</a> </li> <li class="dac-nav-item guide"> <a class="dac-nav-link" href="../../../guide/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API">API Guides</a> </li> <li class="dac-nav-item reference"> <a class="dac-nav-link" href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia">Reference</a> </li> <li class="dac-nav-item tools"> <a class="dac-nav-link" href="../../../sdk/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas">Tools</a></li> <li class="dac-nav-item google"> <a class="dac-nav-link" href="../../../google/index.html">Google Services</a> </li> <li class="dac-nav-item preview"> <a class="dac-nav-link" href="../../../preview/index.html">Preview</a> </li> </ul> </li> <li class="dac-nav-item distribute"> <a class="dac-nav-link" href="../../../distribute/googleplay/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir">Distribute</a> <ul class="dac-nav-secondary distribute"> <li class="dac-nav-item googleplay"> <a class="dac-nav-link" href="../../../distribute/googleplay/index.html">Google Play</a></li> <li class="dac-nav-item essentials"> <a class="dac-nav-link" href="../../../distribute/essentials/index.html">Essentials</a></li> <li class="dac-nav-item users"> <a class="dac-nav-link" href="../../../distribute/users/index.html">Get Users</a></li> <li class="dac-nav-item engage"> <a class="dac-nav-link" href="../../../distribute/engage/index.html">Engage &amp; Retain</a></li> <li class="dac-nav-item monetize"> <a class="dac-nav-link" href="../../../distribute/monetize/index.html">Earn</a> </li> <li class="dac-nav-item analyze"> <a class="dac-nav-link" href="../../../distribute/analyze/index.html">Analyze</a> </li> <li class="dac-nav-item stories"> <a class="dac-nav-link" href="../../../distribute/stories/index.html">Stories</a> </li> </ul> </li> </ul> </nav> <!-- end navigation--> <div class="wrap clearfix" id="body-content"><div class="cols"> <div class="col-4 dac-hidden-mobile" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav"> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled" title="Select your target API level to dim unavailable APIs">API level: </label> <div class="select-wrapper"> <select id="apiLevelSelector"> <!-- option elements added by buildApiLevelSelector() --> </select> </div> </div><!-- end toggle --> <div id="api-nav-title">Android APIs</div> </div><!-- end nav header --> <script> var SINCE_DATA = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23' ]; buildApiLevelSelector(); </script> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav" class="scroll-pane"> <ul> <li class="api apilevel-1"> <a href="../../../reference/android/package-summary.html">android</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/accessibilityservice/package-summary.html">android.accessibilityservice</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/accounts/package-summary.html">android.accounts</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/animation/package-summary.html">android.animation</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/annotation/package-summary.html">android.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/app/package-summary.html">android.app</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/admin/package-summary.html">android.app.admin</a></li> <li class="api apilevel-23"> <a href="../../../reference/android/app/assist/package-summary.html">android.app.assist</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/backup/package-summary.html">android.app.backup</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/app/job/package-summary.html">android.app.job</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/app/usage/package-summary.html">android.app.usage</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/appwidget/package-summary.html">android.appwidget</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/bluetooth/package-summary.html">android.bluetooth</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/bluetooth/le/package-summary.html">android.bluetooth.le</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/package-summary.html">android.content</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/pm/package-summary.html">android.content.pm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/res/package-summary.html">android.content.res</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/package-summary.html">android.database</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/sqlite/package-summary.html">android.database.sqlite</a></li> <li class="api apilevel-"> <a href="../../../reference/android/databinding/package-summary.html">android.databinding</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/drm/package-summary.html">android.drm</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/gesture/package-summary.html">android.gesture</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/package-summary.html">android.graphics</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/package-summary.html">android.graphics.drawable</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/shapes/package-summary.html">android.graphics.drawable.shapes</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/graphics/pdf/package-summary.html">android.graphics.pdf</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/hardware/package-summary.html">android.hardware</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/hardware/camera2/package-summary.html">android.hardware.camera2</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/hardware/camera2/params/package-summary.html">android.hardware.camera2.params</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/hardware/display/package-summary.html">android.hardware.display</a></li> <li class="api apilevel-23"> <a href="../../../reference/android/hardware/fingerprint/package-summary.html">android.hardware.fingerprint</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/hardware/input/package-summary.html">android.hardware.input</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/hardware/usb/package-summary.html">android.hardware.usb</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/inputmethodservice/package-summary.html">android.inputmethodservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/location/package-summary.html">android.location</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/media/package-summary.html">android.media</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/media/audiofx/package-summary.html">android.media.audiofx</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/media/browse/package-summary.html">android.media.browse</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/media/effect/package-summary.html">android.media.effect</a></li> <li class="api apilevel-23"> <a href="../../../reference/android/media/midi/package-summary.html">android.media.midi</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/media/projection/package-summary.html">android.media.projection</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/media/session/package-summary.html">android.media.session</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/media/tv/package-summary.html">android.media.tv</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/mtp/package-summary.html">android.mtp</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/package-summary.html">android.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/http/package-summary.html">android.net.http</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/nsd/package-summary.html">android.net.nsd</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/net/rtp/package-summary.html">android.net.rtp</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/net/sip/package-summary.html">android.net.sip</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/wifi/package-summary.html">android.net.wifi</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/net/wifi/p2p/package-summary.html">android.net.wifi.p2p</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/wifi/p2p/nsd/package-summary.html">android.net.wifi.p2p.nsd</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/nfc/package-summary.html">android.nfc</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/nfc/cardemulation/package-summary.html">android.nfc.cardemulation</a></li> <li class="api apilevel-10"> <a href="../../../reference/android/nfc/tech/package-summary.html">android.nfc.tech</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/opengl/package-summary.html">android.opengl</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/os/package-summary.html">android.os</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/os/storage/package-summary.html">android.os.storage</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/preference/package-summary.html">android.preference</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/package-summary.html">android.print</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/pdf/package-summary.html">android.print.pdf</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/printservice/package-summary.html">android.printservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/provider/package-summary.html">android.provider</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/renderscript/package-summary.html">android.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/sax/package-summary.html">android.sax</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/security/package-summary.html">android.security</a></li> <li class="api apilevel-23"> <a href="../../../reference/android/security/keystore/package-summary.html">android.security.keystore</a></li> <li class="api apilevel-22"> <a href="../../../reference/android/service/carrier/package-summary.html">android.service.carrier</a></li> <li class="api apilevel-23"> <a href="../../../reference/android/service/chooser/package-summary.html">android.service.chooser</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/service/dreams/package-summary.html">android.service.dreams</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/service/media/package-summary.html">android.service.media</a></li> <li class="api apilevel-18"> <a href="../../../reference/android/service/notification/package-summary.html">android.service.notification</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/service/restrictions/package-summary.html">android.service.restrictions</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/service/textservice/package-summary.html">android.service.textservice</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/service/voice/package-summary.html">android.service.voice</a></li> <li class="api apilevel-7"> <a href="../../../reference/android/service/wallpaper/package-summary.html">android.service.wallpaper</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/speech/package-summary.html">android.speech</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/speech/tts/package-summary.html">android.speech.tts</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/annotation/package-summary.html">android.support.annotation</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/app/recommendation/package-summary.html">android.support.app.recommendation</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/customtabs/package-summary.html">android.support.customtabs</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/design/package-summary.html">android.support.design</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/design/widget/package-summary.html">android.support.design.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/multidex/package-summary.html">android.support.multidex</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/percent/package-summary.html">android.support.percent</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v13/app/package-summary.html">android.support.v13.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v14/preference/package-summary.html">android.support.v14.preference</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/package-summary.html">android.support.v17.leanback</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/app/package-summary.html">android.support.v17.leanback.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/database/package-summary.html">android.support.v17.leanback.database</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/graphics/package-summary.html">android.support.v17.leanback.graphics</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/system/package-summary.html">android.support.v17.leanback.system</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/leanback/widget/package-summary.html">android.support.v17.leanback.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v17/preference/package-summary.html">android.support.v17.preference</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/accessibilityservice/package-summary.html">android.support.v4.accessibilityservice</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/animation/package-summary.html">android.support.v4.animation</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/app/package-summary.html">android.support.v4.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/package-summary.html">android.support.v4.content</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/pm/package-summary.html">android.support.v4.content.pm</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/res/package-summary.html">android.support.v4.content.res</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/database/package-summary.html">android.support.v4.database</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/graphics/package-summary.html">android.support.v4.graphics</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/graphics/drawable/package-summary.html">android.support.v4.graphics.drawable</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/hardware/display/package-summary.html">android.support.v4.hardware.display</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/hardware/fingerprint/package-summary.html">android.support.v4.hardware.fingerprint</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/media/package-summary.html">android.support.v4.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/media/session/package-summary.html">android.support.v4.media.session</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/net/package-summary.html">android.support.v4.net</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/os/package-summary.html">android.support.v4.os</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/print/package-summary.html">android.support.v4.print</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/provider/package-summary.html">android.support.v4.provider</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/text/package-summary.html">android.support.v4.text</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/util/package-summary.html">android.support.v4.util</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/package-summary.html">android.support.v4.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/accessibility/package-summary.html">android.support.v4.view.accessibility</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/animation/package-summary.html">android.support.v4.view.animation</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/widget/package-summary.html">android.support.v4.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/app/package-summary.html">android.support.v7.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/appcompat/package-summary.html">android.support.v7.appcompat</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/cardview/package-summary.html">android.support.v7.cardview</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/graphics/package-summary.html">android.support.v7.graphics</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/graphics/drawable/package-summary.html">android.support.v7.graphics.drawable</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/gridlayout/package-summary.html">android.support.v7.gridlayout</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/media/package-summary.html">android.support.v7.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/mediarouter/package-summary.html">android.support.v7.mediarouter</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/preference/package-summary.html">android.support.v7.preference</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/recyclerview/package-summary.html">android.support.v7.recyclerview</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/util/package-summary.html">android.support.v7.util</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/view/package-summary.html">android.support.v7.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/widget/package-summary.html">android.support.v7.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/widget/helper/package-summary.html">android.support.v7.widget.helper</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/widget/util/package-summary.html">android.support.v7.widget.util</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v8/renderscript/package-summary.html">android.support.v8.renderscript</a></li> <li class="selected api apilevel-21"> <a href="../../../reference/android/system/package-summary.html">android.system</a></li> <li class="api apilevel-21"> <a href="../../../reference/android/telecom/package-summary.html">android.telecom</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/telephony/package-summary.html">android.telephony</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/telephony/cdma/package-summary.html">android.telephony.cdma</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/telephony/gsm/package-summary.html">android.telephony.gsm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/package-summary.html">android.test</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/mock/package-summary.html">android.test.mock</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/suitebuilder/package-summary.html">android.test.suitebuilder</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/suitebuilder/annotation/package-summary.html">android.test.suitebuilder.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/package-summary.html">android.text</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/text/format/package-summary.html">android.text.format</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/method/package-summary.html">android.text.method</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/style/package-summary.html">android.text.style</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/util/package-summary.html">android.text.util</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/transition/package-summary.html">android.transition</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/util/package-summary.html">android.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/view/package-summary.html">android.view</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/view/accessibility/package-summary.html">android.view.accessibility</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/view/animation/package-summary.html">android.view.animation</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/view/inputmethod/package-summary.html">android.view.inputmethod</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/view/textservice/package-summary.html">android.view.textservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/webkit/package-summary.html">android.webkit</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/widget/package-summary.html">android.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/internal/backup/package-summary.html">com.android.internal.backup</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/internal/logging/package-summary.html">com.android.internal.logging</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/internal/os/package-summary.html">com.android.internal.os</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/internal/statusbar/package-summary.html">com.android.internal.statusbar</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/internal/widget/package-summary.html">com.android.internal.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/com/android/test/runner/package-summary.html">com.android.test.runner</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/annotation/package-summary.html">dalvik.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/bytecode/package-summary.html">dalvik.bytecode</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/system/package-summary.html">dalvik.system</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/awt/font/package-summary.html">java.awt.font</a></li> <li class="api apilevel-3"> <a href="../../../reference/java/beans/package-summary.html">java.beans</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/io/package-summary.html">java.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/package-summary.html">java.lang</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/annotation/package-summary.html">java.lang.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/ref/package-summary.html">java.lang.ref</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/reflect/package-summary.html">java.lang.reflect</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/math/package-summary.html">java.math</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/net/package-summary.html">java.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/package-summary.html">java.nio</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/package-summary.html">java.nio.channels</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/spi/package-summary.html">java.nio.channels.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/package-summary.html">java.nio.charset</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/spi/package-summary.html">java.nio.charset.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/package-summary.html">java.security</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/acl/package-summary.html">java.security.acl</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/cert/package-summary.html">java.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/interfaces/package-summary.html">java.security.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/spec/package-summary.html">java.security.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/sql/package-summary.html">java.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/text/package-summary.html">java.text</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/package-summary.html">java.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/package-summary.html">java.util.concurrent</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/jar/package-summary.html">java.util.jar</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/logging/package-summary.html">java.util.logging</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/prefs/package-summary.html">java.util.prefs</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/regex/package-summary.html">java.util.regex</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/zip/package-summary.html">java.util.zip</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/package-summary.html">javax.crypto</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/interfaces/package-summary.html">javax.crypto.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/spec/package-summary.html">javax.crypto.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/egl/package-summary.html">javax.microedition.khronos.egl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/opengles/package-summary.html">javax.microedition.khronos.opengles</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/package-summary.html">javax.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/ssl/package-summary.html">javax.net.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/package-summary.html">javax.security.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/callback/package-summary.html">javax.security.auth.callback</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/login/package-summary.html">javax.security.auth.login</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/x500/package-summary.html">javax.security.auth.x500</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/cert/package-summary.html">javax.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/sql/package-summary.html">javax.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/package-summary.html">javax.xml</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/datatype/package-summary.html">javax.xml.datatype</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/namespace/package-summary.html">javax.xml.namespace</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/parsers/package-summary.html">javax.xml.parsers</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/package-summary.html">javax.xml.transform</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/dom/package-summary.html">javax.xml.transform.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/sax/package-summary.html">javax.xml.transform.sax</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/stream/package-summary.html">javax.xml.transform.stream</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/validation/package-summary.html">javax.xml.validation</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/xpath/package-summary.html">javax.xml.xpath</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/framework/package-summary.html">junit.framework</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/runner/package-summary.html">junit.runner</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/package-summary.html">org.apache.http.conn</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/scheme/package-summary.html">org.apache.http.conn.scheme</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/ssl/package-summary.html">org.apache.http.conn.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/params/package-summary.html">org.apache.http.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/json/package-summary.html">org.json</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/w3c/dom/package-summary.html">org.w3c.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/org/w3c/dom/ls/package-summary.html">org.w3c.dom.ls</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/package-summary.html">org.xml.sax</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/ext/package-summary.html">org.xml.sax.ext</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/package-summary.html">org.xmlpull.v1</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/sax2/package-summary.html">org.xmlpull.v1.sax2</a></li> </ul><br/> </div> <!-- end packages-nav --> </div> <!-- end resize-packages --> <div id="classes-nav" class="scroll-pane"> <ul> <li><h2>Classes</h2> <ul> <li class="api apilevel-21"><a href="../../../reference/android/system/Os.html">Os</a></li> <li class="api apilevel-21"><a href="../../../reference/android/system/OsConstants.html">OsConstants</a></li> <li class="selected api apilevel-21"><a href="../../../reference/android/system/StructPollfd.html">StructPollfd</a></li> <li class="api apilevel-21"><a href="../../../reference/android/system/StructStat.html">StructStat</a></li> <li class="api apilevel-21"><a href="../../../reference/android/system/StructStatVfs.html">StructStatVfs</a></li> <li class="api apilevel-21"><a href="../../../reference/android/system/StructUtsname.html">StructUtsname</a></li> </ul> </li> <li><h2>Exceptions</h2> <ul> <li class="api apilevel-21"><a href="../../../reference/android/system/ErrnoException.html">ErrnoException</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none" class="scroll-pane"> <div id="tree-list"></div> </div><!-- end nav-tree --> </div><!-- end swapper --> <div id="nav-swap"> <a class="fullscreen">fullscreen</a> <a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a> </div> </div> <!-- end devdoc-nav --> </div> <!-- end side-nav --> <script type="text/javascript"> // init fullscreen based on user pref var fullscreen = readCookie("fullscreen"); if (fullscreen != 0) { if (fullscreen == "false") { toggleFullscreen(false); } else { toggleFullscreen(true); } } // init nav version for mobile if (isMobile) { swapNav(); // tree view should be used on mobile $('#nav-swap').hide(); } else { chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../"); } } // scroll the selected page into view $(document).ready(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); </script> <div class="col-12" id="doc-col"> <div id="api-info-block"> <div class="sum-details-links"> Summary: <a href="#lfields">Fields</a> &#124; <a href="#pubctors">Ctors</a> &#124; <a href="#pubmethods">Methods</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public final class <h1 itemprop="name">StructPollfd</h1> extends <a href="../../../reference/java/lang/Object.html">Object</a><br/> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-21"> <table class="jd-inheritance-table"> <tr> <td colspan="2" class="jd-inheritance-class-cell"><a href="../../../reference/java/lang/Object.html">java.lang.Object</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="1" class="jd-inheritance-class-cell">android.system.StructPollfd</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p itemprop="articleBody">Used as an in/out parameter to <code><a href="../../../reference/android/system/Os.html#poll(android.system.StructPollfd[], int)">poll(StructPollfd[], int)</a></code>. Corresponds to C's <code>struct pollfd</code> from <code>&lt;poll.h&gt;</code>. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- =========== FIELD SUMMARY =========== --> <table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr> <tr class="alt-color api apilevel-21" > <td class="jd-typecol"><nobr> public short</nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/system/StructPollfd.html#events">events</a></td> <td class="jd-descrcol" width="100%"> The events we're interested in. </td> </tr> <tr class=" api apilevel-21" > <td class="jd-typecol"><nobr> public <a href="../../../reference/java/io/FileDescriptor.html">FileDescriptor</a></nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/system/StructPollfd.html#fd">fd</a></td> <td class="jd-descrcol" width="100%"> The file descriptor to poll. </td> </tr> <tr class="alt-color api apilevel-21" > <td class="jd-typecol"><nobr> public short</nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/system/StructPollfd.html#revents">revents</a></td> <td class="jd-descrcol" width="100%"> The events that actually happened. </td> </tr> <tr class=" api apilevel-21" > <td class="jd-typecol"><nobr> public <a href="../../../reference/java/lang/Object.html">Object</a></nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/system/StructPollfd.html#userData">userData</a></td> <td class="jd-descrcol" width="100%"> A non-standard extension that lets callers conveniently map back to the object their fd belongs to. </td> </tr> </table> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr> <tr class="alt-color api apilevel-21" > <td class="jd-typecol"><nobr> </nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/system/StructPollfd.html#StructPollfd()">StructPollfd</a></span>()</nobr> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-21" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/system/StructPollfd.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv"> Returns a string containing a concise, human-readable description of this object. </div> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Object-trigger" src="../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class <a href="../../../reference/java/lang/Object.html">java.lang.Object</a> <div id="inherited-methods-java.lang.Object"> <div id="inherited-methods-java.lang.Object-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Object-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/Object.html">Object</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#clone()">clone</a></span>()</nobr> <div class="jd-descrdiv"> Creates and returns a copy of this <code>Object</code>. </div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> o)</nobr> <div class="jd-descrdiv"> Compares this instance with the specified object and indicates if they are equal. </div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#finalize()">finalize</a></span>()</nobr> <div class="jd-descrdiv"> Invoked when the garbage collector has detected that this instance is no longer reachable. </div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final <a href="../../../reference/java/lang/Class.html">Class</a>&lt;?&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#getClass()">getClass</a></span>()</nobr> <div class="jd-descrdiv"> Returns the unique instance of <code><a href="../../../reference/java/lang/Class.html">Class</a></code> that represents this object's class. </div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode</a></span>()</nobr> <div class="jd-descrdiv"> Returns an integer hash code for this object. </div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notify()">notify</a></span>()</nobr> <div class="jd-descrdiv"> Causes a thread which is waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up. </div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notifyAll()">notifyAll</a></span>()</nobr> <div class="jd-descrdiv"> Causes all threads which are waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up. </div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv"> Returns a string containing a concise, human-readable description of this object. </div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait()">wait</a></span>()</nobr> <div class="jd-descrdiv"> Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object. </div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long, int)">wait</a></span>(long millis, int nanos)</nobr> <div class="jd-descrdiv"> Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires. </div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long)">wait</a></span>(long millis)</nobr> <div class="jd-descrdiv"> Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires. </div> </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- ========= FIELD DETAIL ======== --> <h2>Fields</h2> <A NAME="events"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public short </span> events </h4> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>The events we're interested in. POLLIN corresponds to being in select(2)'s read fd set, POLLOUT to the write fd set. </p></div> </div> </div> <A NAME="fd"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public <a href="../../../reference/java/io/FileDescriptor.html">FileDescriptor</a> </span> fd </h4> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>The file descriptor to poll. </p></div> </div> </div> <A NAME="revents"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public short </span> revents </h4> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>The events that actually happened. </p></div> </div> </div> <A NAME="userData"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public <a href="../../../reference/java/lang/Object.html">Object</a> </span> userData </h4> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>A non-standard extension that lets callers conveniently map back to the object their fd belongs to. This is used by Selector, for example, to associate each FileDescriptor with the corresponding SelectionKey. </p></div> </div> </div> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <h2>Public Constructors</h2> <A NAME="StructPollfd()"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public </span> <span class="sympad">StructPollfd</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <A NAME="toString()"></A> <div class="jd-details api apilevel-21"> <h4 class="jd-details-title"> <span class="normal"> public <a href="../../../reference/java/lang/String.html">String</a> </span> <span class="sympad">toString</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 21</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: <pre> getClass().getName() + '@' + Integer.toHexString(hashCode())</pre> <p>See <a href="../../../reference/java/lang/Object.html#writing_toString">Writing a useful <code>toString</code> method</a> if you intend implementing your own <code>toString</code> method.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>a printable representation of this object. </li></ul> </div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <A NAME="navbar_top"></A> </div> <!-- jd-content --> <div class="wrap"> <div class="dac-footer"> <div class="cols dac-footer-main"> <div class="col-1of2"> <a class="dac-footer-getnews" data-modal-toggle="newsletter" href="javascript:;">Get news &amp; tips <span class="dac-fab dac-primary"><i class="dac-sprite dac-mail"></i></span></a> </div> <div class="col-1of2 dac-footer-reachout"> <div class="dac-footer-contact"> <a class="dac-footer-contact-link" href="http://android-developers.blogspot.com/">Blog</a> <a class="dac-footer-contact-link" href="/support.html">Support</a> </div> <div class="dac-footer-social"> <a class="dac-fab dac-footer-social-link" href="https://www.youtube.com/user/androiddevelopers"><i class="dac-sprite dac-youtube"></i></a> <a class="dac-fab dac-footer-social-link" href="https://plus.google.com/+AndroidDevelopers"><i class="dac-sprite dac-gplus"></i></a> <a class="dac-fab dac-footer-social-link" href="https://twitter.com/AndroidDev"><i class="dac-sprite dac-twitter"></i></a> </div> </div> </div> <hr class="dac-footer-separator"/> <p class="dac-footer-copyright"> Except as noted, this content is licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. For details and restrictions, see the <a href="../../../license.html"> Content License</a>. </p> <p class="dac-footer-build"> Android 6.0&nbsp;r1 &mdash; <script src="../../../timestamp.js" type="text/javascript"></script> <script>document.write(BUILD_TIMESTAMP)</script> </p> <p class="dac-footer-links"> <a href="/about/index.html">About Android</a> <a href="/auto/index.html">Auto</a> <a href="/tv/index.html">TV</a> <a href="/wear/index.html">Wear</a> <a href="/legal.html">Legal</a> <span id="language" class="locales"> <select name="language" onchange="changeLangPref(this.value, true)"> <option value="en" selected="selected">English</option> <option value="es">Español</option> <option value="ja">日本語</option> <option value="ko">한국어</option> <option value="pt-br">Português Brasileiro</option> <option value="ru">Русский</option> <option value="zh-cn">中文(简体)</option> <option value="zh-tw">中文(繁體)</option> </select> </span> </p> </div> </div> <!-- end footer --> <div data-modal="newsletter" data-newsletter data-swap class="dac-modal newsletter"> <div class="dac-modal-container"> <div class="dac-modal-window"> <header class="dac-modal-header"> <button class="dac-modal-header-close" data-modal-toggle><i class="dac-sprite dac-close"></i></button> <div class="dac-swap" data-swap-container> <section class="dac-swap-section dac-active dac-down"> <h2 class="norule dac-modal-header-title">Get the latest Android developer news and tips that will help you find success on Google Play.</h2> <p class="dac-modal-header-subtitle">&#42; Required Fields</p> </section> <section class="dac-swap-section dac-up"> <h2 class="norule dac-modal-header-title">Hooray!</h2> </section> </div> </header> <div class="dac-swap" data-swap-container> <section class="dac-swap-section dac-active dac-left"> <form action="https://docs.google.com/forms/d/1QgnkzbEJIDu9lMEea0mxqWrXUJu0oBCLD7ar23V0Yys/formResponse" class="dac-form" method="post" target="dac-newsletter-iframe"> <section class="dac-modal-content"> <fieldset class="dac-form-fieldset"> <div class="cols"> <div class="col-1of2 newsletter-leftCol"> <div class="dac-form-input-group"> <label for="newsletter-full-name" class="dac-form-floatlabel">Full name</label> <input type="text" class="dac-form-input" name="entry.1357890476" id="newsletter-full-name" required> <span class="dac-form-required">*</span> </div> <div class="dac-form-input-group"> <label for="newsletter-email" class="dac-form-floatlabel">Email address</label> <input type="email" class="dac-form-input" name="entry.472100832" id="newsletter-email" required> <span class="dac-form-required">*</span> </div> </div> <div class="col-1of2 newsletter-rightCol"> <div class="dac-form-input-group"> <label for="newsletter-company" class="dac-form-floatlabel">Company / developer name</label> <input type="text" class="dac-form-input" name="entry.1664780309" id="newsletter-company"> </div> <div class="dac-form-input-group"> <label for="newsletter-play-store" class="dac-form-floatlabel">One of your Play Store app URLs</label> <input type="url" class="dac-form-input" name="entry.47013838" id="newsletter-play-store" required> <span class="dac-form-required">*</span> </div> </div> </div> </fieldset> <fieldset class="dac-form-fieldset"> <div class="cols"> <div class="col-1of2 newsletter-leftCol"> <legend class="dac-form-legend">Which best describes your business:<span class="dac-form-required">*</span> </legend> <div class="dac-form-radio-group"> <input type="radio" value="Apps" class="dac-form-radio" name="entry.1796324055" id="newsletter-business-type-app" required> <label for="newsletter-business-type-app" class="dac-form-radio-button"></label> <label for="newsletter-business-type-app" class="dac-form-label">Apps</label> </div> <div class="dac-form-radio-group"> <input type="radio" value="Games" class="dac-form-radio" name="entry.1796324055" id="newsletter-business-type-games" required> <label for="newsletter-business-type-games" class="dac-form-radio-button"></label> <label for="newsletter-business-type-games" class="dac-form-label">Games</label> </div> <div class="dac-form-radio-group"> <input type="radio" value="Apps and Games" class="dac-form-radio" name="entry.1796324055" id="newsletter-business-type-appsgames" required> <label for="newsletter-business-type-appsgames" class="dac-form-radio-button"></label> <label for="newsletter-business-type-appsgames" class="dac-form-label">Apps &amp; Games</label> </div> </div> <div class="col-1of2 newsletter-rightCol newsletter-checkboxes"> <div class="dac-form-radio-group"> <div class="dac-media"> <div class="dac-media-figure"> <input type="checkbox" class="dac-form-checkbox" name="entry.732309842" id="newsletter-add" required value="Add me to the mailing list for the monthly newsletter and occasional emails about development and Google Play opportunities."> <label for="newsletter-add" class="dac-form-checkbox-button"></label> </div> <div class="dac-media-body"> <label for="newsletter-add" class="dac-form-label dac-form-aside">Add me to the mailing list for the monthly newsletter and occasional emails about development and Google Play opportunities.<span class="dac-form-required">*</span></label> </div> </div> </div> <div class="dac-form-radio-group"> <div class="dac-media"> <div class="dac-media-figure"> <input type="checkbox" class="dac-form-checkbox" name="entry.2045036090" id="newsletter-terms" required value="I acknowledge that the information provided in this form will be subject to Google's privacy policy (https://www.google.com/policies/privacy/)."> <label for="newsletter-terms" class="dac-form-checkbox-button"></label> </div> <div class="dac-media-body"> <label for="newsletter-terms" class="dac-form-label dac-form-aside">I acknowledge that the information provided in this form will be subject to <a href="https://www.google.com/policies/privacy/">Google's privacy policy</a>.<span class="dac-form-required">*</span></label> </div> </div> </div> </div> </div> </fieldset> </section> <footer class="dac-modal-footer"> <div class="cols"> <div class="col-2of5"> </div> </div> <button type="submit" value="Submit" class="dac-fab dac-primary dac-large dac-modal-action"><i class="dac-sprite dac-arrow-right"></i></button> </footer> </form> </section> <section class="dac-swap-section dac-right"> <div class="dac-modal-content"> <p class="newsletter-success-message"> You have successfully signed up for the latest Android developer news and tips. </p> </div> </section> </div> </div> </div> </div> <!-- end footer --> </div><!-- end doc-content --> </div> <!-- end .cols --> </div> <!-- end body-content --> </body> </html>
{ "content_hash": "24b590a3474b1323a6cf5593790c0990", "timestamp": "", "source": "github", "line_count": 2053, "max_line_length": 297, "avg_line_length": 36.90501704822211, "alnum_prop": 0.5908191009159781, "repo_name": "anas-ambri/androidcompat", "id": "8951e05d7eb4e2634909bc9253a525e4cd6854db", "size": "76093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/android/system/StructPollfd.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "261862" }, { "name": "HTML", "bytes": "581707522" }, { "name": "JavaScript", "bytes": "639438" }, { "name": "Makefile", "bytes": "229" }, { "name": "Shell", "bytes": "138" } ], "symlink_target": "" }
#ifndef DSYNC_MAILBOX_TREE_H #define DSYNC_MAILBOX_TREE_H #include "guid.h" #include "mail-error.h" struct mail_namespace; struct dsync_brain; enum dsync_mailbox_trees_sync_type { /* two-way sync for both mailboxes */ DSYNC_MAILBOX_TREES_SYNC_TYPE_TWOWAY, /* make remote tree look exactly like the local tree */ DSYNC_MAILBOX_TREES_SYNC_TYPE_PRESERVE_LOCAL, /* make local tree look exactly like the remote tree */ DSYNC_MAILBOX_TREES_SYNC_TYPE_PRESERVE_REMOTE }; enum dsync_mailbox_trees_sync_flags { /* Enable debugging */ DSYNC_MAILBOX_TREES_SYNC_FLAG_DEBUG = 0x01, /* Show ourself as "master brain" in the debug output */ DSYNC_MAILBOX_TREES_SYNC_FLAG_MASTER_BRAIN = 0x02 }; enum dsync_mailbox_node_existence { /* this is just a filler node for children or for subscription deletion */ DSYNC_MAILBOX_NODE_NONEXISTENT = 0, /* if mailbox GUID is set, the mailbox exists. otherwise the directory exists. */ DSYNC_MAILBOX_NODE_EXISTS, /* if mailbox GUID is set, the mailbox has been deleted. otherwise the directory has been deleted. */ DSYNC_MAILBOX_NODE_DELETED }; struct dsync_mailbox_node { struct dsync_mailbox_node *parent, *next, *first_child; /* namespace where this node belongs to */ struct mail_namespace *ns; /* this node's name (not including parents) */ const char *name; /* mailbox GUID, or full of zeros if this is about a directory name */ guid_128_t mailbox_guid; /* mailbox's UIDVALIDITY/UIDNEXT (may be 0 if not assigned yet) */ uint32_t uid_validity, uid_next; /* existence of this mailbox/directory. doesn't affect subscription state. */ enum dsync_mailbox_node_existence existence; /* last time the mailbox/directory was created/renamed, 0 if not known */ time_t last_renamed_or_created; /* last time the subscription state was changed, 0 if not known */ time_t last_subscription_change; /* is this mailbox or directory subscribed? */ unsigned int subscribed:1; /* Internal syncing flags: */ unsigned int sync_delayed_guid_change:1; unsigned int sync_temporary_name:1; }; ARRAY_DEFINE_TYPE(dsync_mailbox_node, struct dsync_mailbox_node *); #define dsync_mailbox_node_guids_equal(node1, node2) \ (memcmp((node1)->mailbox_guid, (node2)->mailbox_guid, \ sizeof(guid_128_t)) == 0) #define dsync_mailbox_node_is_dir(node) \ guid_128_is_empty((node)->mailbox_guid) enum dsync_mailbox_delete_type { /* Delete mailbox by given GUID */ DSYNC_MAILBOX_DELETE_TYPE_MAILBOX = 1, /* Delete mailbox directory by given SHA1 name */ DSYNC_MAILBOX_DELETE_TYPE_DIR, /* Unsubscribe mailbox by given SHA1 name */ DSYNC_MAILBOX_DELETE_TYPE_UNSUBSCRIBE, }; struct dsync_mailbox_delete { enum dsync_mailbox_delete_type type; guid_128_t guid; time_t timestamp; }; enum dsync_mailbox_tree_sync_type { DSYNC_MAILBOX_TREE_SYNC_TYPE_CREATE_BOX, DSYNC_MAILBOX_TREE_SYNC_TYPE_CREATE_DIR, DSYNC_MAILBOX_TREE_SYNC_TYPE_DELETE_BOX, DSYNC_MAILBOX_TREE_SYNC_TYPE_DELETE_DIR, /* Rename given mailbox name and its children */ DSYNC_MAILBOX_TREE_SYNC_TYPE_RENAME, DSYNC_MAILBOX_TREE_SYNC_TYPE_SUBSCRIBE, DSYNC_MAILBOX_TREE_SYNC_TYPE_UNSUBSCRIBE }; struct dsync_mailbox_tree_sync_change { enum dsync_mailbox_tree_sync_type type; /* for all types: */ struct mail_namespace *ns; const char *full_name; /* for create_box and delete_box: */ guid_128_t mailbox_guid; /* for create_box: */ uint32_t uid_validity; /* for rename: */ const char *rename_dest_name; }; struct dsync_mailbox_tree *dsync_mailbox_tree_init(char sep, char alt_char); void dsync_mailbox_tree_deinit(struct dsync_mailbox_tree **tree); /* Lookup a mailbox node by name. Returns NULL if not known. */ struct dsync_mailbox_node * dsync_mailbox_tree_lookup(struct dsync_mailbox_tree *tree, const char *full_name); /* Lookup a mailbox node by GUID. Returns NULL if not known. The mailbox GUID hash must have been build before calling this. */ struct dsync_mailbox_node * dsync_mailbox_tree_lookup_guid(struct dsync_mailbox_tree *tree, const guid_128_t guid); /* Lookup or create a mailbox node by name. */ struct dsync_mailbox_node * dsync_mailbox_tree_get(struct dsync_mailbox_tree *tree, const char *full_name); /* Returns full name for the given mailbox node. */ const char *dsync_mailbox_node_get_full_name(const struct dsync_mailbox_tree *tree, const struct dsync_mailbox_node *node); /* Copy everything from src to dest, except name and hierarchy pointers */ void dsync_mailbox_node_copy_data(struct dsync_mailbox_node *dest, const struct dsync_mailbox_node *src); /* Add nodes to tree from the given namespace. If box_name or box_guid is non-NULL, add only that mailbox to the tree. */ int dsync_mailbox_tree_fill(struct dsync_mailbox_tree *tree, struct mail_namespace *ns, const char *box_name, const guid_128_t box_guid, const char *const *exclude_mailboxes, enum mail_error *error_r); /* Return all known deleted mailboxes and directories. */ const struct dsync_mailbox_delete * dsync_mailbox_tree_get_deletes(struct dsync_mailbox_tree *tree, unsigned int *count_r); /* Return mailbox node for a given delete record, or NULL if it doesn't exist. The delete record is intended to come from another tree, possibly with a different hierarchy separator. dsync_mailbox_tree_build_guid_hash() must have been called before this. */ struct dsync_mailbox_node * dsync_mailbox_tree_find_delete(struct dsync_mailbox_tree *tree, const struct dsync_mailbox_delete *del); /* Build GUID lookup hash, if it's not already built. Returns 0 if ok, -1 if there are duplicate GUIDs. The nodes with the duplicate GUIDs are returned. */ int dsync_mailbox_tree_build_guid_hash(struct dsync_mailbox_tree *tree, struct dsync_mailbox_node **dup_node1_r, struct dsync_mailbox_node **dup_node2_r); /* Manually add a new node to hash. */ int dsync_mailbox_tree_guid_hash_add(struct dsync_mailbox_tree *tree, struct dsync_mailbox_node *node, struct dsync_mailbox_node **old_node_r); /* Set remote separator used for directory deletions in dsync_mailbox_tree_find_delete() */ void dsync_mailbox_tree_set_remote_sep(struct dsync_mailbox_tree *tree, char remote_sep); /* Iterate through all nodes in a tree (depth-first) */ struct dsync_mailbox_tree_iter * dsync_mailbox_tree_iter_init(struct dsync_mailbox_tree *tree); bool dsync_mailbox_tree_iter_next(struct dsync_mailbox_tree_iter *iter, const char **full_name_r, struct dsync_mailbox_node **node_r); void dsync_mailbox_tree_iter_deinit(struct dsync_mailbox_tree_iter **iter); /* Sync local and remote trees so at the end they're exactly the same. Return changes done to local tree. */ struct dsync_mailbox_tree_sync_ctx * dsync_mailbox_trees_sync_init(struct dsync_mailbox_tree *local_tree, struct dsync_mailbox_tree *remote_tree, enum dsync_mailbox_trees_sync_type sync_type, enum dsync_mailbox_trees_sync_flags sync_flags); const struct dsync_mailbox_tree_sync_change * dsync_mailbox_trees_sync_next(struct dsync_mailbox_tree_sync_ctx *ctx); void dsync_mailbox_trees_sync_deinit(struct dsync_mailbox_tree_sync_ctx **ctx); const char *dsync_mailbox_node_to_string(const struct dsync_mailbox_node *node); const char * dsync_mailbox_delete_type_to_string(enum dsync_mailbox_delete_type type); #endif
{ "content_hash": "2f9582ad4bd9eff7b6bcd6ad9e25ca95", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 83, "avg_line_length": 37.48730964467005, "alnum_prop": 0.7305348679756263, "repo_name": "mswart/dovecot2deb", "id": "7292afdfb43d6d63389c747da7043aba5ed0b4f5", "size": "7385", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/doveadm/dsync/dsync-mailbox-tree.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "11143751" }, { "name": "C++", "bytes": "88943" }, { "name": "Logos", "bytes": "3470" }, { "name": "Objective-C", "bytes": "1543" }, { "name": "Perl", "bytes": "9273" }, { "name": "Python", "bytes": "1626" }, { "name": "Shell", "bytes": "358811" } ], "symlink_target": "" }