language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.cast( ctypes.pointer(structure), ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)), ).contents
java
public void cacheDescriptorValue(IBond bond, IAtomContainer container, IDescriptorResult doubleResult) { if (cachedDescriptorValues == null) { cachedDescriptorValues = new HashMap(); cachedDescriptorValues.put(PREVIOUS_ATOMCONTAINER, container); } else if (cachedDescriptorValues....
java
public final boolean isId(final String pNm) { for (String idNm : this.idColNms) { if (idNm.equals(pNm)) { return true; } } return false; }
python
async def release(self, conn): """Release free connection back to the connection pool. """ assert conn in self._used, (conn, self._used) self._used.remove(conn) if not conn.closed: if self._closing: await conn.close() else: ...
python
def load_tables(self, query, meta): """ Load necessary resources tables into db to execute given query. """ try: for table in meta.tables: self.load_table(table) except NoCredentialsError: help_link = 'http://boto3.readthedocs.io/en/latest/...
java
public static long getDateParameter(final ServletRequest pReq, final String pName, final long pDefault) { String str = pReq.getParameter(pName); try { return str != null ? StringUtil.toDate(str).getTime() : pDefault; } catch (IllegalArgumentException iae) { ...
python
def is_netcdf(url): ''' Returns True if the URL points to a valid local netCDF file :param str url: Location of file on the file system ''' # Try an obvious exclusion of remote resources if url.startswith('http'): return False # If it's a known extension, give it a shot if url....
python
def clean_highlight(self): """ Remove the empty highlight """ if not self.valid: return for hit in self._results['hits']['hits']: if 'highlight' in hit: hl = hit['highlight'] for key, item in list(hl.items()): ...
python
def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None: """ Adds serialization support for a new type. :param type: The type to add support for. :param serialize: A callable that takes an object of type ``type`` and returns a string. ...
java
private void addNewJobs(Set<BambooJob> jobs, List<BambooJob> existingJobs, BambooCollector collector) { long start = System.currentTimeMillis(); int count = 0; List<BambooJob> newJobs = new ArrayList<>(); for (BambooJob job : jobs) { BambooJob existing = null; if...
python
def add_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read): """ Addes a newly created file handler to the specified logger :param logger: logging name or object to modify, defaults to root logger :param file_path: path to file to lo...
python
def calculate_lyapunov(self): """ Return the current Lyapunov Characteristic Number (LCN). Note that you need to call init_megno() before the start of the simulation. To get a timescale (the Lyapunov timescale), take the inverse of this quantity. """ if self._calculate_me...
python
def precision(links_true, links_pred=None): """precision(links_true, links_pred) Compute the precision. The precision is given by TP/(TP+FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: ...
java
public Invoke createTCInvokeRequest() { InvokeImpl t = (InvokeImpl) TcapFactory.createComponentInvoke(); t.setProvider(provider); return t; }
python
def recursively_save_dict_contents_to_group(h5file, path, dic): """ .... """ reconstruction_flags = {} # reconstruction_key_flags = {} for key, item in dic.items(): if type(key) is not str: # import pickle # key = pickle.dumps(key).decode("ascii") impo...
python
def sigma2Derivative(self,R,log=False): """ NAME: sigmaDerivative PURPOSE: return the derivative wrt R of the sigma_R^2 profile at this R INPUT: R - Galactocentric radius (/ro) log - if True, return the derivative of the log (default: False) ...
java
@Override public void run() { try { while (!delegate.isShutdown()) { this.rateLimiter.acquire(); Runnable r = queue.take(); if (!delegate.isShutdown()) { delegate.execute(r); } } } catch (InterruptedException ie) { LOG.info("Interrupted", ie); } ...
java
protected void ensureImportsChecked(List<JCCompilationUnit> trees) { // if there remain any unimported toplevels (these must have // no classes at all), process their import statements as well. for (JCCompilationUnit tree : trees) { if (!tree.starImportScope.isFilled()) { ...
java
public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException { InputStream inStream = resultset.getBinaryStream(iColumn); if (resultset.wasNull()) this.setData(null, false, DBConstants.READ_MOVE); // Null value else { try { ...
python
def _get_next_obj(self, length): """Assumes we've already read the object length""" data = b'' while len(data) < length: data += self.sock.recv(length - len(data)) return pickle.loads(data)
python
def add_reference_resources(data, remote_retriever=None): """Add genome reference information to the item to process. """ aligner = data["config"]["algorithm"].get("aligner", None) if remote_retriever: data["reference"] = remote_retriever.get_refs(data["genome_build"], ...
python
def deprecated(msg, dep_version): """Decorate a function, method or class to mark as deprecated. Raise DeprecationWarning and add a deprecation notice to the docstring. """ def wrapper(func): docstring = func.__doc__ or '' docstring_msg = '.. deprecated:: {version} {msg}'.format( version=dep_version, msg...
java
public void initLeading () { m_nLeading = 0; while (m_nLeading < m_sValue.length () && m_sValue.charAt (m_nLeading) == ' ') m_nLeading++; if (m_nLeading == m_sValue.length ()) setEmpty (); }
java
public void addFields(List<ModelFieldBean> modelFields) { Assert.notNull(modelFields, "modelFields must not be null"); for (ModelFieldBean bean : modelFields) { this.fields.put(bean.getName(), bean); } }
python
def translate_path(self, orig_path): """Translates a path for a static file request. The server base path could be different from our cwd. Parameters ---------- path : string The path. Returns ------- The absolute file path denoted by the ...
java
public boolean enableWriteAheadLogging() { synchronized (mLock) { throwIfNotOpenLocked(); if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0) { return true; } if (isReadOnlyLocked()) { // WAL doesn't make sense...
java
public static String encodePath(String path, String encoding) throws UnsupportedEncodingException { return HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH); }
python
def _DISPATCH(self, body, ticket=None): """Dispatch message to the appropriate method in :attr:`state`, handle possible exceptions, and return a response suitable to be used in a reply. To protect from calling special methods it does not dispatch method names starting with under...
java
protected IScope getFeatureScope(Anchor anchor) { IScope cached = cachedFeatureScope.get(anchor); if (cached != null) return cached; if (anchor != Anchor.RECEIVER) { cached = createSimpleFeatureCallScope(); cachedFeatureScope.put(anchor, cached); return cached; } else if (context instanceof XExpress...
java
static void relocateOldLogs(File dir) { final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?"); File[] logfiles = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return logfile.matcher(name).matches(); } ...
java
private void syncSysMetaFromRemote() { for (String topology : JStormMetrics.SYS_TOPOLOGIES) { if (context.getTopologyMetricContexts().containsKey(topology)) { syncMetaFromRemote(topology, context.getTopologyMetricContexts().get(topology), ...
python
def launch_local(in_name, out_name, script_path, poll=None, max_input=None, files=(), cmdenvs=(), pipe=True, python_cmd='python', remove_tempdir=True, identity_mapper=False, num_reducers=None, **kw): """A simple local emulation of hadoop This doesn't run hadoo...
java
private final void performRecovery(LogInput logInput) throws ObjectManagerException { final String methodName = "performRecovery"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, method...
java
private static UIComponent createFacetUIPanel(FaceletContext ctx, UIComponent parent, String facetName) { FacesContext facesContext = ctx.getFacesContext(); UIComponent panel = facesContext.getApplication().createComponent(facesContext, UIPanel.COMPONENT_TYPE, null); // The panel cr...
java
protected DataSource createDataSource(DBType aDbType, String aDbUrl, String aUsername, String aPassword, Hashtable<String, DataSource> aDsTable) ...
python
def get_system_uptime_output_show_system_uptime_days(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_system_uptime = ET.Element("get_system_uptime") config = get_system_uptime output = ET.SubElement(get_system_uptime, "output") show_s...
java
public int getInteger(String key, int defaultValue) { int result = defaultValue; try { if (key != null) result = getInteger(key); } catch (MissingResourceException e) { } return result; }
python
def list_perceel_adapter(obj, request): """ Adapter for rendering a list of :class: `crabpy.gateway.capakey.Perceel` to json. """ return { 'id': obj.id, 'sectie': obj.sectie, 'capakey': obj.capakey, 'percid': obj.percid }
java
public void updateStyleElement() { // TODO: this should be sufficient - why does Batik occasionally not pick up // the changes unless we actually replace the style element itself? // cssman.updateStyleElement(document, style); Element newstyle = cssman.makeStyleElement(document); style.getParentNode...
python
def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None, run_task=None, **kwargs): """ Decorator for channel post handler :param commands: list of commands :param regexp: REGEXP :param content_types:...
java
public static ByteBuffer toByteBuffer(String s) { ByteBuffer buffer = ByteBuffer.allocateDirect(s.length()); buffer.put(s.getBytes(UTF_8)); buffer.flip(); return buffer; }
java
private String getCData(final Node n) { StringBuffer buf = new StringBuffer(); NodeList nl = n.getChildNodes(); for (int x = 0; x < nl.getLength(); x++) { Node innerNode = nl.item(x); if ( (innerNode.getNodeType() == Node.TEXT_NODE) || (innerNode.getNodeType() == Node.CDATA_S...
python
def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """ try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() ...
python
def place(self, **kw): """ Place a widget in the parent widget. :param in\_: master relative to which the widget is placed :type in\_: widget :param x: locate anchor of this widget at position x of master :type x: int :param y: locate anchor of this widge...
java
public static FileBytes allocate(File file, String mode, int size) { return new FileBytes(file, mode, (int) Math.min(Memory.Util.toPow2(size), Integer.MAX_VALUE)); }
java
public static <T extends Enum<T>> EnumPath<T> enumPath(Class<? extends T> type, Path<?> parent, String property) { return new EnumPath<T>(type, PathMetadataFactory.forProperty(parent, property)); }
python
def register_connection(self, alias, api_key, base_url, timeout=5): """ Create and register a new connection. :param alias: The alias of the connection. If not changed with `switch_connection`, the connection with default 'alias' is used by the resources. :para...
java
public FieldInfo getDeclaredFieldInfo(final String fieldName) { if (!scanResult.scanSpec.enableFieldInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()"); } if (fieldInfo == null) { return null; } for (final ...
python
def word_game_round(self, message): "play a word game: Play a game where you think of words that start with a letter and fit a topic." letter = random.choice(string.ascii_uppercase) topics = [] while len(topics) < 10: new_topic = random.choice(WORD_GAME_TOPICS) ...
java
public void update(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) { Map<String, Object> esFieldDataTmp = new LinkedHashMap<>(esFieldData.size()); esFieldData.forEach((k, v) -> esFieldDataTmp.put(Util.cleanColumn(k), v)); append4Update(mapping, pkVal, esFieldDataTmp); c...
python
def ephemeral(*, port: int = 6060, timeout_connection: int = 30, verbose: bool = False ) -> Iterator[Client]: """ Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port th...
java
public static int compareMavenVersions(String v1, String v2) { return parseMavenVersion(v1).compareTo(parseMavenVersion(v2)); }
python
def notebook_substitute_ref_with_url(ntbk, cr): """ In markdown cells of notebook object `ntbk`, replace sphinx cross-references with links to online docs. Parameter `cr` is a CrossReferenceLookup object. """ # Iterate over cells in notebook for n in range(len(ntbk['cells'])): # Onl...
python
def add_node(self, node, adapter_number, port_number, label=None, dump=True): """ Add a node to the link :param dump: Dump project on disk """ port = node.get_port(adapter_number, port_number) if port is None: raise aiohttp.web.HTTPNotFound(text="Port {}/{} ...
python
def reciprocal(x, a, b, n): """ reciprocal function to the power n to fit convergence data """ if n < 1: n = 1 elif n > 5: n = 5 if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / x_v ** n) y = np.array(y_l) else: y =...
python
def _process_items(cls, vals): "Processes list of items assigning unique paths to each." if type(vals) is cls: return vals.data elif not isinstance(vals, (list, tuple)): vals = [vals] items = [] counts = defaultdict(lambda: 1) cls._unpack_paths(val...
java
private boolean exceedsThresholds() { boolean isFirstAppend = this.operations.size() > 0 && isAppendOperation(this.operations.getFirst()); long length = isFirstAppend ? this.operations.getFirst().getLength() : 0; if (isFirstAppend && length == 0 && !((AggregatedAppendOperation) this.operations.g...
java
private Context translateContinue(WyilFile.Stmt.Continue stmt, Context context) { LoopScope enclosingLoop = context.getEnclosingLoopScope(); enclosingLoop.addContinueContext(context); return null; }
java
public static IAtomContainer getAtomContainer(String formulaString, IChemObjectBuilder builder) { return MolecularFormulaManipulator.getAtomContainer(MolecularFormulaManipulator.getMolecularFormula( formulaString, builder)); }
java
private static FDBigInteger big5powRec(int p) { if (p < MAX_FIVE_POW) { return POW_5_CACHE[p]; } // construct the value. // recursively. int q, r; // in order to compute 5^p, // compute its square root, 5^(p/2) and square. // or, let q = p / 2,...
java
@Override public MessageContext getMessageContext() throws IllegalStateException { boolean isEndpointMethod = false; // LI2281.07 // Get the method context for the current thread, and check to see if // the current method is from WebService Endpoint interface. ...
java
private void initDurationButtonGroup() { m_groupDuration = new CmsRadioButtonGroup(); m_endsAfterRadioButton = new CmsRadioButton( EndType.TIMES.toString(), Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0)); m_endsAfterRadioButton.setGroup(m_groupDurat...
java
@Override protected void visitItemAccessNode(ItemAccessNode node) { // simplify children first visitChildren(node); ExprNode baseExpr = node.getChild(0); ExprNode keyExpr = node.getChild(1); if (baseExpr instanceof ListLiteralNode && keyExpr instanceof IntegerNode) { ListLiteralNode listLite...
java
public static final boolean deleteTableIfExists(final AmazonDynamoDB dynamo, final DeleteTableRequest deleteTableRequest) { try { dynamo.deleteTable(deleteTableRequest); return true; } catch (final ResourceNotFoundException e) { if (LOG.isTraceEnabled()) { ...
python
def urlencode_utf8(params): """ UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 """ if hasattr(params, 'items'): params = params.items() params = ( '='.join(( quote_plus(k.encode('utf8'), safe='/'), quote_plus(v.encode('utf8'), s...
java
private void updateDatabase() { if (getMainConfig().getInt("Database.dbVersion") == 0) { alertOldDbVersion(0, 1); //We first check if we have the DB version in the database. If we do, we have a old layout in our hands String value = getStorageHandler().getStorageEngine().getC...
java
@NonNull public static On leftOuterJoin(@NonNull DataSource datasource) { if (datasource == null) { throw new IllegalArgumentException("datasource cannot be null."); } return new On(Type.LEFT_OUTER, datasource); }
python
def timestamp(self, timestamp): """ Allows for custom timestamps to be saved with the record. """ clone = copy.deepcopy(self) clone._timestamp = timestamp return clone
python
def main(): """Run the workflow task.""" log = logging.getLogger('sip.mock_workflow_stage') if len(sys.argv) != 2: log.critical('Expecting JSON string as first argument!') return config = json.loads(sys.argv[1]) log.info('Running mock_workflow_stage (version: %s).', __version__) ...
python
def set_target(self, new_target): """ Sets the new target in mm, the movement starts immediately. If the value is outside the interval [0, 250] or the motor is already moving, an error is returned, otherwise the new target is returned.""" try: self.device.target = new...
python
def tb2radiance(self, tb_, **kwargs): """Get the radiance from the Tb using the simple non-linear regression method. SI units of course! """ # L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1) # # C1 = 2 * h * c**2 and C2 = hc/k # lut = kwargs.get('lut', None...
java
@SuppressWarnings("unchecked") private void doPopulateDatabasePass(final BuildData buildData) throws BuildProcessingException { log.info("Doing " + buildData.getBuildLocale() + " Populate Database Pass"); final ContentSpec contentSpec = buildData.getContentSpec(); final Map<String, BaseTopi...
java
public String decryptStr(String data, Charset charset) { return StrUtil.str(decrypt(data), charset); }
python
def get_all_attribute_value( self, tag_name, attribute, format_value=True, **attribute_filter ): """ Yields all the attribute values in xml files which match with the tag name and the specific attribute :param str tag_name: specify the tag name :param str attribute: specify ...
python
def _events_available_during_other_events( events, slots, X, summation_type=None, **kwargs ): """ Constraint that ensures that an event is not scheduled at the same time as another event for which it is unavailable. Unavailability of events is either because it is explicitly defined or because they ...
python
def tran(inimage,outimage,direction='forward',x=None,y=None, coords=None, coordfile=None,colnames=None,separator=None, precision=6, output=None,verbose=True): """ Primary interface to perform coordinate transformations in pixel coordinates between 2 images using STWCS and full distortion mod...
python
def call(self, name, operation, timeout=10, args=None, **kwargs): """Send a message and wait for reply @param name: name of destination service queue @param operation: name of service operation to invoke @param timeout: RPC timeout to await a reply @param args: dictionary of key...
python
def v_args(inline=False, meta=False, tree=False): "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods" if [tree, meta, inline].count(True) > 1: raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.") de...
java
public List<T> getDomainObjectsAsList(Set<? extends KEY> keys) { // it is not "possible" to use huge number of parameters in a // Restrictions.in criterion and therefore we chunk the query // into pieces List<T> all = new ArrayList<T>(); Iterator<? extends KEY> iter = keys.i...
python
def append(self, value): """Validate item appending to list.""" self.__field.validate_element(value) return list.append(self, value)
java
private ParserContext singleBackingTypeParserContext() throws ExpressionCompileException { ParserContext context = new ParserContext(); context.setStrongTyping(true); context.addInput("this", backingType); PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getB...
java
public static Years from(TemporalAmount amount) { if (amount instanceof Years) { return (Years) amount; } Objects.requireNonNull(amount, "amount"); int years = 0; for (TemporalUnit unit : amount.getUnits()) { long value = amount.get(unit); if (...
java
boolean isBuiltin(Class clazz) { return clazz == null ? false : builtin.contains(clazz.getName()); }
python
def to_string(cls, error_code): """Returns the string message for the given error code. Args: cls (JLinkDataErrors): the ``JLinkDataErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Raises: ...
java
public PeriodConverter[] getPeriodConverters() { ConverterSet set = iPeriodConverters; PeriodConverter[] converters = new PeriodConverter[set.size()]; set.copyInto(converters); return converters; }
python
def get_params(self): """Get signature and params """ params = { 'key': self.get_app_key(), 'uid': self.user_id, 'widget': self.widget_code } products_number = len(self.products) if self.get_api_type() == self.API_GOODS: ...
java
public ClassLoader getUserCodeClassLoader() { if (this.userCodeClassLoader == null) { this.userCodeClassLoader = buildUserCodeClassLoader(jarFiles, classpaths, getClass().getClassLoader()); } return this.userCodeClassLoader; }
java
public boolean isShardingColumn(final String columnName, final String tableName) { for (TableRule each : tableRules) { if (each.getLogicTable().equalsIgnoreCase(tableName) && isShardingColumn(each, columnName)) { return true; } } return false; }
java
public org.tensorflow.framework.RPCOptions getRpcOptions() { return rpcOptions_ == null ? org.tensorflow.framework.RPCOptions.getDefaultInstance() : rpcOptions_; }
java
private static String getNotificationID() { NotificationManager.ID_COUNTER = NotificationManager.ID_COUNTER+1; logger.fine("Notifications identifier counter: "+ID_COUNTER); return "Notification#" + (NotificationManager.ID_COUNTER); }
java
public void appendKeyValueNode(final KeyValueNode<?> node) throws NumberFormatException { final String key = node.getKey(); final Object value = node.getValue(); if (isNullOrEmpty(key)) { // Add the node to the list of nodes appendChild(node, false); } else { ...
python
def fcast(value: float) -> TensorLike: """Cast to float tensor""" newvalue = tf.cast(value, FTYPE) if DEVICE == 'gpu': newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover return newvalue
python
def mx_page_trees(self, mx_page): """ return trees assigned to given MX Page """ resp = dict() for tree_name, tree in self.scheduler.timetable.trees.items(): if tree.mx_page == mx_page: rest_tree = self._get_tree_details(tree_name) resp[tree.tree_name]...
java
public final EObject ruleXClosure() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_3=null; Token lv_explicitSyntax_5_0=null; Token otherlv_7=null; EObject lv_declaredFormalParameters_2_0 = null; EObject lv_declaredForma...
python
def revert_snapshot(name, snap_name, runas=None): ''' Revert a VM to a snapshot :param str name: Name/ID of VM to revert to a snapshot :param str snap_name: Name/ID of snapshot to revert to :param str runas: The user that the prlctl command will be run as Example: ...
java
public Actions keyDown(CharSequence key) { if (isBuildingActions()) { action.addAction(new KeyDownAction(jsonKeyboard, jsonMouse, asKeys(key))); } return addKeyAction(key, codePoint -> tick(defaultKeyboard.createKeyDown(codePoint))); }
java
public static base_responses add(nitro_service client, server resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { server addresources[] = new server[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new server(); addre...
python
def take_bug_reports(ads, test_name, begin_time, destination=None): """Takes bug reports on a list of android devices. If you want to take a bug report, call this function with a list of android_device objects in on_fail. But reports will be taken on all the devices in the list concurrently. Bug report...
python
def yara_match(file_path, rules): """Callback for a newly extracted file""" print('New Extracted File: {:s}'.format(file_path)) print('Mathes:') pprint(rules.match(file_path))
java
private void dispatch(final ExecutionReference reference, final ExecutableFlow exflow, final Executor choosenExecutor) throws ExecutorManagerException { exflow.setUpdateTime(System.currentTimeMillis()); this.executorLoader.assignExecutor(choosenExecutor.getId(), exflow.getExecutionId()); try ...