language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_dataset(self, key, info): """Load a dataset.""" if self._polarization != key.polarization: return logger.debug('Reading %s.', key.name) if key.name in ['longitude', 'latitude']: logger.debug('Constructing coordinate arrays.') if self.lons is...
java
public final <T> Class<T> getParameterizedClassArgumentByIndex(int index) { List<Class<?>> list = getParameterizedClassArguments(); if (index > list.size() - 1 || index < 0) { String message = "index %s is out of bounds. Should be within [0, %s]"; throw new IndexOutOfBoundsExcept...
java
public void init(BaseMessageReceiver messageHandler, Record record, BaseMessageFilter messageFilter) { super.init(messageHandler, messageFilter); // This will remove this listener on close. m_record = record; m_record.addListener(m_closeOnFreeBehavior = new FreeOnFreeHandler(this)); }
java
private void join(Iterator<RaftMemberContext> iterator) { if (iterator.hasNext()) { cancelJoinTimer(); joinTimeout = raft.getThreadContext().schedule(raft.getElectionTimeout().multipliedBy(2), () -> { join(iterator); }); RaftMemberContext member = iterator.next(); log.debug("...
python
def import_from_xls( filename_or_fobj, sheet_name=None, sheet_index=0, start_row=None, start_column=None, end_row=None, end_column=None, *args, **kwargs ): """Return a rows.Table created from imported XLS file.""" source = Source.from_file(filename_or_fobj, mode="rb", plugin...
java
private void parseLiteral() { AtomicValue atomic; if (mToken.getType() == TokenType.VALUE || mToken.getType() == TokenType.POINT) { // is numeric literal atomic = parseIntegerLiteral(); } else { // is string literal assert (mToken.getType() == To...
java
public InputStream getIndexFile(String filePath) throws RepositoryException { try { return new RemoteInputStream(filePath); } catch (SecurityException e) { throw new RepositoryException(e); } catch (RPCException e) { throw new RepositoryExcep...
java
public Proxy setPort( int port ) { if ( this.port == port ) { return this; } return new Proxy( type, host, port, auth ); }
python
def most_recent_common_ancestor(self, *ts): """Find the MRCA of some tax_ids. Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if no ancestor of the specified tax_ids could be found. """ if len(ts) > 200: res = self._large_mrca(ts) else: ...
java
protected OutputStream getFilterOutput() { OutputStream target = getTarget(); return target == null? System.out : target; }
java
public final void mOR_ASSIGN() throws RecognitionException { try { int _type = OR_ASSIGN; int _channel = DEFAULT_TOKEN_CHANNEL; // src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:176:5: ( '|=' ) // src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:176:7: '|=' { match("|="); if (state.f...
java
protected static String valueToString(Object value) throws JSONException { if (value == null || value instanceof JSONNull) { return "null"; } if (value instanceof JSONString) { try { return ((JSONString) value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } }...
python
def print_tree(self, tree=None): """ Print referrers tree to console. keyword arguments tree -- if not None, the passed tree will be printed. Otherwise it is based on the rootobject. """ if tree is None: self._print(self.root, '', '') else: ...
java
@Override public void filter(ContainerRequestContext incomingRequestContext) throws IOException { String methodName = "filter(incoming)"; Tracer tracer = OpentracingTracerManager.getTracer(); if (tracer == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) ...
python
def delete(self): """Remove the activation from the agenda.""" if lib.EnvDeleteActivation(self._env, self._act) != 1: raise CLIPSError(self._env) self._env = None
java
public static Slice trim(Slice utf8, int[] whiteSpaceCodePoints) { int start = firstNonMatchPosition(utf8, whiteSpaceCodePoints); int end = lastNonMatchPosition(utf8, start, whiteSpaceCodePoints); return utf8.slice(start, end - start); }
java
protected boolean detectRejection(HttpServletRequest request) { Set<?> parameterKeys = request.getParameterMap().keySet(); if ((parameterKeys.size() == 1) && (parameterKeys.contains("state"))) { return false; } return parameterKeys.size() > 0 && !parameterKeys.contains("oauth_token") && !parameterKey...
python
def create_path(path, is_dir=False): """ Check if path exists, if not create it :param path: path or file to create directory for :param is_dir: pass True if we are passing in a directory, default = False :return: os safe path from `path` """ path = norm_path(path) path_check = path ...
python
def predict_in_sample(self, exogenous=None, start=None, end=None, dynamic=False): """Generate in-sample predictions from the fit ARIMA model. This can be useful when wanting to visualize the fit, and qualitatively inspect the efficacy of the model, or when wanting to co...
java
public LoggingFraction consoleHandler(Level level, String formatter) { consoleHandler(new ConsoleHandler(CONSOLE) .level(level) .namedFormatter(formatter)); return this; }
java
public static Properties flatten(Properties values) { Properties result = new Properties(); Object key = null; Set<String> propertyNames = values.stringPropertyNames(); for (String propertyName : propertyNames) { result.setProperty(propertyName, values.getProperty(propertyName)); } return result...
java
public static XpathEvaluator compileNoError(String xpathStr) { try { return compile(xpathStr); } catch (XpathSyntaxErrorException e) { throw new IllegalStateException("parse xpath \"" + xpathStr + "\" failed", e); } }
java
public void tableEntry(CodeBuilder mv) { mv.visitLocalVariable( variableName(), resultType().getDescriptor(), null, // no generic signature start(), end(), index()); }
python
def _make_hyperparameter_decode_func(locked_values, meta_parameters): """Create a function that converts the binary solution to parameters.""" # Locked parameters are also returned by decode function, but are not # based on solution def decode(solution): """Convert solution into dict of hyperp...
python
def apply_payoff(self): """Apply the payoff that has been accumulated from immediate reward and/or payments from successor match sets. Attempting to call this method before an action has been selected or after it has already been called for the same match set will result in a Val...
java
@Override public final int[] selectChannels(SerializationDelegate<T> record, int numberOfChannels) { switch (strategy) { case FORWARD: case PARTITION_RANDOM: return robin(numberOfChannels); case PARTITION_HASH: case PARTITION_LOCAL_HASH: return hashPartitionDefault(record.getInstance(), numberOfChannel...
python
def convert_to_sqlite(self, destination=None, method="shell", progress=False): """Who wants to use Access when you can deal with SQLite databases instead?""" # Display progress bar # if progress: progress = tqdm.tqdm else: progress = lambda x:x # Default path # if ...
python
def fetch(clobber=False): """ Downloads the IPHAS 3D dust map of Sale et al. (2014). Args: clobber (Optional[bool]): If ``True``, any existing file will be overwritten, even if it appears to match. If ``False`` (the default), ``fetch()`` will attempt to determine if the data...
java
public static void copyFile(String fromFilename, String toFilename) throws IOException { copyFile(new File(fromFilename), new File(toFilename)); }
java
public static String ordinalize(int number){ int modulo = number%100; if(modulo>=11 && modulo<=13) return number+"th"; switch(number%10){ case 1: return number+"st"; case 2: return number+"nd"; case 3: ...
java
public static <R> FuncN<Observable<R>> toAsync(FuncN<? extends R> func) { return toAsync(func, Schedulers.computation()); }
python
def t_surf_parameter(self, num_frame, xax): """ Surface parameter evolution as a function of time or model. Parameters ---------- num_frame : integer Number of frame to plot this plot into. xax : string Either model or time to indicate what is to ...
java
public TerminalSize withRows(int rows) { if(this.rows == rows) { return this; } if(rows == 0 && this.columns == 0) { return ZERO; } return new TerminalSize(this.columns, rows); }
python
def sample_parameter_values(self, parameter, start=None, stop=None, sample_count=500, parameter_cache='realtime', source='ParameterArchive'): """ Returns parameter samples. The query range is split in sample intervals of equal leng...
java
public static void register(final MBeanServer mbs, final Object obj) { final ObjectName mBeanName = JmxUtils.getObjectName(obj.getClass()); try { mbs.registerMBean(obj, mBeanName); } catch (final InstanceAlreadyExistsException e) { ...
java
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) throws IOException { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } if (valueCount <= 0) { throw new IllegalArgumentException("valueCount <= 0"); } // If a bkp ...
python
def sapm_effective_irradiance(poa_direct, poa_diffuse, airmass_absolute, aoi, module, reference_irradiance=1000): """ Calculates the SAPM effective irradiance using the SAPM spectral loss and SAPM angle of incidence loss functions. Parameters ---------- poa_direct ...
java
public Nfs3ReadlinkResponse getReadlink(NfsReadlinkRequest request) throws IOException { Nfs3ReadlinkResponse response = new Nfs3ReadlinkResponse(); _rpcWrapper.callRpcNaked(request, response); return response; }
java
private void finalizeRecord() { myPage.setVal(currentPos, new IntegerConstant(getLastRecordPosition())); setPreviousNextRecordPosition(currentPos + pointerSize); setLastRecordPosition(currentPos); currentPos += pointerSize; setNextRecordPosition(currentPos); // leave for next pointer currentPos +...
java
public synchronized void setJsonMode() { myOptions.blobAsString = true; myOptions.clobAsString = true; myOptions.datagramAsList = true; myOptions.decimalAsFloat = true; myOptions.sexpAsList = true; myOptions.skipAnnotations = true; myO...
java
public Observable<RedisResourceInner> createAsync(String resourceGroupName, String name, RedisCreateParameters parameters) { return createWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() { @Override pub...
python
def write(self, data): """Sendall for non-blocking sockets.""" bytes_sent = 0 data_mv = memoryview(data) payload_size = len(data_mv) while bytes_sent < payload_size: try: bytes_sent += self.send( data_mv[bytes_sent:bytes_sent + SOCK...
python
def parse_string(xml): """ Returns a slash-formatted string from the given XML representation. The return value is a TokenString (for MBSP) or TaggedString (for Pattern). """ string = "" # Traverse all the <sentence> elements in the XML. dom = XML(xml) for sentence in dom(XML_SENTENCE): ...
python
def _multiline_width(multiline_s, line_width_fn=len): """Visible width of a potentially multiline content.""" return max(map(line_width_fn, re.split("[\r\n]", multiline_s)))
python
def get_add_link(self): """ Appends the popup=1 query string to the url so the destination url treats it as a popup. """ url = super(TaggedRelationWidget, self).get_add_link() if url: qs = self.get_add_qs() if qs: url = "%s&%s" % (...
java
@Override public EClass getIfcMassPerLengthMeasure() { if (ifcMassPerLengthMeasureEClass == null) { ifcMassPerLengthMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(837); } return ifcMassPerLengthMeasureEClass; }
java
public void setIgnoreEMail(String serverName, String ignoreEMail) { if (serverName != null) { if (ignoreEMail != null) { ignoreEMails.put(serverName, ignoreEMail); } else { ignoreEMails.remove(serverName); } } }
python
def match_process(pid, name, cmdline, exe, cfg): """ Decides whether a process matches with a given process descriptor :param pid: process pid :param exe: process executable :param name: process name :param cmdline: process cmdline :param cfg: the dictionary from processes that describes wi...
java
public static final int argb_fromNormalized(final double a, final double r, final double g, final double b){ return argb_bounded((int)Math.round(a*0xff), (int)Math.round(r*0xff), (int)Math.round(g*0xff), (int)Math.round(b*0xff)); }
java
public void setUnicodeFileName(String filename, boolean unicode) { put(PdfName.UF, new PdfString(filename, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING)); }
python
def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN) self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN) self._client = n_rpc.get_client(self.target) self._consumers.extend([ [topics...
java
public final <U3> Tuple4<T1, T2, U3, T4> map3(Function<? super T3, ? extends U3> function) { return Tuple.tuple(v1, v2, function.apply(v3), v4); }
python
def __cnc(cls, calib, we_c): """ Compute cnc from weC """ if we_c is None: return None offset_v = calib.pid_elc_mv / 1000.0 response_c = we_c - offset_v # remove electronic zero cnc = response_c / calib.pid_sens_mv # pid_sens_mv...
java
public Map<String, Boolean> getExistsResource() { if (m_existsResource == null) { // create lazy map only on demand m_existsResource = CmsCollectionsGenericWrapper.createLazyMap(new CmsExistsResourceTransformer()); } return m_existsResource; }
java
public JFrame displayChartMatrix() { // Create and set up the window. final JFrame frame = new JFrame(windowTitle); // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater( new Runnable() { @Overr...
java
protected List<WorkUnit> getPreviousWorkUnitsForRetry(SourceState state) { List<WorkUnit> workUnits = Lists.newArrayList(); for (WorkUnitState workUnitState : getPreviousWorkUnitStatesForRetry(state)) { // Make a copy here as getWorkUnit() below returns an ImmutableWorkUnit workUnits.add(WorkUnit.co...
java
public static DayOfYear now(Clock clock) { final LocalDate now = LocalDate.now(clock); // called once return DayOfYear.of(now.getDayOfYear()); }
java
public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{ hanode_routemonitor_binding obj = new hanode_routemonitor_binding(); obj.set_id(id); hanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service); return response; }
python
def _get_elementwise_name_from_keras_layer(keras_layer): """ Get the keras layer name from the activation name. """ mode = keras_layer.mode if mode == 'sum': return 'ADD' elif mode == 'mul': return 'MULTIPLY' elif mode == 'concat': if len(keras_layer.input_shape[0]) =...
java
public JcBoolean asBoolean() { JcBoolean ret = new JcBoolean(null, this, null); QueryRecorder.recordInvocationConditional(this, "asBoolean", ret); return ret; }
java
public void setTranEnlistmentNotNeeded(int reason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "MEF.setTranEnlistmentNotNeeded for enterprise class " + beanMetaData.enterpriseBeanName + ", reason = " + reason); } ...
python
def unpack(self, buff, offset=0): """Unpack *buff* into this object. Do nothing, since the _length is already defined and it is just a Pad. Keep buff and offset just for compability with other unpack methods. Args: buff (bytes): Binary buffer. offset (int): Wher...
python
def _run_program(self, bin, fastafile, params=None): """ Run MEME and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, op...
java
public static void rotateImage(File input, File output, String format, int degrees) throws IOException { BufferedImage inputImage = ImageIO.read(input); Graphics2D g = (Graphics2D) inputImage.getGraphics(); g.drawImage(inputImage, 0, 0, null); AffineTransform at = n...
python
def getMaxAge(self): "get the max-age in seconds from the saved headers data" max_age = 0 cache_control = self.headers.get('cache-control') if cache_control: params = dict(urlparse.parse_qsl(cache_control)) max_age = int(params.get('max-age', '0')) return ...
python
def get_all_regions(db_connection): """ Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_regions, '_results'): sql = 'CALL get_all_regions();' results = execute_sql(sql, db_connection) ...
python
def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT): """ Create a track object from an Echo Nest track ID. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: identifier: A string containing the ID of a previously analyzed track. ...
java
public static final byte[] getISOBytes(String text) { if (text == null) return null; int len = text.length(); byte b[] = new byte[len]; for (int k = 0; k < len; ++k) b[k] = (byte)text.charAt(k); return b; } /** * Let the writer know that all writ...
python
def begin_stream(self, command: Command) -> Reply: '''Start sending content on the data stream. Args: command: A command that tells the server to send data over the data connection. Coroutine. Returns: The begin reply. ''' yield from...
java
public static CommerceTaxMethod fetchByG_A_First(long groupId, boolean active, OrderByComparator<CommerceTaxMethod> orderByComparator) { return getPersistence() .fetchByG_A_First(groupId, active, orderByComparator); }
python
def pending_assignment(self): """Return the pending partition assignment that this state represents.""" return { self.partitions[pid].name: [ self.brokers[bid].id for bid in self.replicas[pid] ] for pid in set(self.pending_partitions) }
java
public void delete(URI path, boolean recursive) throws IOException { Preconditions.checkNotNull(path, "path can not be null"); checkArgument(!path.equals(GCS_ROOT), "Cannot delete root path (%s)", path); logger.atFine().log("delete(%s, %s)", path, recursive); FileInfo fileInfo = getFileInfo(path); ...
java
public boolean isAncestorOf(ConfigurationPropertyName name) { Assert.notNull(name, "Name must not be null"); if (this.getNumberOfElements() >= name.getNumberOfElements()) { return false; } return elementsEqual(name); }
python
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: ...
java
@SuppressWarnings("static-method") protected XExpression _generate(SarlBreakExpression breakStatement, IAppendable it, IExtraLanguageGeneratorContext context) { if (context.getExpectedExpressionType() == null) { it.append("break"); //$NON-NLS-1$ } else { it.append("return ").append(toDefaultValue(context.get...
python
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
python
def textForSaving(self): """Get text with correct EOL symbols. Use this method for saving a file to storage """ lines = self.text.splitlines() if self.text.endswith('\n'): # splitlines ignores last \n lines.append('') return self.eol.join(lines) + self.eol
python
def validate(self, input_string): """ Validate input_string against a regex pattern :return: True if match / False otherwise """ validation_result = False try: validation_result = bool(match(pattern=self.pattern, string=input_string)) except TypeError...
java
public static long addMonths(long timestamp, int m) { final long millis = DateTimeUtils.floorMod(timestamp, DateTimeUtils.MILLIS_PER_DAY); timestamp -= millis; final long x = addMonths((int) (timestamp / DateTimeUtils.MILLIS_PER_DAY), m); return x * DateTimeUtils.MILLIS_PER_DAY + millis; }
python
def state_estimation_ensemble(data, k, n_runs=10, M_list=[], **se_params): """ Runs an ensemble method on the list of M results... Args: data: genes x cells array k: number of classes n_runs (optional): number of random initializations of state estimation M_list (optional): ...
java
void addNewKey(Object key) { ensureRoom(buildKeyPosition + 1); buildKeys[buildKeyPosition++] = updateFunction.apply(key); }
python
def language_create(name, maintenance_db, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 Installs a language into a database CLI Example:...
java
public Optional<MapperInstance> getKeyDeserializer( JType type ) { return Optional.fromNullable( keyDeserializers.get( type.getQualifiedSourceName() ) ); }
java
public SDVariable get(SDIndex... indices) { int ndims = indices.length; long[] begin = new long[ndims]; long[] end = new long[ndims]; long[] strides = new long[ndims]; int[] begin_mask_arr = new int[ndims]; int[] end_mask_arr = new int[ndims]; int[] shrink_axis_ma...
java
public void setClassPath(String classpath) { this.classpath = new ArrayList<>(); for (final String path : Strings.split(classpath, Pattern.quote(File.pathSeparator))) { this.classpath.add(normalizeFile(path)); } }
python
def handle_token(cls, parser, token): """Class method to parse get_comment_list/count/form and return a Node.""" tokens = token.contents.split() if tokens[1] != 'for': raise template.TemplateSyntaxError( "Second argument in %r tag must be 'for'" % tokens[0] ...
python
def _update(self, resource, update_dict=None, params=None, **kwargs): """Update the object.""" url = self._client._build_url(resource, **kwargs) response = self._client._request('PUT', url, json=update_dict, params=params) if response.status_code != requests.codes.ok: # pragma: no cove...
java
public static <F, S> TryType<F, S> success( final S x) { return Success.success(x); }
java
public MFSIP placeMFSIP(String tradingsymbol, String frequency, int installmentDay, int instalments, int initialAmount, double amount) throws KiteException, IOException, JSONException { Map<String, Object> params = new HashMap<String, Object>(); params.put("tradingsymbol", tradingsymbol); params...
python
def compute_layer(cls, data, params, layout): """ Calculate statistics for this layers This is the top-most computation method for the stat. It does not do any computations, but it knows how to verify the data, partition it call the next computation method and merge resu...
python
def putCallback(self,url,headers=""): ''' Set the callback URL. To be used in place of LongPolling when deploying a webapp. **note**: make sure you set up a callback URL in your web app :param str url: complete url, including port, where the callback url is located :param str headers: Optional - Headers...
java
@Override public CreateSnapshotResult createSnapshot(CreateSnapshotRequest request) { request = beforeClientExecution(request); return executeCreateSnapshot(request); }
java
public void reportFailure(E failureException) { assert failureException != null; connectionLock.lock(); try { state = State.Failure; this.failureException = failureException; condition.signalAll(); } finally { connectionLock.unlock(...
java
public void severe(String mesg, Throwable t) { log(Level.SEVERE, mesg, t); }
java
private Queue<QueueElem> getInstanceSplitList(final AbstractInstance instance) { Queue<QueueElem> instanceSplitList = this.instanceMap.get(instance); if (instanceSplitList == null) { // Create and populate instance specific split list instanceSplitList = new PriorityQueue<FileInputSplitList.QueueElem>(); ...
java
public Account getAccountByName(String accountName) { if (accountName != null) { for (Account account : getAccounts()) { if (accountName.equals(account.name)) { return account; } } } return null; }
java
public static ObjectInfo getObjectInfo(Class c) { ObjectInfo info = cachedClassInfoMap.get(c); if (info == null) { synchronized (c) { info = new ObjectInfo(c); cachedClassInfoMap.put(c, info); } } return info; }
java
public static List<String> readLines(InputStream stream, String charset) throws IOException { return readLines(newReader(stream, charset)); }
java
private DateTime resolveDateTime(FunctionRef fun) { final DateTime dt = of.createDateTime(); DateTimeInvocation.setDateTimeFieldsFromOperands(dt, fun.getOperand()); builder.resolveCall("System", "DateTime", new DateTimeInvocation(dt)); return dt; }
java
@Override protected boolean canHighlight(final Component component, final ComponentAdapter adapter) { return component instanceof IconAware || component instanceof JLabel; }