language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _parse_log_entry(entry_pb): """Special helper to parse ``LogEntry`` protobuf into a dictionary. The ``proto_payload`` field in ``LogEntry`` is of type ``Any``. This can be problematic if the type URL in the payload isn't in the ``google.protobuf`` registry. To help with parsing unregistered types, ...
java
public Observable<Page<SubnetInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<SubnetInner>>, Page<SubnetInner>>() { @Override public Page<SubnetInner> call(ServiceResponse<Page...
python
def _validate_duplicates(self): """ Ensure we're not creating a device that already exists Runs only when the DeviceConnector object is created, not when is updated """ # if connector is being created right now if not self.id: duplicates = [] self....
java
public int getWeight() { ProviderStatus status = getStatus(); if (status == ProviderStatus.WARMING_UP) { try { // 还处于预热时间中 Integer warmUpWeight = (Integer) getDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT); if (warmUpWeight != null) { ...
java
public boolean sequenceAndQualityLengthsMatch() { if (sequence == null && quality == null) { return true; } if ((sequence != null && quality == null) || (sequence == null && quality != null)) { return false; } return sequence.length() == quality.length(); }
java
public static QueryException fromThrowable(String message, Throwable cause) { return (cause instanceof QueryException && Objects.equals(message, cause.getMessage())) ? (QueryException) cause : new QueryException(message, cause); }
java
public void product(LongIntVector other) { // TODO: Add special case for LongIntDenseVector. for (int i=0; i<size; i++) { elements[i + start] *= other.get(i); } }
java
public static boolean currentUserHasRole(String... roles) { if (roles == null || roles.length == 0) return false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication.g...
java
@Override protected List<Pair<Integer, Integer>> doGenerateEdges() { long threshold = getConfiguration().getNumberOfEdges() * 4; long potentialEdges = getConfiguration().getNumberOfNodes() * (getConfiguration().getNumberOfNodes() - 1); if (threshold > potentialEdges) { return do...
python
def file_flags(self, _file_flags): """Set the new file flags attribute of the BFD file being processed.""" if not self._ptr: raise BfdException("BFD not initialized") return _bfd.set_file_flags(self._ptr, _file_flags)
python
def readline(self, size=-1): "Ignore the `size` since a complete line must be processed." while True: try: record = next(self.reader) except StopIteration: break # Ensure this is a valid record if checks.record_is_valid(rec...
python
def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data """ if len(self.lines) > 1: return self.lines.pop(0) tail = '' if len(self.lines): tail = self.lines.pop() try: ...
python
def get_output(self, assets_by_taxo, haz, rlzi=None): """ :param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index """ if isinstance(haz, numpy.ndarray): ...
java
public Pattern getPattern(String name) { String valString = get(name); Preconditions.checkNotNull(valString); return Pattern.compile(valString); }
java
final protected Collection common_values() { //TODO: make efficient ArrayList<Object> al = new ArrayList<Object>(); Enumeration vEnum = cache.getAllIds(); while (vEnum.hasMoreElements()) al.add(get(vEnum.nextElement())); return al; }
java
@Deprecated public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) { BasicDBObject ret = new BasicDBObject(); final String[] parts = str.split(","); for (String s : parts) { s = s.trim(); int dir...
python
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path ...
python
def concretize_write_addr(self, addr, strategies=None): """ Concretizes an address meant for writing. :param addr: An expression for the address. :param strategies: A list of concretization strategies (to override the default). :returns: ...
python
def cluster(self, linkageMethod="single"): """ Perform hierarchical clustering on training vectors using specified linkage method. Results can be obtained using getLinkageMatrix(), etc. @param linkageMethod (string) Linkage method for computing between-class dissimilarities. Valid options a...
python
def _get_regions(self): """Get the requested regions.""" if self._specs_in[_REGIONS_STR] == 'all': return [_get_all_objs_of_type( Region, getattr(self._obj_lib, 'regions', self._obj_lib) )] else: return [set(self._specs_in[_REGIONS_STR])]
python
def sagemaker_timestamp(): """Return a timestamp with millisecond precision.""" moment = time.time() moment_ms = repr(moment).split('.')[1][:3] return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment))
python
def detect_request_method(self): """ Analyze request config and find which request method will be used. Returns request method in upper case This method needs simetime when `process_config` method was not called yet. """ method = self.config['method'] ...
java
public void updateContent(List<CmsResourceTypeBean> types, List<String> selectedTypes) { clearList(); fillContent(types, selectedTypes); }
python
def hist(P, edges, **kwargs): r''' Plot histogram. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) autoscale = kwargs.pop( 'auto...
python
def suspend(rq, ctx, duration): "Suspends all workers." ctx.invoke( rq_cli.suspend, duration=duration, **shared_options(rq) )
python
def Page_addScriptToEvaluateOnLoad(self, scriptSource): """ Function path: Page.addScriptToEvaluateOnLoad Domain: Page Method name: addScriptToEvaluateOnLoad WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptSource' (type: string) -> No description ...
java
public ServiceFuture<Void> patchAsync(String jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(patchWithServiceResponseAsync(jobId, jobPatchParameter, jobPatchOptions), serviceCallback); }
python
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: """ Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from pa...
python
def tail(filename, number_of_bytes): """Returns the last number_of_bytes of filename""" with open(filename, "rb") as f: if os.stat(filename).st_size > number_of_bytes: f.seek(-number_of_bytes, 2) return f.read()
python
def send(cfg, **kwargs): """Send a text message, file, or directory""" for name, value in kwargs.items(): setattr(cfg, name, value) with cfg.timing.add("import", which="cmd_send"): from . import cmd_send return go(cmd_send.send, cfg)
java
protected void writeVerticalBand(BandData band, HSSFSheet templateSheet, HSSFSheet resultSheet) { String rangeName = band.getName(); CellReference[] crefs = getRangeContent(templateWorkbook, rangeName); Set<Integer> addedRowNumbers = new HashSet<>(); if (crefs != null) { ad...
java
@Override public boolean setProductCoefficient(IAtomContainer product, Double coefficient) { boolean result = products.setMultiplier(product, coefficient); return result; }
python
def getDevice(self, **kwargs): """Like get, but returns a Device instance (RTSPCameraDevice, etc.) """ filterchain = self.get(**kwargs) if not filterchain: return None # get filterchain init parameters that are compatible with RTSPCameraDevice input...
java
@JsonAnySetter public void setSupplementaryDataValue(String name, String value) { supplementaryData.put(name, value); }
java
final public Selector NullPredicate() throws ParseException { boolean not=false; Selector ans; ans = FieldRef(); jj_consume_token(IS); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NOT: jj_consume_token(NOT); not = true; break; ...
java
@Override public DescribeSecurityGroupsResult describeSecurityGroups(DescribeSecurityGroupsRequest request) { request = beforeClientExecution(request); return executeDescribeSecurityGroups(request); }
python
def from_timeseries(cls, timeSeries): """Create a new Matrix instance from a TimeSeries or MultiDimensionalTimeSeries :param TimeSeries timeSeries: The TimeSeries, which should be used to create a new Matrix. :return: A Matrix with the values of the timeSeries. Each row of ...
java
public static int showInternalOptionDialog(final Component parentComponent, final Object message, final String title, final int optionType, final int messageType, final Icon icon, final Object[] options, final Object initialValue) { return execute(new IntOptionPane() { ...
java
public final ValueWithPos<String> formatCommon(final ValueWithPos<String> pphoneNumber) { return valueWithPosDefaults( this.formatCommonWithPos(this.parsePhoneNumber(pphoneNumber), defaultCountryData), pphoneNumber); }
java
private void addMarkerAnnotation() { if (isLog(4)) { log("... adding marker annotation"); } AnnotationVisitor av = cv.visitAnnotation(ANNOTATION_ALREADY_ENHANCED_MARKER, true); if (av != null) { av.visitEnd(); } }
java
public ListVoiceConnectorsResult withVoiceConnectors(VoiceConnector... voiceConnectors) { if (this.voiceConnectors == null) { setVoiceConnectors(new java.util.ArrayList<VoiceConnector>(voiceConnectors.length)); } for (VoiceConnector ele : voiceConnectors) { this.voiceConn...
python
def _read_para_echo_response_signed(self, code, cbit, clen, *, desc, length, version): """Read HIP ECHO_RESPONSE_SIGNED parameter. Structure of HIP ECHO_RESPONSE_SIGNED parameter [RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 ...
python
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._monetary_account_id is not None: return False if self._card_id is not None: return False if self._amount_local is not None: ...
python
def register_gridfs_files(self, **kwargs): """ This function registers the files that will be saved in GridFS. kwargs is a dictionary mapping the key associated to the file (usually the extension) to the absolute path. By default, files are assumed to be in binary form, for formatted fil...
java
String getEnvVar( String key) { String envVal = System.getenv(key); return envVal != null ? envVal : ""; }
java
public ApiResponse<ApiSuccessResponse> subscribeTopicWithHttpInfo(SubscribeTopicData subscribeTopicData) throws ApiException { com.squareup.okhttp.Call call = subscribeTopicValidateBeforeCall(subscribeTopicData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); ...
java
private void doMacLockRequestWorkaround( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws LockFailedException, IOException { LockedObject lo; final int depth = getDepth( req ); int lockDuration = getTimeout( transaction, req ); if ( ...
python
def http_proxy(self, value): """ Sets http proxy setting. :Args: - value: The http proxy value. """ self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.httpProxy = value
java
@Benchmark public Class<?> benchmarkJavassist() { ProxyFactory proxyFactory = new ProxyFactory() { protected ClassLoader getClassLoader() { return newClassLoader(); } }; proxyFactory.setUseCache(false); proxyFactory.setUseWriteReplace(false); ...
java
public com.google.api.ads.admanager.axis.v201811.FieldPathElement[] getFieldPathElements() { return fieldPathElements; }
python
def set_keepalive(self, interval, callback): """ Turn on/off the callback keepalive. If ``interval`` seconds pass with no data read from or written to the socket, the callback will be executed and the timer will be reset. """ self.__keepalive_interval = interval ...
python
def compute(a, b, axis): """ Finds optimal displacements localized along an axis """ delta = [] for aa, bb in zip(rollaxis(a, axis, 0), rollaxis(b, axis, 0)): delta.append(Displacement.compute(aa, bb).delta) return LocalDisplacement(delta, axis=axis)
java
public void marshall(CrlConfiguration crlConfiguration, ProtocolMarshaller protocolMarshaller) { if (crlConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(crlConfiguration.getEnabled(), ...
python
def __getOrganizations(self, web): """Scrap the number of organizations from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ orgsElements = web.find_all("a", {"class": "avatar-group-item"}) self.organizations = len(orgsElements)
python
def pairwise_extract(features, groups, edges, weight_func, use_orig_distr, group_ids, num_groups, num_links, non_symmetric, return_networkx_graph, out_weights_path): """ Core function to compute the pair-wise histogram distance between all ROIs. Parameters ----...
java
public AddMenuVisibility getAddMenuVisibility(CmsUUID elementViewId, AddMenuType menuType) { if (isAddDisabled()) { return AddMenuVisibility.disabled; } if (elementViewId.equals(getElementView())) { if (isCreateDisabled() && (menuType == AddMenuType.ade)) { ...
java
public Collection<String> getAllPaths() throws Exception { final String path = "/"; while (true) { Stat stat = client.checkExists().forPath(path); if (stat == null) { return Collections.emptyList(); } else { try { return client.getChildren().forPath(path); } catch (KeeperException.NoNode...
python
def create_task(client, list_id, title, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None): ''' Creates a task in the given list See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter information ''' _check...
python
def store(self, value, context=None): """ Converts the value to one that is safe to store on a record within the record values dictionary :param value | <variant> :return <variant> """ if isinstance(value, (str, unicode)): value = self.value...
java
static final Mem _ptr_build_abs(long target, long disp, SEGMENT segmentPrefix, int ptrSize) { return new Mem(target, disp, segmentPrefix, ptrSize); }
java
public static GenericsInfo create(final Class<?> type, final Class<?>... ignoreClasses) { GenericsInfo descriptor = ignoreClasses.length > 0 ? GenericInfoUtils.create(type, ignoreClasses) : CACHE.get(type); if (descriptor == null) { LOCK.lock(); try { ...
java
public ResultList<Video> getSeasonVideos(int tvID, int seasonNumber, String language) throws MovieDbException { return tmdbSeasons.getSeasonVideos(tvID, seasonNumber, language); }
python
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True): r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters i...
java
protected <T> JsonObjectBase buildSuccess(String key, T value) { return JsonObjectUtils.buildObjectSuccess(key, value); }
python
def url_decode(url): """ URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLENCODED string """ return re.compile('%([0-9a-fA-F]{2})', re.M).sub(lambda m: chr(int(m.group(1), 16)), url)
python
def find_tracked_words(self, tokens): """ Finds word-ranges all of phrases in tokens stored in TokenTrie :param tokens: Sequence of tokens to find phrases in :type tokens: list of str :return: List of Tokens found in tokens """ tracked_words = [] for i i...
java
public OvhOrder telephony_billingAccount_line_POST(String billingAccount, String brand, Boolean[] displayUniversalDirectories, Long[] extraSimultaneousLines, String mondialRelayId, String[] offers, Long[] ownerContactIds, Long quantity, Boolean retractation, Long shippingContactId, OvhLineTypeEnum[] types, String[] zon...
java
public Reflector create(Object... args) throws ReflectException { Class<?>[] types = getTypes(args); try { Constructor<?> constructor = type().getDeclaredConstructor(types); return with(constructor, args); } catch (NoSuchMethodException e) { for (Constructor<...
java
public PixelFormat[] getSupportedPixelFormats() { IntPointer formatsPointer = avCodec.pix_fmts(); if (getType() != MediaType.VIDEO || formatsPointer == null) return null; List<PixelFormat> pixelFormats = new ArrayList<PixelFormat>(); int format; int index = 0; while ((format = formatsPointer.get(index...
python
def post_mortem(trace_back=None, exc_info=None): """ Breaks on a traceback and send all execution information to the debugger client. If the interpreter is handling an exception at this traceback, exception information is sent to _line_tracer() which will transmit it to the debugging client. Call...
python
def opensignals_kwargs(obj): """ ----- Brief ----- Function used to automatically apply the OpenSignals graphical style to the toolbar of Bokeh grid plots. ----------- Description ----------- Bokeh grid plots have numerous options in order to personalise the visual aspect and functi...
java
private Set<String> getGroupsByMembership(DirContext context, String callerDn) { String memberOfAttribute = idStoreDefinition.getGroupMemberOfAttribute(); String groupNameAttribute = idStoreDefinition.getGroupNameAttribute(); Attributes attrs; Set<String> groupDns = new HashSet<String>()...
java
public DataSource<String> readTextFile(String filePath) { Validate.notNull(filePath, "The file path may not be null."); return new DataSource<String>(this, new TextInputFormat(new Path(filePath)), BasicTypeInfo.STRING_TYPE_INFO ); }
java
public static Type get(final long _id) throws CacheReloadException { final Cache<Long, Type> cache = InfinispanCache.get().<Long, Type>getCache(Type.IDCACHE); if (!cache.containsKey(_id)) { Type.getTypeFromDB(Type.SQL_ID, _id); } Type ret = cache.get(_id); ...
java
public static double atan2(double y, double x) { if (x != x || y != y) { return Double.NaN; } if (y == 0) { final double result = x * y; final double invx = 1d / x; final double invy = 1d / y; if (invx == 0) { // X is infinite ...
java
public static Vec updateDomain(Vec source, String[] toDomain) { CategoricalWrappedVec tv = makeTransientVec(source.domain(), toDomain); new RemapTask(tv).doAll(source); source.setDomain(tv.domain()); DKV.put(source); return source; }
java
public EEnum getIfcCondenserTypeEnum() { if (ifcCondenserTypeEnumEEnum == null) { ifcCondenserTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(797); } return ifcCondenserTypeEnumEEnum; }
python
def properties(lines): """Parse properties block Returns: dict: {property_type: (atom_index, value)} """ results = {} for i, line in enumerate(lines): type_ = line[3:6] if type_ not in ["CHG", "RAD", "ISO"]: continue # Other properties are not supported yet ...
java
protected <T> CharSequence createSQLExpress(final EntityInfo<T> info, final Map<Class, String> joinTabalis) { CharSequence sb0 = this.column == null || this.column.isEmpty() || this.column.charAt(0) == '#' || info == null ? null : createElementSQLExpress(info, joinTabalis == null ? null : joinTaba...
python
def parse_resource(self, response): """Assuming this response is a resource, use the deserialization callback to parse it. If body is empty, assuming no resource to return. """ self._raise_if_bad_http_status_and_method(response) if not self._is_empty(response): self.r...
python
def rpc_get_block_from_consensus( self, consensus_hash, **con_info ): """ Given the consensus hash, find the block number (or None) """ if not check_string(consensus_hash, min_length=LENGTHS['consensus_hash']*2, max_length=LENGTHS['consensus_hash']*2, pattern=OP_CONSENSUS_HASH_PATTERN): ...
python
def _get_checker(self, user): """ Return a ForumPermissionChecker instance for the given user. """ user_perm_checkers_cache_key = user.id if not user.is_anonymous else 'anonymous' if user_perm_checkers_cache_key in self._user_perm_checkers_cache: return self._user_perm_checkers_cach...
java
public static String getAtonType(BigInteger ts) { if (ts == null) return null; else return getAtonType(ts.intValue()); }
python
def weld_mean(array, weld_type): """Returns the mean of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation....
java
public static base_responses unset(nitro_service client, String selectorname[], String args[]) throws Exception { base_responses result = null; if (selectorname != null && selectorname.length > 0) { nslimitselector unsetresources[] = new nslimitselector[selectorname.length]; for (int i=0;i<selectorname.length...
java
@BetaApi public final HttpHealthCheck2 getHttpHealthCheck( ProjectGlobalHttpHealthCheckName httpHealthCheck) { GetHttpHealthCheckHttpRequest request = GetHttpHealthCheckHttpRequest.newBuilder() .setHttpHealthCheck(httpHealthCheck == null ? null : httpHealthCheck.toString()) ...
python
def _parse_pubkey(stream, packet_type='pubkey'): """See https://tools.ietf.org/html/rfc4880#section-5.5 for details.""" p = {'type': packet_type} packet = io.BytesIO() with stream.capture(packet): p['version'] = stream.readfmt('B') p['created'] = stream.readfmt('>L') p['algo'] = ...
python
def select_delay_factor(self, delay_factor): """ Choose the greater of delay_factor or self.global_delay_factor (default). In fast_cli choose the lesser of delay_factor of self.global_delay_factor. :param delay_factor: See __init__: global_delay_factor :type delay_factor: int ...
java
@Override public Map<String, Object> getQueryParameters() { HashMap<String, Object> params = new HashMap<String, Object>(); if (this.filter!=null) { params.put("filter", this.filter.toString()); } if (this.count!=null) { params.put("count", this.count.toString...
python
def _makepretty(printout, stack): ''' Pretty print the stack trace and environment information for debugging those hard to reproduce user problems. :) ''' printout.write('======== Salt Debug Stack Trace =========\n') traceback.print_stack(stack, file=printout) printout.write('==============...
java
@Override public DeleteTaskResult deleteTask(DeleteTaskRequest request) { request = beforeClientExecution(request); return executeDeleteTask(request); }
java
protected boolean isOperationOnFolder() { Iterator<String> i = getResourceList().iterator(); while (i.hasNext()) { String resName = i.next(); try { CmsResource curRes = getCms().readResource(resName, CmsResourceFilter.ALL); if (curRes.isFolder()) ...
python
def p_sens_level(self, p): 'senslist : AT levelsig' p[0] = SensList((p[2],), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
python
def is_full(self): """Return whether the activity is full.""" capacity = self.get_true_capacity() if capacity != -1: num_signed_up = self.eighthsignup_set.count() return num_signed_up >= capacity return False
python
def average(var, key, N): '''average over N points''' global average_data if not key in average_data: average_data[key] = [var]*N return var average_data[key].pop(0) average_data[key].append(var) return sum(average_data[key])/N
java
public void init(BaseMessageFilter messageFilter, Application application, String strProcessClassName, Map<String, Object> properties) { m_application = application; m_strProcessClassName = strProcessClassName; m_properties = properties; super.init(null, messageFilter); }
java
public Iterable<GHRepository> resolve(Predicate<GitHubServerConfig> predicate) { return from(GitHubPlugin.configuration().findGithubConfig(and(withHost(host), predicate))) .transform(toGHRepository(this)) .filter(notNull()); }
java
protected void appendSARLSpecificationVersion(GenerationContext context, XtendTypeDeclaration source, JvmDeclaredType target) { addAnnotationSafe(target, SarlSpecification.class, SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING); }
java
public static void v(String s, Throwable t) { log(Level.FINEST, s, t); }
java
public void updateModulesFromUpdateBean() throws Exception { // read here how the list of modules to be installed is passed from the setup bean to the // setup thread, and finally to the shell process that executes the setup script: // 1) the list with the package names of the modules to be ins...