language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static ShardingStrategy newInstance(final ShardingStrategyConfiguration shardingStrategyConfig) { if (shardingStrategyConfig instanceof StandardShardingStrategyConfiguration) { return new StandardShardingStrategy((StandardShardingStrategyConfiguration) shardingStrategyConfig); } ...
java
public Double getValue(GriddedTile griddedTile, WritableRaster raster, int x, int y) { short pixelValue = getPixelValue(raster, x, y); Double value = getValue(griddedTile, pixelValue); return value; }
python
def image_absoulte_path(self, url, image): """if the image url does not start with 'http://' it will take the absolute path from the url and fuses them with urljoin""" if not re.match(re_http, image): topimage = urljoin(url, image) return topimage return image
python
def merge(left, right): """ Merge two mappings objects together, combining overlapping Mappings, and favoring right-values left: The left Mapping object. right: The right (favored) Mapping object. NOTE: This is not commutative (merge(a,b) != merge(b,a)). """ merged = {} left_keys ...
python
def is_valid_ipv6(ip_str): """ Check the validity of an IPv6 address """ try: socket.inet_pton(socket.AF_INET6, ip_str) except socket.error: return False return True
java
public static void editModule(CmsModule module, boolean isNew, String caption, Runnable callback) { Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); CmsEditModuleForm form = new CmsEditModuleForm(module, isNew, callback); window.setContent(form); window.setCaption(caption...
java
public void setRoleMembership(String subject, Set<String> roles) { validateStringValue(subject); Validate.notNull(roles); if(roles.isEmpty()) return; Validate.noNullElements(roles); props.setProperty(String.format(ROLE_MEMBERSHIP_FORMAT, subject), ArrayUtils.toString(encapsulateValues(roles))); }
python
def __edges_between_two_vertices(self, vertex1, vertex2, keys=False): """ Iterates over edges between two supplied vertices in current :class:`BreakpointGraph` Checks that both supplied vertices are present in current breakpoint graph and then yield all edges that are located between two supplied verti...
java
public A_CmsReportThread retrieveThread(CmsUUID key) { if (LOG.isDebugEnabled()) { dumpThreads(); } return m_threads.get(key); }
java
@Pure public IntegerProperty z2Property() { if (this.p2.z == null) { this.p2.z = new SimpleIntegerProperty(this, MathFXAttributeNames.Z2); } return this.p2.z; }
java
public final void setCellFactory(Callback<YearMonthView, DateCell> factory) { requireNonNull(factory); cellFactoryProperty().set(factory); }
java
public static Module<Factors> getFactorsModule(FactorGraph fg, Algebra s) { ForwardOnlyFactorsModule fm = new ForwardOnlyFactorsModule(null, fg, s); fm.forward(); return fm; }
python
def set_privacy(self, state): """ :param state: True or False :return: nothing """ values = {"desired_state": {"private": state}} response = self.api_interface.set_device_state(self, values) self._update_state_from_response(response)
python
def download_cutout(self, reading, focus=None, needs_apcor=False): """ Downloads a cutout of the FITS image for a given source reading. Args: reading: ossos.astrom.SourceReading The reading which will be the focus of the downloaded image. focus: tuple(int, int) ...
python
def load_dependency(self, module_name, dependencies, recursive, greedy, ismapping = False): """Loads the module with the specified name if it isn't already loaded.""" key = module_name.lower() if key not in self.modules: if key == "fortpy": #Manually specify the corre...
java
protected void doPrint() { PrintablePage pageInView = previewPane.getPrintablePage(); PrintablePage pageToPrint = new PrintablePage(); try { pageInView.bindPage(pageToPrint); Printer printer = Printer.getDefaultPrinter(); if (printer == null || settingsVie...
java
private String nextString(char quote) throws IOException { StringBuilder builder = null; do { /* the index of the first character not yet appended to the builder. */ int start = pos; while (pos < limit) { int c = buffer[pos++]; if (c =...
java
public static byte[] getByteArray(int size) { byte[][] pool = (byte[][])__pools.get(); boolean full=true; for (int i=pool.length;i-->0;) { if (pool[i]!=null && pool[i].length==size) { byte[]b = pool[i]; pool[i]=null; ...
python
def edit(self, text): """ Edit a text using an external editor. """ if isinstance(text, unicode): text = text.encode(self._encoding) if self._editor is None: printer.p('Warning: no editor found, skipping edit') return text with tempfile.NamedTe...
python
def _build_collapse_to_gene_dict(graph) -> Dict[BaseEntity, Set[BaseEntity]]: """Build a collapse dictionary. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {node: set of PyBEL node tuples} """ collapse_dict = defaultdict(set) r2g = {} for gene_node, rna_node, d in graph...
java
@Pure DBaseFileAttributeAccessor getAccessor(int recordNumber) { DBaseFileAttributeAccessor accessor = this.accessors.get(recordNumber); if (accessor == null) { accessor = new DBaseFileAttributeAccessor(this, recordNumber); this.accessors.put(recordNumber, accessor); } return accessor; }
python
def get(self, key): '''Return the object named by key or None if it does not exist. LoggingDatastore logs the access. ''' self.logger.info('%s: get %s' % (self, key)) value = super(LoggingDatastore, self).get(key) self.logger.debug('%s: %s' % (self, value)) return value
java
protected void int2alphaCount(long val, CharArrayWrapper aTable, FastStringBuffer stringBuf) { int radix = aTable.getLength(); char[] table = new char[radix]; // start table at 1, add last char at index 0. Reason explained above and below. int i; for (i = 0; i < ...
python
def _is_on_import_statement(self, offset): "Does this offset point to an import statement?" data = self.resource.read() bol = data.rfind("\n", 0, offset) + 1 eol = data.find("\n", 0, bol) if eol == -1: eol = len(data) line = data[bol:eol] line = line.s...
java
private void clearAllHeaders() { final boolean bTrace = TraceComponent.isAnyTracingEnabled(); if (bTrace && tc.isEntryEnabled()) { Tr.entry(tc, "clearAllHeaders()"); } HeaderElement elem = this.hdrSequence; while (null != elem) { final HeaderElement next ...
python
def _remove_tree(self, tree, parent=None): """ Really remove the tree identified by `tree` instance from all indexes from database. Args: tree (obj): :class:`.Tree` instance. parent (obj, default None): Reference to parent. """ # remove sub-trees ...
python
def exit_with_exc_info(code=1, message='', print_tb=False, exception=None): '''Exits the program, printing information about the last exception (if any) and an optional error message. Uses *exception* instead if provided. :param code: Exit code. :type code: integer (valid exit code, 0-255) :param ...
java
public void replaceValues(List<Object> values) { Preconditions.checkArgument(values != null, "Values cannot be null"); Preconditions.checkArgument(values.size() <= fields.size(), "Values cannot be larger than fields size"); this.values = values; }
java
private GenericRecord deserialize(Event event, GenericRecord reuse) throws EventDeliveryException { decoder = DecoderFactory.get().binaryDecoder(event.getBody(), decoder); // no checked exception is thrown in the CacheLoader DatumReader<GenericRecord> reader = readers.getUnchecked(schema(event)); ...
java
public static Sample ofIsoText(String isoDate, String textValue) { return new Sample(null, isoDate, null, textValue); }
java
protected void bicoCFUpdate(ClusteringTreeNode x) { // Starts with the global root node as the current root node ClusteringTreeNode r = this.root; int i = 1; while (true) { ClusteringTreeNode y = r.nearestChild(x.getCenter()); // Checks if the node can not be merged to the current level if (r.hasNoChil...
java
public VoiceMessageList listVoiceMessages(final Integer offset, final Integer limit) throws UnauthorizedException, GeneralException { if (offset != null && offset < 0) { throw new IllegalArgumentException("Offset must be > 0"); } if (limit != null && limit < 0) { throw ne...
python
def apseudo(Ss, ipar, sigma): """ draw a bootstrap sample of Ss """ # Is = random.randint(0, len(Ss) - 1, size=len(Ss)) # draw N random integers #Ss = np.array(Ss) if not ipar: # ipar == 0: BSs = Ss[Is] else: # need to recreate measurement - then do the parametric stuffr A...
java
@Override public void setStereoElements(List<IStereoElement> elements) { this.stereoElements = new HashSet<IStereoElement>(); this.stereoElements.addAll(elements); }
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.LOCAL_DATE_AND_TIME_STAMP__STAMP_TYPE: setStampType((Integer)newValue); return; case AfplibPackage.LOCAL_DATE_AND_TIME_STAMP__THUN_YEAR: setTHunYear((Integer)newValue); return; case AfplibPac...
python
def find(self, dtype): """ Parameters ---------- dtype : PandasExtensionDtype or string Returns ------- return the first matching dtype, otherwise return None """ if not isinstance(dtype, str): dtype_type = dtype if not isi...
java
public final void setMaximumInterpreterStackDepth(int max) { if(sealed) onSealedMutation(); if(optimizationLevel != -1) { throw new IllegalStateException("Cannot set maximumInterpreterStackDepth when optimizationLevel != -1"); } if(max < 1) { throw new Illegal...
python
def fast_exponentiation(a, b, q): """Compute (a pow b) % q, alternative shorter implementation :param int a b: non negative :param int q: positive :complexity: O(log b) """ assert a >= 0 and b >= 0 and q >= 1 result = 1 while b: if b % 2 == 1: result = (result * a) %...
java
@Programmatic // not part of metamodel public List<Gmap3ToDoItem> autoComplete(final String description) { // the JDO implementation ... return repositoryService.allMatches( new QueryDefault<>(Gmap3ToDoItem.class, "todo_autoComplete", ...
java
public static String getGroupName(final File file) { if (OsValidator.WINDOWS) { logger.trace("Determining 'group' is skipped for file [{}] on [{}]", file, OsValidator.OS); return null; } try { final Path path = Paths.get(file.getAbsolutePath()); fi...
python
def _get_range_timestamp_key(self, start: Key, end: Key, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. This is used when the key being used is a TIMESTAMP key. """ r...
python
async def get(self, *, encoding=None, decoder=None): """Coroutine that waits for and returns a message. :raises aioredis.ChannelClosedError: If channel is unsubscribed and has no messages. """ assert decoder is None or callable(decoder), decoder if self._queue.exhaus...
java
public static int nvrtcCompileProgram(nvrtcProgram prog, int numOptions, String options[]) { return checkResult(nvrtcCompileProgramNative( prog, numOptions, options)); }
java
@DebugLog private void buildAndInject(){ mComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); mComponent.inject(this); }
python
def get_default_config(self): """ Return the default config for the handler """ config = super(NullHandler, self).get_default_config() config.update({ }) return config
java
@XmlElementDecl(namespace = "http://ping.system.soap.services.server.exampleproject.anythingworks.optimaize.com/", name = "ping") public JAXBElement<Ping> createPing(Ping value) { return new JAXBElement<Ping>(_Ping_QNAME, Ping.class, null, value); }
python
def setup_default_layouts(self, index, settings): """Setup default layouts when run for the first time.""" self.setUpdatesEnabled(False) first_spyder_run = bool(self.first_spyder_run) # Store copy if first_spyder_run: self.set_window_settings(*settings) els...
java
public boolean isEncryptedString( final String str ) { if ( str == null || str.length() < 1 ) { return false; } Matcher matcher = ENCRYPTED_STRING_PATTERN.matcher( str ); return matcher.matches() || matcher.find(); }
java
public String setPropertyTypeFromStringValue( PropertyIdValue propertyIdValue, StringValue value) { String datatype = getPropertyType(propertyIdValue); if (datatype == null) { logger.warn("Could not fetch datatype of " + propertyIdValue.getIri() + ". Assuming type " + DatatypeIdValue.DT_STRING); ...
python
def get_found_includes(self, env, scanner, path): """Return the included implicit dependencies in this file. Cache results so we only scan the file once per path regardless of how many times this information is requested. """ memo_key = (id(env), id(scanner), path) try: ...
java
public int getInvoicesCount(final QueryParams params) { FluentCaseInsensitiveStringsMap map = doHEAD(Invoices.INVOICES_RESOURCE, params); return Integer.parseInt(map.getFirstValue(X_RECORDS_HEADER_NAME)); }
python
def timestamp(s): ''' Converts a timestamp given in "hhmmss[.ss]" ASCII text format to a datetime.time object ''' ms_s = s[6:] ms = ms_s and int(float(ms_s) * 1000000) or 0 t = datetime.time( hour=int(s[0:2]), minute=int(s[2:4]), second=int(s[4:6]), ...
java
protected OptionalThing<RunnerResult> stopConcurrentJobIfNeeds(Cron4jJob job) { // in preparing lock synchronized (runningState) { final OptionalThing<RunnerResult> concurrentResult = createConcurrentJobStopper().stopIfNeeds(job, () -> { return runningState.getBeginTime().get().toStr...
python
def load_cfg(path, envvar_prefix='LIBREANT_', debug=False): '''wrapper of config_utils.load_configs''' try: return load_configs(envvar_prefix, path=path) except Exception as e: if debug: raise else: die(str(e))
python
def _fw_create(self, drvr_name, data, cache): """Firewall create routine. This function updates its local cache with FW parameters. It checks if local cache has information about the Policy associated with the FW. If not, it means a restart has happened. It retrieves the policy ...
java
protected void writePdf(final MBasicTable table, final OutputStream out) throws IOException { try { // step 1: creation of a document-object final Rectangle pageSize = landscape ? PageSize.A4.rotate() : PageSize.A4; final Document document = new Document(pageSize, 50, 50, 50, 50); // step 2: we creat...
python
def bool_check(*args, func=None): """Check if arguments are bytes type.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, bool): name = type(var).__name__ raise BoolError( f'Function {func} expected bool, {name} got instead.')
java
private boolean waitForTasksToFinish() throws Exception { Boolean succeeded = true; // Tracking state for multiple exceptions, if any List<StackTraceElement> stackTraces = new ArrayList<StackTraceElement>(); StringBuilder sb = new StringBuilder(); int exCount = ...
java
public String hashCodeList(List<RecordTemplateSpec.Field> fields) { StringBuilder sb = new StringBuilder(); Iterator<RecordTemplateSpec.Field> iter = fields.iterator(); while(iter.hasNext()) { RecordTemplateSpec.Field field = iter.next(); Type schemaType = field.getSchemaField().getType().getTyp...
python
def __set_tab_title(self, index): """ Sets the name and toolTip of the **Script_Editor_tabWidget** Widget tab with given index. :param index: Index of the tab containing the Model editor. :type index: int """ editor = self.get_widget(index) if not editor: ...
java
public static HeliosClient create(final String domain, final String user) { return HeliosClient.newBuilder() .setDomain(domain) .setUser(user) .build(); }
python
def gadf(y, method="Quantiles", maxk=15, pct=0.8): """ Evaluate the Goodness of Absolute Deviation Fit of a Classifier Finds the minimum value of k for which gadf>pct Parameters ---------- y : array (n, 1) values to be classified method : {'Quantiles, 'Fisher_Jenks', 'Max...
java
protected List<PExp> cloneListPExp(List<PExp> args) { List<PExp> clones = new LinkedList<PExp>(); for (PExp pexp : args) { clones.add(pexp.clone()); } return clones; }
python
def column_list(tables, columns): """ Take a list of tables and a list of column names and return the columns that are present in the tables. Parameters ---------- tables : sequence of _DataFrameWrapper or _TableFuncWrapper Could also be sequence of modified pandas.DataFrames, the impor...
java
public static void putAvailableAuthenticationHandleNames(final RequestContext context, final Collection<String> availableHandlers) { context.getFlowScope().put("availableAuthenticationHandlerNames", availableHandlers); }
python
def get_urls( self, root_view_name=None, optional_trailing_slash=False, decorate=(), name_template='{name}', ): """ Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name...
java
public void setLargestKey(int chunkIdx, byte[] largestKeyInChunk) { maxKeyPerChunk[chunkIdx] = largestKeyInChunk; filledUpTo = Math.max(filledUpTo, chunkIdx); indexBuffer.position(chunkIdx * keySize); indexBuffer.put(largestKeyInChunk); }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.MDRRG__RG_LENGTH: return getRGLength(); case AfplibPackage.MDRRG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); }
java
public static Object put(String key, Object value) { return value == null ? CONTEXT.remove(key) : CONTEXT.put(key, value); }
python
def settings_loader( obj, settings_module=None, env=None, silent=True, key=None, filename=None ): """Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :par...
java
public Partition withParameters(java.util.Map<String, String> parameters) { setParameters(parameters); return this; }
python
def init(config_object: Optional[Any] = None) -> None: """ Initialize NoneBot instance. This function must be called at the very beginning of code, otherwise the get_bot() function will return None and nothing is gonna work properly. :param config_object: configuration object """ globa...
python
def _unset(self, pos): """Set bit at pos to 0.""" assert 0 <= pos < self.len self._datastore.unsetbit(pos)
java
public java.lang.String getRel() { return (java.lang.String) getStateHelper().eval(PropertyKeys.rel); }
java
protected void processRelationship(final ParserData parserData, final SpecNodeWithRelationships specNode, final Relationship relationship) { final String relatedId = relationship.getSecondaryRelationshipId(); // The relationship points to a target so it must be a level or topic if (r...
java
public java.util.List<String> getLaunchTemplateNames() { if (launchTemplateNames == null) { launchTemplateNames = new com.amazonaws.internal.SdkInternalList<String>(); } return launchTemplateNames; }
python
def avail_images(call=None): ''' Return a list of the images that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) ret = {} conn...
java
public final EObject entryRuleTerminalToken() throws RecognitionException { EObject current = null; EObject iv_ruleTerminalToken = null; try { // InternalXtext.g:3115:54: (iv_ruleTerminalToken= ruleTerminalToken EOF ) // InternalXtext.g:3116:2: iv_ruleTerminalToken= ru...
python
def unholdAction(self): """ Unholds the action from being blocked on the leave event. """ self._actionHeld = False point = self.mapFromGlobal(QCursor.pos()) self.setCurrentAction(self.actionAt(point))
java
@Override public EClass getIfcTypeProcess() { if (ifcTypeProcessEClass == null) { ifcTypeProcessEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(738); } return ifcTypeProcessEClass; }
python
def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False
python
def view(self, dtype=None): """ Create a new view of the Series. This function will return a new Series with a view of the same underlying values in memory, optionally reinterpreted with a new data type. The new data type must preserve the same size in bytes as to not ca...
java
@Override public void notifyOfHosts( int yourHostId, int[] hosts, SocketChannel[] sockets, SSLEngine[] sslEngines, InetSocketAddress listeningAddresses[], Map<Integer, JSONObject> jos) throws Exception { m_localHostId = yourHostId; ...
java
public String getUrl() { ContentAccess content = getContentAccess(); String mode = DisplayMode.PROMPT_TO_SAVE.equals(getDisplayMode()) ? "attach" : "inline"; // Check for a "static" resource if (content instanceof InternalResource) { String url = ((InternalResource) content).getTargetUrl(); // This magi...
python
def wrap_json(cls, json, viewers=None, channels=None): """Create a Game instance for the given json :param json: the dict with the information of the game :type json: :class:`dict` :param viewers: The viewer count :type viewers: :class:`int` :param channels: The viewer c...
python
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("...
python
def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None: """Register a hook to be called before the command function.""" self._validate_prepostcmd_hook(func, plugin.PrecommandData) self._precmd_hooks.append(func)
python
def get_lock(self, path): """ Get a job lock corresponding to the path - assumes parent directory exists but the file itself does not. """ if self.lockfile: return self.lockfile.LockFile(path) else: with self.job_locks_lock: if path not in ...
java
private String genElementDefinition(StructureDefinition sd, ElementDefinition ed) { String id = ed.hasBase() ? ed.getBase().getPath() : ed.getPath(); String shortId = id.substring(id.lastIndexOf(".") + 1); String defn; ST element_def; String card = ("*".equals(ed.getMax()) ? (ed.getMin() == 0 ?...
java
@Override public CommerceShipment findByGroupId_Last(long groupId, OrderByComparator<CommerceShipment> orderByComparator) throws NoSuchShipmentException { CommerceShipment commerceShipment = fetchByGroupId_Last(groupId, orderByComparator); if (commerceShipment != null) { return commerceShipment; } ...
python
def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this me...
python
def amended_commits(commits): """Return those git commit sha1s that have been amended later.""" # which SHA1 are declared as amended later? amended_sha1s = [] for message in commits.values(): amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message)) return amended_sha1s
java
@NotNull @ObjectiveCName("shareHistoryWithGid:") public Promise<Void> shareHistory(int gid) { return modules.getGroupsModule().shareHistory(gid); }
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._docume...
python
def list_nodes_select(nodes, selection, call=None): ''' Return a list of the VMs that are on the provider, with select fields ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_select function must be called ' 'with -f or --function.' ) if 'e...
python
def read(self, symbol, date_range=None, columns=None, include_images=False, allow_secondary=None, _target_tick_count=0): """ Read data for the named symbol. Returns a VersionedItem object with a data and metdata element (as passed into write). Parameters ----------...
python
def apply_config(self, config): """ Sets the `discovery` and `meta_cluster` attributes, as well as the configured + available balancer attributes from a given validated config. """ self.discovery = config["discovery"] self.meta_cluster = config.get("meta_cluster")...
java
public ContainerCreate create(String imageId) { ContainerCreate command = new ContainerCreate(); command.image(imageId); action.setCommand(command); return command; }
java
private void updateHubHeartbeatSelf() { _isHubHeartbeatSelf = true; if (_hubHeartbeatCount < 2) { for (Result<Boolean> result : _hubHeartbeatList) { result.ok(true); } _hubHeartbeatList.clear(); } }
python
def next_train_batch(self, batch_size): """ Return the next batch of examples from train data set :param batch_size: int, size of image batch returned :return train_labels: list, of labels :return images: list, of images """ start = self.index_in_train_epoch ...