language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _get_date_time_format(dt_string): ''' Copied from win_system.py (_get_date_time_format) Function that detects the date/time format for the string passed. :param str dt_string: A date/time string :return: The format of the passed dt_string :rtype: str ''' valid_formats = [ ...
java
public void setShrink(double shrink) { if(shrink >= 1 || shrink <= 0 || Double.isNaN(shrink) || Double.isInfinite(shrink) ) throw new ArithmeticException("Shrinkage constant must be > 0 and < 1, not " + shrink); this.shrink = shrink; }
java
private static boolean collectCallableLeavesInternal(Node expr, ArrayList<Node> results) { switch (expr.getToken()) { case FUNCTION: case GETPROP: case NAME: results.add(expr); return true; case SUPER: { // Pretend that `super` is an alias for the superclas...
java
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytes); try { out.writeObject(o); } finally { out.close(); } ObjectInputStream in = new Obj...
java
@Managed @ManagedDescription("Returns global index size") public long getGlobalIndexSize() throws QuotaManagerException { long size = 0; for (RepositoryQuotaManager rqm : rQuotaManagers.values()) { size += rqm.getRepositoryIndexSize(); } return size; }
python
def _slice_area_from_bbox(self, src_area, dst_area, ll_bbox=None, xy_bbox=None): """Slice the provided area using the bounds provided.""" if ll_bbox is not None: dst_area = AreaDefinition( 'crop_area', 'crop_area', 'crop_latlong', ...
java
static public String getFormattedDateTime(long dt, String format, TimeZone tz, String country, long tolerance) { String ret = ""; SimpleDateFormat df = null; try { if(dt > tolerance) { df = formatPool.getFormat(format); df.setT...
java
public WorkProgress createTaskProgress(long amount, String text) { this.amount += amount; SubWorkProgress task = new SubWorkProgress(this, amount, amount, text); synchronized (tasks) { tasks.add(task); if (jp != null) jp.addToJoinDoNotCancel(task.getSynch()); } return task; }
python
def query(self, tableClass, comparison=None, limit=None, offset=None, sort=None): """ Return a generator of instances of C{tableClass}, or tuples of instances if C{tableClass} is a tuple of classes. Examples:: fastCars = s.query(Vehicle, ...
java
public static Parser<Void> blockComment(Parser<Void> begin, Parser<Void> end, Parser<?> commented) { return Parsers.sequence(begin, end.not().next(commented).skipMany(), end); }
java
public Object handleRemoteCommand(String strCommand, Map<String,Object> properties, Object sourceSession) throws RemoteException, DBException { Object objHandled = this.doRemoteCommand(strCommand, properties); // Do I handle it? if (Boolean.FALSE.equals(objHandled)) { // Not handled by ...
python
def libvlc_audio_equalizer_set_preamp(p_equalizer, f_preamp): '''Set a new pre-amplification value for an equalizer. The new equalizer settings are subsequently applied to a media player by invoking L{libvlc_media_player_set_equalizer}(). The supplied amplification value will be clamped to the -20.0 to ...
java
@Override public synchronized ApiFuture<Void> add(RowMutation rowMutation) { Preconditions.checkNotNull(rowMutation, "mutation details cannot be null"); final ApiFuture<Void> response = bulkMutateBatcher.add(rowMutation); operationAccountant.registerOperation(ApiFutureUtil.adapt(response)); return res...
python
def get_registration_email_link(application): """ Retrieve a link that can be emailed to the logged other users. """ url = '%s/applications/%d/' % ( settings.REGISTRATION_BASE_URL, application.pk) is_secret = False return url, is_secret
python
def score_n1(matrix, matrix_size): """\ Implements the penalty score feature 1. ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54) ============================================ ======================== ====== Feature Ev...
python
def deleteSystemVariable(self, remote, name): """Delete a system variable from CCU / Homegear""" if self._server is not None: return self._server.deleteSystemVariable(remote, name)
python
async def CreateModel(self, cloud_tag, config, credential, name, owner_tag, region): ''' cloud_tag : str config : typing.Mapping[str, typing.Any] credential : str name : str owner_tag : str region : str Returns -> typing.Union[_ForwardRef('Number'), str, t...
java
public ServiceFuture<SyncMemberInner> createOrUpdateAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName, String syncMemberName, SyncMemberInner parameters, final ServiceCallback<SyncMemberInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServi...
python
def _update_color_hsv(self, event=None): """Update display after a change in the HSV spinboxes.""" if event is None or event.widget.old_value != event.widget.get(): h = self.hue.get() s = self.saturation.get() v = self.value.get() sel_color = hsv_to_rgb(h,...
python
def case(self, case_id=None): """Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object """ cases = self.cases() if case_id: for case ...
java
@Override public Page<Entity> previousPage(final Page<Entity> page, final TwilioRestClient client) { Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl( Domains.AUTHY.toString(), client.getRegio...
python
def decr(self, key, value, noreply=False): """ The memcached "decr" command. Args: key: str, see class docs for details. value: int, the amount by which to increment the value. noreply: optional bool, False to wait for the reply (the default). Returns: ...
python
def write(self, data, context=None): """Enqueues the passed in data to the :func:`queue`. If the caller specifies a context as well, it will take precedence over the instance in :func:`context`. Args: data (object). data the telemetry data to send. This will be wrapped in an :c...
java
@Override public T get() { try { return clazz.getConstructor(CharStream.class).newInstance(new Object[] { null }); } catch (Exception e) { throw new RuntimeException(e); } }
python
def add_widgets(self, *widgets_or_spacings): """Add widgets/spacing to dialog vertical layout""" layout = self.layout() for widget_or_spacing in widgets_or_spacings: if isinstance(widget_or_spacing, int): layout.addSpacing(widget_or_spacing) else: ...
java
public java.util.List<Ipv6Range> getIpv6Ranges() { if (ipv6Ranges == null) { ipv6Ranges = new com.amazonaws.internal.SdkInternalList<Ipv6Range>(); } return ipv6Ranges; }
python
def _find_last_line_index(contents): """Find the last line of the headerblock in contents.""" lineno = 0 headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT)) if not len(contents): raise RuntimeError("""File does not not have any contents""") while headerblock.match(contents[lineno]): ...
python
def get_kline_data(self, symbol, kline_type='5min', start=None, end=None): """Get kline data For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time. :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string ...
java
public char[] passwordHash(char[] password) { if (null == password) { return null; } return BCrypt.hashpw(password, BCrypt.gensalt()); }
python
def get_magic_guesses(fullpath): """ Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file @type fullpath: string @return: guesses about content of the file @rtype: tuple """ if CFG_HAS_MAGIC == 1: magic_c...
java
public Observable<Page<AppServicePlanInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<AppServicePlanInner>>, Page<AppServicePlanInner>>() { @Override ...
java
void store(int A, int r, int B) { getB(A, r).add(B); getA(B, r).add(A); }
python
def _create(self, **attributes): """ Create new interface on IxNetwork. Set enabled and description (==name). :return: interface object reference. """ attributes['enabled'] = True if 'name' in self._data: attributes['description'] = self._data['name'] ...
python
def validate_all_keys_in_obj(obj_name, obj, validation_fun): """Validate all (nested) keys in `obj` by using `validation_fun`. Args: obj_name (str): name for `obj` being validated. obj (dict): dictionary object. validation_fun (function): function used to validate the va...
java
public static String formatDurationOnSecond(@NotNull Date startDate, @NotNull Date endDate) { return DurationFormatUtils.formatDuration(endDate.getTime() - startDate.getTime(), "HH:mm:ss"); }
python
def sq_dist(X1,X2=None): """ computes a matrix of all pariwise squared distances """ if X2==None: X2 = X1 assert X1.shape[1]==X2.shape[1], 'dimensions do not match' n = X1.shape[0] m = X2.shape[0] d = X1.shape[1] # (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2 X1sq = sp.reshape((...
python
def get_buildfile_path(settings): """ Path to which a build tarball should be downloaded. """ base = os.path.basename(settings.build_url) return os.path.join(BUILDS_ROOT, base)
python
def _addrinfo_or_none(contact_point, port): """ A helper function that wraps socket.getaddrinfo and returns None when it fails to, e.g. resolve one of the hostnames. Used to address PYTHON-895. """ try: return socket.getaddrinfo(contact_point, port, sock...
java
@Override public DescribeIdentityProviderConfigurationResult describeIdentityProviderConfiguration(DescribeIdentityProviderConfigurationRequest request) { request = beforeClientExecution(request); return executeDescribeIdentityProviderConfiguration(request); }
java
@Override public EClass getIfcDerivedUnit() { if (ifcDerivedUnitEClass == null) { ifcDerivedUnitEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(172); } return ifcDerivedUnitEClass; }
python
def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_preprocess, bool, bool, bool, bool, Callable[[s...
python
def get_online_version (): """Download update info and parse it.""" # prevent getting a cached answer headers = {'Pragma': 'no-cache', 'Cache-Control': 'no-cache'} content, info = get_content(UPDATE_URL, addheaders=headers) if content is None: return content, info version, url = None, No...
python
def logout(self): """ Logs the user out of all clients and removes the expires_in, expires_datetime, id_token, refresh_token, access_token, and token_type attributes :return: """ self.client.global_sign_out( AccessToken=self.access_token ) ...
python
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
java
private void handleInputElements(Eventable eventable) { CopyOnWriteArrayList<FormInput> formInputs = eventable.getRelatedFormInputs(); for (FormInput formInput : formHandler.getFormInputs()) { if (!formInputs.contains(formInput)) { formInputs.add(formInput); } } formHandler.handleFormElements(formIn...
python
def process_value(self, value): """Process publication value """ # UID -> SuperModel if api.is_uid(value): return self.to_super_model(value) # Content -> SuperModel elif api.is_object(value): return self.to_super_model(value) # String -> Un...
python
def redirect(self, id, name, **options): """ Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: name is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs...
java
@Pure public List<String> getMimeTypes() { if (this.mimeTypes.isEmpty()) { return Arrays.asList("text/x-" + getLanguageSimpleName().toLowerCase()); //$NON-NLS-1$ } return this.mimeTypes; }
python
def output(data, **kwargs): # pylint: disable=unused-argument ''' Read in the dict structure generated by the salt key API methods and print the structure. ''' color = salt.utils.color.get_colors( __opts__.get('color'), __opts__.get('color_theme')) strip_colors = __opts_...
java
public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFields( int firstFieldNumber, int... rest) { return usingConfig( config.ignoringExtraRepeatedFieldElementsOfFields(asList(firstFieldNumber, rest))); }
python
def image_size(self, pnmfile): """Get width and height of pnm file. simeon@homebox src>pnmfile /tmp/214-2.png /tmp/214-2.png:PPM raw, 100 by 100 maxval 255 """ pout = os.popen(self.shellsetup + self.pnmfile + ' ' + pnmfile, 'r') pnmfileout = pout.read(200) pout....
python
def get_balance(self, address, block="latest"): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getbalance """ response = self.make_request("eth_getBalance", [address, block]) return int(response['result'], 16)
python
def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT): """Writes a plot SVG to a file. Args: plot (list): a list of layers to plot filename (str): the name of the file to write width (float): the width of the output SVG heig...
python
def eth_getBlockByNumber(self, number): """Get block body by block number. :param number: :return: """ block_hash = self.reader._get_block_hash(number) block_number = _format_block_number(number) body_key = body_prefix + block_number + block_hash block_da...
java
private static boolean isValidDate(String date, Calendar out, String separator) { try { String[] dates = date.split(separator); out.set(Calendar.DATE, Integer.parseInt(dates[dates.length - 1])); out.set(Calendar.MONTH, Integer.parseInt(dates[dates.length - 2])); i...
python
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False): """Returns a dictionary of object's attributes, ignoring methods @param obj: The object to represent as dict @param omit_null_fields: If true, will not include fields in the dictionary that are null @re...
java
public static DateIterator createDateIterator( String rdata, Date start, TimeZone tzid, boolean strict) throws ParseException { return new RecurrenceIteratorWrapper( RecurrenceIteratorFactory.createRecurrenceIterator( rdata, dateToDateValue(start, ...
java
public void setCanvasWidthHeight(int width, int height) { hudWidth = width; hudHeight = height; HUD = Bitmap.createBitmap(width, height, Config.ARGB_8888); canvas = new Canvas(HUD); texture = null; }
java
protected OkRequest<T> writePartHeader(final String name, final String filename) throws IOException { return writePartHeader(name, filename, null); }
java
public static void pack(File sourceDir, OutputStream os, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into a stream.", sourceDir); if (!sourceDir.exists()) { throw new ZipException("Given file '" + sourceDir + "' doesn't exist!"); } ZipOutputStream out = null; IOExcep...
python
def __read_lipd_contents(): """ Use the file metadata to read in the LiPD file contents as a dataset library :return dict: Metadata """ global files, settings _d = {} try: if len(files[".lpd"]) == 1: _d = lipd_read(files[".lpd"][0]["full_path"]) if settings["...
java
private void startCameraSource() throws SecurityException { // check that the device has play services available. int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( getActivity().getApplicationContext()); if (code != ConnectionResult.SUCCESS) { ...
java
@PublicAPI(usage = ACCESS) public ClassFileImporter withImportOption(ImportOption option) { return new ClassFileImporter(importOptions.with(option)); }
java
public static String capitalize (String s) { if (isBlank(s)) { return s; } char c = s.charAt(0); if (Character.isUpperCase(c)) { return s; } else { return String.valueOf(Character.toUpperCase(c)) + s.substring(1); } }
java
public static Attribute getQueryRuleAttribute(QueryRule queryRule, EntityType entityType) { String queryRuleField = queryRule.getField(); if (queryRuleField == null) { return null; } Attribute attr = null; String[] queryRuleFieldTokens = StringUtils.split(queryRuleField, NESTED_ATTRIBUTE_SEPA...
python
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expecte...
python
def _compile_pattern(self, rule): ''' Return a regular expression with named groups for each wildcard. ''' out = '' for i, part in enumerate(self.syntax.split(rule)): if i%3 == 0: out += re.escape(part.replace('\\:',':')) elif i%3 == 1: out += '(?P<%s>' % part if part e...
java
private boolean tokenizeCSVLine(CSVFile csvFile, BufferedReader reader, Map<String, String> fieldMap) { fieldMap.clear(); m_token.setLength(0); // First build a list of tokens found in the or...
python
def new_feature_container(self, idx, path=None): """ Add a new feature container with the given data. Parameters: idx (str): An unique identifier within the dataset. path (str): The path to store the feature file. If None a default path is used. Returns: ...
python
def update_bookmark(self, old, new, *, max_retries=3): """ Update a bookmark and check it was successful. The bookmark matches an existing bookmark `old` according to bookmark equalitiy and replaces it by `new`. The bookmark `new` is added if no bookmark matching `old` exists. ...
java
public static <T> void quickSelect(T data, Adapter<T> adapter, int start, int end, int rank) { while(true) { // Optimization for small arrays // This also ensures a minimum size below if(start + SMALL > end) { insertionSort(data, adapter, start, end); return; } // Best...
java
private HttpClient getClient(int retries, int connectionTimeout, int socketTimeout) { HttpClient httpClient = new DefaultHttpClient(); HttpParams httpParams = httpClient.getParams(); // Retries if (retries > 0) { DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpR...
python
def get_name_uids(self, name, channel=None): """get list of users (helper) :param channel: number [1:7] :return: list of users """ if channel is None: channel = self.get_network_channel() uid_list = [] max_ids = self.get_channel_max_user_count(channe...
python
def del_repo(repo, root=None): ''' Delete a repo. root operate on a different root directory. CLI Examples: .. code-block:: bash salt '*' pkg.del_repo alias ''' repos_cfg = _get_configured_repos(root=root) for alias in repos_cfg.sections(): if alias == repo: ...
java
@Override public synchronized Collection<WrapperRunnable> getAndClearStartRunnables() { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) { logger.entering(CLASS_NAME, "getAndClearStartRunnables",this); } //set the pointer to...
python
def array(self, name): """ Returns the array of tables with the given name. """ if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] else: raise NoArrayFoundError else: ...
python
def update(self, read, write, manage): """ Update the SyncMapPermissionInstance :param bool read: Read access. :param bool write: Write access. :param bool manage: Manage access. :returns: Updated SyncMapPermissionInstance :rtype: twilio.rest.sync.v1.service.syn...
python
def options(self): """Train tickets query options.""" arg = self.get(0) if arg.startswith('-') and not self.is_asking_for_help: return arg[1:] return ''.join(x for x in arg if x in 'dgktz')
python
def runcommand(cosmology='WMAP5'): """ Example interface commands """ # Return the WMAP5 cosmology concentration predicted for # z=0 range of masses Mi = [1e8, 1e9, 1e10] zi = 0 print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi)) output = commah.run(cosmology=cosmology, zi=zi, ...
java
public static <T> T getElementAt(T[] array, int index, T defaultValue) { return nullSafeLength(array) > index ? array[index] : defaultValue; }
java
public static Map<FieldType, String> getDefaultAliases() { Map<FieldType, String> map = new HashMap<FieldType, String>(); map.put(TaskField.DATE1, "Suspend Date"); map.put(TaskField.DATE2, "Resume Date"); map.put(TaskField.TEXT1, "Code"); map.put(TaskField.TEXT2, "Activity Type"); ...
java
public void onConversationHidden(Peer peer) { if (visiblePeer != null && visiblePeer.equals(peer)) { this.visiblePeer = null; } }
java
public ConjunctionMatcher<T> and(Matcher<? super T> matcher) { requireNonNull(matcher, "matcher"); return new ConjunctionMatcher<>(compositeDescription, concat(matchers, matcher)); }
java
private static Set<GeoPosition> getMapGeoBounds(JXMapViewer mapViewer) { Set<GeoPosition> set = new HashSet<GeoPosition>(); TileFactory tileFactory = mapViewer.getTileFactory(); int zoom = mapViewer.getZoom(); Rectangle2D bounds = mapViewer.getViewportBounds(); Point2D pt = n...
java
private final ValueNode registerFinalValue(int value) { // We always register final values because while ADDING // we do not know yet whether we will build fast or small. lookupFinalValueNode.setFinalValue(value); Node oldNode=nodes.get(lookupFinalValueNode); if(oldNode!=null) { ...
java
protected void resizeBuffer (final int additionalLength, final boolean copyData) { if (additionalLength < 0) { throw new IllegalArgumentException("The length must be greater or equal than 0."); } dataBuffer.position(length); // reallocate a bigger dataBuffer, if needed if (length + ad...
java
private boolean checkForBadModuleReference(Name name, Ref ref) { JSModuleGraph moduleGraph = compiler.getModuleGraph(); if (name.getGlobalSets() == 0 || ref.type == Ref.Type.SET_FROM_GLOBAL) { // Back off if either 1) this name was never set, or 2) this reference /is/ a set. return false; } ...
python
def _format_pair_no_equals(explode, separator, escape, key, value): """ Format a key, value pair but don't include the equals sign when there is no value """ if not value: return key return _format_pair(explode, separator, escape, key, value)
python
def random_filename(path=None): """Make a UUID-based file name which is extremely unlikely to exist already.""" filename = uuid4().hex if path is not None: filename = os.path.join(path, filename) return filename
python
def op_paths(self, path_base): # type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]] """ Return all operations stored in containers. """ path_base += self.path_prefix for operation in self._operations: for op_path in operation.op_paths(path_ba...
java
@Override @SuppressWarnings("unchecked") public <C> Const<A, C> biMapR(Function<? super B, ? extends C> fn) { return (Const<A, C>) Bifunctor.super.biMapR(fn); }
java
public void clear(int size, int off) { if (size%4 != 4) size = (size/4+1)*4; next = null; previous = null; data = new byte[size]; offset = off; for(int i = 0; i < data.length; i++) data[i] = 0; usableBits = off; }
python
def perform(cls, entity_cls, usecase_cls, request_object_cls, payload: dict, raise_error=False): """ This method bundles all essential artifacts and initiates usecase execution. :param entity_cls: The entity class to be used for running the usecase :param usecase_...
java
@Override public DownloadPolicy getDownloadPolicy() { if (_asset.getWlpInformation() == null) { return null; } return _asset.getWlpInformation().getDownloadPolicy(); }
java
static void escape( final Reader reader, final Writer writer, final XmlEscapeSymbols symbols, final XmlEscapeType escapeType, final XmlEscapeLevel escapeLevel) throws IOException { if (reader == null) { return; } final int level = escapeLevel.get...
python
def check_flashing_need(self, execution_type, build_id, force): """ Check if flashing of local device is required. :param execution_type: Should be 'hardware' :param build_id: Build id, usually file name :param force: Forceflash flag :return: Boolean """ ...
python
def dotted_parts(s): """ For a string "a.b.c", yields "a", "a.b", "a.b.c". """ idx = -1 while s: idx = s.find('.', idx+1) if idx == -1: yield s break yield s[:idx]
java
public boolean hasSystemLocks(CmsDbContext dbc, CmsResource resource) throws CmsException { if (resource == null) { return false; } Iterator<CmsLock> itLocks = OpenCms.getMemoryMonitor().getAllCachedLocks().iterator(); while (itLocks.hasNext()) { CmsLock lock = i...
java
public static CalendarPicker<ThaiSolarCalendar> thaiWithSystemDefaults() { return CalendarPicker.thai( Locale.getDefault(Locale.Category.FORMAT), () -> SystemClock.inLocalView().now(ThaiSolarCalendar.axis()) ); }
java
public static void unregisterLogListener(@NonNull final Context context, @NonNull final DfuLogListener listener) { if (mLogBroadcastReceiver != null) { final boolean empty = mLogBroadcastReceiver.removeLogListener(listener); if (empty) { LocalBroadcastManager.getInstance(context).unregisterReceiver(mLogBro...