language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def regular_fragments(self): """ Iterates through the regular fragments in the list (which are sorted). :rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`) """ for i, fragment in enumerate(self.__fragments): if fragment.fragment_type == SyncM...
python
def position(x=None, y=None): """Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Args: x (int, None, optional) - If not None, this argument overrides the x in the return value. y (int, None, optional) - If not None, this argument overrides the y in ...
python
def clusterflow_pipelines_section(self): """ Generate HTML for section about pipelines, generated from information parsed from run files. """ data = dict() pids_guessed = '' for f,d in self.clusterflow_runfiles.items(): pid = d.get('pipeline_id', 'unknown') ...
python
def stop(self): """Stop the sensor. """ if not self._running: return self._weight_subscriber.unregister() self._running = False
java
public void setSelectedRow(java.lang.Object _selectedRow) { getStateHelper().put(PropertyKeys.selectedRow, _selectedRow); }
java
public static java.util.List<com.liferay.commerce.model.CommerceOrderPayment> getCommerceOrderPayments( int start, int end) { return getService().getCommerceOrderPayments(start, end); }
java
@Override public StorePath uploadImage(FastImageFile fastImageFile) { String fileExtName = fastImageFile.getFileExtName(); Validate.notNull(fastImageFile.getInputStream(), "上传文件流不能为空"); Validate.notBlank(fileExtName, "文件扩展名不能为空"); // 检查是否能处理此类图片 if (!isSupportImage(fileExtNam...
java
@Override public CommerceAddressRestriction[] findByC_C_PrevAndNext( long commerceAddressRestrictionId, long classNameId, long classPK, OrderByComparator<CommerceAddressRestriction> orderByComparator) throws NoSuchAddressRestrictionException { CommerceAddressRestriction commerceAddressRestriction = findByPrima...
java
public static Object convertClob(Connection conn, byte[] value) throws SQLException { Object result = (Object) createClob(conn); result = convertClob(result, value); return result; }
java
public void broadcastInfoPacket() { if (infoScheduled.compareAndSet(false, true)) { scheduler.schedule(() -> { infoScheduled.set(false); sendInfoPacket(infoBroadcastChannel); }, 1, TimeUnit.SECONDS); } }
java
@Override protected List<Pair<Integer, Integer>> doGenerateEdges() { final int edgesPerNewNode = getConfiguration().getEdgesPerNewNode(); final long numberOfNodes = getConfiguration().getNumberOfNodes(); // Create a completely connected network final List<Pair<Integer, Integer>> edg...
python
def db_insert(self): """ Insert results in the `MongDB` database. """ assert self.has_db # Connect to MongoDb and get the collection. coll = self.manager.db_connector.get_collection() print("Mongodb collection %s with count %d", coll, coll.count()) start ...
java
private State checkL(State state) throws DatatypeException, IOException { if (state.context.length() == 0) { state = appendToContext(state); } state.current = state.reader.read(); state = appendToContext(state); state = skipSpaces(state); _checkL('L', true, st...
python
def _uri(self, url): """Returns request absolute URI""" if url and not url.startswith('/'): # Then this must be a proxy request. return url uri = "{0}://{1}{2}{3}".format( self._protocol, self.real_connection.host, self._port_postfix(),...
python
def solar(filename_solar, solar_factor): ''' read solar abundances from filename_solar. Parameters ---------- filename_solar : string The file name. solar_factor : float The correction factor to apply, in case filename_solar is not solar, but some file used to get initia...
java
private void setTrimLeadingWhitespacesByReflection(Renderer result, boolean trimLeadingCommonSourceWhitespaces) { String fieldName = "trimLeadingWhitespace"; if (logger.isDebugEnabled()) { logger.debug("Try setting '{}' field to '{}' for '{}' by reflection.", fieldName, trimLeadingCommonSour...
python
def _get_node_by_key(self, key, path=None): """Returns the 2-tuple (prefix, node) where node either contains the value corresponding to the key, or is the most specific prefix on the path which would contain the key if it were there. The key was found if prefix==key and the node.value is...
java
public void set(TemporalField field, long newValue) { Objects.requireNonNull(field, "field"); synchronized (instantHolder) { ZonedDateTime current = ZonedDateTime.ofInstant(instantHolder.get(), zone); ZonedDateTime result = current.with(field, newValue); instantHolder...
python
def send_text(self, text): """Send text message to telegram user. Text message should be markdown formatted. :param text: markdown formatted text. :return: status code on error. """ if not self.is_token_set: raise ValueError('TelepythClient: Access token is n...
java
public static String underlineToCamel(String param) { if (isEmpty(param.trim())) { return ""; } StringBuilder sb = new StringBuilder(param); Matcher mc = Pattern.compile(UNDERLINE).matcher(param); int i = 0; while (mc.find()) { int position = mc.en...
python
def static_fit_result(fit_result, v_residual=None, v_label='Unit-cell volume $(\mathrm{\AA}^3)$', figsize=(5, 5), height_ratios=(3, 1), ms_data=8, p_err=None, v_err=None, pdf_filen=None, title='Fit result'): """ plot static ...
java
public static Map makeMap(Mapper mapper, Enumeration en, boolean includeNull) { HashMap h = new HashMap(); for (; en.hasMoreElements();) { Object k = en.nextElement(); Object v = mapper.map(k); if (includeNull || v != null) { h.put(k, v); }...
python
def setLineEnds(self, start, end): """setLineEnds(self, start, end)""" CheckParent(self) return _fitz.Annot_setLineEnds(self, start, end)
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.IPS__PSEG_NAME: return PSEG_NAME_EDEFAULT == null ? psegName != null : !PSEG_NAME_EDEFAULT.equals(psegName); case AfplibPackage.IPS__XPS_OSET: return XPS_OSET_EDEFAULT == null ? xpsOset != null : !XPS_OSET_EDEFAULT...
java
public static Geldbetrag valueOf(Number value, Currency currency) { return valueOf(new Geldbetrag(value, currency)); }
java
public long readRawVarint64() throws IOException { int shift = 0; long result = 0; while (shift < 64) { final byte b = readRawByte(); result |= (long) (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; ...
java
@Nonnull public static LBiBoolConsumer biBoolConsumerFrom(Consumer<LBiBoolConsumerBuilder> buildingFunction) { LBiBoolConsumerBuilder builder = new LBiBoolConsumerBuilder(); buildingFunction.accept(builder); return builder.build(); }
java
public static <T, R> Function<T, R> changeInto(R input) { return t -> input; }
java
public void setFacesInitializer(FacesInitializer facesInitializer) // TODO who uses this method? { if (_facesInitializer != null && _facesInitializer != facesInitializer && _servletContext != null) { _facesInitializer.destroyFaces(_servletContext); } _facesInitializer = f...
python
def get_lat_long_climate_zones(latitude, longitude): """ Get climate zones that contain lat/long coordinates. Parameters ---------- latitude : float Latitude of point. longitude : float Longitude of point. Returns ------- climate_zones: dict of str Region ids fo...
python
def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will sto...
python
def flow_transition(Diam, Nu): """Return the flow rate for the laminar/turbulent transition. This equation is used in some of the other equations for flow. """ #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [Nu, ">0", "Nu"]) return np.pi * Diam * RE_TRANSITION_PIPE * Nu / 4
java
private DescribeAlarmsResponse describeAlarms() { DescribeAlarmsResponse ret = new DescribeAlarmsResponse(); DescribeAlarmsResult result = new DescribeAlarmsResult(); MetricAlarms metricAlarms = new MetricAlarms(); MetricAlarm metricAlarm = new MetricAlarm(); metricAlarm.setAlar...
python
def save(self): """ Creates this index in the collection if it hasn't been already created """ api = Client.instance().api index_details = { 'type': self.index_type_obj.type_name } extra_index_attributes = self.index_type_obj.get_extra_attribute...
python
def byaxis(self): """Object to index ``self`` along axes. Examples -------- Indexing with integers or slices: >>> p = odl.uniform_partition([0, 1, 2], [1, 3, 5], (3, 5, 6)) >>> p.byaxis[0] uniform_partition(0.0, 1.0, 3) >>> p.byaxis[1] uniform_pa...
java
@Override public Object toJdbc(final Optional<?> original, final Connection connection, final BindParameterMapperManager parameterMapperManager) { return original.isPresent() ? parameterMapperManager.toJdbc(original.get(), connection) : null; }
python
def get_product_metadata_path(product_name): """ gets a single products metadata """ string_date = product_name.split('_')[-1] date = datetime.datetime.strptime(string_date, '%Y%m%dT%H%M%S') path = 'products/{0}/{1}/{2}/{3}'.format(date.year, date.month, date.day, product_name) return { pr...
python
def profile_df(df): """ Generate a profile of data in a dataframe. Args: df: the Pandas dataframe. """ # The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect. # TODO(gram): strip it out rather than this kludge. return IPython.core.display.HTML( pandas_profiling.Pro...
java
public static long murmurhash3(CharSequence chars, int seed) { final int len = chars.length(); final int nblocks = len / 8; long h1 = seed; long h2 = seed; final long c1 = 0x87c37b91114253d5L; final long c2 = 0x4cf5ad432745937fL; for (int i = 0; i < nblocks; ++i) { int i0 = (i*2 + 0) * 4; int i...
python
def _get_example_values(self, route: str, annotation: ResourceAnnotation) -> Dict[str, Any]: """Gets example values for all properties in the annotation's schema. :param route: The route to get example values for. :type route: werkzeug.routing.Rule for a flask api. ...
java
public BatchGetProjectsResult withProjectsNotFound(String... projectsNotFound) { if (this.projectsNotFound == null) { setProjectsNotFound(new java.util.ArrayList<String>(projectsNotFound.length)); } for (String ele : projectsNotFound) { this.projectsNotFound.add(ele); ...
python
def kong_61_2007(): r"""Kong 61 pt Hankel filter, as published in [Kong07]_. Taken from file ``FilterModules.f90`` provided with 1DCSEM_. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_. """ dlf = DigitalFilter('Kong 61', 'kong_61_2007') dlf.base = ...
java
private void setArgumentValue(final Object value) { try { getUnderlyingField().set(getContainingObject(), value); } catch (final IllegalAccessException e) { throw new CommandLineException.ShouldNeverReachHereException( String.format( ...
python
def __FinalUrlValue(self, value, field): """Encode value for the URL, using field to skip encoding for bytes.""" if isinstance(field, messages.BytesField) and value is not None: return base64.urlsafe_b64encode(value) elif isinstance(value, six.text_type): return value.enc...
java
@SuppressWarnings("WeakerAccess") public Map<DeckReference, BeatGrid> getLoadedBeatGrids() { ensureRunning(); // Make a copy so callers get an immutable snapshot of the current state. return Collections.unmodifiableMap(new HashMap<DeckReference, BeatGrid>(hotCache)); }
java
public Template handleRequest (HttpServletRequest req, HttpServletResponse rsp, Context ctx) throws Exception { InvocationContext ictx = (InvocationContext)ctx; Logic logic = null; // listen for exceptions so that we can report them EventCartridge ec = ictx.getEventCartridge...
python
def join_or_die(self): """Wait for thread to finish, returning a PhaseExecutionOutcome instance.""" if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) # We got a return value or an exception and handled i...
java
private static void searchForJars(final File file, List<File> jars) { if (file.isFile()) { if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) { jars.add(file); LOG.debug("Found a jar: " + file.getAbsolutePath()); } } else if (file.isDirectory()) { File[] files = file.li...
java
private static void addTypeToList(Type type, List<Type> typeList) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; addTypeToList(parameterizedType.getRawType(), typeList); for (Type actualTypeArgument : parameterizedTy...
java
@Override public Object setChild(final String key, final Controller<M, V> controller) { if (null != controller.getParent()) { // controller.getParent().re } return children.put(key, controller); }
java
@Override public final void setJmsxAppId(Byte value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setJmsxAppId", value); getHdr2().setField(JsHdr2Access.XAPPID_COMPACT, value); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnab...
python
def set_disk0(self, disk0): """ Sets the size (MB) for PCMCIA disk0. :param disk0: disk0 size (integer) """ yield from self._hypervisor.send('vm set_disk0 "{name}" {disk0}'.format(name=self._name, disk0=disk0)) log.info('Router "{name}" [{id}]: disk0 updated from {old_...
java
private static String value(String nameEqualsValue) { int idx = nameEqualsValue.indexOf('='); String value = nameEqualsValue.substring(idx + 1).trim(); return QuotedStringTokenizer.unquoteOnly(value); }
python
def formatted_datetime(self, fmt: str = '', **kwargs) -> str: """Generate datetime string in human readable format. :param fmt: Custom format (default is format for current locale) :param kwargs: Keyword arguments for :meth:`~Datetime.datetime()` :return: Formatted datetime string. ...
java
public static @Nonnull JsonArray array(JsonBuilder... elements) { JsonArray jjArray = new JsonArray(); for (JsonBuilder b : elements) { jjArray.add(b); } return jjArray; }
python
def position(self, message): """Calculate position within the PR, which is not the line number""" if not message.line_number: message.line_number = 1 for patched_file in self.patch: target = patched_file.target_file.lstrip("b/") if target == message.path: ...
python
def temporary(self, path): """Establishes a temporary build root, restoring the prior build root on exit.""" if path is None: raise ValueError('Can only temporarily establish a build root given a path.') prior = self._root_dir self._root_dir = path try: yield finally: self._roo...
python
def address(self): """ IP Address using bacpypes Address format """ port = "" if self._port: port = ":{}".format(self._port) return Address( "{}/{}{}".format( self.interface.ip.compressed, self.interface.exploded.spl...
java
public static void installResourceExtension(DatabaseClient client) throws IOException { // create a manager for resource extensions ResourceExtensionsManager resourceMgr = client.newServerConfigManager().newResourceExtensionsManager(); // specify metadata about the resource extension ExtensionMet...
java
static int[] getMeasurementsForShiftingMode(Context context, int screenWidth, int noOfTabs, boolean scrollable) { int[] result = new int[2]; int minWidth = (int) context.getResources().getDimension(R.dimen.shifting_min_width_inactive); int maxWidth = (int) context.getResources().getDimension(R...
python
def comments_1(self, value=None): """Corresponds to IDD Field `comments_1` Args: value (str): value for IDD Field `comments_1` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
python
def get_fields_with_prop(cls, prop_key): """ Return a list of fields with a prop key defined Each list item will be a tuple of field name containing the prop key & the value of that prop key. :param prop_key: key name :return: list of tuples """ ret = [] ...
java
public NodeSchema toTVEAndFixColumns(Map<String, Pair<String, Integer>> nameMap) { final NodeSchema ns = copyAndReplaceWithTVE(); // First convert all non-TVE expressions to TVE in a copy m_columns.clear(); m_columnsMapHelper.clear(); for(int indx = 0; indx < ns.size(); ++indx) { // the...
java
public static MutableLongTuple add( Collection<? extends LongTuple> tuples, MutableLongTuple result) { if (tuples.isEmpty()) { return null; } int size = getSize(result, tuples); MutableLongTuple localResult = tuples.parallel...
python
def _copy_source_to_target(self): """ copy source user configuration to target """ if self.source and self.target: for k, v in self.source.items('config'): # always have source override target. self.target.set_input(k, v)
java
public NameValuePair[] getParameters() { log.trace("enter PostMethod.getParameters()"); int numPairs = this.params.size(); Object[] objectArr = this.params.toArray(); NameValuePair[] nvPairArr = new NameValuePair[numPairs]; for (int i = 0; i < numPairs; i++) { ...
java
public static void assertEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode) throws JSONException { if (expectedStr==actualStr) return; if (expectedStr==null){ throw new AssertionError("Expected string is null."); }else if (actualStr==nul...
python
def get_border_index(I, shape, size): """ Get flattened indices for the border of the region I. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region. size : int region size (technically computable from shape argument) shape : tuple(int, int) ...
java
public static Duration fromMillis(long milliseconds) { Duration.Builder builder = builder(); if (milliseconds < 0) { builder.prior(true); milliseconds *= -1; } int seconds = (int) (milliseconds / 1000); Integer weeks = seconds / (60 * 60 * 24 * 7); if (weeks > 0) { builder.weeks(weeks); } se...
python
def returned(self): """Does the extracted piece contain return statement""" if self._returned is None: node = _parse_text(self.extracted) self._returned = usefunction._returns_last(node) return self._returned
python
def pinch(self, scale, velocity): """ Args: scale (float): scale must > 0 velocity (float): velocity must be less than zero when scale is less than 1 Example: pinchIn -> scale:0.5, velocity: -1 pinchOut -> scale:2.0, velocity: 1 "...
java
public static Navigate from(@NonNull android.support.v4.app.Fragment fragment) { return new Navigate(null, null, null, fragment); }
python
def _CreateZMQSocket(self): """Creates a ZeroMQ socket as well as a regular queue and a thread.""" super(ZeroMQBufferedQueue, self)._CreateZMQSocket() if not self._zmq_thread: thread_name = '{0:s}_zmq_responder'.format(self.name) self._zmq_thread = threading.Thread( target=self._ZeroMQ...
python
def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFields = ListFields
python
def state(self): """Returns the current LED state by querying the remote controller.""" ev = self._query_waiters.request(self.__do_query_state) ev.wait(1.0) return self._state
java
public static VectorFunction asDivFunction(final double arg) { return new VectorFunction() { @Override public double evaluate(int i, double value) { return value / arg; } }; }
python
def _arg(self, line): '''singularity doesn't have support for ARG, so instead will issue a warning to the console for the user to export the variable with SINGULARITY prefixed at build. Parameters ========== line: the line from the recipe file to parse fo...
java
public Map<String, Class<?>> injectRaw(Map<? extends String, byte[]> types) { Dispatcher dispatcher = DISPATCHER.initialize(); Map<String, Class<?>> result = new HashMap<String, Class<?>>(); synchronized (classLoader == null ? BOOTSTRAP_LOADER_LOCK ...
java
private RootPathToken readContextToken() { readWhitespace(); if (!isPathContext(path.currentChar())) { throw new InvalidPathException("Path must start with '$' or '@'"); } RootPathToken pathToken = PathTokenFactory.createRootPathToken(path.currentChar()); if (path...
java
public java.util.List<com.google.api.Billing.BillingDestination> getConsumerDestinationsList() { return consumerDestinations_; }
java
private boolean removeUpdate() throws IOException, ServletException { final File patchDir = getPatchDirectory(); final File[] patches = patchDir.listFiles(new ExtensionFilter(new String[] { "rc", "rcs" })); for (int i = 0; i < patches.length; i++) if (!patches[i].delete()) patches[i].deleteOnExit(); _restart(...
java
private MBeanInfo getInfo(Object object, ClassIntrospector classIntrospector) throws IntrospectionException { JmxBean jmxBean = AnnotationUtils.getAnnotation(object.getClass(), JmxBean.class); MBeanInfo beanInfo = new MBeanInfo(object.getClass().getName(), ...
java
public static void setField(Object obj, String fieldName, Object value) { try { setField(obj, getField(obj.getClass(), fieldName), value); } catch (FieldNotFoundException e) { throw new IllegalArgumentException(String.format("Field with name (%1$s) does not exist on object of type (%2$s)!", ...
python
def sleep(self): """Wait for the sleep time of the last response, to avoid being rate limited.""" if self.next_time and time.time() < self.next_time: time.sleep(self.next_time - time.time())
java
public static RuntimeException propagate(final Exception exception) { if (RuntimeException.class.isAssignableFrom(exception.getClass())) { return (RuntimeException) exception; } return new RuntimeException("Repropagated " + exception.getMessage(), exception); //NOPMD }
java
public EClass getFNP() { if (fnpEClass == null) { fnpEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(269); } return fnpEClass; }
python
def alterar(self, id_script, id_script_type, script, description, model=None): """Change Script from by the identifier. :param id_script: Identifier of the Script. Integer value and greater than zero. :param id_script_type: Identifier of the Script Type. Integer value and greater than zero. ...
java
public void setResources(List value) { if (value == null) { m_resources = new ArrayList(); return; } m_resources = CmsFileUtil.removeRedundancies(value); }
java
public int incrementCount (K key, int amount) { int[] val = get(key); if (val == null) { put(key, val = new int[1]); } val[0] += amount; return val[0]; /* Alternate implementation, less hashing on the first increment but more garbage created * ev...
python
def database(self): """ Before the callback is called, initialize the database if needed. :rtype: None """ #1. Initialize self.callback.im_self.db = sql.setup(self.settings) if self.callback.im_self.db: module = '.'.join(self.callback.im_self.__module_...
java
public static Dynamic ofInvocation(Constructor<?> constructor, List<?> rawArguments) { return ofInvocation(new MethodDescription.ForLoadedConstructor(constructor), rawArguments); }
java
public Observable<ServiceResponse<OperationStatus>> updateEntityWithServiceResponseAsync(UUID appId, String versionId, UUID entityId, UpdateEntityOptionalParameter updateEntityOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoin...
python
def tostring(self): """return a pretty-printed string output for rpc reply""" parser = etree.XMLParser(remove_blank_text=True) outputtree = etree.XML(etree.tostring(self.__doc), parser) return etree.tostring(outputtree, pretty_print=True)
python
def asjsonld( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, export_context=True, basedir=None, ): """Dump a JSON-LD class to the JSON with generated ``@context`` field.""" jsonld_fields = inst.__class__._jsonld_fields attrs = tuple( fi...
java
@SuppressWarnings("unchecked") @Override public List<? extends PairSet<T, I>> powerSet(int min, int max) { return (List<? extends PairSet<T, I>>) super.powerSet(min, max); }
java
public Map<String, Process> getRuleFlows() { ProcessPackage rtp = (ProcessPackage) getResourceTypePackages().get(ResourceType.BPMN2); return rtp == null? Collections.emptyMap() : rtp.getRuleFlows(); }
java
@Override public void actionPerformed(ActionEvent event) { JMenuItem item = (JMenuItem) event.getSource(); if (item.isSelected()) { showColumn(item.getText()); } else { hideColumn(item.getText()); } }
python
def check_for_upload_create(self, relative_path=None): """Traverse the relative_path tree and check for files that need to be uploaded/created. Relativity here refers to the shared directory tree.""" for f in os.listdir( path_join( self.local_path, relative_path) if ...
python
def jpegtran(ext_args): """Create argument list for jpegtran.""" args = copy.copy(_JPEGTRAN_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] if Settings.jpegtran_prog: args += ["-progressive"] args += ['-outfile'] args += [e...
python
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp...