language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case BpsimPackage.BP_SIM_DATA_TYPE__GROUP: return group != null && !group.isEmpty(); case BpsimPackage.BP_SIM_DATA_TYPE__SCENARIO: return !getScenario().isEmpty(); } return super.eIsSet(featureID); }
python
def create(dataset, target, model_name, features=None, validation_set='auto', distributed='auto', verbose=True, seed=None, **kwargs): """ Create a :class:`~turicreate.toolkits.SupervisedLearningModel`, This is generic function that allows you to create any model that implements Su...
python
def read_model(self): """ Read the model and the couplings from the model file. """ if self.verbosity > 0: settings.m(0,'reading model',self.model) # read model boolRules = [] for line in open(self.model): if line.startswith('#') and 'modelType =' ...
java
public static ClassDescriptorCache getInstance() { if (INSTANCE == null) { synchronized (ClassDescriptorCache.class) { if (INSTANCE == null) { INSTANCE = new ClassDescriptorCache(); } } } return INSTANCE; }
java
@Override protected Object primTransform(Object anObject) throws Exception { return Integer.valueOf(((Long) anObject).toString()); }
java
public void updateUtf8(String[] strings) { if (strings != null) { for (String string : strings) { updateUtf8(string); } } }
java
@Override protected void initBuilderSpecific() throws Exception { reset(); FilePath workspace = getModuleRoot(EnvVars.masterEnvVars); FilePath gradlePropertiesPath = new FilePath(workspace, "gradle.properties"); if (releaseProps == null) { releaseProps = PropertyUtils.get...
java
public String removeAgreement(String agreementId) { Invocation invocation = getJerseyClient().target(getEndpoint() + "/agreements/" + agreementId).request() .header("Accept", MediaType.APPLICATION_JSON) .header("Content-Type", MediaType.APPLICATION_JSON) .buildDel...
python
def int_element(element, name, default=0): """ Returns the int value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to ...
python
def get_response_form(self, assessment_section_id, item_id): """Gets the response form for submitting an answer. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` arg: item_id (osid.id.Id): ``Id`` of the ``Item`` return: (osid.assessment....
java
public String getMaxDateCreated() { if (m_searchParams.getMaxDateCreated() == Long.MAX_VALUE) { return ""; } return Long.toString(m_searchParams.getMaxDateCreated()); }
python
def run_container(image, name=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, bg=False, replace=False, ...
python
def run(self): """The main routine for a thread's work. The thread pulls tasks from the manager's task queue and executes them until it encounters a task with a function that is None. """ try: while True: aFunction, arguments = self.manager.taskQueue.get() if aFunction is None...
java
public void addSigningData(String signingMethod, String publicKeyLocation, String clearSignedMessage) { this.signingMethod = signingMethod; this.publicKeyLocation = publicKeyLocation; this.clearSignedMessage = clearSignedMessage; this.signed = true; }
python
def _init_map(self): """stub""" super(MultiLanguageCalculationInteractionQuestionFormRecord, self)._init_map() MultiLanguageQuestionFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) self.my_osid_object_form._my_map['variables'] = \ self._variables_met...
java
static BufferedImage convertImage (BufferedImage image) { switch (image.getType()) { case BufferedImage.TYPE_INT_ARGB_PRE: return image; // Already good to go case BufferedImage.TYPE_4BYTE_ABGR: image.coerceData(true); // Just premultiply the alpha and it's fine return image; } //...
java
private static void decodeBase256Segment(BitSource bits, StringBuilder result, Collection<byte[]> byteSegments) throws FormatException { // Figure out how long the Base 256 Segment is. int codewordPosition = 1 + bits.get...
java
public F3<P1, P2, P3, Option<R>> lift() { final F3<P1, P2, P3, R> me = this; return new F3<P1, P2, P3, Option<R>>() { @Override public Option<R> apply(P1 p1, P2 p2, P3 p3) { try { return some(me.apply(p1, p2, p3)); ...
python
def resolve_code_path(cwd, codeuri): """ Returns path to the function code resolved based on current working directory. Parameters ---------- cwd str Current working directory codeuri CodeURI of the function. This should contain the path to the function code Returns ---...
java
@SuppressWarnings("override")// must be disabled to support jdk 6+ public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) { if (annotationClass == null) { throw new NullPointerException("Cannot get a declared annotation with a 'null' annotationClass."); } ...
python
def ApproximateDistanceBetweenPoints(pa, pb): """Finds the distance between two points on the Earth's surface. This is an approximate distance based on assuming that the Earth is a sphere. The points are specified by their lattitude and longitude. Args: pa: the first (lat, lon) point tuple pb: the sec...
python
def extra_args_parser(parser=None, skip_args=None, **kwargs): """Adds --temps to MCMCIO parser. """ if skip_args is None: skip_args = [] parser, actions = MCMCMetadataIO.extra_args_parser( parser=parser, skip_args=skip_args, **kwargs) if 'temps' not in ski...
python
def drawLine(self, p1, p2): """Draw a line between two points. """ p1 = Point(p1) p2 = Point(p2) if not (self.lastPoint == p1): self.draw_cont += "%g %g m\n" % JM_TUPLE(p1 * self.ipctm) self.lastPoint = p1 self.updateRect(p1) self.draw...
python
def _handle_group_with(self, group_with): '''Handle input option group_with''' if group_with is None or not group_with: var_name = [] var_value = [] elif isinstance(group_with, str): var_name = ['_' + group_with] if group_with not in env.sos_dict: ...
python
def from_bytes(b): """ Generates either a HDPrivateKey or HDPublicKey from the underlying bytes. The serialization must conform to the description in: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format Args: b (bytes): A byte stream ...
python
def remove_chain(self, chain=-1): """ Removes a chain from ChainConsumer. Calling this will require any configurations set to be redone! Parameters ---------- chain : int|str, list[str|int] The chain(s) to remove. You can pass in either the chain index, or the chain ...
java
public final Iterable<ItemT> search(final RequestT request, final String fields) { return search(request, setFieldsInitializer(fields), RetryPolicy.defaultPolicy()); }
java
public Endpoint withWeight(int weight) { ensureSingle(); validateWeight(weight); if (this.weight == weight) { return this; } return new Endpoint(host(), ipAddr(), port, weight, hostType); }
java
static boolean scanForChildTag(XMLStreamReader reader, String tagName) throws XMLStreamException { assert reader.isStartElement(); int level = -1; while (reader.hasNext()) { //keep track of level so we only search children, not descendants if (reader.isStartElement()) { level++; } else i...
python
def _calc_i0p(i0, w, aod700, p): """Calculate the "enhanced extraterrestrial irradiance".""" p0 = 101325. io0 = 1.08 * w**0.0051 i01 = 0.97 * w**0.032 i02 = 0.12 * w**0.56 i0p = i0 * (i02*aod700**2 + i01*aod700 + io0 + 0.071*np.log(p/p0)) return i0p
java
public static ISREInstall getDefaultSREInstall() { final ISREInstall install = getSREFromId(getDefaultSREId()); if (install != null && install.getValidity().isOK()) { return install; } // if the default SRE goes missing, re-detect LOCK.lock(); try { //defaultSREId = null; initializeSREs(); } fina...
python
def _postprocess_response(self, result): """ Apply fixups mimicking ActionBase._execute_module(); this is copied verbatim from action/__init__.py, the guts of _parse_returned_data are garbage and should be removed or reimplemented once tests exist. :param dict result: ...
java
public <T extends RegressionEvaluation> T evaluateRegressionMDS(JavaRDD<MultiDataSet> data, int minibatchSize) { return (T)doEvaluationMDS(data, minibatchSize, new org.deeplearning4j.eval.RegressionEvaluation())[0]; }
python
def maximum_impact_estimation(membership_matrix, max_iters=1000): """An expectation maximization technique that produces pathway definitions devoid of crosstalk. That is, each gene is mapped to the pathway in which it has the greatest predicted impact; this removes any overlap between pathway definition...
python
def this_year(): """ Return start and end date of this fiscal year """ since = TODAY while since.month != 3 or since.day != 1: since -= delta(days=1) until = since + delta(years=1) return Date(since), Date(until)
java
public static void setAdditionalFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 ==...
java
public static HasInputStream lazyStream(final InputStream data) { return new HasInputStream() { @Override public InputStream getInputStream() throws IOException { return data; } @Override public long writeContent(OutputStream outputStr...
java
public static KeyRange closedClosed(Key start, Key end) { return new KeyRange(checkNotNull(start), Endpoint.CLOSED, checkNotNull(end), Endpoint.CLOSED); }
java
public static boolean isAnnotationPresentInSuperClasses(final Class<?> componentClass, final Class<? extends Annotation> annotationClass) { if (componentClass.isAnnotationPresent(annotationClass)) { return true; } Class<?> superClass = componentClass.getSuperclass(); while (superClass != null) { if...
python
def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None): """Calls through to SCons.Subst.scons_subst_list(). See the documentation for that function.""" gvars = self.gvars() lvars = self.lvars() lvars['__env__'] = self if executor: ...
python
def addLayerNode(self, layerName, bias = None, weights = {}): """ Adds a new node to a layer, and puts in new weights. Adds node on the end. Weights will be random, unless specified. bias = the new node's bias weight weights = dict of {connectedLayerName: [weights], ...} ...
java
@InterfaceAudience.Public public SavedRevision getRevision(String revID) { if (revID != null && currentRevision != null && revID.equals(currentRevision.getId())) return currentRevision; RevisionInternal revisionInternal = database.getDocument(getId(), revID, true); return getRevi...
java
private Optional<ScmInfo> generateAndMergeDb(Component file, boolean keepAuthorAndRevision) { Optional<DbScmInfo> dbInfoOpt = scmInfoDbLoader.getScmInfo(file); if (!dbInfoOpt.isPresent()) { return generateScmInfoForAllFile(file); } ScmInfo scmInfo = keepAuthorAndRevision ? dbInfoOpt.get() : remov...
java
public OvhTaskPop delegatedAccount_email_changePassword_POST(String email, String password) throws IOException { String qPath = "/email/domain/delegatedAccount/{email}/changePassword"; StringBuilder sb = path(qPath, email); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "password", passwor...
python
def touch_p(filepath, times=None, mkdir=True): """ mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) ...
python
def record(cls_def): """ Namedtuple which could inherit from other types. >>> from Redy.Magic.Classic import record >>> class Interface: pass >>> @record >>> class S(Interface): >>> name: str >>> addr: str >>> sex : int >>> s = S("sam", "I/O", 1) """ annotati...
java
public void addJoinColumns(String joinColumn) { if (joinColumns == null || joinColumns.isEmpty()) { joinColumns = new HashSet<String>(); } joinColumns.add(joinColumn); }
python
def config_string(self): """ See the class documentation. """ # Note: _write_to_conf is determined when the value is calculated. This # is a hidden function call due to property magic. val = self.str_value if not self._write_to_conf: return "" ...
python
def render_html_attributes(**kwargs): """Returns a string representation of attributes for html entities :param kwargs: attributes and values :return: a well-formed string representation of attributes""" attr = list() if kwargs: attr = ['{}="{}"'.format(key, val) for key, val in kwargs.items...
python
def fft_propagate_2d(fftfield, d, nm, res, method="helmholtz", ret_fft=False): """Propagate a 1D Fourier transformed field in 2D Parameters ---------- fftfield : 1d array Fourier transform of 1D Electric field component d : float Distance to be propagated in p...
java
private String getContentHandlerPkgPrefixes() { String packagePrefixList = System.getProperty(contentPathProp, ""); if (packagePrefixList != "") { packagePrefixList += "|"; } return packagePrefixList + contentClassPrefix; }
java
private void initFinalPositionAndOffset(BufferObjectDataInput in, ClassDefinition cd) { int fieldCount; try { // final position after portable is read finalPosition = in.readInt(); fieldCount = in.readInt(); } catch (IOException e) { throw new Haze...
java
public double getDouble(String key, double defaultValue) { addToDefaults(key, Double.toString(defaultValue)); String value = get(key); if (value == null) { return defaultValue; } else { return Double.valueOf(value); } }
java
private void restoreDescendantState() { FacesContext context = getFacesContext(); if (getChildCount() > 0) { for (UIComponent kid : getChildren()) { if (kid instanceof UIColumn) { restoreDescendantState(kid, context); } } ...
python
def find_font(font_name): """Return the font and a Boolean indicating if the match is exact.""" if font_name in STANDARD_FONT_NAMES: return font_name, True elif font_name in _registered_fonts: return font_name, _registered_fonts[font_name] NOT_FOUND = (None, False) try: # Tr...
python
def collection(name=None): """Render the collection page. It renders it either with a collection specific template (aka collection_{collection_name}.html) or with the default collection template (collection.html). """ if name is None: collection = Collection.query.get_or_404(1) else...
python
def get_build_report(self, project, build_id, type=None): """GetBuildReport. [Preview API] Gets a build report. :param str project: Project ID or project name :param int build_id: The ID of the build. :param str type: :rtype: :class:`<BuildReportMetadata> <azure.devops.v5...
python
def pulse(time, start, duration): """ Implements vensim's PULSE function In range [-inf, start) returns 0 In range [start, start + duration) returns 1 In range [start + duration, +inf] returns 0 """ t = time() return 1 if start <= t < start + duration else 0
java
public static int markRingAtomsAndBonds(IAtomContainer mol) { EdgeToBondMap bonds = EdgeToBondMap.withSpaceFor(mol); return markRingAtomsAndBonds(mol, GraphUtil.toAdjList(mol, bonds), bonds); }
python
def copy(self): """Returns a new :class:`~pyinter.Interval` object with the same bounds and values.""" return Interval(self._lower, self._lower_value, self._upper_value, self._upper)
java
protected boolean equalsNamespace(Node control, Node test) { String controlNS = control.getNamespaceURI(); String testNS = test.getNamespaceURI(); if (controlNS == null) { return testNS == null; } return controlNS.equals(testNS); }
python
def hacking_has_only_comments(physical_line, filename, lines, line_number): """Check for empty files with only comments H104 empty file with only comments """ if line_number == 1 and all(map(EMPTY_LINE_RE.match, lines)): return (0, "H104: File contains nothing but comments")
java
public void doTag() throws JspException { PageContext pageContext = getPageContext(); // Were any error messages specified? ActionMessages errors = null; try { errors = RequestUtils.getActionMessages(pageContext, Globals.ERROR_KEY); } catch (J...
java
public static void cleanup(final Logger log, final AutoCloseable... closeables) { for (AutoCloseable c : closeables) { if (c != null) { try { c.close(); } catch (Exception e) { if (log != null && log.isDebugEnabled()) { log.debug("Exception in closing " + c, e); } } } } }
java
protected void checkNewParentsInList(CmsObject userCms, List<CmsResource> resources) throws CmsException { Map<String, CmsResource> resourcesByPath = new HashMap<String, CmsResource>(); CmsObject rootCms = OpenCms.initCmsObject(m_adminCms); rootCms.getRequestContext().setCurrentProject(user...
java
public void openDialog(String dialogId, String contextType, List<CmsUUID> resources) { openDialog(dialogId, contextType, resources, null); }
java
public static BigDecimal validate(BigDecimal zahl, CurrencyUnit currency) { if (zahl.scale() == 0) { return zahl.setScale(currency.getDefaultFractionDigits(), RoundingMode.HALF_UP); } return zahl; }
java
private PorterDuffColorFilter createTintFilter(ColorStateList tint, PorterDuff.Mode tintMode) { if (tint == null || tintMode == null) { return null; } final int color = tint.getColorForState(getState(), Color.TRANSPARENT); return new PorterDuffColorFilter(color, tintMode); ...
java
private void overrideDeployerDetails(T overrider, Class overriderClass) { if (overrider instanceof DeployerOverrider) { try { Field deployerDetailsField = overriderClass.getDeclaredField("deployerDetails"); deployerDetailsField.setAccessible(true); Obj...
python
def upload(client, source_dir): """Upload listing files in source_dir. folder herachy.""" print('') print('upload store listings') print('---------------------') listings_folder = os.path.join(source_dir, 'listings') langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder)) for...
java
public Date getBaselineEstimatedFinish(int baselineNumber) { Object result = getCachedValue(selectField(TaskFieldLists.BASELINE_ESTIMATED_FINISHES, baselineNumber)); if (!(result instanceof Date)) { result = null; } return (Date) result; }
java
public Page<FieldValueList> list() { // [START ] // This example reads the result 100 rows per RPC call. If there's no need to limit the number, // simply omit the option. Page<FieldValueList> page = table.list(TableDataListOption.pageSize(100)); for (FieldValueList row : page.iterateAll()) { ...
java
public FunctionDeclaration createDeclaration( ImportStack importStack, Context context, Object object, Method method ) { StringBuilder signature = new StringBuilder(); Parameter[] parameters = method.getParameters(); List<ArgumentConverter> argumentConverters = new ArrayList<>(method.getParameterCo...
python
def _expectation(p, kern, feat, none1, none2, nghp=None): """ Compute the expectation: <K_{X, Z}>_p(X) - K_{.,.} :: Linear kernel :return: NxM """ with params_as_tensors_for(kern, feat): # use only active dimensions Z, Xmu = kern._slice(feat.Z, p.mu) return tf.m...
python
def is_directory_archive(path): """ Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it. SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive for an SFrame. Parameters ---------- ...
java
public static String getMessage(IOException e) { String s = e.getLocalizedMessage(); if (s != null) return s; s = e.getMessage(); if (s != null) return s; return e.toString(); }
python
def items(self): """D.items() -> list of D's (key, value) pairs, as 2-tuples""" return list(zip((self.scalars + self.sections), list(self.values())))
java
public java.util.List<String> getStagesAvailable() { if (stagesAvailable == null) { stagesAvailable = new com.amazonaws.internal.SdkInternalList<String>(); } return stagesAvailable; }
java
@SuppressWarnings("unchecked") @Override public EList<IfcDefinitionSelect> getRelatedDefinitions() { return (EList<IfcDefinitionSelect>) eGet(Ifc4Package.Literals.IFC_REL_DECLARES__RELATED_DEFINITIONS, true); }
java
public ElemTemplateElement appendChild(ElemTemplateElement newChild) { int type = ((ElemTemplateElement) newChild).getXSLToken(); switch (type) { case Constants.ELEMNAME_WHEN : case Constants.ELEMNAME_OTHERWISE : // TODO: Positional checking break; default : error(XSLTErro...
python
def transform_i_to_j(self, line: str) -> str: """ Transform instances of consonantal i to j :param line: :return: >>> print(VerseScanner().transform_i_to_j("iactātus")) jactātus >>> print(VerseScanner().transform_i_to_j("bracchia")) bracchia """ ...
java
public void stop() throws Exception { if (server != null) { server.setStopTimeout(100); server.stop(); server = null; } }
java
public static JBBPParser prepare(final String script, final JBBPBitOrder bitOrder) { return new JBBPParser(script, bitOrder, null, 0); }
python
def scanf_compile(format, collapseWhitespace=True): """ Translate the format into a regular expression For example: >>> format_re, casts = scanf_compile('%s - %d errors, %d warnings') >>> print format_re.pattern (\S+) \- ([+-]?\d+) errors, ([+-]?\d+) warnings Translated formats are cached ...
python
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]: """Generates a DFA matching the given pattern.""" # Capture the last sequence wildcard for every level of operation nesting on a stack # Used to add backtracking edges in case the "match" fails later last_wildcards ...
python
def _normalize_path(path): """Makes sure the path starts with a "/" """ if isinstance(path, FileInfo): path = path.path if len(path) == 0: return '/' if not path.startswith('/'): path = '/' + path return path
python
def _parse_alfred_vis(self, data): """ Converts a alfred-vis JSON object to a NetworkX Graph object which is then returned. Additionally checks for "source_vesion" to determine the batman-adv version. """ # initialize graph and list of aggregated nodes graph = sel...
java
public static JsonWebKey jsonWebKeyFromString(String jwkString) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jwkString, JsonWebKey.class); }
java
@Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(configId); sb.append(dm).append(errorCount); sb.append(dm).append(errorLog); sb.append(dm).append(errorName); sb.append(dm).append(lastAccessTime);...
python
def ramp_limits(network): """ Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- """ carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite', 'urani...
java
private void computePhi(final Vec doc, int[] indexMap, double[] phiCols, int K, final Vec gamma_d, final Vec ELogTheta_d, final Vec ExpELogTheta_d) { //φ^k_dn ∝ exp{E[logθdk]+E[logβk,wdn ]}, k ∈ {1, . . . ,K} /* * we have the exp versions of each, and exp(log(x)+log(y)) = x y * so ...
python
def besttype(x, encoding="utf-8", percentify=True): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only im...
python
def number(self) -> int: """Episode number. Unique for an anime and episode type, but not unique across episode types for the same anime. """ match = self._NUMBER_SUFFIX.search(self.epno) return int(match.group(1))
python
def delete(self, **kwargs): """ Deletes the document if it is saved in the collection. """ if self.is_valid: if '_id' in self._document: to_delete = self.find_one({'_id': self._id}) if to_delete: before = self.before_delete...
python
def nac(x, depth, name=None, reuse=None): """NAC as in https://arxiv.org/abs/1808.00508.""" with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse): x_shape = shape_list(x) w = tf.get_variable("w", [x_shape[-1], depth]) m = tf.get_variable("m", [x_shape[-1], depth]) w = tf.tanh(w) ...
python
def AB(self): ''' A list containing Points A and B. ''' try: return self._AB except AttributeError: pass self._AB = [self.A, self.B] return self._AB
python
def getblockhash(self, blocknum: int) -> str: '''get blockhash''' query = 'getblockhash' + '&height=' + str(blocknum) return cast(str, self.api_req(query))
java
public static int compareTo(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { return LexicographicalComparerHolder.BEST_COMPARER. compareTo(buffer1, offset1, length1, buffer2, offset2, length2); }
java
public void marshall(ExtendedS3DestinationConfiguration extendedS3DestinationConfiguration, ProtocolMarshaller protocolMarshaller) { if (extendedS3DestinationConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
python
def _make_gelf_dict(self, record): """Create a dictionary representing a Graylog GELF log from a python :class:`logging.LogRecord` :param record: :class:`logging.LogRecord` to create a Graylog GELF log from. :type record: logging.LogRecord :return: dictionary repres...