language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def isExe(self): """ Determines if the current L{PE} instance is an Executable file. @rtype: bool @return: C{True} if the current L{PE} instance is an Executable file. Otherwise, returns C{False}. """ if not self.isDll() and not self.isDriver() and ( consts.IMAGE...
python
def _next_of_kin(self, pos): """ looks up the next sibling of the closest ancestor with not-None next siblings. """ candidate = None parent = self.parent_position(pos) if parent is not None: candidate = self.next_sibling_position(parent) if...
java
public String postJson(String endpoint, JSONObject json) throws IOException { return this.postJson(endpoint, "", json); }
python
def profile_get(user, default_hidden=True): ''' List profiles for user user : string username default_hidden : boolean hide default profiles CLI Example: .. code-block:: bash salt '*' rbac.profile_get leo salt '*' rbac.profile_get leo default_hidden=False ...
java
public T plus( double beta , T B ) { convertType.specify(this,B); T A = convertType.convert(this); B = convertType.convert(B); T ret = A.createLike(); A.ops.plus(A.mat,beta,B.mat,ret.mat); return ret; }
java
public Criteria deriveTransactionWide() { Criteria ret = new Criteria(); ret.setStartTime(startTime); ret.setEndTime(endTime); ret.setProperties(getProperties().stream().filter(p -> p.getName().equals(Constants.PROP_PRINCIPAL)) .collect(Collectors.toSet())); ret.s...
python
def complete_previous(self, count=1, disable_wrap_around=False): """ Browse to the previous completions. (Does nothing if there are no completion.) """ if self.complete_state: if self.complete_state.complete_index == 0: index = None if...
python
def get_activate_url(self, card_id, outer_str=None): """ 获取开卡插件 Url, 内含调用开卡插件所需的参数 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1499332673_Unm7V :param card_id: 会员卡的card_id :param outer_str: 渠道值,用于统计本次领取的渠道参数 :return: 内含调用开卡插件所需的参数的 Url """ return sel...
python
def tag_value(self, p_key, p_default=None): """ Returns a tag value associated with p_key. Returns p_default if p_key does not exist (which defaults to None). """ return self.tag_values(p_key)[0] if p_key in self.fields['tags'] else p_default
python
def validate_read(self, kwargs): """ remove table keywords from kwargs and return raise if any keywords are passed which are not-None """ kwargs = copy.copy(kwargs) columns = kwargs.pop('columns', None) if columns is not None: raise TypeError("cannot ...
java
private void rebuildSharedTab() { m_form.removeGroup(CmsPropertyPanel.TAB_SHARED); CmsPropertyPanel panel = ((CmsPropertyPanel)m_form.getWidget()); panel.clearTab(CmsPropertyPanel.TAB_SHARED); internalBuildFields(Mode.resource); m_form.renderGroup(CmsPropertyPanel.TAB_SHARED); ...
python
def pop_with_body_instrs(setup_with_instr, queue): """ Pop instructions from `queue` that form the body of a with block. """ body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left') # Last two instructions should always be POP_BLOCK, LOAD_CONST(None). # These don't correspond...
python
def import_attribute(self, path): """ Import an attribute from a module. """ module = '.'.join(path.split('.')[:-1]) function = path.split('.')[-1] module = importlib.import_module(module) return getattr(module, function)
python
def floyd_warshall_get_path(self, distance, nextn, i, j): ''' API: floyd_warshall_get_path(self, distance, nextn, i, j): Description: Finds shortest path between i and j using distance and nextn dictionaries. Pre: (1) distance and nextn are...
java
private int computeDifficulty(Operation left) { int difficulty = 0; if (left instanceof MappedOperation) { difficulty = 10*getMappingDepth(left); } return difficulty; }
java
private void scheduleHeartbeat() { // elapsed time in seconds since the last heartbeat long elapsedSecsSinceLastHeartBeat = System.currentTimeMillis() / 1000 - lastHeartbeatStartTimeInSecs; /* * The initial delay for the new scheduling is 0 if the elapsed * time is more than the heartbe...
java
public static Logger createModuleLogger(String name, Logger parent) { final Logger logger = Logger.getLogger(name); if (parent != null) { logger.setParent(parent); } logger.setUseParentHandlers(true); final Level level = getLoggingLevelFromProperties(); logger.setLevel(level); return logger; }
java
public static Tree CCtransform(Tree t) { boolean notDone = true; while (notDone) { Tree cc = findCCparent(t, t); if (cc != null) { t = cc; } else { notDone = false; } } return t; }
python
def dfilter(self, **kwds): """Returns a DictRegister which contains only the elements that match the given specifications. """ starting_list = self[:] filtered_list = [] for key, value in six.iteritems(kwds): for item in starting_list: if self....
java
public static void rank1UpdateMultR(ZMatrixRMaj A, double u[], int offsetU, double gamma , int colA0, int w0, int w1, do...
python
def get_parser(): """get the parsers dict""" parsers = {} parsers['super'] = argparse.ArgumentParser( description="A credential/secret storage system") parsers['super'].add_argument("-r", "--region", help="the AWS region in which to operate. " ...
python
def resolve(self): """Builds all targets of this dependency and returns the result of self.function on the resulting values """ values = {} for target_name in self.target_names: if self.context.is_build_needed(self.parent, target_name): self.context...
python
def set_defaults(self): """ Set defaults for fields needed to write the header if they have defaults. Notes ----- - This is NOT called by `rdheader`. It is only automatically called by the gateway `wrsamp` for convenience. - This is also not called by `...
python
def read_params(filename, asheader=False, verbosity=0) -> Dict[str, Union[int, float, bool, str, None]]: """Read parameter dictionary from text file. Assumes that parameters are specified in the format: par1 = value1 par2 = value2 Comments that start with '#' are allowed. Parameters ...
python
def cmp_contents(filename1, filename2): """ Returns True if contents of the files are the same Parameters ---------- filename1 : str filename of first file to compare filename2 : str filename of second file to compare Returns ------- tf : bool True if binary con...
java
protected void preInvoke(Method m, Object [] args, String [] interceptorNames) throws InterceptorPivotException { // // If the implementation expects single threaded behavior and our container does // not guarantee it, then enforce it locally here // if (_invokeLock !...
java
@Override public UpdateCrawlerScheduleResult updateCrawlerSchedule(UpdateCrawlerScheduleRequest request) { request = beforeClientExecution(request); return executeUpdateCrawlerSchedule(request); }
java
@Override public ODocument toStream() { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final List<ODocument> inds = new ArrayList<ODocument>(indexDefinitions.size()); final List<String> indClasses = new ArrayList<String>(indexDefinitions.size()); try { document.field("c...
python
def init(cwd, bare=False, template=None, separate_git_dir=None, shared=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-init(1)`_ cwd The...
python
def get_function(rule, domain, normalize, **parameters): """ Create a quadrature function and set default parameter values. Args: rule (str): Name of quadrature rule defined in ``QUAD_FUNCTIONS``. domain (Dist, numpy.ndarray): Defines ``lower`` and ``upper`` that is ...
python
def sample(self, nsims=1000): """ Samples from the posterior predictive distribution Parameters ---------- nsims : int (default : 1000) How many draws from the posterior predictive distribution Returns ---------- - np.ndarray of draws from the data ...
python
def attach_volume(name=None, kwargs=None, instance_id=None, call=None): ''' Attach a volume to an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The attach_volume action must be called with -a or --action.' ) if not kwargs: kwargs = {} if 'ins...
python
def interface_type(self): """The interface type of the resource as a number. """ return self.visalib.parse_resource(self._resource_manager.session, self.resource_name)[0].interface_type
python
def captureQuery(self, query, params=(), engine=None, **kwargs): """ Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo') """ return self.capture( 'raven.events.Query', query=query, params=params, engine=engine, **kwargs)
python
def get_history_kline(self, code, start=None, end=None, ktype=KLType.K_DAY, autype=AuType.QFQ, fields=[KL_FIELD.ALL]): """ 得到本地历史k线,需先参照帮助文档下载k线 :param cod...
python
def __remove_trailing_empty_lines(lines): """ Removes leading empty lines from a list of lines. :param list[str] lines: The lines. """ lines.reverse() tmp = DocBlockReflection.__remove_leading_empty_lines(lines) lines.reverse() tmp.reverse() retu...
java
public void setValueOfField(String fieldName, Object value) { add(new SimpleUpdateField(fieldName, value, UpdateAction.SET)); }
python
def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ret
python
def get_task(self, task=None): """ Returns a (task, description) tuple for a given task """ # Iterate over the grindstone tasks for t in self.grindstone['tasks']: # if they key matches the task if key_of(t) == task: # Return this task ...
python
def route(self, resource): """ route """ route = self.routes.get(resource, Route(resource)) self.routes.update({resource: route}) return route
java
public static Function<Object,Integer> attrOfInteger(final String attributeName) { return new Get<Object,Integer>(Types.INTEGER, attributeName); }
java
protected static void putRolePolicy(String s3Prefix) { try { // set permissions policy for the role String permissionsPolicyDocument = containsKMSKeyARN() ? getPermissionsPolicyWithKMSResources(s3Prefix) : getPermissionsPolicyWithoutKMSReso...
java
public void setStreamInfoList(java.util.Collection<StreamInfo> streamInfoList) { if (streamInfoList == null) { this.streamInfoList = null; return; } this.streamInfoList = new java.util.ArrayList<StreamInfo>(streamInfoList); }
python
def get_valid_directory_list(input_directory): """ Get a list of folders """ valid_input_directories = [] for directory in os.listdir(input_directory): if os.path.isdir(os.path.join(input_directory, directory)): valid_input_directories.append(directory) else: ...
java
protected ConnectionInfo createConnectionInfo( String url, Properties info ) throws SQLException { RepositoryDelegate repositoryDelegate = delegateFactory.createRepositoryDelegate(url, info, this.contextFactory); return repositoryDelegate.getConnectionI...
java
public String getOntRelationId() { if (OntRelationMention_Type.featOkTst && ((OntRelationMention_Type)jcasType).casFeat_ontRelationId == null) jcasType.jcas.throwFeatMissing("ontRelationId", "de.julielab.jules.types.OntRelationMention"); return jcasType.ll_cas.ll_getStringValue(addr, ((OntRelationMention_...
java
static Map<String, ?> buildSourceByJsonMapper(String jsonObjectString) { try { return JsonMapper.readValue(jsonObjectString, MAP_TYPE_REFERENCE); } catch (Exception e) { return JMExceptionManager.handleExceptionAndThrowRuntimeEx(log, e, "buildSourceByJsonMappe...
python
def make_safe_url(self, url): """Makes a URL safe by removing optional hostname and port. Example: | ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')`` | returns ``'/path1/path2?q1=v1&q2=v2#fragment'`` Override this method if you need to allow a ...
java
public static double log2_2pd1(double x) { if(x < 0) return Double.NaN; long rawBits = doubleToLongBits(x); long mantissa = getMantissa(rawBits); int e = Math.getExponent(x); double m = longBitsToDouble(1023L << 52 | mantissa);//m in [1, 2] double log2m =...
python
def _kak_decomposition_to_operations(q0: ops.Qid, q1: ops.Qid, kak: linalg.KakDecomposition, allow_partial_czs: bool, atol: float = 1e-8 ...
java
protected static String getAuditAPIUrl(Dashboard dashboard, AuditSettings settings, long beginDate, long endDate) { LOGGER.info("NFRR Audit Collector creates Audit API URL"); if (CollectionUtils.isEmpty(settings.getServers())) { LOGGER.error("No Server Found to run NoFearRelease audit collec...
java
public String getClassDescription(int index) { Clazz cz = (Clazz) getConstantInfo(index); int ni = cz.getName_index(); return getString(ni); }
java
private String parseHtmlFile(File file, Hashtable properties) throws CmsException { String parsedHtml = ""; try { byte[] content = getFileBytes(file); // use the correct encoding to get the string from the file bytes String contentString = new String(content, m_inp...
java
public XMLString getStringFromNode(int n) { // %OPT% // I guess we'll have to get a static instance of the DTM manager... if(DTM.NULL != n) { return m_dtmMgr.getDTM(n).getStringValue(n); } else { return org.apache.xpath.objects.XString.EMPTYSTRING; } }
java
private Snak copy(Snak snak) { if (snak instanceof ValueSnak) { return copy((ValueSnak) snak); } else if (snak instanceof NoValueSnak) { return copy((NoValueSnak) snak); } else if (snak instanceof SomeValueSnak) { return copy((SomeValueSnak) snak); } else { throw new IllegalArgumentException( "...
java
public final Filter<S> andExists(String propertyName, Filter<?> subFilter) { ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty(); return and(ExistsFilter.build(prop, subFilter, false)); }
python
def connect(self): """ Todo connect """ self.transport = Transport(self.token, on_connect=self.on_connect, on_message=self.on_message)
python
def load_modules(self, data=None, proxy=None): ''' Load the modules into the state ''' log.info('Loading fresh modules for state activity') # Load a modified client interface that looks like the interface used # from the minion, but uses remote execution # ...
java
public SQLInsertClause insertIgnore(RelationalPath<?> entity) { SQLInsertClause insert = insert(entity); insert.addFlag(Position.START_OVERRIDE, "insert ignore into "); return insert; }
python
def sliding_impl(wrap, size, step, sequence): """ Implementation for sliding_t :param wrap: wrap children values with this :param size: size of window :param step: step size :param sequence: sequence to create sliding windows from :return: sequence of sliding windows """ i = 0 n ...
java
public static boolean isSupportedVectorExtension( String name ) { for( String ext : supportedVectors ) { if (name.toLowerCase().endsWith(ext)) { return true; } } return false; }
python
def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ): """ synchronize state with the blockchain. Return True on success Return False if we're supposed to stop indexing Abort on error """ subdomain_index = server_state['subdoma...
python
def execute(self, eopatch): """ Compute argmax/argmin of specified `data_feature` and `data_index` :param eopatch: Input eopatch :return: eopatch with added argmax/argmin features """ if self.mask_data: valid_data_mask = eopatch.mask['VALID_DATA'] else: ...
java
public static MeasureUnit getDistanceUnit(Locale locale) { return USES_MILES.contains(locale.getCountry()) ? MILE : KILOMETER; }
java
public static double price( double timeToMaturity, double coupon, double yield, double redemption, int frequency) { double price = 0.0; if(timeToMaturity > 0) { price += redemption; } double paymentTime = timeToMaturity; while(paymentTime > 0) { price += coupon; // Discount back ...
java
public synchronized MessageResourceBundle getBundle() { if (isModified()) { bundle = createBundle(file); } if (parent != null) { bundle.setParent(parent.getBundle()); } return bundle; }
java
@Override public FileSystemManager provide() { try { return VFS.getManager(); } catch (FileSystemException fse) { logger.error("Cannot create FileSystemManager", fse); throw new RuntimeException("Cannot create FileSystemManager", fse); } }
java
public T orElse(T defaultValue) { T value = get(); if (value != null) { return value; } return defaultValue; }
java
public Object mapToResultType(ControlBeanContext context, Method m, ResultSet resultSet, Calendar cal) { final Class returnType = m.getReturnType(); final boolean isArray = returnType.isArray(); try { if (isArray) { final SQL methodSQL = context.getMethodPropertySet...
java
@Override public EClass getIfcRelAssociatesConstraint() { if (ifcRelAssociatesConstraintEClass == null) { ifcRelAssociatesConstraintEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(529); } return ifcRelAssociatesConstraintEClass; }
java
public static HttpResponse errorJSON(@Nonnull String message, @Nonnull Map<?,?> data) { return new JSONObjectResponse(data).error(message); }
java
public void appendBatchWith(List<Card> groups) { if (mGroupBasicAdapter != null) { insertBatchWith(mGroupBasicAdapter.getGroups().size(), groups); } }
java
public static <T> Promise traverse(List<Supplier<Promise<T>>> queue) { if (queue.size() == 0) { return Promise.success(null); } return queue.remove(0).get() .flatMap(v -> traverse(queue)); }
java
public V computeIfAbsent(final int key, final IntFunction<? extends V> mappingFunction) { checkNotNull(mappingFunction, "mappingFunction cannot be null"); V value = get(key); if (value == null) { value = mappingFunction.apply(key); if (value != null) { put...
java
@Override public void renewToken() { CreateTokenRequest createTokenRequest = new CreateTokenRequest(); createTokenRequest.setUser(credentials.getUserName()); createTokenRequest.setPassword(credentials.getPassword()); CreateTokenResponse createTokenResponse; try { createTokenResponse = send(createTokenReq...
java
public static <A, B> These<A, B> b(B b) { return new _B<>(b); }
java
void showPreview( String path ) { synchronized (lockPreview) { if( path == null ) { pendingPreview = null; } else if( previewThread == null ) { pendingPreview = path; previewThread = new PreviewThread(); previewThread.start(...
java
public ApiResponse<ApiSuccessResponse> completeWithHttpInfo(String mediatype, String id, CompleteData completeData) throws ApiException { com.squareup.okhttp.Call call = completeValidateBeforeCall(mediatype, id, completeData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.g...
python
def with_options(self, component): """Apply options component options to this configuration.""" options = component.get_required_config() component_name = _get_component_name(component) return BoundConfig(self._get_base_config(), component_name, options)
python
def export_process_template(self, id, **kwargs): """ExportProcessTemplate. [Preview API] Returns requested process template. :param str id: The ID of the process :rtype: object """ route_values = {} if id is not None: route_values['id'] = self._seriali...
java
@SuppressWarnings("unchecked") public EList<IfcRelConnectsElements> getConnectedFrom() { return (EList<IfcRelConnectsElements>) eGet(Ifc2x3tc1Package.Literals.IFC_ELEMENT__CONNECTED_FROM, true); }
java
public static String rocChartToHtml(ROCMultiClass rocMultiClass, List<String> classNames) { int n = rocMultiClass.getNumClasses(); List<Component> components = new ArrayList<>(n); for (int i = 0; i < n; i++) { RocCurve roc = rocMultiClass.getRocCurve(i); String headerTe...
java
@Override public CommercePaymentMethodGroupRel findByGroupId_Last(long groupId, OrderByComparator<CommercePaymentMethodGroupRel> orderByComparator) throws NoSuchPaymentMethodGroupRelException { CommercePaymentMethodGroupRel commercePaymentMethodGroupRel = fetchByGroupId_Last(groupId, orderByComparator); i...
java
private ArrayList<String> getNameInCluster(Cluster cluster) { ArrayList<String> itemsInCluster = new ArrayList<String>(); String nodeName; if (cluster.isLeaf()) { nodeName = cluster.getName(); itemsInCluster.add(nodeName); } else { // String[] clusterName = cluster.getNam...
java
public <T> T readObject(final Object object, final DataTypeDescriptor<T> descriptor) { try { return objectFormat.read(object, descriptor); } catch (Exception e) { throw propagate(e); } }
python
def config(conf, confdefs): ''' Initialize a config dict using the given confdef tuples. ''' conf = conf.copy() # for now just populate defval for name, info in confdefs: conf.setdefault(name, info.get('defval')) return conf
java
public String encryptText(String text) throws Exception { return toByteText(this.encrypt(text.getBytes(IO.CHARSET))); }
java
@Override public MongoDeepJobConfig<T> ignoreIdField() { DBObject bsonFields = fields != null ? fields : new BasicDBObject(); bsonFields.put("_id", 0); fields = bsonFields; return this; }
java
public ServiceFuture<DiskInner> beginCreateOrUpdateAsync(String resourceGroupName, String diskName, DiskInner disk, final ServiceCallback<DiskInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, diskName, disk), serviceCallback); }
python
def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs): """Convenience function to get an adb device from usb path or serial. Args: port_path: The filename of usb port to use. serial: The serial number of the device to use. d...
java
@Nonnull @ReturnsMutableCopy public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass) { return getAllSPIImplementations (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (), null); }
python
def login(self, token, use_token=True, mount_point=DEFAULT_MOUNT_POINT): """Login using GitHub access token. Supported methods: POST: /auth/{mount_point}/login. Produces: 200 application/json :param token: GitHub personal API token. :type token: str | unicode :para...
java
public static Integer getDayOfYear(Date date) { if (date == null) return null; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_YEAR); }
python
def find_old_vidyo_rooms(max_room_event_age): """Finds all Vidyo rooms that are: - linked to no events - linked only to events whose start date precedes today - max_room_event_age days """ recently_used = (db.session.query(VCRoom.id) .filter(VCRoom.type == 'vidyo', ...
java
private String guessMimeType(final ChannelBuffer buf) { final String mimetype = guessMimeTypeFromUri(request().getUri()); return mimetype == null ? guessMimeTypeFromContents(buf) : mimetype; }
java
private static void encodeBinary(byte[] bytes, int startpos, int count, int startmode, StringBuilder sb) { if (count == 1 && startmode == TEXT_COMPACTION) { sb.append((ch...
java
public static List extractToList(final Collection collection, final String propertyName) { List list = new ArrayList(collection.size()); try { for (Object obj : collection) { list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (ReflectiveOperationException e) { throw new ReflectionRunt...
java
public static Reader newReader(File file, String encoding) throws IOException { int bomType = getBOMType( file ); int skipBytes = getSkipBytes( bomType ); FileInputStream fIn = new FileInputStream( file ); long skippedBytes = fIn.skip( skipBytes ); return new Inpu...
java
public void setDestinationEncryptionContext(java.util.Map<String, String> destinationEncryptionContext) { this.destinationEncryptionContext = destinationEncryptionContext == null ? null : new com.ibm.cloud.objectstorage.internal.SdkInternalMap<String, String>( destinationEncryptionContext); ...
python
def dependency_images(self, for_running=False): """ What images does this one require Taking into account parent image, and those in link and volumes.share_with options """ candidates = [] detach = dict((candidate, not options.attached) for candidate, options in self.dep...