language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private static boolean isAncestor(ClassLoader p, ClassLoader cl) { ClassLoader acl = cl; do { acl = acl.getParent(); if (p == acl) { return true; } } while (acl != null); return false; }
java
private Boolean toBoolean(Object value) { if (value == null) { return null; } else if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { return Boolean.parseBoolean((String) value); } else if (value instanceof Short) { return (Short) value != 0; } else if (v...
python
def rock(cls, data, eps, number_clusters, threshold=0.5, ccore=False): """ Constructor of the ROCK cluster analysis algorithm :param eps: Connectivity radius (similarity threshold), points are neighbors if distance between them is less than connectivity radius :param number_clusters: De...
java
public static final void textureFit(Shape shape, final Image image, final float scaleX, final float scaleY) { if (!validFill(shape)) { return; } float points[] = shape.getPoints(); Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); ...
python
def _aespad(data): """ipmi demands a certain pad scheme, per table 13-20 AES-CBC encrypted payload fields. """ currlen = len(data) + 1 # need to count the pad length field as well neededpad = currlen % 16 if neededpad: # if it happens to be zero, hurray, but otherwise invert the # sens...
python
def get_languages(self): """ Get the list of languages we need to start servers and create clients for. """ languages = ['python'] all_options = CONF.options(self.CONF_SECTION) for option in all_options: if option in [l.lower() for l in LSP_LANGUAGES]:...
python
def prune_node(self, node, remove_backrefs=False): """ remove node `node` from the network (including any edges that may have been pointing at `node`). """ if not remove_backrefs: for fro, connections in self.edges.items(): if node in self.edges[fro]: ...
python
def find_module(self, fullname, path=None): """Searches for a Coconut file of the given name and compiles it.""" basepaths = [""] + list(sys.path) if fullname.startswith("."): if path is None: # we can't do a relative import if there's no package path ...
python
def _validation_error(prop, prop_type, prop_value, expected): """ Default validation for updated properties """ if prop_type is None: attrib = 'value' assigned = prop_value else: attrib = 'type' assigned = prop_type raise ValidationError( 'Invalid property {attr...
java
public void setPropertyValue(String propertyName, Object value) throws BeansException { if (PropertyAccessorUtils.isIndexedProperty(propertyName)) { setIndexedPropertyValue(propertyName, value); } else { setSimplePropertyValue(propertyName, value); } }
java
public void subtract(R1 relationships) { if (null == base) { throw new AssertionError(""); } for (int i = 0; i < base.length; i++) { if (null == base[i]) { continue; } final IConceptSet set = data[i] = new SparseConceptHashS...
java
static ClientDatanodeProtocol createClientDatanodeProtocolProxy ( DatanodeInfo datanodeid, Configuration conf) throws IOException { InetSocketAddress addr = NetUtils.createSocketAddr( datanodeid.getHost() + ":" + datanodeid.getIpcPort()); if (ClientDatanodeProtocol.LOG.isDebugEnabled()) { Clie...
java
@Override public String getUserFacingMessage() { final StringBuilder bldr = new StringBuilder(); bldr.append(getMessage()); bldr.append(" for "); bldr.append(getName()); bldr.append("\n\treason: "); final SQLException cause = (SQLException) getCause(); final...
python
def _ParseMRUListEntryValue( self, parser_mediator, registry_key, entry_index, entry_letter, codepage='cp1252', **kwargs): """Parses the MRUList entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs...
python
def guest_register(self, userid, meta, net_set): """DB operation for migrate vm from another z/VM host in same SSI :param userid: (str) the userid of the vm to be relocated or tested :param meta: (str) the metadata of the vm to be relocated or tested :param net_set: (str) the net_set of ...
java
public void clear() { _sample.clear(); _count = 0; _max = null; _min = null; _sum = BigDecimal.ZERO; _m = -1; _s = 0; }
java
public Subscription register(final Object mBean, final String name){ try { if (mbeanSupport.get()) { final ObjectName objectName = new ObjectName(name); server.registerMBean(mBean, objectName); return new Subscription() { @Override ...
python
def status_counter(self): """ Returns a :class:`Counter` object that counts the number of tasks with given status (use the string representation of the status as key). """ # Count the number of tasks with given status in each work. counter = self[0].status_counter ...
java
@Override public ApiFuture<Table> modifyFamiliesAsync(ModifyColumnFamiliesRequest request) { com.google.bigtable.admin.v2.ModifyColumnFamiliesRequest modifyColumnRequestProto = request.toProto(instanceName.getProjectId(), instanceName.getInstanceId()); return ApiFutureUtil.transformAndAdapt(delegate....
python
def pdf(self, phi): r""" Evaluate the flow PDF `dN/d\phi`. :param array-like phi: Azimuthal angles. :returns: The flow PDF evaluated at ``phi``. """ if self._n is None: pdf = np.empty_like(phi) pdf.fill(.5/np.pi) return pdf ...
python
def _verify_app_source_dir(src_dir, mode, enforce=True): """Performs syntax and lint checks on the app source. Precondition: the dxapp.json file exists and can be parsed. """ temp_dir = tempfile.mkdtemp(prefix='dx-build_tmp') try: _verify_app_source_dir_impl(src_dir, temp_dir, mode, enforce...
java
@Nullable public static com.google.rpc.Status fromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { StatusException e = (StatusException) cause; return fromStatusAndTrailers(e.getStatus(), e.getTrailers()); ...
java
@Override public SetEndpointAttributesResult setEndpointAttributes(SetEndpointAttributesRequest request) { request = beforeClientExecution(request); return executeSetEndpointAttributes(request); }
java
public ServiceCall<CreateEventResponse> createEvent(CreateEventOptions createEventOptions) { Validator.notNull(createEventOptions, "createEventOptions cannot be null"); String[] pathSegments = { "v1/events" }; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSe...
python
def _gtu32(ins): """ Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 32 bit unsigned version """ op1, op2 = tuple(ins.quad[2:]) rev = op1[0] != 't' and not is_int(op1) and op2[0] == 't...
java
public com.google.api.ads.admanager.axis.v201811.VideoRedirectAsset getMezzanineFile() { return mezzanineFile; }
java
public static int hash(ByteBuffer buf, int seed) { // save byte order for later restoration ByteOrder byteOrder = buf.order(); buf.order(ByteOrder.LITTLE_ENDIAN); int m = 0x5bd1e995; int r = 24; int h = seed ^ buf.remaining(); while (buf.remaining() >= 4) { int...
python
def check_captcha(self, captcha, value, id=None): """ http://api.yandex.ru/cleanweb/doc/dg/concepts/check-captcha.xml""" payload = {'captcha': captcha, 'value': value, 'id': id} r = self.request('get', 'http://cleanweb-api.yandex.ru/1.0/check-captcha', param...
java
public Metadata[] readMetadata(StreamInfo streamInfo) throws IOException { if (streamInfo.isLast()) return new Metadata[0]; ArrayList<Metadata> metadataList = new ArrayList<Metadata>(); Metadata metadata; do { metadata = readNextMetadata(); metadataList.add(metada...
python
def main(): """ Starts the Application. :return: Definition success. :rtype: bool """ args = get_command_line_arguments() return build_toc_tree(args.title, args.input, args.output, args.content_directory)
java
public void marshall(GetIntegrationResponsesRequest getIntegrationResponsesRequest, ProtocolMarshaller protocolMarshaller) { if (getIntegrationResponsesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
python
def main(relation_name=None): """ This is the main entry point for the reactive framework. It calls :func:`~bus.discover` to find and load all reactive handlers (e.g., :func:`@when <decorators.when>` decorated blocks), and then :func:`~bus.dispatch` to trigger handlers until the queue settles out. ...
python
def disconnect(self, code): """Called when WebSocket connection is closed.""" Subscriber.objects.filter(session_id=self.session_id).delete()
java
private void parseMarkupdecl() throws Exception { char[] saved = null; boolean savedPE = expandPE; // prevent "<%foo;" and ensures saved entity is right require('<'); unread('<'); expandPE = false; if (tryRead("<!ELEMENT")) { saved = readBuffer; ...
python
def _prepare_record(self, group): """ compute record dtype and parents dict for this group Parameters ---------- group : dict MDF group dict Returns ------- parents, dtypes : dict, numpy.dtype mapping of channels to records fields, record...
java
public static <T> T getFirst(T[] array, T defaultValue) { return getElementAt(array, 0, defaultValue); }
java
public ArrayList getBlankSignatureNames() { getSignatureNames(); ArrayList sigs = new ArrayList(); for (Iterator it = fields.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); Item item = (Item)entry.getValue(); PdfDictionary merge...
java
public EList<PPORG> getRG() { if (rg == null) { rg = new EObjectContainmentEList.Resolving<PPORG>(PPORG.class, this, AfplibPackage.PPO__RG); } return rg; }
java
public static String joinByComma( List<String> items ) { StringBuilder sb = new StringBuilder(); for( String item : items ) { sb.append(",").append(item); } if (sb.length() == 0) { return ""; } return sb.substring(1); }
python
def _get_index(self): """ Get the point's index. This must return an ``int``. Subclasses may override this method. """ contour = self.contour if contour is None: return None return contour.points.index(self)
python
def publishToMyself(self, roomId, name, data): """ Publish to only myself """ self.publishToRoom(roomId, name, data, [self])
java
public String build(ServiceInstance<?> serviceInstance) { return build(serviceInstance, Maps.<String, Object>newHashMap()); }
python
def _build(self, items, chunk_size=10000): """Build the output, in chunks. :return: Number of items processed :rtype: int """ _log.debug("_build, chunk_size={:d}".format(chunk_size)) n, i = 0, 0 for i, item in enumerate(items): if i == 0: ...
java
private Set<Cookie> doDecode(String header) { List<String> names = new ArrayList<String>(8); List<String> values = new ArrayList<String>(8); extractKeyValuePairs(header, names, values); if (names.isEmpty()) { return Collections.emptySet(); } int i; i...
python
def coerce_indexer_dtype(indexer, categories): """ coerce the indexer input array to the smallest dtype possible """ length = len(categories) if length < _int8_max: return ensure_int8(indexer) elif length < _int16_max: return ensure_int16(indexer) elif length < _int32_max: re...
java
@Override public AbstractMessage copy() { ObjectMessageImpl clone = new ObjectMessageImpl(); copyCommonFields(clone); clone.body = this.body; return clone; }
java
public static int countUniqueParameters(List<ParameterSpace> allLeaves) { List<ParameterSpace> unique = getUniqueObjects(allLeaves); int count = 0; for (ParameterSpace ps : unique) { if (!ps.isLeaf()) { throw new IllegalStateException("Method should only be used with ...
python
def _index_list_of_values(d, k): """Returns d[k] or [d[k]] if the value is not a list""" v = d[k] if isinstance(v, list): return v return [v]
java
public StorageBatchResult<Blob> update(BlobInfo blobInfo, BlobTargetOption... options) { StorageBatchResult<Blob> result = new StorageBatchResult<>(); RpcBatch.Callback<StorageObject> callback = createUpdateCallback(this.options, result); Map<StorageRpc.Option, ?> optionMap = StorageImpl.optionMap(blobInfo,...
python
def append(self, node): """ Append (set) the document root. @param node: A root L{Element} or name used to build the document root element. @type node: (L{Element}|str|None) """ if isinstance(node, basestring): self.__root = Element(node) ...
python
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='', html_message='', context=None, scheduled_time=None, headers=None, template=None, priority=None, render_on_delivery=False, commit=True, backend=''): """ Creates an email from supplied keyword arguments...
java
public void texture(Shape shape, Image image, ShapeFill fill) { texture(shape, image, 0.01f, 0.01f, fill); }
java
private static HashMap<String, String> getGroupDefinitions(Element e) { HashMap<String, String> groups = new HashMap<String, String>(); Elements children = e.getChildElements(); for (int i = 0; i < children.size(); i++) { Element child = children.get(i); if (child.getQual...
python
def _get_audio_duration_seconds(self, audio_abs_path): """ Parameters ---------- audio_abs_path : str Returns ------- total_seconds : int """ HHMMSS_duration = subprocess.check_output( ("""sox --i {} | grep "{}" | awk -F " : " '{{print...
python
def prepare_gold(ctx, annotations, gout): """Prepare bc-evaluate gold file from annotations supplied by CHEMDNER.""" click.echo('chemdataextractor.chemdner.prepare_gold') for line in annotations: pmid, ta, start, end, text, category = line.strip().split('\t') gout.write('%s\t%s:%s:%s\n' % (p...
python
def get_msg(self): """This method is used to prepare the preamble text to display to the user in non-batch mode. If your policy sets self.distro that text will be substituted accordingly. You can also override this method to do something more complicated.""" width = 72 _m...
python
def list_multipart_uploads(self, key_marker='', upload_id_marker='', headers=None): """ List multipart upload objects within a bucket. This returns an instance of an MultiPartUploadListResultSet that automatically handles all...
java
public AbstractPrintQuery addAttributeSet(final AttributeSet _set) throws EFapsException { final String key = "linkfrom[" + _set.getName() + "#" + _set.getAttributeName() + "]"; final OneSelect oneselect = new OneSelect(this, key); this.allSelects.add(oneselect); this.attr2On...
python
def p_statement_plot_attr(p): """ statement : PLOT attr_list expr COMMA expr """ p[0] = make_sentence('PLOT', make_typecast(TYPE.ubyte, p[3], p.lineno(4)), make_typecast(TYPE.ubyte, p[5], p.lineno(4)), p[2])
java
public static Object readPrimitive(Class<?> clazz, String value) throws Exception { if (clazz == String.class) { return value; } else if (clazz == Long.class) { return Long.parseLong(value); } else if (clazz == Integer.class) { return Integer.parseInt(value); ...
python
def rerunTask(self, *args, **kwargs): """ Rerun a Resolved Task This method _reruns_ a previously resolved task, even if it was _completed_. This is useful if your task completes unsuccessfully, and you just want to run it from scratch again. This will also reset the num...
java
public static long readLong(ByteBuffer buf) { byte len=buf.get(); if(len == 0) return 0; return makeLong(buf, len); }
python
def verifyJWT(self, token): """ 验证token @param token str unicode: 请求生成的token串 >> 1. 验证并拆分token为header、payload、signature, 分别解码验证; >> 2. 验证header >> 3. payload一致性验证后, 验证过期时间; >> 4. 根据header、payload用密钥签名对比请求的signature; """ logging.debug("verify token: {0}".fo...
python
def logging_active_formatter(self, value): """ Setter for **self.__logging_active_formatter** attribute. :param value: Attribute value. :type value: unicode or QString """ if value is not None: assert type(value) in ( unicode, QString), "'{0}...
java
public static String readToString(InputStream inputStream, Charset charset) throws IOException { return new String(FileCopyUtils.copyToByteArray(inputStream), charset); }
java
public final EntityType updateEntityType(EntityType entityType, String languageCode) { UpdateEntityTypeRequest request = UpdateEntityTypeRequest.newBuilder() .setEntityType(entityType) .setLanguageCode(languageCode) .build(); return updateEntityType(request); }
java
public void field2in(Object o, String field, Object to, String to_in) { controller.mapInField(o, field, to, to_in); }
java
public void connect(String controllerHost, int controllerPort, String username, char[] password, String clientBindAddress) { connect("remote+http", controllerHost, controllerPort, username, password, clientBindAddress); }
python
def colors_to_dict(colors, img): """Convert list of colors to pywal format.""" return { "wallpaper": img, "alpha": util.Color.alpha_num, "special": { "background": colors[0], "foreground": colors[15], "cursor": colors[15] }, "colors":...
java
public static boolean hasAnnotation(CtField field, String annotationName) { FieldInfo info = field.getFieldInfo(); AnnotationsAttribute ainfo = (AnnotationsAttribute) info.getAttribute(AnnotationsAttribute.invisibleTag); AnnotationsAttribute ainfo2 = (AnnotationsAttribute) ...
python
def _entity_to_region_map(self): """ A dict whose keys are the UUIDs (or just IDs, in some cases) of entities, and whose values are the `(rx, ry)` coordinates in which that entity can be found. This can be used to easily locate particular entities inside the world. """ ...
java
private TimeWindow mergeSessionWindows(TimeWindow oldWindow, TimeWindow newWindow) { if (oldWindow.intersects(newWindow)) { return oldWindow.cover(newWindow); } return newWindow; }
python
def _attach_endpoints(self): """Dynamically attach endpoint callables to this client""" for name, endpoint in inspect.getmembers(self): if inspect.isclass(endpoint) and issubclass(endpoint, self._Endpoint) and (endpoint is not self._Endpoint): endpoint_instance = endpoint(sel...
java
public static BoBHash fromCid(String cid) { String hashType = cid.substring(0, cid.indexOf("+")); String hash = cid.substring(cid.indexOf("+") + 1, cid.indexOf("@bob.xmpp.org")); return new BoBHash(hash, hashType); }
java
public static String[] getDevicesForPattern(final String deviceNamePattern) throws DevFailed { String[] devices; // is p a device name or a device name pattern ? if (!deviceNamePattern.contains("*")) { // p is a pure device name devices = new String[1]; device...
python
def getTlvProperties(cardConnection, featureList=None, controlCode=None): """ return the GET_TLV_PROPERTIES structure @param cardConnection: L{CardConnection} object @param featureList: feature list as returned by L{getFeatureRequest()} @param controlCode: control code for L{FEATURE_GET_TLV_PROPERTIES}...
java
public UntagResourceRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new java.util.ArrayList<String>(tagKeys.length)); } for (String ele : tagKeys) { this.tagKeys.add(ele); } return this; }
java
@Deprecated public C expectNever(Threads threadMatcher) { return expect(SqlQueries.noneQueries().threads(threadMatcher)); }
python
def format_listeners(elb_settings=None, env='dev', region='us-east-1'): """Format ELB Listeners into standard list. Args: elb_settings (dict): ELB settings including ELB Listeners to add, e.g.:: # old { "certificate": null, ...
java
@Override public int doUpdate(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int result) { LOG.debug("SQL:{} executed. Count:{} items.", sqlContext.getSqlName(), result); return result; }
java
public void marshall(RebootInstanceRequest rebootInstanceRequest, ProtocolMarshaller protocolMarshaller) { if (rebootInstanceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(rebootInstanceRe...
python
def _set_num_samples_collected(self, v, load=False): """ Setter method for num_samples_collected, mapped from YANG variable /mpls_state/lsp/auto_bandwidth/num_samples_collected (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_num_samples_collected is considered a...
java
public static Set<String> getIssueGroups(Collection<String> issueTypes, Map<String, Set<String>> groupingSpecification) { Set<String> groups = new HashSet<>(); for (String issueType : issueTypes) { for (Map.Entry<String, Set<String>> entry : groupingSpecification.entrySet()) { ...
python
def _make_blocks(records): # @NoSelf ''' Organizes the physical records into blocks in a list by placing consecutive physical records into a single block, so lesser VXRs will be created. [[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...] Parameters: ...
java
@Override public double getLearningRate(int iterCount, int i) { // We use the learning rate suggested in Leon Bottou's (2012) SGD Tricks paper. // // \gamma_t = \frac{\gamma_0}{(1 + \gamma_0 \lambda t)^p} // // For SGD p = 1.0, for ASGD p = 0.75 if (prm.power == 1.0)...
java
public static void map(int flags, int theme) { if (theme > 0) { _THEMES_MAP.put(flags & _THEME_MASK, theme); } else { final int i = _THEMES_MAP.indexOfKey(flags & _THEME_MASK); if (i > 0) { _THEMES_MAP.removeAt(i); } } }
python
def make_sentence_with_start(self, beginning, strict=True, **kwargs): """ Tries making a sentence that begins with `beginning` string, which should be a string of one to `self.state` words known to exist in the corpus. If strict == True, then markovify will draw its init...
python
def prompt(prompt_string, default=None, secret=False, boolean=False, bool_type=None): """ Prompt user for a string, with a default value * secret converts to password prompt * boolean converts return value to boolean, checking for starting with a Y """ if boolean or bool_type in BOOLEAN_DEFAULT...
python
def Reposition(self): """Reposition the checkbox""" rect = self.GetFieldRect(1) self.safemode_staticbmp.SetPosition((rect.x, rect.y)) self.size_changed = False
java
@Override public void start(StartContext context) throws StartException { Set<KeytabService> services = keytabServices.getValue(); hostServiceMap = new HashMap<String, KeytabService>(services.size()); // Assume at least one per service. /* * Iterate the services and find the first ...
python
def explicit_line_join(logical_line, tokens): r"""Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parenthe...
java
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TypesPackage.JVM_TYPE_ANNOTATION_VALUE__VALUES: return ((InternalEList<?>)getValues()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, feat...
python
def mtf_transformer_lm_baseline(): """Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams """ hparams = mtf_transformer_paper_lm(-1) hparams...
python
def get_last_thread(self): """ Return the last modified thread """ cache_key = '_get_last_thread_cache' if not hasattr(self, cache_key): item = None res = self.thread_set.filter(visible=True).order_by('-modified')[0:1] if len(res)>0: ...
python
def _check_portname(name): ''' Check if portname is valid and whether or not the directory exists in the ports tree. ''' if not isinstance(name, string_types) or '/' not in name: raise SaltInvocationError( 'Invalid port name \'{0}\' (category required)'.format(name) ) ...
python
def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""" if writer is None: writer = ArrayWriter() if encoding is None: encoding = {} variables, attrs = conventions....
java
@Override public void register(CareWebShell shell, ElementBase owner, boolean register) { if (register) { shell.registerHelpResource(this); } }
java
private void getStrings(HashSet<String> strHashSet, SearchCondition searchCondition, String searchConditionString, String prefixString, TreeMap<Character, MDAGNode> transitionTreeMap) { //Traverse all the valid _transition paths beginning from each _transition in transitionTreeMap, inserting the //c...
python
def _BinsToQuery(self, bins, column_name): """Builds an SQL query part to fetch counts corresponding to given bins.""" result = [] # With the current StatsHistogram implementation the last bin simply # takes all the values that are greater than range_max_value of # the one-before-the-last bin. range...
java
public Observable<ServiceResponse<Page<FileServerInner>>> listByWorkspaceNextWithServiceResponseAsync(final String nextPageLink) { return listByWorkspaceNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<FileServerInner>>, Observable<ServiceResponse<Page<FileServerInner>>>>(...