language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void setModellistByModel(ModelListForm listForm, PageIterator pageIterator, HttpServletRequest request) { Collection c = null; try { listForm.setAllCount(pageIterator.getAllCount()); if (pageIterator.getCount() != 0) listForm.setCount(pageIterator.getCount()); c = new ArrayList(pageIterat...
python
def merge_plugin_from_baseline(baseline_plugins, args): """ :type baseline_plugins: tuple of BasePlugin :param baseline_plugins: BasePlugin instances from baseline file :type args: dict :param args: diction of arguments parsed from usage param priority: input param > baseline param > default ...
python
def _should_replace(self, path): """ True if should replace the path """ return ( self._reserved_words is None or path.upper() in self._reserved_words or "-" in path )
python
def log_histogram(self, step, tag, val): ''' Write a histogram event. :param int step: Time step (x-axis in TensorBoard graphs) :param str tag: Label for this value :param numpy.ndarray val: Arbitrary-dimensional array containing values to be aggregated in the result...
java
public static void partByPart(InputStream _inputStream, String delimiter, Function<String, Object> function) { try (Scanner scanner = new Scanner(_inputStream);) { scanner.useDelimiter(delimiter); while (scanner.hasNext()) { String next = scanner.next(); f...
python
def event_tracker(func): """ Event tracking handler """ @wraps(func) async def wrapper(*args, **kwargs): """ Wraps function to provide redis tracking """ event = Event(args[0]) session = kwargs['session'] service_name = session.name awa...
python
def _model_params2table(self, fit_model, star_group_size): """ Place fitted parameters into an astropy table. Parameters ---------- fit_model : `astropy.modeling.Fittable2DModel` instance PSF or PRF model to fit the data. Could be one of the models in thi...
python
def AssignTasksToClient(self, client_id): """Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks. """ rules = data_store.REL_DB.ReadAllForemanRules() if not rules: ret...
python
def output_krdwrd(paragraphs, fp=sys.stdout): """ Outputs the paragraphs in a KrdWrd compatible format: class<TAB>first text node class<TAB>second text node ... where class is 1, 2 or 3 which means boilerplate, undecided or good respectively. Headings are output as undecided. """ ...
java
public static <T extends Comparable<T>> int checkCompare(T a, T b) { return a == null ? b == null ? 0 : -1 : b == null ? 1 : a.compareTo(b); }
python
def force_vertical_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given row.""" self.vertical_padding[index] = padding
java
@Override public StackTraceElement[] getStackTrace() { ArrayList<StackTraceElement> stackTrace = new ArrayList<>(); for (Throwable exception : exceptions) { stackTrace.addAll(Arrays.asList(exception.getStackTrace())); } return stackTrace.toArray(new Stac...
python
def length(self): """Total surveyed cave length, not including splays.""" return sum([shot.length for shot in self.shots if not shot.is_splay])
java
@Override protected void preparePaintComponent(final Request request) { if (!isInitialised()) { textArea.setText(EXAMPLE_TEXT); setInitialised(true); } }
python
def get_aux_files(basename): """ Look for and return all the aux files that are associated witht this filename. Will look for: background (_bkg.fits) rms (_rms.fits) mask (.mim) catalogue (_comp.fits) psf map (_psf.fits) will return filenames if they exist, or None ...
java
public static boolean removeAll( Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); }
python
def _empty_cache(self, termlist=None): """Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as ...
python
def tmpl_asciify(text): """ * synopsis: ``%asciify{text}`` * description: Translate non-ASCII characters to their ASCII \ equivalents. For example, “café” becomes “cafe”. Uses the mapping \ provided by the unidecode module. """ ger_umlaute = {'ae': u'ä', ...
python
def put(self, url, data=None): """Send a HTTP PUT request to a URL and return the result. """ self.conn.request("PUT", url, data) return self._process_response()
java
public static <E extends Exception> int importData(final DataSet dataset, final int offset, final int count, final Try.Predicate<? super Object[], E> filter, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Try.BiConsumer<? super PreparedStatem...
java
private static boolean suppressibleHydrogen(final IAtomContainer container, final IAtom atom) { // is the atom a hydrogen if (!"H".equals(atom.getSymbol())) return false; // is the hydrogen an ion? if (atom.getFormalCharge() != null && atom.getFormalCharge() != 0) return false; /...
java
public <T> Class<T> isAssignableFrom(final Class<?> superType, final Class<T> type) { if (!superType.isAssignableFrom(type)) { fail(String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(), superType.getName())); } return type; }
java
public void stop() { if (stopRequested) return; stopRequested = true; LOG.info("Stopping http server"); try { if (httpServer != null) httpServer.stop(); } catch (Exception e) { LOG.error(StringUtils.stringifyException(e)); } LOG.info("Stopping namesystem"); if(namesyst...
python
def chain(args): """ %prog chain bedfile Chain BED segments together. """ p = OptionParser(chain.__doc__) p.add_option("--dist", default=100000, help="Chaining distance") p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) be...
java
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSiz...
java
public Object invoke(final Object proxy, final Method method, final Object[] args) { final String methodName = method.getName(); if( methodName.startsWith(GET_PREFIX) ) { if( method.getParameterTypes().length > 0 ) { throw new IllegalArgumentException(String.format( "method %s.%s() should have...
java
public boolean isFilterMatch(BaseMessageHeader messageHeader) { boolean bMatch = super.isFilterMatch(messageHeader); if (bMatch) { if (!(messageHeader instanceof RecordMessageHeader)) return false; // Never RecordMessageHeader recMessageHeader = (Rec...
java
@Override public com.liferay.commerce.notification.model.CommerceNotificationTemplateUserSegmentRel updateCommerceNotificationTemplateUserSegmentRel( com.liferay.commerce.notification.model.CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel) { return _commerceNotificationTemplate...
python
def _cleanupConnections(senderkey, signal): """Delete any empty signals for senderkey. Delete senderkey if empty.""" try: receivers = connections[senderkey][signal] except: pass else: if not receivers: # No more connected receivers. Therefore, remove the signal. ...
java
public static Object evaluate(String attributeName, String expression, Class expectedType, Tag tag, PageContext pageContext) throws JspException { // delegate the ...
python
def filter_empty(values, default=None): """ Eliminates None or empty items from lists, tuples or sets passed in. If values is None or empty after filtering, the default is returned. """ if values is None: return default elif hasattr(values, '__len__') and len(values) == 0: retur...
java
public static String computeTimeAgoString(long ts, String suffix) { long now = System.currentTimeMillis(); checkArgument(ts <= now, "Cannot handle timestamp in the future" + ", now: " + now + "/" + new Date(now) + ", ts: " + ts + "/" + new Date(ts)); long diff ...
java
public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey, SigHash sigHash, boolean anyoneCanPay) { return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), signingKey, sigHash, anyoneCanPay); }
java
@Override public List<List<Token>> tokenize(final String[] sentences) { final long start = System.nanoTime(); int noTokens = 0; int prevIndex = 0; int curIndex = 0; final String language = this.lang; final List<List<Token>> result = new ArrayList<List<Token>>(); // TODO improve this fi...
java
public static int size(Object vdmCol) { // Covers sequences and sets if (vdmCol instanceof Collection) { Collection<?> setSeq = (Collection<?>) vdmCol; return setSeq.size(); } // Covers maps if (vdmCol instanceof VDMMap) { VDMMap map = (VDMMap) vdmCol; return map.size(); } throw new I...
python
def built_datetime(self): """Return the built time as a datetime object""" from datetime import datetime try: return datetime.fromtimestamp(self.state.build_done) except TypeError: # build_done is null return None
java
private static String getTypeDescription(ClassNode c, boolean end) { ClassNode d = c; if (ClassHelper.isPrimitiveType(d.redirect())) { d = d.redirect(); } String desc = TypeUtil.getDescriptionByType(d); if (!end && desc.endsWith(";")) { desc = desc.subst...
python
def get_window_size(self, windowHandle='current'): """ Gets the width and height of the current window. :Usage: :: driver.get_window_size() """ command = Command.GET_WINDOW_SIZE if self.w3c: if windowHandle != 'current': ...
java
public static <T> ThriftCompletableFuture<T> successfulCompletedFuture(T value) { final ThriftCompletableFuture<T> future = new ThriftCompletableFuture<>(); future.onComplete(value); return future; }
python
def _upgrade_db(self): """upgrade db using scripts for specified (current) schema version""" migration_path = "_data/migrations" sqlite3.connect(self._db_path).close() # ensure that it exists db_url = "sqlite:///" + self._db_path backend = yoyo.get_backend(db_url) migr...
java
@Override public void accept(Set<String> propertyNames) { if (!isClosed()) { synchronized (this) { for (Map.Entry<PropertyChangeListener, String> entry : listeners.entrySet()) { String propertyName = entry.getValue(); if (propertyNames.cont...
java
public Class<?> findClass(String className) { Class<?> result = null; // look in hash map result = (Class<?>) classes.get(className); if (result != null) { return result; } try { return findSystemClass(className); } catch (Exception e) { Debugger.printWarn(e); } ...
python
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ shutit_global.shutit_global_object.yield_to_draw() if command in ('md5sum','sed','head'): if self.get_current_shutit_pexpect_session_environment().distr...
python
def set_user(self, user): """ Writes user data to session. Args: user: User object """ self.session['user_id'] = user.key self.session['user_data'] = user.clean_value() role = self.get_role() # TODO: this should be remembered from previous lo...
python
def buy_close_order_quantity(self): """ [int] 买方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.BUY and order.position_effect in [POSITION_EFFECT.CLOSE, POSITION_EFFECT.CLOSE_TODAY])
java
public <R> ConnectedStreams<T, R> connect(DataStream<R> dataStream) { return new ConnectedStreams<>(environment, this, dataStream); }
java
public int compareTo(Version v) { if (this == v) return 0; int diff = major - v.major; if (diff != 0) return diff; diff = minor - v.minor; if (diff != 0) return diff; diff = micro - v.micro; if (diff != 0) return dif...
python
def _pastoref16(ins): ''' Stores 2º operand content into address of 1st operand. storef16 a, x => *(&a) = x ''' output = _paddr(ins.quad[1]) value = ins.quad[2] if value[0] == '*': value = value[1:] indirect = True else: indirect = False try: if indirec...
java
private static boolean envelopeContainsEnvelope_(Envelope2D env_a, Envelope2D env_b, double tolerance, ProgressTracker progress_tracker) { if (!envelopeInfContainsEnvelope_(env_a, env_b, tolerance)) return false; if (env_a.getHeight() <= tolerance && env_a.getWidth() <= tolerance) { Point2D pt_a = env_a.g...
java
@Procedure @Description("apoc.couchbase.upsert(hostOrKey, bucket, documentId, jsonDocument) yield id, expiry, cas, mutationToken, content - insert or overwrite a couchbase json document with its unique ID.") public Stream<CouchbaseJsonDocument> upsert(@Name("hostOrKey") String hostOrKey, @Name("bucket") String ...
java
private <E> E fetch(Class<E> entityClass, Key nativeKey) { try { Entity nativeEntity = nativeReader.get(nativeKey); E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); entityManager.executeEntityListeners(CallbackType.POST_LOAD, entity); return entity; } catch (DatastoreExcepti...
java
@GET @Path("/uniqueAttribute/type/{typeName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasEntityWithExtInfo getByUniqueAttributes(@PathParam("typeName") String typeName, @Context HttpServletRequest servletRe...
python
def get_payment_transaction_by_id(cls, payment_transaction_id, **kwargs): """Find PaymentTransaction Return single instance of PaymentTransaction by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> ...
python
def poll(self): """Poll attached subprocess until it is available""" if self._subprocess is not None: self._subprocess.poll() time.sleep(self._beaver_config.get('subprocess_poll_sleep'))
java
public static int dayOfWeek(){ setTime(); int dayofweek = cal.get(Calendar.DAY_OF_WEEK) - 1; if (dayofweek == 0) { dayofweek = 7; } return dayofweek; }
python
def deallocate(self, nodes): # TODO: check docstring """Deallocates all nodes from `nodes` list from this route Parameters ---------- nodes : type Desc """ nodes_demand = 0 for node in nodes: self._nodes.remove(node) ...
java
public List<String> replaceRunOnWords(final String original) { final List<String> candidates = new ArrayList<String>(); String wordToCheck = original; if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { wordToCheck = DictionaryLookup.applyReplacements(original, dictionaryMetadata.getInp...
java
public static void deleteFilePath(FilePath workspace, String path) throws IOException { if (StringUtils.isNotBlank(path)) { try { FilePath propertiesFile = new FilePath(workspace, path); propertiesFile.delete(); } catch (Exception e) { thro...
python
def searchNs(self, doc, nameSpace): """Search a Ns registered under a given name space for a document. recurse on the parents until it finds the defined namespace or return None otherwise. @nameSpace can be None, this is a search for the default namespace. We don't allow ...
python
def _huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta))
python
def move_user_data(primary, secondary): ''' Moves all submissions and other data linked to the secondary user into the primary user. Nothing is deleted here, we just modify foreign user keys. ''' # Update all submission authorships of the secondary to the primary submissions = Submission...
python
def visit_starred(self, node, parent): """visit a Starred node and return a new instance of it""" context = self._get_context(node) newnode = nodes.Starred( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit(self.visit(node.v...
java
@Override public void outputText(SDocumentGraph graph, boolean alignmc, int matchNumber, Writer out) throws IOException, IllegalArgumentException { // first match if (matchNumber == 0) { // output header List<String> headerLine = new ArrayList<>(); for(Map.Entry<Integer, TreeSet<S...
java
public static StormTopology buildVehiclesTopology() { Fields driverField = new Fields(Driver.FIELD_NAME); Fields vehicleField = new Fields(Vehicle.FIELD_NAME); Fields allFields = new Fields(Vehicle.FIELD_NAME, Driver.FIELD_NAME); FixedBatchSpout spout = new FixedBatchSpout(allFi...
java
public void clickOnRadioButton(int index) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "clickOnRadioButton("+index+")"); } clicker.clickOn(RadioButton.class, index); }
python
def _dict_raise_on_duplicates(ordered_pairs): """ Reject duplicate keys. """ d = {} for k, v in ordered_pairs: if k in d: raise ValueError("duplicate key: %r" % (k,)) else: d[k] = v return d
java
public void setValuesToRemove(java.util.Collection<String> valuesToRemove) { if (valuesToRemove == null) { this.valuesToRemove = null; return; } this.valuesToRemove = new java.util.ArrayList<String>(valuesToRemove); }
python
def get_url(self, datatype, verb, urltype, params={}, api_host=None, api_version=None): """Returns a fully formed url :param datatype: a string identifying the data the url will access. :param verb: the HTTP verb needed for use with the url. :param urltype: an adjective used to the natu...
python
def accepts_port(self, port): """ Query whether this Router will accept the given port. """ if self.rejected_ports is None and self.accepted_ports is None: raise RuntimeError("policy hasn't been set yet") if self.rejected_ports: for x in self.rejected_po...
java
@LogExecTime public void verifyTextPresent(String text, String msg) { jtCore.verifyTextPresent(text, msg); }
python
def _lookup_host_mappings(query_type, session=None, **bfilter): """Look up 'query_type' Nexus mappings matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param bfilter: filter for mappings query :returns: mappings if query gave a result, else ra...
python
def _report_container_state_metrics(self, pod_list, instance_tags): """Reports container state & reasons by looking at container statuses""" if pod_list.get('expired_count'): self.gauge(self.NAMESPACE + '.pods.expired', pod_list.get('expired_count'), tags=instance_tags) for pod in p...
java
public static List<String> getOtherChildren(CodeSystem cs, ConceptDefinitionComponent c) { List<String> res = new ArrayList<String>(); for (ConceptPropertyComponent p : c.getProperty()) { if ("parent".equals(p.getCode())) { res.add(p.getValue().primitiveValue()); } } return re...
java
public Observable<ServiceResponse<DomainControlCenterSsoRequestInner>> getControlCenterSsoRequestWithServiceResponseAsync() { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if...
java
@Bean @Conditional(BackwardsCompatibilityCondition.class) @Deprecated Reporter<Span> reporter(ReporterMetrics reporterMetrics, ZipkinProperties zipkin, BytesEncoder<Span> spanBytesEncoder, DefaultListableBeanFactory beanFactory) { List<String> beanNames = new ArrayList<>( Arrays.asList(beanFactory.getBeanNa...
java
public int getIfdImagesCount() { int c = 0; if (metadata.contains("IFD")) { List<TiffObject> l = getMetadataList("IFD"); int n = 0; for (TiffObject to : l) { if (to instanceof IFD) { IFD ifd = (IFD) to; if (ifd.isImage()) n++; } } c =...
python
def highlight(self, *args): """ Highlights the region with a colored frame. Accepts the following parameters: highlight([toEnable], [seconds], [color]) * toEnable (boolean): Enables or disables the overlay * seconds (number): Seconds to show overlay * color (string): He...
java
static public double sphere_noise(double[] x) { double sum = 0.0; for (int i = 0; i < x.length; i++) { sum += x[i] * x[i]; } // NOISE // Comment the next line to remove the noise sum *= (1.0 + 0.1 * Math.abs(random.nextGaussian())); return (sum); }
python
def read_safe(self, size=None): """ We currently close our fbs files by killing them, so sometimes they end up with bad data at the end. Close our reader if we expect `size` bytes and get fewer. This is a hack and should be removed when we cleanly close our connections i...
python
def get_rendered_object(self, obj=None): """Render object""" obj = obj if obj else self.object return [ { **field, 'value': self.render_field(field, obj) } for field in self.get_fields() ]
python
def set(self, person, properties=None, timestamp=None, path=KISSmetrics.SET_PATH): """Set a property (or properties) for a `person`. :param person: individual to associate properties with :param properties: key-value pairs to associate with `person` :type properties: dict ...
java
@Override public Map<String, Object> readJson(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("Reader must not be null"); } String json = readerToString(reader); try { Object jsonObjOrArray = getJsonObjectManager()...
java
public long getDispatchTime(TaskAttemptID taskid){ Long l = dispatchTimeMap.get(taskid); if (l != null) { return l.longValue(); } return 0; }
java
private static Matrix readDenseSVDLIBCtext(File matrix, Type matrixType, boolean transposeOnRead) throws IOException { BufferedReader br = new BufferedReader(new FileReader(matrix)); // Note that according to the formatting, spaces and new lin...
python
def write_compounds(self, stream, compounds, properties=None): """Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds: Iterable of compound entries. properties: Set of compound properties to output (or None to output ...
java
public static String join(Iterator<? extends EncodedPair> pairs, char pairSep){ return join(pairs, pairSep, '=', false, false); }
python
def accept(self, visitor): """Visit this node using the given visitor.""" func = getattr(visitor, "visit_" + self.__class__.__name__.lower()) return func(self)
python
def lifetimes(self, dates, include_start_date, country_codes): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_da...
java
public StatusData<ApacheMetrics> parse(String status) { if (StringUtils.isEmpty(status)) throw new IllegalArgumentException("Empty status to parse!"); final StatusData<ApacheMetrics> result = new StatusData<>(); String[] lines = StringUtils.tokenize(status, '\n'); //extract ...
java
public static Collection<byte[]> getKeyBytes(Collection<String> keys) { Collection<byte[]> rv=new ArrayList<byte[]>(keys.size()); for(String s : keys) { rv.add(getKeyBytes(s)); } return rv; }
java
private static String readIO(HttpURLConnection httpUrlConn) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), Constant.DEFAULT_CHARSET)); String line; ...
python
def color(self): """ Returns the color image. """ return ColorImage(self.raw_data[:, :, :3].astype( np.uint8), frame=self.frame)
java
private boolean calculateGraph() { // cache size of lists int list1size = list1.size(); int list2size = list2.size(); // this stores the order number for each Node HashMap<INode, Integer> orderNum1 = new HashMap<INode, Integer>(); HashMap<INode, Integer> orderNum2...
python
def user_saw_task(self, username, courseid, taskid): """ Set in the database that the user has viewed this task """ self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid"...
java
private ParameterizationFunction project(double[][] basis, ParameterizationFunction f) { // Matrix m = new Matrix(new // double[][]{f.getPointCoordinates()}).times(basis); double[] m = transposeTimes(basis, f.getColumnVector()); return new ParameterizationFunction(DoubleVector.wrap(m)); }
java
private void showExplanation() { Snackbar.make(findSuitableView(), getString(R.string.activity_gallery_permission_request_explanation), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.activity_gallery_permission_request_settings, new View.OnClickListener() { @Override ...
java
public static Matcher<Date> hasHour(final int hour, final ClockPeriod clockPeriod) { return new IsDateWithTime(hour, clockPeriod, null, null, null); }
python
def validate_user_name(self, user_name, timeout=-1): """ Verifies if a userName is already in use. Args: user_name: The userName to be verified. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort t...
python
def get_found_locations(): """ INFO:__main__:found HELP in 1572 INFO:__main__:found MATHS in 1704 INFO:__main__:found ROCKS in 1975 #random.seed(1572) #garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)]) #wrd_location = garbage.find('HELP') #print(wrd_location) # 7383...
python
def profile_update_args_v2(self, profile): """Update v1 profile args to v2 schema for args. .. code-block:: javascript "args": { "app": { "input_strings": "capitalize", "tc_action": "Capitalize" } }, ...