language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def dbmin10years(self, value=None): """ Corresponds to IDD Field `dbmin10years` 10-year return period values for minimum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmin10years` Unit: C if `value` is None it will not be ch...
java
public void check(BioCDocument document) { String text = checkText(document); check(document, 0, text); for (BioCPassage passage : document.getPassages()) { check(passage, 0, text, document); for (BioCSentence sentence : passage.getSentences()) { check(sentence, 0, text, document, passag...
java
public static Builder newBuilder( TableId destinationTable, List<String> sourceUris, FormatOptions format) { return newBuilder(destinationTable, sourceUris).setFormatOptions(format); }
java
@Override public PutObjectResult putObject(PutObjectRequest request) { request = beforeClientExecution(request); return executePutObject(request); }
java
private void layoutCyclicParts() throws CDKException { logger.debug("Start of layoutNextRingSystem()"); resetUnplacedRings(); IAtomContainer placedAtoms = AtomPlacer.getPlacedAtoms(molecule); logger.debug("Finding attachment bond to already placed part..."); IBond nextRingAttach...
python
def add_field(self, field): """Add the received field to the model.""" self.remove_field(field.name) self._fields[field.name] = field if field.default is not None: if six.callable(field.default): self._default_callables[field.key] = field.default ...
java
private void addValue(Object chartSerie, Number x, String lastXValue, Number y, HashMap<String, String> formatValues, int chartsNo) { if (chart.getType().isLine()) { ((XYSeries)chartSerie).add(x, y); } else if (isLineCombo) { lineBarDataset.addValue(y, (String)chartSerie, lastXValue); } else if...
java
private void setRenderFlag(String oid) { try { DigitalObject object = storage.getObject(oid); Properties props = object.getMetadata(); props.setProperty("render-pending", "true"); storeProperties(object, props); } catch (StorageException ex) { log.error("Error accessing storage for '{}'", oid, ex); ...
python
def slew(self, value): '''move to a given position in the file''' if float(value) != self.filepos: pos = float(value) * self.filesize self.mlog.f.seek(int(pos)) self.find_message()
python
def new(self, inlineparent = None): ''' Create an empty struct of this type. "initfunc" is called on the created struct to initialize it. :param inlineparent: if specified, this struct is embedded into another struct "inlineparent" :returns: a created struct (usually a ...
java
public Predicate create(Filter filter) { List<Predicate> predicates = new ArrayList<>(filter.getPredicates().size()); for (org.cdlflex.fruit.Predicate fp : filter.getPredicates()) { predicates.add(create(fp)); } return connect(predicates, filter.getConnective()); }
python
def _set_timeout(self, msecs: int) -> None: """Called by libcurl to schedule a timeout.""" if self._timeout is not None: self.io_loop.remove_timeout(self._timeout) self._timeout = self.io_loop.add_timeout( self.io_loop.time() + msecs / 1000.0, self._handle_timeout ...
python
def set_array(longarray, shortarray): """ :param longarray: a numpy array of floats of length L >= l :param shortarray: a numpy array of floats of length l Fill `longarray` with the values of `shortarray`, starting from the left. If `shortarry` is shorter than `longarray`, then the remaining elemen...
python
def get_mapping_client(self, max_concurrency=64, auto_batch=None): """Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :...
python
def refresh(self): """Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions. """ j = self.vera_request(id='sdata', output_format='json').json() devices = j.get('devices') for device_data in devices: if device_data.get('id'...
java
public void setSeparatorColor(int separatorColor) { mSeparatorColor = separatorColor; Field[] pickerFields = NumberPicker.class.getDeclaredFields(); for (Field pf : pickerFields) { if (pf.getName().equals("mSelectionDivider")) { pf.setAccessible(true); ...
java
@Override public EClass getIfcCartesianTransformationOperator() { if (ifcCartesianTransformationOperatorEClass == null) { ifcCartesianTransformationOperatorEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(81); } return ifcCartesianTransformationOp...
python
def get_network_channel(self): """Get a reasonable 'default' network channel. When configuring/examining network configuration, it's desirable to find the correct channel. Here we run with the 'real' number of the current channel if it is a LAN channel, otherwise it evaluates a...
java
void registerPrefetchCall(@NotNull ApolloPrefetch apolloPrefetch) { checkNotNull(apolloPrefetch, "apolloPrefetch == null"); OperationName operationName = apolloPrefetch.operation().name(); registerCall(activePrefetchCalls, operationName, apolloPrefetch); }
python
def http_method(self, method): """ Execute the given HTTP method and returns if it's success or not and the response as a string if not success and as python object after unjson if it's success. """ self.build_url() try: response = self.get_http_metho...
java
public void setOwner(Path f, String user, String group) throws IOException { try (Closeable context = new TimerContextWithLog(this.setOwnerTimer.time(), "setOwner", f, user, group)) { super.setOwner(f, user, group); } }
java
@SuppressWarnings("unchecked") public QuickfixModel getOrCreate(String name, QuickfixType type) { Iterable<Vertex> results = (Iterable<Vertex>)getQuery().getRawTraversal().has(QuickfixModel.PROPERTY_TYPE, type).has(QuickfixModel.PROPERTY_DESCRIPTION, name).toList(); if (!results.iterator().hasNe...
java
private static void findAnnotatedElements( Element element, Set<? extends Class<? extends Annotation>> annotationClasses, ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> annotatedElements) { for (Element enclosedElement : element.getEnclosedElements()) { if (!enclosedEleme...
python
def inline_bbl(root_tex, bbl_tex): """Inline a compiled bibliography (.bbl) in place of a bibliography environment. Parameters ---------- root_tex : unicode Text to process. bbl_tex : unicode Text of bibliography file. Returns ------- txt : unicode Text with...
python
def load_ner_model(lang="en", version="2"): """Return a named entity extractor parameters for `lang` and of version `version` Args: lang (string): language code. version (string): version of the parameters to be used. """ src_dir = "ner{}".format(version) p = locate_resource(src_dir, lang) fh = _op...
java
public TransformJobDefinition withEnvironment(java.util.Map<String, String> environment) { setEnvironment(environment); return this; }
java
public BigMoney minusMinor(long amountToSubtract) { if (amountToSubtract == 0) { return this; } BigDecimal newAmount = amount.subtract(BigDecimal.valueOf(amountToSubtract, currency.getDecimalPlaces())); return BigMoney.of(currency, newAmount); }
java
public static final void reset(){ instance.reset(); String junittest = System.getProperty("JUNITTEST"); if (junittest!=null && junittest.equalsIgnoreCase("true")) return; StartBuiltInProducers.restartbuiltin(); }
python
def _create_run_ini(self, port, production, output='development.ini', source='development.ini', override_site_url=True): """ Create run/development.ini in datadir with debug and site_url overridden and with correct db passwords inserted """ cp = SafeConfig...
python
def name(self) -> str: """Return name relevant to direction.""" if self.direction == DIRECTION_IN: return self.raw.get('Input.Name', '') return self.raw.get('Output.Name', '')
python
def _initialize_rest(self): """Used to initialize the View object on first use. """ if self._submit_context is None: raise ValueError("View has not been created.") job = self._submit_context._job_access() self._view_object = job.get_views(name=self.name)[0]
java
private void autoSelectAuthHandler(final HttpProxyResponse response) throws ProxyAuthException { // Get the Proxy-Authenticate header List<String> values = response.getHeaders().get("Proxy-Authenticate"); ProxyIoSession proxyIoSession = getProxyIoSession(); if (values == nul...
python
def sigint_handler(self, signum: int, frame) -> None: """Signal handler for SIGINTs which typically come from Ctrl-C events. If you need custom SIGINT behavior, then override this function. :param signum: signal number :param frame """ if self.cur_pipe_proc_reader is no...
java
@NotNull @ObjectiveCName("doStartAuthWithEmail:") public Promise<AuthStartRes> doStartEmailAuth(String email) { return modules.getAuthModule().doStartEmailAuth(email); }
python
def _patch_redirect(session): # type: (requests.Session) -> None """Whether redirect policy should be applied based on status code. HTTP spec says that on 301/302 not HEAD/GET, should NOT redirect. But requests does, to follow browser more than spec https://github.com/requests/requests/blob/f6e13cc...
python
def debug_interactive_inspect_node(self): """ Call after segmentation to see selected node neighborhood. User have to select one node by click. :return: """ if ( np.sum( np.abs( np.asarray(self.msinds.shape) - np.asarray(sel...
java
public PropertyManager<T> getPropertyManager(T property) { PropertyManager<T> propertyManager = propertyManagerCache.get(property); if (propertyManager == null) { PropertyManager<T> newPropertyManager = new PropertyManager<T>(property, ...
python
def add_holiday(self, start_dt, holiday_name, end_dt = None, calendar_id = 'notices'): '''Adds a holiday event to the calendar. start_dt and end_dt (if supplied) should be date objects. Returns True if the event was added.''' assert(calendar_id in self.configured_calendar_ids.keys()) calendarId...
python
def encode(self, obj): """Returns ``obj`` serialized as a pickle binary string. Raises ------ ~ipfsapi.exceptions.EncodingError Parameters ---------- obj : object Serializable Python object Returns ------- bytes "...
java
private List<Trip.Leg> parsePathIntoLegs(List<Label.Transition> path, Graph graph, Weighting weighting, Translation tr) { if (path.size() <= 1) { return Collections.emptyList(); } if (GtfsStorage.EdgeType.ENTER_PT == path.get(1).edge.edgeType) { final GtfsStorage.FeedIdWi...
python
def t_string_UNESCAPED(self, t): r'[\x20-\x21,\x23-\x5B,\x5D-\xFF]+' t.value = t.value if isinstance(t.value, unicode) else unicode(t.value, encoding='utf8') return t
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DroolsPackage.IMPORT_TYPE__NAME: return getName(); } return super.eGet(featureID, resolve, coreType); }
python
def p_new_elseif_list(p): '''new_elseif_list : empty | new_elseif_list ELSEIF LPAREN expr RPAREN COLON inner_statement_list''' if len(p) == 2: p[0] = [] else: p[0] = p[1] + [ast.ElseIf(p[4], ast.Block(p[7], lineo=p.lineno(6)), lineno=p...
python
def begin(self): """Initialize library, must be called once before other functions are called. """ resp = ws.ws2811_init(self._leds) if resp != 0: str_resp = ws.ws2811_get_return_t_str(resp) raise RuntimeError('ws2811_init failed with code {0} ({1})'.form...
java
@Override public String getNativePath() { if (! isWindows()) { return getFullPath(); } String path = getFullPath(); int length = path.length(); CharBuffer cb = new CharBuffer(); char ch; int offset = 0; // For windows, convert /c: to c: if (length >= 3 && path.cha...
java
private static String cleanWS(String s) { s = replaceAll(s, OuterWhiteSpacesPtn, ""); s = replaceAll(s, WhiteSpacesPtn, " "); return s; }
java
public boolean await() throws InterruptedException { boolean noTimeout = true; // Use a loop and a boolean to avoid spurious time outs. try { while (!isSignal && noTimeout) { noTimeout = conditionVar.await(timeoutPeriod, timeoutUnits); } } finally { isSignal = false; } ...
python
def produce(topic, conf): """ Produce User records """ from confluent_kafka.avro import AvroProducer producer = AvroProducer(conf, default_value_schema=record_schema) print("Producing user records to topic {}. ^c to exit.".format(topic)) while True: # Instantiate new User, pop...
python
def save(self, *args, **kwargs): """ Saves the forum instance. """ # It is vital to track the changes of the parent associated with a forum in order to # maintain counters up-to-date and to trigger other operations such as permissions updates. old_instance = None if self.pk: ...
python
def criteria_text(self, sep=' ', params=False): """ Get a text representation of the criteria node. :param sep: Separator used to indent the contents of the node. :param params: Boolean, set to True in order to display node parameters. :return: """ s = '' ...
java
@Override @Transactional(enabled = false) public CommerceWarehouse createCommerceWarehouse(long commerceWarehouseId) { return commerceWarehousePersistence.create(commerceWarehouseId); }
java
public static void init(@NonNull Application app, @NonNull CoreConfiguration config, boolean checkReportsOnApplicationStart) { final boolean senderServiceProcess = isACRASenderServiceProcess(); if (senderServiceProcess) { if (ACRA.DEV_LOGGING) log.d(LOG_TAG, "Not initialisin...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { syslog_server_responses result = (syslog_server_responses) service.get_payload_formatter().string_to_resource(syslog_server_responses.class, response); if(result.errorcode != 0) { if (result.error...
java
public boolean send() { assert sentRequests == null; sentRequests = new ArrayList<RequestCallInfo>(); // add prepended requests, addPrependedRequests( sentRequests ); // add requests to send while( !requestsToSend.isEmpty() ) sentRequests.add( requestsToSend.remove( 0 ) ); // add appended requests ...
python
def file_query(database, file_name, **connection_args): ''' Run an arbitrary SQL query from the specified file and return the the number of affected rows. .. versionadded:: 2017.7.0 database database to run script inside file_name File name of the script. This can be on the...
java
public void setThreadMax(int max) { if (max == _threadMax) { // avoid update() overhead if unchanged return; } if (max <= 0) { max = DEFAULT_THREAD_MAX; } if (max < _idleMin) throw new ConfigException(L.l("IdleMin ({0}) must be less than ThreadMax ({1})", _idleMin...
python
def shell_run(cmd, cin=None, cwd=None, timeout=10, critical=True, verbose=True): ''' Runs a shell command within a controlled environment. .. note:: |use_photon_m| :param cmd: The command to run * A string one would type into a console like \ :command:`git push -u origin...
python
def can_aquire_user_lock(repository_path, session_token): """ Allow a user to acquire the lock if no other user is currently using it, if the original user is returning, presumably after a network error, or if the lock has expired. """ # NOTE ALWAYS use within lock access callback user_file_path = cpj...
java
protected static double[] average(double[] base, double[] target) { int dataNum = base.length; double[] average = new double[dataNum]; for (int index = 0; index < dataNum; index++) { average[index] = (base[index] + target[index]) / 2.0; } return average;...
python
def _qteRunQueuedMacro(self, macroName: str, widgetObj: QtGui.QWidget=None, keysequence: QtmacsKeysequence=None): """ Execute the next macro in the macro queue. This method is triggered by the ``timerEvent`` in conjunction with the f...
java
@Override public GenThread[] prepare(JobConf conf, Text key, Text value) throws IOException { this.rtc = new GenWriterRunTimeConstants(); super.prepare(conf, key, value, rtc); rtc.task_name = key.toString() + rtc.taskID; rtc.roll_interval = conf.getLong(WRITER_ROLL_INTERVAL_KEY, ...
python
async def work_async(self): """Perform a single Connection iteration asynchronously.""" try: raise self._error except TypeError: pass except Exception as e: _logger.warning("%r", e) raise try: await self.lock_async() ...
java
private Assignment initializeAssignment(FactorGraph factorGraph) { // Select the initial assignment. // TODO: Perform a search to find an outcome with nonzero probability. Variable[] variables = factorGraph.getVariables().getVariablesArray(); int[] varNums = factorGraph.getVariables().getVariableNumsArray...
java
public Integer[] nextPermutation() { if (permLeft.equals(permTotal)) { permLeft = permLeft.subtract(BigInteger.ONE); return position; } // Find largest index j with a[j] < a[j+1] int j = position.length - 2;...
python
def _update_state(self, change): """ Keep position and direction in sync with axis """ self._block_updates = True try: self.position = self.axis.Location() self.direction = self.axis.Direction() finally: self._block_updates = False
java
public static PlainDate parseDate( CharSequence iso, ParseLog plog ) { int hyphens = 0; int n = iso.length(); int start = plog.getPosition(); int len = n - start; if (len < 7) { plog.setError(n, "Too short to be compatible with ISO-8601: " + iso.s...
python
def optimize_png_file(f, o=None): """ Use pngquant for optimize PNG-image. f - path to input image file or file-object. o - path to output image file or file-object for save result. NOTICE: f and o can not be of different type """ if isinstance(f, basestring): if o is None: ...
java
public synchronized void initialiseFromAPIToken(final String token) { final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_TOKEN_EXCHANGE, null, getOwnCallbackUri().toString(), ...
python
def _parse_proto(prototxt_fname): """Parse Caffe prototxt into symbol string """ proto = caffe_parser.read_prototxt(prototxt_fname) # process data layer input_name, input_dim, layers = _get_input(proto) # only support single input, so always use `data` as the input data mapping = {input_nam...
python
def require_attribute_value( self, attribute: str, value: Union[int, str, float, bool, None]) -> None: """Require an attribute on the node to have a particular value. This requires the attribute to exist, and to have the given value \ and corresponding type. Handy for in...
java
public String encodeURL(String url) { // should not encode if cookies in evidence if (_servletHttpRequest==null || _servletHttpRequest.isRequestedSessionIdFromCookie() && _servletHttpRequest.getServletHandler().isUsingCookies()) return url; ...
java
protected boolean isSubsetContainedIn(Set<String> selectedListItems, Set<String> distinctFacetValues) { boolean isPresent = false; for (String selectedListItem : selectedListItems) { isPresent = distinctFacetValues.contains(selectedListItem); } return isPresent; }
python
def get_triplets_at_q(grid_point, mesh, point_group, # real space point group of space group reciprocal_lattice, # column vectors is_time_reversal=True, swappable=True, stores_triplets_m...
java
public void putField(VariableElement field) throws IOException { if (field.getModifiers().contains(Modifier.STATIC)) { throw new IllegalArgumentException(field+" is static"); } int index = subClass.resolveFieldIndex(field); putfield(index); }
python
def configure_discord_logger( self, discord_webhook=None, discord_recipient=None, log_level='ERROR', log_format=ReportingFormats.PRETTY_PRINT.value, custom_args='' ): """logger for sending messages to Discord. Easy way to alert humans ...
java
@Override protected void closeConnection(Object connection) { try { if (qSession!=null) qSession.close(); if (qConnection!=null) qConnection.close(); } catch (Exception e) { } qSession = null; qConnection = null; }
python
def export(self): """ Run the export process Returns: (list of str): The path of the exported disks. """ if self._with_threads: utils.invoke_different_funcs_in_parallel( *map(lambda mgr: mgr.export, self._get_export_mgr()) ) ...
java
public ServiceFuture<LiveOutputInner> createAsync(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters, final ServiceCallback<LiveOutputInner> serviceCallback) { return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, a...
python
def explain_prediction_lightning(estimator, doc, vec=None, top=None, target_names=None, targets=None, feature_names=None, vectorized=False, coef_scale=None): """ Return an explanation of a lightning estimator predicti...
python
def fit(self, df, duration_col, event_col=None, weights_col=None, show_progress=False): """ Parameters ---------- Fit the Aalen Additive model to a dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns `duration_col` a...
java
public java.lang.String getErrorClass() { return (java.lang.String) getStateHelper().eval(PropertyKeys.errorClass); }
python
def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. Blank list if unsupported. ''' preview = embedded_preview(src_path) if not is_valid_preview(preview): preview = generator_preview(src_path) if not is_valid_preview(...
python
def read_long(self, base, offset=0): """ Return the int value of the four bytes at the file position defined by self._base_offset + *base* + *offset*. If *base* is None, the long is read from the current position in the stream. The endian setting of this instance is used to inter...
java
protected boolean checkConnection() { try{ super.checkConnection(); } finally { if (_jarConnection==null) { _entry=null; _file=null; _jarFile=null; _list=null; } } ...
python
def serialize(self, cls, record): """ Serialize the record to JSON. cls unused in this implementation. >>> s = teststore() >>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'}) '{"id": "1", "name": "Toto"}' """ return json.dumps(record, cls=self.encoder)
java
@Override public WxResp template_api_set_industry(String industry_id1, String industry_id2) { return postJson("/template/api_set_industry", "industry_id1", industry_id1, "industry_id2", industry_id2); }
python
def get_docstr_list(red): """Find all triple-quoted docstrings in module.""" docstr_list = [] for n in red.find_all("string"): if n.value.startswith('"""'): docstr_list.append(n) return docstr_list
python
def get(self): """ Constructs a WorkflowCumulativeStatisticsContext :returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumul...
java
public boolean isCompatible(Interval interval){ return interval.getStart() >= getBasicInterval().getStart() && interval.getStart() < getBasicInterval().getEnd(); }
python
def _profile(self, frame, event, arg): """The callback function to register by :func:`sys.setprofile`.""" # c = event.startswith('c_') if event.startswith('c_'): return time1 = self.timer() frames = self.frame_stack(frame) if frames: frames.pop() ...
python
def get_random_sequences(self, n=10, length=200, chroms=None, max_n=0.1): """Return random genomic sequences. Parameters ---------- n : int , optional Number of sequences to return. length : int , optional Length of sequences to return. chroms :...
java
public static <T> FibonacciHeap<T> merge(FibonacciHeap<T> one, FibonacciHeap<T> two) { /* Create a new FibonacciHeap to hold the result. */ FibonacciHeap<T> result = new FibonacciHeap<T>(); /* Merge the two Fibonacci heap root lists together. This helper function * also computes the m...
python
def shap_interaction_values(self, X, y=None, tree_limit=None): """ Estimate the SHAP interaction values for a set of samples. Parameters ---------- X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost) A matrix of samples (# samples x # features) on which to expl...
python
def _tweak_lane(lane_details, dname): """Potentially tweak lane information to handle custom processing, reading a lane_config.yaml file. """ tweak_config_file = os.path.join(dname, "lane_config.yaml") if os.path.exists(tweak_config_file): with open(tweak_config_file) as in_handle: t...
python
def setup(self, mujoco_objects, table_top_offset, table_size): """ Args: Mujoco_objcts(MujocoObject * n_obj): object to be placed table_top_offset(float * 3): location of table top center table_size(float * 3): x,y,z-FULLsize of the table """ self.mujo...
java
public SetData set(String path, String data) { SetData command = new SetData(); command.path(path); command.data(data); command.version(0); action.setCommand(command); return command; }
java
public void export(DatabaseMetaData md) throws SQLException { if (beanPackageName == null) { beanPackageName = module.getPackageName(); } if (beansTargetFolder == null) { beansTargetFolder = targetFolder; } module.bind(SQLCodegenModule.BEAN_PACKAGE_NAME, ...
python
def _prepare_output(partitions, unavailable_brokers, verbose): """Returns dict with 'raw' and 'message' keys filled.""" partitions_count = len(partitions) out = {} out['raw'] = { 'replica_unavailability_count': partitions_count, } if partitions_count == 0: out['message'] = 'All ...
python
def _parse_splits(patch, splits): """ Parse splits string to get list of all associated subset strings. Parameters ---------- patch : obj Patch object containing data to subset splits : str Specifies how a column of a dataset should be split. See Notes. Returns ------- ...
python
def __set_labels(self, labels): """ Add a label on the document. """ with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \ as file_desc: for label in labels: file_desc.write("%s,%s\n" % (label.name, ...