language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static ChaincodeCollectionConfiguration fromYamlFile(File configFile) throws InvalidArgumentException, IOException, ChaincodeCollectionConfigurationException { return fromFile(configFile, false); }
java
public PublicRenderParameterType<PortletAppType<T>> getOrCreatePublicRenderParameter() { List<Node> nodeList = childNode.get("public-render-parameter"); if (nodeList != null && nodeList.size() > 0) { return new PublicRenderParameterTypeImpl<PortletAppType<T>>(this, "public-render-paramete...
python
def compare_filesystems(fs0, fs1, concurrent=False): """Compares the two given filesystems. fs0 and fs1 are two mounted GuestFS instances containing the two disks to be compared. If the concurrent flag is True, two processes will be used speeding up the comparison on multiple CPUs. Returns a ...
java
public static String makeValidJavaClassName(String className) { StringBuffer result = new StringBuffer(className.length()); int length = className.length(); boolean nodot = true; for (int i = 0; i < length; i++) { char ch = className.charAt(i); if (nodot) { ...
python
def target(key, full=True): ''' Return the basename of a SysFS key path :param key: the location to resolve within SysFS :param full: full path instead of basename :return: fullpath or basename of path CLI example: .. code-block:: bash salt '*' sysfs.read class/ttyS0 ''' ...
java
private static byte[] getSHEBlock(Block block, byte[] key){ //create a copy of the iv so we can increment it byte[] iv = new byte [32]; System.arraycopy(block.getIV(), 0, iv, 0, iv.length); //increment the iv based on the block number iv[block.getBlockNo()%32] += block.getBlockNo()+1; return Misc.XOR(...
python
def key_to_path(self, key): """Return the fullpath to the file with sha1sum key.""" return os.path.join(self.cache_dir, key[:2], key[2:4], key[4:] + '.pkl')
java
@SuppressWarnings("unchecked") @Override public EList<IfcMaterialDefinitionRepresentation> getHasRepresentation() { return (EList<IfcMaterialDefinitionRepresentation>) eGet(Ifc4Package.Literals.IFC_MATERIAL__HAS_REPRESENTATION, true); }
java
private void readHolidays() { for (MapRow row : m_tables.get("HOL")) { ProjectCalendar calendar = m_calendarMap.get(row.getInteger("CALENDAR_ID")); if (calendar != null) { Date date = row.getDate("DATE"); ProjectCalendarException exception = calendar.add...
java
@Override public DeleteChangeSetResult deleteChangeSet(DeleteChangeSetRequest request) { request = beforeClientExecution(request); return executeDeleteChangeSet(request); }
java
protected ReferenceType mergeReferenceTypes(ReferenceType aRef, ReferenceType bRef) throws DataflowAnalysisException { if (aRef.equals(bRef)) { return aRef; } byte aType = aRef.getType(); byte bType = bRef.getType(); try { // Special case: ExceptionObjectT...
python
def client_kill_filter(self, _id=None, _type=None, addr=None, skipme=None): """ Disconnects client(s) using a variety of filter options :param id: Kills a client by its unique ID field :param type: Kills a client by type where type is one of 'normal', 'master', 'slave' or 'pubsub...
python
def next(self): """ Gets the next page, respecting sort order """ if self._order_by == 'oldest': return self.newer if self._order_by == 'newest': return self.older return None
python
def __store_service(self, key, service): """ Stores the given service in the dictionary :param key: Dictionary key :param service: Service to add to the dictionary """ self._future_value.setdefault(key, []).append(service)
java
private static void outputTzdbDat(OutputStream jos, Map<String, SortedMap<String, ZoneRules>> allBuiltZones, Set<String> allRegionIds, Set<ZoneRules> allRules) throws IOException { DataOutputStream out = new DataOutputStream(jos); // file version out.writeByte(1); ...
python
def _get_resource(self, resource, obj, params=None, **kwargs): """Returns a mapped object from an HTTP resource.""" r = self._http_resource('GET', resource, params=params) item = self._resource_deserialize(r.content.decode("utf-8")) return obj.new_from_dict(item, h=self, **kwargs)
java
@Nullable public <T> Provider<T> getScopedFactory(Class scope, Class<T> classDefinition) { //noinspection unchecked return factories.getScope(scope).get(classDefinition); }
python
def select_leaves(self, name): """Returns all leaves under all nodes matching name """ if self.is_leaf: return [self] if re.search(name, self.label) else [] else: leaves = [] if re.search(name, self.label): for c in self.children: ...
python
def findLastCharIndexMatching(text, func): """ Return index of last character in string for which func(char) evaluates to True. """ for i in range(len(text) - 1, -1, -1): if func(text[i]): return i
python
def run(self): """Launch the broker(s) and worker(s) assigned on every hosts.""" # Launch the broker(s) for hostname, nb_brokers in self.broker_hosts: for ind in range(nb_brokers): if self.externalHostname in utils.localHostnames: self.brokers.appe...
python
def order_stop(backend, order_run_id): """ Stop the run of an order - Stop the running order and keep all state around. """ if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='gre...
java
public void addPathDetails(Map<String, List<PathDetail>> details) { if (!this.pathDetails.isEmpty() && !details.isEmpty() && this.pathDetails.size() != details.size()) { throw new IllegalStateException("Details have to be the same size"); } for (Map.Entry<String, List<PathDetail>> de...
java
private void cleanBvalCache() { if (isBeanValidationVersion11() && !FrameworkState.isStopping()) { ClassLoader classLoader = null; SetContextClassLoaderPrivileged setClassLoader = null; ClassLoader oldClassLoader = null; boolean wasTcclCreated = false; ...
python
def content(self, name, attrs=None, characters=None): """Writes an element, some content for the element, and then closes the element, all without indentation. :name: the name of the element :attrs: a dict of attributes :characters: the characters to write """ with self.no_inner_space(outer...
python
def verify(self, obj): """Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reaso...
python
def find(self, id): """breadth-first sprite search by ID""" for sprite in self.sprites: if sprite.id == id: return sprite for sprite in self.sprites: found = sprite.find(id) if found: return found
python
def _read_plain(self, lines): """ Read text fragments from a plain format text file. :param list lines: the lines of the plain text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) :raises: ValueError: ...
python
def to_add_link(self, ): ''' To add link ''' if self.check_post_role()['ADD']: pass else: return False kwd = { 'pager': '', 'uid': '', } self.render('misc/link/link_add.html', topmenu='', ...
python
def authenticate(cls, client_id, secret): """ Authenticate a client using it's secret :param client_id: the client / service ID :param secret: the client secret :returns: a Service instance """ result = yield views.oauth_client.get(key=[secret, client_id]) ...
python
def poisson_objective(X, m, w): """ Creates an objective function and its derivative for M, given W and X Args: w (array): clusters x cells X (array): genes x cells selected_genes (array): array of ints - genes to be selected """ clusters, cells = w.shape genes = X.shape[...
java
@SuppressWarnings("static-method") @Provides @Singleton public ProgressBarConfig getProgressBarConfig(ConfigurationFactory configFactory, Injector injector) { final ProgressBarConfig config = ProgressBarConfig.getConfiguration(configFactory); injector.injectMembers(config); return config; }
java
public static boolean areEqual(Field destination,Field source){ return getGenericString(destination).equals(getGenericString(source)); }
java
public void marshall(UpdateDeviceStateRequest updateDeviceStateRequest, ProtocolMarshaller protocolMarshaller) { if (updateDeviceStateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateD...
java
private synchronized ZNames loadTimeZoneNames(String tzID) { ZNames tznames = _tzNamesMap.get(tzID); if (tznames == null) { ZNamesLoader loader = new ZNamesLoader(); loader.loadTimeZone(_zoneStrings, tzID); tznames = ZNames.createTimeZoneAndPutInCache(_tzNamesMap, loa...
python
def _CheckFileEntryType(self, file_entry): """Checks the file entry type find specifications. Args: file_entry (FileEntry): file entry. Returns: bool: True if the file entry matches the find specification, False if not or None if no file entry type specification is defined. """ ...
java
protected CmsVfsEntryBean makeEntryBean(CmsResource resource, boolean root) throws CmsException { CmsObject cms = getCmsObject(); boolean isFolder = resource.isFolder(); String name = root ? "/" : resource.getName(); String path = cms.getSitePath(resource); boolean hasChildren =...
java
public List<String> getComments(String tag) { List<String> c = comments.get( normaliseTag(tag) ); if(c == null) { return new ArrayList<String>(); } else { return c; } }
java
public Matrix solve (Matrix B) { return (m == n ? (new LUDecomposition(this)).solve(B) : (new QRDecomposition(this)).solve(B)); }
python
def get_aggregate_check(self, check, age=None): """ Returns the list of aggregates for a given check """ data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)...
java
public void applyTo(List<String> list) { for(int i = 0; i < list.size(); i++) list.set(i, stem(list.get(i))); }
java
private RolePlayerFragmentSet removeRoleVar() { Preconditions.checkNotNull(role()); return new AutoValue_RolePlayerFragmentSet( varProperty(), relation(), edge(), rolePlayer(), null, roleLabels(), relationTypeLabels() ); }
python
def has_in_url_path(url, subs): """Test if any of `subs` strings is present in the `url` path.""" scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
java
public List<EntitySummary> getEntitiesFromApplication(String brooklynId) throws IOException { Invocation invocation = getJerseyClient().target(getEndpoint() + "/v1/applications/" + brooklynId + "/entities") .request().buildGet(); return invocation.invoke().readEntity(new GenericType<Lis...
java
public synchronized void setKey(int i, int key) { if (i < 0 || i >= count) { throw new IndexOutOfBoundsException(); } if (!sortOnValues) { sorted = false; } keys[i] = key; }
python
def dump_report_content(self, request, result): """ Dumps the content to a string, suitable to being written on a file. :param result: The result being processed. :return: string """ output = StringIO() writer = csv.writer(output, **self.csv_kwargs) write...
python
def _apply(self, ctx: ExtensionContext) -> AugmentedDict: """ Replaces any {{var::*}} directives with it's actual variable value or a default. Args: ctx: The processing context. Returns: Returns the altered node key and value. """ node_key, node_...
python
def frombinary(path, ext='bin', conf='conf.json', dtype=None, shape=None, skip=0, index=None, labels=None, engine=None, credentials=None): """ Load series data from flat binary files. Parameters ---------- path : string URI or local filesystem path Directory to load from, can be a URI strin...
python
def pair_strings_sum_formatter(a, b): """ Formats the sum of a and b. Note ---- Both inputs are numbers already converted to strings. """ if b[:1] == "-": return "{0} - {1}".format(a, b[1:]) return "{0} + {1}".format(a, b)
python
def get_names(): """Get colormap names.""" res = list(cmaps.keys()) res = sorted(res, key=lambda s: s.lower()) return res
java
public Project.Layouts.Layout.RolledupStates.Rolledup createProjectLayoutsLayoutRolledupStatesRolledup() { return new Project.Layouts.Layout.RolledupStates.Rolledup(); }
java
protected void addProperties(Root<T> root, Set<String> properties) { // Si le conteneur est vide if(properties == null || properties.size() == 0) return; // Parcours du conteneur for (String property : properties) { // Si la ppt est nulle ou vide if(property == null || property.trim().l...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: return getPFName(); case AfplibPackage.EPF__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); }
java
public static Frame getFromDKV(String param_name, String key_str) { return getFromDKV(param_name, Key.make(key_str)); }
python
def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs): """Query on study properties. See documentation for _OTIWrapper class.""" if self.use_v1: uri = '{p}/singlePropertySearchForStudies'.format(p=self.query_prefix) else: uri = '{p}/find_studies'.f...
java
public static int countTrue(BMatrixRMaj A) { int total = 0; int N = A.getNumElements(); for (int i = 0; i < N; i++) { if( A.data[i] ) total++; } return total; }
java
public void serveFile(final String contentFile, final String root, final String validSubPaths) { if (rootPath == null) { final String slash = root.endsWith("/") ? "" : "/"; rootPath = root + slash; } final String contentPath = rootPath + context.request.uri; try { final byte[] fileCo...
java
public Node cloneNode(boolean deep) { try { if (isXMLDoc == UNKNOWN_TYPE) isXMLDoc = getDocumentType(); if (isXMLDoc == NON_XML) { throw new UnsupportedOperationException( "Text document cannot be cloned"); } // initialize a new...
java
public Record getChild(String key) { Record result = null; if (key != null) { for (Record record : m_records) { if (key.equals(record.getField())) { result = record; break; } } } return result; ...
python
def location(self): """ Returns a ``string`` constant to indicate whether the game was played at the team's home venue, the opponent's venue, or at a neutral site. """ if self._location == '': return HOME if self._location == 'N': return NEUTRAL ...
python
def _add_child_to_dr(self, child, logical_block_size): # type: (dr.DirectoryRecord, int) -> int ''' An internal method to add a child to a directory record, expanding the space in the Volume Descriptor(s) if necessary. Parameters: child - The new child. logical...
python
def query(self, sql, args=None, many=None, as_dict=False): """The connection raw sql query, when select table, show table to fetch records, it is compatible the dbi execute method. :param sql string: the sql stamtement like 'select * from %s' :param args list: Wen set None, will...
python
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): ''' Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str ''' escape = '\\{}'.format return ''....
java
public static boolean isMethodDirectlyExists(Object object, String methodName, Class<?>... params) { try { Method method = object.getClass().getDeclaredMethod(methodName, params); return true; } catch (NoSuchMethodException e) { return false; } catch (SecurityException e) { throw new RuntimeExc...
python
def load_byte(buf, pos): """Load single byte""" end = pos + 1 if end > len(buf): raise BadRarFile('cannot load byte') return S_BYTE.unpack_from(buf, pos)[0], end
java
public void marshall(Flow flow, ProtocolMarshaller protocolMarshaller) { if (flow == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(flow.getAvailabilityZone(), AVAILABILITYZONE_BINDING); ...
python
def samefile(path1, path2): """ Return True if both pathname arguments refer to the same file or directory. Equivalent to "os.path.samefile". Args: path1 (path-like object): Path or URL. path2 (path-like object): Path or URL. Returns: bool: True if same file or directory. ...
java
protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs) { if(callAttrs) m_test.getExpression().callVisitors(m_test, visitor); super.callChildVisitors(visitor, callAttrs); }
java
public static void unmapByteBuffer(final MappedByteBuffer map) { if(map == null) { return; } map.force(); try { if(Runtime.class.getDeclaredMethod("version") != null) return; // At later Java, the hack below will not work anymore. } catch(NoSuchMethodException e) { // T...
java
public static Map<String, String> readProperties(CmsObject cms, I_CmsXmlContentLocation baseLocation) { Map<String, String> result = new HashMap<String, String>(); String elementName = CmsXmlContentProperty.XmlNode.Properties.name(); String nameElementName = CmsXmlContentProperty.XmlNode.Name.n...
java
private MutableSecondaryTypeDefinition getSecondaryTypeDefinition(final String typeId, final boolean includePropertyDefinitions, final boolean baseType) { final TypeDefinitionFactory factory = TypeDefinitionFactory.newInstance(); final MutableSecondaryTypeDefinition def = factory.createSecondaryTypeDefinition...
java
@Override public E peek() { // Copy field to avoid re-reading after volatile load final AtomicReferenceArray<E> buffer = this.buffer; // LoadLoad final long cIndex = lpConsumerIndex(); final int offset = calcElementOffset(cIndex); E e = lvElement(buffer, offset); ...
python
def clear_all(self): """ Clears all cache and metadata. """ for urlpath in self._metadata.keys(): self.clear_cache(urlpath) # Safely clean up anything else. if not os.path.isdir(self._cache_dir): return for subdir in os.listdir(self._cache...
python
def setup_mult_dirs(self): """ setup the directories to use for multiplier parameterization. Directories are make within the PstFromFlopyModel.m.model_ws directory """ # setup dirs to hold the original and multiplier model input quantities set_dirs = [] # if len(self.pp_...
python
def parse_django(classifiers): """Parse out the versions of django supported a/c classifiers.""" prefix = 'Framework :: Django ::' django_classifiers = [c.split('::')[2].strip() for c in classifiers if c.startswith(prefix)] return ', '.join([c for c in django_classifiers if parse_version(c)])
python
def read(self): "Connect to the feedback service and read all data." log.msg('APNSService read (connecting)') try: server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME if self.environment == 'sandbox' else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT) ...
python
def gt(gt_value): """ Validates that a field value is greater than the value given to this validator. """ def validate(value): if value <= gt_value: return e("{} is not greater than {}", value, gt_value) return validate
python
def get_subscribers(self): """ :calls: `GET /repos/:owner/:repo/subscribers <http://developer.github.com/v3/activity/watching>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` """ return github.PaginatedList.PaginatedList( g...
python
def map_constructor(self, loader, node, deep=False): """ Walk the mapping, recording any duplicate keys. """ mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=...
python
def create_custom_gradebook_column(self, course_id, column_title, column_hidden=None, column_position=None, column_teacher_notes=None): """ Create a custom gradebook column. Create a custom gradebook column """ path = {} data = {} params = {} #...
python
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key, user_claims_key, csrf_value=None, audience=None, leeway=0, allow_expired=False): """ Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode ...
java
public ParametricFactorGraph build() { return new ParametricFactorGraph(new DynamicFactorGraph(variables, constantFactors, constantFactorNames), parametricFactors, factorPatterns, parametricFactorNames); }
java
public synchronized void reset() throws IOException { checkClosed(); try { if (mpos <= Integer.MAX_VALUE) { lo.seek((int)mpos); } else { lo.seek64(mpos, LargeObject.SEEK_SET); } buffer = null; apos = mpos; } catch (SQLException se) { throw new IOException(...
java
public boolean execDelete(D6Model[] modelObjs) { if (modelObjs == null || modelObjs.length == 0) { return false; } boolean retVal = false; final D6CrudDeleteHelper dh = new D6CrudDeleteHelper(modelObjs[0].getClass()); final String deleteSQL = dh.createDeletePreparedSQLStatement(); log(...
java
public void invoke(Node root, Action result) throws IOException { doInvoke(0, root, root.isLink(), new ArrayList<>(includes), new ArrayList<>(excludes), result); }
python
def chdir(self, target_directory): """Change current working directory to target directory. Args: target_directory: The path to new current working directory. Raises: OSError: if user lacks permission to enter the argument directory or if the target is n...
java
public Collection<String> scanPackages() { return scanJar(p -> Files.isDirectory(p) && !isIgnored(p.toAbsolutePath())); }
java
public RebuildWorkspacesRequest withRebuildWorkspaceRequests(RebuildRequest... rebuildWorkspaceRequests) { if (this.rebuildWorkspaceRequests == null) { setRebuildWorkspaceRequests(new com.amazonaws.internal.SdkInternalList<RebuildRequest>(rebuildWorkspaceRequests.length)); } for (Reb...
python
def set_review_solution(self, during_attempt=None, after_attempt=None, before_deadline=None, after_deadline=None): """stub""" solution = self.my_osid_object_form._my_map['reviewOptions']['solu...
java
protected final void setCurrentParentView(@NonNull final View currentParentView) { Condition.INSTANCE.ensureNotNull(currentParentView, "The parent view may not be null"); this.currentParentView = currentParentView; }
java
public void addHttpHeaderToResponseStream(final HttpServletResponse servletResponse, final UriInfo uriInfo, final FedoraResource resource) { getUriAwareHttpHeaderFactories().forEach((bean, factory) -> { LOGG...
python
def get_asset_admin_session_for_repository(self, repository_id=None, *args, **kwargs): """Gets an asset administration session for the given repository. arg: repository_id (osid.id.Id): the Id of the repository return: (osid.repository.AssetAdminSession) - an AssetAdminSessio...
python
def team_players(self, team): """Store output of team players to a CSV file""" headers = ['Jersey Number', 'Name', 'Position', 'Nationality', 'Date of Birth'] result = [headers] result.extend([player['shirtNumber'], player['name'], ...
java
protected void searchStarted() { // initialize init(); // (re)set metadata startTime = System.currentTimeMillis(); stopTime = JamesConstants.INVALID_TIMESTAMP; currentSteps = 0; lastImprovementTime = JamesConstants.INVALID_TIMESTAMP; stepsSinceLastImprovem...
java
protected void resolvePropertyReplacements(Api api) { if (api == null) { return; } String endpoint = api.getEndpoint(); endpoint = resolveProperties(endpoint); api.setEndpoint(endpoint); Map<String, String> properties = api.getEndpointProperties(); fo...
python
def small_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.""" if self.application_id is None: return None try: small_image = self.assets['small_image'] except KeyError: return ...
python
async def maintenance(self, service, enable, *, reason=None): """Enters maintenance mode / Resumes normal operation for service Parameters: service (ObjectID): Service ID enable (bool): Enter or exit maintenance mode reason (str): Text string explaining the reason fo...
java
protected void removePersistedSession(String id) { if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) { LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[REMOVE_PERSISTED_SESSION], id); } Connect...
python
def get_waiter(self, waiter_name): """Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter ob...
java
public DeleteAgentStatisticResponse deleteAgentStatistic(String object) throws ApiException { ApiResponse<DeleteAgentStatisticResponse> resp = deleteAgentStatisticWithHttpInfo(object); return resp.getData(); }
python
def library_pg(args, l, config): """Report on the operation of a Postgres Library database""" import tabulate import terminaltables from textwrap import fill from ambry.util.text import getTerminalSize import sys if args.connect: try: l.database.connection.execute('SELEC...