language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _process_cell(i, state, finite=False): """Process 3 cells and return a value from 0 to 7. """ op_1 = state[i - 1] op_2 = state[i] if i == len(state) - 1: if finite: op_3 = state[0] else: op_3 = 0 else: op_3 = state[i + 1] result = 0 for i, ...
java
public Collection<ID> getIds(final WebQuery constraints) { return (Collection<ID>) find(constraints, JPASearchStrategy.ID).getList(); }
python
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: ...
python
def read_until(data: bytes, *, return_tail: bool = True, from_=None) -> bytes: """ read until some bytes appear """ return (yield (Traps._read_until, data, return_tail, from_))
python
def partition(src, key=None): """No relation to :meth:`str.partition`, ``partition`` is like :func:`bucketize`, but for added convenience returns a tuple of ``(truthy_values, falsy_values)``. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) >>> nonempty ['hi', 'bye'] *key* defaul...
java
@Override public boolean validateObject(SocketAddress key, DatagramSocket socket) { return socket.isBound() && !socket.isClosed() && socket.isConnected(); }
python
def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=True): """The internal reply getter function. DO NOT CALL THIS YOURSELF. :param str user: The user ID as passed to ``reply()``. :param str msg: The formatted user message. :param str context: The repl...
java
public String getBrowserBasedAuthenticationMechanism() { if (m_useBrowserBasedHttpAuthentication) { return AUTHENTICATION_BASIC; } else if (m_browserBasedAuthenticationMechanism != null) { return m_browserBasedAuthenticationMechanism; } else if (m_formBasedHttpAuthentica...
python
def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int: """ For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT`` variable (see e.g. https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017). Returns ``None`` if it ...
java
public boolean addCassandraHost(CassandraHost cassandraHost) { Properties props = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, getPersistenceUnit()) .getProperties(); String keyspace = null; if (externalProperties != null) { ke...
java
public static String bytesToString(byte[] bytes, int offset, int length) { return new String(bytes, offset, length, UTF8_CHARSET); }
java
public TenantDefinition searchForTenant(TenantFilter filter) { checkServiceState(); for (TenantDefinition tenantDef : getAllTenantDefs().values()) { if (filter.selectTenant(tenantDef)) { return tenantDef; } } return null; }
python
def resolve_config_file_path(self, config_filepath): """ Determines whether given path is valid, and if so uses it. Otherwise searches both the working directory and nomenclate/core for the specified config file. :param config_filepath: str, file path or relative file name within package ...
java
public IfcSoundScaleEnum createIfcSoundScaleEnumFromString(EDataType eDataType, String initialValue) { IfcSoundScaleEnum result = IfcSoundScaleEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.get...
python
def _from_dict(cls, _dict): """Initialize a Classifier object from a json dictionary.""" args = {} if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: raise ValueError( 'Required property \'classifier_id\' not pres...
python
def sha(self): """Return sha, lazily compute if not done yet.""" if self._sha is None: self._sha = compute_auth_key(self.userid, self.password) return self._sha
java
public void logFirstSelectQueryForCurrentThread() { String firstSelectQuery = getSelectQueriesForCurrentThread() .stream() .findFirst() .map(CircularQueueCaptureQueriesListener::formatQueryAsSql) .orElse("NONE FOUND"); ourLog.info("First select Query:\n{}", firstSelectQuery); }
java
private void publishFileSet(CopyEntity.DatasetAndPartition datasetAndPartition, Collection<WorkUnitState> datasetWorkUnitStates) throws IOException { Map<String, String> additionalMetadata = Maps.newHashMap(); Preconditions.checkArgument(!datasetWorkUnitStates.isEmpty(), "publishFileSet received ...
java
public byte[] getMemberData(String memberId) throws ZooKeeperConnectionException, KeeperException, InterruptedException { return zkClient.get().getData(getMemberPath(memberId), false, null); }
python
def split_filename(name): """ Splits the filename into three parts: the name part, the hash part, and the extension. Like with the extension, the hash part starts with a dot. """ parts = hashed_filename_re.match(name).groupdict() return (parts['name'] or '', parts['hash'] or '', parts['ext'] or...
python
def check_roles(self, account, aws_policies, aws_roles): """Iterate through the roles of a specific account and create or update the roles if they're missing or does not match the roles from Git. Args: account (:obj:`Account`): The account to check roles on aws_policies ...
java
public static <K1, V1, K2, V2> void addMapper(JobConf job, Class<? extends Mapper<K1, V1, K2, V2>> klass, Class<? extends K1> inputKeyClass, Class<? extends V1> inputValueClass, Class<? extends K2> outputKeyClass...
python
def input_fn(dataset, filepattern, skip_random_fraction_when_training, batch_size_means_tokens_param, batch_size_multiplier, max_length, mode, hparams, data_dir=None, params=None, config=Non...
java
private int loadTable(long uuid) throws IOException { int bufferIndex = -1; Set<Long> uuids = null; // Always attempt to append to the last block first. int blockIndex = _blocks.size() - 1; TableBlock lastBlock = _blocks.get(blockIndex); // Even though this ...
python
def rmon_alarm_entry_alarm_owner(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon") alarm_entry = ET.SubElement(rmon, "alarm-entry") alarm_index_key = ET.SubElement(alar...
java
public void init(final Connection connection, final String host, final String port) throws DevFailed { connection.url = new TangoUrl(buildUrlName(TangoUrl.getCanonicalName(host), port)); connection.setDevice_is_dbase(true); connection.transparent_reconnection = true; // Always true for Database ApiUtil.g...
java
public static <E> List<E> buildList(Iterable<E> iterable) { return StreamSupport.stream(iterable.spliterator(), false) .collect(toList()); }
java
public String convertIndexToString(int index) { String tempString = null; if ((index >= 0) && (index <= 9)) { char value[] = new char[1]; value[0] = (char)('0' + index); tempString = new String(value); // 1 = '1'; 2 = '2'; etc... } ...
python
def visit_ImportFrom(self, node): """ Register imported modules and usage symbols. """ module_path = tuple(node.module.split('.')) self.imports.add(module_path[0]) for alias in node.names: path = module_path + (alias.name,) self.symbols[alias.asname or alias.name...
java
@Override public void enterGraph(GDLParser.GraphContext graphContext) { inGraph = true; String variable = getVariable(graphContext.header()); Graph g; if (variable != null && userGraphCache.containsKey(variable)) { g = userGraphCache.get(variable); } else { g = initNewGraph(graphContex...
python
def set_proxy(proxy_url, transport_proxy=None): """Create the proxy to PyPI XML-RPC Server""" global proxy, PYPI_URL PYPI_URL = proxy_url proxy = xmlrpc.ServerProxy( proxy_url, transport=RequestsTransport(proxy_url.startswith('https://')), allow_none=True)
java
public UpdateForClause in(String variable, String path) { Expression in = x(variable + " IN " + path); vars.add(in); return this; }
python
def set(ctx, key, value): """ Set configuration parameters """ if key == "default_account" and value[0] == "@": value = value[1:] ctx.bitshares.config[key] = value
python
def current_spi_to_number(self): """ Convert subpage & subitem to a integer * if page == 1, then return 0, since the item count is the true # of items * if page == 2, then return, page-1 * items_per_page, since we are returning the # of items on a full page. Args: * None Ret...
python
def run(self) -> Generator[Tuple[int, int, str, type], None, None]: """ Runs the checker. ``fix_file()`` only mutates the buffer object. It is the only way to find out if some error happened. """ if self.filename != STDIN: buffer = StringIO() opti...
java
protected final PrcCsvSampleDataRow lazyGetPrcCsvSampleDataRow( final Map<String, Object> pAddParam) throws Exception { String beanName = PrcCsvSampleDataRow.class.getSimpleName(); @SuppressWarnings("unchecked") PrcCsvSampleDataRow proc = (PrcCsvSampleDataRow) this.processorsMap.get(beanName...
python
def random_get_int(rnd: Optional[tcod.random.Random], mi: int, ma: int) -> int: """Return a random integer in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. lo...
java
public static void main(String[] args) throws Exception { SAXProcessor sp = new SAXProcessor(); // data // double[] dat = TSProcessor.readFileColumn(DAT_FNAME, 1, 0); // TSProcessor tp = new TSProcessor(); // double[] dat = tp.readTS("src/resources/dataset/asys40.txt", 0); // double[] dat ...
java
@Override public List<XMLObject> getOrderedChildren() { ArrayList<XMLObject> children = new ArrayList<XMLObject>(); if (this.schemeInformation != null) { children.add(this.schemeInformation); } children.addAll(this.metadataLists); if (this.distributionPoints != null) { children.add(thi...
python
def get_compute(self, compute_id): """ Returns a compute server or raise a 404 error. """ try: return self._computes[compute_id] except KeyError: if compute_id == "vm": raise aiohttp.web.HTTPNotFound(text="You try to use a node on the GNS3 ...
java
private static boolean isUnM49AreaCode(String code) { if (code.length() != 3) { return false; } for (int i = 0; i < 3; ++i) { final char character = code.charAt(i); if (!(character >= '0' && character <= '9')) { return false; } ...
python
def is_java_project(self): """ Indicates if the project's main binary is a Java Archive. """ if self._is_java_project is None: self._is_java_project = isinstance(self.arch, ArchSoot) return self._is_java_project
python
def setDeclaration(self, declaration): """ Set the declaration this model will use for rendering the the headers. """ assert isinstance(declaration.proxy, ProxyAbstractItemView), \ "The model declaration must be a QtAbstractItemView subclass. " \ "Got {]...
python
def tile_x_size(self, zoom): """ Width of a tile in SRID units at zoom level. - zoom: zoom level """ warnings.warn(DeprecationWarning("tile_x_size is deprecated")) validate_zoom(zoom) return round(self.x_size / self.matrix_width(zoom), ROUND)
java
public void trustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) { if (trustCallback == null) { throw new IllegalStateException("No TrustCallback set."); } trustCallback.setTrust(device, fingerprint, TrustState.trusted); }
java
@Beta @CheckReturnValue public final FluentIterable<E> append(E... elements) { return from(Iterables.concat(iterable, Arrays.asList(elements))); }
python
def tange_pth(v, temp, v0, gamma0, a, b, theta0, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for the Tange equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen ...
java
private void initializeRequestHandler(ResponseBuilder rb) { if (requestHandler == null) { // try to initialize for (Entry<String, SolrInfoBean> entry : rb.req.getCore().getInfoRegistry().entrySet()) { if (entry.getValue() instanceof MtasRequestHandler) { requestHandlerName = entry.getKey(); reques...
java
public static base_response update(nitro_service client, aaakcdaccount resource) throws Exception { aaakcdaccount updateresource = new aaakcdaccount(); updateresource.kcdaccount = resource.kcdaccount; updateresource.keytab = resource.keytab; updateresource.realmstr = resource.realmstr; updateresource.delegate...
java
private void uninstallWindowListeners(JRootPane root) { if (window != null) { window.removeMouseListener(mouseInputListener); window.removeMouseMotionListener(mouseInputListener); } }
python
def _align_hydrogen_atoms(mol1, mol2, heavy_indices1, heavy_indices2): """ Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second mol...
java
public static Calendar getJavaCalendar(final double excelDate, final boolean use1904windowing) { if (isValidExcelDate(excelDate)) { int startYear = EXCEL_BASE_YEAR; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which // it isn't final int who...
java
public IServerInterceptor loggingInterceptor() { LoggingInterceptor retVal = new LoggingInterceptor(); retVal.setLoggerName("fhirtest.access"); retVal.setMessageFormat( "Path[${servletPath}] Source[${requestHeader.x-forwarded-for}] Operation[${operationType} ${operationName} ${idOrResourceName}] UA[${requestH...
python
def load(self): """ 加载会话信息 """ if not os.path.isfile(self.persist_file): return with open(self.persist_file, 'r') as f: cfg = json.load(f) or {} self.cookies = cfg.get('cookies', {}) self.user_alias = cfg.get('user_alias') or None ...
python
def writefile(openedfile, newcontents): """Set the contents of a file.""" openedfile.seek(0) openedfile.truncate() openedfile.write(newcontents)
python
def _AssignVar(self, matched, value): """Assigns variable into current record from a matched rule. If a record entry is a list then append, otherwise values are replaced. Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value. """ _value = self...
java
public static <T extends PropertyDispatcher> T getInstance(Class<T> cls, PropertySetterDispatcher dispatcher) { try { PropertyDispatcherClass annotation = cls.getAnnotation(PropertyDispatcherClass.class); if (annotation == null) { throw new ...
python
def send(self, msg, timeout=None): """ Send a message to NI-CAN. :param can.Message msg: Message to send :raises can.interfaces.nican.NicanError: If writing to transmit buffer fails. It does not wait for message to be ACKed currently. """ ...
python
def full_number(self): """ Returns the full number including the verification digit. :return: str """ return '{}{}'.format( ''.join(str(n) for n in self.numbers), ReceiptBarcodeGenerator.verification_digit(self.numbers), )
python
def sinusoid(freq, phase=0.): """ Sinusoid based on the optimized math.sin """ # When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14 # peak to peak. That's fairly enough. for n in modulo_counter(start=phase, modulo=2 * pi, step=freq): yield sin(n)
java
private static boolean isSimpleMode(Element element){ // simple mode is triggered through the marker css class 'o-simple-drag' return org.opencms.gwt.client.util.CmsDomUtil.getAncestor(element, "o-simple-drag")!=null; }
python
def find_metabolites_not_produced_with_open_bounds(model): """ Return metabolites that cannot be produced with open exchange reactions. A perfect model should be able to produce each and every metabolite when all medium components are available. Parameters ---------- model : cobra.Model ...
python
def _prepare_mock(context: 'torment.contexts.TestContext', symbol: str, return_value = None, side_effect = None) -> None: '''Sets return value or side effect of symbol's mock in context. .. seealso:: :py:func:`_find_mocker` **Parameters** :``context``: the search context :``symbol``: ...
python
def kunc_v(p, v0, k0, k0p, order=5, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at referen...
java
@JsonIgnore public Map<String, Object> getSettings() { if (settings == null) { settings = new LinkedHashMap<>(); } return settings; }
python
def _init_metadata(self): """stub""" super(EdXDragAndDropQuestionFormRecord, self)._init_metadata() QuestionTextFormRecord._init_metadata(self) QuestionFilesFormRecord._init_metadata(self)
java
public int get(Object o) { Integer n = indices.get(o); return n == null ? -1 : n.intValue(); }
java
public static void warn(Log log, String format, Object... arguments) { warn(log, null, format, arguments); }
python
def uri(self, context=None): """ :param dict context: keys that were missing in the static context given in constructor to resolve the butcket name. """ if context is None: context = self.context else: ctx = copy.deepcopy(self.context) ...
java
@Override public void visitMethod(Method obj) { state = State.SAW_NOTHING; iConst0Looped.clear(); stack.resetForMethodEntry(this); }
java
protected void addAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang); NameWithUpdate currentLabel = newLabels.get(lang); // If there isn't any label for that language, put the alias there ...
java
public ListAppResponse listApp(ListAppRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_APP); return invokeHttpClient(internalRequest, ListAppResponse.class); }
java
@SuppressWarnings({"ConstantConditions","deprecation"}) @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") public void addAction(@Nonnull Action a) { if(a==null) { throw new IllegalArgumentException("Action must be non-null"); } getActions().add(a); }
python
def date(self, field=None, val=None): """ Like datetime, but truncated to be a date only """ return self.datetime(field=field, val=val).date()
java
private JPanel getJPanel() { if (jPanel == null) { java.awt.GridBagConstraints gridBagConstraints7 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints5 = new GridBagConstraints(); gridBagConstraints5.gridwidth = 2; java.awt.GridBagC...
java
public Playlist withOutputKeys(String... outputKeys) { if (this.outputKeys == null) { setOutputKeys(new com.amazonaws.internal.SdkInternalList<String>(outputKeys.length)); } for (String ele : outputKeys) { this.outputKeys.add(ele); } return this; }
java
protected boolean containsRel100(Message message) { ListIterator<SIPHeader> requireHeaders = message.getHeaders(RequireHeader.NAME); if(requireHeaders != null) { while (requireHeaders.hasNext()) { if(REL100_OPTION_TAG.equals(requireHeaders.next().getValue())) { return true; } } } ListIterator...
java
public static CPDefinition fetchByCPTaxCategoryId_First( long CPTaxCategoryId, OrderByComparator<CPDefinition> orderByComparator) { return getPersistence() .fetchByCPTaxCategoryId_First(CPTaxCategoryId, orderByComparator); }
python
def overlay_gateway_loopback_id(self, **kwargs): """Configure Overlay Gateway ip interface loopback Args: gw_name: Name of Overlay Gateway <WORD:1-32> loopback_id: Loopback interface Id <NUMBER: 1-255> get (bool): Get config instead of editing config. (True, False)...
python
def is_registered(self, event_type, callback, details_filter=None): """Check if a callback is registered. :param event_type: event type callback was registered to :param callback: callback that was used during registration :param details_filter: details filter that was used during ...
java
private static Filter[] filters(QueryFragment... fragments) { Filter[] ret = new Filter[fragments.length]; for (int i = 0; i < fragments.length; ++i) { ret[i] = fragments[i].getFilter(); } return ret; }
python
def blit_rect( self, console: tcod.console.Console, x: int, y: int, width: int, height: int, bg_blend: int, ) -> None: """Blit onto a Console without scaling or rotation. Args: console (Console): Blit destination Console. ...
python
def is_zombie(self, path): '''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
python
def fermionic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a)...
python
def observed_data_to_xarray(self): """Convert observed data to xarray.""" if self.observed is None: return None observed_data = {} if isinstance(self.observed, self.tf.Tensor): with self.tf.Session() as sess: vals = sess.run(self.observed,...
python
def getTotalExpectedOccurrencesTicks_2_5(ticks): """ Extract a set of tick locations and labels. The input ticks are assumed to mean "How many *other* occurrences are there of the sensed feature?" but we want to show how many *total* occurrences there are. So we add 1. We label tick 2, and then 5, 10, 15, 20...
java
private void completeHalfDoneAcceptRecovery( PersistedRecoveryPaxosData paxosData) throws IOException { if (paxosData == null) { return; } long segmentId = paxosData.getSegmentState().getStartTxId(); long epoch = paxosData.getAcceptedInEpoch(); File tmp = journalStorage.getSyncLogT...
java
public static CPDefinitionLink fetchByCPD_T_First(long CPDefinitionId, String type, OrderByComparator<CPDefinitionLink> orderByComparator) { return getPersistence() .fetchByCPD_T_First(CPDefinitionId, type, orderByComparator); }
java
private boolean implementsCommonInterface(String name) { try { JavaClass cls = Repository.lookupClass(name); JavaClass[] infs = cls.getAllInterfaces(); for (JavaClass inf : infs) { String infName = inf.getClassName(); if (ignorableInterfaces.c...
java
protected void fireSegmentAdded(RoadSegment segment) { if (this.listeners != null && isEventFirable()) { for (final RoadNetworkListener listener : this.listeners) { listener.onRoadSegmentAdded(this, segment); } } }
java
public static <V> LongObjectHashMap<V> createPrimitiveLongKeyMap(int initialCapacity, float loadFactor) { return new LongObjectHashMap<V>(initialCapacity, loadFactor); }
python
def do_bestfit(self): """ do bestfit using scipy.odr """ self.check_important_variables() x = np.array(self.args["x"]) y = np.array(self.args["y"]) if self.args.get("use_RealData", True): realdata_kwargs = self.args.get("RealData_kwargs", {}) ...
python
def mousePressEvent(self, event): """Override Qt method""" if event.button() == Qt.MidButton: index = self.tabBar().tabAt(event.pos()) if index >= 0: self.sig_close_tab.emit(index) event.accept() return QTabWidget.mo...
java
public Object execute(final Map<Object, Object> iArgs) { if (newRecords == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OCommandParameters commandParameters = new OCommandParameters(iArgs); if (indexName != null) { fina...
python
def calculate_size(transaction_id, thread_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(transaction_id) data_size += LONG_SIZE_IN_BYTES return data_size
java
@Override public synchronized void onClose() { super.onClose(); if (phoneStateListener != null) telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); }
python
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1): """ Builds mask image from rootname's DQ array If there is no valid 'DQ' array in image, then return an empty string. """ # If no bitvalue is set or rootname given, assume no mask is desired # However, this name wou...
python
def _get_binop_contexts(context, left, right): """Get contexts for binary operations. This will return two inference contexts, the first one for x.__op__(y), the other one for y.__rop__(x), where only the arguments are inversed. """ # The order is important, since the first one should be # ...
python
def create_shortlink(self, callback_uri=None, description=None, serial_number=None): """Register new shortlink Arguments: callback_uri: URI called by mCASH when user scans shortlink description: Shortlink description displ...
java
static public int asIntValue(byte[] array, int offset, int length) { if (null == array || array.length <= offset) { return -1; } int intVal = 0; int mark = 1; int digit; int i = offset + length - 1; // PK16337 - ignore trailing whitespace for...