language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def values_for(self, k): """ Each value with name `k`. """ return [getattr(frame, k) for frame in self.stack if hasattr(frame, k)]
java
public BeanComparator<T> reverse() { BeanComparator<T> bc = new BeanComparator<T>(this); bc.mOrderByName = mOrderByName; bc.mUsingComparator = mUsingComparator; bc.mFlags = mFlags ^ 0x01; return bc; }
java
public static DatatypeFactory getDTF() { DatatypeFactory dtf = threadDTF.get(); if (dtf == null) { try { dtf = DatatypeFactory.newInstance(); } catch (Exception e) { throw wrap(e); } threadDTF.set(dtf); } return dtf; }
java
public AddressDataType getAddressDataType(ProposalPersonContract person) { AddressDataType addressType = AddressDataType.Factory.newInstance(); if (person != null) { String street1 = person.getAddressLine1(); addressType.setStreet1(street1); String street2 = person.getAddressLine2(); if (street2 != null && !street2.equals("")) { addressType.setStreet2(street2); } String city = person.getCity(); addressType.setCity(city); String state = person.getState(); if (state != null && !state.equals("")) { addressType.setState(state); } String zipcode = person.getPostalCode(); if (zipcode != null && !zipcode.equals("")) { addressType.setZipCode(zipcode); } String county = person.getCounty(); if (county != null && !county.equals("")) { addressType.setCounty(county); } String country = person.getCountryCode(); CountryCodeType.Enum countryCode = null; if (country != null && !country.equals("")) { countryCode = CountryCodeType.Enum.forString(country); } addressType.setCountry(countryCode); } return addressType; }
python
def to_tnw(orbit): """In the TNW Local Orbital Reference Frame, x is oriented along the velocity vector, z along the angular momentum, and y complete the frame. Args: orbit (list): Array of length 6 Return: numpy.ndarray: matrix to convert from inertial frame to TNW. >>> delta_tnw = [1, 0, 0] >>> p = [-6142438.668, 3492467.560, -25767.25680] >>> v = [505.8479685, 942.7809215, 7435.922231] >>> pv = p + v >>> mat = to_tnw(pv).T >>> delta_inert = mat @ delta_tnw >>> all(delta_inert == v / norm(v)) True """ pos, vel = _split(orbit) t = vel / norm(vel) w = np.cross(pos, vel) / (norm(pos) * norm(vel)) n = np.cross(w, t) return np.array([t, n, w])
java
public BranchEvent setAdType(AdType adType) { return addStandardProperty(Defines.Jsonkey.AdType.getKey(), adType.getName()); }
java
public File getFile() throws IOException { // Try the permission hack if (checkConnection()) { Permission perm = _connection.getPermission(); if (perm instanceof java.io.FilePermission) return new File(perm.getName()); } // Try the URL file arg try {return new File(_url.getFile());} catch(Exception e) {LogSupport.ignore(log,e);} // Don't know the file return null; }
java
private void validateXmlHeaderFragment(String receivedHeaderData, String controlHeaderData, XmlMessageValidationContext validationContext, TestContext context) { log.debug("Start XML header data validation ..."); Document received = XMLUtils.parseMessagePayload(receivedHeaderData); Document source = XMLUtils.parseMessagePayload(controlHeaderData); XMLUtils.stripWhitespaceNodes(received); XMLUtils.stripWhitespaceNodes(source); if (log.isDebugEnabled()) { log.debug("Received header data:\n" + XMLUtils.serialize(received)); log.debug("Control header data:\n" + XMLUtils.serialize(source)); } validateXmlTree(received, source, validationContext, namespaceContextBuilder.buildContext(new DefaultMessage(receivedHeaderData), validationContext.getNamespaces()), context); }
java
private boolean verifyNodeRegistration(DatanodeRegistration nodeReg, String ipAddr) throws IOException { assert (hasWriteLock()); return inHostsList(nodeReg, ipAddr); }
java
public static callhome get(nitro_service service) throws Exception{ callhome obj = new callhome(); callhome[] response = (callhome[])obj.get_resources(service); return response[0]; }
java
public String getImageUrl() { if (thumbnailUrl != null) { return thumbnailUrl; } if (image != null) { return image.url; } return null; }
python
def toggle_class(self, csscl): """Same as jQuery's toggleClass function. It toggles the css class on this element.""" self._stable = False action = ("add", "remove")[self.has_class(csscl)] return getattr(self.attrs["klass"], action)(csscl)
java
public String pfop(String bucket, String key, String fops) throws QiniuException { return pfop(bucket, key, fops, null); }
java
public void removeFromSet (String setName, Comparable<?> key) { requestEntryRemove(setName, getSet(setName), key); }
java
public static <K, V> Func1<Iterable<Map.Entry<K, V>>, SolidMap<K, V>> toSolidMap() { return new Func1<Iterable<Map.Entry<K, V>>, SolidMap<K, V>>() { @Override public SolidMap<K, V> call(Iterable<Map.Entry<K, V>> iterable) { return new SolidMap<>(stream(iterable).map(new Func1<Map.Entry<K, V>, Pair<K, V>>() { @Override public Pair<K, V> call(Map.Entry<K, V> value) { return new Pair<>(value.getKey(), value.getValue()); } })); } }; }
java
public void delete(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) { if (mapping.get_id() != null) { getBulk().add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString())); commitBulk(); } else { SearchResponse response = transportClient.prepareSearch(mapping.get_index()) .setTypes(mapping.get_type()) .setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal)) .setSize(10000) .get(); for (SearchHit hit : response.getHits()) { getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId()) .setDoc(esFieldData)); commitBulk(); } } }
java
private int getPackedPosition(final int position) { if (position < getHeaderViewsCount()) { return position; } else { Pair<Integer, Integer> pair = getItemPosition(position - getHeaderViewsCount()); int groupIndex = pair.first; int childIndex = pair.second; if (childIndex == -1 && groupIndex == -1) { int childCount = 0; for (int i = 0; i < getExpandableListAdapter().getGroupCount(); i++) { childCount += getExpandableListAdapter().getChildrenCount(i); } return getHeaderViewsCount() + getExpandableListAdapter().getGroupCount() + childCount + position - (getHeaderViewsCount() + adapter.getCount()); } else if (childIndex != -1) { return getPackedChildPosition(groupIndex, childIndex); } else { return getPackedGroupPosition(groupIndex); } } }
python
def _register_parser(cls): '''class decorator to register msg parser''' assert cls.cls_msg_type is not None assert cls.cls_msg_type not in _MSG_PARSERS _MSG_PARSERS[cls.cls_msg_type] = cls.parser return cls
python
def index(): """main functionality of webserver""" default = ["pagan", "python", "avatar", "github"] slogan = request.forms.get("slogan") if not slogan: if request.get_cookie("hist1"): slogan = request.get_cookie("hist1") else: slogan = "pagan" if not request.get_cookie("hist1"): hist1, hist2, hist3, hist4 = default[:] else: hist1 = request.get_cookie("hist1") hist2 = request.get_cookie("hist2") hist3 = request.get_cookie("hist3") hist4 = request.get_cookie("hist4") if slogan in (hist1, hist2, hist3, hist4): history = [hist1, hist2, hist3, hist4] history.remove(slogan) hist1, hist2, hist3 = history[0], history[1], history[2] response.set_cookie("hist1", slogan, max_age=60*60*24*30, httponly=True) response.set_cookie("hist2", hist1, max_age=60*60*24*30, httponly=True) response.set_cookie("hist3", hist2, max_age=60*60*24*30, httponly=True) response.set_cookie("hist4", hist3, max_age=60*60*24*30, httponly=True) # slogan, hist1, hist2, hist3 = escape(slogan), escape(hist1),\ # escape(hist2), escape(hist3) md5 = hashlib.md5() md5.update(slogan) slogan_hash = md5.hexdigest() md5.update(hist1) hist1_hash = md5.hexdigest() md5.update(hist2) hist2_hash = md5.hexdigest() md5.update(hist3) hist3_hash = md5.hexdigest() return template(TEMPLATEINDEX, slogan=slogan, hist1=hist1, hist2=hist2, hist3=hist3, sloganHash=slogan_hash, hist1Hash=hist1_hash, hist2Hash=hist2_hash, hist3Hash=hist3_hash)
python
def hypo_list(nodes): """ :param nodes: a hypoList node with N hypocenter nodes :returns: a numpy array of shape (N, 3) with strike, dip and weight """ check_weights(nodes) data = [] for node in nodes: data.append([node['alongStrike'], node['downDip'], node['weight']]) return numpy.array(data, float)
python
def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: points = points.reshape((1,points.size)) c = (2/np.sqrt(3.0))*points[:,1] b = (2*points[:,0] - c)/2.0 a = 1.0 - c - b out = np.vstack([a,b,c]).T if ndim == 1: return out.reshape((3,)) return out
python
def __get_document(self, content): """ Returns a `QTextDocument <http://doc.qt.nokia.com/qtextdocument.html>`_ class instance with given content. :return: Document. :rtype: QTextDocument """ document = QTextDocument(QString(content)) document.clearUndoRedoStacks() document.setModified(False) return document
java
public static RuntimeException codeBug(String msg) throws RuntimeException { msg = "FAILED ASSERTION: " + msg; RuntimeException ex = new IllegalStateException(msg); // Print stack trace ASAP ex.printStackTrace(System.err); throw ex; }
java
public static StatusUpdate instantiateStatusUpdate( final String typeIdentifier, final FormItemList values) throws StatusUpdateInstantiationFailedException { final StatusUpdateTemplate template = getStatusUpdateTemplate(typeIdentifier); final Class<?> templateInstantiationClass = template .getInstantiationClass(); try { // instantiate status update final StatusUpdate statusUpdate = (StatusUpdate) templateInstantiationClass .newInstance(); // set status update fields String value; try { for (String fieldName : template.getFields().keySet()) { try { value = values.getField(fieldName); } catch (final IllegalArgumentException e) { throw new StatusUpdateInstantiationFailedException( e.getMessage()); } templateInstantiationClass.getField(fieldName).set( statusUpdate, value); } // set status update file paths for (String fileName : template.getFiles().keySet()) { try { value = values.getFile(fileName).getAbsoluteFilePath(); } catch (final IllegalArgumentException e) { throw new StatusUpdateInstantiationFailedException( e.getMessage()); } templateInstantiationClass.getField(fileName).set( statusUpdate, value); } } catch (final IllegalArgumentException e) { throw new StatusUpdateInstantiationFailedException( "The types of the parameters passed do not match the status update template."); } return statusUpdate; } catch (final SecurityException e) { throw new IllegalArgumentException( "failed to load the status update type specified, SecurityException occurred!"); } catch (final InstantiationException e) { throw new IllegalArgumentException( "failed to load the status update type specified, InstantiationException occurred!"); } catch (final IllegalAccessException e) { throw new IllegalArgumentException( "failed to load the status update type specified, IllegalAccessException occurred!"); } catch (final NoSuchFieldException e) { throw new IllegalArgumentException( "failed to load the status update type specified, NoSuchFieldException occurred!"); } }
python
def update_in_hdx(self, **kwargs): # type: (Any) -> None """Check if resource exists in HDX and if so, update it Args: **kwargs: See below operation (string): Operation to perform eg. patch. Defaults to update. Returns: None """ self._check_load_existing_object('resource', 'id') if self.file_to_upload and 'url' in self.data: del self.data['url'] self._merge_hdx_update('resource', 'id', self.file_to_upload, **kwargs)
java
public void insert(final short[] argin, final int dim_x, final int dim_y) { attrval.r_dim.dim_x = dim_x; attrval.r_dim.dim_y = dim_y; DevVarShortArrayHelper.insert(attrval.value, argin); }
java
public alluxio.grpc.CompleteFilePOptions getOptions() { return options_ == null ? alluxio.grpc.CompleteFilePOptions.getDefaultInstance() : options_; }
java
public void setPicker(GVRPicker picker) { if (mPicker != null) { mPicker.setEnable(false); } mPicker = picker; }
java
public void marshall(AdminSetUserSettingsRequest adminSetUserSettingsRequest, ProtocolMarshaller protocolMarshaller) { if (adminSetUserSettingsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(adminSetUserSettingsRequest.getUserPoolId(), USERPOOLID_BINDING); protocolMarshaller.marshall(adminSetUserSettingsRequest.getUsername(), USERNAME_BINDING); protocolMarshaller.marshall(adminSetUserSettingsRequest.getMFAOptions(), MFAOPTIONS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def GetPathFromLink(resource_link, resource_type=''): """Gets path from resource link with optional resource type :param str resource_link: :param str resource_type: :return: Path from resource link with resource type appended (if provided). :rtype: str """ resource_link = TrimBeginningAndEndingSlashes(resource_link) if IsNameBased(resource_link): # Replace special characters in string using the %xx escape. For example, space(' ') would be replaced by %20 # This function is intended for quoting the path section of the URL and excludes '/' to be quoted as that's the default safe char resource_link = urllib_quote(resource_link) # Padding leading and trailing slashes to the path returned both for name based and resource id based links if resource_type: return '/' + resource_link + '/' + resource_type + '/' else: return '/' + resource_link + '/'
java
@Override public Long generate() { // get maximum identifier we can use (before obtaining new identifier to make sure it is in the current pool) long max = maximum.get(); // generate new identifier long identifier = atomicLong.incrementAndGet(); // check we need to obtain new identifier pool (identifier is out of range for current pool) if (identifier > max) { // loop until we get an identifier value do { // log information if (logger.isDebugEnabled()) logger.debug("About to request a pool of identifiers from database, maximum id: {}", max); // make sure only one thread gets a new range of identifiers synchronized (monitor) { // update maximum number in pool, do not switch the next two statements (in case another thread was executing the synchronized block while the current thread was waiting) max = maximum.get(); identifier = atomicLong.incrementAndGet(); // verify a new identifier is needed (compare it with current maximum) if (identifier >= max) { // create database session try (Session session = driver.session()) { // create transaction try (Transaction transaction = session.beginTransaction()) { // create cypher command, reserve poolSize identifiers Statement statement = new Statement("MERGE (g:`" + sequenceNodeLabel + "`) ON CREATE SET g.nextId = 1 ON MATCH SET g.nextId = g.nextId + {poolSize} RETURN g.nextId", Collections.singletonMap("poolSize", poolSize)); // execute statement StatementResult result = transaction.run(statement); // process result if (result.hasNext()) { // get record Record record = result.next(); // get nextId value long nextId = record.get(0).asLong(); // set value for next identifier (do not switch the next two statements!) atomicLong.set(nextId - poolSize); maximum.set(nextId); } // commit transaction.success(); } } // update maximum number in pool max = maximum.get(); // get a new identifier identifier = atomicLong.incrementAndGet(); // log information if (logger.isDebugEnabled()) logger.debug("Requested new pool of identifiers from database, current id: {}, maximum id: {}", identifier, max); } else if (logger.isDebugEnabled()) logger.debug("No need to request pool of identifiers, current id: {}, maximum id: {}", identifier, max); } } while (identifier > max); } else if (logger.isDebugEnabled()) logger.debug("Current identifier: {}", identifier); // return identifier return identifier; }
java
private void createImageAndGraphics(int layer) { layeredImage[layer] = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); layeredGraphics[layer] = layeredImage[layer].createGraphics(); layeredGraphics[layer].setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); }
java
public void setSecurityControllerMap(Map map) { for( Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry) i.next(); registerSecurityControllerAlias( (String) entry.getKey(), (SecurityController) entry.getValue() ); } }
python
def remove_step_method(self, step_method): """ Removes a step method. """ try: for s in step_method.stochastics: self.step_method_dict[s].remove(step_method) if hasattr(self, "step_methods"): self.step_methods.discard(step_method) self._sm_assigned = False except AttributeError: for sm in step_method: self.remove_step_method(sm)
java
@Override public String getPortletOutput( IPortletWindowId portletWindowId, HttpServletRequest request, HttpServletResponse response) { final IPortletRenderExecutionWorker tracker = getRenderedPortletBodyWorker(portletWindowId, request, response); final long timeout = getPortletRenderTimeout(portletWindowId, request); try { final String output = tracker.getOutput(timeout); return output == null ? "" : output; } catch (Exception e) { final IPortletFailureExecutionWorker failureWorker = this.portletWorkerFactory.createFailureWorker( request, response, portletWindowId, e); // TODO publish portlet error event? try { failureWorker.submit(); return failureWorker.getOutput(timeout); } catch (Exception e1) { logger.error("Failed to render error portlet for: " + portletWindowId, e1); return "Error Portlet Unavailable. Please contact your portal administrators."; } } }
java
@Override public <G> Choice6<A, B, C, D, E, G> flatMap( Function<? super F, ? extends Monad<G, Choice6<A, B, C, D, E, ?>>> fn) { return match(Choice6::a, Choice6::b, Choice6::c, Choice6::d, Choice6::e, f -> fn.apply(f).coerce()); }
java
public Vector2d normalizedPositiveX(Vector2d dir) { dir.x = m11; dir.y = -m01; return dir; }
java
private static <T> T createCustomComponent(Class<T> componentType, String componentSpec, Map<String, String> configProperties, IPluginRegistry pluginRegistry, T defaultComponent) throws Exception { if (componentSpec == null && defaultComponent == null) { throw new IllegalArgumentException("Null component type."); //$NON-NLS-1$ } if (componentSpec == null && defaultComponent != null) { return defaultComponent; } if (componentSpec.startsWith("class:")) { //$NON-NLS-1$ Class<?> c = ReflectionUtils.loadClass(componentSpec.substring("class:".length())); //$NON-NLS-1$ return createCustomComponent(componentType, c, configProperties); } else if (componentSpec.startsWith("plugin:")) { //$NON-NLS-1$ PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(componentSpec); if (coordinates == null) { throw new IllegalArgumentException("Invalid plugin component spec: " + componentSpec); //$NON-NLS-1$ } int ssidx = componentSpec.indexOf('/'); if (ssidx == -1) { throw new IllegalArgumentException("Invalid plugin component spec: " + componentSpec); //$NON-NLS-1$ } String classname = componentSpec.substring(ssidx + 1); Plugin plugin = pluginRegistry.loadPlugin(coordinates); PluginClassLoader classLoader = plugin.getLoader(); Class<?> class1 = classLoader.loadClass(classname); return createCustomComponent(componentType, class1, configProperties); } else { Class<?> c = ReflectionUtils.loadClass(componentSpec); return createCustomComponent(componentType, c, configProperties); } }
java
public DiscoverItems discoverCommands(Jid jid) throws XMPPException, SmackException, InterruptedException { return serviceDiscoveryManager.discoverItems(jid, NAMESPACE); }
python
def group_attrib(self): ''' return a namedtuple containing all attributes attached to groups of which the given series is a member for each group of which the series is a member ''' group_attributes = [g.attrib for g in self.dataset.groups if self in g] if group_attributes: return concat_namedtuples(*group_attributes)
python
def category(self) -> Optional[str]: '''Determine the category of existing statement''' if self.statements: if self.statements[-1][0] == ':': # a hack. ... to avoid calling isValid recursively def validDirective(): if not self.values: return True if self.values[-1].strip().endswith(','): return False try: compile( 'func(' + ''.join(self.values) + ')', filename='<string>', mode='eval') except Exception: return False return True if validDirective() and self._action is not None: return 'script' return 'directive' return 'statements' return None
java
static AtomTypePattern[] loadPatterns(InputStream smaIn) throws IOException { List<AtomTypePattern> matchers = new ArrayList<AtomTypePattern>(); BufferedReader br = new BufferedReader(new InputStreamReader(smaIn)); String line = null; while ((line = br.readLine()) != null) { if (skipLine(line)) continue; String[] cols = line.split(" "); String sma = cols[0]; String symb = cols[1]; try { matchers.add(new AtomTypePattern(SmartsPattern.create(sma).setPrepare(false), symb)); } catch (IllegalArgumentException ex) { throw new IOException(ex); } } return matchers.toArray(new AtomTypePattern[matchers.size()]); }
python
def addNodeLabelPrefix(self, prefix=None, copy=False): ''' Rename all nodes in the network from x to prefix_x. If no prefix is given, use the name of the graph as the prefix. The purpose of this method is to make node names unique so that composing two graphs is well-defined. ''' nxgraph = Topology.__relabel_graph(self.__nxgraph, prefix) if copy: newtopo = copy.deepcopy(self) newtopo.nxgraph = nxgraph return newtopo else: # looks like it was done in place self.__nxgraph = nxgraph
python
def add_view_permissions(sender, verbosity, **kwargs): """ This post_syncdb/post_migrate hooks takes care of adding a view permission too all our content types. """ from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission for content_type in ContentType.objects.all(): codename = "view_%s" % content_type.model _, created = Permission.objects \ .get_or_create(content_type=content_type, codename=codename, defaults={'name': 'Can view %s' % content_type.name}) if created and verbosity >= 1: print('Added view permission for %s' % content_type.name)
java
public static void setSpinnerDraggingEnabled( final JSpinner spinner, boolean enabled) { SpinnerModel spinnerModel = spinner.getModel(); if (!(spinnerModel instanceof SpinnerNumberModel)) { throw new IllegalArgumentException( "Dragging is only possible for spinners with a " + "SpinnerNumberModel, found "+spinnerModel.getClass()); } if (enabled) { disableSpinnerDragging(spinner); enableSpinnerDragging(spinner); } else { disableSpinnerDragging(spinner); } }
java
public static void add(final DMatrixD1 a , final DMatrixD1 b , final DMatrixD1 c ) { if( a.numCols != b.numCols || a.numRows != b.numRows ) { throw new MatrixDimensionException("The matrices are not all the same dimension."); } c.reshape(a.numRows,a.numCols); final int length = a.getNumElements(); for( int i = 0; i < length; i++ ) { c.set(i, a.get(i) + b.get(i)); } }
java
private static boolean multiPointDisjointEnvelope_(MultiPoint multipoint_a, Envelope envelope_b, double tolerance, ProgressTracker progress_tracker) { Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); multipoint_a.queryEnvelope2D(env_a); envelope_b.queryEnvelope2D(env_b); if (envelopeInfContainsEnvelope_(env_b, env_a, tolerance)) return false; Envelope2D env_b_inflated = new Envelope2D(); env_b_inflated.setCoords(env_b); env_b_inflated.inflate(tolerance, tolerance); Point2D pt_a = new Point2D(); for (int i = 0; i < multipoint_a.getPointCount(); i++) { multipoint_a.getXY(i, pt_a); if (!env_b_inflated.contains(pt_a)) continue; return false; } return true; }
java
public static Builder builder() { return new AutoValue_StackdriverStatsConfiguration.Builder() .setProjectId(DEFAULT_PROJECT_ID) .setConstantLabels(DEFAULT_CONSTANT_LABELS) .setExportInterval(DEFAULT_INTERVAL) .setMonitoredResource(DEFAULT_RESOURCE); }
java
private static String cleanPath(final Event event) throws RepositoryException { // remove any trailing data for property changes final String path = PROPERTY_TYPES.contains(event.getType()) ? event.getPath().substring(0, event.getPath().lastIndexOf("/")) : event.getPath(); // reformat any hash URIs and remove any trailing /jcr:content final HashConverter converter = new HashConverter(); return converter.reverse().convert(path.replaceAll("/" + JCR_CONTENT, "")); }
java
protected void readPersons() { try { final LoginContext login = new LoginContext( getApplicationName(), new LoginCallbackHandler(ActionCallback.Mode.ALL_PERSONS, null, null)); login.login(); for (final JAASSystem system : JAASSystem.getAllJAASSystems()) { if (ImportHandler.LOG.isDebugEnabled()) { ImportHandler.LOG.debug("check JAAS system '" + system + "'"); } final Set<?> users = login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass()); for (final Object persObj : users) { if (ImportHandler.LOG.isDebugEnabled()) { ImportHandler.LOG.debug("- check person '" + persObj + "'"); } try { final String persKey = (String) system.getPersonMethodKey().invoke(persObj, (Object) null); final String persName = (String) system.getPersonMethodName().invoke(persObj, (Object) null); PersonMapper persMapper = null; Person foundPerson = Person.getWithJAASKey(system, persKey); if (foundPerson == null) { foundPerson = Person.get(persName); } if (foundPerson == null) { persMapper = this.name2persMapper.get(persName); } else { persMapper = this.pers2persMapper.get(foundPerson); if (persMapper == null) { persMapper = this.name2persMapper.get(persName); } } if (persMapper == null) { persMapper = new PersonMapper(foundPerson, persName); } persMapper.addJAASSystem(system, persKey); } catch (final EFapsException e) { ImportHandler.LOG.error("could not search for person with JAAS key " + system.getName(), e); } catch (final IllegalAccessException e) { ImportHandler.LOG.error("could not execute person key method for system " + system.getName(), e); } catch (final IllegalArgumentException e) { ImportHandler.LOG.error("could not execute person key method for system " + system.getName(), e); } catch (final InvocationTargetException e) { ImportHandler.LOG.error("could not execute person key method for system " + system.getName(), e); } } } } catch (final LoginException e) { ImportHandler.LOG.error("could not create login context", e); } }
java
public void setXmlContentTypeManager(CmsXmlContentTypeManager manager) { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_VFS_XML_CONTENT_FINISHED_0)); } m_xmlContentTypeManager = manager; }
java
public void getGuildLogInfo(String id, String api, Callback<List<GuildLog>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildLogInfo(id, api).enqueue(callback); }
python
def make_sh_output(value, output_script, witness=False): ''' int, str -> TxOut ''' return _make_output( value=utils.i2le_padded(value, 8), output_script=make_sh_output_script(output_script, witness))
python
def loadTexture_Async(self, textureId): """Loads and returns a texture for use in the application.""" fn = self.function_table.loadTexture_Async ppTexture = POINTER(RenderModel_TextureMap_t)() result = fn(textureId, byref(ppTexture)) return result, ppTexture
java
public byte[] computeSharedSecret(Key key) throws InvalidKeyException { keyAgreement.doPhase(key, true); return keyAgreement.generateSecret(); }
java
@Override public final <T> void updateEntity( final Map<String, Object> pAddParam, final T pEntity) throws Exception { ColumnsValues columnsValues = evalColumnsValues(pAddParam, pEntity); String whereStr = evalWhereForUpdate(pEntity, columnsValues); prepareColumnValuesForUpdate(columnsValues, pEntity); int result = getSrvDatabase().executeUpdate(pEntity.getClass() .getSimpleName().toUpperCase(), columnsValues, whereStr); if (result != 1) { if (result == 0 && columnsValues.ifContains(VERSION_NAME)) { throw new ExceptionWithCode(ISrvDatabase.DIRTY_READ, "dirty_read"); } else { String query = hlpInsertUpdate.evalSqlUpdate(pEntity.getClass() .getSimpleName().toUpperCase(), columnsValues, whereStr); throw new ExceptionWithCode(ISrvDatabase.ERROR_INSERT_UPDATE, "It should be 1 row updated but it was " + result + ", query:\n" + query); } } }
java
public static int getSystemProperty (String key, int defval) { String valstr = System.getProperty(key); int value = defval; if (valstr != null) { try { value = Integer.parseInt(valstr); } catch (NumberFormatException nfe) { log.warning("'" + key + "' must be a numeric value", "value", valstr, "error", nfe); } } return value; }
python
def _post_tags(self, fileobj): """Raises ogg.error""" page = OggPage.find_last(fileobj, self.serial, finishing=True) if page is None: raise OggVorbisHeaderError self.length = page.position / float(self.sample_rate)
java
public void bindView(final MessageCenterFragment fragment, final MessageCenterRecyclerViewAdapter adapter, final Composer composer) { title.setText(composer.title); title.setContentDescription(composer.title); closeButton.setOnClickListener(guarded(new View.OnClickListener() { public void onClick(View view) { if (!TextUtils.isEmpty(message.getText().toString().trim()) || !images.isEmpty()) { Bundle bundle = new Bundle(); bundle.putString("message", composer.closeBody); bundle.putString("positive", composer.closeDiscard); bundle.putString("negative", composer.closeCancel); ApptentiveAlertDialog.show(fragment, bundle, Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION); } else { if (adapter.getListener() != null) { adapter.getListener().onCancelComposing(); } } } })); sendButton.setContentDescription(composer.sendButton); sendButton.setOnClickListener(guarded(new View.OnClickListener() { public void onClick(View view) { if (adapter.getListener() != null) { adapter.getListener().onFinishComposing(); } } })); message.setHint(composer.messageHint); message.removeTextChangedListener(textWatcher); textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { if (adapter.getListener() != null) { adapter.getListener().beforeComposingTextChanged(charSequence); } } @Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { if (adapter.getListener() != null) { adapter.getListener().onComposingTextChanged(charSequence); } } @Override public void afterTextChanged(Editable editable) { if (adapter.getListener() != null) { adapter.getListener().afterComposingTextChanged(editable.toString()); } Linkify.addLinks(editable, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES); } }; message.addTextChangedListener(textWatcher); attachButton.setOnClickListener(guarded(new View.OnClickListener() { public void onClick(View view) { if (adapter.getListener() != null) { adapter.getListener().onAttachImage(); } } })); attachments.setupUi(); attachments.setupLayoutListener(); attachments.setListener(new ApptentiveImageGridView.ImageItemClickedListener() { @Override public void onClick(int position, ImageItem image) { if (adapter.getListener() != null) { adapter.getListener().onClickAttachment(position, image); } } }); attachments.setAdapterIndicator(R.drawable.apptentive_remove_button); attachments.setImageIndicatorCallback(fragment); //Initialize image attachments band with empty data clearImageAttachmentBand(); attachments.setVisibility(View.GONE); attachments.setData(new ArrayList<ImageItem>()); setAttachButtonState(); if (adapter.getListener() != null) { adapter.getListener().onComposingViewCreated(this, message, attachments); } }
java
public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception { URL wsdlURL = getClass().getResource("/CustomerService.wsdl"); com.example.customerservice.CustomerServiceService service = new com.example.customerservice.CustomerServiceService(wsdlURL); com.example.customerservice.CustomerService customerService = service.getCustomerServiceRedirectPort(); System.out.println("Using new SOAP CustomerService with old client and the redirection"); customer.v1.Customer customer = createOldCustomer("Barry Old to New SOAP With Redirection"); customerService.updateCustomer(customer); customer = customerService.getCustomerByName("Barry Old to New SOAP With Redirection"); printOldCustomerDetails(customer); }
java
public synchronized TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException { return indexSearcher.search(query, maxQueryResults); }
python
def _download_without_backoff(url, as_file=True, method='GET', **kwargs): """ Get the content of a URL and return a file-like object. """ # Make requests consistently hashable for caching. # 'headers' is handled by requests itself. # 'cookies' and 'proxies' contributes to headers. # 'files' and 'json' contribute to data. for k in ['data', 'params']: if k in kwargs and isinstance(kwargs[k], dict): kwargs[k] = OrderedDict(sorted(kwargs[k].items())) kwargs_copy = dict(kwargs) if not _is_url_in_cache(method, url, **kwargs): now = datetime.datetime.now() _rate_limit_for_url(url, now) _rate_limit_touch_url(url, now) L.info("Download {}".format(url)) if 'timeout' not in kwargs_copy: kwargs_copy['timeout'] = _TIMEOUT if 'headers' in kwargs_copy: head_dict = CaseInsensitiveDict(kwargs_copy['headers']) if 'user-agent' not in head_dict: head_dict['user-agent'] = _USER_AGENT kwargs_copy['headers'] = head_dict else: kwargs_copy['headers'] = CaseInsensitiveDict({'user-agent': _USER_AGENT}) response = requests.request(method, url, **kwargs_copy) if logging.getLogger().isEnabledFor(logging.DEBUG): # This can be slow on large responses, due to chardet. L.debug('"{}"'.format(response.text)) response.raise_for_status() if as_file: return BytesIO(response.content) else: return response
java
public void setDestinationName(final String destinationName) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(this, TRACE, "DestinationName", destinationName); } _destinationName = destinationName; }
python
def random_codebuch(path): """Generate a month-long codebuch and save it to a file.""" lines = [] for i in range(31): line = str(i+1) + " " # Pick rotors all_rotors = ['I', 'II', 'III', 'IV', 'V'] rotors = [random.choice(all_rotors)] while len(rotors) < 3: r = random.choice(all_rotors) if not r in rotors: rotors.append(r) line += r + ' ' # Pick rotor settings. settings = [str(random.randint(1, 26))] while len(settings) < 3: s = str(random.randint(1, 26)) if not s in settings: settings.append(s) line += s + ' ' # Pick plugboard settings. plugboard = [] while len(plugboard) < 20: p1 = random_letters(1) p2 = random_letters(1) if (not p1 == p2 and not p1 in plugboard and not p2 in plugboard): plugboard.extend([p1, p2]) line += p1 + p2 + ' ' # Pick a reflector. reflector = random.choice(['B', 'C']) line += reflector line += os.linesep lines.append(line) with open(path, 'w') as f: f.writelines(lines) return lines
python
def _visit_or_none(node, attr, visitor, parent, visit="visit", **kws): """If the given node has an attribute, visits the attribute, and otherwise returns None. """ value = getattr(node, attr, None) if value: return getattr(visitor, visit)(value, parent, **kws) return None
java
private static String readScript(EncodedResource resource, String commentPrefix, String separator) throws IOException { LineNumberReader lnr = new LineNumberReader(resource.getReader()); try { return readScript(lnr, commentPrefix, separator); } finally { lnr.close(); } }
python
def pad(attrs, inputs, proto_obj): """ Add padding to input tensor""" new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width', 'value' : 'constant_value' }) new_attrs['pad_width'] = translation_utils._pad_sequence_fix(new_attrs.get('pad_width')) return 'pad', new_attrs, inputs
java
@Override public final String renderAsPhrase() { final Place place = placeRenderer.getGedObject(); return GedRenderer.escapeString(place.getString()); }
java
@Override public boolean removeAll(Collection<?> candidateElements) { boolean didRemoveAny = false; for (Object nextCandidate : candidateElements) { if (remove(nextCandidate)) { didRemoveAny = true; } } return didRemoveAny; }
java
public String getMinDateCreated() { if (m_searchParams.getMinDateCreated() == Long.MIN_VALUE) { return ""; } return Long.toString(m_searchParams.getMinDateCreated()); }
java
protected static <E extends LogRecordHandler> boolean removeHandler(Class<E> toRemove) { boolean rtn = false; Iterator<LogRecordHandler> iter = handlers.iterator(); while(iter.hasNext()){ if(iter.next().getClass().equals(toRemove)){ rtn = true; iter.remove(); } } return rtn; }
python
def get_data_range(self, name): """Gets the min/max of a scalar given its name across all blocks""" mini, maxi = np.inf, -np.inf for i in range(self.n_blocks): data = self[i] if data is None: continue # get the scalar if availble arr = get_scalar(data, name) if arr is None: continue tmi, tma = np.nanmin(arr), np.nanmax(arr) if tmi < mini: mini = tmi if tma > maxi: maxi = tma return mini, maxi
python
def printable(data): """ Replace unprintable characters with dots. @type data: str @param data: Binary data. @rtype: str @return: Printable text. """ result = '' for c in data: if 32 < ord(c) < 128: result += c else: result += '.' return result
java
public byte getByte( String key, byte defaultValue ) throws MissingResourceException { try { return getByte( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
java
public void setReferenceObject(Reference bindingObject, Class<? extends ObjectFactory> objectFactory) throws InjectionException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "setReferenceObject", bindingObjectToString(bindingObject), objectFactory); ivInjectedObject = null; ivBindingObject = bindingObject; ivObjectFactoryClass = objectFactory; // F48603.4 ivObjectFactoryClassName = objectFactory.getName(); // F54050 }
java
public void setForecastResultsByTime(java.util.Collection<ForecastResult> forecastResultsByTime) { if (forecastResultsByTime == null) { this.forecastResultsByTime = null; return; } this.forecastResultsByTime = new java.util.ArrayList<ForecastResult>(forecastResultsByTime); }
java
private <T extends AmazonWebServiceRequest> Request<T> marshall( T awsRequest, Marshaller<Request<T>, T> marshaller, AWSRequestMetrics awsRequestMetrics) { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { return marshaller.marshall(awsRequest); } catch (AmazonClientException ex) { throw ex; } catch (Exception ex) { throw new AmazonClientException(ex.getMessage(), ex); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } }
python
def _get_version_from_git_tag(path): """Return a PEP440-compliant version derived from the git status. If that fails for any reason, return the changeset hash. """ m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '') if m is None: return None version, post_commit, hash = m.groups() return version if post_commit == '0' else "{0}.post{1}+{2}".format(version, post_commit, hash)
java
public static void post(String path, String acceptType, Route route) { getInstance().post(path, acceptType, route); }
java
public void copyResourceToProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.getCurrentProject()); m_driverManager.copyResourceToProject(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_COPY_RESOURCE_TO_PROJECT_2, context.getSitePath(resource), context.getCurrentProject().getName()), e); } finally { dbc.clear(); } }
python
def call(self, op_name, query=None, **kwargs): """ Make a request to a method in this client. The response data is returned from this call as native Python data structures. This method differs from just calling the client method directly in the following ways: * It automatically handles the pagination rather than relying on a separate pagination method call. * You can pass an optional jmespath query and this query will be applied to the data returned from the low-level call. This allows you to tailor the returned data to be exactly what you want. * It automatically gets rid of uneeded parameters (with None values) :type op_name: str :param op_name: The name of the request you wish to make. :type query: str :param query: A jmespath query that will be applied to the data returned by the operation prior to returning it to the user. :type kwargs: keyword arguments :param kwargs: Additional keyword arguments you want to pass to the method when making the request. """ LOG.debug(kwargs) kwargs = {k: v for k, v in kwargs.items() if v} if query: query = jmespath.compile(query) if self.client.can_paginate(op_name): paginator = self.client.get_paginator(op_name) results = paginator.paginate(**kwargs) data = results.build_full_result() else: op = getattr(self.client, op_name) data = op(**kwargs) if query: data = query.search(data) return data
python
def main(name, options): """The main method for this script. :param name: The name of the VM to create. :type name: str :param template_name: The name of the template to use for creating \ the VM. :type template_name: str """ server = config._config_value("general", "server", options.server) if server is None: raise ValueError("server must be supplied on command line" " or in configuration file.") username = config._config_value("general", "username", options.username) if username is None: raise ValueError("username must be supplied on command line" " or in configuration file.") password = config._config_value("general", "password", options.password) if password is None: raise ValueError("password must be supplied on command line" " or in configuration file.") vm_template = None if options.template is not None: try: vm_template = template.load_template(options.template) except TemplateNotFoundError: print("ERROR: Template \"%s\" could not be found." % options.template) sys.exit(1) expected_opts = ["compute_resource", "datastore", "disksize", "nics", "memory", "num_cpus", "guest_id", "host"] vm_opts = {} for opt in expected_opts: vm_opts[opt] = getattr(options, opt) if vm_opts[opt] is None: if vm_template is None: raise ValueError("%s not specified on the command line and" " you have not specified any template to" " inherit the value from." % opt) try: vm_opts[opt] = vm_template[opt] except AttributeError: raise ValueError("%s not specified on the command line and" " no value is provided in the specified" " template." % opt) client = Client(server=server, username=username, password=password) create_vm(client, name, vm_opts["compute_resource"], vm_opts["datastore"], vm_opts["disksize"], vm_opts["nics"], vm_opts["memory"], vm_opts["num_cpus"], vm_opts["guest_id"], host=vm_opts["host"]) client.logout()
python
def _run_step(step_obj, step_declaration, initialized_resources): """Actually run a step.""" start_time = time.time() # Open any resources that need to be opened before we run this step for res_name in step_declaration.resources.opened: initialized_resources[res_name].open() # Create a dictionary of all of the resources that are required for this step used_resources = {local_name: initialized_resources[global_name] for local_name, global_name in step_declaration.resources.used.items()} # Allow steps with no resources to not need a resources keyword parameter if len(used_resources) > 0: out = step_obj.run(resources=used_resources) else: out = step_obj.run() # Close any resources that need to be closed before we run this step for res_name in step_declaration.resources.closed: initialized_resources[res_name].close() end_time = time.time() return (end_time - start_time, out)
java
<T> InjectScope<T> scope(Class<? extends Annotation> scopeType) { Supplier<InjectScope<T>> scopeGen = (Supplier) _scopeMap.get(scopeType); if (scopeGen == null) { throw error("{0} is an unknown scope", scopeType.getSimpleName()); } return scopeGen.get(); }
python
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceback (most recent call last): ... ValueError: Key conflict in inverted mapping """ res = dict((v, k) for k, v in map.items()) if not len(res) == len(map): raise ValueError('Key conflict in inverted mapping') return res
java
public static QName getQualifiedName(Object obj) { return new QName(STIXSchema.getNamespaceURI(obj), STIXSchema.getName(obj)); }
java
public static ViewGroup buildStickyDrawerItemFooter(Context ctx, DrawerBuilder drawer, View.OnClickListener onClickListener) { //create the container view final LinearLayout linearLayout = new LinearLayout(ctx); linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); //set the background color to the drawer background color (if it has alpha the shadow won't be visible) linearLayout.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(ctx, R.attr.material_drawer_background, R.color.material_drawer_background)); //create the divider if (drawer.mStickyFooterDivider) { addStickyFooterDivider(ctx, linearLayout); } fillStickyDrawerItemFooter(drawer, linearLayout, onClickListener); return linearLayout; }
python
def check_starts_with_this(self, function, docstring): """D404: First word of the docstring should not be `This`. Docstrings should use short, simple language. They should not begin with "This class is [..]" or "This module contains [..]". """ if docstring: first_word = ast.literal_eval(docstring).split()[0] if first_word.lower() == 'this': return violations.D404()
java
private Set<JSModule> getTransitiveDeps(JSModule m) { Set<JSModule> deps = dependencyMap.computeIfAbsent(m, JSModule::getAllDependencies); return deps; }
python
def warn_on_deprecated_args(self, args): """ Print warning messages for any deprecated arguments that were passed. """ # Output warning if setup.py is present and neither --ignore-setup-py # nor --use-setup-py was specified. if getattr(args, "private", None) is not None and \ (os.path.exists(os.path.join(args.private, "setup.py")) or os.path.exists(os.path.join(args.private, "pyproject.toml")) ): if not getattr(args, "use_setup_py", False) and \ not getattr(args, "ignore_setup_py", False): warning(" **** FUTURE BEHAVIOR CHANGE WARNING ****") warning("Your project appears to contain a setup.py file.") warning("Currently, these are ignored by default.") warning("This will CHANGE in an upcoming version!") warning("") warning("To ensure your setup.py is ignored, please specify:") warning(" --ignore-setup-py") warning("") warning("To enable what will some day be the default, specify:") warning(" --use-setup-py") # NDK version is now determined automatically if args.ndk_version is not None: warning('--ndk-version is deprecated and no longer necessary, ' 'the value you passed is ignored') if 'ANDROIDNDKVER' in environ: warning('$ANDROIDNDKVER is deprecated and no longer necessary, ' 'the value you set is ignored')
java
public static <T> TimestampedValue<T> from(StreamRecord<T> streamRecord) { if (streamRecord.hasTimestamp()) { return new TimestampedValue<>(streamRecord.getValue(), streamRecord.getTimestamp()); } else { return new TimestampedValue<>(streamRecord.getValue()); } }
python
def program_files(self, executable): """ OPTIONAL, this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool (to transport them to a cloud service, for example). Returns a list of files or directories that are necessary to run the tool. """ directory = os.path.dirname(executable) return [os.path.join('.', directory, f) for f in self.BINS]
python
def attachFile(self, CorpNum, ItemCode, MgtKey, FilePath, UserID=None): """ 파일 첨뢀 args CorpNum : νŒλΉŒνšŒμ› μ‚¬μ—…μžλ²ˆν˜Έ ItemCode : λͺ…μ„Έμ„œ μ’…λ₯˜ μ½”λ“œ [121 - 거래λͺ…μ„Έμ„œ], [122 - μ²­κ΅¬μ„œ], [123 - κ²¬μ μ„œ], [124 - λ°œμ£Όμ„œ], [125 - μž…κΈˆν‘œ], [126 - 영수증] MgtKey : νŒŒνŠΈλ„ˆ λ¬Έμ„œκ΄€λ¦¬λ²ˆν˜Έ FilePath : μ²¨λΆ€νŒŒμΌμ˜ 경둜 UserID : 팝빌 νšŒμ›μ•„μ΄λ”” return 처리결과. consist of code and message raise PopbillException """ if MgtKey == None or MgtKey == "": raise PopbillException(-99999999, "κ΄€λ¦¬λ²ˆν˜Έκ°€ μž…λ ₯λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.") if FilePath == None or FilePath == "": raise PopbillException(-99999999, "νŒŒμΌκ²½λ‘œκ°€ μž…λ ₯λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.") if ItemCode == None or ItemCode == "": raise PopbillException(-99999999, "λͺ…μ„Έμ„œ μ’…λ₯˜ μ½”λ“œκ°€ μž…λ ₯λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.") files = [] try: with open(FilePath, "rb") as F: files = [File(fieldName='Filedata', fileName=F.name, fileData=F.read())] except IOError: raise PopbillException(-99999999, "ν•΄λ‹Ήκ²½λ‘œμ— 파일이 μ—†κ±°λ‚˜ 읽을 수 μ—†μŠ΅λ‹ˆλ‹€.") return self._httppost_files('/Statement/' + str(ItemCode) + '/' + MgtKey + '/Files', None, files, CorpNum, UserID)
python
def get_assessment_ids_by_bank(self, bank_id): """Gets the list of ``Assessment`` ``Ids`` associated with a ``Bank``. arg: bank_id (osid.id.Id): ``Id`` of the ``Bank`` return: (osid.id.IdList) - list of related assessment ``Ids`` raise: NotFound - ``bank_id`` is not found raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceBinSession.get_resource_ids_by_bin id_list = [] for assessment in self.get_assessments_by_bank(bank_id): id_list.append(assessment.get_id()) return IdList(id_list)
python
def keybundle_from_local_file(filename, typ, usage): """ Create a KeyBundle based on the content in a local file :param filename: Name of the file :param typ: Type of content :param usage: What the key should be used for :return: The created KeyBundle """ usage = harmonize_usage(usage) if typ.lower() == "jwks": kb = KeyBundle(source=filename, fileformat="jwks", keyusage=usage) elif typ.lower() == 'der': kb = KeyBundle(source=filename, fileformat="der", keyusage=usage) else: raise UnknownKeyType("Unsupported key type") return kb
python
def fire(self, args, kwargs): """ Fire this signal with the specified arguments and keyword arguments. Typically this is used by using :meth:`__call__()` on this object which is more natural as it does all the argument packing/unpacking transparently. """ for info in self._listeners[:]: if info.pass_signal: info.listener(*args, signal=self, **kwargs) else: info.listener(*args, **kwargs)
java
@Override public RequestCertificateResult requestCertificate(RequestCertificateRequest request) { request = beforeClientExecution(request); return executeRequestCertificate(request); }
python
def parse_optional_matrix(x): """Parse optional NRRD matrix from string into (M,N) :class:`numpy.ndarray` of :class:`float`. Function parses optional NRRD matrix from string into an (M,N) :class:`numpy.ndarray` of :class:`float`. This function works the same as :meth:`parse_matrix` except if a row vector in the matrix is none, the resulting row in the returned matrix will be all NaNs. See :ref:`user-guide:double matrix` for more information on the format. Parameters ---------- x : :class:`str` String containing NRRD matrix Returns ------- matrix : (M,N) :class:`numpy.ndarray` of :class:`float` Matrix that is parsed from the :obj:`x` string """ # Split input by spaces to get each row and convert into a vector. The row can be 'none', in which case it will # return None matrix = [parse_optional_vector(x, dtype=float) for x in x.split()] # Get the size of each row vector, 0 if None sizes = np.array([0 if x is None else len(x) for x in matrix]) # Get sizes of each row vector removing duplicate sizes # Since each row vector should be same size, the unique sizes should return one value for the row size or it may # return a second one (0) if there are None vectors unique_sizes = np.unique(sizes) if len(unique_sizes) != 1 and (len(unique_sizes) != 2 or unique_sizes.min() != 0): raise NRRDError('Matrix should have same number of elements in each row') # Create a vector row of NaN's that matches same size of remaining vector rows # Stack the vector rows together to create matrix nan_row = np.full((unique_sizes.max()), np.nan) matrix = np.vstack([nan_row if x is None else x for x in matrix]) return matrix
java
@Path("/{dsID}/content") @GET public Response getDatastream(@PathParam(RestParam.PID) String pid, @PathParam(RestParam.DSID) String dsID, @QueryParam(RestParam.AS_OF_DATE_TIME) String dateTime, @QueryParam(RestParam.DOWNLOAD) String download, @QueryParam(RestParam.FLASH) @DefaultValue("false") boolean flash) { Context context = getContext(); try { Date asOfDateTime = DateUtility.parseDateOrNull(dateTime); MIMETypedStream stream = m_access.getDatastreamDissemination(context, pid, dsID, asOfDateTime); if (m_datastreamFilenameHelper != null) { m_datastreamFilenameHelper .addContentDispositionHeader(context, pid, dsID, download, asOfDateTime, stream); } return buildResponse(stream); } catch (Exception ex) { return handleException(ex, flash); } }
java
@CheckForNull public T newInstanceFromRadioList(JSONObject config) throws FormException { if(config.isNullObject()) return null; // none was selected int idx = config.getInt("value"); return get(idx).newInstance(Stapler.getCurrentRequest(),config); }