text
stringlengths
2
1.04M
meta
dict
package org.innovateuk.ifs.activitylog.service; import org.innovateuk.ifs.activitylog.resource.ActivityLogResource; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.service.BaseRestService; import org.springframework.stereotype.Service; import java.util.List; import static org.innovateuk.ifs.commons.service.ParameterizedTypeReferences.activityLogResourceListType; @Service public class ActivityLogRestServiceImpl extends BaseRestService implements ActivityLogRestService { @Override public RestResult<List<ActivityLogResource>> findByApplicationId(long applicationId) { return getWithRestResult(String.format("/activity-log?applicationId=%d", applicationId), activityLogResourceListType()); } }
{ "content_hash": "f3f45a56217b3496111ee931e33a08bd", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 128, "avg_line_length": 39.89473684210526, "alnum_prop": 0.8324538258575198, "repo_name": "InnovateUKGitHub/innovation-funding-service", "id": "57ccb471a386a282a5ca3697e842843a25fd2a78", "size": "758", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "common/ifs-rest-api-service/src/main/java/org/innovateuk/ifs/activitylog/service/ActivityLogRestServiceImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1972" }, { "name": "HTML", "bytes": "6342985" }, { "name": "Java", "bytes": "26591674" }, { "name": "JavaScript", "bytes": "269444" }, { "name": "Python", "bytes": "58983" }, { "name": "RobotFramework", "bytes": "3317394" }, { "name": "SCSS", "bytes": "100274" }, { "name": "Shell", "bytes": "60248" } ], "symlink_target": "" }
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // define the schema for our user model var userSchema = mongoose.Schema({ email : String, password : String }); // methods ====================== // generating a hash userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; // create the model for users and expose it to our app module.exports = mongoose.model('User', userSchema);
{ "content_hash": "5ad4cd689429f816650fc3595e49b642", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 66, "avg_line_length": 28.347826086956523, "alnum_prop": 0.6947852760736196, "repo_name": "mohamadir/15-minutes", "id": "255e62f6f03daadedf6e93443d34802714ceffbd", "size": "701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "temp/app/models/user.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "826538" }, { "name": "HTML", "bytes": "79649" }, { "name": "JavaScript", "bytes": "3588288" } ], "symlink_target": "" }
<?php namespace Mailer\AppBundle\Twig; class AppExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('ellipse', array($this, 'ellipseFilter')), ); } public function ellipseFilter($str, $length = 30) { if (strlen($str) <= $length) { return $str; } return substr($str, 0, $length - 3).'...'; } public function getName() { return 'app_extension'; } }
{ "content_hash": "8ad5b01813f4afb8658b2f1ae1dbeb29", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 77, "avg_line_length": 18.962962962962962, "alnum_prop": 0.541015625, "repo_name": "fweber-de/imap-mailer-client", "id": "e7e1acaf0ad61b0243a51ed34b6462e55f1ee6d1", "size": "512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Mailer/AppBundle/Twig/AppExtension.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "3131" }, { "name": "JavaScript", "bytes": "616" }, { "name": "PHP", "bytes": "77468" } ], "symlink_target": "" }
require 'simplecov' module SimpleCov::Configuration def clean_filters @filters = [] end end SimpleCov.configure do clean_filters load_adapter 'test_frameworks' end ENV["COVERAGE"] && SimpleCov.start do add_filter "/.rvm/" end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'mlbam' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| end
{ "content_hash": "8e57a106e3283bf4a329bfb3631f1605", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 69, "avg_line_length": 20.586206896551722, "alnum_prop": 0.6968174204355109, "repo_name": "mdtjr/mlbam", "id": "3f5b27173255ec882ebab861175a20eb0f71fb0a", "size": "597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5915" } ], "symlink_target": "" }
package tablewriter import ( "bytes" "math" ) var ( nl = []byte{'\n'} sp = []byte{' '} ) const defaultPenalty = 1e5 // Wrap wraps s into a paragraph of lines of length lim, with minimal // raggedness. func WrapString(s string, lim int) ([]string, int) { words := bytes.Split(bytes.Replace(bytes.TrimSpace([]byte(s)), nl, sp, -1), sp) var lines []string max := 0 for _, v := range words { max = len(v) if max > lim { lim = max } } for _, line := range WrapWords(words, 1, lim, defaultPenalty) { lines = append(lines, string(bytes.Join(line, sp))) } return lines, lim } // WrapWords is the low-level line-breaking algorithm, useful if you need more // control over the details of the text wrapping process. For most uses, either // Wrap or WrapBytes will be sufficient and more convenient. // // WrapWords splits a list of words into lines with minimal "raggedness", // treating each byte as one unit, accounting for spc units between adjacent // words on each line, and attempting to limit lines to lim units. Raggedness // is the total error over all lines, where error is the square of the // difference of the length of the line and lim. Too-long lines (which only // happen when a single word is longer than lim units) have pen penalty units // added to the error. func WrapWords(words [][]byte, spc, lim, pen int) [][][]byte { n := len(words) length := make([][]int, n) for i := 0; i < n; i++ { length[i] = make([]int, n) length[i][i] = len(words[i]) for j := i + 1; j < n; j++ { length[i][j] = length[i][j-1] + spc + len(words[j]) } } nbrk := make([]int, n) cost := make([]int, n) for i := range cost { cost[i] = math.MaxInt32 } for i := n - 1; i >= 0; i-- { if length[i][n-1] <= lim { cost[i] = 0 nbrk[i] = n } else { for j := i + 1; j < n; j++ { d := lim - length[i][j-1] c := d*d + cost[j] if length[i][j-1] > lim { c += pen // too-long lines get a worse penalty } if c < cost[i] { cost[i] = c nbrk[i] = j } } } } var lines [][][]byte i := 0 for i < n { lines = append(lines, words[i:nbrk[i]]) i = nbrk[i] } return lines }
{ "content_hash": "a2d1ed6e26a631a2b4498e2fa8171412", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 80, "avg_line_length": 25.28235294117647, "alnum_prop": 0.6035365286179618, "repo_name": "zenoss/tablewriter", "id": "dfb3d3bf3aea9bed7c439dd4148a92b2725847de", "size": "2450", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wrap.go", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2014 The Bazel Authors. All rights reserved. // // 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 com.google.devtools.build.lib.rules; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.packages.Attribute; import com.google.devtools.build.lib.packages.Attribute.AllowedValueSet; import com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition; import com.google.devtools.build.lib.packages.Attribute.SkylarkLateBound; import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.SkylarkAspect; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature; import com.google.devtools.build.lib.syntax.BuiltinFunction; import com.google.devtools.build.lib.syntax.Environment; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.EvalUtils; import com.google.devtools.build.lib.syntax.FuncallExpression; import com.google.devtools.build.lib.syntax.Runtime; import com.google.devtools.build.lib.syntax.SkylarkCallbackFunction; import com.google.devtools.build.lib.syntax.SkylarkDict; import com.google.devtools.build.lib.syntax.SkylarkList; import com.google.devtools.build.lib.syntax.SkylarkSignatureProcessor; import com.google.devtools.build.lib.syntax.SkylarkType; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.syntax.Type.ConversionException; import com.google.devtools.build.lib.syntax.UserDefinedFunction; import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.util.FileTypeSet; import com.google.devtools.build.lib.util.Preconditions; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * A helper class to provide Attr module in Skylark. * * <p>It exposes functions (e.g. 'attr.string', 'attr.label_list', etc.) to Skylark users. The * functions are executed through reflection. As everywhere in Skylark, arguments are type-checked * with the signature and cannot be null. */ @SkylarkModule( name = "attr", namespace = true, category = SkylarkModuleCategory.BUILTIN, doc = "Module for creating new attributes. " + "They are only for use with <a href=\"globals.html#rule\">rule</a> or " + "<a href=\"globals.html#aspect\">aspect</a>." ) public final class SkylarkAttr { // Arguments private static final String ALLOW_FILES_ARG = "allow_files"; private static final String ALLOW_FILES_DOC = "whether File targets are allowed. Can be True, False (default), or a list of file " + "extensions that are allowed (e.g. <code>[\".cc\", \".cpp\"]</code>)."; private static final String ALLOW_RULES_ARG = "allow_rules"; private static final String ALLOW_RULES_DOC = "which rule targets (name of the classes) are allowed. This is deprecated (kept only for " + "compatiblity), use providers instead."; private static final String ASPECTS_ARG = "aspects"; private static final String ASPECT_ARG_DOC = "aspects that should be applied to dependencies specified by this attribute"; private static final String CONFIGURATION_ARG = "cfg"; private static final String CONFIGURATION_DOC = "configuration of the attribute. It can be either \"data\" or \"host\"."; private static final String DEFAULT_ARG = "default"; private static final String DEFAULT_DOC = "the default value of the attribute."; private static final String EXECUTABLE_ARG = "executable"; private static final String EXECUTABLE_DOC = "True if the labels have to be executable. This means the label must refer to an " + "executable file, or to a rule that outputs an executable file. Access the labels " + "with <code>ctx.executable.&lt;attribute_name&gt;</code>."; private static final String FLAGS_ARG = "flags"; private static final String FLAGS_DOC = "deprecated, will be removed"; private static final String MANDATORY_ARG = "mandatory"; private static final String MANDATORY_DOC = "True if the value must be explicitly specified"; private static final String NON_EMPTY_ARG = "non_empty"; private static final String NON_EMPTY_DOC = "True if the attribute must not be empty. Deprecated: Use allow_empty instead."; private static final String ALLOW_EMPTY_ARG = "allow_empty"; private static final String ALLOW_EMPTY_DOC = "True if the attribute can be empty"; private static final String PROVIDERS_ARG = "providers"; private static final String PROVIDERS_DOC = "mandatory providers list. It should be either a list of providers, or a " + "list of lists of providers. Every dependency should provide ALL providers " + "from at least ONE of these lists. A single list of providers will be " + "automatically converted to a list containing one list of providers."; private static final String SINGLE_FILE_ARG = "single_file"; private static final String ALLOW_SINGLE_FILE_ARG = "allow_single_file"; private static final String VALUES_ARG = "values"; private static final String VALUES_DOC = "the list of allowed values for the attribute. An error is raised if any other " + "value is given."; private static boolean containsNonNoneKey(SkylarkDict<String, Object> arguments, String key) { return arguments.containsKey(key) && arguments.get(key) != Runtime.NONE; } private static void setAllowedFileTypes( String attr, Object fileTypesObj, FuncallExpression ast, Attribute.Builder<?> builder) throws EvalException { if (fileTypesObj == Boolean.TRUE) { builder.allowedFileTypes(FileTypeSet.ANY_FILE); } else if (fileTypesObj == Boolean.FALSE) { builder.allowedFileTypes(FileTypeSet.NO_FILE); } else if (fileTypesObj instanceof SkylarkFileType) { // TODO(laurentlb): deprecated, to be removed builder.allowedFileTypes(((SkylarkFileType) fileTypesObj).getFileTypeSet()); } else if (fileTypesObj instanceof SkylarkList) { List<String> arg = SkylarkList.castSkylarkListOrNoneToList( fileTypesObj, String.class, "allow_files argument"); builder.allowedFileTypes(FileType.of(arg)); } else { throw new EvalException( ast.getLocation(), attr + " should be a boolean or a string list"); } } private static Attribute.Builder<?> createAttribute( Type<?> type, SkylarkDict<String, Object> arguments, FuncallExpression ast, Environment env) throws EvalException, ConversionException { // We use an empty name now so that we can set it later. // This trick makes sense only in the context of Skylark (builtin rules should not use it). Attribute.Builder<?> builder = Attribute.attr("", type); Object defaultValue = arguments.get(DEFAULT_ARG); if (!EvalUtils.isNullOrNone(defaultValue)) { if (defaultValue instanceof UserDefinedFunction) { // Late bound attribute. Non label type attributes already caused a type check error. builder.value( new SkylarkLateBound( new SkylarkCallbackFunction((UserDefinedFunction) defaultValue, ast, env))); } else { builder.defaultValue(defaultValue); } } for (String flag : SkylarkList.castSkylarkListOrNoneToList( arguments.get(FLAGS_ARG), String.class, FLAGS_ARG)) { builder.setPropertyFlag(flag); } if (containsNonNoneKey(arguments, MANDATORY_ARG) && (Boolean) arguments.get(MANDATORY_ARG)) { builder.setPropertyFlag("MANDATORY"); } // TODO(laurentlb): Deprecated, remove in August 2016 (use allow_empty instead). if (containsNonNoneKey(arguments, NON_EMPTY_ARG) && (Boolean) arguments.get(NON_EMPTY_ARG)) { builder.setPropertyFlag("NON_EMPTY"); } if (containsNonNoneKey(arguments, ALLOW_EMPTY_ARG) && !(Boolean) arguments.get(ALLOW_EMPTY_ARG)) { builder.setPropertyFlag("NON_EMPTY"); } if (containsNonNoneKey(arguments, EXECUTABLE_ARG) && (Boolean) arguments.get(EXECUTABLE_ARG)) { builder.setPropertyFlag("EXECUTABLE"); } // TODO(laurentlb): Deprecated, remove in August 2016 (use allow_single_file). if (containsNonNoneKey(arguments, SINGLE_FILE_ARG) && (Boolean) arguments.get(SINGLE_FILE_ARG)) { if (containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) { throw new EvalException( ast.getLocation(), "Cannot specify both single_file (deprecated) and allow_single_file"); } builder.setPropertyFlag("SINGLE_ARTIFACT"); } if (containsNonNoneKey(arguments, ALLOW_FILES_ARG) && containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) { throw new EvalException( ast.getLocation(), "Cannot specify both allow_files and allow_single_file"); } if (containsNonNoneKey(arguments, ALLOW_FILES_ARG)) { Object fileTypesObj = arguments.get(ALLOW_FILES_ARG); setAllowedFileTypes(ALLOW_FILES_ARG, fileTypesObj, ast, builder); } else if (containsNonNoneKey(arguments, ALLOW_SINGLE_FILE_ARG)) { Object fileTypesObj = arguments.get(ALLOW_SINGLE_FILE_ARG); setAllowedFileTypes(ALLOW_SINGLE_FILE_ARG, fileTypesObj, ast, builder); builder.setPropertyFlag("SINGLE_ARTIFACT"); } else if (type.equals(BuildType.LABEL) || type.equals(BuildType.LABEL_LIST)) { builder.allowedFileTypes(FileTypeSet.NO_FILE); } Object ruleClassesObj = arguments.get(ALLOW_RULES_ARG); if (ruleClassesObj != null && ruleClassesObj != Runtime.NONE) { builder.allowedRuleClasses( SkylarkList.castSkylarkListOrNoneToList( ruleClassesObj, String.class, "allowed rule classes for attribute definition")); } List<Object> values = SkylarkList.castSkylarkListOrNoneToList( arguments.get(VALUES_ARG), Object.class, VALUES_ARG); if (!Iterables.isEmpty(values)) { builder.allowedValues(new AllowedValueSet(values)); } if (containsNonNoneKey(arguments, PROVIDERS_ARG)) { Object obj = arguments.get(PROVIDERS_ARG); SkylarkType.checkType(obj, SkylarkList.class, PROVIDERS_ARG); boolean isSingleListOfStr = true; for (Object o : (SkylarkList) obj) { isSingleListOfStr = o instanceof String; if (!isSingleListOfStr) { break; } } if (isSingleListOfStr) { builder.mandatoryProviders(((SkylarkList<?>) obj).getContents(String.class, PROVIDERS_ARG)); } else { builder.mandatoryProvidersList(getProvidersList((SkylarkList) obj)); } } if (containsNonNoneKey(arguments, CONFIGURATION_ARG)) { Object trans = arguments.get(CONFIGURATION_ARG); if (trans instanceof ConfigurationTransition) { // TODO(laurentlb): Deprecated, to be removed in August 2016. builder.cfg((ConfigurationTransition) trans); } else if (trans.equals("data")) { builder.cfg(ConfigurationTransition.DATA); } else if (trans.equals("host")) { builder.cfg(ConfigurationTransition.HOST); } else { throw new EvalException(ast.getLocation(), "cfg must be either 'data' or 'host'."); } } return builder; } private static List<List<String>> getProvidersList(SkylarkList skylarkList) throws EvalException { List<List<String>> providersList = new ArrayList<>(); String errorMsg = "Illegal argument: element in '%s' is of unexpected type. " + "Should be list of string, but got %s. " + "Notice: one single list of string as 'providers' is still supported."; for (Object o : skylarkList) { if (!(o instanceof SkylarkList)) { throw new EvalException(null, String.format(errorMsg, PROVIDERS_ARG, EvalUtils.getDataTypeName(o, true))); } for (Object value : (SkylarkList) o) { if (!(value instanceof String)) { throw new EvalException(null, String.format(errorMsg, PROVIDERS_ARG, "list with an element of type " + EvalUtils.getDataTypeNameFromClass(value.getClass()))); } } providersList.add(((SkylarkList<?>) o).getContents(String.class, PROVIDERS_ARG)); } return providersList; } private static Descriptor createAttrDescriptor( SkylarkDict<String, Object> kwargs, Type<?> type, FuncallExpression ast, Environment env) throws EvalException { try { return new Descriptor(createAttribute(type, kwargs, ast, env)); } catch (ConversionException e) { throw new EvalException(ast.getLocation(), e.getMessage()); } } private static final Map<Type<?>, String> whyNotConfigurable = ImmutableMap.<Type<?>, String>builder() .put(BuildType.LICENSE, "loading phase license checking logic assumes non-configurable values") .put(BuildType.OUTPUT, "output paths are part of the static graph structure") .build(); /** * If the given attribute type is non-configurable, returns the reason why. Otherwise, returns * {@code null}. */ @Nullable public static String maybeGetNonConfigurableReason(Type<?> type) { return whyNotConfigurable.get(type); } private static Descriptor createNonconfigurableAttrDescriptor( SkylarkDict<String, Object> kwargs, Type<?> type, FuncallExpression ast, Environment env) throws EvalException { String whyNotConfigurableReason = Preconditions.checkNotNull(maybeGetNonConfigurableReason(type), type); try { return new Descriptor( createAttribute(type, kwargs, ast, env).nonconfigurable(whyNotConfigurableReason)); } catch (ConversionException e) { throw new EvalException(ast.getLocation(), e.getMessage()); } } @SkylarkSignature( name = "int", doc = "Creates an attribute of type int.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = Integer.class, defaultValue = "0", doc = DEFAULT_DOC, named = true, positional = false ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", doc = MANDATORY_DOC, named = true, positional = false ), @Param( name = VALUES_ARG, type = SkylarkList.class, generic1 = Integer.class, defaultValue = "[]", doc = VALUES_DOC, named = true, positional = false ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction integer = new BuiltinFunction("int") { public Descriptor invoke( Integer defaultInt, Boolean mandatory, SkylarkList<?> values, FuncallExpression ast, Environment env) throws EvalException { // TODO(bazel-team): Replace literal strings with constants. env.checkLoadingOrWorkspacePhase("attr.int", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultInt, MANDATORY_ARG, mandatory, VALUES_ARG, values), Type.INTEGER, ast, env); } }; @SkylarkSignature( name = "string", doc = "Creates an attribute of type <a href=\"string.html\">string</a>.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = String.class, defaultValue = "''", doc = DEFAULT_DOC, named = true, positional = false ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", doc = MANDATORY_DOC, named = true, positional = false ), @Param( name = VALUES_ARG, type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", doc = VALUES_DOC, named = true, positional = false ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction string = new BuiltinFunction("string") { public Descriptor invoke( String defaultString, Boolean mandatory, SkylarkList<?> values, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.string", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultString, MANDATORY_ARG, mandatory, VALUES_ARG, values), Type.STRING, ast, env); } }; @SkylarkSignature( name = "label", doc = "Creates an attribute of type <a href=\"Target.html\">Target</a> which is the target " + "referred to by the label. " + "It is the only way to specify a dependency to another target. " + "If you need a dependency that the user cannot overwrite, " + "<a href=\"../rules.html#private-attributes\">make the attribute private</a>.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = Label.class, callbackEnabled = true, noneable = true, defaultValue = "None", named = true, positional = false, doc = DEFAULT_DOC + " Use the <a href=\"globals.html#Label\"><code>Label</code></a> function to " + "specify a default value ex:</p>" + "<code>attr.label(default = Label(\"//a:b\"))</code>" ), @Param( name = EXECUTABLE_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = EXECUTABLE_DOC ), @Param( name = ALLOW_FILES_ARG, defaultValue = "None", named = true, positional = false, doc = ALLOW_FILES_DOC ), @Param( name = ALLOW_SINGLE_FILE_ARG, defaultValue = "None", named = true, positional = false, doc = "This is similar to <code>allow_files</code>, with the restriction that the label must " + "correspond to a single <a href=\"file.html\">File</a>. " + "Access it through <code>ctx.file.&lt;attribute_name&gt;</code>." ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ), @Param( name = PROVIDERS_ARG, type = SkylarkList.class, defaultValue = "[]", named = true, positional = false, doc = PROVIDERS_DOC ), @Param( name = ALLOW_RULES_ARG, type = SkylarkList.class, generic1 = String.class, noneable = true, defaultValue = "None", named = true, positional = false, doc = ALLOW_RULES_DOC ), @Param( name = SINGLE_FILE_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = "Deprecated: Use <code>allow_single_file</code> instead. " + "If True, the label must correspond to a single <a href=\"file.html\">File</a>. " + "Access it through <code>ctx.file.&lt;attribute_name&gt;</code>." ), @Param( name = CONFIGURATION_ARG, type = Object.class, noneable = true, defaultValue = "None", named = true, positional = false, doc = CONFIGURATION_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction label = new BuiltinFunction("label") { public Descriptor invoke( Object defaultO, Boolean executable, Object allowFiles, Object allowSingleFile, Boolean mandatory, SkylarkList<?> providers, Object allowRules, Boolean singleFile, Object cfg, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.label", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, EXECUTABLE_ARG, executable, ALLOW_FILES_ARG, allowFiles, ALLOW_SINGLE_FILE_ARG, allowSingleFile, MANDATORY_ARG, mandatory, PROVIDERS_ARG, providers, ALLOW_RULES_ARG, allowRules, SINGLE_FILE_ARG, singleFile, CONFIGURATION_ARG, cfg), BuildType.LABEL, ast, env); } }; @SkylarkSignature( name = "string_list", doc = "Creates an attribute which is a <a href=\"list.html\">list</a> of " + "<a href=\"string.html\">strings</a>.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = NON_EMPTY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction stringList = new BuiltinFunction("string_list") { public Descriptor invoke( SkylarkList<?> defaultList, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.string_list", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultList, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty), Type.STRING_LIST, ast, env); } }; @SkylarkSignature( name = "int_list", doc = "Creates an attribute which is a <a href=\"list.html\">list</a> of ints", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkList.class, generic1 = Integer.class, defaultValue = "[]", doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = ALLOW_EMPTY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction intList = new BuiltinFunction("int_list") { public Descriptor invoke( SkylarkList<?> defaultList, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.int_list", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultList, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty), Type.INTEGER_LIST, ast, env); } }; @SkylarkSignature( name = "label_list", doc = "Creates an attribute which is a <a href=\"list.html\">list</a> of type " + "<a href=\"Target.html\">Target</a> which are specified by the labels in the list. " + "See <a href=\"attr.html#label\">label</a> for more information.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkList.class, generic1 = Label.class, callbackEnabled = true, defaultValue = "[]", named = true, positional = false, doc = DEFAULT_DOC + " Use the <a href=\"globals.html#Label\"><code>Label</code></a> function to " + "specify default values ex:</p>" + "<code>attr.label_list(default = [ Label(\"//a:b\"), Label(\"//a:c\") ])</code>" ), @Param( name = ALLOW_FILES_ARG, // bool or FileType filter defaultValue = "None", named = true, positional = false, doc = ALLOW_FILES_DOC ), @Param( name = ALLOW_RULES_ARG, type = SkylarkList.class, generic1 = String.class, noneable = true, defaultValue = "None", named = true, positional = false, doc = ALLOW_RULES_DOC ), @Param( name = PROVIDERS_ARG, type = SkylarkList.class, defaultValue = "[]", named = true, positional = false, doc = PROVIDERS_DOC ), @Param( name = FLAGS_ARG, type = SkylarkList.class, generic1 = String.class, defaultValue = "[]", named = true, positional = false, doc = FLAGS_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = ALLOW_EMPTY_DOC ), @Param( name = CONFIGURATION_ARG, type = Object.class, noneable = true, defaultValue = "None", named = true, positional = false, doc = CONFIGURATION_DOC ), @Param( name = ASPECTS_ARG, type = SkylarkList.class, generic1 = SkylarkAspect.class, defaultValue = "[]", named = true, positional = false, doc = ASPECT_ARG_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction labelList = new BuiltinFunction("label_list") { public Descriptor invoke( Object defaultList, Object allowFiles, Object allowRules, SkylarkList<?> providers, SkylarkList<?> flags, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, Object cfg, SkylarkList<?> aspects, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.label_list", ast.getLocation()); SkylarkDict<String, Object> kwargs = EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultList, ALLOW_FILES_ARG, allowFiles, ALLOW_RULES_ARG, allowRules, PROVIDERS_ARG, providers, FLAGS_ARG, flags, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty, CONFIGURATION_ARG, cfg); try { Attribute.Builder<?> attribute = createAttribute(BuildType.LABEL_LIST, kwargs, ast, env); ImmutableList<SkylarkAspect> skylarkAspects = ImmutableList.copyOf(aspects.getContents(SkylarkAspect.class, "aspects")); return new Descriptor(attribute, skylarkAspects); } catch (EvalException e) { throw new EvalException(ast.getLocation(), e.getMessage(), e); } } }; @SkylarkSignature( name = "bool", doc = "Creates an attribute of type bool.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction bool = new BuiltinFunction("bool") { public Descriptor invoke( Boolean defaultO, Boolean mandatory, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.bool", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, MANDATORY_ARG, mandatory), Type.BOOLEAN, ast, env); } }; @SkylarkSignature( name = "output", doc = "Creates an attribute of type output. " + "The user provides a file name (string) and the rule must create an action that " + "generates the file.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = Label.class, noneable = true, defaultValue = "None", named = true, positional = false, doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction output = new BuiltinFunction("output") { public Descriptor invoke( Object defaultO, Boolean mandatory, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.output", ast.getLocation()); return createNonconfigurableAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, MANDATORY_ARG, mandatory), BuildType.OUTPUT, ast, env); } }; @SkylarkSignature( name = "output_list", doc = "Creates an attribute which is a <a href=\"list.html\">list</a> of outputs. " + "See <a href=\"attr.html#output\">output</a> for more information.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkList.class, generic1 = Label.class, defaultValue = "[]", named = true, positional = false, doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = ALLOW_EMPTY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction outputList = new BuiltinFunction("output_list") { public Descriptor invoke( SkylarkList defaultList, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.output_list", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultList, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty), BuildType.OUTPUT_LIST, ast, env); } }; @SkylarkSignature( name = "string_dict", doc = "Creates an attribute of type <a href=\"dict.html\">dict</a>, mapping from " + "<a href=\"string.html\">string</a> to <a href=\"string.html\">string</a>.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkDict.class, named = true, positional = false, defaultValue = "{}", doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, named = true, positional = false, defaultValue = "False", doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = ALLOW_EMPTY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction stringDict = new BuiltinFunction("string_dict") { public Descriptor invoke( SkylarkDict<?, ?> defaultO, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.string_dict", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty), Type.STRING_DICT, ast, env); } }; @SkylarkSignature( name = "string_list_dict", doc = "Creates an attribute of type <a href=\"dict.html\">dict</a>, mapping from " + "<a href=\"string.html\">string</a> to <a href=\"list.html\">list</a> of " + "<a href=\"string.html\">string</a>.", objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { @Param( name = DEFAULT_ARG, type = SkylarkDict.class, defaultValue = "{}", named = true, positional = false, doc = DEFAULT_DOC ), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ), @Param( name = NON_EMPTY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = NON_EMPTY_DOC ), @Param( name = ALLOW_EMPTY_ARG, type = Boolean.class, defaultValue = "True", doc = ALLOW_EMPTY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction stringListDict = new BuiltinFunction("string_list_dict") { public Descriptor invoke( SkylarkDict<?, ?> defaultO, Boolean mandatory, Boolean nonEmpty, Boolean allowEmpty, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.string_list_dict", ast.getLocation()); return createAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, MANDATORY_ARG, mandatory, NON_EMPTY_ARG, nonEmpty, ALLOW_EMPTY_ARG, allowEmpty), Type.STRING_LIST_DICT, ast, env); } }; @SkylarkSignature( name = "license", doc = "Creates an attribute of type license.", // TODO(bazel-team): Implement proper license support for Skylark. objectType = SkylarkAttr.class, returnType = Descriptor.class, parameters = { // TODO(bazel-team): ensure this is the correct default value @Param( name = DEFAULT_ARG, defaultValue = "None", noneable = true, named = true, positional = false, doc = DEFAULT_DOC), @Param( name = MANDATORY_ARG, type = Boolean.class, defaultValue = "False", named = true, positional = false, doc = MANDATORY_DOC ) }, useAst = true, useEnvironment = true ) private static BuiltinFunction license = new BuiltinFunction("license") { public Descriptor invoke( Object defaultO, Boolean mandatory, FuncallExpression ast, Environment env) throws EvalException { env.checkLoadingOrWorkspacePhase("attr.license", ast.getLocation()); return createNonconfigurableAttrDescriptor( EvalUtils.<String, Object>optionMap( env, DEFAULT_ARG, defaultO, MANDATORY_ARG, mandatory), BuildType.LICENSE, ast, env); } }; /** A descriptor of an attribute defined in Skylark. */ @SkylarkModule( name = "attr_defintion", category = SkylarkModuleCategory.NONE, doc = "Representation of a definition of an attribute; constructed by <code>attr.*</code>" + " functions. They are only for use with <a href=\"globals.html#rule\">rule</a> or " + "<a href=\"globals.html#aspect\">aspect</a>." ) public static final class Descriptor { private final Attribute.Builder<?> attributeBuilder; private final ImmutableList<SkylarkAspect> aspects; boolean exported; public Descriptor(Attribute.Builder<?> attributeBuilder) { this(attributeBuilder, ImmutableList.<SkylarkAspect>of()); } public Descriptor(Attribute.Builder<?> attributeBuilder, ImmutableList<SkylarkAspect> aspects) { this.attributeBuilder = attributeBuilder; this.aspects = aspects; exported = false; } public Attribute.Builder<?> getAttributeBuilder() { return attributeBuilder; } public ImmutableList<SkylarkAspect> getAspects() { return aspects; } public void exportAspects(Location definitionLocation) throws EvalException { if (exported) { // Only export an attribute definiton once. return; } Attribute.Builder<?> attributeBuilder = getAttributeBuilder(); for (SkylarkAspect skylarkAspect : getAspects()) { if (!skylarkAspect.isExported()) { throw new EvalException(definitionLocation, "All aspects applied to rule dependencies must be top-level values"); } attributeBuilder.aspect(skylarkAspect, definitionLocation); } exported = true; } } static { SkylarkSignatureProcessor.configureSkylarkFunctions(SkylarkAttr.class); } }
{ "content_hash": "2c2bdf1eb769086ca2a64d7445ab0118", "timestamp": "", "source": "github", "line_count": 1259, "max_line_length": 100, "avg_line_length": 33.58220810166799, "alnum_prop": 0.5892620624408704, "repo_name": "mikelalcon/bazel", "id": "7256393faaa05ebf39e22d2ce9f0a2c724627917", "size": "42280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/rules/SkylarkAttr.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "50369" }, { "name": "C++", "bytes": "457803" }, { "name": "HTML", "bytes": "17135" }, { "name": "Java", "bytes": "17885235" }, { "name": "Protocol Buffer", "bytes": "94411" }, { "name": "Python", "bytes": "242749" }, { "name": "Shell", "bytes": "493380" } ], "symlink_target": "" }
package com.ximsfei.dynamicskindemo.widget; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.util.AttributeSet; import com.ximsfei.dynamicskindemo.R; import skin.support.content.res.SkinCompatResources; import skin.support.widget.SkinCompatHelper; import skin.support.widget.SkinCompatImageHelper; import skin.support.widget.SkinCompatSupportable; import static skin.support.widget.SkinCompatHelper.INVALID_ID; /** * Created by ximsfei on 2017/1/17. */ public class CustomCircleImageView extends CircleImageView implements SkinCompatSupportable { private final SkinCompatImageHelper mImageHelper; private int mFillColorResId = INVALID_ID; private int mBorderColorResId = INVALID_ID; public CustomCircleImageView(Context context) { this(context, null); } public CustomCircleImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomCircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mImageHelper = new SkinCompatImageHelper(this); mImageHelper.loadFromAttributes(attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderColorResId = a.getResourceId(R.styleable.CircleImageView_civ_border_color, INVALID_ID); mFillColorResId = a.getResourceId(R.styleable.CircleImageView_civ_fill_color, INVALID_ID); a.recycle(); applySkin(); } @Override public void setImageResource(@DrawableRes int resId) { super.setImageResource(resId); if (mImageHelper != null) { mImageHelper.applySkin(); } } @Override public void setBorderColorResource(@ColorRes int borderColorRes) { super.setBorderColorResource(borderColorRes); mBorderColorResId = borderColorRes; applySkin(); } @Override public void setFillColorResource(@ColorRes int fillColorRes) { super.setFillColorResource(fillColorRes); mFillColorResId = fillColorRes; applySkin(); } @Override public void applySkin() { if (mImageHelper != null) { mImageHelper.applySkin(); } mBorderColorResId = SkinCompatHelper.checkResourceId(mBorderColorResId); if (mBorderColorResId != INVALID_ID) { int color = SkinCompatResources.getInstance().getColor(mBorderColorResId); setBorderColor(color); } mFillColorResId = SkinCompatHelper.checkResourceId(mFillColorResId); if (mFillColorResId != INVALID_ID) { int color = SkinCompatResources.getInstance().getColor(mFillColorResId); setFillColor(color); } } }
{ "content_hash": "a10725fefcf23f98504ebf35aeeb78c5", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 103, "avg_line_length": 32.85227272727273, "alnum_prop": 0.7097890003459011, "repo_name": "wutongke/AndroidSkinAnimator", "id": "124a35c376725ae0204081b975b93c1b4c41172a", "size": "2891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "skin-app/src/main/java/com/ximsfei/dynamicskindemo/widget/CustomCircleImageView.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "281774" } ], "symlink_target": "" }
import nj from '../core'; import * as tools from '../utils/tools'; import { extensionConfig } from '../helpers/extension'; //提取xml open tag export function getXmlOpenTag(obj, tmplRule) { return tmplRule.xmlOpenTag.exec(obj); } //验证xml self close tag const REGEX_XML_SELF_CLOSE_TAG = /^<[^>]+\/>$/i; export function isXmlSelfCloseTag(obj) { return REGEX_XML_SELF_CLOSE_TAG.test(obj); } //Verify self close tag name export const OMITTED_CLOSE_TAGS = { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true }; export function verifySelfCloseTag(tagName) { return OMITTED_CLOSE_TAGS[tagName.toLowerCase()]; } //Extract parameters inside the xml open tag export function getOpenTagParams(tag, tmplRule) { const pattern = tmplRule.openTagParams; let matchArr, ret; while ((matchArr = pattern.exec(tag))) { let key = matchArr[1]; if (key === '/') { //If match to the last of "/", then continue the loop. continue; } if (!ret) { ret = []; } let value = matchArr[8], onlyKey = false; const onlyBrace = matchArr[4] != null ? matchArr[4] : matchArr[6]; if (value != null) { value = tools.clearQuot(value); //Remove quotation marks } else { value = key; //Match to Similar to "checked" or "disabled" attribute. if (!onlyBrace) { onlyKey = true; } } //Removed at the end of "/>", ">" or "/". if (!matchArr[9] && !matchArr[10]) { if (/\/>$/.test(value)) { value = value.substr(0, value.length - 2); } else if (/>$/.test(value) || /\/$/.test(value)) { value = value.substr(0, value.length - 1); } } //Transform special key let hasColon; if (key[0] === ':') { key = key.substr(1); hasColon = true; } ret.push({ key, value, onlyBrace, hasColon, onlyKey }); } return ret; } //判断xml close tag export function isXmlCloseTag(obj, tagName) { return tools.isString(obj) && obj.toLowerCase() === '</' + tagName + '>'; } //get inside brace param export function getInsideBraceParam(obj, tmplRule) { return tmplRule.braceParam.exec(obj); } //判断扩展标签并返回参数 export function isEx(obj, tmplRule, noParams?) { let ret; const ret1 = tmplRule.extension.exec(obj); if (ret1) { ret = [ret1[1]]; if (!noParams) { const params = getOpenTagParams(obj, tmplRule); //提取各参数 if (params) { ret.push(params); } } } return ret; } export function isExAll(obj, tmplRule) { return obj.match(tmplRule.exAll); } const REGEX_LOWER_CASE = /^[a-z]/; const REGEX_UPPER_CASE = /^[A-Z]/; export function fixExTagName(tagName, tmplRule) { let ret; if (!nj.fixTagName) { return ret; } const _tagName = tools.lowerFirst(tagName), config = extensionConfig[_tagName]; if ( config && (!config.needPrefix || (config.needPrefix == 'onlyUpperCase' && REGEX_LOWER_CASE.test(tagName)) || (config.needPrefix == 'onlyLowerCase' && REGEX_UPPER_CASE.test(tagName))) ) { ret = tmplRule.extensionRule + _tagName; } return ret; } //Test whether as parameters extension export function isParamsEx(name) { return name === 'params' || name === 'props'; } //Add to the "paramsEx" property of the parent node export function addParamsEx(node, parent, isDirective, isSubTag) { const exPropsName = 'paramsEx'; if (!parent[exPropsName]) { let exPropsNode; if (isDirective || isSubTag) { exPropsNode = { type: 'nj_ex', ex: 'props', content: [node] }; } else { exPropsNode = node; } exPropsNode.parentType = parent.type; parent[exPropsName] = exPropsNode; } else { tools.arrayPush(parent[exPropsName].content, isDirective || isSubTag ? [node] : node.content); } } export function exCompileConfig(name) { return extensionConfig[name] || {}; } export function isPropS(elemName, tmplRule) { return elemName.indexOf(tmplRule.propRule) === 0; } export function isStrPropS(elemName, tmplRule) { return elemName.indexOf(tmplRule.strPropRule + tmplRule.propRule) === 0; }
{ "content_hash": "d9a6eb418d0bf2e5e4c697539ad70c4a", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 98, "avg_line_length": 22.73936170212766, "alnum_prop": 0.6194152046783625, "repo_name": "joe-sky/nornj", "id": "02a07900feb75a8727cf58befb155e3d1ea7e95d", "size": "4319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/nornj/src/transforms/transformElement.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "120106" }, { "name": "TypeScript", "bytes": "164131" } ], "symlink_target": "" }
A bot that lets you add custom Slack emoji by URL. [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) ### How it works In Slack: `@emojifier add <emoji name> <image url>` - downloads image and resizes it to aspect fit within 128px x 128px. - navigates Slack with [PhantomJS](http://phantomjs.org) (because the Slack API doesn't allow adding emoji) - signs into Slack using Google Account or email & password (if you're using two step verification, [use an application specific password](https://support.google.com/accounts/answer/185833)) ![](public/demo.png) ### Running Locally `bundle install` The following environment variables are required: - `SLACK_API_TOKEN` - `SLACK_TEAM_URL` If using Google OAuth: - `GOOGLE_ACCOUNT_EMAIL` - `GOOGLE_ACCOUNT_PASSWORD` If using email + password: - `ACCOUNT_EMAIL` - `ACCOUNT_PASSWORD` you can put them in a `.env` file and run `dotenv bundle exec rackup` or otherwise just `bundle exec rackup`
{ "content_hash": "57b450b93b78225ee5e74edfabc5d2c5", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 190, "avg_line_length": 24.675, "alnum_prop": 0.7375886524822695, "repo_name": "Bogidon/emojifier-slack-bot", "id": "fb990d0c401d535ddaaff4f2310da3fb1ae02fa1", "size": "1030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "8418" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c1233bcd5a67ab421311f1ec057dd377", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "80e53e709fd17a9653c4a3161599b4852f2ac351", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Campanulaceae/Lobelia/Lobelia inconspicua/ Syn. Lobelia maranguensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php // security - hide paths if (!defined('ADODB_DIR')) die(); // Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575 // SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t class perf_db2 extends adodb_perf{ var $createTableSQL = "CREATE TABLE adodb_logsql ( created TIMESTAMP NOT NULL, sql0 varchar(250) NOT NULL, sql1 varchar(4000) NOT NULL, params varchar(3000) NOT NULL, tracer varchar(500) NOT NULL, timer decimal(16,6) NOT NULL )"; var $settings = array( 'Ratios', 'data cache hit ratio' => array('RATIO', "SELECT case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end FROM TABLE(SNAPSHOT_APPL('',-2)) as t", '=WarnCacheRatio'), 'Data Cache', 'data cache buffers' => array('DATAC', 'select sum(npages) from SYSCAT.BUFFERPOOLS', 'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ), 'cache blocksize' => array('DATAC', 'select avg(pagesize) from SYSCAT.BUFFERPOOLS', '' ), 'data cache size' => array('DATAC', 'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS', '' ), 'Connections', 'current connections' => array('SESS', "SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t", ''), false ); function __construct(&$conn) { $this->conn = $conn; } function Explain($sql,$partial=false) { $save = $this->conn->LogSQL(false); if ($partial) { $sqlq = $this->conn->qstr($sql.'%'); $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq"); if ($arr) { foreach($arr as $row) { $sql = reset($row); if (crc32($sql) == $partial) break; } } } $qno = rand(); $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql"); ob_start(); if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>"; else { $rs = $this->conn->Execute("select * from explain_statement where queryno=$qno"); if ($rs) rs2html($rs); } $s = ob_get_contents(); ob_end_clean(); $this->conn->LogSQL($save); $s .= $this->Tracer($sql); return $s; } /** * Gets a list of tables * * @param int $throwaway discarded variable to match the parent method * @return string The formatted table list */ function Tables($throwaway=0) { $rs = $this->conn->Execute("select tabschema,tabname,card as rows, npages pages_used,fpages pages_allocated, tbspace tablespace from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2"); return rs2html($rs,false,false,false,false); } }
{ "content_hash": "1d6ec85c3b6f1cdba834ae3c009a7048", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 133, "avg_line_length": 28.63157894736842, "alnum_prop": 0.6455882352941177, "repo_name": "Universidad-de-Sevilla/icasus", "id": "bcfa840f209a858e2b8be9344b9b99f6d9a3298b", "size": "3239", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "cascara_core/adodb5.21/perf/perf-db2.inc.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "98885" }, { "name": "HTML", "bytes": "111708" }, { "name": "JavaScript", "bytes": "441699" }, { "name": "PHP", "bytes": "3525076" }, { "name": "Smarty", "bytes": "2024477" }, { "name": "XSLT", "bytes": "27654" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "7996f470e0ed2499d36ef2ad170fbe42", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "5bf3abe6edcb38f22d4d93b32c430b3862716046", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Meliaceae/Dysoxylum/Dysoxylum hirsutum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import { Entity } from "../../../../src/decorator/entity/Entity" import { PrimaryColumn } from "../../../../src/decorator/columns/PrimaryColumn" import { ManyToOne } from "../../../../src/decorator/relations/ManyToOne" import { Group } from "./Group" @Entity() export class Player { @PrimaryColumn() email: string @ManyToOne((type) => Group) group: Group }
{ "content_hash": "fdbd17526a0531968f013793b72b962c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 79, "avg_line_length": 28.846153846153847, "alnum_prop": 0.6373333333333333, "repo_name": "typeorm/typeorm", "id": "d2cf2b5b273111faf9468347a1914cddb690830f", "size": "375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/github-issues/401/entity/Player.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "580" }, { "name": "JavaScript", "bytes": "16233" }, { "name": "Shell", "bytes": "2208" }, { "name": "TypeScript", "bytes": "8547494" } ], "symlink_target": "" }
<header class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#top-menu"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">WebApplication3</a> </div> <div id="top-menu" class="collapse navbar-collapse"> <ul class="nav navbar-nav" data-bind="foreach: router.navigationModel"> <li data-bind="css: { active: isActive }"> <a data-bind="attr: { href: hash }, text: title"></a> </li> </ul> <form class="navbar-form navbar-right navbar-search" role="search" data-bind="submit: search"> <label for="global-search" class="sr-only">Search</label> <div class="input-group"> <input type="text" id="global-search" name="global-search" class="form-control" placeholder="Search..." /> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="sr-only">Search</span> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </form> </div> </div> </header> <div class="router-loader" data-bind="visible: router.isNavigating"> <i class="fa fa-spinner fa-2x fa-spin active"></i> </div> <section id="main" class="container" data-bind="router: { transition:'entrance', cacheViews:true }"></section> <footer class="well"> This is your footer </footer>
{ "content_hash": "28901a1f1a8e829420030c272ecabc80", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 126, "avg_line_length": 49.17948717948718, "alnum_prop": 0.5328467153284672, "repo_name": "VincentSchippefilt/DDD-DomainEvents", "id": "f7e816367ca5e0d4c46ea55290637202ea5eeb5f", "size": "1918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebApplication3/wwwroot/app/views/shell.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "ApacheConf", "bytes": "72" }, { "name": "C#", "bytes": "287260" }, { "name": "CSS", "bytes": "440960" }, { "name": "CoffeeScript", "bytes": "6526" }, { "name": "Groff", "bytes": "160" }, { "name": "HTML", "bytes": "1105893" }, { "name": "JavaScript", "bytes": "5390595" }, { "name": "Makefile", "bytes": "275" }, { "name": "PHP", "bytes": "16913" }, { "name": "Shell", "bytes": "184" } ], "symlink_target": "" }
hexchat.register('PMColor', '1', 'Color PM tabs like highlights') for _, event in pairs({'Private Message to Dialog', 'Private Action to Dialog'}) do hexchat.hook_print(event, function (args) hexchat.command('gui color 3') end) end
{ "content_hash": "02e2997f11350310ad6b9a1321e0fcd3", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 83, "avg_line_length": 33.857142857142854, "alnum_prop": 0.7172995780590717, "repo_name": "TingPing/plugins", "id": "dd8753d42e326bbb61229b6729938b0f86984242", "size": "269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HexChat/pmcolor.lua", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1174" }, { "name": "Lua", "bytes": "30172" }, { "name": "Python", "bytes": "89892" } ], "symlink_target": "" }
#!/usr/bin/env node /** * Created by idok on 11/10/14. */ 'use strict'; //var fs = require('fs'); var _ = require('lodash'); var path = require('path'); var api = require('./api'); var context = require('./context'); var shell = require('./shell'); var pkg = require('../package.json'); //var defaultOptions = {commonJS: false, force: false, json: false}; var options = require('./options'); var reactDOMSupport = require('./reactDOMSupport'); var reactTemplates = require('./reactTemplates'); function executeOptions(currentOptions) { var ret = 0; var files = currentOptions._; context.options.format = currentOptions.format || 'stylish'; if (currentOptions.version) { console.log('v' + pkg.version); } else if (currentOptions.help) { if (files.length) { console.log(options.generateHelpForOption(files[0])); } else { console.log(options.generateHelp()); } } else if (currentOptions.listTargetVersion) { printVersions(currentOptions); } else if (!files.length) { console.log(options.generateHelp()); } else { _.forEach(files, handleSingleFile.bind(this, currentOptions)); ret = shell.printResults(context); } return ret; } function printVersions(currentOptions) { var ret = Object.keys(reactDOMSupport); if (currentOptions.format === 'json') { console.log(JSON.stringify(ret, undefined, 2)); } else { console.log(ret.join(', ')); } } /** * @param {*} currentOptions * @param {string} filename file name to process */ function handleSingleFile(currentOptions, filename) { if (path.extname(filename) !== '.rt') { context.error('invalid file, only handle rt files', filename); return;// only handle html files } try { var ext; if (currentOptions.modules !== 'typescript') { ext = '.js'; } else { ext = '.ts'; } api.convertFile(filename, filename + ext, currentOptions, context); } catch (e) { context.error(e.message, filename, e.line, e.column, e.startOffset, e.endOffset); } } /** * Executes the CLI based on an array of arguments that is passed in. * @param {string|Array|Object} args The arguments to process. * @returns {int} The exit code for the operation. */ function execute(args) { var currentOptions; try { currentOptions = options.parse(args); } catch (error) { console.error(error.message); return 1; } //console.log(currentOptions); return executeOptions(currentOptions); } module.exports = { execute: execute, executeOptions: executeOptions, handleSingleFile: handleSingleFile, convertTemplateToReact: reactTemplates.convertTemplateToReact };
{ "content_hash": "8e747aa435eaa50efc6f67dcef546c13", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 89, "avg_line_length": 29.49473684210526, "alnum_prop": 0.6313347608850821, "repo_name": "strikingly/react-templates", "id": "33d1d9fdf7472c261dedc04872f90be4a2803108", "size": "2802", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "src/cli.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "39875" }, { "name": "HTML", "bytes": "8665" }, { "name": "JavaScript", "bytes": "2614657" }, { "name": "TypeScript", "bytes": "146" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in in Braun & Mel'nik, Trudy Botanicheskogo Instituta im. V. L. Komarova 20: 38 (1997) #### Original name Cercospora ampelopsidis Peck, 1878 ### Remarks null
{ "content_hash": "e1df1971e0d5bb1bcd4b66cf064bffc8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 83, "avg_line_length": 18.615384615384617, "alnum_prop": 0.7231404958677686, "repo_name": "mdoering/backbone", "id": "148a885fa5c7f5e46d90406d5a87b7964f497dfc", "size": "310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Cercospora/Cercospora ampelopsidis/ Syn. Passalora ampelopsidis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.openforis.idm.metamodel.xml.internal.unmarshal; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; /** * @author G. Miceli */ abstract class TextPullReader extends IdmlPullReader { private boolean trimWhitespace; protected TextPullReader(String tagName) { this(tagName, null); } protected TextPullReader(String tagName, Integer maxCount) { super(tagName, maxCount); this.trimWhitespace = true; } protected boolean isTrim() { return trimWhitespace; } protected void setTrimWhitespace(boolean trim) { this.trimWhitespace = trim; } @Override protected void onStartTag() throws XmlPullParserException, IOException { XmlPullParser parser = getParser(); String text = parser.nextText(); processText(trimWhitespace ? text.trim() : text); } protected abstract void processText(String text); }
{ "content_hash": "c8881c2ef1ad34f9ce8b4582cc9e2f63", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 73, "avg_line_length": 24, "alnum_prop": 0.7307692307692307, "repo_name": "openforis/collect", "id": "82464fcb09106eb21e2ebf780c6d57b0911343d3", "size": "936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "collect-core/src/main/java/org/openforis/idm/metamodel/xml/internal/unmarshal/TextPullReader.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2032" }, { "name": "CSS", "bytes": "492878" }, { "name": "HTML", "bytes": "55093" }, { "name": "Java", "bytes": "6027874" }, { "name": "JavaScript", "bytes": "5049757" }, { "name": "Less", "bytes": "60736" }, { "name": "SCSS", "bytes": "310370" }, { "name": "Shell", "bytes": "515" }, { "name": "TSQL", "bytes": "1199" }, { "name": "XSLT", "bytes": "8150" } ], "symlink_target": "" }
#pragma once #include "IElement.hpp" /* Documentation at: http://www.metroid2002.com/retromodding/wiki/Particle_Script#Mod_Vector_Elements */ namespace urde { class CMVEImplosion : public CModVectorElement { std::unique_ptr<CVectorElement> x4_implPoint; std::unique_ptr<CRealElement> x8_magScale; std::unique_ptr<CRealElement> xc_maxMag; std::unique_ptr<CRealElement> x10_minMag; bool x14_enableMinMag; public: CMVEImplosion(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CRealElement>&& b, std::unique_ptr<CRealElement>&& c, std::unique_ptr<CRealElement>&& d, bool e) : x4_implPoint(std::move(a)) , x8_magScale(std::move(b)) , xc_maxMag(std::move(c)) , x10_minMag(std::move(d)) , x14_enableMinMag(std::move(e)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEExponentialImplosion : public CModVectorElement { std::unique_ptr<CVectorElement> x4_implPoint; std::unique_ptr<CRealElement> x8_magScale; std::unique_ptr<CRealElement> xc_maxMag; std::unique_ptr<CRealElement> x10_minMag; bool x14_enableMinMag; public: CMVEExponentialImplosion(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CRealElement>&& b, std::unique_ptr<CRealElement>&& c, std::unique_ptr<CRealElement>&& d, bool e) : x4_implPoint(std::move(a)) , x8_magScale(std::move(b)) , xc_maxMag(std::move(c)) , x10_minMag(std::move(d)) , x14_enableMinMag(std::move(e)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVELinearImplosion : public CModVectorElement { std::unique_ptr<CVectorElement> x4_implPoint; std::unique_ptr<CRealElement> x8_magScale; std::unique_ptr<CRealElement> xc_maxMag; std::unique_ptr<CRealElement> x10_minMag; bool x14_enableMinMag; public: CMVELinearImplosion(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CRealElement>&& b, std::unique_ptr<CRealElement>&& c, std::unique_ptr<CRealElement>&& d, bool e) : x4_implPoint(std::move(a)) , x8_magScale(std::move(b)) , xc_maxMag(std::move(c)) , x10_minMag(std::move(d)) , x14_enableMinMag(std::move(e)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVETimeChain : public CModVectorElement { std::unique_ptr<CModVectorElement> x4_a; std::unique_ptr<CModVectorElement> x8_b; std::unique_ptr<CIntElement> xc_swFrame; public: CMVETimeChain(std::unique_ptr<CModVectorElement>&& a, std::unique_ptr<CModVectorElement>&& b, std::unique_ptr<CIntElement>&& c) : x4_a(std::move(a)), x8_b(std::move(b)), xc_swFrame(std::move(c)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEBounce : public CModVectorElement { std::unique_ptr<CVectorElement> x4_planePoint; std::unique_ptr<CVectorElement> x8_planeNormal; std::unique_ptr<CRealElement> xc_friction; std::unique_ptr<CRealElement> x10_restitution; bool x14_planePrecomputed; bool x15_dieOnPenetrate; zeus::CVector3f x18_planeValidatedNormal; float x24_planeD; public: CMVEBounce(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CVectorElement>&& b, std::unique_ptr<CRealElement>&& c, std::unique_ptr<CRealElement>&& d, bool e); bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEConstant : public CModVectorElement { std::unique_ptr<CRealElement> x4_x; std::unique_ptr<CRealElement> x8_y; std::unique_ptr<CRealElement> xc_z; public: CMVEConstant(std::unique_ptr<CRealElement>&& a, std::unique_ptr<CRealElement>&& b, std::unique_ptr<CRealElement>&& c) : x4_x(std::move(a)), x8_y(std::move(b)), xc_z(std::move(c)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEFastConstant : public CModVectorElement { zeus::CVector3f x4_val; public: CMVEFastConstant(float a, float b, float c) : x4_val(a, b, c) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEGravity : public CModVectorElement { std::unique_ptr<CVectorElement> x4_a; public: CMVEGravity(std::unique_ptr<CVectorElement>&& a) : x4_a(std::move(a)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEExplode : public CModVectorElement { std::unique_ptr<CRealElement> x4_a; std::unique_ptr<CRealElement> x8_b; public: CMVEExplode(std::unique_ptr<CRealElement>&& a, std::unique_ptr<CRealElement>&& b) : x4_a(std::move(a)), x8_b(std::move(b)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVESetPosition : public CModVectorElement { std::unique_ptr<CVectorElement> x4_a; public: CMVESetPosition(std::unique_ptr<CVectorElement>&& a) : x4_a(std::move(a)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEPulse : public CModVectorElement { std::unique_ptr<CIntElement> x4_aDuration; std::unique_ptr<CIntElement> x8_bDuration; std::unique_ptr<CModVectorElement> xc_aVal; std::unique_ptr<CModVectorElement> x10_bVal; public: CMVEPulse(std::unique_ptr<CIntElement>&& a, std::unique_ptr<CIntElement>&& b, std::unique_ptr<CModVectorElement>&& c, std::unique_ptr<CModVectorElement>&& d) : x4_aDuration(std::move(a)), x8_bDuration(std::move(b)), xc_aVal(std::move(c)), x10_bVal(std::move(d)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVEWind : public CModVectorElement { std::unique_ptr<CVectorElement> x4_velocity; std::unique_ptr<CRealElement> x8_factor; public: CMVEWind(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CRealElement>&& b) : x4_velocity(std::move(a)), x8_factor(std::move(b)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; class CMVESwirl : public CModVectorElement { std::unique_ptr<CVectorElement> x4_helixPoint; std::unique_ptr<CVectorElement> x8_curveBinormal; std::unique_ptr<CRealElement> xc_filterGain; std::unique_ptr<CRealElement> x10_tangentialVelocity; public: CMVESwirl(std::unique_ptr<CVectorElement>&& a, std::unique_ptr<CVectorElement>&& b, std::unique_ptr<CRealElement>&& c, std::unique_ptr<CRealElement>&& d) : x4_helixPoint(std::move(a)) , x8_curveBinormal(std::move(b)) , xc_filterGain(std::move(c)) , x10_tangentialVelocity(std::move(d)) {} bool GetValue(int frame, zeus::CVector3f& pVel, zeus::CVector3f& pPos) const override; }; } // namespace urde
{ "content_hash": "47b7195717b8c92a95e64c0be1fb1bb6", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 120, "avg_line_length": 38.24, "alnum_prop": 0.708756724447101, "repo_name": "RetroView/PathShagged", "id": "6e01908f4cab27de551752cfe6e3533c3c003999", "size": "6692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Runtime/Particle/CModVectorElement.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "30964" }, { "name": "C++", "bytes": "1853098" }, { "name": "CMake", "bytes": "25640" }, { "name": "Python", "bytes": "29052" } ], "symlink_target": "" }
export default { reportingUrl: 'http://eum.example.com', xhrTransmissionTimeout: 5432, beaconBatchingTime: 0, secretPropertyKey: '__secret__', sessionId: undefined, sessionStorageKey: 'session', defaultSessionInactivityTimeoutMillis: 100, defaultSessionTerminationTimeoutMillis: 200, maxAllowedSessionTimeoutMillis: 500 };
{ "content_hash": "cf2d18142e86ae9d382cb70826a8ccb9", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 46, "avg_line_length": 31.09090909090909, "alnum_prop": 0.7777777777777778, "repo_name": "instana/weasel", "id": "c08b9ab11570c410ad75a691590f6d35bfa102b4", "size": "342", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/__mocks__/vars.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "51818" }, { "name": "JavaScript", "bytes": "274100" } ], "symlink_target": "" }
""" Filename: unittest_test_mc_compute_stationary.py Author: Daisuke Oyama Unittest for mc_compute_stationary in mc_tools.py from quantecon Input Markov matrices defined by the Kandori-Mailath-Rob model with - two actions (0 and 1), - payoffs being characterized by the level of p-dominance of action 1, - N players, and - mutation probability epsilon. References ---------- https://github.com/oyamad/test_mc_compute_stationary """ from __future__ import division import sys import argparse import numpy as np from scipy.stats import binom import unittest from mc_tools import mc_compute_stationary # Default parameter values default_N, default_epsilon = 27, 1e-2 default_p = 1/3 # action 1 is risk-dominant # Default move: 'sequential' or 'simultaneous' default_move = 'sequential' # Tolerance level default_TOL = 1e-2 def KMR_Markov_matrix_simultaneous(N, p, epsilon): """ Generate the Markov matrix for the KMR model with *simultaneous* move Parameters ---------- N : int Number of players p : float Level of p-dominance of action 1, i.e., the value of p such that action 1 is the BR for (1-q, q) for any q > p, where q (1-q, resp.) is the prob that the opponent plays action 1 (0, resp.) epsilon : float Probability of mutation Returns ------- P : numpy.ndarray Markov matrix for the KMR model with simultaneous move Notes ----- For simplicity, the transition probabilities are computed under the assumption that a player is allowed to be matched to play with himself. """ P = np.empty((N+1, N+1), dtype=float) for n in range(N+1): P[n, :] = \ (n/N < p) * binom.pmf(range(N+1), N, epsilon/2) + \ (n/N == p) * binom.pmf(range(N+1), N, 1/2) + \ (n/N > p) * binom.pmf(range(N+1), N, 1-epsilon/2) return P def KMR_Markov_matrix_sequential(N, p, epsilon): """ Generate the Markov matrix for the KMR model with *sequential* move Parameters ---------- N : int Number of players p : float Level of p-dominance of action 1, i.e., the value of p such that action 1 is the BR for (1-q, q) for any q > p, where q (1-q, resp.) is the prob that the opponent plays action 1 (0, resp.) epsilon : float Probability of mutation Returns ------- P : numpy.ndarray Markov matrix for the KMR model with simultaneous move """ P = np.zeros((N+1, N+1), dtype=float) P[0, 0], P[0, 1] = 1 - epsilon * (1/2), epsilon * (1/2) for n in range(1, N): P[n, n-1] = \ (n/N) * (epsilon * (1/2) + (1 - epsilon) * (((n-1)/(N-1) < p) + ((n-1)/(N-1) == p) * (1/2)) ) P[n, n+1] = \ ((N-n)/N) * (epsilon * (1/2) + (1 - epsilon) * ((n/(N-1) > p) + (n/(N-1) == p) * (1/2)) ) P[n, n] = 1 - P[n, n-1] - P[n, n+1] P[N, N-1], P[N, N] = epsilon * (1/2), 1 - epsilon * (1/2) return P class TestComputeStationary(unittest.TestCase): def setUp(self): self.P, self.v = P, v def test_markov_matrix(self): for i in range(len(self.P)): self.assertEqual(sum(self.P[i, :]), 1) def test_sum_one(self): self.assertTrue(np.allclose(sum(self.v), 1, atol=TOL)) def test_nonnegative(self): self.assertEqual(np.prod(self.v >= 0-TOL), 1) def test_left_eigen_vec(self): self.assertTrue(np.allclose(np.dot(self.v, self.P), self.v, atol=TOL)) def tearDown(self): pass if __name__ == '__main__': parser = argparse.ArgumentParser(description='Unittest for mc_compute_stationary.') parser.add_argument( "--N", dest='N', type=int, action='store', default=default_N, metavar='N', help=u'N = number of players' ) parser.add_argument( "--epsilon", dest='epsilon', type=float, action='store', default=default_epsilon, metavar='epsilon', help=u'epsilon = mutation probability' ) parser.add_argument( "--p", dest='p', action='store', default=default_p, metavar='p', help=u'p = level of p-dominance of action 1' ) parser.add_argument( "--tolerance", type=float, dest='tol', action='store', default=default_TOL, metavar='tol', help=u'tol = tolerance' ) parser.add_argument( "--move", dest='move', action='store', default=default_move, help=u'\'sequential\' (default) or \'simulataneous\'' ) args = parser.parse_args() if args.move == 'simultaneous': P = KMR_Markov_matrix_simultaneous(N=args.N, p=args.p, epsilon=args.epsilon) else: P = KMR_Markov_matrix_sequential(N=args.N, p=args.p, epsilon=args.epsilon) v = mc_compute_stationary(P) TOL = args.tol print 'N =', args.N, ', epsilon =', args.epsilon, '\n' if args.N <= 5: print 'P =\n', P, '\n' print 'v =\n', v, '\n' print 'TOL =', TOL, '\n' suite = unittest.TestLoader().loadTestsFromTestCase(TestComputeStationary) unittest.TextTestRunner(verbosity=2, stream=sys.stderr).run(suite)
{ "content_hash": "4cc11b42e7c4172884458822cb7808b0", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 89, "avg_line_length": 29.463276836158194, "alnum_prop": 0.5825503355704698, "repo_name": "oyamad/test_mc_compute_stationary", "id": "6a9675f4ba3317c0f62e6ba3f898ea2193167a09", "size": "5215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "unittest_mc_compute_stationary.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "32599" } ], "symlink_target": "" }
package org.pentaho.di.ui.core.dialog; import java.io.BufferedReader; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.lang.StringUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.pentaho.di.core.Const; import org.pentaho.di.core.SwtUniversalImage; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.laf.BasePropertyHandler; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.util.SwtSvgImageUtil; import org.pentaho.di.version.BuildVersion; /** * Displays the Kettle splash screen * * @author Matt * @since 14-mrt-2005 */ public class Splash { private Shell splash; private Image kettle_image; private Image kettle_icon; private Image exclamation_image; private Font verFont; private Font licFont; private Font devWarningFont; private Color versionWarningBackgroundColor; private Color versionWarningForegroundColor; private int licFontSize = 8; private static Class<?> PKG = Splash.class; // for i18n purposes, needed by Translator2!! private static LogChannelInterface log; public Splash( Display display ) throws KettleException { this( display, new Shell( display, SWT.APPLICATION_MODAL ) ); } protected Splash( Display display, Shell splashShell ) throws KettleException { log = new LogChannel( Spoon.APP_NAME ); Rectangle displayBounds = display.getPrimaryMonitor().getBounds(); // "kettle_splash.png" kettle_image = loadAsResource( display, BasePropertyHandler.getProperty( "splash_image" ) ); // "spoon.ico" kettle_icon = loadAsResource( display, BasePropertyHandler.getProperty( "splash_icon" ) ); // "exclamation.png" exclamation_image = loadAsResource( display, BasePropertyHandler.getProperty( "exclamation_image" ) ); verFont = new Font( display, "Helvetica", 11, SWT.BOLD ); licFont = new Font( display, "Helvetica", licFontSize, SWT.NORMAL ); devWarningFont = new Font( display, "Helvetica", 10, SWT.NORMAL ); // versionWarningBackgroundColor = new Color(display, 255, 253, 213); versionWarningBackgroundColor = new Color( display, 255, 255, 255 ); versionWarningForegroundColor = new Color( display, 220, 177, 20 ); splash = splashShell; splash.setImage( kettle_icon ); splash.setText( BaseMessages.getString( PKG, "SplashDialog.Title" ) ); // "Pentaho Data Integration" splash.addPaintListener( new PaintListener() { public void paintControl( PaintEvent e ) { StringBuilder sb = new StringBuilder(); String line = null; try { BufferedReader reader = new BufferedReader( new InputStreamReader( Splash.class.getClassLoader().getResourceAsStream( "org/pentaho/di/ui/core/dialog/license/license.txt" ) ) ); while ( ( line = reader.readLine() ) != null ) { sb.append( line + System.getProperty( "line.separator" ) ); } } catch ( Exception ex ) { sb.append( "" ); log.logError( BaseMessages.getString( PKG, "SplashDialog.LicenseTextNotFound" ), ex ); } Calendar cal = Calendar.getInstance(); String licenseText = String.format( sb.toString(), cal ); e.gc.drawImage( kettle_image, 0, 0 ); String fullVersionText = BaseMessages.getString( PKG, "SplashDialog.Version" ); String buildVersion = BuildVersion.getInstance().getVersion(); if ( StringUtils.ordinalIndexOf( buildVersion, ".", 2 ) > 0 ) { fullVersionText = fullVersionText + " " + buildVersion.substring( 0, StringUtils.ordinalIndexOf( buildVersion, ".", 2 ) ); } else { fullVersionText = fullVersionText + " " + buildVersion; } e.gc.setFont( verFont ); e.gc.drawText( fullVersionText, 290, 205, true ); String inputStringDate = BuildVersion.getInstance().getBuildDate(); String outputStringDate = ""; SimpleDateFormat inputFormat = null; SimpleDateFormat outputFormat = null; if ( inputStringDate.matches( "^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}.\\d{3}$" ) ) { inputFormat = new SimpleDateFormat( "yyyy/MM/dd hh:mm:ss.SSS" ); } if ( inputStringDate.matches( "^\\d{4}-\\d{1,2}-\\d{1,2}\\_\\d{1,2}-\\d{2}-\\d{2}$" ) ) { inputFormat = new SimpleDateFormat( "yyyy-MM-dd_hh-mm-ss" ); } if ( inputStringDate.matches( "^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}.\\d{2}.\\d{2}$" ) ) { inputFormat = new SimpleDateFormat( "yyyy-MM-dd hh.mm.ss" ); } outputFormat = new SimpleDateFormat( "MMMM d, yyyy hh:mm:ss" ); try { if ( inputFormat != null ) { Date date = inputFormat.parse( inputStringDate ); outputStringDate = outputFormat.format( date ); } else { // If date isn't correspond to formats above just show date in origin format outputStringDate = inputStringDate; } } catch ( ParseException pe ) { // Just show date in origin format outputStringDate = inputStringDate; } // try using the desired font size for the license text e.gc.setFont( licFont ); // if the text will not fit the allowed space while ( !willLicenseTextFit( licenseText, e.gc ) ) { licFontSize--; if ( licFont != null ) { licFont.dispose(); } licFont = new Font( e.display, "Helvetica", licFontSize, SWT.NORMAL ); e.gc.setFont( licFont ); } e.gc.drawText( licenseText, 290, 275, true ); String version = buildVersion; // If this is a Milestone or RC release, warn the user if ( Const.RELEASE.equals( Const.ReleaseType.MILESTONE ) ) { version = BaseMessages.getString( PKG, "SplashDialog.DeveloperRelease" ) + " - " + version; drawVersionWarning( e ); } else if ( Const.RELEASE.equals( Const.ReleaseType.RELEASE_CANDIDATE ) ) { version = BaseMessages.getString( PKG, "SplashDialog.ReleaseCandidate" ) + " - " + version; } else if ( Const.RELEASE.equals( Const.ReleaseType.PREVIEW ) ) { version = BaseMessages.getString( PKG, "SplashDialog.PreviewRelease" ) + " - " + version; } else if ( Const.RELEASE.equals( Const.ReleaseType.GA ) ) { version = BaseMessages.getString( PKG, "SplashDialog.GA" ) + " - " + version; } String buildDate = BaseMessages.getString( PKG, "SplashDialog.BuildDate" ) + " " + outputStringDate; // use the same font/size as the license text e.gc.drawText( version, 290, 235, true ); e.gc.drawText( buildDate, 290, 250, true ); } } ); splash.addDisposeListener( new DisposeListener() { public void widgetDisposed( DisposeEvent arg0 ) { kettle_image.dispose(); kettle_icon.dispose(); exclamation_image.dispose(); verFont.dispose(); licFont.dispose(); devWarningFont.dispose(); versionWarningForegroundColor.dispose(); versionWarningBackgroundColor.dispose(); } } ); Rectangle bounds = kettle_image.getBounds(); int x = ( displayBounds.width - bounds.width ) / 2; int y = ( displayBounds.height - bounds.height ) / 2; splash.setSize( bounds.width, bounds.height ); splash.setLocation( x, y ); splash.open(); TimerTask timerTask = new TimerTask() { @Override public void run() { try { splash.redraw(); LogChannel.UI.logBasic( "Redraw!" ); } catch ( Throwable e ) { // ignore. } } }; final Timer timer = new Timer(); timer.schedule( timerTask, 0, 100 ); splash.addDisposeListener( new DisposeListener() { public void widgetDisposed( DisposeEvent arg0 ) { timer.cancel(); } } ); } // load image from svg private Image loadAsResource( Display display, String location ) { SwtUniversalImage img = SwtSvgImageUtil.getImageAsResource( display, location ); Image image = new Image( display, img.getAsBitmap( display ), SWT.IMAGE_COPY ); img.dispose(); return image; } // determine if the license text will fit the allocated space private boolean willLicenseTextFit( String licenseText, GC gc ) { Point splashSize = splash.getSize(); Point licenseDrawLocation = new Point( 290, 290 ); Point requiredSize = gc.textExtent( licenseText ); int width = splashSize.x - licenseDrawLocation.x; int height = splashSize.y - licenseDrawLocation.y; boolean fitsVertically = width >= requiredSize.x; boolean fitsHorizontally = height >= requiredSize.y; return ( fitsVertically && fitsHorizontally ); } private void drawVersionWarning( PaintEvent e ) { drawVersionWarning( e.gc, e.display ); } private void drawVersionWarning( GC gc, Display display ) { gc.setBackground( versionWarningBackgroundColor ); gc.setForeground( versionWarningForegroundColor ); // gc.fillRectangle(290, 231, 367, 49); // gc.drawRectangle(290, 231, 367, 49); gc.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) ); gc.drawImage( exclamation_image, 304, 243 ); gc.setFont( devWarningFont ); gc.drawText( BaseMessages.getString( PKG, "SplashDialog.DevelopmentWarning" ), 335, 241, true ); } public void dispose() { if ( !splash.isDisposed() ) { splash.dispose(); } } public void hide() { if ( !splash.isDisposed() ) { splash.setVisible( false ); } } public void show() { if ( !splash.isDisposed() ) { splash.setVisible( true ); } } }
{ "content_hash": "bfa51a5e2317275230cd9e7e23301f54", "timestamp": "", "source": "github", "line_count": 287, "max_line_length": 134, "avg_line_length": 36.53310104529617, "alnum_prop": 0.6528373867429661, "repo_name": "brosander/pentaho-kettle", "id": "6d81898b4390a4d1289d447bc3f51311c46213cf", "size": "11389", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ui/src/org/pentaho/di/ui/core/dialog/Splash.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14028" }, { "name": "CSS", "bytes": "20530" }, { "name": "GAP", "bytes": "4005" }, { "name": "HTML", "bytes": "69511" }, { "name": "Java", "bytes": "37786915" }, { "name": "JavaScript", "bytes": "16314" }, { "name": "Shell", "bytes": "18925" }, { "name": "XSLT", "bytes": "5600" } ], "symlink_target": "" }
layout: post title: "How to Ramdisk Image ramdisk.cpio.gz" date: 2016-10-31 19:31:50 categories: Linux tags: android linux embedded reverse --- ``` gzip -d ramdisk.cpio.gz mkdir rootfs cd rootfs cpio -i -d -m ../ramdisk.cpio ``` ``` out/host/linux-x86/bin/mkbootfs -d out/target/product/msm8952_64/system out/target/product/msm8952_64/root | out/host/linux-x86/bin/minigzip > out/target/product/msm8952_64/ramdisk.img ``` ``` out/host/linux-x86/bin/mkbootimg --kernel out/target/product/msm8952_64/kernel --ramdisk out/target/product/msm8952_64/ramdisk.img --cmdline "console=ttyHSL0,115200,n8 androidboot.console=ttyHSL0 androidboot.hardware=qcom msm_rtb.filter=0x237 ehci-hcd.park=3 androidboot.bootdevice=7824900.sdhci lpm_levels.sleep_disabled=1 earlyprintk" --base 0x80000000 --pagesize 2048 --output out/target/product/msm8952_64/boot.img ``` ``` out/host/linux-x86/bin/boot_signer /boot out/target/product/msm8952_64/boot.img build/target/product/security/verity.pk8 build/target/product/security/verity.x509.pem out/target/product/msm8952_64/boot.img size=$(for i in out/target/product/msm8952_64/boot.img; do stat --format "%s" "$i" | tr -d '\n'; echo +; done; echo 0); total=$(( $( echo "$size" ) )); printname=$(echo -n "out/target/product/msm8952_64/boot.img" | tr " " +); img_blocksize=135168; twoblocks=$((img_blocksize * 2)); onepct=$(((((69206016 / 100) - 1) / img_blocksize + 1) * img_blocksize)); reserve=$((twoblocks > onepct ? twoblocks : onepct)); maxsize=$((69206016 - reserve)); echo "$printname maxsize=$maxsize blocksize=$img_blocksize total=$total reserve=$reserve"; if [ "$total" -gt "$maxsize" ]; then echo "error: $printname too large ($total > [69206016 - $reserve])"; false; elif [ "$total" -gt $((maxsize - 32768)) ]; then echo "WARNING: $printname approaching size limit ($total now; limit $maxsize)"; fi out/target/product/msm8952_64/boot.img maxsize=68395008 blocksize=135168 total=30418216 reserve=811008 ``` ### Referencee * http://pete.akeo.ie/2013/10/compiling-and-running-your-own-android.html * https://leanpub.com/awesomeasciidoctornotebook/read * http://akosma.github.io/eBook-Template/ * http://superuser.com/questions/240473/ramdisk-img-to-ramdisk-cpio-gz * http://www.lhpup.org/help/faqs/initrd.html
{ "content_hash": "f653d8b6486a9a385b972da19546137b", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 778, "avg_line_length": 65.48571428571428, "alnum_prop": 0.7212041884816754, "repo_name": "thalib/thalib.github.io", "id": "51d5b7c4ddd0e5b9c11cbd87d277c8c71b94b92e", "size": "2297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_drafts/2016-10-31-creating-ramdisk-image.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "24138" }, { "name": "JavaScript", "bytes": "21978" }, { "name": "SCSS", "bytes": "37338" }, { "name": "Shell", "bytes": "711" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "907212775dec3fb222251f9bb9a4871d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d62e5f107fa4af9e3f88ee9ec7f4485267922fd1", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia wellbyi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.elasticlib.console.command.repositories; import java.util.List; import org.elasticlib.console.command.AbstractCommand; import org.elasticlib.console.command.Category; import org.elasticlib.console.config.ConsoleConfig; import org.elasticlib.console.display.Display; import org.elasticlib.console.http.Session; /** * The repositories command. */ public class Repositories extends AbstractCommand { /** * Constructor. */ public Repositories() { super(Category.REPOSITORIES); } @Override public void execute(Display display, Session session, ConsoleConfig config, List<String> params) { session.getClient() .repositories() .listInfos() .forEach(display::print); } }
{ "content_hash": "cdb78b33d793fea70aaddb60bba50813", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 102, "avg_line_length": 26, "alnum_prop": 0.6923076923076923, "repo_name": "elasticlib/elasticlib", "id": "560041a51860c681ac247c7cf2eb75da43ecb103", "size": "1411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "elasticlib-console/src/main/java/org/elasticlib/console/command/repositories/Repositories.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3942" }, { "name": "Java", "bytes": "1302052" }, { "name": "Shell", "bytes": "3352" } ], "symlink_target": "" }
import datetime, re; from sqlalchemy.orm import validates; from server import DB, FlaskServer; class Irrigators_phone(DB.Model): id = DB.Column(DB.Integer, primary_key=True, autoincrement=True); irrigator_id = DB.relationship(DB.Integer, DB.ForeignKey('irrigators.id'), lazy='joined'); phone_id = DB.relationship(DB.Integer, DB.ForeignKey('phones.id'), lazy='joined'); primary_phone = DB.Column(DB.Boolean); created_by = DB.Column(DB.Integer, DB.ForeignKey('users.id')); created_at = DB.Column(DB.DateTime); updated_by = DB.Column(DB.Integer, DB.ForeignKey('users.id')); updated_at = DB.Column(DB.DateTime, nullable=True); def __init__(self, primary_phone, created_at, updated_at): self.primary_phone = primary_phone; self.created_at = datetime.datetime.now(); self.updated_at = self.created_at;
{ "content_hash": "a78b982cf0df5390932152294e3c54fd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 91, "avg_line_length": 40.75, "alnum_prop": 0.7288343558282209, "repo_name": "mikelambson/tcid", "id": "7e005c47d7d32acb5701202fff6561d5c81a8562", "size": "815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/models/irrigators_phone.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7583" }, { "name": "HTML", "bytes": "10429" }, { "name": "JavaScript", "bytes": "6996" }, { "name": "Python", "bytes": "19634" }, { "name": "TypeScript", "bytes": "11676" } ], "symlink_target": "" }
require 'spec_helper' feature 'Merge Request Discussions', feature: true do before do sign_in(create(:admin)) end describe "Diff discussions" do let(:merge_request) { create(:merge_request, importing: true) } let(:project) { merge_request.source_project } let!(:old_merge_request_diff) { merge_request.merge_request_diffs.create(diff_refs: outdated_diff_refs) } let!(:new_merge_request_diff) { merge_request.merge_request_diffs.create } let!(:outdated_discussion) { create(:diff_note_on_merge_request, project: project, noteable: merge_request, position: outdated_position).to_discussion } let!(:active_discussion) { create(:diff_note_on_merge_request, noteable: merge_request, project: project).to_discussion } let(:outdated_position) do Gitlab::Diff::Position.new( old_path: "files/ruby/popen.rb", new_path: "files/ruby/popen.rb", old_line: nil, new_line: 9, diff_refs: outdated_diff_refs ) end let(:outdated_diff_refs) { project.commit("874797c3a73b60d2187ed6e2fcabd289ff75171e").diff_refs } before(:each) do visit project_merge_request_path(project, merge_request) end context 'active discussions' do it 'shows a link to the diff' do within(".discussion[data-discussion-id='#{active_discussion.id}']") do path = diffs_project_merge_request_path(project, merge_request, anchor: active_discussion.line_code) expect(page).to have_link('the diff', href: path) end end end context 'outdated discussions' do it 'shows a link to the outdated diff' do within(".discussion[data-discussion-id='#{outdated_discussion.id}']") do path = diffs_project_merge_request_path(project, merge_request, diff_id: old_merge_request_diff.id, anchor: outdated_discussion.line_code) expect(page).to have_link('an old version of the diff', href: path) end end end end describe 'Commit comments displayed in MR context', :js do let(:merge_request) { create(:merge_request) } let(:project) { merge_request.project } shared_examples 'a functional discussion' do let(:discussion_id) { note.discussion_id(merge_request) } it 'is displayed' do expect(page).to have_css(".discussion[data-discussion-id='#{discussion_id}']") end it 'can be replied to' do within(".discussion[data-discussion-id='#{discussion_id}']") do click_button 'Reply...' fill_in 'note[note]', with: 'Test!' click_button 'Comment' expect(page).to have_css('.note', count: 2) end end end before(:each) do visit project_merge_request_path(project, merge_request) end context 'a regular commit comment' do let(:note) { create(:note_on_commit, project: project) } it_behaves_like 'a functional discussion' end context 'a commit diff comment' do let(:note) { create(:diff_note_on_commit, project: project) } it_behaves_like 'a functional discussion' end end end
{ "content_hash": "ac9b22b3cf49e3ccd60dd938ee6b8294", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 156, "avg_line_length": 34.53333333333333, "alnum_prop": 0.6534749034749034, "repo_name": "dplarson/gitlabhq", "id": "55846f8609b8d5ef35cf11136e7afc95ac013205", "size": "3108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/features/merge_requests/discussion_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "536999" }, { "name": "Gherkin", "bytes": "116570" }, { "name": "HTML", "bytes": "1044163" }, { "name": "JavaScript", "bytes": "2193246" }, { "name": "Ruby", "bytes": "11711128" }, { "name": "Shell", "bytes": "27251" }, { "name": "Vue", "bytes": "196242" } ], "symlink_target": "" }
package com.google.gson; import junit.framework.TestCase; import java.lang.reflect.Type; /** * Unit tests for the {@link MappedObjectConstructor} class. * * @author Joel Leitch */ public class MappedObjectConstructorTest extends TestCase { private ParameterizedTypeHandlerMap<InstanceCreator<?>> creatorMap; private MappedObjectConstructor constructor; @Override protected void setUp() throws Exception { super.setUp(); creatorMap = new ParameterizedTypeHandlerMap<InstanceCreator<?>>(); constructor = new MappedObjectConstructor(creatorMap); } public void testInstanceCreatorTakesTopPrecedence() throws Exception { creatorMap.register(ObjectWithDefaultConstructor.class, new MyInstanceCreator(), false); ObjectWithDefaultConstructor obj = constructor.construct(ObjectWithDefaultConstructor.class); assertEquals("instanceCreator", obj.stringValue); assertEquals(10, obj.intValue); } public void testNoInstanceCreatorInvokesDefaultConstructor() throws Exception { ObjectWithDefaultConstructor expected = new ObjectWithDefaultConstructor(); ObjectWithDefaultConstructor obj = constructor.construct(ObjectWithDefaultConstructor.class); assertEquals(expected.stringValue, obj.stringValue); assertEquals(expected.intValue, obj.intValue); } public void testNoDefaultConstructor() throws Exception { ObjectNoDefaultConstructor obj = constructor.construct(ObjectNoDefaultConstructor.class); assertNull(obj.stringValue); assertEquals(0, obj.intValue); } private static class MyInstanceCreator implements InstanceCreator<ObjectWithDefaultConstructor> { public ObjectWithDefaultConstructor createInstance(Type type) { return new ObjectWithDefaultConstructor("instanceCreator", 10); } } private static class ObjectWithDefaultConstructor { public final String stringValue; public final int intValue; private ObjectWithDefaultConstructor() { this("default", 5); } public ObjectWithDefaultConstructor(String stringValue, int intValue) { this.stringValue = stringValue; this.intValue = intValue; } } private static class ObjectNoDefaultConstructor extends ObjectWithDefaultConstructor { @SuppressWarnings("unused") public ObjectNoDefaultConstructor(String stringValue, int intValue) { super(stringValue, intValue); } } }
{ "content_hash": "d54412ca687d0fdc696e825dd3c91506", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 93, "avg_line_length": 32.554054054054056, "alnum_prop": 0.7667081776670818, "repo_name": "eatnumber1/google-gson", "id": "da36ef02c6d6b9270f611bf9ae73e114b27144c2", "size": "3003", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/com/google/gson/MappedObjectConstructorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "982947" } ], "symlink_target": "" }
package inst import ( "fmt" "regexp" "strconv" "strings" ) // InstanceKey is an instance indicator, identifued by hostname and port type InstanceKey struct { Hostname string Port int } var ( ipv4Regexp = regexp.MustCompile(`^([0-9]+)[.]([0-9]+)[.]([0-9]+)[.]([0-9]+)$`) ipv4HostPortRegexp = regexp.MustCompile(`^([^:]+):([0-9]+)$`) ipv4HostRegexp = regexp.MustCompile(`^([^:]+)$`) ipv6HostPortRegexp = regexp.MustCompile(`^\[([:0-9a-fA-F]+)\]:([0-9]+)$`) // e.g. [2001:db8:1f70::999:de8:7648:6e8]:3308 ipv6HostRegexp = regexp.MustCompile(`^([:0-9a-fA-F]+)$`) // e.g. 2001:db8:1f70::999:de8:7648:6e8 ) const detachHint = "//" func newInstanceKey(hostname string, port int, resolve bool) (instanceKey *InstanceKey, err error) { if hostname == "" { return instanceKey, fmt.Errorf("NewResolveInstanceKey: Empty hostname") } instanceKey = &InstanceKey{Hostname: hostname, Port: port} if resolve { instanceKey, err = instanceKey.ResolveHostname() } return instanceKey, err } // newInstanceKeyStrings func newInstanceKeyStrings(hostname string, port string, resolve bool) (*InstanceKey, error) { portInt, err := strconv.Atoi(port) if err != nil { return nil, fmt.Errorf("Invalid port: %s", port) } return newInstanceKey(hostname, portInt, resolve) } func parseRawInstanceKey(hostPort string, resolve bool) (instanceKey *InstanceKey, err error) { hostname := "" port := "" if submatch := ipv4HostPortRegexp.FindStringSubmatch(hostPort); len(submatch) > 0 { hostname = submatch[1] port = submatch[2] } else if submatch := ipv4HostRegexp.FindStringSubmatch(hostPort); len(submatch) > 0 { hostname = submatch[1] } else if submatch := ipv6HostPortRegexp.FindStringSubmatch(hostPort); len(submatch) > 0 { hostname = submatch[1] port = submatch[2] } else if submatch := ipv6HostRegexp.FindStringSubmatch(hostPort); len(submatch) > 0 { hostname = submatch[1] } else { return nil, fmt.Errorf("Cannot parse address: %s", hostPort) } if port == "" { port = "3306" } return newInstanceKeyStrings(hostname, port, resolve) } func NewResolveInstanceKey(hostname string, port int) (instanceKey *InstanceKey, err error) { return newInstanceKey(hostname, port, true) } // NewResolveInstanceKeyStrings creates and resolves a new instance key based on string params func NewResolveInstanceKeyStrings(hostname string, port string) (*InstanceKey, error) { return newInstanceKeyStrings(hostname, port, true) } func ParseResolveInstanceKey(hostPort string) (instanceKey *InstanceKey, err error) { return parseRawInstanceKey(hostPort, true) } func ParseRawInstanceKey(hostPort string) (instanceKey *InstanceKey, err error) { return parseRawInstanceKey(hostPort, false) } // NewResolveInstanceKeyStrings creates and resolves a new instance key based on string params func NewRawInstanceKeyStrings(hostname string, port string) (*InstanceKey, error) { return newInstanceKeyStrings(hostname, port, false) } func (instanceKey *InstanceKey) ResolveHostname() (*InstanceKey, error) { if !instanceKey.IsValid() { return instanceKey, nil } hostname, err := ResolveHostname(instanceKey.Hostname) if err == nil { instanceKey.Hostname = hostname } return instanceKey, err } // Equals tests equality between this key and another key func (instanceKey *InstanceKey) Equals(other *InstanceKey) bool { if other == nil { return false } return instanceKey.Hostname == other.Hostname && instanceKey.Port == other.Port } // SmallerThan returns true if this key is dictionary-smaller than another. // This is used for consistent sorting/ordering; there's nothing magical about it. func (instanceKey *InstanceKey) SmallerThan(other *InstanceKey) bool { if instanceKey.Hostname < other.Hostname { return true } if instanceKey.Hostname == other.Hostname && instanceKey.Port < other.Port { return true } return false } // IsDetached returns 'true' when this hostname is logically "detached" func (instanceKey *InstanceKey) IsDetached() bool { return strings.HasPrefix(instanceKey.Hostname, detachHint) } // IsValid uses simple heuristics to see whether this key represents an actual instance func (instanceKey *InstanceKey) IsValid() bool { if instanceKey.Hostname == "_" { return false } if instanceKey.IsDetached() { return false } return len(instanceKey.Hostname) > 0 && instanceKey.Port > 0 } // DetachedKey returns an instance key whose hostname is detahced: invalid, but recoverable func (instanceKey *InstanceKey) DetachedKey() *InstanceKey { if instanceKey.IsDetached() { return instanceKey } return &InstanceKey{Hostname: fmt.Sprintf("%s%s", detachHint, instanceKey.Hostname), Port: instanceKey.Port} } // ReattachedKey returns an instance key whose hostname is detahced: invalid, but recoverable func (instanceKey *InstanceKey) ReattachedKey() *InstanceKey { if !instanceKey.IsDetached() { return instanceKey } return &InstanceKey{Hostname: instanceKey.Hostname[len(detachHint):], Port: instanceKey.Port} } // StringCode returns an official string representation of this key func (instanceKey *InstanceKey) StringCode() string { return fmt.Sprintf("%s:%d", instanceKey.Hostname, instanceKey.Port) } // DisplayString returns a user-friendly string representation of this key func (instanceKey *InstanceKey) DisplayString() string { return instanceKey.StringCode() } // String returns a user-friendly string representation of this key func (instanceKey InstanceKey) String() string { return instanceKey.StringCode() } // IsValid uses simple heuristics to see whether this key represents an actual instance func (instanceKey *InstanceKey) IsIPv4() bool { return ipv4Regexp.MatchString(instanceKey.Hostname) }
{ "content_hash": "d66eb31e48073c96aba927631691291b", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 121, "avg_line_length": 32.72571428571428, "alnum_prop": 0.7407019381875327, "repo_name": "mahak/vitess", "id": "2a3124aeb57c73d7112a7ee245665e5cac744700", "size": "6337", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "go/vt/vtorc/inst/instance_key.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "198" }, { "name": "CSS", "bytes": "18852" }, { "name": "Dockerfile", "bytes": "28594" }, { "name": "Go", "bytes": "23060389" }, { "name": "HCL", "bytes": "959" }, { "name": "HTML", "bytes": "25753" }, { "name": "Java", "bytes": "990163" }, { "name": "JavaScript", "bytes": "33028" }, { "name": "Jsonnet", "bytes": "121075" }, { "name": "Makefile", "bytes": "23322" }, { "name": "Perl", "bytes": "3161" }, { "name": "Python", "bytes": "1955" }, { "name": "SCSS", "bytes": "41351" }, { "name": "Shell", "bytes": "184185" }, { "name": "Smarty", "bytes": "30493" }, { "name": "TypeScript", "bytes": "711819" }, { "name": "Yacc", "bytes": "162805" } ], "symlink_target": "" }
namespace FbTk { class Accessor<class T>; /// a bool menu item class BoolMenuItem: public FbTk::MenuItem { public: BoolMenuItem(const FbTk::FbString &label, Accessor<bool> &item, FbTk::RefCount<FbTk::Command<void> > &cmd): FbTk::MenuItem(label, cmd), m_item(item) { FbTk::MenuItem::setSelected(m_item); setToggleItem(true); setCloseOnClick(false); } BoolMenuItem(const FbTk::FbString &label, Accessor<bool> &item): FbTk::MenuItem(label), m_item(item) { FbTk::MenuItem::setSelected(m_item); setToggleItem(true); setCloseOnClick(false); } bool isSelected() const { return m_item; } // toggle state void click(int button, int time, unsigned int mods) { setSelected(!m_item); FbTk::MenuItem::click(button, time, mods); } void setSelected(bool value) { m_item = value; FbTk::MenuItem::setSelected(m_item); } private: Accessor<bool> &m_item; }; } // end namespace FbTk #endif // FBTK_BOOLMENUITEM_HH
{ "content_hash": "944180e50526953156d8c4a22b5dff19", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 68, "avg_line_length": 28.594594594594593, "alnum_prop": 0.6181474480151229, "repo_name": "ystk/debian-fluxbox", "id": "3e68cbd1a4a38bc64cb33ffa1f2ca6da655c5b1d", "size": "2320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FbTk/BoolMenuItem.hh", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1965241" }, { "name": "M", "bytes": "431706" }, { "name": "Matlab", "bytes": "110320" }, { "name": "Perl", "bytes": "7893" }, { "name": "Shell", "bytes": "413670" } ], "symlink_target": "" }
@class BaseResponse; @interface AddTrustedFriendsResp : WXPBGeneratedMessage { } + (void)initialize; // Remaining properties @property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse; @end
{ "content_hash": "590f0c2c7c7f966c78b69a828baed0cb", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 82, "avg_line_length": 16.76923076923077, "alnum_prop": 0.7752293577981652, "repo_name": "walkdianzi/DashengHook", "id": "192a2af775aa770e900f4d83ef1f10215236866e", "size": "391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WeChat-Headers/AddTrustedFriendsResp.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "986" }, { "name": "Objective-C", "bytes": "10153542" }, { "name": "Objective-C++", "bytes": "18332" }, { "name": "Shell", "bytes": "1459" } ], "symlink_target": "" }
package org.corebounce.resman; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; public class AutoComplete { private final List<TableItem> items = new ArrayList<>(); private final Table table; private final Shell popupShell; public AutoComplete(Text text) { popupShell = new Shell(text.getDisplay(), SWT.ON_TOP); popupShell.setLayout(new FillLayout()); table = new Table(popupShell, SWT.SINGLE); text.addListener(SWT.KeyDown, new Listener() { @Override public void handleEvent(Event event) { if(table.getItemCount() > 0) { switch (event.keyCode) { case SWT.ARROW_DOWN: int index = (table.getSelectionIndex() + 1) % table.getItemCount(); table.setSelection(index); event.doit = false; break; case SWT.ARROW_UP: index = table.getSelectionIndex() - 1; if (index < 0) index = table.getItemCount() - 1; table.setSelection(index); event.doit = false; break; case SWT.CR: if (popupShell.isVisible() && table.getSelectionIndex() != -1) { text.setText(table.getSelection()[0].getText()); text.selectAll(); popupShell.setVisible(false); } break; case SWT.ESC: popupShell.setVisible(false); break; } } } }); text.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { String string = text.getText(); if (string.length() == 0) { popupShell.setVisible(false); } else { Rectangle textBounds = text.getDisplay().map(text.getShell(), null, text.getBounds()); popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height, textBounds.width, table.getItemHeight() * table.getItemCount()); popupShell.setVisible(true); String prefix = text.getText(); for(int i = 0; i < items.size(); i++) if(items.get(i).getText().startsWith(prefix)) { table.select(i); return; } table.deselectAll(); } } }); table.addListener(SWT.DefaultSelection, new Listener() { @Override public void handleEvent(Event event) { text.setText(table.getSelection()[0].getText()); text.selectAll(); popupShell.setVisible(false); } }); table.addListener(SWT.KeyDown, new Listener() { @Override public void handleEvent(Event event) { if (event.keyCode == SWT.ESC) { popupShell.setVisible(false); } } }); Listener focusOutListener = new Listener() { @Override public void handleEvent(Event event) { Display display = Display.getDefault(); display.asyncExec(new Runnable() { @Override public void run() { if (display.isDisposed()) return; if(event.type == SWT.FocusOut) { Control control = display.getFocusControl(); if(!(popupShell.isDisposed()) && (control == null || (control != text && control != table))) popupShell.setVisible(false); } else if(event.type == SWT.FocusIn) { Control control = display.getFocusControl(); if (control instanceof Text) ((Text)control).selectAll(); } } }); } }; table.addListener(SWT.FocusOut, focusOutListener); text.addListener(SWT.FocusOut, focusOutListener); text.addListener(SWT.FocusIn, focusOutListener); text.getShell().addListener(SWT.Move, new Listener() { @Override public void handleEvent(Event event) { popupShell.setVisible(false); } }); } public void addItem(String item) { TableItem titem = new TableItem(table, SWT.NONE); items.add(titem); titem.setText(item); } public void clear() { for(TableItem titem : items) titem.dispose(); items.clear(); } public void setVisible(boolean visible) { popupShell.setVisible(visible); } }
{ "content_hash": "fcfb5d350f71656e2aa4067923fde822", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 138, "avg_line_length": 29.04861111111111, "alnum_prop": 0.6595744680851063, "repo_name": "arisona/ether", "id": "b73e6bdff244a3c45d72659ea167eb9ce5e4955b", "size": "4183", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "ether-soundium/src/main/java/org/corebounce/resman/AutoComplete.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "GLSL", "bytes": "17986" }, { "name": "Java", "bytes": "2453722" } ], "symlink_target": "" }
namespace Gu.Wpf.UiAutomation.WindowsAPI { public static class LayeredWindowAttributes { public const uint LWA_COLORKEY = 0x1; public const uint LWA_ALPHA = 0x2; } }
{ "content_hash": "1ffd45fc009bd4c254144f9da42f3336", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 47, "avg_line_length": 24.25, "alnum_prop": 0.6752577319587629, "repo_name": "JohanLarsson/Gu.Wpf.UiAutomation", "id": "b9bf31740d7efc725b88f41d77332ce37f51a8f0", "size": "467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gu.Wpf.UiAutomation/WindowsAPI/LayeredWindowAttributes.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "661633" } ], "symlink_target": "" }
<?php namespace Symfony\Component\HttpKernel\Tests\EventListener; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\EventListener\EsiListener; use Symfony\Component\HttpKernel\HttpCache\Esi; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; class EsiListenerTest extends \PHPUnit_Framework_TestCase { public function testFilterDoesNothingForSubRequests() { $dispatcher = new EventDispatcher(); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $response = new Response('foo <esi:include src="" />'); $listener = new EsiListener(new Esi()); $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse')); $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response); $dispatcher->dispatch(KernelEvents::RESPONSE, $event); $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control')); } public function testFilterWhenThereIsSomeEsiIncludes() { $dispatcher = new EventDispatcher(); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $response = new Response('foo <esi:include src="" />'); $listener = new EsiListener(new Esi()); $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse')); $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response); $dispatcher->dispatch(KernelEvents::RESPONSE, $event); $this->assertEquals('content="ESI/1.0"', $event->getResponse()->headers->get('Surrogate-Control')); } public function testFilterWhenThereIsNoEsiIncludes() { $dispatcher = new EventDispatcher(); $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'); $response = new Response('foo'); $listener = new EsiListener(new Esi()); $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse')); $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response); $dispatcher->dispatch(KernelEvents::RESPONSE, $event); $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control')); } }
{ "content_hash": "8e241e08bbf3d91196f923cd6ecd69df", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 113, "avg_line_length": 41.01587301587302, "alnum_prop": 0.7109133126934984, "repo_name": "DerDu/MOC-Framework-Mark-V", "id": "14c161f5eb9e25c235dc99aa5d86fdf9365f111a", "size": "2813", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Component/Router/Vendor/Symfony/Component/HttpKernel/Tests/EventListener/EsiListenerTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "110" }, { "name": "HTML", "bytes": "252" }, { "name": "PHP", "bytes": "299247" }, { "name": "Smarty", "bytes": "252" } ], "symlink_target": "" }
package io.cloudslang.content.xml.services.impl; import io.cloudslang.content.xml.entities.inputs.EditXmlInputs; import io.cloudslang.content.xml.services.OperationService; import io.cloudslang.content.xml.utils.Constants; import io.cloudslang.content.xml.utils.DocumentUtils; import io.cloudslang.content.xml.utils.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Created by moldovas on 7/8/2016. */ public class InsertOperationServiceImpl implements OperationService { /** * Inserts in an XML (provided as String or file) a new element; attribute or text text at a given XPath. * * @param inputs inputs * @return a String representation of the modified XML * @throws Exception in case something goes wrong */ @Override public String execute(EditXmlInputs inputs) throws Exception { Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures()); NodeList nodeList = XmlUtils.readNode(doc, inputs.getXpath1(), XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath())); Node childNode = null; Node node; Node parentNode; // create new Node to insert if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) { childNode = XmlUtils.stringToNode(inputs.getValue(), doc.getXmlEncoding(), inputs.getParsingFeatures()); } for (int i = 0; i < nodeList.getLength(); i++) { node = nodeList.item(i); if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) { //check if provided xpath doesn't contain root node if (node != doc.getDocumentElement()) { childNode = doc.importNode(childNode, true); parentNode = node.getParentNode(); parentNode.insertBefore(childNode, node); } } else if (Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) { node.setTextContent(inputs.getValue() + node.getTextContent()); } else if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) { ((Element) node).setAttribute(inputs.getName(), inputs.getValue()); } } return DocumentUtils.documentToString(doc); } }
{ "content_hash": "821ed28ed27ea5ad748dc2cd497d61a8", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 140, "avg_line_length": 43.03636363636364, "alnum_prop": 0.6582171525137305, "repo_name": "robert-sandor/cs-actions", "id": "04e200ad906901aa6d4398ad7de892fec3c3aa21", "size": "2851", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cs-xml/src/main/java/io/cloudslang/content/xml/services/impl/InsertOperationServiceImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2994121" }, { "name": "XSLT", "bytes": "544" } ], "symlink_target": "" }
package org.jboss.pnc.common.json.moduleconfig; import org.jboss.pnc.common.json.AbstractModuleConfig; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; /** * Runtime configuration parameters for the Build Agent * * @author Alex Creasy */ @JsonIgnoreProperties({ "@module-config"}) public class OpenshiftBuildAgentConfig extends AbstractModuleConfig { public static final String MODULE_NAME = "openshift-build-agent"; private final JsonNode pncBuilderPod; private final JsonNode pncBuilderService; private final JsonNode pncBuilderRoute; private final JsonNode pncBuilderSshRoute; public OpenshiftBuildAgentConfig( @JsonProperty("pncBuilderPod") JsonNode pncBuilderPod, @JsonProperty("pncBuilderService") JsonNode pncBuilderService, @JsonProperty("pncBuilderRoute") JsonNode pncBuilderRoute, @JsonProperty("pncBuilderSshRoute") JsonNode pncBuilderSshRoute) { this.pncBuilderPod = pncBuilderPod; this.pncBuilderService = pncBuilderService; this.pncBuilderRoute = pncBuilderRoute; this.pncBuilderSshRoute = pncBuilderSshRoute; } public String getBuilderPod() { if (pncBuilderPod.isNull()) { return null; } return pncBuilderPod.toString(); } public String getPncBuilderService() { if (pncBuilderService.isNull()) { return null; } return pncBuilderService.toString(); } public String getPncBuilderRoute() { if (pncBuilderRoute.isNull()) { return null; } return pncBuilderRoute.toString(); } public String getPncBuilderSshRoute() { if (pncBuilderSshRoute.isNull()) { return null; } return pncBuilderSshRoute.toString(); } }
{ "content_hash": "3e9d371b1930ea7ab44eb1b213872e41", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 78, "avg_line_length": 31.14516129032258, "alnum_prop": 0.69135163127913, "repo_name": "jdcasey/pnc", "id": "5d2a893c5a69e6431f65ae4f7566c4c4223f7469", "size": "2639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "moduleconfig/src/main/java/org/jboss/pnc/common/json/moduleconfig/OpenshiftBuildAgentConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "109709" }, { "name": "HTML", "bytes": "355476" }, { "name": "Java", "bytes": "3334728" }, { "name": "JavaScript", "bytes": "3010359" }, { "name": "PLSQL", "bytes": "1616" }, { "name": "PLpgSQL", "bytes": "8490" } ], "symlink_target": "" }
The &lt;scsidevice&gt; inspectors refer to the Small Computer System Interface devices connected to the Client computer. # product of &lt;scsidevice&gt; : string The product string for the given SCSI device. # revision of &lt;scsidevice&gt; : string The revision of the SCSI device. # type of &lt;scsidevice&gt; : string Returns a SCSI device type, such as: DISK, TAPE, PRINTER, CPU, WORM, CDROM, SCAN, DISK, or UNKNOWN. # vendor of &lt;scsidevice&gt; : string Vendor string for given SCSI device.
{ "content_hash": "8f29302fa189b0d339d9da5f80b893bd", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 120, "avg_line_length": 29.764705882352942, "alnum_prop": 0.7470355731225297, "repo_name": "briangreenery/developer.bigfix.com", "id": "28e2ffe2f0f7397207a3612c898c30659d452009", "size": "526", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "site/pages/relevance/_reference/docs/scsidevice.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "129207" }, { "name": "HTML", "bytes": "25477" }, { "name": "JavaScript", "bytes": "39163" }, { "name": "Makefile", "bytes": "8028" }, { "name": "Nginx", "bytes": "362" }, { "name": "Shell", "bytes": "2117" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.yy</groupId> <artifactId>studyappfuse</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>core</artifactId> <packaging>jar</packaging> <name>AppFuse Modular Application - Core</name> <build> <finalName>studyappfuse-core</finalName> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>hibernate3-maven-plugin</artifactId> <version>2.2</version> <configuration> <components> <component> <name>hbm2ddl</name> <implementation>annotationconfiguration</implementation> </component> </components> <componentProperties> <drop>true</drop> <jdk5>true</jdk5> <propertyfile>target/test-classes/jdbc.properties</propertyfile> <skip>${skipTests}</skip> </componentProperties> </configuration> <executions> <execution> <phase>process-test-resources</phase> <goals> <goal>hbm2ddl</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>${jdbc.groupId}</groupId> <artifactId>${jdbc.artifactId}</artifactId> <version>${jdbc.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>dbunit-maven-plugin</artifactId> <version>1.0-beta-3</version> <configuration> <dataTypeFactoryName>${dbunit.dataTypeFactoryName}</dataTypeFactoryName> <driver>${jdbc.driverClassName}</driver> <username>${jdbc.username}</username> <password>${jdbc.password}</password> <url>${jdbc.url}</url> <src>src/test/resources/sample-data.xml</src> <type>${dbunit.operation.type}</type> <schema>${dbunit.schema}</schema> <skip>${skipTests}</skip> <transaction>true</transaction> </configuration> <executions> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>operation</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>${jdbc.groupId}</groupId> <artifactId>${jdbc.artifactId}</artifactId> <version>${jdbc.version}</version> </dependency> </dependencies> </plugin> </plugins> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> </testResource> </testResources> </build> <!-- Dependencies calculated by AppFuse when running full-source plugin --> <dependencies> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons.beanutils.version}</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>${commons.collections.version}</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons.lang.version}</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.4.GA</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>${javamail.version}</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>${jpa.version}</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <version>4.5</version> <scope>test</scope> <optional>true</optional> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>wstx-asl</artifactId> <groupId>org.codehaus.woodstox</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-common-utilities</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <artifactId>wstx-asl</artifactId> <groupId>org.codehaus.woodstox</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-jaxrs</artifactId> <version>1.6.0</version> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.0.3</version> </dependency> <dependency> <groupId>org.compass-project</groupId> <artifactId>compass</artifactId> <version>${compass.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>${hibernate.annotations.version}</version> <exclusions> <exclusion> <artifactId>ejb3-persistence</artifactId> <groupId>org.hibernate</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <artifactId>ehcache</artifactId> <groupId>net.sf.ehcache</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock</artifactId> <version>${jmock.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-junit4</artifactId> <version>${jmock.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.subethamail</groupId> <artifactId>subethasmtp-wiser</artifactId> <version>${wiser.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>velocity</groupId> <artifactId>velocity</artifactId> <version>${velocity.version}</version> </dependency> </dependencies> </project>
{ "content_hash": "0c0251bb6fd9ab4df147969973008f9e", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 201, "avg_line_length": 38.84848484848485, "alnum_prop": 0.5076269717455365, "repo_name": "yyitsz/myjavastudio", "id": "82d9510d6db82f955c70bd6f2c52463ad0addc5d", "size": "11538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "studyappfuse/core/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "29361" }, { "name": "Batchfile", "bytes": "5917" }, { "name": "C#", "bytes": "1904272" }, { "name": "CSS", "bytes": "206344" }, { "name": "HTML", "bytes": "53455" }, { "name": "Java", "bytes": "3185115" }, { "name": "JavaScript", "bytes": "654297" }, { "name": "PLSQL", "bytes": "10155" }, { "name": "Roff", "bytes": "178" }, { "name": "Shell", "bytes": "418" }, { "name": "XSLT", "bytes": "12347" } ], "symlink_target": "" }
class PagesController < ApplicationController def home end end
{ "content_hash": "6b6625738e8d43a9a0d5e8897a4ebbe1", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 45, "avg_line_length": 13.6, "alnum_prop": 0.7941176470588235, "repo_name": "lewg/click", "id": "38bab446bbad85549bd94f50ccfa61a57959aa76", "size": "68", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "app/controllers/pages_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "13094" }, { "name": "Ruby", "bytes": "29126" } ], "symlink_target": "" }
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.internal.constraintvalidators.hv; import java.text.Normalizer; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import org.hibernate.validator.constraints.Normalized; /** * Check that a character sequence is normalized. * * @author Craig Andrews */ public class NormalizedValidator implements ConstraintValidator<Normalized, CharSequence> { private Normalizer.Form form; @Override public void initialize(Normalized parameters) { form = parameters.form(); } @Override public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) { if ( value == null ) { return true; } return Normalizer.isNormalized( value, form ); } }
{ "content_hash": "7537b49e32f8549338480d39eafcb786", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 100, "avg_line_length": 26.675675675675677, "alnum_prop": 0.7750759878419453, "repo_name": "marko-bekhta/hibernate-validator", "id": "7afcde7d042f36c2b72942614251ca6269bc9499", "size": "987", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "engine/src/main/java/org/hibernate/validator/internal/constraintvalidators/hv/NormalizedValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "7782" }, { "name": "HTML", "bytes": "1387" }, { "name": "Java", "bytes": "4873228" }, { "name": "Shell", "bytes": "476" } ], "symlink_target": "" }
require 'ads_common/savon_service' require 'dfp_api/v201411/reconciliation_report_row_service_registry' module DfpApi; module V201411; module ReconciliationReportRowService class ReconciliationReportRowService < AdsCommon::SavonService def initialize(config, endpoint) namespace = 'https://www.google.com/apis/ads/publisher/v201411' super(config, endpoint, namespace, :v201411) end def get_reconciliation_report_rows_by_statement(*args, &block) return execute_action('get_reconciliation_report_rows_by_statement', args, &block) end def get_reconciliation_report_rows_by_statement_to_xml(*args) return get_soap_xml('get_reconciliation_report_rows_by_statement', args) end def update_reconciliation_report_rows(*args, &block) return execute_action('update_reconciliation_report_rows', args, &block) end def update_reconciliation_report_rows_to_xml(*args) return get_soap_xml('update_reconciliation_report_rows', args) end private def get_service_registry() return ReconciliationReportRowServiceRegistry end def get_module() return DfpApi::V201411::ReconciliationReportRowService end end end; end; end
{ "content_hash": "7910aefbbcb2c540224c7d612348f77d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 88, "avg_line_length": 32.945945945945944, "alnum_prop": 0.7350287120590648, "repo_name": "ramdanplusplus/google-api-ads-ruby", "id": "0f37346ca5d00939261e1866866d4058468ec5d0", "size": "1496", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dfp_api/lib/dfp_api/v201411/reconciliation_report_row_service.rb", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1319" }, { "name": "HTML", "bytes": "7882" }, { "name": "JavaScript", "bytes": "757" }, { "name": "Python", "bytes": "187" }, { "name": "Ruby", "bytes": "9268366" } ], "symlink_target": "" }
//**************************************************************************/ // Copyright (c) 1998-2006 Autodesk, Inc. // All rights reserved. // // These coded instructions, statements, and computer programs contain // unpublished proprietary information written by Autodesk, Inc., and are // protected by Federal copyright law. They may not be disclosed to third // parties or copied or duplicated in any form, in whole or in part, without // the prior written consent of Autodesk, Inc. //**************************************************************************/ #pragma once #define ANIMTYPE_NODE 1 #define ANIMTYPE_ROOTNODE 3 #define ANIMTYPE_CONTROL 2 // The maximum number of track views that can be opened. Each // animatable stores 3 bits for each track to identify it's open/close // state and selection state. #define MAX_TRACK_VIEWS 16 #define ALL_TRACK_VIEWS 0xffff // The maximum number of track view selection sets #define MAX_TRACKVIEW_SELSETS 16 //! \brief 'type' argument to the OpenTreeEntry, CloseTreeEntry, IsTreeEntryOpen methods /*! \see Animatable::OpenTreeEntry(int type, DWORD tv) \see Animatable::CloseTreeEntry(int type, DWORD tv) \see Animatable::IsTreeEntryOpen(int type, DWORD tv) */ #define TRACKVIEW_NODE 0 //!< operate on the tree based on the node parent/child relationship #define TRACKVIEW_ANIM 1 //!< operate on the tree based on the animatable/subanim relationship /*! \defgroup AnimatableFlags Animatable Flags Animatable flags are generally meant to be used in enumerations of Animatable instances where each instance must be visited only once. The Animatable flags are in general not persisted, nor copied between instances of class Animatable. Many of these flags are for internal use only. Unique Animatable bit flag values can be requested via Animatable::RequestFlagBit(). Plugins are encouraged to use this mechanism over the older <A href="#Animatable_Work_Flags">General Animatable work flags</A>, or the <A href="#Animatable_Plugin_Flags">Animatable plugin flags</A>. */ //!@{ // BITS 5-11, and 19 are reserved for specific sub-class use. /*! \name Atmospheric flags */ //!@{ //! \brief The atmosphere effect is disabled #define A_ATMOS_DISABLED (1<<5) //! \brief Not used anywhere. #define A_ATMOS_OBJECTXREF (1<<6) //! \brief An atmospheric scene xref #define A_ATMOS_SCENEXREF (1<<7) //!@} /*! \name Tone Operator flags */ //!@{ //! \brief The exposure control is disabled #define A_TONEOP_DISABLED (1<<5) //! \brief The exposure control proceses the background. #define A_TONEOP_PROCESS_BG (1<<6) //! \brief Only processes indirect lights only. #define A_TONEOP_INDIRECT_ONLY (1<<7) //!@} /*! \name Object flags */ //!@{ //! \brief The object is being created. It doesn't want to snap to itself. #define A_OBJ_CREATING (1<<5) #ifdef _OSNAP /*! \brief Persists throughout the whole creation process as opposed to A_OBJ_CREATING which gets cleared as as the object is added to the scene. */ #define A_OBJ_LONG_CREATE (1<<6) #endif #define A_OBJ_BEING_EDITED (1<<7) //!@} /*! \name Modifier flags */ //!@{ //! \brief The modifier is disabled #define A_MOD_DISABLED (1<<5) //! \brief The modifer is deleted #define A_MOD_BEING_EDITED (1<<6) //! \brief No longer used - use sub-ob selection #define A_MOD_USE_SEL (1<<7) //! \brief Modifier is disabled in viewports only #define A_MOD_DISABLED_INVIEWS (1<<8) //! \brief Modifier is disabled in renderer only #define A_MOD_DISABLED_INRENDER (1<<9) //!@} /*! \name Modapp flags */ //!@{ //! \brief Used internally #define A_MODAPP_DISABLED (1<<5) //! \brief parent node is selected #define A_MODAPP_SELECTED (1<<6) //! \brief Used internally #define A_MODAPP_DISPLAY_ACTIVE (1<<7) //! \brief Used internally #define A_MODAPP_DYNAMIC_BOX (1<<8) //! \brief Render begin turns this on and render end turns it off #define A_MODAPP_RENDERING (1<<9) //!@} //! \brief When the last modifier is deleted form this derived object, don't delete the derived object #define A_DERIVEDOBJ_DONTDELETE (1<<9) /*! \name Control flags */ //!@{ //! \brief Used internally #define A_ORT_MASK 7 //! \brief Uses bits 5,6 and 7 to store ORT #define A_ORT_BEFORESHIFT 5 //! \brief Uses bits 8,9 and 10 to store ORT #define A_ORT_AFTERSHIFT 8 //! \brief Used internally #define A_CTRL_DISABLED (1<<11) //! \brief Indicates that the ORT is disabled #define A_ORT_DISABLED (1<<19) //!@} /*! \name Inode flags */ //!@{ //! \brief Terminates the top of an IK chain #define A_INODE_IK_TERMINATOR (1<<5) //! \brief The position is pinned #define A_INODE_IK_POS_PINNED (1<<6) //! \brief The rotation is pinned #define A_INODE_IK_ROT_PINNED (1<<7) #ifdef _OSNAP #define A_INODE_CLONE_TARGET (1<<8) #endif //! \brief Used internally only #define A_INODE_IN_UPDATE (1<<9) //! \brief Flag is set if it's updating it's TM. Don't Call GetNodeTM if it is. #define A_INODE_IN_UPDATE_TM (1<<10) //!@} //! \brief Needed for CompositeBase and its children /*! \note CompositeBase derives from ShapeObject) */ #define A_COMPONENT_LOCKED (1<<19) //! \brief Don't call RescaleWorldUnits on sub-controllers #define A_TVNODE_DONTRESACLECONTROLLERS (1 << 5) /*! \name Flags for Hold and Restore logic For "lazy holding" to avoid multiple holding. */ //!@{ //! \brief Typically a plug-in would not hold unless this flag was not set. /*! Then set it once it has held something, then clear it once EndHold() is called on the RestoreObj. This will keep it from putting multiple restore objects in one cycle. See Undo/Redo for more details. */ #define A_HELD (1<<12) //! \brief Similar to A_HELD except is used by controllers #define A_SET (1<<13) //! \brief Used internally /*! Deleted but kept around for UNDO */ #define A_IS_DELETED (1<<14) //! \brief Used internally /*! To prevent AutoDelete from being re-entered. */ #define A_BEING_AUTO_DELETED (1<<15) //!@} //! \brief Reserved for future internal use. #define A_RESERVED_B16 (1<<16) //! \brief Used internally /*! Used by FileLink for replacing Acad controllers, and is used on controllers. \note Nothing else should use it. */ #define A_CHANGE_PARENTS_DONE (1<<17) //! \brief Used internally /*! Used to flag that at least one reference has been set on a refmaker, and that the refmaker's references were checked at that time to make sure they were all NULL. */ #define A_REFMAKER_REFS_CHECKED (1<<18) /*! \name Reserved for superclass use */ //!@{ #define A_SUPERCLASS1 (1<<20) #define A_SUPERCLASS2 (1<<21) //!@} /*! <A name="Animatable_Plugin_Flags"></A> \name Reserved for use by plugins These flags are not persisted with the max file, thus they should only be used as temporary storage. It is highly recommended that plugin code clears the flag it wishes to use before starting to set it on Animatable instances.*/ //!@{ #define A_PLUGIN1 (1<<22) #define A_PLUGIN2 (1<<23) #define A_PLUGIN3 (1<<24) #define A_PLUGIN4 (1<<25) //!@} //! \brief Used to test for a dependency #define A_DEPENDENCY_TEST (1<<26) //! \brief Ref target isn't deleted when dependents goes to 0 if this flag is set. /*! Setting this flag will keep an item from being deleted when you delete a reference to it. For example, if you need to swap references for two items. For instance, say you have two nodes and two objects and you want to swap the object reference of the nodes. If you simply call ReplaceReference() on one node with the other node's object, the old object will get deleted because nothing else is referencing it anymore. By setting this flag temporarily you can keep it from being deleted and perform the swap. */ #define A_LOCK_TARGET (1<<27) /*! \name General work flags <A name="Animatable_Work_Flags"></A> These flags can be used by both 3ds Max and plugins. These flags are not persisted with the max file, thus they should only be used as temporary storage. It is highly recommended that plugin code clears the work flag it wishes to use before starting to set it on Animatable instances.*/ //!@{ #define A_WORK1 (1<<28) #define A_WORK2 (1<<29) #define A_WORK3 (1<<30) #define A_WORK4 (1<<31) //!@} /*! \name Values for Animatable extended flags. Reserved for future internal use \see Animatable::SetAFlagEx(DWORD mask) \see Animatable::ClearAFlagEx(DWORD mask) \see Animatable::TestAFlagEx(DWORD mask) */ //!@{ #define A_EX_RESERVED_B00 (1<<0) #define A_EX_RESERVED_B01 (1<<1) #define A_EX_RESERVED_B02 (1<<2) #define A_EX_RESERVED_B03 (1<<3) #define A_EX_RESERVED_B04 (1<<4) #define A_EX_RESERVED_B05 (1<<5) #define A_EX_RESERVED_B06 (1<<6) #define A_EX_RESERVED_B07 (1<<7) #define A_EX_RESERVED_B08 (1<<8) #define A_EX_RESERVED_B09 (1<<9) #define A_EX_RESERVED_B10 (1<<10) #define A_EX_RESERVED_B11 (1<<11) #define A_EX_RESERVED_B12 (1<<12) #define A_EX_RESERVED_B13 (1<<13) #define A_EX_RESERVED_B14 (1<<14) #define A_EX_RESERVED_B15 (1<<15) #define A_EX_RESERVED_B16 (1<<16) #define A_EX_RESERVED_B17 (1<<17) #define A_EX_RESERVED_B18 (1<<18) #define A_EX_RESERVED_B19 (1<<19) #define A_EX_RESERVED_B20 (1<<20) #define A_EX_RESERVED_B21 (1<<21) #define A_EX_RESERVED_B22 (1<<22) #define A_EX_RESERVED_B23 (1<<23) #define A_EX_RESERVED_B24 (1<<24) #define A_EX_RESERVED_B25 (1<<25) #define A_EX_RESERVED_B26 (1<<26) #define A_EX_RESERVED_B27 (1<<27) #define A_EX_RESERVED_B28 (1<<28) #define A_EX_RESERVED_B29 (1<<29) #define A_EX_RESERVED_B30 (1<<30) #define A_EX_RESERVED_B31 (1<<31) //!@} /*! \name Values for Animatable::aflag The following flags are bits of the aflag data member of class Animatable. \n See methods Animatable::ClearAFlag(), Animatable::SetAFlag() and Animatable::TestAFlag() to work with these flags. */ //!\{ //! \brief Used Internally #define A_EVALUATING 1 //! \brief Used Internally #define A_NOTIFYDEP (1<<1) //! \brief Used Internally #define A_DEPENDENTS_BEING_ENUMERATED (1<<2) //! \brief Animatable is being used in a scene file load and is locked. /*! If Animatable is a ReferenceTarget, it will not be deleted when dependents goes to 0 if this flag is set. The ReferenceTarget in this case will be deleted at the end of the file load process when MaybeAutoDelete() is called on it. */ #define A_ANIMATABLE_FILE_LOAD_LOCKED (1<<3) //! \brief Used Internally #define A_OBJECT_REDUCED (1<<4) //!\}
{ "content_hash": "0f4f4355d6a530b0856875d979a85e31", "timestamp": "", "source": "github", "line_count": 283, "max_line_length": 128, "avg_line_length": 36.706713780918726, "alnum_prop": 0.694358875625722, "repo_name": "SuperMap/OGDC", "id": "54eb28a7a7401bad6251682edc3b23321e2985bb", "size": "10388", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Samples/MaxPlugins/LibShared/MaxSDK/Max2014/include/AnimatableFlags.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "313835" }, { "name": "C++", "bytes": "1831724" } ], "symlink_target": "" }
namespace niven { Route &Module::RouteBuilder::operator[](const std::string path) { auto route = std::make_shared<Route>(this->parent, this->method, this->GetPath(path)); this->parent->routes.push_back(route); return *route; } std::string Module::RouteBuilder::GetPath(std::string path) { auto relative = emg::String::trim(path, '/'); auto parent = emg::String::trim(this->parent->path, '/'); return "/" + (parent.empty() ? relative : relative.empty() ? parent : parent + "/" + relative); } }
{ "content_hash": "96aceb427b282e9cedd2fc2a5806bb6b", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 97, "avg_line_length": 25.85, "alnum_prop": 0.6499032882011605, "repo_name": "parnham/libniven", "id": "c8bdbdd4e9f662e66b45912d0b74630d18ef63fd", "size": "545", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/niven/Module.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "65" }, { "name": "C++", "bytes": "380933" }, { "name": "Earthly", "bytes": "1752" }, { "name": "Lua", "bytes": "1454" }, { "name": "Makefile", "bytes": "837" }, { "name": "Shell", "bytes": "177" } ], "symlink_target": "" }
<?php namespace flat\lib\exception; class bad_param extends \flat\lib\exception { public function get_param_key() { return $this->_key; } public function get_reason() { return $this->_reason; } public function get_reason_code() { return sprintf("%u",crc32($this->_reason)); } private $_key; private $_reason; public function __construct($key,$reason) { $this->_key = $key; $this->_reason = $reason; parent::__construct("bad param: $key, reason: $reason",$this->_value_to_code($key.$reason)); } }
{ "content_hash": "23b44d00ce30eb24f8f76e6e199ac05c", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 98, "avg_line_length": 26.761904761904763, "alnum_prop": 0.604982206405694, "repo_name": "katmore/flat", "id": "b3ae1de39649577aab4f3e9ad7df9bb7a651fc6c", "size": "1961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/flat/lib/exception/bad_param.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "144" }, { "name": "PHP", "bytes": "1529581" } ], "symlink_target": "" }
# XmlMessage This class acts as a superclass for classes which build XML documents by utilizing the factory pattern. Its purpose is to provide a convenient base for classes which encapsulate logic to generate XML using Xmlify by following a few simple conventions. If you are unfamiliar with Xmlify then review the documentation for it [here](xmlify.md). XmlMessage throws XmlMessageException if there's an error. ## Example In this example, we want to create a php class which has the single responsibility of generating the XML for a product order. The order might look something like this once converted to XML: ```xml <?xml version="1.0" encoding="UTF-8"?> <ProductOrder> <Buyer> <Name>John Doe</Name> <Title>Developer</Title> </Buyer> <Products> <Product id="1"> <ProductID>13344</ProductID> <Manufacturer>Amazon</Manufacturer> </Product> <Product id="2"> <ProductID>11119</ProductID> <Manufacturer>Amazon</Manufacturer> </Product> </Products> </ProductOrder> ``` The first convenient feature of XmlMessage is that the name we give our class will become the root element of our XML. Next we simply have to define a function called "build" which returns the content of our root element. ```php use Gunsobal\Xmlary\XmlMessage; class ProductOrder extends XmlMessage { public function build(){ return [ 'Buyer' => [ 'Name' => 'John Doe', 'Title' => 'Developer' ], 'Products' => [ 'Product' => [ [ '@attributes' => ['id' => 1], 'ProductID' => '13344', 'Manufacturer' => 'Amazon' ], [ '@attributes' => ['id' => 2], 'ProductID' => '11119', 'Manufacturer' => 'Amazon' ] ] ] ]; } } ``` Now if we run the following code we get the exact same output as the XML message described above ```php $msg = new ProductOrder(); $msg->toXml(); ``` * __NOTE:__ The build function does not need to be public, but it's often convenient in case this particular bit of XML generation needs to be re-used. However we do not want to hardcode the values for our XML so we need to specify some parameters for our class. Ideally we would want to have properties for any of the fields which contain values that might change so we would do the following changes to our class ```php class ProductOrder extends XmlMessage { public function build(){ $build = [ 'Buyer' => [ 'Name' => $this->buyer->name, 'Title' => $this->buyer->title, ] ]; for ($i = 0; $i < count($this->products); ++$i){ $build['Products']['Product'][] = [ '@attributes' => ['id' => $i + 1], 'ProductID' => $this->products[$i]->id, 'Manufacturer' => $this->products[$i]->manufacturer ]; } return $build; } } ``` Now we can simply pass a buyer object and an array of product objects to our message and it will generate the same XML as before. ```php $b = (object) [ 'name' => 'John Doe', 'title' => 'Developer' ]; $p1 = (object) [ 'id' => '13344', 'manufacturer' => 'Amazon' ]; $p2 = (object) [ 'id' => '11119','manufacturer' => 'Amazon' ]; $msg = new ProductOrder([ 'buyer' => $b, 'products' => [$p1, $p2] ]); $msg->toXml(); ``` * __NOTE:__ Any key defined in the array passed into the XML message will be accessible as a property in that class as per the factory pattern. To facilitate defensive programming, it is easy to setup the class so it throws an XmlMessageException if it doesn't get the properties it needs to generate the XML. All that needs to be done is specifying a property with an array of required properties where each key corresponds to the property, and its value will be the message displayed with the exception. ```php protected $_required = [ 'buyer' => 'Needs to be a buyer object with name and title properties', 'products' => 'Needs to be an array of product objects with id and manufacturer properties' ]; ``` * __NOTE:__ You can define more properties to change the XmlMessage, see __Configurable properties__ section. ## API Classes inheriting the XmlMessage class will get set up with a factory pattern as well as some properties to control the configuration of the XML generation. Any settings properties defined in the base class will have an underscore prefix in their name. ### Functions ```php /** * Convert this message to XML markup style string with no XML header * * @see Gunsobal\Xmlify\stringify() * @throws \BadMethodCallException * @throws \UnexpectedValueException * @return string */ public function toString() /** * Convert this message to XML string * * @see Gunsobal\Xmlify\xmlify() * @throws \BadMethodCallException * @throws \UnexpectedValueException * @return string Valid XML */ public function toXml() /** * Convert this message to DOMDocument * * @see Gunsobal\Xmlify\xmlify() * @throws \BadMethodCallException * @throws \UnexpectedValueException * @return \DOMDocument */ public function toDOM() ``` ### Configurable properties ```php /** @var string $_version Version head of XML document, defaults to 1.0 **/ protected $_version; /** @var string $_encoding Encoding head of XML document, defaults to UTF-8 **/ protected $_encoding; /** @var string $_name The name of the root element in the xml message, defaults to class name **/ protected $_name; /** @var array $_required Each key is a required field in the message and its value is a custom error message **/ protected $_required = []; ```
{ "content_hash": "f231b9dc35d8deb2e5ef9a713b9f2b7d", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 361, "avg_line_length": 33.95977011494253, "alnum_prop": 0.6332712810966322, "repo_name": "Gunsobal/Xmlary", "id": "a560c488b6c27ed0079a7b76bc26929c5f4829e2", "size": "5909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/xmlmessage.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "32" }, { "name": "PHP", "bytes": "25340" } ], "symlink_target": "" }
using System.Text; using DogAgilityCompetition.Circe; using JetBrains.Annotations; namespace DogAgilityCompetition.Controller.Engine.Storage; /// <summary> /// The outcome of a competition run, achieved by a single competitor. /// </summary> /// <remarks> /// Deeply immutable by design to allow for safe cross-thread member access. /// </remarks> public class CompetitionRunResult { public const int FaultStepSize = 5; public const int MaxFaultValue = 95; public const int RefusalStepSize = 5; public const int EliminationThreshold = 3; public const int MaxRefusalsValue = RefusalStepSize * EliminationThreshold; public Competitor Competitor { get; } public CompetitionRunTimings? Timings { get; } public int FaultCount { get; } public int RefusalCount { get; } public bool IsEliminated { get; } public int Placement { get; } public string PlacementText => Placement > 0 ? Placement.ToString() : string.Empty; public bool HasCompleted => IsEliminated || HasFinished; public bool HasFinished => Timings?.FinishTime != null; public CompetitionRunResult(Competitor competitor) { Guard.NotNull(competitor, nameof(competitor)); Competitor = competitor; } protected CompetitionRunResult(Competitor competitor, CompetitionRunTimings? timings, int faultCount, int refusalCount, bool isEliminated, int placement) : this(competitor) { Timings = timings; FaultCount = faultCount; RefusalCount = refusalCount; IsEliminated = isEliminated; Placement = placement; } public CompetitionRunResult ChangeCompetitor(Competitor competitor) { Guard.NotNull(competitor, nameof(competitor)); return new CompetitionRunResult(competitor, Timings, FaultCount, RefusalCount, IsEliminated, Placement); } public CompetitionRunResult ChangeTimings(CompetitionRunTimings? timings) { return new CompetitionRunResult(Competitor, timings, FaultCount, RefusalCount, IsEliminated, Placement); } public CompetitionRunResult ChangeFaultCount(int faultCount) { AssertFaultCountIsValid(faultCount); return new CompetitionRunResult(Competitor, Timings, faultCount, RefusalCount, IsEliminated, Placement); } [AssertionMethod] public static void AssertFaultCountIsValid(int faultCount) { if (faultCount is < 0 or > MaxFaultValue || faultCount % FaultStepSize != 0) { throw new ArgumentOutOfRangeException(nameof(faultCount), faultCount, $"faultCount must be in range [0-{MaxFaultValue}] and dividable by {FaultStepSize}."); } } public CompetitionRunResult ChangeRefusalCount(int refusalCount) { AssertRefusalCountIsValid(refusalCount); return new CompetitionRunResult(Competitor, Timings, FaultCount, refusalCount, IsEliminated, Placement); } [AssertionMethod] public static void AssertRefusalCountIsValid(int refusalCount) { if (refusalCount is < 0 or > MaxRefusalsValue || refusalCount % RefusalStepSize != 0) { throw new ArgumentOutOfRangeException(nameof(refusalCount), refusalCount, $"refusalCount must be in range [0-{MaxRefusalsValue}] and dividable by {RefusalStepSize}."); } } public CompetitionRunResult ChangeIsEliminated(bool isEliminated) { return new CompetitionRunResult(Competitor, Timings, FaultCount, RefusalCount, isEliminated, Placement); } public CompetitionRunResult ChangePlacement(int placement) { return new CompetitionRunResult(Competitor, Timings, FaultCount, RefusalCount, IsEliminated, placement); } public CompetitionRunTimings UpdateTimingsFrom(TimeSpanWithAccuracy? intermediateTime1, TimeSpanWithAccuracy? intermediateTime2, TimeSpanWithAccuracy? intermediateTime3, TimeSpanWithAccuracy? finishTime) { RecordedTime startTime = CreateBestPossibleStartTime(); CompetitionRunTimings timings = Timings ?? new CompetitionRunTimings(startTime); // @formatter:keep_existing_linebreaks true timings = timings .ChangeIntermediateTime1(TryCreateRecordedTime(startTime, intermediateTime1)) .ChangeIntermediateTime2(TryCreateRecordedTime(startTime, intermediateTime2)) .ChangeIntermediateTime3(TryCreateRecordedTime(startTime, intermediateTime3)) .ChangeFinishTime(TryCreateRecordedTime(startTime, finishTime)); // @formatter:keep_existing_linebreaks restore return timings; } private RecordedTime CreateBestPossibleStartTime() { // Note: In case we have no start time, we generate one here (with high precision). A low-precision elapsed // time is caused by either one or both times to be low precision. Although we cannot know the // precision of start time here, the nett effect when the precision of an elapsed time is recalculated will // be the same as long as we assume that the start time was high precision. RecordedTime startTime = Timings?.StartTime ?? new RecordedTime(TimeSpan.Zero, SystemContext.UtcNow()); return startTime; } public CompetitionRunTimings UpdateFinishTimeFrom(TimeSpanWithAccuracy? finishTime) { RecordedTime startTime = CreateBestPossibleStartTime(); CompetitionRunTimings timings = Timings ?? new CompetitionRunTimings(startTime); timings = timings.ChangeFinishTime(TryCreateRecordedTime(startTime, finishTime)); return timings; } private static RecordedTime? TryCreateRecordedTime(RecordedTime startTime, TimeSpanWithAccuracy? elapsed) { return elapsed != null ? startTime.Add(elapsed.Value) : null; } [Pure] public override string ToString() { var textBuilder = new StringBuilder(); textBuilder.Append(Competitor); if (IsEliminated) { textBuilder.Append(" has been eliminated"); } else if (Timings?.FinishTime != null) { textBuilder.Append(" finished at "); TimeSpanWithAccuracy finishTime = Timings.FinishTime.ElapsedSince(Timings.StartTime); textBuilder.Append(finishTime); if (FaultCount > 0) { textBuilder.Append(" with "); textBuilder.Append(FaultCount); textBuilder.Append(" faults"); } if (RefusalCount > 0) { textBuilder.Append(FaultCount > 0 ? " and " : " with "); textBuilder.Append(RefusalCount); textBuilder.Append(" refusals"); } } return textBuilder.ToString(); } public static bool AreEquivalent(CompetitionRunResult? first, CompetitionRunResult? second) { return EqualitySupport.EqualsWithNulls(first, second, CompetitorRunResultsAreEqual); } public static bool AreEquivalentRun(CompetitionRunResult? first, CompetitionRunResult? second) { return EqualitySupport.EqualsWithNulls(first, second, RunResultsAreEqual); } private static bool CompetitorRunResultsAreEqual(CompetitionRunResult first, CompetitionRunResult second) { return CompetitorsAreEqual(first, second) && RunResultsAreEqual(first, second); } private static bool CompetitorsAreEqual(CompetitionRunResult first, CompetitionRunResult second) { return first.Competitor == second.Competitor; } private static bool RunResultsAreEqual(CompetitionRunResult first, CompetitionRunResult second) { return EqualitySupport.EqualsWithNulls(first.Timings, second.Timings, FinishTimesAreEqual) && first.FaultCount == second.FaultCount && first.RefusalCount == second.RefusalCount && first.IsEliminated == second.IsEliminated; } private static bool FinishTimesAreEqual(CompetitionRunTimings firstTimings, CompetitionRunTimings secondTimings) { return firstTimings.FinishTime == secondTimings.FinishTime; } }
{ "content_hash": "50c1d82e8c3262a04f682a824b594c0d", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 157, "avg_line_length": 37.629629629629626, "alnum_prop": 0.7006643700787402, "repo_name": "bkoelman/DogAgilityCompetitionManagement", "id": "003aa9871e0cbef1684368697b52fbecf224243f", "size": "8128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Controller/Engine/Storage/CompetitionRunResult.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1134823" } ], "symlink_target": "" }
package com.fxc.translator.beans; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; /** * Created by fxc07 on 2016/12/11. */ public class DailyBean extends BaseBean { /** * sid : 2441 * tts : http://news.iciba.com/admin/tts/2016-12-11-day.mp3 * content : Friendship means understanding,not agreement.It means forgiveness,not forgetting.It means the memories last,even if contact is lost. * note : 友情是理解,不是妥协;是原谅,不是遗忘。即使不联系,感情依然在。 * love : 3646 * translation : 词霸小编:这句话来自言子姑娘,她说:“小女子不才,想不起来agreement的意思,于是乎发现这个句子让我牢牢记住了它,故来享之。”如果你也有这样的句子想跟大家分享的话呢,就把你想分享的句子加上你想跟小编说的话邮件发送到hiciba@wps.cn,小编会挑选比较好的分享给大家哦~今天早睡觉哦大家,明天又是辛苦的一周! * picture : http://cdn.iciba.com/news/word/20161211.jpg * picture2 : http://cdn.iciba.com/news/word/big_20161211b.jpg * caption : 词霸每日一句 * dateline : 2016-12-11 * s_pv : 0 * sp_pv : 0 * tags : [{"id":null,"name":null}] * fenxiang_img : http://cdn.iciba.com/web/news/longweibo/imag/2016-12-11.jpg */ private String sid; private String tts; private String content; private String note; private String love; private String translation; private String picture; private String picture2; private String caption; private String dateline; private String s_pv; private String sp_pv; private String fenxiang_img; private List<TagsBean> tags; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getTts() { return tts; } public void setTts(String tts) { this.tts = tts; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getLove() { return love; } public void setLove(String love) { this.love = love; } public String getTranslation() { return translation; } public void setTranslation(String translation) { this.translation = translation; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getPicture2() { return picture2; } public void setPicture2(String picture2) { this.picture2 = picture2; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getDateline() { return dateline; } public void setDateline(String dateline) { this.dateline = dateline; } public String getS_pv() { return s_pv; } public void setS_pv(String s_pv) { this.s_pv = s_pv; } public String getSp_pv() { return sp_pv; } public void setSp_pv(String sp_pv) { this.sp_pv = sp_pv; } public String getFenxiang_img() { return fenxiang_img; } public void setFenxiang_img(String fenxiang_img) { this.fenxiang_img = fenxiang_img; } public List<TagsBean> getTags() { return tags; } public void setTags(List<TagsBean> tags) { this.tags = tags; } public static class TagsBean { /** * id : null * name : null */ private Object id; private Object name; public Object getId() { return id; } public void setId(Object id) { this.id = id; } public Object getName() { return name; } public void setName(Object name) { this.name = name; } } public static DailyBean parseGson(String json) { Gson gson = new Gson(); Type type = new TypeToken<DailyBean>() { }.getType(); DailyBean bean = gson.fromJson(json, type); return bean; } }
{ "content_hash": "457b1b83a08b9b7cd665da978849ef3f", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 177, "avg_line_length": 18.497435897435896, "alnum_prop": 0.6875519822567231, "repo_name": "fxc0719/Ugly-Wife-s-Translator", "id": "86e3dda7a189447379df63828befecea5ea7a132", "size": "3953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/fxc/translator/beans/DailyBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "51909" } ], "symlink_target": "" }
Development Guidelines ====================== Dask is a community maintained project. We welcome contributions in the form of bug reports, documentation, code, design proposals, and more. This page provides resources on how best to contribute. .. note:: Dask strives to be a welcoming community of individuals with diverse backgrounds. For more information on our values, please see our `code of conduct <https://github.com/dask/governance/blob/main/code-of-conduct.md>`_ and `diversity statement <https://github.com/dask/governance/blob/main/diversity.md>`_ Where to ask for help --------------------- Dask conversation happens in the following places: #. `Dask Discourse forum`_: for usage questions and general discussion #. `Stack Overflow #dask tag`_: for usage questions #. `GitHub Issue Tracker`_: for discussions around new features or established bugs #. `Dask Community Slack`_: for real-time discussion For usage questions and bug reports we prefer the use of Discourse, Stack Overflow and GitHub issues over Slack chat. Discourse, GitHub and Stack Overflow are more easily searchable by future users, so conversations had there can be useful to many more people than just those directly involved. .. _`Dask Discourse forum`: https://dask.discourse.group .. _`Stack Overflow #dask tag`: https://stackoverflow.com/questions/tagged/dask .. _`GitHub Issue Tracker`: https://github.com/dask/dask/issues/ .. _`Dask Community Slack`: https://join.slack.com/t/dask/shared_invite/zt-mfmh7quc-nIrXL6ocgiUH2haLYA914g Separate Code Repositories -------------------------- Dask maintains code and documentation in a few git repositories hosted on the GitHub ``dask`` organization, https://github.com/dask. This includes the primary repository and several other repositories for different components. A non-exhaustive list follows: * https://github.com/dask/dask: The main code repository holding parallel algorithms, the single-machine scheduler, and most documentation * https://github.com/dask/distributed: The distributed memory scheduler * https://github.com/dask/dask-ml: Machine learning algorithms * https://github.com/dask/s3fs: S3 Filesystem interface * https://github.com/dask/gcsfs: GCS Filesystem interface * https://github.com/dask/hdfs3: Hadoop Filesystem interface * ... Git and GitHub can be challenging at first. Fortunately good materials exist on the internet. Rather than repeat these materials here, we refer you to Pandas' documentation and links on this subject at https://pandas.pydata.org/pandas-docs/stable/contributing.html Issues ------ The community discusses and tracks known bugs and potential features in the `GitHub Issue Tracker`_. If you have a new idea or have identified a bug, then you should raise it there to start public discussion. If you are looking for an introductory issue to get started with development, then check out the `"good first issue" label`_, which contains issues that are good for starting developers. Generally, familiarity with Python, NumPy, Pandas, and some parallel computing are assumed. .. _`"good first issue" label`: https://github.com/dask/dask/labels/good%20first%20issue Development Environment ----------------------- Download code ~~~~~~~~~~~~~ Make a fork of the main `Dask repository <https://github.com/dask/dask>`_ and clone the fork:: git clone https://github.com/<your-github-username>/dask.git cd dask You should also pull the latest git tags (this ensures ``pip``'s dependency resolver can successfully install Dask):: git remote add upstream https://github.com/dask/dask.git git pull upstream main --tags Contributions to Dask can then be made by submitting pull requests on GitHub. .. _develop-install: Install ~~~~~~~ From the top level of your cloned Dask repository you can install a local version of Dask, along with all necessary dependencies, using pip or conda_ .. _conda: https://conda.io/ ``pip``:: python -m pip install -e ".[complete,test]" ``conda``:: conda env create -n dask-dev -f continuous_integration/environment-3.10.yaml conda activate dask-dev python -m pip install --no-deps -e . Run Tests ~~~~~~~~~ Dask uses py.test_ for testing. You can run tests from the main dask directory as follows:: py.test dask --verbose --doctest-modules .. _py.test: https://docs.pytest.org/en/latest/ Contributing to Code -------------------- Dask maintains development standards that are similar to most PyData projects. These standards include language support, testing, documentation, and style. Python Versions ~~~~~~~~~~~~~~~ Dask supports Python versions 3.8, 3.9 and 3.10. Name changes are handled by the :file:`dask/compatibility.py` file. .. _develop-test: Test ~~~~ Dask employs extensive unit tests to ensure correctness of code both for today and for the future. Test coverage is expected for all code contributions. Tests are written in a py.test style with bare functions: .. code-block:: python def test_fibonacci(): assert fib(0) == 0 assert fib(1) == 0 assert fib(10) == 55 assert fib(8) == fib(7) + fib(6) for x in [-3, 'cat', 1.5]: with pytest.raises(ValueError): fib(x) These tests should compromise well between covering all branches and fail cases and running quickly (slow test suites get run less often). You can run tests locally by running ``py.test`` in the local dask directory:: py.test dask You can also test certain modules or individual tests for faster response:: py.test dask/dataframe py.test dask/dataframe/tests/test_dataframe.py::test_rename_index If you want the tests to run faster, you can run them in parallel using ``pytest-xdist``:: py.test dask -n auto Tests run automatically on the Travis.ci and Appveyor continuous testing frameworks on every push to every pull request on GitHub. Tests are organized within the various modules' subdirectories:: dask/array/tests/test_*.py dask/bag/tests/test_*.py dask/bytes/tests/test_*.py dask/dataframe/tests/test_*.py dask/diagnostics/tests/test_*.py For the Dask collections like Dask Array and Dask DataFrame, behavior is typically tested directly against the NumPy or Pandas libraries using the ``assert_eq`` functions: .. code-block:: python import numpy as np import dask.array as da from dask.array.utils import assert_eq def test_aggregations(): nx = np.random.random(100) dx = da.from_array(nx, chunks=(10,)) assert_eq(nx.sum(), dx.sum()) assert_eq(nx.min(), dx.min()) assert_eq(nx.max(), dx.max()) ... This technique helps to ensure compatibility with upstream libraries and tends to be simpler than testing correctness directly. Additionally, by passing Dask collections directly to the ``assert_eq`` function rather than call compute manually, the testing suite is able to run a number of checks on the lazy collections themselves. Docstrings ~~~~~~~~~~ User facing functions should roughly follow the numpydoc_ standard, including sections for ``Parameters``, ``Examples``, and general explanatory prose. By default, examples will be doc-tested. Reproducible examples in documentation is valuable both for testing and, more importantly, for communication of common usage to the user. Documentation trumps testing in this case and clear examples should take precedence over using the docstring as testing space. To skip a test in the examples add the comment ``# doctest: +SKIP`` directly after the line. .. code-block:: python def fib(i): """ A single line with a brief explanation A more thorough description of the function, consisting of multiple lines or paragraphs. Parameters ---------- i: int A short description of the argument if not immediately clear Examples -------- >>> fib(4) 3 >>> fib(5) 5 >>> fib(6) 8 >>> fib(-1) # Robust to bad inputs ValueError(...) """ .. _numpydoc: https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard Docstrings are tested under Python 3.8 on GitHub Actions. You can test docstrings with pytest as follows:: py.test dask --doctest-modules Docstring testing requires ``graphviz`` to be installed. This can be done via:: conda install -y graphviz Code Formatting ~~~~~~~~~~~~~~~ Dask uses several code linters (flake8, black, isort, pyupgrade, mypy), which are enforced by CI. Developers should run them locally before they submit a PR, through the single command ``pre-commit run --all-files``. This makes sure that linter versions and options are aligned for all developers. Optionally, you may wish to setup the `pre-commit hooks <https://pre-commit.com/>`_ to run automatically when you make a git commit. This can be done by running:: pre-commit install from the root of the Dask repository. Now the code linters will be run each time you commit changes. You can skip these checks with ``git commit --no-verify`` or with the short version ``git commit -n``. Contributing to Documentation ----------------------------- Dask uses Sphinx_ for documentation, hosted on https://readthedocs.org . Documentation is maintained in the RestructuredText markup language (``.rst`` files) in ``dask/docs/source``. The documentation consists both of prose and API documentation. The documentation is automatically built, and a live preview is available, for each pull request submitted to Dask. Additionally, you may also build the documentation yourself locally by following the instructions outlined below. How to build the Dask documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To build the documentation locally, make a fork of the main `Dask repository <https://github.com/dask/dask>`_, clone the fork:: git clone https://github.com/<your-github-username>/dask.git cd dask/docs Install the packages in ``requirements-docs.txt``. Optionally create and activate a ``conda`` environment first:: conda create -n daskdocs -c conda-forge python=3.8 conda activate daskdocs Install the dependencies with ``pip``:: python -m pip install -r requirements-docs.txt Then build the documentation with ``make``:: make html The resulting HTML files end up in the ``build/html`` directory. You can now make edits to rst files and run ``make html`` again to update the affected pages. Dask CI Infrastructure ---------------------- Github Actions ~~~~~~~~~~~~~~ Dask uses Github Actions for Continuous Integration (CI) testing for each PR. These CI builds will run the test suite across a variety of Python versions, operating systems, and package dependency versions. Additionally, if a commit message includes the phrase ``test-upstream``, then an additional CI build will be triggered which uses the development versions of several dependencies including: NumPy, pandas, fsspec, etc. The CI workflows for Github Actions are defined in `.github/workflows <https://github.com/dask/dask/tree/main/.github/workflows>`_ with additional scripts and metadata located in `continuous_integration <https://github.com/dask/dask/tree/main/continuous_integration>`_ GPU CI ~~~~~~ Pull requests are also tested with a GPU enabled CI environment provided by NVIDIA: `gpuCI <https://gpuci.gpuopenanalytics.com/>`_. Unlike Github Actions, the CI environment for gpuCI is controlled with the `rapidsai/dask-build-environment <https://github.com/rapidsai/dask-build-environment/>`_ docker image. When making commits to the `dask-build-environment repo <https://github.com/rapidsai/dask-build-environment/>`_ , a new image is built. The docker image building process can be monitored `here <https://gpuci.gpuopenanalytics.com/job/dask/job/dask-build-environment/job/branch/job/dask-build-env-main/>`_. Note, the ``dask-build-environment`` has two separate Dockerfiles for Dask and Distributed similiarlly, gpuCI will run for both `Dask <https://gpuci.gpuopenanalytics.com/job/dask/job/dask/job/prb/job/dask-prb/>`_ and `Distributed <https://gpuci.gpuopenanalytics.com/job/dask/job/distributed/job/prb/job/distributed-prb/>`_ For each PR, gpuCI will run all tests decorated with the pytest marker ``@pytest.mark.gpu``. This is configured in the `gpuci folder <https://github.com/dask/dask/tree/main/continuous_integration/gpuci>`_ . Like Github Actions, gpuCI will not run when first time contributors to Dask or Distributed submit PRs. In this case, the gpuCI bot will comment on the PR: .. note:: Can one of the admins verify this patch? .. image:: images/gputester-msg.png :alt: "Screenshot of a GitHub comment left by the GPUtester bot, where the comment says 'Can one of the admins verify this patch?'." Dask Maintainers can then approve gpuCI builds for these PRs with following choices: - To only approve the PR contributor for the current PR, leave a comment which states ``ok to test`` - To approve the current PR and all future PRs from the contributor, leave a comment which states ``add to allowlist`` For more information about gpuCI please consult the `docs page <https://docs.rapids.ai/gpuci>`_ .. _Sphinx: https://www.sphinx-doc.org/
{ "content_hash": "5905b7d8565526a6e001ae02c13b8df6", "timestamp": "", "source": "github", "line_count": 383, "max_line_length": 135, "avg_line_length": 34.595300261096604, "alnum_prop": 0.7313207547169811, "repo_name": "jakirkham/dask", "id": "625823f26bc589c7b73bb131e5b2384756cbb9a9", "size": "13250", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "docs/source/develop.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jinja", "bytes": "6086" }, { "name": "Python", "bytes": "4588734" }, { "name": "Shell", "bytes": "5098" } ], "symlink_target": "" }
// BLASTX IMPLEMENTIERUNG VON ANNKATRIN BRESSIN UND MARJAN FAIZI // SOFTWAREPROJEKT VOM 2.4. - 29.5.2012 // VERSION VOM 04.MAI.2013 #ifndef SANDBOX_MY_SANDBOX_APPS_BLASTX_OWN_FUNCTIONS_ #include <iostream> #include <seqan/arg_parse.h> #include <seqan/sequence.h> #include <seqan/seq_io.h> #include <seqan/find.h> #include <seqan/index.h> #include <seqan/basic.h> #include <cstring> #include <seqan/index_extras.h> #include <seqan/score.h> #include <algorithm> #include <typeinfo> #include <seqan/align.h> using namespace std; using namespace seqan; typedef StringSet<String<AminoAcid> > StrSetSA; typedef Iterator<StringSet<String<char> > >::Type TStringSetIterator; typedef Align<String<AminoAcid>, ArrayGaps> TAlign; /** *@brief In dieser Datei befindet sich die Deklaration der Klasse Variable. * Die Klasse speichert alle Benutzereingaben. */ class Variable{ public: String<char> fasta_file; /**< Dateipfad zur Proteindatenbank */ String<char> fastq_file; /**< Dateipfad zu den Reads */ int seed; /**< Laenge der seeds */ unsigned size_alp; /**< Auf wieviel Zeichen soll das Alphabet reduziert werden */ String<unsigned int> numb_alp; /**< Wieviele verschiedene Alphabete soll es geben*/ int hamming_distance; /**< Groesse der Hamming-Distanz bei nicht exakter Suche */ }; class Match_found{ public: String<unsigned int> position_read; /**< Position Read in StringSet trans_reads */ String<unsigned int> begin_read; /**< begin in read */ String<unsigned int> end_read; /**< end in read */ String<unsigned int> position_protein; /**< begin in protein */ String<unsigned int> begin_protein; /**< begin in protein */ String<unsigned int> end_protein; /**< end in protein */ }; template <typename Tchar> int GET_DATAS(String<char> & file,StringSet<String<Tchar> > & sequence,StringSet<String<char> > & id){ /** *@brief GET_DATAS oeffnet die Inputfiles und laedt sie in ihre entsprechenden container *@param file Name der Inputfile *@param sequence Sequenzen in den Files *@param id Ids der verschiedenen Sequenzen *@return Gibt 0 zurueck wenn die Daten erfolgreich gespeichert wurden und 1 falls es fehlschlaegt */ SequenceStream seqStream(toCString(file)); if (!isGood(seqStream)){ std::cerr << "ERROR: Could not open the file.\n"; return 1; } readAll(id, sequence, seqStream); return 0; } // PARSE_ARGUMENTS.CPP --------------------------------------------------------------------------- // INITIALISIERUNG DER KLASSE VARIABLE MIT DEFAULT WERTEN void DEFAULT_VALUES(Variable & comVal); // WERTE AUS KOMMANDOZEILE WERDEN GEPARST UND IN comVal GESCHRIEBEN // WENN DAS PARSEN FEHL SCHLAEGT DANN RETURN WERT 1 // SONST SCHLIEßt DIE FUNKTION MIT RETURN WERT 0 int PARSE_ARGUMENTS(int argc,char const ** argv,Variable & comVal); // int check_values(Variable & comVal,StringSet<String<Dna> > & Reads); // PARSE_ARGUMENTS.CPP --------------------------------------------------------------------------- // ALPHABET.CPP ---------------------------------------------------------------------------------- StringSet<String<AminoAcid> > GET_ALPHABET_FORCE(); StringSet<String<AminoAcid> > GET_ALPHABET(unsigned & size_alp, String<unsigned int> & numb_alp); // ALPHABET.CPP ---------------------------------------------------------------------------------- // FINDER.CPP ------------------------------------------------------------------------------------ int get_read_position(unsigned int & pattern_pos,StringSet<int> & found_reads,int binary); // SPEICHERT MATCH INFORMATIONEN IN MATCH_FOUND KLASSE int append_to_match_found(Match_found & seed_found,Pair<unsigned int,unsigned int> & begin_found_prot,Pair<unsigned int,unsigned int> & end_found_prot,Pair<unsigned int,unsigned int> & pattern_found,int & seed,StringSet<int> & found_reads); // FINDET MATCHES DER LAENGE SEED FUER EIN DATENSATZ VON TRANS_READS UND EINEN DATENSATZ TRANS_PROTEINE UND SPEICHERT // DIESE IN EINE KLASSE VON MATCH_FOUND int find_matches(StrSetSA & trans_proteine,StrSetSA & trans_reads,int & seed,int & distance,Match_found & seed_found); // FUER JEDES ALPHABET WIRD UEBERSETZT, SEED MATCHES GESUCHT, VERIFIZIERT UND ÍN EINER TEXTDATEI AUSGEGEBEN int FIND_MATCHES_FOR_ALL(StringSet<String<Dna> > & Reads,StringSet<String<char> > & ReadID,StrSetSA & Proteine,StringSet<String<char> > & ProteinID, int & seed,int & distance,StrSetSA & Alphabete); // FINDER.CPP ------------------------------------------------------------------------------------ // TRANSLATE.CPP --------------------------------------------------------------------------------- // HASH-FUNKTION GIBT FUER JEDES CODON EIN EINDEUTIGEN INT WIEDER // DER INT GIBT DIE POSITION IN EINEM ARRAY AN, WELCHER INDIREKT DIE // AMINOSAEURE GESPEICHERT HAELT int hash(int x,int y,int z); // FUNKTION BEINHALTET EIN ARRAY MIT 64 POSITIONEN WELCHE DIE ADRESSE // EINER AMINOSAEURE BEINHALTEN int get_Amino_Acid_Pos(int pos); // BEKOMMT EIN CODON UND GIBT GRUPPENNUMMER DER JEWEILIGEN AMINOSÄURE ZURUECK int get_translate_from_codon(String<Dna> & aktual_triplet,String<AminoAcid> & Alphabete,int reduziert); // BEKOMMT EIN READ UND UEBERSETZT ES ZUERST UEBER EINE HASH-FUNKTION IN DIE JEWEILIGE AMINOSAEURE // DA READING FRAME NICHT BEKANNT IST AUCH IN ALLE 6 MOEGLICHEN READING FRAMES (WIRD NICHT GESPEICHERT) // SONDERN NUR MIT DER GRUPPEN NUMMER DES JEWEILIGEN ALPHABETES IN TRANS_READS GESPEICHERT int translate(StrSetSA & trans_reads,String<Dna> & read,String<AminoAcid> & Alphabete,int frame,int reduziert); // UEBERSETZT ALLE READS FUER EIN ALPHABET int translate_reads(StringSet<String<Dna> > & Reads,StrSetSA & trans_reads,String<AminoAcid> & Alphabete,int reduziert); // BEKOMMT ALLE PROTEINSEQUENZ UND UEBERSETZT DIESE IN DAS VEREINFACHTE ALPHABET int translate_database(StrSetSA & trans_proteine,StrSetSA & protein,String<AminoAcid> & Alphabete); // TRANSLATE.CPP --------------------------------------------------------------------------------- // VERIFY.CPP ------------------------------------------------------------------------------------ // Pair<unsigned int, unsigned int> get_position_in_prot(TAlign & align,int & begin,int & end)// // int known_position(int & begin,int & end,StringSet<Pair<unsigned int, unsigned int>> & pair_position); // int verify_seed_match(String<AminoAcid> protein,String<AminoAcid> & read,Match_found & verify_found,int & begin, int & end); // int verify_all(Match_found & seed_found, int & distance,StrSetSA & trans_proteine,StrSetSA & trans_reads,Match_found & verify_found,StringSet<String<Dna> > & Reads,StrSetSA & Proteine); // VERIFY.CPP ------------------------------------------------------------------------------------ // OUTPUT.CPP ------------------------------------------------------------------------------------ void write_to_file(Match_found & seed_found, StringSet<String<char> > & proteinID, StringSet<String<char> > & readID); // OUTPUT.CPP ------------------------------------------------------------------------------------ #define SANDBOX_MY_SANDBOX_APPS_BLASTX_OWN_FUNCTIONS_ #endif
{ "content_hash": "6d1b06aa0e66f25f569f8599ecb5b881", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 240, "avg_line_length": 48.29530201342282, "alnum_prop": 0.6321567537520845, "repo_name": "bkahlert/seqan-research", "id": "204d827166c0bca1044ede441b3ae9e3e7103081", "size": "7196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw/pmsb13/pmsb13-data-20130530/sources/fjt74l9mlcqisdus/2013-05-10T22-25-22.981+0200/sandbox/my_sandbox/apps/blastX/own_functions.h", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
namespace blink { class WebLocalFrame; class WebURL; class WebView; } // namespace blink namespace content { class BlinkTestRunner; class GamepadController; class TestRunner; class WebViewTestProxy; class TestInterfaces { public: TestInterfaces(); ~TestInterfaces(); void SetMainView(blink::WebView* web_view); void Install(blink::WebLocalFrame* frame); void ResetAll(); bool TestIsRunning(); void SetTestIsRunning(bool running); void ConfigureForTestWithURL(const blink::WebURL& test_url, bool protocol_mode); void WindowOpened(WebViewTestProxy* proxy); void WindowClosed(WebViewTestProxy* proxy); // This returns the BlinkTestRunner from the oldest created WebViewTestProxy. // TODO(lukasza): Using the first BlinkTestRunner as the main BlinkTestRunner // is wrong, but it is difficult to change because this behavior has been // baked for a long time into test assumptions (i.e. which PrintMessage gets // delivered to the browser depends on this). BlinkTestRunner* GetFirstBlinkTestRunner(); TestRunner* GetTestRunner(); // TODO(danakj): This is a list of all RenderViews not of all windows. There // will be a RenderView for each frame tree fragment in the process, not just // one per window. We should only return the RenderViews with a local main // frame. // TODO(danakj): Some clients want a list of the main frames (maybe most/all?) // so can we add a GetMainFrameList() or something? const std::vector<WebViewTestProxy*>& GetWindowList(); private: std::unique_ptr<GamepadController> gamepad_controller_; std::unique_ptr<TestRunner> test_runner_; std::vector<WebViewTestProxy*> window_list_; blink::WebView* main_view_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TestInterfaces); }; } // namespace content #endif // CONTENT_SHELL_RENDERER_WEB_TEST_TEST_INTERFACES_H_
{ "content_hash": "8a4513ea9b188f7562de97e7a0e37d00", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 80, "avg_line_length": 32.89473684210526, "alnum_prop": 0.7392, "repo_name": "endlessm/chromium-browser", "id": "a82fd8d4493e89dba726b35e4fd60ef112e2a287", "size": "2257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/shell/renderer/web_test/test_interfaces.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace es = CPM_ES_NS; namespace esys = CPM_ES_SYSTEMS_NS; namespace { // We may want to enforce that these components have bson serialization members // (possibly a static assert?). struct CompPosition { CompPosition() {} CompPosition(const glm::vec3& pos) {position = pos;} void checkEqual(const CompPosition& pos) const { EXPECT_FLOAT_EQ(position.x, pos.position.x); EXPECT_FLOAT_EQ(position.y, pos.position.y); EXPECT_FLOAT_EQ(position.z, pos.position.z); } // What this 'struct' is all about -- the data. glm::vec3 position; }; struct CompHomPos { CompHomPos() {} CompHomPos(const glm::vec4& pos) {position = pos;} void checkEqual(const CompHomPos& pos) const { EXPECT_FLOAT_EQ(position.x, pos.position.x); EXPECT_FLOAT_EQ(position.y, pos.position.y); EXPECT_FLOAT_EQ(position.z, pos.position.z); EXPECT_FLOAT_EQ(position.w, pos.position.w); } // DATA glm::vec4 position; }; struct CompGameplay { CompGameplay() : health(0), armor(0) {} CompGameplay(int healthIn, int armorIn) { this->health = healthIn; this->armor = armorIn; } void checkEqual(const CompGameplay& gp) const { EXPECT_EQ(health, gp.health); EXPECT_EQ(armor, gp.armor); } // DATA int32_t health; int32_t armor; }; // Component positions. associated with id. The first component is not used. std::vector<CompPosition> posComponents = { glm::vec3(0.0, 0.0, 0.0), glm::vec3(1.0, 2.0, 3.0), glm::vec3(5.5, 6.0, 10.7), glm::vec3(1.5, 3.0, 107), glm::vec3(4.0, 7.0, 9.0), glm::vec3(2.92, 89.0, 4.0), }; std::vector<CompHomPos> homPosComponents = { glm::vec4(0.0, 0.0, 0.0, 0.0), glm::vec4(1.0, 11.0, 41.0, 51.0), glm::vec4(2.0, 12.0, 42.0, 52.0), glm::vec4(3.0, 13.0, 43.0, 53.0), glm::vec4(4.0, 14.0, 44.0, 54.0), glm::vec4(5.0, 15.0, 45.0, 55.0), }; std::vector<CompGameplay> gameplayComponents = { CompGameplay(0, 0), CompGameplay(45, 21), CompGameplay(23, 123), CompGameplay(99, 892), CompGameplay(73, 64), CompGameplay(23, 92), }; // This basic system will apply, every frame, to entities with the CompPosition, // CompHomPos, and CompGameplay components. class BasicSystem : public es::GenericSystem<false, CompPosition, CompHomPos, CompGameplay> { public: static std::map<uint64_t, bool> invalidComponents; static int32_t runCount; void execute(es::ESCoreBase&, uint64_t entityID, const CompPosition* pos, const CompHomPos* homPos, const CompGameplay* gp) override { // Check to see if this entityID should have been executed. if (invalidComponents.find(entityID) != invalidComponents.end()) FAIL() << "BasicSystem attempt to execute on an invalid component." << std::endl; // Check the values contained in each of pos, homPos, and gp. pos->checkEqual(posComponents[entityID]); homPos->checkEqual(homPosComponents[entityID]); gp->checkEqual(gameplayComponents[entityID]); ++runCount; } // Compile time polymorphic function required by CerealCore when registering. static const char* getName() { return "ren:BasicSystem"; } }; int32_t BasicSystem::runCount = 0; class SystemOne : public es::GenericSystem<false, CompHomPos, CompGameplay> { public: static std::map<uint64_t, bool> invalidComponents; static int32_t runCount; void execute(es::ESCoreBase&, uint64_t entityID, const CompHomPos* homPos, const CompGameplay* gp) override { // Basic system should run before SystemOne because of alphabetical order. EXPECT_GT(BasicSystem::runCount, 0); // Check to see if this entityID should have been executed. if (invalidComponents.find(entityID) != invalidComponents.end()) FAIL() << "SystemOne attempt to execute on an invalid component." << std::endl; // Check the values contained in each of pos, homPos, and gp. homPos->checkEqual(homPosComponents[entityID]); gp->checkEqual(gameplayComponents[entityID]); ++runCount; } // Compile time polymorphic function required by CerealCore when registering. static const char* getName() { return "ren:SystemOne"; } }; int32_t SystemOne::runCount = 0; std::map<uint64_t, bool> BasicSystem::invalidComponents; std::map<uint64_t, bool> SystemOne::invalidComponents; TEST(EntitySystem, BasicConstruction) { // Generate entity system core. std::shared_ptr<es::ESCore> core(new es::ESCore()); std::shared_ptr<esys::SystemCore> systems(new esys::SystemCore); systems->clearRegisteredSystems(); // Register systems. All of the above text regarding components applies // to systems as well. systems->registerSystem<SystemOne>(); systems->registerSystem<BasicSystem>(); // Destroy the core and re-register components and systems. // Then deserialize the data from memory to see if the correct components // and systems are serialized back in. uint64_t rootID = core->getNewEntityID(); uint64_t id = rootID; core->addComponent(id, posComponents[id]); core->addComponent(id, homPosComponents[id]); core->addComponent(id, gameplayComponents[id]); id = core->getNewEntityID(); core->addComponent(id, homPosComponents[id]); core->addComponent(id, gameplayComponents[id]); BasicSystem::invalidComponents.insert(std::make_pair(id, true)); id = core->getNewEntityID(); core->addComponent(id, posComponents[id]); core->addComponent(id, homPosComponents[id]); core->addComponent(id, gameplayComponents[id]); id = core->getNewEntityID(); core->addComponent(id, posComponents[id]); core->addComponent(id, homPosComponents[id]); core->addComponent(id, gameplayComponents[id]); std::shared_ptr<BasicSystem> sysBasic(new BasicSystem()); std::shared_ptr<SystemOne> sysOne(new SystemOne()); core->renormalize(true); systems->addActiveSystemViaType<SystemOne>(); systems->addActiveSystemViaType<BasicSystem>(); systems->renormalize(); systems->runSystems(*core, 0); systems->runSystems(*core, 0); EXPECT_EQ(2 * 3, BasicSystem::runCount); EXPECT_EQ(2 * 4, SystemOne::runCount); } }
{ "content_hash": "43bcc83c059a974e7bc9bf428aa3823c", "timestamp": "", "source": "github", "line_count": 213, "max_line_length": 91, "avg_line_length": 28.6056338028169, "alnum_prop": 0.691285081240768, "repo_name": "iauns/cpm-es-systems", "id": "32cce45c26589f4c91c9274c006f015ff1835d9e", "size": "6277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/TestGS.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "42121" }, { "name": "Shell", "bytes": "333" } ], "symlink_target": "" }
import unittest import os import uuid from nvm import pmem class MapMixin(object): def create_mapping(self, size=4096): filename = "{}.pmem".format(uuid.uuid4()) mapping = pmem.map_file(filename, size, pmem.FILE_CREATE | pmem.FILE_EXCL, 0666) return filename, mapping def clear_mapping(self, filename, mapping): pmem.unmap(mapping) os.unlink(filename) class TestCheckVersion(unittest.TestCase): def test_version_ok(self): self.assertTrue(pmem.check_version(1, 0)) def test_wrong_version(self): with self.assertRaises(RuntimeError): pmem.check_version(1000, 1000) class TestHasHardwareDrain(unittest.TestCase): def test_has_hw_drain(self): self.assertIn(pmem.has_hw_drain(), [True, False]) class TestMap(unittest.TestCase, MapMixin): def test_map_ok(self): filename, mapping = self.create_mapping() self.assertIsInstance(mapping, pmem.MemoryBuffer) self.clear_mapping(filename, mapping) class TestMemoryBuffer(unittest.TestCase, MapMixin): def test_len(self): filename, mapping = self.create_mapping(4096) self.assertEqual(len(mapping), 4096) self.clear_mapping(filename, mapping) def test_write_seek_read(self): filename, mapping = self.create_mapping() test_str = "testing" test_len = len(test_str) mapping.write(test_str) mapping.seek(0) self.assertEqual(mapping.read(test_len), test_str) self.clear_mapping(filename, mapping) def test_write_out_range(self): filename, mapping = self.create_mapping(128) with self.assertRaises(RuntimeError): mapping.write('0' * 256) self.clear_mapping(filename, mapping) class TestIsPmem(unittest.TestCase, MapMixin): def test_is_pmem(self): filename, mapping = self.create_mapping() self.assertIn(pmem.is_pmem(mapping), [True, False]) self.clear_mapping(filename, mapping) class TestPersist(unittest.TestCase, MapMixin): def test_persist(self): filename, mapping = self.create_mapping() pmem.persist(mapping) self.clear_mapping(filename, mapping) class TestMsync(unittest.TestCase, MapMixin): def test_msync(self): filename, mapping = self.create_mapping() ret = pmem.msync(mapping) self.assertEqual(ret, 0) self.clear_mapping(filename, mapping) class TestFlush(unittest.TestCase, MapMixin): def test_flush(self): filename, mapping = self.create_mapping() pmem.flush(mapping) self.clear_mapping(filename, mapping) class TestHwDrain(unittest.TestCase, MapMixin): def test_hw_drain(self): filename, mapping = self.create_mapping() pmem.drain(mapping) self.clear_mapping(filename, mapping) class TestMapContext(unittest.TestCase): def test_map_context(self): filename = "{}.pmem".format(uuid.uuid4()) with pmem.map_file(filename, 4096, pmem.FILE_CREATE | pmem.FILE_EXCL, 0666) as reg: reg.write("test") os.unlink(filename) if __name__ == '__main__': unittest.main()
{ "content_hash": "a861fba438630798fe8137f11ae22aa6", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 66, "avg_line_length": 29.392857142857142, "alnum_prop": 0.6351761846901579, "repo_name": "perone/pynvm", "id": "68f6fa00e90980d2dd93a8a2f047e9cf20b3acf6", "size": "3292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_pmem.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "28506" } ], "symlink_target": "" }
{% verbatim %} <div class="content container" data-ng-cloak data-ng-controller="semDomTransAppManagementCtrl"> <div id="sfchecks-hmenu" class="hdrnav"> <ul class="topNav"> <li class="here"><a href="/app/projects">My Projects</a></li> <li><a href="/app/activity">Activity</a></li> </ul> <br /> </div> <div style="padding-top:10px"> <sil-notices></sil-notices> <h2 style="font-weight:normal">Semantic Domain Translation App Management</h2> <tabset ng-show="dtoLoaded"> <tab heading="Export"> <div ng-show="languages.length > 0"> <p>Export the following semantic domain language lists in FLEx XML format</p> <button ng-click="doExport()" class="btn btn-primary">Export {{languages.length}} languages</button> <span style="font-weight: bold" ng-repeat="language in languages"><a ng-href="/app/semdomtrans/{{language.id}}">{{language.name}}</a> </span> </div> <div ng-hide="languages.length > 0"> No Semantic Domain Translations Exist </div> </tab> </tabset> </div> </div> {% endverbatim %}
{ "content_hash": "7a3f0d03cdf7736a531dad4333e1a877", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 158, "avg_line_length": 41.42857142857143, "alnum_prop": 0.6008620689655172, "repo_name": "sil-student-projects/web-scriptureforge", "id": "b6329ac60600bf272cd5d9e61ca0d01af7fb875d", "size": "1160", "binary": false, "copies": "1", "ref": "refs/heads/master-sbu", "path": "src/angular-app/languageforge/semdomtrans/app-management/ng-app.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "189" }, { "name": "Batchfile", "bytes": "707" }, { "name": "C#", "bytes": "5038" }, { "name": "CSS", "bytes": "238365" }, { "name": "HTML", "bytes": "437125" }, { "name": "JavaScript", "bytes": "5874376" }, { "name": "PHP", "bytes": "1334582" }, { "name": "Python", "bytes": "64414" }, { "name": "Ruby", "bytes": "5277" }, { "name": "Shell", "bytes": "14967" } ], "symlink_target": "" }
<?php namespace Tests\AppBundle\Form; use AppBundle\Criteria\Model as ModelCriteria; use AppBundle\Form\Criteria as CriteriaForm; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Form\Form; class CriteriaTest extends KernelTestCase { /** * @var Form */ private $form; public function setup() { self::bootKernel(); $container = self::$kernel->getContainer(); $formFactory = $container->get('form.factory'); $this->form = $formFactory->create( CriteriaForm::class, new ModelCriteria(), [ 'csrf_protection' => false ] ); } public function testFormFields() { $this->assertSame(5, $this->form->count()); $hasNameField = $this->form->has('name'); $this->assertTrue($hasNameField); } public function testFormWithValidData() { $submittedData = [ 'name' => 'test', 'limit' => 1, 'offset' => 2, 'orderField' => 'name', 'orderDirection' => 'DESC' ]; $this->form->submit($submittedData); $isValid = $this->form->isValid(); $this->assertTrue($isValid); $criteria = $this->form->getData(); $this->assertInstanceOf(ModelCriteria::class, $criteria); $this->assertSame('test', $criteria->getName()); $this->assertSame(1, $criteria->getLimit()); $this->assertSame(2, $criteria->getOffset()); $this->assertSame('name', $criteria->getOrderField()); $this->assertSame('DESC', $criteria->getOrderDirection()); } public function testFormWithInvalidData() { $submittedData = ['name' => '']; $this->form->submit($submittedData); $isValid = $this->form->isValid(); $this->assertFalse($isValid); } }
{ "content_hash": "8d518ef6d641a900937e7d6920e75918", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 66, "avg_line_length": 26.34722222222222, "alnum_prop": 0.562467053241961, "repo_name": "danbelden/symfony-crud-api", "id": "e5a63305aa2d3bc81ac3940aa274e357691a2852", "size": "1897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/AppBundle/Form/CriteriaTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "88684" }, { "name": "Dockerfile", "bytes": "198" }, { "name": "HTML", "bytes": "4872" }, { "name": "PHP", "bytes": "148026" } ], "symlink_target": "" }
package eu.hyvar.feature.mapping.resource.hymapping.debug; public class HymappingDebugVariable { // The generator for this class is currently disabled by option // 'disableDebugSupport' in the .cs file. }
{ "content_hash": "aa4a4a8058a8d9622876462f3ee0468f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 64, "avg_line_length": 26.25, "alnum_prop": 0.780952380952381, "repo_name": "DarwinSPL/DarwinSPL", "id": "52d41686cee6b19af6054849765f582dac29337e", "size": "255", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/eu.hyvar.feature.mapping.resource.hymapping/src-gen/eu/hyvar/feature/mapping/resource/hymapping/debug/HymappingDebugVariable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "18119" }, { "name": "CSS", "bytes": "367911" }, { "name": "FreeMarker", "bytes": "13035" }, { "name": "GAP", "bytes": "1672492" }, { "name": "Gherkin", "bytes": "987" }, { "name": "Java", "bytes": "78282002" }, { "name": "JavaScript", "bytes": "145859" }, { "name": "Smalltalk", "bytes": "1783" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/spec_helper' describe "arrays" do def contain_same_elements_as(expected) simple_matcher "array with same elements in any order as #{expected.inspect}" do |actual| if actual.size == expected.size a, e = actual.dup, expected.dup until e.empty? do if i = a.index(e.pop) then a.delete_at(i) end end a.empty? else false end end end describe "can be matched by their contents disregarding order" do subject { [1,2,2,3] } it { should contain_same_elements_as([1,2,2,3]) } it { should contain_same_elements_as([2,3,2,1]) } it { should_not contain_same_elements_as([3,3,2,1]) } end describe "fail the match with different contents" do subject { [1,2,3] } it { should_not contain_same_elements_as([2,3,4])} it { should_not contain_same_elements_as([1,2,2,3])} it { should_not contain_same_elements_as([1,2])} end end
{ "content_hash": "710ae1c703b85d0e788bb2632711a019", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 93, "avg_line_length": 31.225806451612904, "alnum_prop": 0.618801652892562, "repo_name": "shanti/olio", "id": "46cc6375ec0a77f1dcf095f7fc705ddbacaa8977", "size": "1756", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tags/0.2-final/webapp/rails/trunk/vendor/plugins/rspec/examples/passing/simple_matcher_example.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2669517" }, { "name": "JavaScript", "bytes": "1058343" }, { "name": "PHP", "bytes": "1001174" }, { "name": "Perl", "bytes": "252989" }, { "name": "Ruby", "bytes": "2400328" }, { "name": "Shell", "bytes": "57800" } ], "symlink_target": "" }
<!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{ site.baseurl }}/">{{ site.title }}</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="{{ site.baseurl }}/">主页</a> </li> <li> <a href="/archive">列表</a> </li> <li> <a href="/tags">标签</a> </li> <li> <a href="/plan">计划</a> </li> <li> <a href="/resume">简历</a> </li> <li> <a href="/about">关于</a> </li> <!-- {% for page in site.pages %}{% if page.title %} <li> <a href="{{ page.url | prepend: site.baseurl }}">{{ page.title }}</a> </li> {% endif %}{% endfor %} --> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav>
{ "content_hash": "18f2b2665c0cf2b9be4cea8e7b7dfb93", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 123, "avg_line_length": 37.326530612244895, "alnum_prop": 0.41224712957900495, "repo_name": "caijun-carr/caijun-carr.github.io", "id": "7e1308af67ac100e30d89263a8df157f3dbf4af3", "size": "1853", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/nav.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23254" }, { "name": "HTML", "bytes": "18440" }, { "name": "JavaScript", "bytes": "54353" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace HaloOnline.Server.Model.TitleResource.TitleConfigurations { public class PlayerLevel : TitleInstance { public PlayerLevel(string instanceName) : base(instanceName) { Name = ""; LevelIndex = 0; XpUnlock = 0; ItemsRecieved = new List<string>(); ItemsUnlocked = new List<string>(); } [JsonIgnore] public string Name { get; set; } [JsonIgnore] public int LevelIndex { get; set; } [JsonIgnore] public int? XpUnlock { get; set; } [JsonIgnore] public List<string> ItemsRecieved { get; set; } [JsonIgnore] public List<string> ItemsUnlocked { get; set; } public override string ClassName { get { return TitleInstanceConstants.PlayerLevelClassName; } } public override List<TitleProperty> Properties { get { return GetProperties().ToList(); } } private IEnumerable<TitleProperty> GetProperties() { yield return new TitlePropertyString { Name = TitleInstanceConstants.TitleInstanceName, Value = Name }; yield return new TitlePropertyInteger { Name = TitleInstanceConstants.PlayerLevelLevelIndex, Value = LevelIndex }; yield return new TitlePropertyInteger { Name = TitleInstanceConstants.PlayerLevelXpUnlock, Value = XpUnlock }; yield return new TitlePropertyStringList { Name = TitleInstanceConstants.PlayerLevelItemsRecieved, Value = ItemsRecieved }; yield return new TitlePropertyStringList { Name = TitleInstanceConstants.PlayerLevelItemsUnlocked, Value = ItemsUnlocked }; } } }
{ "content_hash": "5098fab0ad16288358af55bec98824bd", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 71, "avg_line_length": 28.98611111111111, "alnum_prop": 0.552467656923814, "repo_name": "Atvaark/Emurado", "id": "1918e90341802b53449af4196c11bfeecde5cecb", "size": "2089", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HaloOnline.Server.Model/TitleResource/TitleConfigurations/PlayerLevel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "358746" }, { "name": "CSS", "bytes": "35" }, { "name": "HTML", "bytes": "5357" }, { "name": "JavaScript", "bytes": "6499" } ], "symlink_target": "" }
"""This module contains the Resilient propagation optimizer.""" import mathadapt as ma from base import Minimizer class Rprop(Minimizer): """Rprop optimizer. Resilient propagation is an optimizer that was originally tailored towards neural networks. It can however be savely applied to all kinds of optimization problems. The idea is to have a parameter specific step rate which is determined by sign changes of the derivative of the objective function. To be more precise, given the derivative of the loss given the parameters :math:`f'(\\theta_t)` at time step :math:`t`, the :math:`i` th component of the vector of steprates :math:`\\alpha` is determined as .. math:: \\alpha_i \\leftarrow \\begin{cases} \\alpha_i \\cdot \\eta_{\\text{grow}} ~\\text{if}~ f'(\\theta_t)_i \\cdot f'(\\theta_{t-1})_i > 0 \\\\ \\alpha_i \\cdot \\eta_{\\text{shrink}} ~\\text{if}~ f'(\\theta_t)_i \\cdot f'(\\theta_{t-1})_i < 0 \\\\ \\alpha_i \\end{cases} where :math:`0 < \\eta_{\\text{shrink}} < 1 < \\eta_{\\text{grow}}` specifies the shrink and growth rates of the step rates. Typically, we will threshold the step rates at minimum and maximum values. The parameters are then adapted according to the sign of the error gradient: .. math:: \\theta_{t+1} = -\\alpha~\\text{sgn}(f'(\\theta_t)). This results in a method which is quite robust. On the other hand, it is more sensitive towards stochastic objectives, since that stochasticity might lead to bad estimates of the sign of the gradient. .. note:: Works with gnumpy. .. [riedmiller1992rprop] M. Riedmiller und Heinrich Braun: Rprop - A Fast Adaptive Learning Algorithm. Proceedings of the International Symposium on Computer and Information Science VII, 1992 Attributes ---------- wrt : array_like Current solution to the problem. Can be given as a first argument to \ ``.fprime``. fprime : Callable First derivative of the objective function. Returns an array of the \ same shape as ``.wrt``. step_shrink : float Constant to shrink step rates by if the gradients of the error do not agree over time. step_grow : float Constant to grow step rates by if the gradients of the error do agree over time. min_step : float Minimum step rate. max_step : float Maximum step rate. """ def __init__(self, wrt, fprime, step_shrink=0.5, step_grow=1.2, min_step=1E-6, max_step=1, changes_init=0.1, args=None): """Create an Rprop object. Parameters ---------- wrt : array_like Current solution to the problem. Can be given as a first argument to ``.fprime``. fprime : Callable First derivative of the objective function. Returns an array of the same shape as ``.wrt``. step_shrink : float Constant to shrink step rates by if the gradients of the error do not agree over time. step_grow : float Constant to grow step rates by if the gradients of the error do agree over time. min_step : float Minimum step rate. max_step : float Maximum step rate. args : iterable Iterator over arguments which ``fprime`` will be called with. """ super(Rprop, self).__init__(wrt, args=args) self.fprime = fprime self.step_shrink = step_shrink self.step_grow = step_grow self.min_step = min_step self.max_step = max_step self.changes_init = changes_init def __iter__(self): gradient_m1 = ma.zero_like(self.wrt) changes = ma.ones_like(self.wrt) * self.changes_init for i, (args, kwargs) in enumerate(self.args): gradient = self.fprime(self.wrt, *args, **kwargs) changes_min = changes * self.step_grow changes_max = changes * self.step_shrink gradprod = gradient_m1 * gradient changes_min *= gradprod > 0 changes_max *= gradprod < 0 changes *= gradprod == 0 # TODO actually, this should be done to changes changes_min = ma.clip(changes_min, self.min_step, self.max_step) changes_max = ma.clip(changes_max, self.min_step, self.max_step) changes += changes_min + changes_max step = -changes * ma.sign(gradient) self.wrt += step gradient_m1 = gradient yield { 'n_iter': i, 'args': args, 'kwargs': kwargs, 'gradient': gradient, 'gradient_m1': gradient_m1, 'step': step, }
{ "content_hash": "cdc2ef6af48ecab7be42acfa3e3de649", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 115, "avg_line_length": 33.04026845637584, "alnum_prop": 0.5864310379849685, "repo_name": "SFPD/rlreloaded", "id": "aaa681eb6a835e2b48bb1999b9b8d96e442fef20", "size": "4948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3rdparty/climin/rprop.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "753" }, { "name": "C++", "bytes": "88527" }, { "name": "CMake", "bytes": "33134" }, { "name": "Python", "bytes": "478983" }, { "name": "Shell", "bytes": "953" } ], "symlink_target": "" }
<!-- ~ Copyright 2016 Davide Maestroni ~ ~ 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. --> <html> <head> <title>jroutine-method</title> </head> <body> <a href="https://github.com/davide-maestroni/jroutine" target="_blank">Parallel programming on the go.</a> <h1>Overview</h1> <p> Routine method implementation based on the <a href="http://davide-maestroni.github.io/jroutine/javadoc/6/core" target="_blank">jroutine-core</a> and <a href="http://davide-maestroni.github.io/jroutine/javadoc/6/object" target="_blank">jroutine-object</a> libraries. </p> <p> This module provides classes enabling a routine implementation through simple methods. </p> <h2>Main concepts</h2> <ul> <li> <a href="http://davide-maestroni.github.io/jroutine/javadoc/6/method/com/github/dm/jrt/method/RoutineMethod.html">RoutineMethod</a> <p> Base class providing a simple way to implement a routine as an object method.<br> The method will receive input and produce outputs through channel instances passed as parameters. </p> </li> </ul> <h2>Dependencies</h2> <p> Below a full list of the included modules: </p> <ul> <li><a href="http://davide-maestroni.github.io/jroutine/javadoc/6/channel" target="_blank">jroutine-channel</a> &mdash; utility classes extending channel functionalities</li> <li><a href="http://davide-maestroni.github.io/jroutine/javadoc/6/core" target="_blank">jroutine-core</a> &mdash; core routine and channel classes</li> <li><a href="http://davide-maestroni.github.io/jroutine/javadoc/6/object" target="_blank">jroutine-object</a> &mdash; routines wrapping object and class methods</li> </ul> <h2>Usage examples</h2> <p> The code below shows how it is possible to create a routine method printing different outputs based on their types.. </p> <b>Example 1:</b> via routine method implementation. <pre> <code> final Channel&lt;Integer, Integer&gt; inputInts = JRoutineCore.io().buildChannel(); final Channel&lt;String, String&gt; inputStrings = JRoutineCore.io().buildChannel(); final Channel&lt;String, String&gt; outputChannel = JRoutineCore.io().buildChannel(); new RoutineMethod() { void print(&commat;In final Channel&lt;?, Integer&gt; inputInts, &commat;In final Channel&lt;?, String&gt; inputStrings, &commat;Out final Channel&lt;String, ?&gt; output) { final Channel&lt;?, ?&gt; inputChannel = switchInput(); if (inputChannel.hasNext()) { if (inputChannel == inputInts) { output.pass("Number: " + inputChannel.next()); } else if (inputChannel == inputStrings) { output.pass("String: " + inputChannel.next()); } } } }.call(inputInts, inputStrings, outputChannel); outputChannel.bind(new TemplateChannelConsumer&lt;String&gt;() { &#64;Override public void onOutput(final String out) { System.out.println(out); } }); </code> </pre> </body> </html>
{ "content_hash": "f321ad1fee04c57da4f37a3ec4c6fa0e", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 269, "avg_line_length": 44.07142857142857, "alnum_prop": 0.6528903295515938, "repo_name": "davide-maestroni/jroutine", "id": "2d0bde0826824d1b936fd062318f86498420da10", "size": "3702", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "method/docs/overview.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "151268" }, { "name": "Java", "bytes": "5147734" } ], "symlink_target": "" }
<!doctype html> <html id="mindmaps"> <head> <meta charset="utf-8"> <title>Framindmap</title> <link rel="shortcut icon" href="favicon.ico"> <link rel="stylesheet" href="css/common.css"> <link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/Aristo/jquery-ui-1.8.7.custom.css" /> <link rel="stylesheet" href="css/minicolors/jquery.miniColors.css"> <script id="template-float-panel" type="text/x-jquery-tmpl"> <div class="ui-widget ui-dialog ui-corner-all ui-widget-content float-panel no-select"> <div class="ui-dialog-titlebar ui-widget-header ui-helper-clearfix"> <span class="ui-dialog-title">${title}</span> <a class="ui-dialog-titlebar-close ui-corner-all" href="#" role="button"> <span class="ui-icon"></span> </a> </div> <div class="ui-dialog-content ui-widget-content"> </div> </div> </script> <script id="template-notification" type="text/x-jquery-tmpl"> <div class="notification"> {{if closeButton}} <a href="#" class="close-button">x</a> {{/if}} {{if title}} <h1 class="title">{{html title}}</h1> {{/if}} <div class="content">{{html content}}</div> </div> </script> <script id="template-open-table-item" type="text/x-jquery-tmpl"> <tr> <td><a class="title" href="#">${title}</a></td> <td>${$item.format(dates.modified)}</td> <td><a class="delete" href="#">Effacer</a></td> </tr> </script> <script id="template-open" type="text/x-jquery-tmpl"> <div id="open-dialog" class="file-dialog" title="Ouvrir une carte mentale"> <h1>Stockage local</h1> <p>Liste des cartes mentales enregistr&eacute;es dans le stockage local de votre navigateur. Cliquez sur le titre d'une carte pour l'ouvrir.</p> <table class="localstorage-filelist"> <thead> <tr> <th class="title">Titre</th> <th class="modified">Derni&egrave;re modification</th> <th class="delete"></th> </tr> </thead> <tbody class="document-list"></tbody> </table> <div class="seperator"></div> <h1>Depuis un fichier</h1> <p>Choisir une carte depuis le disque dur de l'ordinateur.</p> <div class="file-chooser"> <input type="file" /> </div> </div> </script> <script id="template-save" type="text/x-jquery-tmpl"> <div id="save-dialog" class="file-dialog" title="Enregistrer la carte mentale"> <h1>Stockage local</h1> <p>Vous pouvez enregistrer votre carte dans le stockage local de votre navigateur. Attention, cette fonctionnalit&eacute; est exp&eacute;rimentale: l'espace est limit&eacute; et il n'y a aucune garantie que votre navigateur conserve ce document ind&eacute;finiment.</p> <button id="button-save-localstorage">Enregistrer</button> <input type="checkbox" id="checkbox-autosave-localstorage"> <label for="checkbox-autosave-localstorage">Enregistrer automatiquement toutes les minutes.</label> <div class="seperator"></div> <h1>Dans un fichier</h1> <p>Enregistrer la carte dans un fichier sur l'ordinateur.</p> <p class="text-danger">Le plugin flash doit être installé et activé.</p> <div id="button-save-hdd" style="width:100px">Enregistrer</div> </div> </script> <script id="template-navigator" type="text/x-jquery-tmpl"> <div id="navigator"> <div class="active"> <div id="navi-content"> <div id="navi-canvas-wrapper"> <canvas id="navi-canvas"></canvas> <div id="navi-canvas-overlay"></div> </div> <div id="navi-controls"> <span id="navi-zoom-level"></span> <div class="button-zoom" id="button-navi-zoom-out"></div> <div id="navi-slider"></div> <div class="button-zoom" id="button-navi-zoom-in"></div> </div> </div> </div> <div class="inactive"> </div> </div> </script> <script id="template-inspector" type="text/x-jquery-tmpl"> <div id="inspector"> <div id="inspector-content"> <table id="inspector-table"> <tr> <td>Taille de police:</td> <td><div class="buttonset buttons-very-small buttons-less-padding"> <button id="inspector-button-font-size-decrease">A-</button> <button id="inspector-button-font-size-increase">A+</button> </div></td> </tr> <tr> <td>Style de police:</td> <td><div class="font-styles buttonset buttons-very-small buttons-less-padding"> <input type="checkbox" id="inspector-checkbox-font-bold" /> <label for="inspector-checkbox-font-bold" id="inspector-label-font-bold">G</label> <input type="checkbox" id="inspector-checkbox-font-italic" /> <label for="inspector-checkbox-font-italic" id="inspector-label-font-italic">I</label> <input type="checkbox" id="inspector-checkbox-font-underline" /> <label for="inspector-checkbox-font-underline" id="inspector-label-font-underline">S</label> <input type="checkbox" id="inspector-checkbox-font-linethrough" /> <label for="inspector-checkbox-font-linethrough" id="inspector-label-font-linethrough">B</label> </div> </td> </tr> <tr> <td>Couleur de police:</td> <td><input type="hidden" id="inspector-font-color-picker" class="colorpicker" /></td> </tr> <tr> <td>Couleur de branche:</td> <td><input type="hidden" id="inspector-branch-color-picker" class="colorpicker" /> <button id="inspector-button-branch-color-children" title="Appliquer la couleur de la branche &agrave; toutes les branches filles." class="right buttons-small buttons-less-padding">H&eacute;riter</button> </td> </tr> </table> </div> </div> </script> <script id="template-export-map" type="text/x-jquery-tmpl"> <div id="export-map-dialog" title="Exporter une carte mentale"> <h2 class='image-description'>Cliquer-droit sur l'image pour enregsitrer la carte et choisir "Enregistrer l'image sous..."</h2> <div id="export-preview"></div> </div> </script> </head> <body> <script src="https://framasoft.org/nav/nav.js" type="text/javascript"></script> <div id="print-area"> <p class="print-placeholder">Utiliser l'option imprimer du menu carte mentale</p> </div> <div id="container"> <div id="topbar"> <div id="toolbar"> <div id="logo" class="logo-bg"> <a href="/" style="text-decoration: none" title="Retour à l'accueil"><span style="color: #6A5687;">Fra</span><span style="color: #9BAE5F;">mindmap</span></a> </div> <div class="buttons"> <span class="buttons-left"> </span> <span class="buttons-right"> </span> </div> </div> </div> <div id="canvas-container"> <div id="drawing-area"></div> </div> <div id="bottombar"> <div id="about"> <a href="/" target="_blank">&Agrave; propos de Framindmap</a> <span style="padding: 0 4px;">|</span> <a style="font-weight: bold" href="http://contact.framasoft.org" target="_blank">Contact</a> </div> <div id="statusbar"> <div class="buttons buttons-right buttons-small buttons-less-padding"></div> </div> </div> </div> <script src="js/jquery-1.6.1.min.js"></script> <!-- JS:LIB:BEGIN --> <script src="js/libs/jquery-ui-1.8.11.custom.min.js"></script> <script src="js/libs/dragscrollable.js"></script> <script src="js/libs/jquery.hotkeys.js"></script> <script src="js/libs/jquery.mousewheel.js"></script> <script src="js/libs/jquery.minicolors.js"></script> <script src="js/libs/jquery.tmpl.js"></script> <script src="js/libs/swfobject.js"></script> <script src="js/libs/downloadify.min.js"></script> <script src="js/libs/events.js"></script> <script src="js/MindMaps.js"></script> <script src="js/Command.js"></script> <script src="js/CommandRegistry.js"></script> <script src="js/Action.js"></script> <script src="js/Util.js"></script> <script src="js/Point.js"></script> <script src="js/Document.js"></script> <script src="js/MindMap.js"></script> <script src="js/Node.js"></script> <script src="js/NodeMap.js"></script> <script src="js/UndoManager.js"></script> <script src="js/UndoController.js"></script> <script src="js/ClipboardController.js"></script> <script src="js/ZoomController.js"></script> <script src="js/ShortcutController.js"></script> <script src="js/HelpController.js"></script> <script src="js/FloatPanel.js"></script> <script src="js/Navigator.js"></script> <script src="js/Inspector.js"></script> <script src="js/ToolBar.js"></script> <script src="js/StatusBar.js"></script> <script src="js/CanvasDrawingTools.js"></script> <script src="js/CanvasView.js"></script> <script src="js/CanvasPresenter.js"></script> <script src="js/ApplicationController.js"></script> <script src="js/MindMapModel.js"></script> <script src="js/NewDocument.js"></script> <script src="js/OpenDocument.js"></script> <script src="js/SaveDocument.js"></script> <script src="js/MainViewController.js"></script> <script src="js/Storage.js"></script> <script src="js/Event.js"></script> <script src="js/Notification.js"></script> <script src="js/StaticCanvas.js"></script> <script src="js/PrintController.js"></script> <script src="js/ExportMap.js"></script> <script src="js/AutoSaveController.js"></script> <!-- JS:LIB:END --> </body> </html>
{ "content_hash": "9a49f5ff35a3766b81815143d0aaf504", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 272, "avg_line_length": 36.88715953307393, "alnum_prop": 0.6348101265822785, "repo_name": "framasoft/framindmap", "id": "7f01d150236cc05fa13d8a998eb8b4ecd9c4b290", "size": "9484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webapps/wisemapping/mindmaps/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21678" }, { "name": "HTML", "bytes": "11800" }, { "name": "Java", "bytes": "137966" }, { "name": "JavaScript", "bytes": "250571" }, { "name": "Shell", "bytes": "1524" } ], "symlink_target": "" }
package com.androidapp.richard.startfresh.Fragments; import android.Manifest; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.androidapp.richard.startfresh.AdaptersAndOtherClasses.ToDoItemToday; import com.androidapp.richard.startfresh.AdaptersAndOtherClasses.ToDoItemTodayRVAdapter; import com.androidapp.richard.startfresh.R; import com.google.android.gms.awareness.Awareness; import com.google.android.gms.awareness.snapshot.WeatherResult; import com.google.android.gms.awareness.state.Weather; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import pl.droidsonroids.gif.GifImageView; public class DashboardFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener { public ArrayList listOfItems; private ToDoItemTodayRVAdapter rvAdapter; public GoogleApiClient mGoogleApiClient; public ToDoItemTodayRVAdapter getRvAdapter(){ return this.rvAdapter; } private OnFragmentInteractionListener mListener; public DashboardFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); Calendar calendar = Calendar.getInstance(); Date today = calendar.getTime(); DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); String todayAsString = dateFormat.format(today); listOfItems= new ArrayList<>(); if (sharedPref.getInt(todayAsString, 0) > 0){ for(int i = 0; i < sharedPref.getInt(todayAsString, 0); i ++){ ToDoItemToday task = new ToDoItemToday("task", sharedPref.getString("task" + String.valueOf(i)+"-name", "Task Summary"), sharedPref.getString("task" + String.valueOf(i)+"-time", "Task Time"), sharedPref.getString("task" + String.valueOf(i)+"-details", "Task Details")); listOfItems.add(task); } } mGoogleApiClient = new GoogleApiClient.Builder(getActivity().getApplicationContext()) .enableAutoManage(getActivity(), this) .addApi(Awareness.API).build(); mGoogleApiClient.connect(); } public ArrayList getListOfItems(){ return this.listOfItems; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_dashboard, container, false); LinearLayoutManager llm = new LinearLayoutManager(view.getContext()); llm.setOrientation(LinearLayoutManager.VERTICAL); RecyclerView rView = (RecyclerView) view.findViewById(R.id.recycler_view); final GifImageView gifImageView = (GifImageView) view.findViewById(R.id.weather_gifview); rView.setHasFixedSize(true); rvAdapter = new ToDoItemTodayRVAdapter(listOfItems); rView.setLayoutManager(llm); rView.setAdapter(rvAdapter); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Awareness.SnapshotApi.getWeather(mGoogleApiClient) .setResultCallback(new ResultCallback<WeatherResult>() { @Override public void onResult(@NonNull WeatherResult weatherResult) { if (weatherResult.getStatus().isSuccess()) { Weather weather = weatherResult.getWeather(); TextView weatherTV = (TextView) view.findViewById(R.id.weather_test_textview); weatherTV.setText("Current Temperature: " + Math.round(weather.getTemperature(Weather.CELSIUS)) + " \u00b0C "); switch(weather.getConditions()[0]) { case Weather.CONDITION_CLEAR: gifImageView.setBackgroundResource(R.drawable.weather_sunny); break; case Weather.CONDITION_CLOUDY: gifImageView.setBackgroundResource(R.drawable.weather_cloudy); break; case Weather.CONDITION_SNOWY: gifImageView.setBackgroundResource(R.drawable.weather_snowy); break; case Weather.CONDITION_RAINY: gifImageView.setBackgroundResource(R.drawable.weather_rainy); break; case Weather.CONDITION_STORMY: break; default: gifImageView.setBackgroundResource(R.drawable.weather_sunny); break; }; } else { Log.d("Could not retrieve data", weatherResult.getStatus().toString()); } } }); } return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
{ "content_hash": "fc8c40ab324a583836968e06ce1b6a70", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 285, "avg_line_length": 44.05806451612903, "alnum_prop": 0.6224923121979792, "repo_name": "richardzhanguw/StartFresh", "id": "145772c3b89b1e13ab69f01a828b96e88f4c71bf", "size": "6829", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/androidapp/richard/startfresh/Fragments/DashboardFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "48320" } ], "symlink_target": "" }
package org.ziwenxie.leafer.redis; public interface CacheSupport { /** * 刷新容器中的所有键 * @param cacheName */ void refreshCache(String cacheName); /** * 按照容器以及给定的键刷新 * @param cacheName * @param cacheKey */ void refreshCacheByKey(String cacheName,String cacheKey); }
{ "content_hash": "eed22b3ee6e26f085c442422e09081f1", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 61, "avg_line_length": 17.555555555555557, "alnum_prop": 0.629746835443038, "repo_name": "ziwenxie/leafer", "id": "559ac553f2068dff2786bc3859752c0dda347519", "size": "358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/ziwenxie/leafer/redis/CacheSupport.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20202" }, { "name": "HTML", "bytes": "31072" }, { "name": "Java", "bytes": "68221" }, { "name": "JavaScript", "bytes": "14363" } ], "symlink_target": "" }
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Main" android:fitsSystemWindows="true"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <include layout="@layout/toolbar"/> <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> <android.support.design.widget.NavigationView android:id="@+id/navigation" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="left" android:fitsSystemWindows="true" app:menu="@menu/navigation" app:insetForeground="#4000" app:itemIconTint="@color/navigation_color_set" app:itemTextColor="@color/navigation_color_set" app:headerLayout="@layout/navigation_header"/> </android.support.v4.widget.DrawerLayout>
{ "content_hash": "c1da5f4c49bc8d3a016fb466a7117442", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 62, "avg_line_length": 41.774193548387096, "alnum_prop": 0.6694980694980694, "repo_name": "Garthi/Running-Leaderboard", "id": "70d1341499279024c2f80116fac1cb99cded3c8a", "size": "1295", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/res/layout/main.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "113027" } ], "symlink_target": "" }
import Delegator from 'dom-delegator'; /////////////////////////////////////////////////////////////////////////////// const delegator = new Delegator(); delegator.listenTo('click'); delegator.listenTo('dragenter'); delegator.listenTo('dragleave'); delegator.listenTo('dragover'); delegator.listenTo('drop'); ///////////////////////////////////////////////////////////////////////////////
{ "content_hash": "5960eb2209ac343fcc194d3957a2b3ef", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 79, "avg_line_length": 30.23076923076923, "alnum_prop": 0.45038167938931295, "repo_name": "craigdallimore/hog", "id": "7c1713f3ec3a9a0838b5d9e1ac8d151a4ce78131", "size": "709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/lib/domDelegator.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2122" }, { "name": "JavaScript", "bytes": "49043" } ], "symlink_target": "" }
package com.chrisyazbek.holla; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button contactButton, favButton,mapButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView start = (ImageView) findViewById(R.id.startButtonView); start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, FavActivity.class); startActivity(intent); finish(); } }); } }
{ "content_hash": "be6d1dacc94debdbde0f7e3afdcd7d4b", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 81, "avg_line_length": 27.25, "alnum_prop": 0.6952089704383282, "repo_name": "cyazbek/holla", "id": "2505f5a7fe059256206f36675709877850e9a164", "size": "981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Holla/app/src/main/java/com/chrisyazbek/holla/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "34297" } ], "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_112) on Mon May 01 08:43:54 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.mail (Public javadocs 2017.5.0 API)</title> <meta name="date" content="2017-05-01"> <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="org.wildfly.swarm.mail (Public javadocs 2017.5.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.5.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/logstash/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/wildfly/swarm/mail/detect/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/mail/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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"> <h1 title="Package" class="title">Package&nbsp;org.wildfly.swarm.mail</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation"> <caption><span>Interface Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Interface</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/mail/EnhancedMailSessionConsumer.html" title="interface in org.wildfly.swarm.mail">EnhancedMailSessionConsumer</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/mail/EnhancedSMTPServerConsumer.html" title="interface in org.wildfly.swarm.mail">EnhancedSMTPServerConsumer</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/mail/EnhancedMailSession.html" title="class in org.wildfly.swarm.mail">EnhancedMailSession</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/mail/EnhancedSMTPServer.html" title="class in org.wildfly.swarm.mail">EnhancedSMTPServer</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/mail/MailFraction.html" title="class in org.wildfly.swarm.mail">MailFraction</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </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="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.5.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/logstash/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/wildfly/swarm/mail/detect/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/mail/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "9d4aa963f6befde4f659506ae9a13dd2", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 179, "avg_line_length": 37.907514450867055, "alnum_prop": 0.6413540713632205, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "cf964014ead076e944ecbf37e05f8b70e74fad1a", "size": "6558", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2017.5.0/apidocs/org/wildfly/swarm/mail/package-summary.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#pragma once #define MOONSTONE_NET_PROTOCOL_VERSION 106 /** * Define this to enable debugging code in the p2p network interface. * This is code that would never be executed in normal operation, but is * used for automated testing (creating artificial net splits, * tracking where messages came from and when) */ #define ENABLE_P2P_DEBUGGING_API 1 /** * 2MiB */ #define MAX_MESSAGE_SIZE 1024*1024*2 #define MOONSTONE_NET_DEFAULT_PEER_CONNECTION_RETRY_TIME 30 // seconds /** * AFter trying all peers, how long to wait before we check to * see if there are peers we can try again. */ #define MOONSTONE_PEER_DATABASE_RETRY_DELAY 15 // seconds #define MOONSTONE_NET_PEER_HANDSHAKE_INACTIVITY_TIMEOUT 5 #define MOONSTONE_NET_PEER_DISCONNECT_TIMEOUT 20 #define MOONSTONE_NET_TEST_SEED_IP "104.236.44.210" // autogenerated #define MOONSTONE_NET_TEST_P2P_PORT 1700 #define MOONSTONE_NET_DEFAULT_P2P_PORT 1776 #define MOONSTONE_NET_DEFAULT_DESIRED_CONNECTIONS 20 #define MOONSTONE_NET_DEFAULT_MAX_CONNECTIONS 200 #define MOONSTONE_NET_MAXIMUM_QUEUED_MESSAGES_IN_BYTES (1024 * 1024) /** * When we receive a message from the network, we advertise it to * our peers and save a copy in a cache were we will find it if * a peer requests it. We expire out old items out of the cache * after this number of blocks go by. * * Recently lowered from 30 to match the default expiration time * the web wallet imposes on transactions. */ #define MOONSTONE_NET_MESSAGE_CACHE_DURATION_IN_BLOCKS 5 /** * We prevent a peer from offering us a list of blocks which, if we fetched them * all, would result in a blockchain that extended into the future. * This parameter gives us some wiggle room, allowing a peer to give us blocks * that would put our blockchain up to an hour in the future, just in case * our clock is a bit off. */ #define MOONSTONE_NET_FUTURE_SYNC_BLOCKS_GRACE_PERIOD_SEC (60 * 60) #define MOONSTONE_NET_MAX_INVENTORY_SIZE_IN_MINUTES 2 #define MOONSTONE_NET_MAX_BLOCKS_PER_PEER_DURING_SYNCING 200 /** * During normal operation, how many items will be fetched from each * peer at a time. This will only come into play when the network * is being flooded -- typically transactions will be fetched as soon * as we find out about them, so only one item will be requested * at a time. * * No tests have been done to find the optimal value for this * parameter, so consider increasing or decreasing it if performance * during flooding is lacking. */ #define MOONSTONE_NET_MAX_ITEMS_PER_PEER_DURING_NORMAL_OPERATION 1 /** * Instead of fetching all item IDs from a peer, then fetching all blocks * from a peer, we will interleave them. Fetch at least this many block IDs, * then switch into block-fetching mode until the number of blocks we know about * but haven't yet fetched drops below this */ #define MOONSTONE_NET_MIN_BLOCK_IDS_TO_PREFETCH 10000 #define MOONSTONE_NET_MAX_TRX_PER_SECOND 1000
{ "content_hash": "8a381f597edf5202d89276035ad600af", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 95, "avg_line_length": 39.10843373493976, "alnum_prop": 0.6829944547134935, "repo_name": "moonstonedac/moonstone", "id": "e9bb7f1592d83a8f44c6cdd2db12ef03a43862f2", "size": "4408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/net/include/moonstone/net/config.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "236547" }, { "name": "C++", "bytes": "3651457" }, { "name": "CMake", "bytes": "290565" }, { "name": "HTML", "bytes": "72284" }, { "name": "Python", "bytes": "4351" } ], "symlink_target": "" }
#include "config.h" #include "core/dom/NodeTraversal.h" #include "platform/testing/URLTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebPrerender.h" #include "public/platform/WebPrerenderingSupport.h" #include "public/platform/WebString.h" #include "public/platform/WebUnitTestSupport.h" #include "public/web/WebCache.h" #include "public/web/WebFrame.h" #include "public/web/WebPrerendererClient.h" #include "public/web/WebScriptSource.h" #include "public/web/WebView.h" #include "public/web/WebViewClient.h" #include "web/WebLocalFrameImpl.h" #include "web/tests/FrameTestHelpers.h" #include "wtf/OwnPtr.h" #include <functional> #include <gtest/gtest.h> #include <list> using namespace blink; using blink::URLTestHelpers::toKURL; namespace { WebURL toWebURL(const char* url) { return WebURL(toKURL(url)); } class TestPrerendererClient : public WebPrerendererClient { public: TestPrerendererClient() { } virtual ~TestPrerendererClient() { } void setExtraDataForNextPrerender(WebPrerender::ExtraData* extraData) { ASSERT(!m_extraData); m_extraData = adoptPtr(extraData); } WebPrerender releaseWebPrerender() { ASSERT(!m_webPrerenders.empty()); WebPrerender retval(m_webPrerenders.front()); m_webPrerenders.pop_front(); return retval; } bool empty() const { return m_webPrerenders.empty(); } void clear() { m_webPrerenders.clear(); } private: // From WebPrerendererClient: void willAddPrerender(WebPrerender* prerender) override { prerender->setExtraData(m_extraData.leakPtr()); ASSERT(!prerender->isNull()); m_webPrerenders.push_back(*prerender); } OwnPtr<WebPrerender::ExtraData> m_extraData; std::list<WebPrerender> m_webPrerenders; }; class TestPrerenderingSupport : public WebPrerenderingSupport { public: TestPrerenderingSupport() { initialize(this); } ~TestPrerenderingSupport() override { shutdown(); } void clear() { m_addedPrerenders.clear(); m_canceledPrerenders.clear(); m_abandonedPrerenders.clear(); } size_t totalCount() const { return m_addedPrerenders.size() + m_canceledPrerenders.size() + m_abandonedPrerenders.size(); } size_t addCount(const WebPrerender& prerender) const { return std::count_if(m_addedPrerenders.begin(), m_addedPrerenders.end(), [&prerender](const WebPrerender& other) { return other.toPrerender() == prerender.toPrerender(); }); } size_t cancelCount(const WebPrerender& prerender) const { return std::count_if(m_canceledPrerenders.begin(), m_canceledPrerenders.end(), [&prerender](const WebPrerender& other) { return other.toPrerender() == prerender.toPrerender(); }); } size_t abandonCount(const WebPrerender& prerender) const { return std::count_if(m_abandonedPrerenders.begin(), m_abandonedPrerenders.end(), [&prerender](const WebPrerender& other) { return other.toPrerender() == prerender.toPrerender(); }); } private: // From WebPrerenderingSupport: void add(const WebPrerender& prerender) override { m_addedPrerenders.append(prerender); } void cancel(const WebPrerender& prerender) override { m_canceledPrerenders.append(prerender); } void abandon(const WebPrerender& prerender) override { m_abandonedPrerenders.append(prerender); } Vector<WebPrerender> m_addedPrerenders; Vector<WebPrerender> m_canceledPrerenders; Vector<WebPrerender> m_abandonedPrerenders; }; class PrerenderingTest : public testing::Test { public: ~PrerenderingTest() override { Platform::current()->unitTestSupport()->unregisterAllMockedURLs(); } void initialize(const char* baseURL, const char* fileName) { URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(baseURL), WebString::fromUTF8(fileName)); const bool RunJavascript = true; m_webViewHelper.initialize(RunJavascript); m_webViewHelper.webView()->setPrerendererClient(&m_prerendererClient); FrameTestHelpers::loadFrame(m_webViewHelper.webView()->mainFrame(), std::string(baseURL) + fileName); } void navigateAway() { FrameTestHelpers::loadFrame(m_webViewHelper.webView()->mainFrame(), "about:blank"); } void close() { m_webViewHelper.webView()->mainFrame()->collectGarbage(); m_webViewHelper.reset(); WebCache::clear(); } Element& console() { Document* document = m_webViewHelper.webViewImpl()->mainFrameImpl()->frame()->document(); Element* console = document->getElementById("console"); ASSERT(isHTMLUListElement(console)); return *console; } unsigned consoleLength() { return console().countChildren() - 1; } WebString consoleAt(unsigned i) { ASSERT(consoleLength() > i); Node* item = NodeTraversal::childAt(console(), 1 + i); ASSERT(item); ASSERT(isHTMLLIElement(item)); ASSERT(item->hasChildren()); return item->textContent(); } void executeScript(const char* code) { m_webViewHelper.webView()->mainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(code))); } TestPrerenderingSupport* prerenderingSupport() { return &m_prerenderingSupport; } TestPrerendererClient* prerendererClient() { return &m_prerendererClient; } private: TestPrerenderingSupport m_prerenderingSupport; TestPrerendererClient m_prerendererClient; FrameTestHelpers::WebViewHelper m_webViewHelper; }; TEST_F(PrerenderingTest, SinglePrerender) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(toWebURL("http://prerender.com/"), webPrerender.url()); EXPECT_EQ(PrerenderRelTypePrerender, webPrerender.relTypes()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); webPrerender.didStartPrerender(); EXPECT_EQ(1u, consoleLength()); EXPECT_EQ("webkitprerenderstart", consoleAt(0)); webPrerender.didSendDOMContentLoadedForPrerender(); EXPECT_EQ(2u, consoleLength()); EXPECT_EQ("webkitprerenderdomcontentloaded", consoleAt(1)); webPrerender.didSendLoadForPrerender(); EXPECT_EQ(3u, consoleLength()); EXPECT_EQ("webkitprerenderload", consoleAt(2)); webPrerender.didStopPrerender(); EXPECT_EQ(4u, consoleLength()); EXPECT_EQ("webkitprerenderstop", consoleAt(3)); } TEST_F(PrerenderingTest, CancelPrerender) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); executeScript("removePrerender()"); EXPECT_EQ(1u, prerenderingSupport()->cancelCount(webPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, AbandonPrerender) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); navigateAway(); EXPECT_EQ(1u, prerenderingSupport()->abandonCount(webPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); // Check that the prerender does not emit an extra cancel when garbage-collecting everything. close(); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, ExtraData) { class TestExtraData : public WebPrerender::ExtraData { public: explicit TestExtraData(bool* alive) : m_alive(alive) { *alive = true; } ~TestExtraData() override { *m_alive = false; } private: bool* m_alive; }; bool alive = false; { prerendererClient()->setExtraDataForNextPrerender(new TestExtraData(&alive)); initialize("http://www.foo.com/", "prerender/single_prerender.html"); EXPECT_TRUE(alive); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); executeScript("removePrerender()"); close(); prerenderingSupport()->clear(); } EXPECT_FALSE(alive); } TEST_F(PrerenderingTest, TwoPrerenders) { initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); WebPrerender firstPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(firstPrerender.isNull()); EXPECT_EQ(toWebURL("http://first-prerender.com/"), firstPrerender.url()); WebPrerender secondPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(firstPrerender.isNull()); EXPECT_EQ(toWebURL("http://second-prerender.com/"), secondPrerender.url()); EXPECT_EQ(1u, prerenderingSupport()->addCount(firstPrerender)); EXPECT_EQ(1u, prerenderingSupport()->addCount(secondPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); firstPrerender.didStartPrerender(); EXPECT_EQ(1u, consoleLength()); EXPECT_EQ("first_webkitprerenderstart", consoleAt(0)); secondPrerender.didStartPrerender(); EXPECT_EQ(2u, consoleLength()); EXPECT_EQ("second_webkitprerenderstart", consoleAt(1)); } TEST_F(PrerenderingTest, TwoPrerendersRemovingFirstThenNavigating) { initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); WebPrerender firstPrerender = prerendererClient()->releaseWebPrerender(); WebPrerender secondPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(1u, prerenderingSupport()->addCount(firstPrerender)); EXPECT_EQ(1u, prerenderingSupport()->addCount(secondPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); executeScript("removeFirstPrerender()"); EXPECT_EQ(1u, prerenderingSupport()->cancelCount(firstPrerender)); EXPECT_EQ(3u, prerenderingSupport()->totalCount()); navigateAway(); EXPECT_EQ(1u, prerenderingSupport()->abandonCount(secondPrerender)); EXPECT_EQ(4u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, TwoPrerendersAddingThird) { initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); WebPrerender firstPrerender = prerendererClient()->releaseWebPrerender(); WebPrerender secondPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(1u, prerenderingSupport()->addCount(firstPrerender)); EXPECT_EQ(1u, prerenderingSupport()->addCount(secondPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); executeScript("addThirdPrerender()"); WebPrerender thirdPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(1u, prerenderingSupport()->addCount(thirdPrerender)); EXPECT_EQ(3u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, ShortLivedClient) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); navigateAway(); close(); // This test passes if this next line doesn't crash. webPrerender.didStartPrerender(); } TEST_F(PrerenderingTest, FastRemoveElement) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); // Race removing & starting the prerender against each other, as if the element was removed very quickly. executeScript("removePrerender()"); EXPECT_FALSE(webPrerender.isNull()); webPrerender.didStartPrerender(); // The page should be totally disconnected from the Prerender at this point, so the console should not have updated. EXPECT_EQ(0u, consoleLength()); } TEST_F(PrerenderingTest, MutateTarget) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(toWebURL("http://prerender.com/"), webPrerender.url()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(0u, prerenderingSupport()->cancelCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); // Change the href of this prerender, make sure this is treated as a remove and add. executeScript("mutateTarget()"); EXPECT_EQ(1u, prerenderingSupport()->cancelCount(webPrerender)); WebPrerender mutatedPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(toWebURL("http://mutated.com/"), mutatedPrerender.url()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->addCount(mutatedPrerender)); EXPECT_EQ(3u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, MutateRel) { initialize("http://www.foo.com/", "prerender/single_prerender.html"); WebPrerender webPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_FALSE(webPrerender.isNull()); EXPECT_EQ(toWebURL("http://prerender.com/"), webPrerender.url()); EXPECT_EQ(1u, prerenderingSupport()->addCount(webPrerender)); EXPECT_EQ(0u, prerenderingSupport()->cancelCount(webPrerender)); EXPECT_EQ(1u, prerenderingSupport()->totalCount()); // Change the rel of this prerender, make sure this is treated as a remove. executeScript("mutateRel()"); EXPECT_EQ(1u, prerenderingSupport()->cancelCount(webPrerender)); EXPECT_EQ(2u, prerenderingSupport()->totalCount()); } TEST_F(PrerenderingTest, RelNext) { initialize("http://www.foo.com/", "prerender/rel_next_prerender.html"); WebPrerender relNextOnly = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(toWebURL("http://rel-next-only.com/"), relNextOnly.url()); EXPECT_EQ(PrerenderRelTypeNext, relNextOnly.relTypes()); WebPrerender relNextAndPrerender = prerendererClient()->releaseWebPrerender(); EXPECT_EQ(toWebURL("http://rel-next-and-prerender.com/"), relNextAndPrerender.url()); EXPECT_EQ(static_cast<unsigned>(PrerenderRelTypeNext | PrerenderRelTypePrerender), relNextAndPrerender.relTypes()); } } // namespace
{ "content_hash": "248b92bf86d5cde0586d8bb456e8b98e", "timestamp": "", "source": "github", "line_count": 471, "max_line_length": 129, "avg_line_length": 32.00212314225053, "alnum_prop": 0.6985338021628077, "repo_name": "Bysmyyr/chromium-crosswalk", "id": "8458c4cd8a66d383705ac09302798410d94c3a03", "size": "16635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/web/tests/PrerenderingTest.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.kie.workbench.common.screens.projectimportsscreen.client.forms; import javax.inject.Inject; import com.google.gwt.user.client.ui.IsWidget; import org.guvnor.common.services.project.model.ProjectImports; import org.jboss.errai.common.client.api.Caller; import org.jboss.errai.common.client.api.RemoteCallback; import org.kie.workbench.common.screens.projectimportsscreen.client.resources.i18n.ProjectConfigScreenConstants; import org.kie.workbench.common.screens.projectimportsscreen.client.type.ProjectImportsResourceType; import org.kie.workbench.common.services.shared.project.ProjectImportsContent; import org.kie.workbench.common.services.shared.project.ProjectImportsService; import org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants; import org.kie.workbench.common.widgets.metadata.client.KieEditor; import org.uberfire.backend.vfs.ObservablePath; import org.uberfire.backend.vfs.Path; import org.uberfire.client.annotations.WorkbenchEditor; import org.uberfire.client.annotations.WorkbenchMenu; import org.uberfire.client.annotations.WorkbenchPartTitle; import org.uberfire.client.annotations.WorkbenchPartView; import org.uberfire.ext.widgets.common.client.callbacks.HasBusyIndicatorDefaultErrorCallback; import org.uberfire.lifecycle.OnClose; import org.uberfire.lifecycle.OnMayClose; import org.uberfire.lifecycle.OnStartup; import org.uberfire.mvp.Command; import org.uberfire.mvp.ParameterizedCommand; import org.uberfire.mvp.PlaceRequest; import org.uberfire.workbench.events.NotificationEvent; import org.uberfire.workbench.model.menu.Menus; @WorkbenchEditor(identifier = "projectConfigScreen", supportedTypes = { ProjectImportsResourceType.class }) public class ProjectImportsScreenPresenter extends KieEditor { private ProjectImportsScreenView view; private Caller<ProjectImportsService> importsService; private ProjectImports model; public ProjectImportsScreenPresenter() { } @Inject public ProjectImportsScreenPresenter( final ProjectImportsScreenView view, final Caller<ProjectImportsService> importsService ) { super( view ); this.view = view; this.importsService = importsService; } @OnStartup public void init( final ObservablePath path, final PlaceRequest place ) { super.init( path, place, new ProjectImportsResourceType() ); } private RemoteCallback<ProjectImportsContent> getModelSuccessCallback() { return new RemoteCallback<ProjectImportsContent>() { @Override public void callback( final ProjectImportsContent content ) { //Path is set to null when the Editor is closed (which can happen before async calls complete). if ( versionRecordManager.getCurrentPath() == null ) { return; } model = content.getModel(); resetEditorPages( content.getOverview() ); view.setContent( model, isReadOnly ); view.hideBusyIndicator(); createOriginalHash( content.getModel() ); } }; } protected void makeMenuBar() { menus = menuBuilder .addSave( versionRecordManager.newSaveMenuItem( new Command() { @Override public void execute() { onSave(); } } ) ) .addCopy( versionRecordManager.getCurrentPath(), fileNameValidator ) .addRename( versionRecordManager.getPathToLatest(), fileNameValidator ) .addDelete( versionRecordManager.getPathToLatest() ) .addNewTopLevelMenu( versionRecordManager.buildMenu() ) .build(); } @Override protected void loadContent() { importsService.call( getModelSuccessCallback(), new HasBusyIndicatorDefaultErrorCallback( view ) ).loadContent( versionRecordManager.getCurrentPath() ); } protected void save() { saveOperationService.save( versionRecordManager.getCurrentPath(), new ParameterizedCommand<String>() { @Override public void execute( final String commitMessage ) { view.showSaving(); importsService.call( getSaveSuccessCallback(), new HasBusyIndicatorDefaultErrorCallback( view ) ).save( versionRecordManager.getCurrentPath(), model, metadata, commitMessage ); } } ); } private RemoteCallback<Path> getSaveSuccessCallback() { return new RemoteCallback<Path>() { @Override public void callback( final Path path ) { view.hideBusyIndicator(); notification.fire( new NotificationEvent( CommonConstants.INSTANCE.ItemSavedSuccessfully() ) ); createOriginalHash( model ); } }; } @WorkbenchPartTitle public String getTitleText() { return ProjectConfigScreenConstants.INSTANCE.ExternalImports(); } @WorkbenchPartView public IsWidget asWidget() { return super.getWidget(); } @OnClose public void onClose() { versionRecordManager.clear(); } @WorkbenchMenu public Menus getMenus() { return menus; } @OnMayClose public boolean mayClose() { return super.mayClose( model ); } }
{ "content_hash": "aeb6ccb02f69f4e055d33c0301f34a36", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 159, "avg_line_length": 38.25, "alnum_prop": 0.5942930017535469, "repo_name": "scandihealth/kie-wb-common", "id": "0f1e298701ece662bfa93cb6eac79742ff902364", "size": "6894", "binary": false, "copies": "2", "ref": "refs/heads/6.5.0.csc", "path": "kie-wb-common-screens/kie-wb-common-project-imports-editor/kie-wb-common-project-imports-editor-client/src/main/java/org/kie/workbench/common/screens/projectimportsscreen/client/forms/ProjectImportsScreenPresenter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18581" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "31605" }, { "name": "Java", "bytes": "8589867" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> @include('partials/head') <body> @include('partials/navbar') <div class="container theme-showcase"> <div class="page-header"> <h1>{{{ $title }}}</h1> </div> @include('partials/flashmsgs') <!-- Start of content --> @yield('content') <!-- End content --> <p>&nbsp;</p> @include('partials/copyright') </div> @include('partials/footer') </body> </html>
{ "content_hash": "d5f553c372b87fd9f57e3cffc4344eb1", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 46, "avg_line_length": 22.583333333333332, "alnum_prop": 0.45571955719557194, "repo_name": "bobsta63/turbine", "id": "6f14b4b859f57b84788b495153da59993acf77c8", "size": "542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/layout.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "199" }, { "name": "JavaScript", "bytes": "267" }, { "name": "PHP", "bytes": "135761" }, { "name": "Shell", "bytes": "7447" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('article', '0005_auto_20170124_1531'), ] operations = [ migrations.AddField( model_name='article', name='show_featured_image', field=models.BooleanField(default=True), ), ]
{ "content_hash": "37503ad63bcd3a2d4645706ed1206952", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 52, "avg_line_length": 21.77777777777778, "alnum_prop": 0.6020408163265306, "repo_name": "PARINetwork/pari", "id": "5657bbc08c97718b2b9721969bfce86a1a5dd28b", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "article/migrations/0006_article_show_featured_image.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "94103" }, { "name": "HTML", "bytes": "452629" }, { "name": "JavaScript", "bytes": "124537" }, { "name": "Less", "bytes": "229040" }, { "name": "Python", "bytes": "479247" }, { "name": "Shell", "bytes": "3919" } ], "symlink_target": "" }
console.log("Application started."); var Core = require('./NodeJS/core');
{ "content_hash": "d25a7d1d828f99a7bf1eb36c26d7b19a", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 36, "avg_line_length": 37, "alnum_prop": 0.7027027027027027, "repo_name": "chriswoodle/Name-Tag-Printer", "id": "d120b37236ec0bd8e5aab5a727894e8d6b712706", "size": "74", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6499" }, { "name": "Python", "bytes": "1421" }, { "name": "Shell", "bytes": "50" } ], "symlink_target": "" }
<?php namespace Thessia\Tasks\CLI; use JBZoo\PimpleDumper\PimpleDumper; use Jenssegers\Lean\SlimServiceProvider; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Thessia\Service\SystemServiceProvider; class UpdateThessia extends Command { protected function configure() { $this ->setName("update") ->setDescription("Updates composer, phpstormmeta, phpdocs and other stuff"); } protected function execute(InputInterface $input, OutputInterface $output) { // Update the api docs $this->generateApiDoc(); // Generate the .phpstorm.meta.php file //$this->phpStormMeta(); // Update composer $this->updateComposer(); // @todo Update phpdoc } private function generateApiDoc() { // If the file doesn't exist there, just return.. if(!file_exists("/usr/local/bin/apidoc")) return; $docsPath = __DIR__ . "/../../docs"; $outputDir = __DIR__ . "/../../public/apidoc/"; $filter = ".*\\.apidoc$"; exec("/usr/local/bin/apidoc -i {$docsPath} -f {$filter} -o {$outputDir}"); } private function updateComposer() { if(!file_exists(__DIR__ . "/../../composer.phar")) file_put_contents(__DIR__ . "/../../composer.phar", file_get_contents("https://getcomposer.org/composer.phar")); if(!file_exists(__DIR__ . "/../../vendor")) exec("/usr/bin/php7.0 " . __DIR__ . "/../../composer.phar install -o"); else exec("/usr/bin/php7.0 " . __DIR__ . "/../../composer.phar update -o"); } private function phpStormMeta() { $container = getContainer(); $container->addServiceProvider(new SlimServiceProvider()); $systemProvider = new SystemServiceProvider(); $slimProvider = new SlimServiceProvider(); $systemProvides = $systemProvider->provides(); $slimProvides = $slimProvider->provides(); $provides = array_merge($systemProvides, $slimProvides); // Generate the instance array $instanceArray = array(); foreach($provides as $service) { if(is_object($container->get($service))) { $instance = get_class($container->get($service)); $instanceArray[$service] = $instance; } } // Manually added parts $instanceArray["render"] = '\Thessia\Lib\Render'; // Generate the phpstorm meta file and output it to the root of the directory. $location = __DIR__ . "/../../.phpstorm.meta.php"; $data = "<?php namespace PHPSTORM_META { \$STATIC_METHOD_TYPES = [ \\Interop\\Container\\ContainerInterface::get('') => [\n"; //"mongo" instanceof Client, foreach($instanceArray as $key => $inst) $data .= " '{$key}' instanceof {$inst},\n"; // "" == "@", $data .= " ] ]; }"; file_put_contents($location, $data); } }
{ "content_hash": "d9d432f8cbf9c6c30582bd239945e520", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 124, "avg_line_length": 32.4040404040404, "alnum_prop": 0.5570448877805486, "repo_name": "new-eden/Thessia", "id": "04250c805e750173904d18e6efe7c00f06731f83", "size": "4381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tasks/CLI/UpdateThessia.php", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "1202" }, { "name": "PHP", "bytes": "141653" } ], "symlink_target": "" }
<!DOCTYPE html> <HTML><head><TITLE>Manpage of consoletype_selinux</TITLE> <meta charset="utf-8"> <link rel="stylesheet" href="/css/main.css" type="text/css"> </head> <body> <header class="site-header"> <div class="wrap"> <div class="site-title"><a href="/manpages/index.html">linux manpages</a></div> <div class="site-description">{"type":"documentation"}</div> </div> </header> <div class="page-content"><div class="wrap"> <H1>consoletype_selinux</H1> Section: consoletype SELinux Policy documentation (8)<BR>Updated: consoletype<BR><A HREF="#index">Index</A> <A HREF="/manpages/index.html">Return to Main Contents</A><HR> <A NAME="lbAB">&nbsp;</A> <H2>NAME</H2> consoletype_selinux - Security Enhanced Linux Policy for the consoletype processes <A NAME="lbAC">&nbsp;</A> <H2>DESCRIPTION</H2> <P> <P> SELinux Linux secures <B>consoletype</B> ( Determine of the console connected to the controlling terminal. ) processes via flexible mandatory access control. <P> <P> <P> <A NAME="lbAD">&nbsp;</A> <H2>FILE CONTEXTS</H2> SELinux requires files to have an extended attribute to define the file type. <P> You can see the context of a file using the <B>-Z</B> option to <B>lsP Policy governs the access confined processes have to these files. SELinux consoletype policy is very flexible allowing users to setup their consoletype processes in as secure a method as possible. <P> The following file types are defined for consoletype: <P> <P> <P> consoletype_exec_t </B> <P> - Set files with the consoletype_exec_t type, if you want to transition an executable to the consoletype_t domain. <P> <P> <P> Note: File context can be temporarily modified with the chcon command. If you want to permanently change the file context you need to use the <B>semanage fcontext </B> command. This will modify the SELinux labeling database. You will need to use <B>restorecon</B> to apply the labels. <P> <A NAME="lbAE">&nbsp;</A> <H2>PROCESS TYPES</H2> SELinux defines process types (domains) for each process running on the system <P> You can see the context of a process using the <B>-Z</B> option to <B>psP Policy governs the access confined processes have to files. SELinux consoletype policy is very flexible allowing users to setup their consoletype processes in as secure a method as possible. <P> The following process types are defined for consoletype: <P> consoletype_t </B> <P> Note: <B>semanage permissive -a PROCESS_TYPE </B> can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated. <P> <A NAME="lbAF">&nbsp;</A> <H2>COMMANDS</H2> <B>semanage fcontext</B> can also be used to manipulate default file context mappings. <P> <B>semanage permissive</B> can also be used to manipulate whether or not a process type is permissive. <P> <B>semanage module</B> can also be used to enable/disable/install/remove policy modules. <P> <P> <B>system-config-selinux </B> is a GUI tool available to customize SELinux policy settings. <P> <A NAME="lbAG">&nbsp;</A> <H2>AUTHOR<TT>&nbsp;&nbsp;</TT></H2> This manual page was autogenerated by genman.py.<BR> <P> <A NAME="lbAH">&nbsp;</A> <H2>SEE ALSO</H2> <A HREF="/manpages/index.html?8+selinux">selinux</A>(8), <A HREF="http://localhost/cgi-bin/man/man2html?8+consoletype">consoletype</A>(8), <A HREF="http://localhost/cgi-bin/man/man2html?8+semanage">semanage</A>(8), <A HREF="http://localhost/cgi-bin/man/man2html?8+restorecon">restorecon</A>(8), <A HREF="http://localhost/cgi-bin/man/man2html?1+chcon">chcon</A>(1) <P> <HR> <A NAME="index">&nbsp;</A><H2>Index</H2> <DL> <DT><A HREF="#lbAB">NAME</A><DD> <DT><A HREF="#lbAC">DESCRIPTION</A><DD> <DT><A HREF="#lbAD">FILE CONTEXTS</A><DD> <DT><A HREF="#lbAE">PROCESS TYPES</A><DD> <DT><A HREF="#lbAF">COMMANDS</A><DD> <DT><A HREF="#lbAG">AUTHOR<TT>&nbsp;&nbsp;</TT></A><DD> <DT><A HREF="#lbAH">SEE ALSO</A><DD> </DL> <HR> This document was created by <A HREF="/manpages/index.html">man2html</A>, using the manual pages.<BR> Time: 05:34:25 GMT, December 24, 2015 </div></div> </body> </HTML>
{ "content_hash": "1b9182c71c07d89f6b1c30f0aa687b63", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 363, "avg_line_length": 27.716216216216218, "alnum_prop": 0.7130667966845441, "repo_name": "yuweijun/yuweijun.github.io", "id": "13dd53c9b62ddc6706e4d6268845336bafed5941", "size": "4102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manpages/man8/consoletype_selinux.8.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "589062" }, { "name": "CSS", "bytes": "86538" }, { "name": "Go", "bytes": "2652" }, { "name": "HTML", "bytes": "126806134" }, { "name": "JavaScript", "bytes": "12389716" }, { "name": "Perl", "bytes": "7390" }, { "name": "PostScript", "bytes": "32036" }, { "name": "Ruby", "bytes": "8626" }, { "name": "Shell", "bytes": "193" }, { "name": "Vim Script", "bytes": "209" }, { "name": "XSLT", "bytes": "7176" } ], "symlink_target": "" }
class LogBreak < ApplicationRecord belongs_to :rule belongs_to :student end
{ "content_hash": "ddedb88c367dfcd959a1f6d43e52380d", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 34, "avg_line_length": 20, "alnum_prop": 0.775, "repo_name": "BOJOP/organize_cu", "id": "49f04bc7b82ab6aa650e7f82ffe5b3bece68a7e7", "size": "80", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/log_break.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "374343" }, { "name": "HTML", "bytes": "146355" }, { "name": "JavaScript", "bytes": "50396" }, { "name": "Ruby", "bytes": "212087" } ], "symlink_target": "" }
#!/usr/bin/env node import '../server/env'; /* * This script runs breaks out how many new and old backers are added per active month per collective */ console.log('This script is being deprecated.'); console.log('To re-enable it, remove this message with a Pull Request explaining the use case.'); process.exit(); /* import fs from 'fs'; import moment from 'moment'; import { parse as json2csv } from 'json2csv'; import models, { Op } from '../server/models'; const done = err => { if (err) console.log(err); console.log('\ndone!\n'); ``; process.exit(); }; const results = {}; const arrayLength = 30; const outputFilename = 'backer_count_output.csv'; const initiateNewCollectiveStats = (firstOrder, isNewBacker) => { const generateMonths = collectiveStats => { const numArray = Array.apply(null, { length: arrayLength }) .map(Number.call, Number) .slice(2, arrayLength); numArray.map(i => { collectiveStats.months[i] = { newBackerCount: 0, oldBackerCount: 0, }; }); return collectiveStats; }; const collectiveStats = { id: firstOrder.CollectiveId, slug: firstOrder.collective.slug, months: { 1: { date: firstOrder.createdAt, newBackerCount: isNewBacker ? 1 : 0, oldBackerCount: isNewBacker ? 0 : 1, }, }, }; const newCollectiveStats = generateMonths(collectiveStats); console.log('newCollectiveStats', newCollectiveStats); return newCollectiveStats; }; const countOrderInStats = (order, isNewBacker) => { // calculate which month slot it should go in const orderStats = results[order.CollectiveId]; const newOrderDate = moment(order.createdAt); let diff = newOrderDate.diff(moment(orderStats.months['1'].date)); console.log(orderStats); console.log(order.createdAt, orderStats.months['1'].date, diff); if (diff < 0) diff = 0; const month = (Math.floor(diff / 1000 / 3600 / 24 / 30) % 30) + 1; console.log('month', month); if (isNewBacker) { orderStats.months[`${month}`].newBackerCount += 1; } else { orderStats.months[`${month}`].oldBackerCount += 1; } }; const calculateBackersPerCollective = () => { const seenFromCollectiveIdList = {}; return models.Order.findAll({ where: { CollectiveId: { [Op.notIn]: [1], }, }, include: [ { model: models.Collective, as: 'fromCollective', paranoid: false }, { model: models.Collective, as: 'collective', paranoid: false }, ], order: ['id'], }) .tap(orders => console.log('Orders found: ', orders.length)) .each(order => { if (order.FromCollectiveId in seenFromCollectiveIdList) { // means this is now an old backer if (order.CollectiveId in results) { // results[order.CollectiveId]['oldBackerCount'] += 1; countOrderInStats(order, false); } else { // results[order.CollectiveId] = { id: order.CollectiveId, slug: order.collective.slug, newBackerCount: 0, oldBackerCount: 1}; results[order.CollectiveId] = initiateNewCollectiveStats(order, false); } } else { // means this is a new backer seenFromCollectiveIdList[order.FromCollectiveId] = true; if (order.CollectiveId in results) { // results[order.CollectiveId]['newBackerCount'] += 1; countOrderInStats(order, true); } else { // results[order.CollectiveId] = { id: order.CollectiveId, slug: order.collective.slug, newBackerCount: 1, oldBackerCount: 0}; results[order.CollectiveId] = initiateNewCollectiveStats(order, true); } } }) .then(() => { let csvFields = ['id', 'slug']; const array = Array.apply(null, { length: arrayLength }) .map(Number.call, Number) .slice(0, -1); array.map(n => (csvFields = csvFields.concat([`month${n + 1}NewBackerCount`, `month${n + 1}OldBackerCount`]))); console.log(csvFields); // console.log(results); console.log(array); const data = Object.keys(results).map(key => { const obj = { id: results[key].id, slug: results[key].slug }; array.map(n => { console.log(`${n + 1}`, results[key].months[`${n + 1}`]); obj[`month${n + 1}NewBackerCount`] = results[key].months[`${n + 1}`].newBackerCount; obj[`month${n + 1}OldBackerCount`] = results[key].months[`${n + 1}`].oldBackerCount; }); return obj; }); console.log('data', data); console.log('Writing the output to', outputFilename); try { const csv = json2csv(data, { fields: csvFields }); fs.writeFileSync(outputFilename, csv); } catch (err) { console.log(err); } }); }; const run = () => { console.log('\nStarting calc_new_backers_per_collective...'); return calculateBackersPerCollective() .then(() => done()) .catch(done); }; run(); */
{ "content_hash": "1430a37ff7024f88a746191d86055071", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 136, "avg_line_length": 29.1, "alnum_prop": 0.6159288457651102, "repo_name": "OpenCollective/opencollective-api", "id": "4005cbeaef992f4216a3fcf76a7785661bf768c7", "size": "4947", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "scripts/calc_new_backers_per_collective.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "67984" }, { "name": "JavaScript", "bytes": "897429" }, { "name": "Makefile", "bytes": "325" }, { "name": "Shell", "bytes": "13123" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using UiAuthorisation.Models; namespace UiAuthorisation.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } } }
{ "content_hash": "4ae1e215519347affb9b0bdc3fccfe8c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 88, "avg_line_length": 33.46153846153846, "alnum_prop": 0.7103448275862069, "repo_name": "andrewlock/blog-examples", "id": "54a5b1c26e12743923b532516312e2285c699dcb", "size": "872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modifying-the-ui-based-on-user-authorisation/UiAuthorisation/src/UiAuthorisation/Data/ApplicationDbContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "110" }, { "name": "C#", "bytes": "1423366" }, { "name": "CSS", "bytes": "50971" }, { "name": "Dockerfile", "bytes": "6057" }, { "name": "HTML", "bytes": "1558331" }, { "name": "JavaScript", "bytes": "306348" }, { "name": "Less", "bytes": "608619" }, { "name": "PowerShell", "bytes": "13240" }, { "name": "SCSS", "bytes": "212845" }, { "name": "Shell", "bytes": "4423" }, { "name": "Smarty", "bytes": "7468" } ], "symlink_target": "" }
const forEach = require('lodash/forEach'); module.exports = { check: (batch, maxCount) => { let result = true; let maxValue = 0; forEach(batch, (value) => { let count = 0; forEach(batch, (inner) => { count += (inner === value); }); result &= (count <= maxCount); maxValue = (count >= maxValue) ? count : maxValue; }); // console.log('maxValue', maxValue, result); return result; } };
{ "content_hash": "ae56f3d66f305a4b79aba8afd8a81805", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 56, "avg_line_length": 23.789473684210527, "alnum_prop": 0.5376106194690266, "repo_name": "prasanna1211/ranker-backend", "id": "a5ef65e01c0141b649383656ae63ecaa67eae73a", "size": "452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/helpers/checkIfCountIsLimited.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "17637" } ], "symlink_target": "" }
export * from './toLowerCase' export * from './toUpperCase'
{ "content_hash": "d7973c8903f199aa49939632b0aacf73", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 29, "avg_line_length": 30, "alnum_prop": 0.7, "repo_name": "TylorS167/167", "id": "70b7e30d8e7b846316ed230d9b138fa028a7695d", "size": "60", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/string/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4543" }, { "name": "TypeScript", "bytes": "196915" } ], "symlink_target": "" }
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.7.4. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{ "content_hash": "2d98b383dcbc4a129e021a5d60ca3785", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 160, "avg_line_length": 40.48, "alnum_prop": 0.7480237154150198, "repo_name": "manuelhuber/LostColonies", "id": "de4059a044535d8a78075fa3e5f1251f3c93e051", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14931" }, { "name": "HTML", "bytes": "15809" }, { "name": "JavaScript", "bytes": "1689" }, { "name": "TypeScript", "bytes": "56460" } ], "symlink_target": "" }
package org.mifos.accounts.productdefinition.business; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.mifos.accounts.productdefinition.exceptions.ProductDefinitionException; import org.mifos.accounts.productdefinition.persistence.PrdOfferingPersistence; import org.mifos.accounts.productdefinition.util.helpers.ApplicableTo; import org.mifos.accounts.productdefinition.util.helpers.PrdStatus; import org.mifos.accounts.productdefinition.util.helpers.ProductDefinitionConstants; import org.mifos.accounts.productdefinition.util.helpers.ProductType; import org.mifos.accounts.productsmix.business.ProductMixBO; import org.mifos.application.master.business.MifosCurrency; import org.mifos.application.util.helpers.YesNoFlag; import org.mifos.customers.office.business.OfficeBO; import org.mifos.customers.office.persistence.OfficePersistence; import org.mifos.dto.domain.PrdOfferingDto; import org.mifos.dto.domain.ProductDetailsDto; import org.mifos.framework.business.AbstractBusinessObject; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.Money; import org.mifos.security.util.UserContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.Set; /** * A product is a set of rules (interest rate, number of installments, maximum * amount, etc) which describes what an MFI offers. * * Although we may sometimes call these "offerings", the preferred word is * "products" (that is what they are called in the functional specification, and * the wider microfinance industry). */ public abstract class PrdOfferingBO extends AbstractBusinessObject { private static final Logger logger = LoggerFactory.getLogger(PrdOfferingBO.class); private final Short prdOfferingId; private String prdOfferingName; private String prdOfferingShortName; private final String globalPrdOfferingNum; private ProductTypeEntity prdType; private ProductCategoryBO prdCategory; private PrdStatusEntity prdStatus; private PrdApplicableMasterEntity prdApplicableMaster; private Date startDate; private Date endDate; private MifosCurrency currency; private OfficeBO office; private String description; private Set<ProductMixBO> collectionProductMix; private Set<PrdOfferingBO> prdOfferingNotAllowedId; // For Not allowed products private Short prdMixFlag; // Tagging products for which mixes were defined private Set<QuestionGroupReference> questionGroups; /** * default constructor for hibernate usage */ protected PrdOfferingBO() { this(null, null, null, null); } /** * minimal legal constructor (based on table schema) */ public PrdOfferingBO(Integer userId, String globalProductId, String name, String shortName, ProductCategoryBO productCategory, PrdStatusEntity status, PrdApplicableMasterEntity applicableToEntity, DateTime startDate, MifosCurrency currency) { this.prdOfferingId = null; this.prdOfferingName = name; this.prdOfferingShortName = shortName; this.globalPrdOfferingNum = globalProductId; this.prdCategory = productCategory; this.prdType = productCategory.getProductType(); this.prdStatus = status; this.prdApplicableMaster = applicableToEntity; this.startDate = startDate.toDate(); this.createdBy = userId.shortValue(); this.createdDate = new DateTime().toDate(); this.currency = currency; } @Deprecated protected PrdOfferingBO(final Short prdOfferingId) { this(prdOfferingId, null, null, null); } @Deprecated protected PrdOfferingBO(final Short prdOfferingId, final String globalPrdOfferingNum, final ProductTypeEntity prdType, final OfficeBO office) { this.prdOfferingId = prdOfferingId; this.globalPrdOfferingNum = globalPrdOfferingNum; this.prdType = prdType; this.office = office; } /** * */ @Deprecated public PrdOfferingBO(final String name, final String shortName, final String globalProductNumber, final Date startDate, final ApplicableTo applicableToCustomer, final ProductCategoryBO category, final PrdStatusEntity prdStatus, final Date createdDate, final Short createdByUserId) { this.prdOfferingName = name; this.prdOfferingShortName = shortName; this.globalPrdOfferingNum = globalProductNumber; this.startDate = startDate; this.prdApplicableMaster = new PrdApplicableMasterEntity(applicableToCustomer); this.prdCategory = category; this.createdDate = createdDate; this.createdBy = createdByUserId; this.prdType = category.getProductType(); this.prdStatus = prdStatus; this.prdOfferingId = null; this.office = null; } @Deprecated protected PrdOfferingBO(final UserContext userContext, final String prdOfferingName, final String prdOfferingShortName, final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate) throws ProductDefinitionException { this(userContext, prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate, null, null); } @Deprecated protected PrdOfferingBO(final UserContext userContext, final String prdOfferingName, final String prdOfferingShortName, final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate, final Date endDate, final String description) throws ProductDefinitionException { super(userContext); logger.debug("creating product offering"); validateUserContext(userContext); vaildate(prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate); validateStartDateAgainstCurrentDate(startDate); validateEndDateAgainstCurrentDate(startDate, endDate); validateDuplicateProductOfferingName(prdOfferingName); validateDuplicateProductOfferingShortName(prdOfferingShortName); prdOfferingId = null; this.prdOfferingName = prdOfferingName; this.prdOfferingShortName = prdOfferingShortName; this.prdCategory = prdCategory; this.prdType = prdCategory.getProductType(); this.prdApplicableMaster = prdApplicableMaster; this.startDate = startDate; this.endDate = endDate; this.description = description; this.globalPrdOfferingNum = generatePrdOfferingGlobalNum(); this.prdStatus = getPrdStatus(startDate, prdType); try { this.office = new OfficePersistence().getOffice(userContext.getBranchId()); } catch (PersistenceException e) { throw new ProductDefinitionException(e); } logger.debug("creating product offering done"); } public Short getPrdOfferingId() { return prdOfferingId; } public String getPrdOfferingName() { return prdOfferingName; } public String getPrdOfferingShortName() { return prdOfferingShortName; } public String getGlobalPrdOfferingNum() { return globalPrdOfferingNum; } public ProductTypeEntity getPrdType() { return prdType; } public ProductCategoryBO getPrdCategory() { return prdCategory; } /** * Most callers will want {@link #isActive()} instead (or perhaps * {@link #getStatus()}. */ public PrdStatusEntity getPrdStatus() { return prdStatus; } public PrdStatus getStatus() { return PrdStatus.fromInt(prdStatus.getOfferingStatusId()); } public abstract boolean isActive(); public PrdApplicableMasterEntity getPrdApplicableMaster() { return prdApplicableMaster; } public ApplicableTo getPrdApplicableMasterEnum() { return prdApplicableMaster.asEnum(); } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public OfficeBO getOffice() { return office; } public String getDescription() { return description; } void setPrdOfferingName(final String prdOfferingName) { this.prdOfferingName = prdOfferingName; } public void setPrdOfferingShortName(final String prdOfferingShortName) { this.prdOfferingShortName = prdOfferingShortName; } public void setPrdCategory(final ProductCategoryBO prdCategory) { this.prdCategory = prdCategory; } public void setPrdStatus(final PrdStatusEntity prdStatus) { this.prdStatus = prdStatus; } public void setPrdApplicableMaster(final PrdApplicableMasterEntity prdApplicableMaster) { this.prdApplicableMaster = prdApplicableMaster; } void setStartDate(final Date startDate) { this.startDate = startDate; } void setEndDate(final Date endDate) { this.endDate = endDate; } public void setCurrency(MifosCurrency currency) { this.currency = currency; } public MifosCurrency getCurrency() { if(currency == null) { return Money.getDefaultCurrency(); } return currency; } public void setDescription(final String description) { this.description = description; } public Set<ProductMixBO> getCollectionProductMix() { return collectionProductMix; } public void setCollectionProductMix(final Set<ProductMixBO> collectionProductMix) { this.collectionProductMix = collectionProductMix; } public Set<PrdOfferingBO> getPrdOfferingNotAllowedId() { return prdOfferingNotAllowedId; } public void setPrdOfferingNotAllowedId(final Set<PrdOfferingBO> prdOfferingNotAllowedId) { this.prdOfferingNotAllowedId = prdOfferingNotAllowedId; } public Short getPrdMixFlag() { return prdMixFlag; } public void setPrdMixFlag(final Short prdMixFlag) { this.prdMixFlag = prdMixFlag; } private String generatePrdOfferingGlobalNum() throws ProductDefinitionException { logger.debug("Generating new product Offering global number"); StringBuilder globalPrdOfferingNum = new StringBuilder(); globalPrdOfferingNum.append(userContext.getBranchId()); globalPrdOfferingNum.append("-"); Short maxPrdID = null; try { maxPrdID = new PrdOfferingPersistence().getMaxPrdOffering(); } catch (PersistenceException e) { throw new ProductDefinitionException(e); } globalPrdOfferingNum.append(StringUtils.leftPad(String.valueOf(maxPrdID != null ? maxPrdID + 1 : ProductDefinitionConstants.DEFAULTMAX + 1), 3, '0')); logger.debug("Generation of new product Offering global number done" + globalPrdOfferingNum); return globalPrdOfferingNum.toString(); } private void vaildate(final String prdOfferingName, final String prdOfferingShortName, final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate) throws ProductDefinitionException { logger.debug("Validating the fields in Prd Offering"); if (prdOfferingName == null || prdOfferingShortName == null || prdCategory == null || prdApplicableMaster == null || prdOfferingShortName.length() > 4 || startDate == null) { throw new ProductDefinitionException(ProductDefinitionConstants.ERROR_CREATE); } logger.debug("Validation of the fields in Prd Offering done."); } private void validateUserContext(final UserContext userContext) throws ProductDefinitionException { logger.debug("Validating the usercontext in Prd Offering"); if (userContext == null) { throw new ProductDefinitionException(ProductDefinitionConstants.ERROR_CREATE); } logger.debug("Validation of the fields in Prd Offering done."); } protected void validateStartDateAgainstCurrentDate(final Date startDate) throws ProductDefinitionException { if (DateUtils.getDateWithoutTimeStamp(startDate.getTime()) .compareTo(DateUtils.getCurrentDateWithoutTimeStamp()) < 0) { throw new ProductDefinitionException(ProductDefinitionConstants.INVALIDSTARTDATE); } } private void validateEndDateAgainstCurrentDate(final Date startDate, final Date endDate) throws ProductDefinitionException { if (endDate != null && DateUtils.getDateWithoutTimeStamp(startDate.getTime()).compareTo( DateUtils.getDateWithoutTimeStamp(endDate.getTime())) >= 0) { throw new ProductDefinitionException(ProductDefinitionConstants.INVALIDENDDATE); } } private PrdStatusEntity getPrdStatus(final Date startDate, final ProductTypeEntity prdType) throws ProductDefinitionException { logger.debug("getting the Product status for prdouct offering with start date :" + startDate + " and product Type :" + prdType.getProductTypeID()); PrdStatus prdStatus = null; if (startDate.compareTo(DateUtils.getCurrentDateWithoutTimeStamp()) == 0) { prdStatus = getActivePrdStatus(prdType); } else { prdStatus = getInActivePrdStatus(prdType); } try { logger.debug("getting the Product status for product status :" + prdStatus); return new PrdOfferingPersistence().getPrdStatus(prdStatus); } catch (PersistenceException e) { throw new ProductDefinitionException(e); } } private PrdStatus getActivePrdStatus(final ProductTypeEntity prdType) { logger.debug("getting the Active Product status for product Type :" + prdType.getProductTypeID()); if (prdType.getProductTypeID().equals(ProductType.LOAN.getValue())) { return PrdStatus.LOAN_ACTIVE; } return PrdStatus.SAVINGS_ACTIVE; } private PrdStatus getInActivePrdStatus(final ProductTypeEntity prdType) { logger.debug("getting the In Active Product status for product Type :" + prdType.getProductTypeID()); if (prdType.getProductTypeID().equals(ProductType.LOAN.getValue())) { return PrdStatus.LOAN_INACTIVE; } return PrdStatus.SAVINGS_INACTIVE; } private void validateDuplicateProductOfferingName(final String productOfferingName) throws ProductDefinitionException { logger.debug("Checking for duplicate product offering name"); try { PrdOfferingPersistence prdOfferingPersistence = new PrdOfferingPersistence(); Integer count = prdOfferingPersistence.getProductOfferingNameCount(productOfferingName); if (!count.equals(0)) { throw new ProductDefinitionException(ProductDefinitionConstants.DUPLPRDINSTNAME); } } catch (PersistenceException e) { throw new ProductDefinitionException(e); } } private void validateDuplicateProductOfferingShortName(final String productOfferingShortName) throws ProductDefinitionException { logger.debug("Checking for duplicate product offering short name"); try { if (!new PrdOfferingPersistence().getProductOfferingShortNameCount(productOfferingShortName).equals( Integer.valueOf("0"))) { throw new ProductDefinitionException(ProductDefinitionConstants.DUPLPRDINSTSHORTNAME); } } catch (PersistenceException e) { throw new ProductDefinitionException(e); } } public void update(final Short userId, final String prdOfferingName, final String prdOfferingShortName, final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate, final Date endDate, final String description, final PrdStatus status) throws ProductDefinitionException { vaildate(prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate); validateStartDateForUpdate(startDate); validateEndDateAgainstCurrentDate(startDate, endDate); if (!prdOfferingName.equals(this.prdOfferingName)) { validateDuplicateProductOfferingName(prdOfferingName); } if (!prdOfferingShortName.equals(this.prdOfferingShortName)) { validateDuplicateProductOfferingShortName(prdOfferingShortName); } this.prdOfferingName = prdOfferingName; this.prdOfferingShortName = prdOfferingShortName; this.prdCategory = prdCategory; this.prdApplicableMaster = prdApplicableMaster; this.startDate = startDate; this.endDate = endDate; this.description = description; try { this.prdStatus = new PrdOfferingPersistence().getPrdStatus(status); } catch (PersistenceException pe) { throw new ProductDefinitionException(pe); } logger.debug("creating product offering done"); } private void validateStartDateForUpdate(final Date startDate) throws ProductDefinitionException { if (DateUtils.getDateWithoutTimeStamp(this.startDate.getTime()).compareTo( DateUtils.getCurrentDateWithoutTimeStamp()) <= 0 && DateUtils.getDateWithoutTimeStamp(startDate.getTime()).compareTo( DateUtils.getDateWithoutTimeStamp(this.startDate.getTime())) != 0) { throw new ProductDefinitionException(ProductDefinitionConstants.STARTDATEUPDATEEXCEPTION); } else if (DateUtils.getDateWithoutTimeStamp(this.startDate.getTime()).compareTo( DateUtils.getCurrentDateWithoutTimeStamp()) > 0) { validateStartDateAgainstCurrentDate(startDate); } } public void updatePrdOfferingFlag() throws PersistenceException { this.setPrdMixFlag(YesNoFlag.YES.getValue()); new PrdOfferingPersistence().createOrUpdate(this); } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + (prdOfferingId == null ? 0 : prdOfferingId.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PrdOfferingBO other = (PrdOfferingBO) obj; return isOfSameOffering(other); } public boolean isOfSameOffering(final PrdOfferingBO other) { if (prdOfferingId == null) { if (other.prdOfferingId != null) { return false; } } else if (!prdOfferingId.equals(other.getPrdOfferingId())) { return false; } if (this.globalPrdOfferingNum != null && other.getGlobalPrdOfferingNum() != null) { if (!other.getGlobalPrdOfferingNum().equals(this.globalPrdOfferingNum)) { return false; } } return true; } public PrdOfferingDto toDto() { return new PrdOfferingDto(this.prdOfferingId, this.prdOfferingName, this.globalPrdOfferingNum); } public ProductDetailsDto toDetailsDto() { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); DateTime startDateTime = new DateTime(this.startDate); String startDateFormatted = format.format(this.startDate); String endDateFormatted = ""; DateTime endDateTime = null; if (this.endDate != null) { endDateTime = new DateTime(this.endDate); endDateFormatted = format.format(this.endDate); } ProductDetailsDto detailsDto = new ProductDetailsDto(this.prdOfferingName, this.prdOfferingShortName, this.description, this.prdCategory.getProductCategoryID().intValue(), startDateTime, endDateTime, this.prdApplicableMaster.getId().intValue()); detailsDto.setId(this.prdOfferingId.intValue()); detailsDto.setGlobalNumber(this.globalPrdOfferingNum); detailsDto.setStatus(this.prdStatus.getOfferingStatusId().intValue()); detailsDto.setCategoryName(this.prdCategory.getProductCategoryName()); detailsDto.setStartDateFormatted(startDateFormatted); detailsDto.setEndDateFormatted(endDateFormatted); detailsDto.setCreatedDate(new DateTime(this.getCreatedDate())); detailsDto.setCreatedDateFormatted(format.format(this.getCreatedDate())); return detailsDto; } public void updateDetailsOfProductNotInUse(String name, String shortName, String description, ProductCategoryBO productCategory, Date startDate, Date endDate, PrdApplicableMasterEntity applicableMasterEntity, PrdStatusEntity prdStatusEntity) { updateProductDetails(name, shortName, description, productCategory, startDate, endDate, prdStatusEntity); this.prdApplicableMaster = applicableMasterEntity; } public void updateProductDetails(String name, String shortName, String description, ProductCategoryBO productCategory, Date startDate, Date endDate, PrdStatusEntity prdStatusEntity) { this.prdOfferingName = name; this.prdOfferingShortName = shortName; this.description = description; this.prdCategory = productCategory; this.startDate = startDate; this.endDate = endDate; this.prdStatus = prdStatusEntity; } public void updateStatus(PrdStatusEntity status) { this.prdStatus = status; } public boolean isDifferentName(final String name) { return !this.prdOfferingName.equals(name); } public boolean isDifferentShortName(final String shortName) { return !this.prdOfferingShortName.equals(shortName); } public boolean isDifferentStartDate(DateTime startDate) { return !new LocalDate(startDate).equals(new LocalDate(this.startDate)); } public Set<QuestionGroupReference> getQuestionGroups() { return questionGroups; } public void setQuestionGroups(Set<QuestionGroupReference> questionGroups) { this.questionGroups = questionGroups; } public void mergeQuestionGroups(Set<QuestionGroupReference> questionGroups) { if (this.questionGroups == null || questionGroups == null) { setQuestionGroups(questionGroups); } else { for (Iterator<QuestionGroupReference> iterator = this.questionGroups.iterator(); iterator.hasNext();) { QuestionGroupReference questionGroup = iterator.next(); if (questionGroups.contains(questionGroup)) { questionGroups.remove(questionGroup); } else { iterator.remove(); } } this.questionGroups.addAll(questionGroups); } } }
{ "content_hash": "3877264a1239ea36904380e002de98a8", "timestamp": "", "source": "github", "line_count": 574, "max_line_length": 253, "avg_line_length": 40.69337979094077, "alnum_prop": 0.7005308673687816, "repo_name": "maduhu/mifos-head", "id": "442ac79fea526111ee8e3ba3e448243f8a0dd56e", "size": "24119", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "application/src/main/java/org/mifos/accounts/productdefinition/business/PrdOfferingBO.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "128581" }, { "name": "Groff", "bytes": "671" }, { "name": "HTML", "bytes": "83305" }, { "name": "Java", "bytes": "19433677" }, { "name": "JavaScript", "bytes": "586018" }, { "name": "Makefile", "bytes": "44" }, { "name": "Python", "bytes": "27237" }, { "name": "Shell", "bytes": "65574" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Trans. Br. mycol. Soc. 23: 251 (1939) #### Original name Dasyscyphus winterianus Rehm ### Remarks null
{ "content_hash": "324b61f793dbc01d70df11087fa54c89", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 14.615384615384615, "alnum_prop": 0.7052631578947368, "repo_name": "mdoering/backbone", "id": "2a3ece3c5ad4260e73ed07eeabac5a4427a1adc8", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Hyaloscyphaceae/Unguicularia/Unguicularia carestiana/ Syn. Unguicularia winteriana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import Ember from 'ember'; export default Ember.Component.extend({ tagName: "ul", // Passable parameters tags: [], //tagAdded: functionName, //tagRemoved: functionName placeholderText: "Tags", tagLimit: 10, tagit: null, shouldSendActions: true, didInsertElement: function() { var self = this; Ember.run.scheduleOnce('afterRender', this, function() { var ele = $(self.$()); var tagit = ele.tagit({ tagLimit: this.get('tagLimit'), placeholderText: this.get('placeholderText'), afterTagAdded: function(event, ui) { if (self.get('shouldSendActions')) self.afterTagAdded(ui.tagLabel); }, afterTagRemoved: function(event, ui) { if (self.get('shouldSendActions')) self.afterTagRemoved(ui.tagLabel); } }); self.set('tagit', tagit); self.notifyPropertyChange('tags'); }); }, willDestroyElement: function() { this.get('tagit').tagit('destroy'); }, refreshTagitTags: function() { var self = this; // check if the same Tags var tags = this.get('tags'), tagitTags = this.getAssignedTags(); if (tags.join() === tagitTags.join()) return; // Temporarily don't send any actions until done populating self.set('shouldSendActions', false); this.clearTags(); _.forEach(this.get('tags'), function(tag) { self.createTag(tag); }); self.set('shouldSendActions', true); }.observes('tags.@each'), clearTags: function() { var tagit = this.get('tagit'); if (tagit) tagit.tagit('removeAll'); }, createTag: function(tag) { var tagit = this.get('tagit'); if (tagit) tagit.tagit('createTag', tag); }, getAssignedTags: function() { var tagit = this.get('tagit'); if (!tagit) return []; return tagit.tagit('assignedTags'); }, afterTagAdded: function(tag) { var tagAdded = this.get('tagAdded'); if (tagAdded) this.sendAction('tagAdded', tag); }, afterTagRemoved: function(tag) { var tagRemoved = this.get('tagRemoved'); if (tagRemoved) this.sendAction('tagRemoved', tag); } });
{ "content_hash": "d1d0d5c3deb046381c64bac5020b1bfc", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 63, "avg_line_length": 24.211111111111112, "alnum_prop": 0.6025699862322166, "repo_name": "davidlukerice/genSynth", "id": "95c510bb0dcd67ae32c86de333de3315f6bfec5d", "size": "2247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/app/components/tag-it.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "115326" }, { "name": "JavaScript", "bytes": "115286" }, { "name": "Shell", "bytes": "430" } ], "symlink_target": "" }
<!DOCTYPE html> <script src="../../../resources/js-test.js"></script> <script src="testutils.js"></script> <body> <script> description('Tests that Custom Elements does not induce leaks'); var jsTestIsAsync = true; if (!window.internals) testFailed('this test requires window.internals'); function step1() { debug('Test a custom element with minimal capturing'); withFrame(function (frame) { // Create some upgrade candidates frame.contentDocument.body.innerHTML = '<x-x><x-x></x-x></x-x>'; // Register a custom element var proto = Object.create(frame.contentWindow.HTMLElement.prototype); proto.createdCallback = function () {}; proto.enteredViewCallback = function () {}; proto.leftViewCallback = function () {}; proto.attributeChangedCallback = function () {}; var ctor = frame.contentDocument.register('x-x', {prototype: proto}); // Create some instances frame.contentDocument.createElement('x-x'); frame.contentDocument.body.appendChild(new ctor()); frame.contentDocument.body.firstElementChild.innerHTML = '<x-x></x-x>'; // Watch to see that some objects die observations = { 'frame': internals.observeGC(frame), 'window': internals.observeGC(frame.contentWindow), 'document': internals.observeGC(frame.contentDocument), 'proto': internals.observeGC(proto), 'ctor': internals.observeGC(ctor), 'callback': internals.observeGC(proto.attributeChangedCallback) }; // Throw everything away frame.remove(); // We check leaks in a separate closure. checkLeaks(step2); }); } function step2() { debug('Test callbacks which close over a bunch of objects'); withFrame(function (frame) { // Register a custom element with a callback which closes over // the prototype, constructor, document, window and frame. var contentWindow = frame.contentWindow; var contentDocument = frame.contentDocument; var proto = Object.create(contentWindow.HTMLElement.prototype); proto.attributeChangedCallback = function () { var goodies = [proto, ctor, contentDocument, contentWindow, frame]; goodies.forEach(function (loot) { console.log(loot); }); }; var ctor = contentDocument.register('x-x', {prototype: proto}); // Create an instance; put it in the document var elem = new ctor(); contentDocument.body.appendChild(elem); // Watch to see that some objects die observations = { 'frame': internals.observeGC(frame), 'window': internals.observeGC(contentWindow), 'document': internals.observeGC(contentDocument), 'proto': internals.observeGC(proto), 'ctor': internals.observeGC(ctor), 'callback': internals.observeGC(proto.attributeChangedCallback) }; // Throw everything away frame.remove(); checkLeaks(step3); }); } function step3() { debug('Test that navigating a frame with custom elements does not leak'); withFrame(function (frame) { // Register a custom element with a callback which closes over // the prototype, constructor, document, window and frame. var contentWindow = frame.contentWindow; var contentDocument = frame.contentDocument; var proto = Object.create(contentWindow.HTMLElement.prototype); proto.attributeChangedCallback = function () { var goodies = [proto, ctor, contentDocument, contentWindow, frame]; goodies.forEach(function (loot) { console.log(loot); }); }; var ctor = contentDocument.register('x-x', {prototype: proto}); // Create an instance; put it in the document *and* point to // it from the window. var elem = new ctor(); contentDocument.body.appendChild(elem); contentWindow.thePrecious = elem; // Watch to see that some objects die; we don't watch the // window because Blink recycles the window observations = { 'document': internals.observeGC(contentDocument), 'proto': internals.observeGC(proto), 'ctor': internals.observeGC(ctor), 'callback': internals.observeGC(proto.attributeChangedCallback) }; // Throw everything away frame.onload = checkLeaksAndFinishTest; frame.src = 'about:blank'; }); } function checkLeaksAndFinishTest() { checkLeaks(finishJSTest); } function checkLeaks(nextStep) { setTimeout(function () { gc(); // Check that everything that should have died, did die for (var prop in observations) shouldBeTrue('observations.' + prop + '.wasCollected'); observations = null; nextStep(); }, 0); } step1(); var successfullyParsed = true; </script>
{ "content_hash": "2c6569e6323040eb9b2bbc5060564813", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 79, "avg_line_length": 33.18543046357616, "alnum_prop": 0.6308122131311116, "repo_name": "lordmos/blink", "id": "eac4cbfc5edba1a633bc11e53ce5ce3be8d5ec93", "size": "5011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LayoutTests/fast/dom/custom/leaks.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6433" }, { "name": "C", "bytes": "753714" }, { "name": "C++", "bytes": "40028043" }, { "name": "CSS", "bytes": "539440" }, { "name": "F#", "bytes": "8755" }, { "name": "Java", "bytes": "18650" }, { "name": "JavaScript", "bytes": "25700387" }, { "name": "Objective-C", "bytes": "426711" }, { "name": "PHP", "bytes": "141755" }, { "name": "Perl", "bytes": "901523" }, { "name": "Python", "bytes": "3748305" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "9635" }, { "name": "XSLT", "bytes": "49328" } ], "symlink_target": "" }
package com.liangmayong.base.binding.mvp; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by LiangMaYong on 2016/9/17. */ public class Presenter<V> { //viewState private V viewState = null; //isAttached private boolean isAttached = false; /** * getViewState * * @return view */ protected final V getViewState() { return viewState; } /** * isAttached * * @return isAttached */ public final boolean isAttached() { return isAttached; } /** * attach * * @param view view */ public void onAttach(final V view) { try { viewState = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (isAttached()) { Object result = method.invoke(view, args); return result; } } catch (Exception e) { handleThrowable(e); } return null; } }); } catch (Exception e) { viewState = view; } isAttached = true; } /** * handleThrowable * * @param throwable throwable */ protected void handleThrowable(Throwable throwable) { throwable.printStackTrace(); } /** * dettach */ public void onDettach() { isAttached = false; } }
{ "content_hash": "3a9fca15baba0abc2047adc81bbe471d", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 143, "avg_line_length": 22.705128205128204, "alnum_prop": 0.5059288537549407, "repo_name": "LiangMaYong/android-base", "id": "4137f80814a7270f1a46d61fa56d5f207a705dc4", "size": "1771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base/src/main/java/com/liangmayong/base/binding/mvp/Presenter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "64" }, { "name": "CSS", "bytes": "8643" }, { "name": "HTML", "bytes": "41228" }, { "name": "Java", "bytes": "1009177" }, { "name": "JavaScript", "bytes": "28344" } ], "symlink_target": "" }
class CreateUserPermissions < ActiveRecord::Migration def change create_table :user_permissions do |t| t.string :action t.string :target t.timestamps end end end
{ "content_hash": "63ef024f3435d09fd434174a0d222719", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 53, "avg_line_length": 19.3, "alnum_prop": 0.6787564766839378, "repo_name": "TaxiDash/ServerV2", "id": "90b33542cbd751e7805af1bbbae71a9576a7effc", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20140819215644_create_user_permissions.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4095" }, { "name": "CoffeeScript", "bytes": "2954" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "151641" } ], "symlink_target": "" }
TS=`date +"%d%b%y_%H%M"` bname=`basename "$1" | cut -d'.' -f1` logname="Results/"$bname"_"$TS".log" bname=`basename "$1"` bname="${bname#*.}" logname="Results/ba_ctrl_"$TS".log" ## Print metrics and save to log files # Arguments: # original (reference) dataset in eddgelist format # # find datasets -name "$bname"_*dimacs.tree | parallel python "td.phrg.py --orig '$1' --clqtree" {} ">" {}.log # python td.isom_jaccard_sim.py --orig /data/saguinag/datasets/out.ucidata-gama --pathfrag datasets/ucidata-gama_ # cat tdec/maindatasets | parallel python "td.isom_jaccard_sim.py --orig {} --pathfrag datasets/'$bname'_" #echo $1 | parallel python "td.isom_jaccard_sim.py --orig {} --pathfrag datasets/'$bname'_" python td_rndGStats.py &>$logname
{ "content_hash": "ddf01f7c83222bbef1b3973e72a14bf6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 114, "avg_line_length": 47, "alnum_prop": 0.6702127659574468, "repo_name": "nddsg/TreeDecomps", "id": "34ad29ed888e6d0951c7deb452408f5122631adf", "size": "764", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xplodnTree/tdec/exp.rnd.sh", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "2829280" }, { "name": "Jupyter Notebook", "bytes": "187050" }, { "name": "Python", "bytes": "612322" }, { "name": "R", "bytes": "1183" }, { "name": "Shell", "bytes": "12336" }, { "name": "TeX", "bytes": "3599" } ], "symlink_target": "" }
package org.robolectric.shadows; import android.content.ContentProviderResult; import android.net.Uri; import java.lang.reflect.Field; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; @Implements(ContentProviderResult.class) public class ShadowContentProviderResult { @RealObject ContentProviderResult realResult; @Implementation protected void __constructor__(Uri uri) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = realResult.getClass().getField("uri"); field.setAccessible(true); field.set(realResult, uri); } @Implementation protected void __constructor__(int count) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = realResult.getClass().getField("count"); field.setAccessible(true); field.set(realResult, count); } }
{ "content_hash": "d0f0c2bbc2a86aa411b6b1ca31be036c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 79, "avg_line_length": 32.83870967741935, "alnum_prop": 0.775049115913556, "repo_name": "spotify/robolectric", "id": "baf44dd137b1d29860256c6aa20a72f25e4e9c7c", "size": "1018", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "shadows/framework/src/main/java/org/robolectric/shadows/ShadowContentProviderResult.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "27392" }, { "name": "Java", "bytes": "4430781" }, { "name": "Ruby", "bytes": "9159" }, { "name": "Shell", "bytes": "20540" } ], "symlink_target": "" }
package org.linaro.glmark2; import android.app.Activity; import android.os.Bundle; import android.opengl.GLSurfaceView; import android.app.Dialog; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Context; import android.os.PowerManager; import android.os.PowerManager.WakeLock; public class Glmark2Activity extends Activity { public static final int DIALOG_EGLCONFIG_FAIL_ID = 0; public static final String TAG = "GLMark2"; private WakeLock mWakeLock; @Override protected void onDestroy() { super.onDestroy(); mWakeLock.release(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); mWakeLock.acquire(); mGLView = new Glmark2SurfaceView(this); setContentView(mGLView); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); Glmark2Activity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid()); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch (id) { case DIALOG_EGLCONFIG_FAIL_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Glmark2 cannot run because it couldn't find a suitable EGLConfig for GLES2.0. Please check that proper GLES2.0 drivers are installed."); builder.setCancelable(false); builder.setPositiveButton("Quit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Glmark2Activity.this.finish(); /* * Force process shutdown. There is no safer way to * do this, as we have open threads we can't close * when we fail to get an EGLConfig */ android.os.Process.killProcess(android.os.Process.myPid()); } }); dialog = builder.create(); break; default: dialog = null; break; } return dialog; } private GLSurfaceView mGLView; static { System.loadLibrary("glmark2-android"); } }
{ "content_hash": "ea037c136593df803299c85d67a3aed9", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 172, "avg_line_length": 31.102272727272727, "alnum_prop": 0.5893313847278042, "repo_name": "endlessm/chromium-browser", "id": "bc0dde4a7893489563d04cf06add5069bd170c83", "size": "2737", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "third_party/angle/third_party/glmark2/src/android/src/org/linaro/glmark2/Glmark2Activity.java", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_111) on Thu Aug 18 01:51:59 UTC 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.hadoop.fs.http.server.HttpFSParametersProvider (Apache Hadoop HttpFS 2.7.3 API)</title> <meta name="date" content="2016-08-18"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.fs.http.server.HttpFSParametersProvider (Apache Hadoop HttpFS 2.7.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/fs/http/server/HttpFSParametersProvider.html" title="class in org.apache.hadoop.fs.http.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/fs/http/server/class-use/HttpFSParametersProvider.html" target="_top">Frames</a></li> <li><a href="HttpFSParametersProvider.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.fs.http.server.HttpFSParametersProvider" class="title">Uses of Class<br>org.apache.hadoop.fs.http.server.HttpFSParametersProvider</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.fs.http.server.HttpFSParametersProvider</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/fs/http/server/HttpFSParametersProvider.html" title="class in org.apache.hadoop.fs.http.server">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/fs/http/server/class-use/HttpFSParametersProvider.html" target="_top">Frames</a></li> <li><a href="HttpFSParametersProvider.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "30580cba576e95eacc619504f02e99a9", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 177, "avg_line_length": 40.376068376068375, "alnum_prop": 0.6202370872142252, "repo_name": "TK-TarunW/ecosystem", "id": "9f5025d51c31948bfa39854959dc2a5a55a1c605", "size": "4724", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hadoop-2.7.3/share/doc/hadoop/hadoop-hdfs-httpfs/apidocs/org/apache/hadoop/fs/http/server/class-use/HttpFSParametersProvider.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "9732" }, { "name": "Batchfile", "bytes": "188552" }, { "name": "C", "bytes": "598922" }, { "name": "C++", "bytes": "949406" }, { "name": "CSS", "bytes": "551632" }, { "name": "HTML", "bytes": "98452345" }, { "name": "Java", "bytes": "7461358" }, { "name": "JavaScript", "bytes": "38346" }, { "name": "M4", "bytes": "76410" }, { "name": "Makefile", "bytes": "144646" }, { "name": "Perl", "bytes": "226332" }, { "name": "Perl6", "bytes": "70570" }, { "name": "PowerShell", "bytes": "13769" }, { "name": "Python", "bytes": "2259345" }, { "name": "R", "bytes": "226319" }, { "name": "Scala", "bytes": "554308" }, { "name": "Shell", "bytes": "772310" }, { "name": "XS", "bytes": "132876" }, { "name": "XSLT", "bytes": "27180" } ], "symlink_target": "" }
import Schema from 'ember-cli-mirage/orm/schema'; import Model from 'ember-cli-mirage/orm/model'; import Db from 'ember-cli-mirage/db'; import {module, test} from 'qunit'; var db, schema, User; module('Integration | ORM | attrs', { beforeEach() { db = new Db({ users: [ { id: 1, name: 'Link', evil: false } ] }); User = Model.extend(); schema = new Schema(db, { user: User }); } }); test('attrs returns the models attributes', function(assert) { let user = schema.users.find(1); assert.deepEqual(user.attrs, { id: '1', name: 'Link', evil: false }); }); test('attributes can be read via plain property access', function(assert) { let user = schema.users.find(1); assert.equal(user.name, 'Link'); });
{ "content_hash": "b33efac4dd10eb047f3e8d2698392969", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 24.966666666666665, "alnum_prop": 0.630173564753004, "repo_name": "lazybensch/ember-cli-mirage", "id": "50b1756b8f7a005d35e932718ba174ffc39a15d4", "size": "777", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/integration/orm/attrs-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31" }, { "name": "HTML", "bytes": "3013" }, { "name": "JavaScript", "bytes": "321414" } ], "symlink_target": "" }
package io.pravega.connectors.flink; import org.apache.flink.api.common.typeutils.SerializerTestBase; import org.apache.flink.api.common.typeutils.TypeSerializer; public class FlinkPravegaTransactionStateSerializerTest extends SerializerTestBase<FlinkPravegaWriter.PravegaTransactionState> { @Override protected TypeSerializer<FlinkPravegaWriter.PravegaTransactionState> createSerializer() { return new FlinkPravegaWriter.TransactionStateSerializer(); } @Override protected Class<FlinkPravegaWriter.PravegaTransactionState> getTypeClass() { return FlinkPravegaWriter.PravegaTransactionState.class; } @Override protected int getLength() { return -1; } @Override protected FlinkPravegaWriter.PravegaTransactionState[] getTestData() { //noinspection unchecked return new FlinkPravegaWriter.PravegaTransactionState[] { new FlinkPravegaWriter.PravegaTransactionState("txnid", 1L), new FlinkPravegaWriter.PravegaTransactionState("txnid", null), new FlinkPravegaWriter.PravegaTransactionState(), }; } @Override public void testInstantiate() { // this serializer does not support instantiation } }
{ "content_hash": "c075b68711e707f38ff1992dbcbdb42b", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 128, "avg_line_length": 33.21052631578947, "alnum_prop": 0.7321711568938193, "repo_name": "pravega/flink-connectors", "id": "a1087c9dfbe3f5101da994bbe33b2b43d8469e43", "size": "1857", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/io/pravega/connectors/flink/FlinkPravegaTransactionStateSerializerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "836719" }, { "name": "Python", "bytes": "16835" } ], "symlink_target": "" }
npm run build cp ./clasp/production/.clasp.json ./dist cp ./clasp/production/appsscript.json ./dist cp ./src/api.js ./dist (cd ./dist && clasp push) rm ./dist/.clasp.json rm ./dist/appsscript.json rm ./dist/api.js
{ "content_hash": "7632f75ce57ac98685b093dc090baa15", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 21.5, "alnum_prop": 0.7023255813953488, "repo_name": "artofthesmart/Ob2SS", "id": "d8171c5bfb989316b21cfbedae06f078aea9dcf2", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clasp/production/push.sh", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26186" }, { "name": "Shell", "bytes": "397" }, { "name": "TypeScript", "bytes": "80325" } ], "symlink_target": "" }
package com.github.ybq.android.spinkit.animation.interpolator; import android.view.animation.Interpolator; /** * Created by ybq. */ public class Ease { public static Interpolator inOut() { return PathInterpolatorCompat.create(0.42f, 0f, 0.58f, 1f); } }
{ "content_hash": "38358b6666ea38f32b836f0fac1d3e98", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 67, "avg_line_length": 22.75, "alnum_prop": 0.7106227106227107, "repo_name": "horsesdeveloper/camera", "id": "916ca6f97496f9d4f4ea58c02db94ec0cd7314fb", "size": "273", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spin/src/main/java/com/github/ybq/android/spinkit/animation/interpolator/Ease.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "247100" } ], "symlink_target": "" }
package org.jvyamlb.nodes; import org.jruby.util.ByteList; import org.jvyamlb.Position; import org.jvyamlb.Positionable; /** * @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a> */ public class PositionedScalarNode extends ScalarNode implements Positionable { private Position.Range range; public PositionedScalarNode(final String tag, final ByteList value, final char style, final Position.Range range) { super(tag, value, style); assert range != null; this.range = range; } public Position getPosition() { return range.start; } public Position.Range getRange() { return range; } public boolean equals(Object other) { boolean ret = this == other; if(!ret && (other instanceof PositionedScalarNode)) { PositionedScalarNode o = (PositionedScalarNode)other; ret = this.getValue().equals(o.getValue()) && (null == this.getTag() ? null == o.getTag() : this.getTag().equals(o.getTag())) && this.getStyle() == o.getStyle() && this.getRange().equals(o.getRange()); } return ret; } public String toString() { return "#<" + this.getClass().getName() + " value=\"" + getValue() + "\" tag="+getTag()+" style="+getStyle()+" range=" + getRange() + ">"; } }// PositionedScalarEvent
{ "content_hash": "5c3c335d7b9765c6d72b446d9036f409", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 146, "avg_line_length": 31.066666666666666, "alnum_prop": 0.6008583690987125, "repo_name": "olabini/jvyamlb", "id": "8edecf4d2199f4d9740a215b79d6b4e19531acb8", "size": "1481", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/org/jvyamlb/nodes/PositionedScalarNode.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "471267" }, { "name": "Perl", "bytes": "91" }, { "name": "Ragel in Ruby Host", "bytes": "2942" }, { "name": "Shell", "bytes": "241" } ], "symlink_target": "" }
""" ******************************************** * Title: Creating data manipulation w/ Gui * * Author: Dustin A. Landers * * License: GNU GPL-3 * ******************************************** """ import os import csv from Tkinter import * def cls(): os.system('cls') class Data: """ This is the standard Data object. It requires the location of the CSV file to be uploaded. self.data provides a dictionary of rows, so that self.data[0] provides the first row of the data. This could be used to extract the coloumn names for example. self.name provides the file location. self.col provides a dictionary of columns, so that self.col[0] provides the first column of the data. self.col is essentially the transposed version of self.data. """ def __init__(self, loc): self.name = loc self.data = self.data_read() self.ncol = self.ncol() self.nrow = self.nrow() self.col = self.transpose() self.bio_data = self.biodata_transform() self.col_ncol = self.col_ncol() self.col_nrow = self.col_nrow() ## This function reads the data in to a dictionary where each key is the row number def data_read(self): data = dict() with open(self.name, 'rb') as csvfile: reader = csv.reader(csvfile) n = 0 for row in reader: data[n] = row n += 1 return data ## This function returns the number of columns in self.data def ncol(self): ncol = 0 for row in self.data: if len(self.data[row]) > ncol: ncol = len(self.data[row]) return ncol ## This function returns the number of rows in self.data def nrow(self): nrow = 0 for row in self.data: nrow += 1 return nrow ## This function returns the number of columns in self.col def col_ncol(self): ncol = 0 for row in self.col: if len(self.col[row]) > ncol: ncol = len(self.col[row]) return ncol ## The function returns the number of rows in self.col def col_nrow(self): nrow = 0 for row in self.col: nrow += 1 return nrow ## This function provides a dictionary of lists (vectors in R) for each ## of the columns (as opposed to each of the row which is what self.data is) def transpose(self): col_dict = dict() to_dict = [] for column in range(self.ncol): for row in self.data: to_dict.append(self.data[row][column]) col_dict[column] = to_dict to_dict = [] return col_dict ## This function tranposes the data to the proper format def biodata_transform(self): trans_dict = dict() row_num = 0 for row in self.data: use_range = range(len(self.data[row])-2) replicate = 1 for i in use_range: use_range[i] = use_range[i] + 2 for each in use_range: trans_dict[row_num] = [replicate, self.data[row][0], self.data[row][1], self.data[row][each]] row_num += 1 replicate += 1 return trans_dict ## This function exports the dictionary to csv def data_write(self, dict, file): with open(file, 'wb') as csvfile: writer = csv.writer(csvfile) for row in dict: writer.writerow(dict[row]) class App: """ This builds the GUI app which will eventually be put to an executable. """ def __init__(self, master): self.label = Label(master, text='Type full CSV location below \n Example: C:\Users\Dustin\Documents\Github\PyPlant \n\n\n') self.label.pack() self.en = Entry(master) self.en.pack() self.button = Button(master, text='Click here to transform and export as export.csv', command=self.load) self.button.pack() def load(self): filename = self.en.get() test = Data(filename) test.data_write(test.bio_data, 'export.csv') root = Tk() root.wm_title('Stapleton Lab Data Cleaner') app = App(root) root.mainloop()
{ "content_hash": "a480832c62b7210e046f3733d107c4c0", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 125, "avg_line_length": 27.601503759398497, "alnum_prop": 0.6513211658948516, "repo_name": "mtnman38/Horiz2Vert", "id": "57eba2ed55ab22308e8c249acfa5e915456ea9f1", "size": "3671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SL Data Cleaner/gum.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "19822" } ], "symlink_target": "" }
<div class="mod_animate" id="J_datasourceContent"></div>
{ "content_hash": "218d10e20cf79acc145f5b0060c5280f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 56, "avg_line_length": 56, "alnum_prop": 0.7321428571428571, "repo_name": "knowThis/wxms", "id": "c6ececa173274a05e8cb84b1bbd5ced75e3111b4", "size": "56", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "views/datasource_content.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4991" }, { "name": "HTML", "bytes": "74138" }, { "name": "JavaScript", "bytes": "219119" } ], "symlink_target": "" }
from pysc2.lib import actions import random from oscar.agent.custom_agent import CustomAgent # TODO: As RandomAgent is no more callable directly by pysc2, action_spec is undefined. class RandomAgent(CustomAgent): def __init__(self): super().__init__() def step(self, obs, locked_choice=None): output = [] selected_action_id = random.choice(obs.observation["available_actions"]) args = self.action_spec.functions[selected_action_id].args for arg in args: output.append([random.randint(0, size - 1) for size in arg.sizes]) return {'actions': [actions.FunctionCall(selected_action_id, output)]}
{ "content_hash": "9c179ecc6ecac5d31ee80b6233cde525", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 30.363636363636363, "alnum_prop": 0.6736526946107785, "repo_name": "Xaxetrov/OSCAR", "id": "133c9c40fda6320dcdb329f7a2f39138acff8693", "size": "668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oscar/agent/scripted/random.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "250337" }, { "name": "Shell", "bytes": "3498" } ], "symlink_target": "" }
@interface ArtistDetailTableViewConrtoller () - (BOOL)validAttribute:(NSString * )attrib; @property (nonatomic, strong, readonly) NSArray *values; @end @implementation ArtistDetailTableViewConrtoller @synthesize artist = _artist; @synthesize values = _values; - (void)viewWillDisappear:(BOOL)animated { // setup the animation for a page flip [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO]; // commit the animations [UIView commitAnimations]; } - (BOOL)validAttribute:(NSString * )attrib { BOOL isValid = FALSE; NSRange range = [attrib rangeOfString:@"??" options:NSCaseInsensitiveSearch]; NSRange range2 = [attrib rangeOfString:@"--" options:NSCaseInsensitiveSearch]; if (range.location == NSNotFound && range2.location == NSNotFound) { isValid = TRUE; } return isValid; } - (NSArray *)values { if (!_values) { NSMutableArray *mutable = [NSMutableArray array]; [mutable addObject:[NSArray arrayWithObjects:@"Artist Name", self.artist.artist_name, nil]]; [mutable addObject:[NSArray arrayWithObjects:@"Birthdate", self.artist.birthdate, nil]]; if ([self validAttribute:self.artist.birthplace]) { [mutable addObject:[NSArray arrayWithObjects:@"Birthplace", self.artist.birthplace, nil]]; } if ([self validAttribute:self.artist.died]) { // Death date [mutable addObject:[NSArray arrayWithObjects:@"Died", self.artist.died, nil]]; } else { // Still alive, calculate current age NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"dd-MMM-yy"]; NSLog(@"%@", self.artist.birthdate.description); NSDate *birthdate = [formatter dateFromString:self.artist.birthdate]; NSInteger yearsOld = [birthdate calculateAgeInYears]; NSString *yearsOldString = [NSString stringWithFormat:@"%d", yearsOld]; [mutable addObject:[NSArray arrayWithObjects:@"Current Age", yearsOldString , nil]]; } if ([self validAttribute:self.artist.bands_played]) { [mutable addObject:[NSArray arrayWithObjects:@"Bands Played", self.artist.bands_played, nil]]; } if ([self validAttribute:self.artist.url]) { [mutable addObject:[NSArray arrayWithObjects:@"Wikipedia link", self.artist.url, nil]]; } NSLog(@"values=%@", mutable); _values = mutable; } return _values; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.values.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } id value = [self.values objectAtIndex:indexPath.row]; cell.textLabel.text = [value objectAtIndex:0]; cell.detailTextLabel.text = [value objectAtIndex:1]; return cell; } - (IBAction)showURL:(UIBarButtonItem *)sender { NSURL *url = [NSURL URLWithString:self.artist.url]; if (url.scheme.length < 4 || [url.scheme compare:@"http" options:NSCaseInsensitiveSearch range:NSMakeRange(0, 4)] != NSOrderedSame) { NSArray *subs = [self.artist.artist_name componentsSeparatedByString:@" "]; NSString *arg = [subs componentsJoinedByString:@"+"]; url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", arg]]; } [[UIApplication sharedApplication] openURL:url]; } - (IBAction)tweet:(id)sender { if ([TWTweetComposeViewController canSendTweet]) { TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init]; [tweetSheet setInitialText:[NSString stringWithFormat:@"Happy Birthday %@!", self.artist.artist_name]]; [self presentModalViewController:tweetSheet animated:YES]; } else { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; } } @end
{ "content_hash": "53bf24b767d9aa384a924f976ffc39b2", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 276, "avg_line_length": 38.72868217054263, "alnum_prop": 0.6361088871096877, "repo_name": "austimkelly/rrdb", "id": "55a9b7ffaf7dd23daa3a21277d8885e57a2653d5", "size": "6299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coreDataDemoComplete/RockAndRollBirthdays/RockAndRollBirthdays/ArtistDetailTableViewConrtoller.m", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }