language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def clip_lower(self, threshold): """ Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as vector arrays, in which case each individual element in each vector is clipped. Throws an exception if the SArray is em...
java
public void delete(String key) throws VictimsException { key = hash(key); try { FileUtils.forceDelete(FileUtils.getFile(location, key)); } catch (IOException e) { throw new VictimsException(String.format( "Could not delete the cached entry from disk: %...
java
@SuppressWarnings("unused") // called through reflection by RequestServer public FramesV3 column(int version, FramesV3 s) { // TODO: should return a Vec schema Frame frame = getFromDKV("key", s.frame_id.key()); Vec vec = frame.vec(s.column); if (null == vec) throw new H2OColumnNotFoundArgumentExcep...
python
def runCommand(command): """Run a command. :param command: the command to run. :type command: list Tries to run a command. If it fails, raise a :py:class:`ProgramError`. This function uses the :py:mod:`subprocess` module. .. warning:: The variable ``command`` should be a list of stri...
java
public FromHostResult < J > convert(byte[] hostData, int start, int length) { Cob2JaxbVisitor visitor = new Cob2JaxbVisitor(getCobolContext(), hostData, start, length, jaxbWrapperFactory); visitor.visit(getCobolComplexType()); JaxbWrapper < ? > jaxbWrapper = visitor ...
python
def get_max_bond_lengths(structure, el_radius_updates=None): """ Provides max bond length estimates for a structure based on the JMol table and algorithms. Args: structure: (structure) el_radius_updates: (dict) symbol->float to update atomic radii Returns: (dict) - (Element...
python
def get_composition_query_session_for_repository(self, repository_id, proxy): """Gets a composition query session for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionQuerySes...
python
def concat(self, *args, **kwargs): """ :type args: FormattedText :type kwargs: FormattedText """ for arg in args: assert self.formatted_text._is_compatible(arg), "Cannot concat text with different modes" self.format_args.append(arg.text) for kwarg ...
java
@Deprecated public com.ibm.cloud.objectstorage.services.s3.model.ProgressListener getProgressListener() { ProgressListener generalProgressListener = getGeneralProgressListener(); if (generalProgressListener instanceof LegacyS3ProgressListener) { return ((LegacyS3ProgressListener)generalP...
java
public static Map<String, StoreDefinition> getSystemStoreDefMap() { Map<String, StoreDefinition> sysStoreDefMap = Maps.newHashMap(); List<StoreDefinition> storesDefs = SystemStoreConstants.getAllSystemStoreDefs(); for(StoreDefinition def: storesDefs) { sysStoreDefMap.put(def.getName(...
java
public Availability getEntryByDate(Date date) { Availability result = null; for (Availability entry : this) { DateRange range = entry.getRange(); int comparisonResult = range.compareTo(date); if (comparisonResult >= 0) { if (comparisonResult == 0) ...
java
@Override public Map<Circuit, Collection<TileRef>> getCircuits(Collection<Media> levels, Media sheetsConfig, Media groupsConfig) { final Collection<MapTile> mapsSet = new HashSet<>(leve...
java
public static Value<Boolean> and (Value<Boolean>... values) { return and(Arrays.asList(values)); }
java
public static String arrayToDelimitedString(Object[] arr, String delim) { if (Objects.isEmpty(arr)) { return ""; } if (arr.length == 1) { return Objects.nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.len...
python
def copy(self): """ Make a new instance of this Token. This method makes a copy of the mutable part of the token before making the instance. """ return self.__class__(self.tag, self.data.copy(), self.context.copy())
python
def fit_from_image(self, data, voxelsize, seeds, unique_cls): """ This Method allows computes feature vector and train model. :cls: list of index number of requested classes in seeds """ fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls) self...
python
def update_variable(self, var, grad_var): """Update the variable and its slots.""" params = self.params global_step = tf.to_float(self.global_step) + 1 # compute learning rate lrate = params.learning_rate if params.learning_rate_decay_scheme == "noam": lrate *= tf.minimum(global_step * pa...
java
public final void setGeoidheight(StringBuilder contentBuffer) { ptValues[GpxMetadata.PTGEOIDWEIGHT] = Double.parseDouble(contentBuffer.toString()); }
java
public static <REACTOR extends ReactBuilder> ReactPool<REACTOR> elasticPool(final Supplier<REACTOR> supplier) { return new ReactPool<>( supplier); }
java
public NodeOverrides withNodePropertyOverrides(NodePropertyOverride... nodePropertyOverrides) { if (this.nodePropertyOverrides == null) { setNodePropertyOverrides(new java.util.ArrayList<NodePropertyOverride>(nodePropertyOverrides.length)); } for (NodePropertyOverride ele : nodePrope...
java
public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{ cachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding(); obj.set_labelname(labelname); cachepolicylabel_policybinding_binding response[] = (cachepolicylabel_polic...
python
def add_seconds(datetime_like_object, n, return_date=False): """ Returns a time that n seconds after a time. :param datetimestr: a datetime object or a datetime str :param n: number of seconds, value can be negative **中文文档** 返回给定日期N秒之后的时间。 """ a_datetime = parser.parse_datetime(dateti...
java
public static void drawChessboard( Graphics2D g2 , WorldToCameraToPixel fiducialToPixel , int numRows , int numCols , double squareWidth ) { Point3D_F64 fidPt = new Point3D_F64(); Point2D_F64 pixel0 = new Point2D_F64(); Point2D_F64 pixel1 = new Point2D_F64(); Point2D_F64 pixel2 = new Point2D_F64();...
python
def plot_confusion_matrix(self, normalised=True): """ Plots the confusion matrix. """ conf_matrix = self.confusion_matrix() if normalised: sns.heatmap(conf_matrix, annot=True, annot_kws={"size": 12}, fmt='2.1f', cmap='YlGnBu', vmin=0.0, ...
python
def _set_trust(self, v, load=False): """ Setter method for trust, mapped from YANG variable /interface/port_channel/qos/trust (container) If this variable is read-only (config: false) in the source YANG file, then _set_trust is considered as a private method. Backends looking to populate this variab...
java
public void setPosition(Long pos) { Interval interval = getInterval(); if (interval != null) { resetInterval(pos, interval.getStartGranularity()); } else { resetInterval(pos, null); } }
java
@Override public void finishRawResponseMessage(WsByteBuffer[] body) throws IOException, MessageSentException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "finishRawResponseMessage(sync)"); } setRawBody(true); finishResponseMessage(body...
java
private void writeInitPacket(final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) throws DeviceDisconnectedException, DfuException, UploadAbortedException { if (mAborted) throw new UploadAbortedException(); byte[] locBuffer = buffer; if (buffer.length != size) { locBuffe...
java
@Override public GetFacetResult getFacet(GetFacetRequest request) { request = beforeClientExecution(request); return executeGetFacet(request); }
python
def _process_json(data): """ return a list of GradPetition objects. """ requests = [] for item in data: petition = GradPetition() petition.description = item.get('description') petition.submit_date = parse_datetime(item.get('submitDate')) petition.decision_date = pars...
java
@Override public URL[] findResources() { URL[] result = null; if (classesToScan != null && !classesToScan.isEmpty()) { result = findResourcesByContextLoader(); } // else // { // result = findResourcesByClasspath(); // } return ...
java
public static void closeQuietly(final InputStream aInputStream) { if (aInputStream != null) { try { aInputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } }
java
@Deprecated protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf) throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecExcept...
python
def _load_module(path): 'Helper to load a Python file at path and return as a module' module_name = os.path.splitext(os.path.basename(path))[0] module = None if sys.version_info.minor < 5: loader = importlib.machinery.SourceFileLoader(module_name, path) module = loader.load_mod...
java
public void layout (Graphics2D gfx, SceneObject tipFor, Rectangle boundary) { layout(gfx, ICON_PAD, EXTRA_PAD); bounds = new Rectangle(_size); // locate the most appropriate tip layout for (int ii = 0, ll = _layouts.size(); ii < ll; ii++) { LayoutReg reg = _layouts.get(i...
python
def check_password_expired(user): """ Return True if password is expired and system is using password expiration, False otherwise. """ if not settings.ACCOUNT_PASSWORD_USE_HISTORY: return False if hasattr(user, "password_expiry"): # user-specific value expiry = user.pass...
python
def get_prop(self, key, default_val=None): """ Returns a property set on the context. :Parameters: key String key to lookup in the context props dict default_val Value to return if key is not set on the context props """ if self.props....
python
def identify_sep(filepath): """ Identifies the separator of data in a filepath. It reads the first line of the file and counts supported separators. Currently supported separators: ['|', ';', ',','\t',':'] """ ext = os.path.splitext(filepath)[1].lower() allowed_exts = ['.csv', '.txt', '.tsv'...
python
def _seconds_to_section_split(record, sections): """ Finds the seconds to the next section from the datetime of a record. """ next_section = sections[ bisect_right(sections, _find_weektime(record.datetime))] * 60 return next_section - _find_weektime(record.datetime, time_type='sec')
java
public static String readContentAsString(File file, String encoding) { try { return readContentAsString(new FileInputStream(file), encoding); } catch (FileNotFoundException e) { throw new RuntimeException(e); } }
java
public LabelAlphabet buildLabelAlphabet(String name) { IAlphabet alphabet = null; if (!maps.containsKey(name)) { maps.put(name, new LabelAlphabet()); alphabet = maps.get(name); }else { alphabet = maps.get(name); if (!(alphabet instanceof LabelAlphabet)) { throw new ClassCastException(); ...
python
def being(self): """ Being a Transaction @author: Nick Verbeck @since: 5/14/2011 """ try: if self.connection is not None: self.lock() c = self.getCursor() c.execute('BEGIN;') c.close() except Exception, e: pass
python
def focal(self): """ Get the focal length in pixels for the camera. Returns ------------ focal : (2,) float Focal length in pixels """ if self._focal is None: # calculate focal length from FOV focal = [(px / 2.0) / np.tan(np.radi...
python
def build_unprocessable_error(cls, errors=None): """Utility method to build a HTTP 422 Parameter Error object""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.UNPROCESSABLE_ENTITY, errors)
java
public SoyMsgBundle createFromFile(File inputFile) throws IOException { // TODO: This is for backwards-compatibility. Figure out how to get rid of this. // We special-case English locales because they often don't have translated files and falling // back to the Soy source should be fine. if (!inputFile...
java
@Nullable // TODO make non-null and always throw? public Bitmap get() throws IOException { long started = System.nanoTime(); checkNotMain(); if (deferred) { throw new IllegalStateException("Fit cannot be used with get."); } if (!data.hasImage()) { return null; } Request reque...
python
def set(self, *raw_args, **raw_kwargs): """ Manually set the cache value with its appropriate expiry. """ if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_args = list(raw_args) data = raw_args.pop() ...
python
def set(self, value): """ Sets the value of the object :param value: A byte string """ if not isinstance(value, byte_cls): raise TypeError(unwrap( ''' %s value must be a byte string, not %s ''', ...
python
def available(self): """ Check whether we have a PEP identity associated with our account. """ disco_info = yield from self._disco_client.query_info( self.client.local_jid.bare() ) for item in disco_info.identities.filter(attrs={"category": "pubsub"}): ...
java
@Override public void eUnset(int featureID) { switch (featureID) { case XbasePackage.XTHROW_EXPRESSION__EXPRESSION: setExpression((XExpression)null); return; } super.eUnset(featureID); }
python
def checkReference(self, reference): """ Check the reference for security. Tries to avoid any characters necessary for doing a script injection. """ pattern = re.compile(r'[\s,;"\'&\\]') if pattern.findall(reference.strip()): return False return True
python
def enc_file(name, out=None, **kwargs): ''' This is a helper function to encrypt a file and return its contents. You can provide an optional output file using `out` `name` can be a local file or when not using `salt-run` can be a url like `salt://`, `https://` etc. CLI Examples: .. code-bloc...
java
public static double largeEstimator(final int log2m, final int registerSizeInBits, final double estimator) { final double twoToL = TWO_TO_L[(REG_WIDTH_INDEX_MULTIPLIER * registerSizeInBits) + log2m]; return -1 * twoToL * Math.log(1.0 - (estimator/twoToL)); }
python
def _parse_expires(expires): """ Parse the 'expires' attribute, guessing what format it is in and returning a datetime """ # none is used to signify positive infinity if expires is None or expires in ('never', 'infinity'): return 'infinity' try: return dateutil.parser.parse(...
java
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) return; mergeOrOverwriteTurnInfo(fromEdge, viaNode, toEdge, turnFlags, true); }
java
public void setAmbientIntensity(float r, float g, float b, float a) { setVec4("ambient_intensity", r, g, b, a); }
java
private void initialize() { this.setName(Constant.messages.getString("pscan.options.name")); this.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.weightx = 1.0; gbc.anchor = GridBagConstraints.LINE_START; ...
java
public static base_response restore(nitro_service client, appfwprofile resource) throws Exception { appfwprofile restoreresource = new appfwprofile(); restoreresource.archivename = resource.archivename; return restoreresource.perform_operation(client,"restore"); }
java
@Override public void setFilter(Service.Filter filter) { _filter = _filter == null ? filter : new CompoundServiceFilter(filter, _filter); }
java
public static sslvserver[] get(nitro_service service) throws Exception{ sslvserver obj = new sslvserver(); sslvserver[] response = (sslvserver[])obj.get_resources(service); return response; }
python
def eparOptionFactory(master, statusBar, param, defaultParam, doScroll, fieldWidths, plugIn=None, editedCallbackObj=None, helpCallbackObj=None, mainGuiObj=None, defaultsVerb="Default", bg=None, indent=False, fl...
python
def get_network(network_id): """Get the network with the given id.""" try: net = models.Network.query.filter_by(id=network_id).one() except NoResultFound: return error_response(error_type="/network GET: no network found", status=403) # return the data return success_response(network...
java
public void setResources(java.util.Collection<HandshakeResource> resources) { if (resources == null) { this.resources = null; return; } this.resources = new java.util.ArrayList<HandshakeResource>(resources); }
java
public void start(Xid xid, int flags) throws XAException { try { cl.getManagedConnection().getLocalTransaction().begin(); } catch (ResourceException re) { throw new LocalXAException("start", XAException.XAER_RMERR, re); } }
java
@Override public Map<String, Object> toSource() { Map<String, Object> sourceMap = new HashMap<>(); if (createdBy != null) { addFieldToSource(sourceMap, "createdBy", createdBy); } if (createdTime != null) { addFieldToSource(sourceMap, "createdTime", createdTime...
java
public static Date getTime(Datebox datebox, Timebox timebox) { if (timebox.getValue() == null || datebox.getValue() == null) { return DateUtil.stripTime(datebox.getValue()); } Calendar date = Calendar.getInstance(); Calendar time = Calendar.getInstance(); date.setTim...
python
def create_batch(self, job_id, data, file_type): """ Creates a batch with either a string of data or a file containing data. If a file is provided, this will pull the contents of the file_target into memory when running. That shouldn't be a problem for any files that meet the Salesforce...
python
def count(self, event_str, inc_int=1): """Count an event. Args: event_str: The name of an event to count. Used as a key in the event dict. The same name will also be used in the summary. inc_int: int Optional argument to increase the count for th...
python
def _compute_biases(self, rs): """Generate MLP biases""" # use supplied biases if present biases = self._get_user_components('biases') if (biases is None): b_size = self.n_hidden biases = rs.normal(size=b_size) self.components_['biases'] = biases
java
public static long calculateDate( CmsObject cms, CmsResource resource, List<String> dateIdentifiers, long defaultValue) { long result = 0; List<CmsProperty> properties = null; for (int i = 0, size = dateIdentifiers.size(); i < size; i++) { // check al...
java
public static <K, V> V putIfAbsent(Map<K, V> map, K key, V value) { V old = map.putIfAbsent(key, value); if (old != null) { return old; } return value; }
java
public JSONNavi<T> set(String key, float value) { return set(key, Float.valueOf(value)); }
python
def _parse_line(self, line): """ Parsed result:: {'timestamp':'May 18 14:24:14', 'procname': 'kernel', 'hostname':'lxc-rhel68-sat56', 'message': '...', 'raw_message': '...: ...' } """ msg_info = {'raw_message': ...
java
public static Geometry rotate(Geometry geom, double theta, Point point) { return rotate(geom, theta, point.getX(), point.getY()); }
java
public String convertIfcWorkScheduleTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public static IbanLengthMapSharedConstants create() { if (ibanLengthMapConstants == null) { // NOPMD it's thread save! synchronized (IbanLengthMapConstantsClient.class) { if (ibanLengthMapConstants == null) { final IbanLengthMapConstants ibanLengthMap = GWT.create(IbanLengthMapConstants.clas...
java
public static <T> boolean addAll( Collection<T> addTo, Iterator<? extends T> iterator) { checkNotNull(addTo); checkNotNull(iterator); boolean wasModified = false; while (iterator.hasNext()) { wasModified |= addTo.add(iterator.next()); } return wasModified; }
python
def server_close(self): """Called to clean-up the server. May be overridden. """ if self.remove_file: try: os.remove(self.remove_file) except: pass self.socket.close()
python
def create_mirror_settings(repo_url): """ Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all repositories to look at. :param repo_url: the repository URL to use :returns: filepath to the created file """ cwd = os.getcwd() ...
java
private void exit(final int arity, final OtpErlangPid to, final OtpErlangObject reason) { try { final String node = to.node(); if (node.equals(home.node())) { home.deliver(new OtpMsg(OtpMsg.exitTag, self, to, reason)); } else { fina...
python
def plot_places(self): '''Plot places where the agent has been and generated a spirograph. ''' from matplotlib import pyplot as plt fig, ax = plt.subplots() x = [] y = [] if len(self.arg_history) > 1: xs = [] ys = [] for p in s...
python
def list_upcoming(cls): """ Returns a collection of upcoming tasks (tasks that have not yet been completed, regardless of whether they’re overdue) for the authenticated user :return: :rtype: list """ return fields.ListField(name=cls.ENDPOINT, init_class=cls).deco...
python
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the...
python
def merge(x, y): """ Merge two dictionaries and raise an error for inconsistencies. Parameters ---------- x : dict dictionary x y : dict dictionary y Returns ------- x : dict merged dictionary Raises ------ ValueError if `x` and `y` are ...
java
@Override public String convertTo(final Object value) { if (value == null) return "null"; return convertTo(value.getClass(), value); }
python
def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False): """ Shift fields from the discovery set to the requested date by the average motion of L7 kbos in the discovery field. :param ras: :param decs: :param plot: :param ax: :param kbos: precompu...
python
def get_pull_requests_activities(self, project, repository, pull_request_id): """ Get pull requests activities :param project: :param repository: :param pull_request_id: the ID of the pull request within the repository :return: """ url = 'rest/api/1.0/proj...
python
def _recipient_from_cloud(self, recipient, field=None): """ Transform a recipient from cloud data to object data """ if recipient: recipient = recipient.get(self._cc('emailAddress'), recipient if isinstance(recipient, ...
python
def check_uniqueness(self, *args, **kwargs): """Check if the given "value" (via `args`) is unique or not. For the parameters, see ``BaseIndex.check_uniqueness`` """ if not self.field.unique: return try: pk = self.instance.pk.get() except Attrib...
java
public java.util.List<StepAdjustment> getStepAdjustments() { if (stepAdjustments == null) { stepAdjustments = new com.amazonaws.internal.SdkInternalList<StepAdjustment>(); } return stepAdjustments; }
java
public List<CsvError> getGlobalErrors() { final List<CsvError> list = new ArrayList<CsvError>(); for(CsvError item : this.errors) { if(!(item instanceof CsvFieldError)) { list.add(item); } } return list; }
python
def find_selected(self, event): '''find the selected menu item''' for m in self.items: ret = m.find_selected(event) if ret is not None: return ret return None
java
void onColumnSelect(final int index, final boolean selected) { final DataColumnDef columnDef = acceptableColumns.get(index); if (selected) { listEditor.getList().add(columnDef.clone()); } else { listEditor.getList().remove(columnDef); } columnsChangedEvent...
python
def _parse_memory(s): """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024} if s[-1].lower() not in units: ...
java
public <EE extends E> Iterator<EE> iterator(Class<EE> type) { try { disableSeek(); } catch (IOException exception) { // } return Iterators.filter(new ElementIterator(), type); }
python
def file_resolve(backend, filepath): """ Mark a conflicted file as resolved, so that a merge can be completed """ recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_dateti...
python
def set(self, name, value, **kw): """Set the attribute to the given value. The keyword arguments represent the other attribute values to integrate constraints to other values. """ # check write permission sm = getSecurityManager() permission = permissions.Manage...
python
def client(self, name): """ Returns the :class:`~plexapi.client.PlexClient` that matches the specified name. Parameters: name (str): Name of the client to return. Raises: :class:`plexapi.exceptions.NotFound`: Unknown client name """ for c...
python
def _validate_query_parameters(self, query, action_spec): """Check the query parameter for the action specification. Args: query: query parameter to check. action_spec: specification of the action. Returns: True if the query is valid. """ pro...
python
def _upload_assets_to_OSF(dlgr_id, osf_id, provider="osfstorage"): """Upload experimental assets to the OSF.""" root = "https://files.osf.io/v1" snapshot_filename = "{}-code.zip".format(dlgr_id) snapshot_path = os.path.join("snapshots", snapshot_filename) r = requests.put( "{}/resources/{}/p...