language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void clearLayerMaskArrays() { for (Layer layer : layers) { layer.setMaskArray(null); } this.inputMaskArrays = null; this.labelMaskArrays = null; }
java
@SuppressWarnings("null") private Object parseBean(final Class<?> beanType) throws Exception { String propName = ""; try { XMLEvent event = null; // handle case where whole bean is Joda-Convert string if (settings.getConverter().isConvertible(beanType)) { ...
python
def _collect_names(handlers, scopes, user, client): """ Get the names of the claims supported by the handlers for the requested scope. """ results = set() data = {'user': user, 'client': client} def visitor(_scope_name, func): claim_names = func(data) # If the claim_names is None, it ...
java
public void add(final OrchestrationShardingSchema orchestrationShardingSchema) { String schemaName = orchestrationShardingSchema.getSchemaName(); if (!schemaGroup.containsKey(schemaName)) { schemaGroup.put(schemaName, new LinkedList<String>()); } schemaGroup.get(schemaName).a...
java
public Observable<JobAgentInner> getAsync(String resourceGroupName, String serverName, String jobAgentName) { return getWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName).map(new Func1<ServiceResponse<JobAgentInner>, JobAgentInner>() { @Override public JobAgentInner ca...
python
def master_for(self, service): """Returns wrapper to master's pool for requested service.""" # TODO: make it coroutine and connect minsize connections if service not in self._masters: self._masters[service] = ManagedPool( self, service, is_master=True, ...
java
public static <K, E> Collector<E, Map<K, E>, ImmutableMap<K, E>> uniqueIndex(Function<? super E, K> keyFunction) { return uniqueIndex(keyFunction, Function.<E>identity()); }
java
protected String getCellClass(HtmlRenderingContext context, int row, int col) { if (ArrayUtils.indexOf(_highlightedColumns, col) == -1) { return null; } return "highlighted"; }
python
def _run(self): '''Continually poll TWS''' stop = self._stop_evt connected = self._connected_evt tws = self._tws fd = tws.fd() pollfd = [fd] while not stop.is_set(): while (not connected.is_set() or not tws.isConnected()) and not stop.is_set(): ...
python
def validate_and_decode(jwt_bu64, cert_obj): """Example for validating the signature of a JWT using only the cryptography library. Note that this does NOT validate the claims in the claim set. """ public_key = cert_obj.public_key() message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:...
java
public synchronized void replaceSegments(Collection<Segment> segments, Segment segment) { // Update the segment descriptor and lock the segment. segment.descriptor().update(System.currentTimeMillis()); segment.descriptor().lock(); // Iterate through old segments and remove them from the segments list. ...
java
private List<List<Integer>> calcOrbits() { int n = subunits.getSubunitCount(); List<List<Integer>> orbits = new ArrayList<List<Integer>>(); for (int i = 0; i < n; i++) { orbits.add(Collections.singletonList(i)); } return orbits; }
python
def TTA(self, n_aug=4, is_test=False): """ Predict with Test Time Augmentation (TTA) Additional to the original test/validation images, apply image augmentation to them (just like for training images) and calculate the mean of predictions. The intent is to increase the accuracy of predi...
java
public EClass getGRLINERG() { if (grlinergEClass == null) { grlinergEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(500); } return grlinergEClass; }
java
public static <K, V> KeyAffinityService<K> newKeyAffinityService(Cache<K, V> cache, Executor ex, KeyGenerator<K> keyGenerator, int keyBufferSize) { return newKeyAffinityService(cache, ex, keyGenerator, keyBufferSize, true); }
python
def _model_abilities_one_components(self,beta): """ Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array ...
java
public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions) { boolean bFlag = false; if (strCommand.equalsIgnoreCase(ThinMenuConstants.UNDO)) { // Special - handle undo if (m_sfTarget != null) if (m_sfTarget.getScreenFieldView().ge...
python
def _update_service_context(self, resp, **kwargs): """ Deal with Provider Config Response. Based on the provider info response a set of parameters in different places needs to be set. :param resp: The provider info response :param service_context: Information collected/used by s...
python
def add_private_note(self, private_notes, source=None): """Add private notes. :param private_notes: hidden notes for the current document :type private_notes: string :param source: source for the given private notes :type source: string """ self._append_to('_pri...
python
def getJSModuleURL(self, moduleName): """ Retrieve an L{URL} object which references the given module name. This makes a 'best effort' guess as to an fully qualified HTTPS URL based on the hostname provided during rendering and the configuration of the site. This is to avoid un...
python
def delete_user_template(self, uid=0, temp_id=0, user_id=''): """ Delete specific template :param uid: user ID that are generated from device :param user_id: your own user ID :return: bool """ if self.tcp and user_id: command = 134 command...
python
def ask_user_for_telemetry(): """ asks the user for if we can collect telemetry """ answer = " " while answer.lower() != 'yes' and answer.lower() != 'no': answer = prompt(u'\nDo you agree to sending telemetry (yes/no)? Default answer is yes: ') if answer == '': answer = 'yes' ...
python
def frequencies_iter(self): """ Iterates over all non-zero frequencies of logical conjunction mappings in this list Yields ------ tuple[caspo.core.mapping.Mapping, float] The next pair (mapping,frequency) """ f = self.__matrix.mean(axis=0) for...
java
public static <T> Collector<T, ?, Long> summingLong(ToLongFunction<? super T> mapper) { return new CollectorImpl<>( () -> new long[1], (a, t) -> { a[0] += mapper.applyAsLong(t); }, (a, b) -> { a[0] += b[0]; return a; }, a -> a[0], CH_NOID); ...
python
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True): """ Get a logger for ResourceProvider and it's components, such as Allocators. :param name: Name for logger :param short_name: Shorthand name for the logger :param log_to_file: Boolean, True if logger should log to a file...
python
def get_remote_settings(self, name): import posixpath """ Args: name (str): The name of the remote that we want to retrieve Returns: dict: The content beneath the given remote name. Example: >>> config = {'remote "server"': {'url': 'ssh://lo...
java
@Invalidate public void stop() { if (registration != null) { registration.unregister(); registration = null; } if (manager != null) { manager.removeCache(WISDOM_KEY); } }
python
def import_config(self): """ Loads parameters from config files Returns ------- int config object #TODO check type """ # load parameters from configs cfg_ding0.load_config('config_db_tables.cfg') cfg_ding0.load_config('config_calc.cfg') ...
java
public static String replaceFirst(String source, String pattern, String replacement) { return replaceOne(source, pattern, replacement, findFirst(source, pattern)); }
python
def _get_source(link): """ Return source of the `link` whether it is filename or url. Args: link (str): Filename or URL. Returns: str: Content. Raises: UserWarning: When the `link` couldn't be resolved. """ if link.startswith("http://") or link.startswith("https://...
java
@SuppressWarnings("unchecked") private <T> T[] getArrayValue(Class<T> type, String propertyName, EDBObject object) { List<T> elements = getListValue(type, propertyName, object); T[] ar = (T[]) Array.newInstance(type, elements.size()); return elements.toArray(ar); }
python
def _non_local_part(q0: ops.Qid, q1: ops.Qid, interaction_coefficients: Tuple[float, float, float], allow_partial_czs: bool, atol: float = 1e-8): """Yields non-local operation of KAK decomposition.""" x, y, z = interaction_coeffici...
java
public static <K, V> V getIfAbsentPut(Map<K, V> map, K key, Function0<? extends V> instanceBlock) { if (map instanceof MutableMap) { return ((MutableMap<K, V>) map).getIfAbsentPut(key, instanceBlock); } V result = map.get(key); if (MapIterate.isAbsent(result, map,...
python
def get_property(self, index, doctype, name): """ Returns a property of a given type :return a mapped property """ return self.indices[index][doctype].properties[name]
java
public PMSession getSession(String sessionId) { final PMSession s = sessions.get(sessionId); if (s != null) { s.setLastAccess(new Date()); } return s; }
python
def slurpChompedLines(file, expand=False): r"""Return ``file`` a list of chomped lines. See `slurpLines`.""" f=_normalizeToFile(file, "r", expand) try: return list(chompLines(f)) finally: f.close()
python
def list(self, list_folders=False, list_files=False): """ A simple generator that yields a File or Folder object based on the arguments. """ a_files = os.listdir(self.folder.path) for a_file in a_files: path = self.folder.child(a_file) if os.path....
python
def lock(self, name, ttl=60): """ Create a new lock. :param name: name of the lock :type name: string or bytes :param ttl: length of time for the lock to live for in seconds. The lock will be released after this time elapses, unless refres...
java
private SequenceLabel makeName(final String nameString, final String neType) { final SequenceLabel name = this.nameFactory.createSequence(nameString, neType, this.yychar, yylength()); return name; }
java
public AutomatonInstance doClone() { AutomatonInstance clone = new AutomatonInstance(this.automatonEng, this.current, this.instanceId, this.safeGuard); clone.failed = this.failed; clone.transitionCount = this.transitionCount; clone.failCount = this.failCount; clone.iterateCount = this.iterateCount; clone.ba...
java
public int handleMessage(BaseMessage message) { Record record = this.getMainRecord(); // Record changed if ((record.getTable() instanceof GridTable) // Always except HTML && (message.getMessageHeader() != null) && (message.getMessageHeader() instanceof RecordMessageHe...
python
def decrypt(text, key=None): """ Decrypts the inputted text using the inputted key. :param text | <str> key | <str> :return <str> """ if key is None: key = ENCRYPT_KEY bits = len(key) text = base64.b64decode(text) iv = text[:16] ...
java
public Date getDate(int columnIndex) throws SQLException { TimestampData t = (TimestampData) getColumnInType(columnIndex, Type.SQL_DATE); if (t == null) { return null; } return (Date) Type.SQL_DATE.convertSQLToJava(session, t); }
java
public ApiResponse<ApiSuccessResponse> addDocumentWithHttpInfo(String mediatype, String id, AddDocumentData addDocumentData) throws ApiException { com.squareup.okhttp.Call call = addDocumentValidateBeforeCall(mediatype, id, addDocumentData, null, null); Type localVarReturnType = new TypeToken<ApiSuccess...
java
void setResponse(HttpResponse response) { if (isResponseAborted) { // This means that we already tried to close the request, so abort the response immediately. if (!response.isComplete()) { response.abort(); } } else { this.response = respo...
java
public static final Mat4 lookAt(final Vec3 eye, final Vec3 center, final Vec3 up) { final Vec3 f = center.subtract(eye).getUnitVector(); Vec3 u = up.getUnitVector(); final Vec3 s = f.cross(u).getUnitVector(); u = s.cross(f); return new Mat4( s.x, u.x, -f.x, 0f, s.y, u.y, -f.y, 0f, s.z, u.z, -f....
python
async def list(self): ''' Get a list of (name, info) tuples for the CryoTanks. Returns: list: A list of tufos. ''' return [(name, await tank.info()) for (name, tank) in self.tanks.items()]
java
public static boolean onCheckMainThread(BooleanSupplier defaultChecker) { if (defaultChecker == null) { throw new NullPointerException("defaultChecker == null"); } BooleanSupplier current = onCheckMainThread; try { if (current == null) { return defaultChecker.getAsBoolean(); } ...
python
def _construct_as_path_attr(self, as_path_attr, as4_path_attr): """Marge AS_PATH and AS4_PATH attribute instances into a single AS_PATH instance.""" def _listify(li): """Reconstruct AS_PATH list. Example:: >>> _listify([[1, 2, 3], {4, 5}, [6, 7]]) ...
java
public List<TypeFieldInner> listFieldsByType(String resourceGroupName, String automationAccountName, String typeName) { return listFieldsByTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, typeName).toBlocking().single().body(); }
python
def drawPoints(points, bg=','): """A small debug function that takes an iterable of (x, y) integer tuples and draws them to the screen.""" # Note: I set bg to ',' instead of '.' because using ... in the docstrings # confuses doctest and makes it think it's Python's secondary ... prompt, # causing d...
python
def _create_inverse_maps(self): '''Create the inverse mappings (UniParc -> SEQRES -> ATOM -> Rosetta).''' # We have already determined that the inverse maps are well-defined (the normal maps are injective). The inverse maps will be partial maps in general. self.atom_to_rosetta_sequence_maps = ...
java
protected Name nextNameForVersionNode( Property predecessors, ChildReferences historyChildren ) { String proposedName = null; CachedNode versionNode = null; // Try to find the versions in the history that are considered predecessors ... if (pre...
java
public List<SecondaryTable<Entity<T>>> getAllSecondaryTable() { List<SecondaryTable<Entity<T>>> list = new ArrayList<SecondaryTable<Entity<T>>>(); List<Node> nodeList = childNode.get("secondary-table"); for(Node node: nodeList) { SecondaryTable<Entity<T>> type = new SecondaryTableIm...
python
def set_default_calibrator(self, parameter, type, data): # pylint: disable=W0622 """ Apply a calibrator while processing raw values of the specified parameter. If there is already a default calibrator associated to this parameter, that calibrator gets replaced. .. note:: ...
java
private JsonObject getPendingJSONObject() { for (Map.Entry<String, BoxJSONObject> entry : this.children.entrySet()) { BoxJSONObject child = entry.getValue(); JsonObject jsonObject = child.getPendingJSONObject(); if (jsonObject != null) { if (this.pendingChange...
java
public static IWicketJquerySelectorsSettings assignedSettingsOrDefault() { Application app = Application.exists() ? Application.get() : null; if (isInstalled(app)) { return settings(); } else { LOG.info("try to get settings, but WicketJquerySelectors wasn't installed to ...
python
def _on_queue_declareok(self, frame): """ Callback invoked when a queue is successfully declared. Args: frame (pika.frame.Method): The message sent from the server. """ _log.info("Successfully declared the %s queue", frame.method.queue) for binding in self._b...
java
public static void debugLogDOMFeatures () { for (final Map.Entry <EXMLDOMFeatureVersion, ICommonsList <String>> aEntry : s_aSupportedFeatures.entrySet ()) for (final String sFeature : aEntry.getValue ()) if (LOGGER.isInfoEnabled ()) LOGGER.info ("DOM " + aEntry.getKey ().getID () + " featu...
python
def basic_auth(credentials): """Create an HTTP basic authentication callable Parameters ---------- credentials: ~typing.Tuple[str, str] The (username, password)-tuple Returns ------- ~typing.Callable[[Request], Request] A callable which adds basic authentication to a :class...
java
public void start(String rmc) throws GassException { if (rmc == null) { throw new IllegalArgumentException("Resource manager contact not specified"); } GassServer gassServer = null; String error = null; try { gassServer = new GassServer(this.cred, 0); String gassURL = gassServer...
python
def line_and_column(text, position): """Return the line number and column of a position in a string.""" position_counter = 0 for idx_line, line in enumerate(text.splitlines(True)): if (position_counter + len(line.rstrip())) >= position: return (idx_line, position - position_counter) ...
java
@Override public Optional<ResourceID> failAllocation(final AllocationID allocationID, final Exception cause) { componentMainThreadExecutor.assertRunningInMainThread(); final PendingRequest pendingRequest = pendingRequests.removeKeyB(allocationID); if (pendingRequest != null) { // request was still pending ...
python
def find_descriptor(desc, find_all=False, custom_match=None, **args): r"""Find an inner descriptor. find_descriptor works in the same way as the core.find() function does, but it acts on general descriptor objects. For example, suppose you have a Device object called dev and want a Configuration of thi...
python
def destroy(self): """ Destroy the consumer group. """ resp = {} for key in self.keys: resp[key] = self.database.xgroup_destroy(key, self.name) return resp
python
def filter_by(self, types=(), units=()): """Return list of value labels, filtered by either or both type and unit. An empty sequence for either argument will match as long as the other argument matches any values.""" if not (isinstance(types, Sequence) and isinstance(units, Sequence)): ...
python
def clear_target_names(self, target_id): """stub""" if self.get_targets_metadata().is_read_only(): raise NoAccess() updated_targets = [] for current_target in self.my_osid_object_form._my_map['targets']: if current_target['id'] != target_id: update...
python
def _get_models(self, app): """ return models_array """ try: app_models = app.get_models() appmods = [] for model in app_models: appmods.append(model) except Exception as e: self.err(e) return ret...
python
def merge_figures(figures): """ Generates a single Figure from a list of figures Parameters: ----------- figures : list(Figures) List of figures to be merged. """ figure={} data=[] for fig in figures: for trace in fig['data']: data.append(trace) layout=get_base_layout(figures) figure['data']=data ...
java
public void render(int x, int y, int layer) { render(x, y, 0, 0, getWidth(), getHeight(), layer, false); }
java
public static void invokeServiceAdded(ServiceConfig cfg, Service<?, ?> service) { requireNonNull(cfg, "cfg"); requireNonNull(service, "service"); try { service.serviceAdded(cfg); } catch (Exception e) { throw new IllegalStateException( "failed...
java
@Override protected Content getNavLinkModule() { Content linkContent = getModuleLink(utils.elementUtils.getModuleOf(annotationType), contents.moduleLabel); Content li = HtmlTree.LI(linkContent); return li; }
python
def DbDeleteDeviceAttributeProperty(self, argin): """ delete a device attribute property from the database :param argin: Str[0] = Device name Str[1] = Attribute name Str[2] = Property name Str[n] = Property name :type: tango.DevVarStringArray :return: :rt...
java
@Override public void type(String text) throws WidgetException{ try{ if (getGUIDriver().isJavascriptTypeMode()) { // Replaces apostrophes that have not been escaped with escaped variations // Slashes need to be escaped multiple times. Once for Java's string escaping ...
python
def _slice_at(self, index, length=1): """Create a slice for index and length.""" length_ = len(self) if -length <= index < 0: index += length_ return slice(index, index + length)
python
def config_altered(self, persistGlobal): """ Called when some element of configuration has been altered, to update the lists of phrases/folders. @param persistGlobal: save the global configuration at the end of the process """ _logger.info("Configuration changed...
java
public DoubleParameter setDefaultValue(double defaultValue) { super.setDefaultValue(defaultValue); if (hasMinimumValue) { if (minimumValueInclusive) { Util.checkParameter(defaultValue >= minimumValue, "Default value (" + defaultValue + ") must be greater than or equal to minimum (" + minimumValue + ")"...
python
def sens_atmos_send(self, TempAmbient, Humidity, force_mavlink1=False): ''' Atmospheric sensors (temperature, humidity, ...) TempAmbient : Ambient temperature [degrees Celsius] (float) Humidity : Relative humidity [%] (float...
java
protected void onGetImageSuccess(String cacheKey, Bitmap response) { // cache the image that was fetched. imageCache.putBitmap(cacheKey, response); // remove the request from the list of in-flight requests. BatchedImageRequest request = inFlightRequests.remove(cacheKey); if (re...
python
def main(): """function to """ # parse arg to find file(s) parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="convert the markdown file to HTML") parser.add_argument("-d", "--directory", help="convert the markdown files in the...
python
def set_params(self, deep=False, force=False, **parameters): """ sets an object's paramters Parameters ---------- deep : boolean, default: False when True, also sets non-user-facing paramters force : boolean, default: False when True, also sets pa...
python
def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string
python
def camel_case_to_snake_case(name): """ HelloWorld -> hello_world """ s1 = _FIRST_CAP_RE.sub(r'\1_\2', name) return _ALL_CAP_RE.sub(r'\1_\2', s1).lower()
python
def prod(self): """Return the product of ``self``. See Also -------- numpy.prod sum """ results = [x.ufuncs.prod() for x in self.elem] return np.prod(results)
python
def get_instance_id(self, instance): " Returns instance pk even if multiple instances were passed to RichTextField. " if type(instance) in [list, tuple]: core_signals.request_finished.connect(receiver=RichTextField.reset_instance_counter_listener) if RichTextField.__inst_counter ...
python
def get_dev_mac_learn(devid, auth, url): ''' function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.a...
python
def get_recently_played_games(self, steamID, count=0, format=None): """Request a list of recently played games by a given steam id. steamID: The users ID count: Number of games to return. (0 is all recent games.) format: Return format. None defaults to json. (json, xml, vdf) ""...
python
def create_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None, grant_type_for_scope=None, claims=None): """Extract grant_type and route to the designated handler.""" request = Request( uri, http_m...
java
public static void registerConstructor(String module, String classname, IObjectConstructor constructor) { objectConstructors.put(module + "." + classname, constructor); }
java
@Override public void dumpResponse(Map<String, Object> result) { Map<String, Cookie> cookiesMap = exchange.getResponseCookies(); dumpCookies(cookiesMap, "responseCookies"); this.putDumpInfoTo(result); }
java
private static List<FieldSchema> getFieldSchemas(HiveRegistrationUnit unit) { List<Column> columns = unit.getColumns(); List<FieldSchema> fieldSchemas = new ArrayList<>(); if (columns != null && columns.size() > 0) { fieldSchemas = getFieldSchemas(columns); } else { Deserializer deserializer...
python
def sigma_r2(self, r, a, gamma, rho0_r0_gamma, r_ani): """ equation (19) in Suyu+ 2010 """ # first term prefac1 = 4*np.pi * const.G * a**(-gamma) * rho0_r0_gamma / (3-gamma) prefac2 = r * (r + a)**3/(r**2 + r_ani**2) hyp1 = vel_util.hyp_2F1(a=2+gamma, b=gamma, c=3...
java
@Override protected ITerminalStatement getLeastSignificantTerminalStatement_internal( boolean[] bAbsolute ) { ITerminalStatement termRet = null; bAbsolute[0] = true; boolean bBreak = false; ITerminalStatement lastCaseTerm = null; if( _cases != null ) { for( int i = 0; i < _cases.length...
python
def create_object(self, filename, read_only=False): """Create a functional data object for the given file. Expects the file to be a valid functional data file. Expects exactly one file that has suffix mgh/mgz or nii/nii.gz. Parameters ---------- filename : string ...
java
private boolean hasSubGroup(int tmp_model,int tmp_chain,int tmp_group) { if (tmp_model >= structure.nrModels()) { return false; } List<Chain> model = structure.getModel(tmp_model); if (tmp_chain >= model.size()) { if(fixed_model) return false; return hasSubGroup(tmp_model + 1, 0, 0); } Chai...
python
def max_n(self): """Returns the maximum index of Pauli matrices in the Term.""" return max(term.max_n() for term in self.terms if term.ops)
java
public String readBestUrlName(CmsDbContext dbc, CmsUUID id, Locale locale, List<Locale> defaultLocales) throws CmsDataAccessException { List<CmsUrlNameMappingEntry> entries = getVfsDriver(dbc).readUrlNameMappingEntries( dbc, dbc.currentProject().isOnlineProject(), CmsUrl...
java
public static ExtensionId toExtensionId(String groupId, String artifactId, String classifier, Version version) { String extensionId = toExtensionId(groupId, artifactId, classifier); return new ExtensionId(extensionId, version); }
java
public static List<CPDefinitionOptionValueRel> findByCompanyId( long companyId, int start, int end) { return getPersistence().findByCompanyId(companyId, start, end); }
python
def graph_sparsify(M, epsilon, maxiter=10): r"""Sparsify a graph (with Spielman-Srivastava). Parameters ---------- M : Graph or sparse matrix Graph structure or a Laplacian matrix epsilon : int Sparsification parameter Returns ------- Mnew : Graph or sparse matrix ...