language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static AnnotationMemberDeclaration mergeAnnotationMember( AnnotationMemberDeclaration one, AnnotationMemberDeclaration two) { if (isAllNull(one, two)) return null; AnnotationMemberDeclaration amd = null; if (isAllNotNull(one, two)) { amd = new AnnotationMemberDeclaration(); amd.setJavaDoc(mergeSelective(one.getJavaDoc(), two.getJavaDoc())); amd.setComment(mergeSelective(one.getComment(), two.getComment())); amd.setAnnotations(mergeListNoDuplicate(one.getAnnotations(), two.getAnnotations())); amd.setModifiers(mergeModifiers(one.getModifiers(), two.getModifiers())); amd.setName(one.getName()); amd.setDefaultValue(mergeSelective(one.getDefaultValue(), two.getDefaultValue())); amd.setType(mergeSelective(one.getType(), two.getType())); LOG.info("merge AnnotationMemberDeclaration --> {}", amd.getName()); } else { amd = findFirstNotNull(one, two); LOG.info("add AnnotationMemberDeclaration --> {}", amd.getName()); } return amd; }
python
def find_encrypt_data(self, resp): """ Verifies if a saml response contains encrypted assertions with encrypted data. :param resp: A saml response. :return: True encrypted data exists otherwise false. """ if resp.encrypted_assertion: res = self.find_encrypt_data_assertion(resp.encrypted_assertion) if res: return True if resp.assertion: for tmp_assertion in resp.assertion: if tmp_assertion.advice: if tmp_assertion.advice.encrypted_assertion: res = self.find_encrypt_data_assertion( tmp_assertion.advice.encrypted_assertion) if res: return True return False
java
public java.lang.String getNodeName() { java.lang.Object ref = nodeName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nodeName_ = s; return s; } }
python
def plot_learning_curve(classifiers, train, test=None, increments=100, metric="percent_correct", title="Learning curve", label_template="[#] @ $", key_loc="lower right", outfile=None, wait=True): """ Plots a learning curve. :param classifiers: list of Classifier template objects :type classifiers: list of Classifier :param train: dataset to use for the building the classifier, used for evaluating it test set None :type train: Instances :param test: optional dataset (or list of datasets) to use for the testing the built classifiers :type test: list or Instances :param increments: the increments (>= 1: # of instances, <1: percentage of dataset) :type increments: float :param metric: the name of the numeric metric to plot (Evaluation.<metric>) :type metric: str :param title: the title for the plot :type title: str :param label_template: the template for the label in the plot (#: 1-based index of classifier, @: full classname, !: simple classname, $: options, *: 1-based index of test set) :type label_template: str :param key_loc: the location string for the key :type key_loc: str :param outfile: the output file, ignored if None :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return if not train.has_class(): logger.error("Training set has no class attribute set!") return if increments >= 1: inc = increments else: inc = round(train.num_instances * increments) if test is None: tst = [train] elif isinstance(test, list): tst = test elif isinstance(test, Instances): tst = [test] else: logger.error("Expected list or Instances object, instead: " + type(test)) return for t in tst: if train.equal_headers(t) is not None: logger.error("Training and test set are not compatible: " + train.equal_headers(t)) return steps = [] cls = [] evls = {} for classifier in classifiers: cl = Classifier.make_copy(classifier) cls.append(cl) evls[cl] = {} for t in tst: evls[cl][t] = [] for i in range(train.num_instances): if (i > 0) and (i % inc == 0): steps.append(i+1) for cl in cls: # train if cl.is_updateable: if i == 0: tr = Instances.copy_instances(train, 0, 1) cl.build_classifier(tr) else: cl.update_classifier(train.get_instance(i)) else: if (i > 0) and (i % inc == 0): tr = Instances.copy_instances(train, 0, i + 1) cl.build_classifier(tr) # evaluate if (i > 0) and (i % inc == 0): for t in tst: evl = Evaluation(t) evl.test_model(cl, t) evls[cl][t].append(getattr(evl, metric)) fig, ax = plt.subplots() ax.set_xlabel("# of instances") ax.set_ylabel(metric) ax.set_title(title) fig.canvas.set_window_title(title) ax.grid(True) i = 0 for cl in cls: evlpertest = evls[cl] i += 1 n = 0 for t in tst: evl = evlpertest[t] n += 1 plot_label = label_template.\ replace("#", str(i)).\ replace("*", str(n)).\ replace("@", cl.classname).\ replace("!", cl.classname[cl.classname.rfind(".") + 1:]).\ replace("$", join_options(cl.config)) ax.plot(steps, evl, label=plot_label) plt.draw() plt.legend(loc=key_loc, shadow=True) if outfile is not None: plt.savefig(outfile) if wait: plt.show()
python
def _ensure_field(self, key): """Ensure a non-array field""" if self._has_field: self._size += 2 # comma, space self._has_field = True self._size += len(key) + 4
python
def CRRAutility_inv(u, gam): ''' Evaluates the inverse of the CRRA utility function (with risk aversion para- meter gam) at a given utility level u. Parameters ---------- u : float Utility value gam : float Risk aversion Returns ------- (unnamed) : float Consumption corresponding to given utility value ''' if gam == 1: return np.exp(u) else: return( ((1.0-gam)*u)**(1/(1.0-gam)) )
python
def vcs_virtual_ipv6_address_ipv6address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocade-vcs") virtual = ET.SubElement(vcs, "virtual") ipv6 = ET.SubElement(virtual, "ipv6") address = ET.SubElement(ipv6, "address") ipv6address = ET.SubElement(address, "ipv6address") ipv6address.text = kwargs.pop('ipv6address') callback = kwargs.pop('callback', self._callback) return callback(config)
python
def create_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0): """ Function creates box. Based on orientation it can be either HORIZONTAL or VERTICAL """ h_box = Gtk.Box(orientation=orientation, spacing=spacing) h_box.set_homogeneous(False) return h_box
python
def _division(divisor, dividend, remainder, base): """ Get the quotient and remainder :param int divisor: the divisor :param dividend: the divident :type dividend: sequence of int :param int remainder: initial remainder :param int base: the base :returns: quotient and remainder :rtype: tuple of (list of int) * int Complexity: O(log_{divisor}(quotient)) """ quotient = [] for value in dividend: remainder = remainder * base + value (quot, rem) = divmod(remainder, divisor) quotient.append(quot) if quot > 0: remainder = rem return (quotient, remainder)
java
protected Binder findBinderByPropertyName(Class parentObjectType, String propertyName) { PropertyNameKey key = new PropertyNameKey(parentObjectType, propertyName); Binder binder = (Binder)propertyNameBinders.get(key); if (binder == null) { // if no direct match was found try to find a match in any super classes final Map potentialMatchingBinders = new HashMap(); for (Iterator i = propertyNameBinders.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); if (((PropertyNameKey)entry.getKey()).getPropertyName().equals(propertyName)) { potentialMatchingBinders.put(((PropertyNameKey)entry.getKey()).getParentObjectType(), entry.getValue()); } } binder = (Binder) ClassUtils.getValueFromMapForClass(parentObjectType, potentialMatchingBinders); if (binder != null) { // remember the lookup so it doesn't have to be discovered again registerBinderForPropertyName(parentObjectType, propertyName, binder); } } return binder; }
java
@Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case FrameworkEvent.ERROR: status.addStartException(event.getBundle(), event.getThrowable()); break; // Wake up the listener if a startlevel changed event occurs, // or the framework is stopped... case FrameworkEvent.STOPPED: case FrameworkEvent.STOPPED_UPDATE: case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED: case FrameworkEvent.STARTLEVEL_CHANGED: levelReached(false); break; default: break; } }
java
public ServiceFuture<OperationStatus> deleteRegexEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId, final ServiceCallback<OperationStatus> serviceCallback) { return ServiceFuture.fromResponse(deleteRegexEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId), serviceCallback); }
python
def _upload_folder_in_background(self, folder_path, container, ignore, upload_key, ttl=None): """Runs the folder upload in the background.""" uploader = FolderUploader(folder_path, container, ignore, upload_key, self, ttl=ttl) uploader.start()
python
def SetHasherNames(self, hasher_names_string): """Sets the hashers that should be enabled. Args: hasher_names_string (str): comma separated names of hashers to enable. """ hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString( hasher_names_string) debug_hasher_names = ', '.join(hasher_names) logger.debug('Got hasher names: {0:s}'.format(debug_hasher_names)) self._hashers = hashers_manager.HashersManager.GetHashers(hasher_names) self._hasher_names_string = hasher_names_string
java
@Override public UnblockingAckMessage createUBA(int cic) { UnblockingAckMessage msg = createUBA(); CircuitIdentificationCode code = this.parameterFactory.createCircuitIdentificationCode(); code.setCIC(cic); msg.setCircuitIdentificationCode(code); return msg; }
java
public static GeoShape fromJson(String json) { try { return JsonSerializer.fromString(json, GeoShape.class); } catch (IOException e) { throw new IllegalArgumentException("Unparseable shape"); } }
python
def randomString(size: int = 20) -> str: """ Generate a random string in hex of the specified size DO NOT use python provided random class its a Pseudo Random Number Generator and not secure enough for our needs :param size: size of the random string to generate :return: the hexadecimal random string """ def randomStr(size): if not isinstance(size, int): raise PlenumTypeError('size', size, int) if not size > 0: raise PlenumValueError('size', size, '> 0') # Approach 1 rv = randombytes(size // 2).hex() return rv if size % 2 == 0 else rv + hex(randombytes_uniform(15))[-1] # Approach 2 this is faster than Approach 1, but lovesh had a doubt # that part of a random may not be truly random, so until # we have definite proof going to retain it commented # rstr = randombytes(size).hex() # return rstr[:size] return randomStr(size)
python
def get_language_tabs(self): """ Determine the language tabs to show. """ current_language = self.get_current_language() if self.object: available_languages = list(self.object.get_available_languages()) else: available_languages = [] return get_language_tabs(self.request, current_language, available_languages)
python
def _parse_player(self, index, attributes, postgame, game_type): """Parse a player.""" try: voobly_user = voobly.user(self._voobly_session, attributes.player_name, ladder_ids=VOOBLY_LADDERS.values()) voobly_ladder = '{} {}'.format(game_type, self._diplomacy['type']) voobly_ladder_id = VOOBLY_LADDERS.get(voobly_ladder) if voobly_ladder_id in voobly_user['ladders']: voobly_rating = voobly_user['ladders'].get(voobly_ladder_id).get('rating') else: voobly_rating = None except voobly.VooblyError: voobly_user = None voobly_rating = None player = { 'index': index, 'number': attributes.player_color + 1, 'color': mgz.const.PLAYER_COLORS[attributes.player_color], 'coordinates': { 'x': attributes.camera_x, 'y': attributes.camera_y }, 'action_histogram': dict(self._actions_by_player[index]), 'apm': _calculate_apm(index, self._actions_by_player, self._actions_without_player, self._time / 1000), 'name': attributes.player_name, 'civilization': mgz.const.CIVILIZATION_NAMES[attributes.civilization], 'position': self._compass_position(attributes.camera_x, attributes.camera_y), 'research': self._research.get(index, []), 'build': self._build.get(index, []), 'voobly': { 'rating_game': self._ratings.get(attributes.player_name), 'rating_current': voobly_rating, 'nation': voobly_user['nationid'] if voobly_user else None, 'uid': voobly_user['uid'] if voobly_user else None }, 'ages': {}, 'achievements': {} } if postgame: achievements = None # player index doesn't always match order of postgame achievements! (restores?) for ach in postgame.achievements: if attributes.player_name == ach.player_name: achievements = ach if not achievements: return player player['score'] = achievements.total_score player['mvp'] = achievements.mvp player['winner'] = achievements.victory player['achievements'] = { 'units_killed': achievements.military.units_killed, 'units_lost': achievements.military.units_lost, 'buildings_razed': achievements.military.buildings_razed, 'buildings_lost': achievements.military.buildings_lost, 'conversions': achievements.military.units_converted, 'food_collected': achievements.economy.food_collected, 'wood_collected': achievements.economy.wood_collected, 'gold_collected': achievements.economy.gold_collected, 'stone_collected': achievements.economy.stone_collected, 'tribute_sent': achievements.economy.tribute_sent, 'tribute_received': achievements.economy.tribute_received, 'trade_gold': achievements.economy.trade_gold, 'relic_gold': achievements.economy.relic_gold, 'explored_percent': achievements.technology.explored_percent, 'total_castles': achievements.society.total_castles, 'relics_collected': achievements.society.relics_captured, 'villager_high': achievements.society.villager_high } player['ages'] = { 'feudal': _timestamp_to_time(achievements.technology.feudal_time), 'castle': _timestamp_to_time(achievements.technology.castle_time), 'imperial': _timestamp_to_time(achievements.technology.imperial_time) } return player
python
def pca(Y, input_dim): """ Principal component analysis: maximum likelihood solution by SVD :param Y: NxD np.array of data :param input_dim: int, dimension of projection :rval X: - Nxinput_dim np.array of dimensionality reduced data :rval W: - input_dimxD mapping from X to Y """ if not np.allclose(Y.mean(axis=0), 0.0): print("Y is not zero mean, centering it locally (GPy.util.linalg.pca)") # Y -= Y.mean(axis=0) Z = linalg.svd(Y - Y.mean(axis=0), full_matrices=False) [X, W] = [Z[0][:, 0:input_dim], np.dot(np.diag(Z[1]), Z[2]).T[:, 0:input_dim]] v = X.std(axis=0) X /= v W *= v return X, W.T
java
public <T> T getSessionAttr(String key) { HttpSession session = request.getSession(false); return session != null ? (T)session.getAttribute(key) : null; }
java
public static int getYear(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); return c.get(Calendar.YEAR); }
python
def get_max_return(self, weights, returns): """ Maximizes the returns of a portfolio. """ def func(weights): """The objective function that maximizes returns.""" return np.dot(weights, returns.values) * -1 constraints = ({'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)}) solution = self.solve_minimize(func, weights, constraints) max_return = solution.fun * -1 # NOTE: `max_risk` is not used anywhere, but may be helpful in the future. # allocation = solution.x # max_risk = np.matmul( # np.matmul(allocation.transpose(), cov_matrix), allocation # ) return max_return
python
def position_before(self, instr): """ Position immediately before the given instruction. The current block is also changed to the instruction's basic block. """ self._block = instr.parent self._anchor = self._block.instructions.index(instr)
java
static String[] getUsable(final List<String> available, final String[] supported) { final List<String> filtered = new ArrayList<String>(available.size()); final List<String> supportedList = Arrays.asList(supported); for (final String s : available) { if (supportedList.contains(s)) filtered.add(s); } final String[] filteredArray = new String[filtered.size()]; filtered.toArray(filteredArray); return filteredArray; }
java
public void setThemes_event(int i, Event v) { if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_themes_event == null) jcasType.jcas.throwFeatMissing("themes_event", "ch.epfl.bbp.uima.genia.Event"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_themes_event), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Event_Type)jcasType).casFeatCode_themes_event), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public OutlierResult run(Database database, Relation<O> relation) { // Get a nearest neighbor query on the relation. KNNQuery<O> knnq = QueryUtil.getKNNQuery(relation, getDistanceFunction(), k); // Output data storage WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_DB); // Track minimum and maximum scores DoubleMinMax minmax = new DoubleMinMax(); // Iterate over all objects for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { KNNList neighbors = knnq.getKNNForDBID(iter, k); // Aggregate distances MeanVariance mv = new MeanVariance(); for(DoubleDBIDListIter neighbor = neighbors.iter(); neighbor.valid(); neighbor.advance()) { // Skip the object itself. The 0 is not very informative. if(DBIDUtil.equal(iter, neighbor)) { continue; } mv.put(neighbor.doubleValue()); } // Store score scores.putDouble(iter, mv.getSampleStddev()); } // Wrap the result in the standard containers // Actual min-max, theoretical min-max! OutlierScoreMeta meta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0, Double.POSITIVE_INFINITY); DoubleRelation rel = new MaterializedDoubleRelation(relation.getDBIDs(), "stddev-outlier", scores); return new OutlierResult(meta, rel); }
java
public void overrideCacheConfig(Properties properties) { if (properties != null) { FieldInitializer.initFromSystemProperties(this, properties); } processOffloadDirectory(); if (!this.enableServletSupport) { this.disableTemplatesSupport = true; } }
python
def _populate_user(self): """ Populates our User object with information from the LDAP directory. """ self._populate_user_from_attributes() self._populate_user_from_group_memberships() self._populate_user_from_dn_regex() self._populate_user_from_dn_regex_negation()
python
def make_initial_state(project, stack_length): """ :return: an initial state with a symbolic stack and good options for rop """ initial_state = project.factory.blank_state( add_options={options.AVOID_MULTIVALUED_READS, options.AVOID_MULTIVALUED_WRITES, options.NO_SYMBOLIC_JUMP_RESOLUTION, options.CGC_NO_SYMBOLIC_RECEIVE_LENGTH, options.NO_SYMBOLIC_SYSCALL_RESOLUTION, options.TRACK_ACTION_HISTORY}, remove_options=options.resilience | options.simplification) initial_state.options.discard(options.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY) initial_state.options.update({options.TRACK_REGISTER_ACTIONS, options.TRACK_MEMORY_ACTIONS, options.TRACK_JMP_ACTIONS, options.TRACK_CONSTRAINT_ACTIONS}) symbolic_stack = initial_state.solver.BVS("symbolic_stack", project.arch.bits * stack_length) initial_state.memory.store(initial_state.regs.sp, symbolic_stack) if initial_state.arch.bp_offset != initial_state.arch.sp_offset: initial_state.regs.bp = initial_state.regs.sp + 20 * initial_state.arch.bytes initial_state.solver._solver.timeout = 500 # only solve for half a second at most return initial_state
python
def patch(): """ Patch startService and stopService so that they check the previous state first. (used for debugging only) """ from twisted.application.service import Service old_startService = Service.startService old_stopService = Service.stopService def startService(self): assert not self.running, "%r already running" % (self,) return old_startService(self) def stopService(self): assert self.running, "%r already stopped" % (self,) return old_stopService(self) Service.startService = startService Service.stopService = stopService
java
public static CoreDictionary.Attribute guessAttribute(Term term) { CoreDictionary.Attribute attribute = CoreDictionary.get(term.word); if (attribute == null) { attribute = CustomDictionary.get(term.word); } if (attribute == null) { if (term.nature != null) { if (Nature.nx == term.nature) attribute = new CoreDictionary.Attribute(Nature.nx); else if (Nature.m == term.nature) attribute = CoreDictionary.get(CoreDictionary.M_WORD_ID); } else if (term.word.trim().length() == 0) attribute = new CoreDictionary.Attribute(Nature.x); else attribute = new CoreDictionary.Attribute(Nature.nz); } else term.nature = attribute.nature[0]; return attribute; }
python
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): """monkey patched reverse path supports easy patching 3rd party urls if 3rd party app has namespace for example ``catalogue`` and you create FeinCMS plugin with same name as this namespace reverse returns url from ApplicationContent ! """ if not urlconf: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} prefix = get_script_prefix() if not isinstance(viewname, six.string_types): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] resolved_path = [] ns_pattern = '' while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: for urlconf, config in six.iteritems( ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG): partials = viewname.split(':') app = partials[0] partials = partials[1:] # check if namespace is same as app name and try resolve if urlconf.split(".")[-1] == app: try: return app_reverse( ':'.join(partials), urlconf, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch: pass if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) if ns_pattern: resolver = get_ns_resolver(ns_pattern, resolver) return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
python
def Corr(poly, dist=None, **kws): """ Correlation matrix of a distribution or polynomial. Args: poly (Poly, Dist): Input to take correlation on. Must have ``len(poly)>=2``. dist (Dist): Defines the space the correlation is taken on. It is ignored if ``poly`` is a distribution. Returns: (numpy.ndarray): Correlation matrix with ``correlation.shape == poly.shape+poly.shape``. Examples: >>> Z = chaospy.MvNormal([3, 4], [[2, .5], [.5, 1]]) >>> print(numpy.around(chaospy.Corr(Z), 4)) [[1. 0.3536] [0.3536 1. ]] >>> x = chaospy.variable() >>> Z = chaospy.Normal() >>> print(numpy.around(chaospy.Corr([x, x**2], Z), 4)) [[1. 0.] [0. 1.]] """ if isinstance(poly, distributions.Dist): poly, dist = polynomials.variable(len(poly)), poly else: poly = polynomials.Poly(poly) cov = Cov(poly, dist, **kws) var = numpy.diag(cov) vvar = numpy.sqrt(numpy.outer(var, var)) return numpy.where(vvar > 0, cov/vvar, 0)
python
def get_signature_request_list(self, page=1, ux_version=None): ''' Get a list of SignatureRequest that you can access This includes SignatureRequests you have sent as well as received, but not ones that you have been CCed on. Args: page (int, optional): Which page number of the SignatureRequest list to return. Defaults to 1. ux_version (int): UX version, either 1 (default) or 2. Returns: A ResourceList object ''' request = self._get_request() parameters = { "page": page } if ux_version is not None: parameters['ux_version'] = ux_version return request.get(self.SIGNATURE_REQUEST_LIST_URL, parameters=parameters)
python
def yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie :param: :date_from date de référence :return datetime """ # date d'hier return self.delta(date_from=date_from, date_format=date_format, days=-1)
java
private void reallocateBuffer(int newCapacity) { byte[] newBuffer = new byte[newCapacity]; System.arraycopy(m_buffer, 0, newBuffer, 0, Math.min(m_size, newCapacity)); m_buffer = newBuffer; }
java
public void unregisterPrototype( String key, Class c ) { prototypes.remove(new PrototypeKey(key, c)); }
java
public void put(ContextPair... pairs) { if (pairs != null) { for (int i = 0; i < pairs.length; i++) { ContextPair pair = pairs[i]; this.put(pair.getKey(), pair.getValue()); } } }
python
def uint(self, length, name, value=None, align=None): """Add an unsigned integer to template. `length` is given in bytes and `value` is optional. `align` can be used to align the field to longer byte length. Examples: | uint | 2 | foo | | uint | 2 | foo | 42 | | uint | 2 | fourByteFoo | 42 | align=4 | """ self._add_field(UInt(length, name, value, align=align))
python
def create_keyvault(access_token, subscription_id, rgname, vault_name, location, template_deployment=True, tenant_id=None, object_id=None): '''Create a new key vault in the named resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. vault_name (str): Name of the new key vault. location (str): Azure data center location. E.g. westus2. template_deployment (boolean): Whether to allow deployment from template. tenant_id (str): Optionally specify a tenant ID (otherwise picks first response) from ist_tenants(). object_id (str): Optionally specify an object ID representing user or principal for the access policy. Returns: HTTP response. JSON body of key vault properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.KeyVault/vaults/', vault_name, '?api-version=', KEYVAULT_API]) # get tenant ID if not specified if tenant_id is None: ret = list_tenants(access_token) tenant_id = ret['value'][0]['tenantId'] # if object_id is None: access_policies = [{'tenantId': tenant_id, 'objectId': object_id, 'permissions': { 'keys': ['get', 'create', 'delete', 'list', 'update', 'import', 'backup', 'restore', 'recover'], 'secrets': ['get', 'list', 'set', 'delete', 'backup', 'restore', 'recover'], 'certificates': ['get', 'list', 'delete', 'create', 'import', 'update', 'managecontacts', 'getissuers', 'listissuers', 'setissuers', 'deleteissuers', 'manageissuers', 'recover'], 'storage': ['get', 'list', 'delete', 'set', 'update', 'regeneratekey', 'setsas', 'listsas', 'getsas', 'deletesas'] }}] vault_properties = {'tenantId': tenant_id, 'sku': {'family': 'A', 'name': 'standard'}, 'enabledForTemplateDeployment': template_deployment, 'accessPolicies': access_policies} vault_body = {'location': location, 'properties': vault_properties} body = json.dumps(vault_body) return do_put(endpoint, body, access_token)
python
def readline(self, size=None): """Reads one line from the stream.""" if self._pos >= self.limit: return self.on_exhausted() if size is None: size = self.limit - self._pos else: size = min(size, self.limit - self._pos) try: line = self._readline(size) except (ValueError, IOError): return self.on_disconnect() if size and not line: return self.on_disconnect() self._pos += len(line) return line
java
public void start() throws Exception { _class=_httpHandler.getHttpContext().loadClass(_className); if(log.isDebugEnabled())log.debug("Started holder of "+_class); }
java
private void writeChar(final char chr) throws IOException { switch (chr) { case '\t': this.Tab(); break; case '\n': { this.out.write(this.lineSeparator); this.lineNumber++; this.prevMode = this.mode; this.mode = MODE_START_LINE; this.linePosition = 0; for (final Extra e : extras) { e.onNewLine(this, this.lineNumber); } } break; case '\r': break; default: { if (!Character.isISOControl(chr)) { this.out.write(chr); this.linePosition++; if (this.mode == MODE_START_LINE) { this.mode = this.prevMode; } } } break; } }
java
private int doPublish(boolean isControl, String deviceId, String topic, KuraPayload kuraPayload, int qos, boolean retain, int priority) throws KuraException { String target = target(applicationId + ":" + topic); int kuraMessageId = Math.abs(new Random().nextInt()); Map<String, Object> headers = new HashMap<>(); headers.put(CAMEL_KURA_CLOUD_CONTROL, isControl); headers.put(CAMEL_KURA_CLOUD_MESSAGEID, kuraMessageId); headers.put(CAMEL_KURA_CLOUD_DEVICEID, deviceId); headers.put(CAMEL_KURA_CLOUD_QOS, qos); headers.put(CAMEL_KURA_CLOUD_RETAIN, retain); headers.put(CAMEL_KURA_CLOUD_PRIORITY, priority); producerTemplate.sendBodyAndHeaders(target, kuraPayload, headers); return kuraMessageId; }
python
def _print_unique_links_with_status_codes(page_url, soup): """ Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: ["link" -> "status_code"] (per line) Page links include those obtained from: "a"->"href", "img"->"src", "link"->"href", and "script"->"src". """ links = _get_unique_links(page_url, soup) for link in links: status_code = _get_link_status_code(link) print(link, " -> ", status_code)
python
def to_jsondict(self, encode_string=base64.b64encode): """ This method returns a JSON style dict to describe this object. The returned dict is compatible with json.dumps() and json.loads(). Suppose ClassName object inherits StringifyMixin. For an object like the following:: ClassName(Param1=100, Param2=200) this method would produce:: { "ClassName": {"Param1": 100, "Param2": 200} } This method takes the following arguments. .. tabularcolumns:: |l|L| ============= ===================================================== Argument Description ============= ===================================================== encode_string (Optional) specify how to encode attributes which has python 'str' type. The default is base64. This argument is used only for attributes which don't have explicit type annotations in _TYPE class attribute. ============= ===================================================== """ dict_ = {} encode = lambda key, val: self._encode_value(key, val, encode_string) for k, v in obj_attrs(self): dict_[k] = encode(k, v) return {self.__class__.__name__: dict_}
java
public static String getMapGetterName(Field field) { if (field.isMap()) { return GETTER_PREFIX + Formatter.toPascalCase(field.getName()) + MAP_SUFFIX; } throw new IllegalArgumentException(field.toString()); }
java
private synchronized void refreshTree() { if (!isTreeRefreshRequired()) { // The groupsTree was already re-built while // we were waiting to enter this method. return; } log.info("Refreshing groups tree for SmartLdap"); // We must join the builder thread if // we don't have an existing groupsTree. final boolean doJoin = groupsTree == null; // In most cases, re-build the tree in a separate thread; the current // request can proceed with the newly-expired groupsTree. Thread refresh = new Thread("SmartLdap Refresh Worker") { @Override public void run() { // Replace the old with the new... try { groupsTree = buildGroupsTree(); } catch (Throwable t) { log.error("SmartLdapGroupStore failed to build the groups tree", t); } } }; refresh.setDaemon(true); refresh.start(); if (doJoin) { try { log.info("Joining the SmartLdap Refresh Worker Thread"); refresh.join(); } catch (InterruptedException ie) { throw new RuntimeException(ie); } } // Even if the refresh thread failed, don't try // again for another groupsTreeRefreshIntervalSeconds. lastTreeRefreshTime = System.currentTimeMillis(); }
python
def content(self, content): """ Overwrite Dockerfile with specified content :param content: string to be written to Dockerfile """ if self.cache_content: self.cached_content = b2u(content) try: with self._open_dockerfile('wb') as dockerfile: dockerfile.write(u2b(content)) except (IOError, OSError) as ex: logger.error("Couldn't write content to dockerfile: %r", ex) raise
java
private void reportAvailableService(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); writer.println("<h2>" + request.getServletPath() + "</h2>"); writer.println("<h3>Hello! This is a CXF Web Service!</h3>"); }
java
public Matrix3x2d scaleAroundLocal(double sx, double sy, double sz, double ox, double oy, double oz) { return scaleAroundLocal(sx, sy, ox, oy, this); }
java
public void setVisible(boolean visible) { if (isVisible() == visible) return; if (!fireEvent(new VisibleStateChange<>(this, visible))) return; this.visible = visible; if (!visible) { this.setHovered(false); this.setFocused(false); } return; }
java
public static int hash(MemorySegment[] segments, int offset, int numBytes) { if (inFirstSegment(segments, offset, numBytes)) { return MurmurHashUtil.hashBytes(segments[0], offset, numBytes); } else { return hashMultiSeg(segments, offset, numBytes); } }
python
def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func
java
public List<CmsJspNavElement> getNavigationTreeForFolder(String folder, int startlevel, int endlevel) { folder = CmsResource.getFolderPath(folder); // Make sure start and end level make sense if (endlevel < startlevel) { return Collections.<CmsJspNavElement> emptyList(); } int currentlevel = CmsResource.getPathLevel(folder); if (currentlevel < endlevel) { endlevel = currentlevel; } if (startlevel == endlevel) { return getNavigationForFolder(CmsResource.getPathPart(folder, startlevel), startlevel); } List<CmsJspNavElement> result = new ArrayList<CmsJspNavElement>(); float parentcount = 0; for (int i = startlevel; i <= endlevel; i++) { String currentfolder = CmsResource.getPathPart(folder, i); List<CmsJspNavElement> entries = getNavigationForFolder(currentfolder); // Check for parent folder if (parentcount > 0) { for (CmsJspNavElement e : entries) { e.setNavPosition(e.getNavPosition() + parentcount); } } // Add new entries to result result.addAll(entries); Collections.sort(result); // Finally spread the values of the navigation items so that there is enough room for further items float pos = 0; int count = 0; String nextfolder = CmsResource.getPathPart(folder, i + 1); parentcount = 0; for (CmsJspNavElement e : result) { pos = 10000 * (++count); e.setNavPosition(pos); if (e.getResourceName().startsWith(nextfolder)) { parentcount = pos; } } if (parentcount == 0) { parentcount = pos; } } return result; }
java
public Short getHeaderKey(String value) { if (StringUtils.isNotEmpty(value) && headerCache != null) { return headerCache.getKey(value); } return null; }
python
def _set_receive(self, v, load=False): """ Setter method for receive, mapped from YANG variable /routing_system/ipv6/receive (container) If this variable is read-only (config: false) in the source YANG file, then _set_receive is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_receive() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=receive.receive, is_container='container', presence=False, yang_name="receive", rest_name="receive", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Receive ACL', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ipv6-access-list', defining_module='brocade-ipv6-access-list', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """receive must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=receive.receive, is_container='container', presence=False, yang_name="receive", rest_name="receive", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Receive ACL', u'cli-incomplete-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ipv6-access-list', defining_module='brocade-ipv6-access-list', yang_type='container', is_config=True)""", }) self.__receive = t if hasattr(self, '_set'): self._set()
java
public final LangPreferences revealLangPreferences( final IRequestData pRequestData, final List<Languages> pLangs, final List<DecimalSeparator> pDecSeps, final List<DecimalGroupSeparator> pDecGrSeps, final List<LangPreferences> pLangPrefs, final boolean pIsFirstReq) throws Exception { boolean isDbgSh = this.logger.getDbgSh(this.getClass()) && this.logger.getDbgFl() < 5001 && this.logger.getDbgCl() > 5003; LangPreferences lpf = null; boolean needSetCookie = false; //check request changing preferences: String lang = pRequestData.getParameter("lang"); String decSep = pRequestData.getParameter("decSep"); String decGrSep = pRequestData.getParameter("decGrSep"); String digInGr = pRequestData.getParameter("digInGr"); if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Request's lang/decSep/decGrSep/digInGr: " + lang + "/" + decSep + "/" + decGrSep + "/" + digInGr); } if (lang == null || lang.length() == 0 || decSep == null || decSep.length() == 0 || decGrSep == null || decGrSep.length() == 0 || digInGr == null || digInGr.length() == 0) { lang = null; decSep = null; decGrSep = null; digInGr = null; } else { needSetCookie = true; } if (decGrSep == null && decSep == null && lang == null) { lang = pRequestData.getCookieValue("lang"); decSep = pRequestData.getCookieValue("decSep"); decGrSep = pRequestData.getCookieValue("decGrSep"); digInGr = pRequestData.getCookieValue("digInGr"); if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Client's cookie lang/decSep/decGrSep/digInGr: " + lang + "/" + decSep + "/" + decGrSep + "/" + digInGr); } } if (decGrSep != null && decSep != null && lang != null && digInGr != null) { if (decGrSep.equals(decSep)) { if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Separators are same!! decSep/decGrSep: " + decSep); } } else { //try to match from cookies or changed by user: lpf = new LangPreferences(); lpf.setDigitsInGroup(Integer.parseInt(digInGr)); for (Languages ln : pLangs) { if (ln.getItsId().equals(lang)) { lpf.setLang(ln); break; } } if (lpf.getLang() == null) { lpf = null; } else { for (DecimalSeparator ds : pDecSeps) { if (ds.getItsId().equals(decSep)) { lpf.setDecimalSep(ds); break; } } if (lpf.getDecimalSep() == null) { lpf = null; } else { for (DecimalGroupSeparator dgs : pDecGrSeps) { if (dgs.getItsId().equals(decGrSep)) { lpf.setDecimalGroupSep(dgs); break; } } if (lpf.getDecimalGroupSep() == null) { lpf = null; } } } } } if (lpf == null) { // try match client's locale, if not - default or the first: String ccountry = null; String clang = null; if (pRequestData.getLocale() != null) { ccountry = pRequestData.getLocale().getCountry(); clang = pRequestData.getLocale().getLanguage(); if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Client prefers lang/country: " + clang + "/" + ccountry); } } LangPreferences lpfMf = null; LangPreferences lpfMl = null; LangPreferences lpfDef = null; for (LangPreferences lpft : pLangPrefs) { if (lpft.getCountry().getItsId().equals(ccountry) && lpft.getLang().getItsId().equals(clang)) { lpfMf = lpft; break; } if (lpft.getLang().getItsId().equals(clang)) { lpfMl = lpft; } if (lpft.getIsDefault()) { lpfDef = lpft; } else if (lpfDef == null) { lpfDef = lpft; } } if (lpfMf != null) { lpf = lpfMf; if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Full match lang/decSep/decGrSep/digInGr: " + lpf.getLang() .getItsId() + "/" + lpf.getDecimalSep().getItsId() + "/" + lpf.getDecimalGroupSep().getItsId() + "/" + lpf.getDigitsInGroup()); } } else if (lpfMl != null) { lpf = lpfMl; if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Lang match lang/decSep/decGrSep/digInGr: " + lpf.getLang() .getItsId() + "/" + lpf.getDecimalSep().getItsId() + "/" + lpf.getDecimalGroupSep().getItsId() + "/" + lpf.getDigitsInGroup()); } } else { lpf = lpfDef; if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "No match, default lang/decSep/decGrSep/digInGr: " + lpf.getLang().getItsId() + "/" + lpf.getDecimalSep().getItsId() + "/" + lpf.getDecimalGroupSep().getItsId() + "/" + lpf.getDigitsInGroup()); } } needSetCookie = true; } if (needSetCookie) { pRequestData.setCookieValue("digInGr", lpf.getDigitsInGroup().toString()); pRequestData.setCookieValue("lang", lpf.getLang().getItsId()); pRequestData.setCookieValue("decSep", lpf.getDecimalSep().getItsId()); pRequestData.setCookieValue("decGrSep", lpf.getDecimalGroupSep().getItsId()); if (pIsFirstReq || isDbgSh) { this.logger.debug(null, HndlI18nRequest.class, "Cookie is set lang/decSep/decGrSep: " + lpf.getLang() .getItsId() + "/" + lpf.getDecimalSep().getItsId() + "/" + lpf.getDecimalGroupSep().getItsId()); } } return lpf; }
java
public EClass getIfcFillAreaStyleHatching() { if (ifcFillAreaStyleHatchingEClass == null) { ifcFillAreaStyleHatchingEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(235); } return ifcFillAreaStyleHatchingEClass; }
java
public <T extends View> boolean searchFor(Set<T> uniqueViews, Class<T> viewClass, final int index) { ArrayList<T> allViews = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(viewClass, true)); int uniqueViewsFound = (getNumberOfUniqueViews(uniqueViews, allViews)); if(uniqueViewsFound > 0 && index < uniqueViewsFound) { return true; } if(uniqueViewsFound > 0 && index == 0) { return true; } return false; }
java
@Override public void toFile(File file, Engine engine) throws IOException { if (engine.getInputVariables().isEmpty()) { throw new RuntimeException("[exporter error] engine has no input variables to export the surface"); } if (engine.getOutputVariables().isEmpty()) { throw new RuntimeException("[exporter error] engine has no output variables to export the surface"); } InputVariable a = engine.getInputVariables().get(0); InputVariable b = engine.getInputVariables().get(1 % engine.numberOfInputVariables()); toFile(file, engine, a, b, 1024, FldExporter.ScopeOfValues.AllVariables, engine.getOutputVariables()); }
python
def random_point_triangle(triangle, use_int_coords=True): """ Selects a random point in interior of a triangle """ xs, ys = triangle.exterior.coords.xy A, B, C = zip(xs[:-1], ys[:-1]) r1, r2 = np.random.rand(), np.random.rand() rx, ry = (1 - sqrt(r1)) * np.asarray(A) + sqrt(r1) * (1 - r2) * np.asarray(B) + sqrt(r1) * r2 * np.asarray(C) if use_int_coords: rx, ry = round(rx), round(ry) return Point(int(rx), int(ry)) return Point(rx, ry)
java
public ConcurrentMap<String, L> getLoggersInContext(final LoggerContext context) { ConcurrentMap<String, L> loggers; lock.readLock ().lock (); try { loggers = registry.get (context); } finally { lock.readLock ().unlock (); } if (loggers != null) { return loggers; } else { lock.writeLock ().lock (); try { loggers = registry.get (context); if (loggers == null) { loggers = new ConcurrentHashMap<> (); registry.put (context, loggers); } return loggers; } finally { lock.writeLock ().unlock (); } } }
python
def list_cands(candsfile, threshold=0.): """ Prints candidate info in time order above some threshold """ loc, prop, d0 = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True) if 'snr2' in d0['features']: snrcol = d0['features'].index('snr2') elif 'snr1' in d0['features']: snrcol = d0['features'].index('snr1') dmindcol = d0['featureind'].index('dmind') if len(loc): snrs = prop[:, snrcol] times = pc.int2mjd(d0, loc) times = times - times[0] logger.info('Getting candidates...') logger.info('candnum: loc, SNR, DM (pc/cm3), time (s; rel)') for i in range(len(loc)): logger.info("%d: %s, %.1f, %.1f, %.1f" % (i, str(loc[i]), prop[i, snrcol], np.array(d0['dmarr'])[loc[i,dmindcol]], times[i]))
python
def emit(self, action, event): """ Send a notification to clients scoped by projects :param action: Action name :param event: Event to send """ # If use in tests for documentation we save a sample if os.environ.get("PYTEST_BUILD_DOCUMENTATION") == "1": os.makedirs("docs/api/notifications", exist_ok=True) try: import json data = json.dumps(event, indent=4, sort_keys=True) if "MagicMock" not in data: with open(os.path.join("docs/api/notifications", action + ".json"), 'w+') as f: f.write(data) except TypeError: # If we receive a mock as an event it will raise TypeError when using json dump pass if "project_id" in event: self._send_event_to_project(event["project_id"], action, event) else: self._send_event_to_all(action, event)
python
def connect_to_rackspace(region, access_key_id, secret_access_key): """ returns a connection object to Rackspace """ pyrax.set_setting('identity_type', 'rackspace') pyrax.set_default_region(region) pyrax.set_credentials(access_key_id, secret_access_key) nova = pyrax.connect_to_cloudservers(region=region) return nova
python
def _activate_inbound(self): """switch on newly negotiated encryption parameters for inbound traffic""" block_size = self._cipher_info[self.remote_cipher]['block-size'] if self.server_mode: IV_in = self._compute_key('A', block_size) key_in = self._compute_key('C', self._cipher_info[self.remote_cipher]['key-size']) else: IV_in = self._compute_key('B', block_size) key_in = self._compute_key('D', self._cipher_info[self.remote_cipher]['key-size']) engine = self._get_cipher(self.remote_cipher, key_in, IV_in) mac_size = self._mac_info[self.remote_mac]['size'] mac_engine = self._mac_info[self.remote_mac]['class'] # initial mac keys are done in the hash's natural size (not the potentially truncated # transmission size) if self.server_mode: mac_key = self._compute_key('E', mac_engine().digest_size) else: mac_key = self._compute_key('F', mac_engine().digest_size) self.packetizer.set_inbound_cipher(engine, block_size, mac_engine, mac_size, mac_key) compress_in = self._compression_info[self.remote_compression][1] if (compress_in is not None) and ((self.remote_compression != '[email protected]') or self.authenticated): self._log(DEBUG, 'Switching on inbound compression ...') self.packetizer.set_inbound_compressor(compress_in())
python
def unzip(input_layer, split_dim=0, num_splits=2): """Unzips this Tensor along the split_dim into num_splits Equal chunks. Examples: * `[1, 2, 3, 4] -> [1, 3], [2, 4]` * `[[1, 1], [2, 2], [3, 3], [4, 4]] -> [[1, 1], [3, 3]], [[2, 2], [4, 4]]` Args: input_layer: The chainable object, supplied. split_dim: The dimension to split along. Defaults to batch. num_splits: The number of splits. Returns: A list of PrettyTensors. Raises: ValueError: If split_dim is out of range or isn't divided evenly by num_splits. """ shape = input_layer.shape _check_split_dims(num_splits, split_dim, shape) splits = functions.unzip(input_layer, split_dim, shape[split_dim], num_splits) return input_layer.with_sequence(splits)
java
public static CommercePriceList fetchByLtD_S_First(Date displayDate, int status, OrderByComparator<CommercePriceList> orderByComparator) { return getPersistence() .fetchByLtD_S_First(displayDate, status, orderByComparator); }
java
@Deprecated @SuppressWarnings("unchecked") public void addInput(List<Operator<IN>> inputs) { this.input = Operator.createUnionCascade(this.input, inputs.toArray(new Operator[inputs.size()])); }
python
def get_default_config(self): """ Returns the default collector settings """ config = super(PassengerCollector, self).get_default_config() config.update({ "path": "passenger_stats", "bin": "/usr/lib/ruby-flo/bin/passenger-memory-stats", "use_sudo": False, "sudo_cmd": "/usr/bin/sudo", "passenger_status_bin": "/usr/bin/passenger-status", "passenger_memory_stats_bin": "/usr/bin/passenger-memory-stats", }) return config
python
def handle_lock_expired( payment_state: InitiatorPaymentState, state_change: ReceiveLockExpired, channelidentifiers_to_channels: ChannelMap, block_number: BlockNumber, ) -> TransitionResult[InitiatorPaymentState]: """Initiator also needs to handle LockExpired messages when refund transfers are involved. A -> B -> C - A sends locked transfer to B - B attempted to forward to C but has not enough capacity - B sends a refund transfer with the same secrethash back to A - When the lock expires B will also send a LockExpired message to A - A needs to be able to properly process it Related issue: https://github.com/raiden-network/raiden/issues/3183 """ initiator_state = payment_state.initiator_transfers.get(state_change.secrethash) if not initiator_state: return TransitionResult(payment_state, list()) channel_identifier = initiator_state.channel_identifier channel_state = channelidentifiers_to_channels.get(channel_identifier) if not channel_state: return TransitionResult(payment_state, list()) secrethash = initiator_state.transfer.lock.secrethash result = channel.handle_receive_lock_expired( channel_state=channel_state, state_change=state_change, block_number=block_number, ) assert result.new_state, 'handle_receive_lock_expired should not delete the task' if not channel.get_lock(result.new_state.partner_state, secrethash): transfer = initiator_state.transfer unlock_failed = EventUnlockClaimFailed( identifier=transfer.payment_identifier, secrethash=transfer.lock.secrethash, reason='Lock expired', ) result.events.append(unlock_failed) return TransitionResult(payment_state, result.events)
python
def junos_install_os(path=None, **kwargs): ''' .. versionadded:: 2019.2.0 Installs the given image on the device. path The image file source. This argument supports the following URIs: - Absolute path on the Minion. - ``salt://`` to fetch from the Salt fileserver. - ``http://`` and ``https://`` - ``ftp://`` - ``swift:/`` - ``s3://`` dev_timeout: ``30`` The NETCONF RPC timeout (in seconds) reboot: ``False`` Whether to reboot the device after the installation is complete. no_copy: ``False`` If ``True`` the software package will not be copied to the remote device. CLI Example: .. code-block:: bash salt '*' napalm.junos_install_os salt://images/junos_16_1.tgz reboot=True ''' prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable if not prep['result']: return prep return __salt__['junos.install_os'](path=path, **kwargs)
java
private void handle(SelectionKey key) { // 有客户端接入此服务端 if (key.isAcceptable()) { // 获取通道 转化为要处理的类型 final ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel socketChannel; try { // 获取连接到此服务器的客户端通道 socketChannel = server.accept(); } catch (IOException e) { throw new IORuntimeException(e); } // SocketChannel通道的可读事件注册到Selector中 registerChannel(selector, socketChannel, Operation.READ); } // 读事件就绪 if (key.isReadable()) { final SocketChannel socketChannel = (SocketChannel) key.channel(); read(socketChannel); // SocketChannel通道的可写事件注册到Selector中 registerChannel(selector, socketChannel, Operation.WRITE); } // 写事件就绪 if (key.isWritable()) { final SocketChannel socketChannel = (SocketChannel) key.channel(); write(socketChannel); // SocketChannel通道的可读事件注册到Selector中 registerChannel(selector, socketChannel, Operation.READ); } }
python
def hello(environ, start_response): '''The WSGI_ application handler which returns an iterable over the "Hello World!" message.''' if environ['REQUEST_METHOD'] == 'GET': data = b'Hello World!\n' status = '200 OK' response_headers = [ ('Content-type', 'text/plain'), ('Content-Length', str(len(data))) ] start_response(status, response_headers) return iter([data]) else: raise MethodNotAllowed
python
def get_kmgraph_meta(mapper_summary): """ Extract info from mapper summary to be displayed below the graph plot """ d = mapper_summary["custom_meta"] meta = ( "<b>N_cubes:</b> " + str(d["n_cubes"]) + " <b>Perc_overlap:</b> " + str(d["perc_overlap"]) ) meta += ( "<br><b>Nodes:</b> " + str(mapper_summary["n_nodes"]) + " <b>Edges:</b> " + str(mapper_summary["n_edges"]) + " <b>Total samples:</b> " + str(mapper_summary["n_total"]) + " <b>Unique_samples:</b> " + str(mapper_summary["n_unique"]) ) return meta
java
@Override public Future fire(Object data) throws IOException { reset(); socket.internalSocket().write(socket.request(), data); return this; }
java
public SimpleOrderedMap<Object> createListOutput(boolean shardRequests, int maxNumber) { garbageCollect(); SimpleOrderedMap<Object> output = new SimpleOrderedMap<>(); output.add(NAME_ENABLED, enabled()); output.add(NAME_ENABLED, true); int numberTotal = data.size(); ListData listData = new ListData(); synchronized (data) { ListIterator<MtasSolrStatus> iter = data.listIterator(data.size()); MtasSolrStatus item; int number = 0; while (iter.hasPrevious() && number < maxNumber) { item = iter.previous(); if (item.shardRequest()) { listData.addShardRequest(); if (shardRequests) { listData.outputList.add(item.createItemOutput()); number++; } } else { listData.addNormal(); listData.outputList.add(item.createItemOutput()); number++; } } } output.add(NAME_SIZE_TOTAL, numberTotal); output.add(NAME_SIZE_NORMAL, listData.numberNormal); output.add(NAME_SIZE_SHARDREQUESTS, listData.numberShardRequests); output.add(NAME_LIST, listData.outputList); return output; }
java
public void decrementTargetIncomingTransitionCounts() { for(Entry<Character, MDAGNode> transitionKeyValuePair: outgoingTransitionTreeMap.entrySet()) transitionKeyValuePair.getValue().incomingTransitionCount--; }
java
static boolean isIllegalHoppingSpecified(List<NodeInfo> order) { for (int i = 0; i < order.size(); i++) { NodeInfo ni = (NodeInfo) order.get(i); // look for move restricted nodes if (!ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) continue; // now check nodes in lower position to see if they "hopped" here // or if they have similar precedence and came from another parent. for (int j = 0; j < i; j++) { NodeInfo niSib = (NodeInfo) order.get(j); // skip lower precedence nodes from this parent. These will get // bumped during the lower precedence check if (niSib.getPrecedence() == Precedence.getUserPrecedence()) continue; if (niSib.getPrecedence().isEqualTo(ni.getPrecedence()) && (niSib.getIndexInCVP() == -1 || // from another parent ni.getIndexInCVP() < niSib.getIndexInCVP())) // niSib hopping left return true; } // now check upper positioned nodes to see if they "hopped" for (int j = i + 1; j < order.size(); j++) { NodeInfo niSib = (NodeInfo) order.get(j); // ignore nodes from other parents and user precedence nodes if (niSib.getIndexInCVP() == -1 || niSib.getPrecedence() == Precedence.getUserPrecedence()) continue; if (ni.getIndexInCVP() > niSib.getIndexInCVP() && // niSib hopped right niSib.getPrecedence().isEqualTo(ni.getPrecedence())) return true; } } return false; }
java
private CreateVpcResponseType createVpc(final String cidrBlock, final String instanceTenancy) { CreateVpcResponseType ret = new CreateVpcResponseType(); ret.setRequestId(UUID.randomUUID().toString()); MockVpc mockVpc = mockVpcController.createVpc(cidrBlock, instanceTenancy); VpcType vpcType = new VpcType(); vpcType.setVpcId(mockVpc.getVpcId()); vpcType.setState(mockVpc.getState()); vpcType.setCidrBlock(mockVpc.getCidrBlock()); vpcType.setIsDefault(mockVpc.getIsDefault()); ret.setVpc(vpcType); return ret; }
java
public Footer getFooter() { List<Footer> list = this.getDescendants(Footer.class); if (list.size() > 0) { return list.get(0); } else { return null; } }
python
def load(path, variable='Datamat'): """ Load datamat at path. Parameters: path : string Absolute path of the file to load from. """ f = h5py.File(path,'r') try: dm = fromhdf5(f[variable]) finally: f.close() return dm
java
@Override public GetKeyRotationStatusResult getKeyRotationStatus(GetKeyRotationStatusRequest request) { request = beforeClientExecution(request); return executeGetKeyRotationStatus(request); }
python
async def start(self): """Enter the transaction or savepoint block.""" self.__check_state_base('start') if self._state is TransactionState.STARTED: raise apg_errors.InterfaceError( 'cannot start; the transaction is already started') con = self._connection if con._top_xact is None: if con._protocol.is_in_transaction(): raise apg_errors.InterfaceError( 'cannot use Connection.transaction() in ' 'a manually started transaction') con._top_xact = self else: # Nested transaction block top_xact = con._top_xact if self._isolation != top_xact._isolation: raise apg_errors.InterfaceError( 'nested transaction has a different isolation level: ' 'current {!r} != outer {!r}'.format( self._isolation, top_xact._isolation)) self._nested = True if self._nested: self._id = con._get_unique_id('savepoint') query = 'SAVEPOINT {};'.format(self._id) else: if self._isolation == 'read_committed': query = 'BEGIN;' elif self._isolation == 'repeatable_read': query = 'BEGIN ISOLATION LEVEL REPEATABLE READ;' else: query = 'BEGIN ISOLATION LEVEL SERIALIZABLE' if self._readonly: query += ' READ ONLY' if self._deferrable: query += ' DEFERRABLE' query += ';' try: await self._connection.execute(query) except BaseException: self._state = TransactionState.FAILED raise else: self._state = TransactionState.STARTED
python
def update_telemetry_configurations(self, configuration, timeout=-1): """ Updates the telemetry configuration of a logical interconnect. Changes to the telemetry configuration are asynchronously applied to all managed interconnects. Args: configuration: The telemetry configuration for the logical interconnect. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: dict: The Logical Interconnect. """ telemetry_conf_uri = self._get_telemetry_configuration_uri() default_values = self._get_default_values(self.SETTINGS_TELEMETRY_CONFIG_DEFAULT_VALUES) configuration = self._helper.update_resource_fields(configuration, default_values) return self._helper.update(configuration, uri=telemetry_conf_uri, timeout=timeout)
java
public String replacePlaceholders(String value, final Properties properties) { Assert.notNull(properties, "'properties' must not be null"); return replacePlaceholders(value, new PlaceholderResolver() { @Override public String resolvePlaceholder(String placeholderName) { return properties.getProperty(placeholderName); } }); }
java
@SuppressWarnings("Unchecked") public static Object checkImmutable(String className, String fieldName, Object field) { if (field == null || field instanceof Enum || inImmutableList(field.getClass().getName())) return field; if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field); if (field.getClass().getAnnotation(MY_CLASS) != null) return field; final String typeName = field.getClass().getName(); throw new RuntimeException(createErrorMessage(className, fieldName, typeName, "constructing")); }
python
def _start_reader_thread(self, stream, chunks): """Starts a thread for reading output from FFMPEG. The thread reads consecutive chunks from the stream and saves them in the given list. Args: stream: output stream of the FFMPEG process. chunks: list to save output chunks to. Returns: Thread """ import io # pylint: disable=g-import-not-at-top import threading # pylint: disable=g-import-not-at-top def target(): while True: chunk = stream.read(io.DEFAULT_BUFFER_SIZE) if not chunk: break chunks.append(chunk) thread = threading.Thread(target=target) thread.start() return thread
python
def create( self, name, description="", private=False, runs_executable_tasks=True, runs_docker_container_tasks=True, runs_singularity_container_tasks=True, active=True, whitelists=None, ): """Create a task queue. Args: name (str): The name of the task queue. description (str, optional): A description of the task queue. private (bool, optional): A boolean specifying whether the queue is exclusive to its creator. Defaults to False. runs_executable_tasks (bool, optional): A Boolean specifying whether the queue runs executable tasks. Defaults to True. runs_docker_container_tasks (bool, optional): A Boolean specifying whether the queue runs container tasks that run in Docker containers. Defaults to True. runs_singularity_container_tasks (bool, optional): A Boolean specifying whether the queue runs container tasks that run in Singularity containers. Defaults to True. active (bool, optional): A boolean specifying whether the queue is active. Default to True. whitelists (list, optional): A list of task whitelist IDs. Defaults to None (which gets translated to []). Returns: :class:`saltant.models.task_queue.TaskQueue`: A task queue model instance representing the task queue just created. """ # Translate whitelists None to [] if necessary if whitelists is None: whitelists = [] # Create the object request_url = self._client.base_api_url + self.list_url data_to_post = { "name": name, "description": description, "private": private, "runs_executable_tasks": runs_executable_tasks, "runs_docker_container_tasks": runs_docker_container_tasks, "runs_singularity_container_tasks": runs_singularity_container_tasks, "active": active, "whitelists": whitelists, } response = self._client.session.post(request_url, data=data_to_post) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_201_CREATED, ) # Return a model instance representing the task instance return self.response_data_to_model_instance(response.json())
java
public void setPos(Object p) { Object[] a = (Object[]) p; buf = (char[]) a[0]; int[] v = (int[]) a[1]; pos.setIndex(v[0]); bufPos = v[1]; }
java
public void setTopicSpaceUuid(SIBUuid12 topicSpace) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setTopicSpaceUuid", topicSpace); this.topicSpaceUuid = topicSpace; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setTopicSpaceUuid"); }
python
def maybe_get_ax(*args, **kwargs): """ It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. @param args: @type args: @param kwargs: @type kwargs: @return: @rtype: """ if 'ax' in kwargs: ax = kwargs.pop('ax') elif len(args) == 0: fig = plt.gcf() ax = plt.gca() elif isinstance(args[0], mpl.axes.Axes): ax = args[0] args = args[1:] else: ax = plt.gca() return ax, args, dict(kwargs)
python
def press(button=LEFT): """ Sends a down event for the specified button, using the provided constants """ location = get_position() button_code, button_down, _, _ = _button_mapping[button] e = Quartz.CGEventCreateMouseEvent( None, button_down, location, button_code) # Check if this is a double-click (same location within the last 300ms) if _last_click["time"] is not None and datetime.datetime.now() - _last_click["time"] < datetime.timedelta(seconds=0.3) and _last_click["button"] == button and _last_click["position"] == location: # Repeated Click _last_click["click_count"] = min(3, _last_click["click_count"]+1) else: # Not a double-click - Reset last click _last_click["click_count"] = 1 Quartz.CGEventSetIntegerValueField( e, Quartz.kCGMouseEventClickState, _last_click["click_count"]) Quartz.CGEventPost(Quartz.kCGHIDEventTap, e) _button_state[button] = True _last_click["time"] = datetime.datetime.now() _last_click["button"] = button _last_click["position"] = location
python
def get_backend_choices(currency=None): """ Get active backends modules. Backend list can be filtered by supporting given currency. """ choices = [] backends_names = getattr(settings, 'GETPAID_BACKENDS', []) for backend_name in backends_names: backend = import_module(backend_name) if currency: if currency in backend.PaymentProcessor.BACKEND_ACCEPTED_CURRENCY: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) else: choices.append( (backend_name, backend.PaymentProcessor.BACKEND_NAME) ) return choices
java
public OvhFirewallNetworkRule ip_firewall_ipOnFirewall_rule_sequence_GET(String ip, String ipOnFirewall, Long sequence) throws IOException { String qPath = "/ip/{ip}/firewall/{ipOnFirewall}/rule/{sequence}"; StringBuilder sb = path(qPath, ip, ipOnFirewall, sequence); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhFirewallNetworkRule.class); }
python
def get_recipe_env(self, arch, with_flags_in_cc=True): """ Add libgeos headers to path """ env = super(ShapelyRecipe, self).get_recipe_env(arch, with_flags_in_cc) libgeos_dir = Recipe.get_recipe('libgeos', self.ctx).get_build_dir(arch.arch) env['CFLAGS'] += " -I{}/dist/include".format(libgeos_dir) return env
java
public boolean publish(String topicName, DefaultMessage message,boolean asynSend){ if(routeEnv != null)topicName = routeEnv + "." + topicName; return producer.publish(topicName, message,asynSend); }
python
def isChar(ev): """ Check if an event may be a typed character """ text = ev.text() if len(text) != 1: return False if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier): return False asciiCode = ord(text) if asciiCode <= 31 or asciiCode == 0x7f: # control characters return False if text == ' ' and ev.modifiers() == Qt.ShiftModifier: return False # Shift+Space is a shortcut, not a text return True