language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setFormatsByArgumentIndex(Format[] newFormats) { if (msgPattern.hasNamedArguments()) { throw new IllegalArgumentException( "This method is not available in MessageFormat objects " + "that use alphanumeric argument names."); } for (i...
python
def Unpack(self, msg): """Unpacks the current Any message into specified message.""" descriptor = msg.DESCRIPTOR if not self.Is(descriptor): return False msg.ParseFromString(self.value) return True
java
private boolean execute(boolean readResponse) throws IOException { try { httpEngine.sendRequest(); route = httpEngine.getRoute(); handshake = httpEngine.getConnection() != null ? httpEngine.getConnection().getHandshake() : null; if (readResponse) { httpEngine.read...
java
public NfsMkdirRequest makeMkdirRequest(NfsSetAttributes attributes) throws IOException { return getNfs().makeMkdirRequest(getParentFile().getFileHandle(), getName(), attributes); }
java
@Override public void close() throws IOException { RootMetricContext.get().removeNotificationTarget(this.notificationTargetUUID); RootMetricContext.get().removeReporter(this); }
python
def smartDumpDictHdf5(RV,o): """ Dump a dictionary where each page is a list or an array or still a dictionary (in this case, it iterates)""" for key in list(RV.keys()): if type(RV[key])==dict: g = o.create_group(key) smartDumpDictHdf5(RV[key],g) else: o.creat...
java
public ChannelBuffer formatJVMStatsV1(final Map<String, Map<String, Object>> map) { throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, "The requested API endpoint has not been implemented", this.getClass().getCanonicalName() + " has not implemented formatJVMStatsV1"); }
python
def add(self, *args, **kwargs): """Add Cookie objects by their names, or create new ones under specified names. Any unnamed arguments are interpreted as existing cookies, and are added under the value in their .name attribute. With keyword arguments, the key is interpreted as th...
python
def from_proto(cls, proto_mesh, scale, pos, vel, euler, euler_vel, rotation_vel=(0,0,0), component_com_x=None): """ Turn a ProtoMesh into a Mesh scaled and placed in orbit. Update all geometry fields from the proto reference fram...
java
private synchronized void initialize() { if (this.runtimes != null) { return; } this.runtimes = new HashMap<>(); for (final AvroRuntimeDefinition rd : runtimeDefinition.getRuntimes()) { try { // We need to create different injector for each runtime as they define conflicting bind...
python
def get_single_assignment(self, id, course_id, all_dates=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None): """ Get a single assignment. Returns the assignment with the given id. "observed_users" is passed, submissions for observed users will...
python
def get_new(self): """List new files since last recorded file state. pysat stores filenames in the user_home/.pysat directory. Returns a list of all new fileanmes since the last known change to files. Filenames are stored if there is a change and either update_files is T...
java
public SolutionCategory getCategory(List<List<ColumnName>> names) { Piece xPiece = null; // find the "x" piece for(Piece p: pieces) { if ("x".equals(p.name)) { xPiece = p; break; } } // find the row containing the "x" for(List<ColumnName> row: names) { if (row.c...
python
def from_result(cls, container, result): """Create from ambiguous result.""" if result is None: raise errors.NoObjectException elif cls.is_prefix(result): return cls.from_prefix(container, result) elif cls.is_key(result): return cls.from_key(containe...
python
def traffic(stack_name: str, stack_version: Optional[str], percentage: Optional[int], region: Optional[str], remote: Optional[str], output: Optional[str]): '''Manage stack traffic''' lizzy = setup_lizzy_client(remote) if percentage is None: ...
python
def SetOption(self, section, option, value, overwrite=True): """Set the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to set the value of. value: string, the value to set the option. overwrite: bool, Tru...
java
public static Trades adaptTrades(BitstampTransaction[] transactions, CurrencyPair currencyPair) { List<Trade> trades = new ArrayList<>(); long lastTradeId = 0; for (BitstampTransaction tx : transactions) { final long tradeId = tx.getTid(); if (tradeId > lastTradeId) { lastTradeId = trad...
python
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT): """Get objects.""" from itertools import islice path = path.rstrip(SEP) + SEP if path else path result_set = self.native_container.list(path, SEP, marker) # Get +1 res...
java
public static void setOffsetInZooKeeper(CuratorFramework curatorClient, String groupId, String topic, int partition, long offset) throws Exception { ZKGroupTopicDirs topicDirs = new ZKGroupTopicDirs(groupId, topic); String path = topicDirs.consumerOffsetDir() + "/" + partition; curatorClient.newNamespaceAwareEnsu...
python
def intensity_measure_types(value): """ :param value: input string :returns: non-empty list of Intensity Measure Type objects >>> intensity_measure_types('PGA') ['PGA'] >>> intensity_measure_types('PGA, SA(1.00)') ['PGA', 'SA(1.0)'] >>> intensity_measure_types('SA(0.1), SA(0.10)') T...
python
def dest(self): """Create link destination details.""" if hasattr(self, "parent") and self.parent is None: raise ValueError("orphaned object: parent is None") if self.parent.parent.isClosed or self.parent.parent.isEncrypted: raise ValueError("operation illegal for closed ...
python
def to_python(fname, *args): """ Parse a NRML file and return an associated Python object. It works by calling nrml.read() and node_to_obj() in sequence. """ [node] = read(fname) return node_to_obj(node, fname, *args)
java
public void setStackIds(java.util.Collection<String> stackIds) { if (stackIds == null) { this.stackIds = null; return; } this.stackIds = new com.amazonaws.internal.SdkInternalList<String>(stackIds); }
java
public void serviceName_templatesControl_POST(String serviceName, OvhTypeTemplateEnum activity, String description, String message, String name, String reason) throws IOException { String qPath = "/sms/{serviceName}/templatesControl"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new Has...
python
def save_intermediate_img(self, img, name): """Save intermediate FITS objects.""" if self.intermediate_results: img.writeto(name, overwrite=True)
java
private void validateChildNodeDefinition( JcrNodeDefinition childNodeDefinition, List<Name> supertypes, List<JcrNodeType> pendingTypes ) throws RepositoryException { if (childNodeDefinition.isAutoCreated() && !childNodeD...
python
def execute_one(correlation_id, component, args): """ Executes specific component. To be executed components must implement [[IExecutable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through...
python
def equal (a, b): """ Returns True iff 'a' contains the same elements as 'b', irrespective of their order. # TODO: Python 2.4 has a proper set class. """ assert is_iterable(a) assert is_iterable(b) return contains (a, b) and contains (b, a)
python
async def load_by_path(self, path): """ Load a module by full path. If there are dependencies, they are also loaded. """ try: p, module = findModule(path, True) except KeyError as exc: raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + s...
java
public OvhVoipLineService packName_voipLine_services_domain_GET(String packName, String domain) throws IOException { String qPath = "/pack/xdsl/{packName}/voipLine/services/{domain}"; StringBuilder sb = path(qPath, packName, domain); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, ...
python
def draw_sample(self, Xstar, n=0, num_samp=1, rand_vars=None, rand_type='standard normal', diag_factor=1e3, method='cholesky', num_eig=None, mean=None, cov=None, modify_sign=None, **kwargs): """Draw a sample evaluated at the given points `Xstar`. ...
python
def fetcher_with_object(cls, parent_object, relationship="child"): """ Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: ...
java
public JimfsPath emptyPath() { JimfsPath result = emptyPath; if (result == null) { // use createPathInternal to avoid recursive call from createPath() result = createPathInternal(null, ImmutableList.of(Name.EMPTY)); emptyPath = result; return result; } return result; }
python
def update_job_queue(self, queue_name, priority, state, compute_env_order): """ Update a job queue :param queue_name: Queue name :type queue_name: str :param priority: Queue priority :type priority: int :param state: Queue state :type state: string ...
java
public double getATMForward(AnalyticModelInterface model, boolean isFirstPeriodIncluded) { if(!Double.isNaN(cachedATMForward) && cacheStateModel.get() == model && cacheStateIsFirstPeriodIncluded == isFirstPeriodIncluded) { return cachedATMForward; } ScheduleInterface remainderSchedule = schedule; if(!isFirs...
python
def off(self, name, callback, once=False): """ Removes callback to the event specified by name """ if name not in self.event_listeners: return self.event_listeners[name].remove((callback, once))
java
public String convertIfcDocumentConfidentialityEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public static String toHex(byte b) { StringBuilder sb = new StringBuilder(); appendByteAsHex(sb, b); return sb.toString(); }
python
def touch(self, mode=0o666, exist_ok=True): """Create a fake file for the path with the given access mode, if it doesn't exist. Args: mode: the file mode for the file if it does not exist exist_ok: if the file already exists and this is True, nothing happ...
python
def actual_original_query_range(self): """ This accounts for hard clipped bases and a query sequence that hasnt been reverse complemented :return: the range covered on the original query sequence :rtype: GenomicRange """ l = self.original_query_sequence_length a = self.alignment_ranges ...
java
public static <P> NearestNeighbor<P> kdRandomForest( KdTreeDistance<P> distance , int maxNodesSearched , int numTrees , int numConsiderSplit , long randomSeed ) { Random rand = new Random(randomSeed); return new KdForestBbfSearch<>(numTrees,maxNodesSearched,distance, new AxisS...
java
public @NotNull MediaArgs mediaFormat(MediaFormat value) { if (value == null) { this.mediaFormats = null; } else { this.mediaFormats = new MediaFormat[] { value }; } return this; }
java
public float ENgetoption( OptionParameterCodes optionCode ) throws EpanetException { float[] optionValue = new float[1]; int error = epanet.ENgetoption(optionCode.getCode(), optionValue); checkError(error); return optionValue[0]; }
java
private String buildConfiguration(Object cache) { final StringBuilder sb = new StringBuilder(); // getCacheConfiguration() et getMaxElementsOnDisk() n'existent pas en ehcache 1.2 final CacheConfiguration config = ((Ehcache) cache).getCacheConfiguration(); sb.append("ehcache [maxElementsInMemory = ").append(...
python
def Fisher(d1, d2, tag=None): """ An F (fisher) random variate Parameters ---------- d1 : int Numerator degrees of freedom d2 : int Denominator degrees of freedom """ assert ( int(d1) == d1 and d1 >= 1 ), 'Fisher (F) "d1" must be an integer greater than 0...
java
public Observable<ServiceResponse<Image>> addImageWithServiceResponseAsync(String listId, Integer tag, String label) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (listId == null) { ...
java
static WebClient createWebClient(CredHubProperties properties, ClientHttpConnector clientHttpConnector) { return buildWebClient(properties.getUrl(), clientHttpConnector) .build(); }
python
def list_locks(root=None): ''' List current package locks. root operate on a different root directory. Return a dict containing the locked package with attributes:: {'<package>': {'case_sensitive': '<case_sensitive>', 'match_type': '<match_type>' ...
python
def update_forward_refs(cls, **localns: Any) -> None: """ Try to update ForwardRefs on fields based on this Model, globalns and localns. """ globalns = sys.modules[cls.__module__].__dict__ globalns.setdefault(cls.__name__, cls) for f in cls.__fields__.values(): ...
python
def CrossEntropyFlat(*args, axis:int=-1, **kwargs): "Same as `nn.CrossEntropyLoss`, but flattens input and target." return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs)
java
public void setBundleId(String bundleId) { if (JawrRequestHandler.CLIENTSIDE_HANDLER_REQ_PATH.equals(bundleId)) throw new IllegalArgumentException("The provided id [" + JawrRequestHandler.CLIENTSIDE_HANDLER_REQ_PATH + "] can't be used since it's the same as the clientside handler path. Please change this id (...
python
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these ...
python
def send_template(self, template, to, reply_to=None, **context): """ Send Template message """ if self.provider == "SES": self.mail.send_template(template=template, to=to, reply_to=reply_to, **context) elif self.provider == "FLASK-MAIL": ses_mail = ses_mai...
java
public void importRelation(String resourceName, String targetPath, String relationType) throws CmsException { createRelation(resourceName, targetPath, relationType, true); }
java
protected PlanNode attachProject( QueryContext context, PlanNode plan, List<? extends Column> columns, Map<SelectorName, Table> selectors ) { PlanNode projectNode = new PlanNode(Type.PROJECT); ...
python
def set_default_locale(code: str) -> None: """Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a tran...
java
void returnWorkPermit() { while (true) { long current = permits.get(); int workPermits = workPermits(current); if (permits.compareAndSet(current, updateWorkPermits(current, workPermits + 1))) return; } }
java
public static double J0(double x) { double ax; if ((ax = Math.abs(x)) < 8.0) { double y = x * x; double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7 + y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456))))); double an...
python
def remove(self, item): """ Remove an item from the set, returning if it was present """ with self.lock: if item in self.set: self.set.remove(item) return True return False
java
public void finish() throws TransactionFailureException { Preconditions.checkState(currentTx != null, "Cannot finish tx that has not been started"); // each of these steps will abort and rollback the tx in case if errors, and throw an exception checkForConflicts(); persist(); commit(); postCommi...
java
public long getLastModified( Artifact artifact ) throws IOException, ArtifactNotFoundException { Entry entry = backing.get( artifact.getGroupId().replace( '.', '/' ) + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() + "/" + artifact.getName() ); if ( ...
java
public static <K, V, A> A ifPresentApply( Map<K, V> map, K key, Function<? super V, ? extends A> function) { if (map instanceof UnsortedMapIterable) { return ((MapIterable<K, V>) map).ifPresentApply(key, function); } V result = map.get(...
python
def Alt_Fn(self, n, dl = 0): """Alt + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.alt_key)
python
def set_data(self, x=None, y=None, z=None, colors=None): """Update the data in this surface plot. Parameters ---------- x : ndarray | None 1D array of values specifying the x positions of vertices in the grid. If None, values will be assumed to be integers. ...
java
protected static void checkMetricLabelName(String name) { if (!METRIC_LABEL_NAME_RE.matcher(name).matches()) { throw new IllegalArgumentException("Invalid metric label name: " + name); } if (RESERVED_METRIC_LABEL_NAME_RE.matcher(name).matches()) { throw new IllegalArgumentException("Invalid metr...
java
public DebugLogWrapper createDebugLogWrapper(int logId) { Preconditions.checkState(this.bookKeeper.get() != null, "BookKeeperLogFactory is not initialized."); return new DebugLogWrapper(logId, this.zkClient, this.bookKeeper.get(), this.config, this.executor); }
java
public static long getMacAddr() { if (macAddr == 0) { try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); for (byte temp : mac) ...
java
private String encodeUri( String uri ) { String newUri = ""; StringTokenizer st = new StringTokenizer( uri, "/ ", true ); while ( st.hasMoreTokens()) { String tok = st.nextToken(); if ( tok.equals( "/" )) newUri += "/"; else if ( tok.equals( " " )) newUri += "%20"; el...
java
private String getPreprocessorDefinitions(final CommandLineCompilerConfiguration compilerConfig, final boolean isDebug) { final StringBuffer defines = new StringBuffer(); final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if (arg.startsWith("/D")) { S...
python
def directive_DCB(self, label, params): """ label DCB value[, value ...] Allocate a byte space in read only memory for the value or list of values """ # TODO make this read only # TODO check for byte size self.labels[label] = self.space_pointer if param...
java
public String button (String name, String text, String extra) { return fixedInput("button", name, text, extra); }
python
def update_persistent_boot(self, device_type=[]): """Changes the persistent boot device order for the host :param device_type: ordered list of boot devices :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on ...
python
def use_plenary_activity_view(self): """Pass through to provider ActivityLookupSession.use_plenary_activity_view""" self._object_views['activity'] = PLENARY # self._get_provider_session('activity_lookup_session') # To make sure the session is tracked for session in self._get_provider_ses...
java
@Override public final void invoke() { if (index < inters.length) inters[index++].intercept(this); else if (index++ == inters.length) invocation.invoke(); }
python
def group2commlst(commlst, glist): """add group info to commlst""" for (gname, objname), commitem in zip(glist, commlst): newitem1 = "group %s" % (gname, ) newitem2 = "idfobj %s" % (objname, ) commitem[0].insert(0, newitem1) commitem[0].insert(1, newitem2) return commlst
java
@Override public double getInclusionProbability(Instance instance) { for (int i = 0 ; i < this.dimensions ; i++) { if ((int) instance.value(i) != this.coordinates[i]) return 0.0; } return 1.0; }
java
@Override public Value caseASetEnumSetExp(ASetEnumSetExp node, Context ctxt) throws AnalysisException { BreakpointManager.getBreakpoint(node).check(node.getLocation(), ctxt); ValueSet values = new ValueSet(); for (PExp e : node.getMembers()) { values.add(e.apply(VdmRuntime.getExpressionEvaluator(), ct...
python
def impulse_response(self, j=5): r""" Pulls off the imuplse response coefficients to a shock in :math:`w_{t}` for :math:`x` and :math:`y` Important to note: We are uninterested in the shocks to v for this method * :math:`x` coefficients are :math:`C, AC, A^2 C...` ...
java
void onSurfaceCreated() { Log.v(TAG, "onSurfaceCreated"); Thread currentThread = Thread.currentThread(); // Reduce contention with other Android processes currentThread.setPriority(Thread.MAX_PRIORITY); // we know that the current thread is a GL one, so we store it to ...
java
@Override public CreateOpenIDConnectProviderResult createOpenIDConnectProvider(CreateOpenIDConnectProviderRequest request) { request = beforeClientExecution(request); return executeCreateOpenIDConnectProvider(request); }
java
@SuppressWarnings("unchecked") public <V> Mapper<String, V> mapper() { if (!isChanged && nameValMap.isPresent()) { return (Mapper<String, V>) nameValMap.get(); } Map<String, Object> fm = Maps.newHashMap(); if (fieldHolder.isPresent()) { fieldLoop(new TransformFields2Map<Object>(fm, this.trace)); } ...
python
def copy_neg(self): """ Return a copy of self with the opposite sign bit. Unlike -self, this does not make use of the context: the result has the same precision as the original. """ result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) ...
java
public static <T> ReservoirItemsSketch<T> newInstance(final int k, final ResizeFactor rf) { return new ReservoirItemsSketch<>(k, rf); }
java
public void marshall(ResourcePath resourcePath, ProtocolMarshaller protocolMarshaller) { if (resourcePath == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourcePath.getComponents(), COMPONENTS_BI...
python
def get_predicate_indices(tags: List[str]) -> List[int]: """ Return the word indices of a predicate in BIO tags. """ return [ind for ind, tag in enumerate(tags) if 'V' in tag]
python
def _read_decimal(data, size, writer_schema): """ based on https://github.com/apache/avro/pull/82/ """ scale = writer_schema.get('scale', 0) precision = writer_schema['precision'] datum_byte = str2ints(data) unscaled_datum = 0 msb = fstint(data) leftmost_bit = (msb >> 7) & 1 if...
java
private void addPostParams(final Request request) { if (identity != null) { request.addPostParam("Identity", identity); } if (userAddress != null) { request.addPostParam("UserAddress", userAddress); } if (attributes != null) { request.addPost...
python
def recordHostname(self, basedir): "Record my hostname in twistd.hostname, for user convenience" log.msg("recording hostname in twistd.hostname") filename = os.path.join(basedir, "twistd.hostname") try: hostname = os.uname()[1] # only on unix except AttributeError: ...
python
def _dirdiffcopyandupdate(self, dir1, dir2): """ Private function which does directory diff, copy and update (synchro) """ self._dowork(dir1, dir2, self._copy, self._update)
python
def _set_acl_state(self, v, load=False): """ Setter method for acl_state, mapped from YANG variable /acl_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_acl_state is considered as a private method. Backends looking to populate this variable should ...
java
@Override public ListClustersResult listClusters(ListClustersRequest request) { request = beforeClientExecution(request); return executeListClusters(request); }
java
private void handleFragmentResponseMessage(FragmentResponseMessage message) { if (isFragmentMisrouted(message)){ m_mailbox.send(message.getDestinationSiteId(), message); return; } final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.SPI); ...
java
public void setCollapsed (boolean collapse) { if (collapse) { _content.setVisible(false); _trigger.setIcon(_downIcon); } else { _content.setVisible(true); _trigger.setIcon(_upIcon); } SwingUtil.refresh(this); }
java
private void buildGui(RibbonBarInfo barInfo, MapWidget mapWidget) { if (null == barInfo) { throw new IllegalArgumentException("RibbonBarLayout cannot be built without RibbonBarInfo configuration."); } for (RibbonGroupInfo groupInfo : barInfo.getGroups()) { RibbonGroupLayout group = new RibbonGroupLayout(gro...
python
def horizontal_border(self, _, outer_widths): """Handle the GitHub heading border. E.g.: |:---|:---:|---:|----| :param _: Unused. :param iter outer_widths: List of widths (with padding) for each column. :return: Prepared border strings in a generator. :rtype: i...
java
@Override public int docAppearedIn(String word) { T element = extendedVocabulary.get(word); if (element != null) { return (int) element.getSequencesCount(); } else return -1; }
python
def _on_work_finished(self, results): """ Display results. :param status: Response status :param results: Response data, messages. """ messages = [] for msg in results: msg = CheckerMessage(*msg) if msg.line >= self.editor.blockCount(): ...
python
def channels(self): """Output channels""" try: return self._channels except AttributeError: logger.debug("initialize output channels ...") channels = self.args.channels config_channels = [sec.rpartition('_')[0] for sec in self.config.sections(suffix='_cha...
python
def _ncc_c_3dim(x, y): """ Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms """ den = norm(x, axis=1)[:, None] * norm(y, axis=1) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1...
python
def setup(self): """Load backends and plugins. :returns: A `BuildConfiguration` object constructed during backend/plugin loading. """ return self._load_plugins( self._working_set, self._bootstrap_options.pythonpath, self._bootstrap_options.plugins, self._bootstrap_options.backen...