language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected boolean keysEqual(@NotNull Object queriedKey, @Nullable K keyInMap) { return queriedKey.equals(keyInMap); }
java
public static String readFromInputStreamIntoString(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuilder text = new StringBuilder(); String line; while( (line = reader.readLine()) != null) { ...
java
@Override @SuppressWarnings("squid:S3346") public ReconfigurationPlan buildReconfigurationPlan(Solution s, Model src) throws SchedulerException { ReconfigurationPlan plan = new DefaultReconfigurationPlan(src); for (NodeTransition action : nodeActions) { action.insertActions(s, plan);...
java
public Closeable onConnectionStateChange(final Consumer<BitfinexConnectionStateEnum> listener) { connectionStateConsumers.offer(listener); return () -> connectionStateConsumers.remove(listener); }
java
static Class<?> getElementTypeFromEnumSet(Object enumSet) { if (__elementTypeFromEnumSet == null) { throw new RuntimeException( "Could not access (reflection) the private " + "field *elementType* (enumClass) from: class java.util.Enum...
java
public Number getNumber(Object node, String expression) { return (Number) evalXPath(expression, node, XPathConstants.NUMBER); }
python
def _cls_lookup_dist(cls): """ Attempt to resolve the distribution from the provided class in the most naive way - this assumes the Python module path to the class contains the name of the package that provided the module and class. """ frags = cls.__module__.split('.') for name in ('.'.joi...
java
public static String dateToString(final Date date) { String result; if (date == null) { result = ""; } else { result = Z_DATE_FORMAT.format(date); } return result; }
java
public void goBack() { String action = "Going back one page"; String expected = "Previous page from browser history is loaded"; try { driver.navigate().back(); } catch (Exception e) { reporter.fail(action, expected, "Browser was unable to go back one page. " + e.g...
python
def _call(self, x, out=None): """Project ``x`` onto the subspace.""" if out is None: out = x[self.index].copy() else: out.assign(x[self.index]) return out
java
public final Transaction getTransaction() throws ObjectManagerException { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass , "getTransaction" ); // If the log is full introduce a ...
python
def log_level(level_string): """ Return a log level for a string >>> log_level('DEBUG') == logging.DEBUG True >>> log_level('30') == logging.WARNING True """ if level_string.isdigit(): return int(level_string) return getattr(logging, level_string.upper())
java
public static void dynamicCodeGenerate(OutputStream os, Class cls, Charset charset) throws IOException { dynamicCodeGenerate(os, cls, charset, getCodeGenerator(cls)); }
python
def getTotalDiscountedPrice(self): """Compute total discounted price """ price = self.getDiscountedPrice() vat = self.getVAT() price = price and price or 0 vat = vat and vat or 0 return float(price) + (float(price) * float(vat)) / 100
python
def get_subfolder_queries(store, label_store, folders, fid, sid): '''Returns [unicode]. This returns a list of queries that can be passed on to "other" search engines. The list of queries is derived from the subfolder identified by ``fid/sid``. ''' queries = [] for cid, subid, url, stype, ...
python
def worker_start(obj, queues, name, celery_args): """ Start a worker process. \b CELERY_ARGS: Additional Celery worker command line arguments. """ try: start_worker(queues=queues.split(','), config=obj['config'], name=name, cele...
python
def _create_layers(self, n_classes): """Create the layers of the model from self.layers. :param n_classes: number of classes :return: self """ next_layer_feed = tf.reshape(self.input_data, [-1, self.original_shape[0], ...
java
public static boolean isFunctionDeclaration(Node n) { // Note: There is currently one case where an unnamed function has a declaration parent. // `export default function() {...}` // In this case we consider the function to be an expression. return n.isFunction() && isDeclarationParent(n.getParent()) &&...
python
def use(self, middleware=None, path='/', method_mask=HTTPMethod.ALL): """ Use the middleware (a callable with parameters res, req, next) upon requests match the provided path. A None path matches every request. Returns the middleware so this method may be used as a decorator. ...
python
def array_from_pair_dictionary( pair_dict, array_fn, dtype="float32", square_result=False): """ Convert a dictionary whose keys are pairs (k1, k2) into a sparse or incomplete array. Parameters ---------- pair_dict : dict Dictionary from pairs of keys to v...
java
public static <T extends TOP> Collection<T> selectFromAllViews(JCas jCas, Class<T> type) { Collection<T> result = new ArrayList<T>(); try { Iterator<JCas> viewIterator = jCas.getViewIterator(); while (viewIterator.hasNext()) { JCas next = viewIterator.next();...
python
def _init_map(self): """stub""" MultiChoiceAnswerFormRecord._init_map(self) FilesAnswerFormRecord._init_map(self) FeedbackAnswerFormRecord._init_map(self) super(MultiChoiceFeedbackAndFilesAnswerFormRecord, self)._init_map()
java
public static String getSessionDirection(IoSessionEx session) { IoServiceEx service = session.getService(); String connectionDirection; if (service instanceof IoAcceptorEx || service instanceof AbstractBridgeAcceptor) { connectionDirection = ACCEPT_DIRECTION; } else if (serv...
java
@Override public void render() { if (false == HuluSetting.isDevMode) { Response.sendError(this.errorCode, this.errorContent); return; } if (null != e) { StaticLog.error(e); if (null == this.errorContent) { this.errorContent = StrUtil.EMPTY; } String stacktraceContent = Exceptio...
python
def get_instance(self): """Get the Streams instance that owns this view. Returns: Instance: Streams instance owning this view. """ return Instance(self.rest_client.make_request(self.instance), self.rest_client)
python
def repository_contributors(self, **kwargs): """Return a list of contributors for the project. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts wit...
python
def sort(m, reverse=False): """Return sorted m (default: ascending order)""" ty = type(m) if ty == matrix: m = list(m) m = sorted(m, reverse=reverse) if ty == matrix: m = matrix(m) return m
java
public void getValue(float[] valueDestination) { valueDestination = new float[size() * 2]; for (int i = 0; i < size(); i++) { SFVec2f sfVec2f = value.get(i); valueDestination[i*3] = sfVec2f.x; valueDestination[i*3 + 1] = sfVec2f.y; } }
java
public <P extends Stanza> P nextResultOrThrow() throws NoResponseException, XMPPErrorException, InterruptedException, NotConnectedException { return nextResultOrThrow(connection.getReplyTimeout()); }
java
public static void removeLegacySubscriptionOnParent(ExecutionEntity execution, EventSubscriptionEntity eventSubscription) { ActivityImpl activity = execution.getActivity(); if (activity == null) { return; } ActivityBehavior behavior = activity.getActivityBehavior(); ActivityBehavior parentBeh...
java
public Matrix3d rotation(AxisAngle4d axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); }
python
def packet(self): """Returns a string containing the packet's bytes No further parts should be added to the packet once this is done.""" if not self.finished: self.finished = 1 for question in self.questions: self.write_question(question) ...
python
def check(text): """Suggest the preferred forms.""" err = "hedging.misc" msg = "Hedging. Just say it." narcissism = [ "I would argue that", ", so to speak", "to a certain degree", ] return existence_check(text, narcissism, err, msg)
java
protected void checkText(PageElement pageElement, String textOrKey) throws TechnicalException, FailureException { WebElement webElement = null; String value = getTextOrKey(textOrKey); try { webElement = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLo...
python
def raises_gathered(error_type): '''For use in tests. Many tests expect a single error to be thrown, and want it to be of a specific type. This is a helper method for when that type is inside a gathered exception.''' container = RaisesGatheredContainer() try: yield container except Gathe...
java
public static boolean isAnnotationMirrorOfType(AnnotationMirror annotationMirror, String fqcn) { assert annotationMirror != null; assert fqcn != null; String annotationClassName = annotationMirror.getAnnotationType().toString(); return annotationClassName.equals( fqcn ); }
java
public static boolean intersectsLineSegment(Coordinate a, Coordinate b, Coordinate c, Coordinate d) { // check single-point segment: these never intersect if ((a.getX() == b.getX() && a.getY() == b.getY()) || (c.getX() == d.getX() && c.getY() == d.getY())) { return false; } double c1 = cross(a, c, a, b); d...
java
@Override public void concat(Path trg, Path[] psrcs) throws IOException { logger.atFine().log("GHFS.concat: %s, %s", trg, lazy(() -> Arrays.toString(psrcs))); checkArgument(psrcs.length > 0, "psrcs must have at least one source"); URI trgPath = getGcsPath(trg); List<URI> srcPaths = Arrays.stream(psr...
java
public SimulationBuilder phase(String phase) { phases.remove(phase); phases.add(phase); return this; }
java
public static boolean isValidDoubleBondConfiguration(IAtomContainer container, IBond bond) { //org.openscience.cdk.interfaces.IAtom[] atoms = bond.getAtoms(); List<IAtom> connectedAtoms = container.getConnectedAtomsList(bond.getBegin()); IAtom from = null; for (IAtom connectedAtom : conn...
java
public static <T> Set<T> asSet(T... items) { Set<T> set = new HashSet<T>(); for (T item : items) { set.add(item); } return set; }
python
def open(self, mode='rb'): """ Open the file for reading. :rtype: django.core.files.storage.File """ file = self.storage.open(self.relative_name, mode=mode) # type: File return file
python
def _load_config(self): """load configuration from config/""" logger.debug( 'Listing per-account config subdirectories in %s', self._conf_dir ) for acct_id in os.listdir(self._conf_dir): path = os.path.join(self._conf_dir, acct_id) # skip if not a dire...
python
def generate_pdfa( pdf_pages, output_file, compression, log, threads=1, pdf_version='1.5', pdfa_part='2', ): """Generate a PDF/A. The pdf_pages, a list files, will be merged into output_file. One or more PDF files may be merged. One of the files in this list must be a pdfmark ...
java
public static void writeJpg(Image image, ImageOutputStream destImageStream) throws IORuntimeException { write(image, IMAGE_TYPE_JPG, destImageStream); }
java
public URLNormalizer secureScheme() { Matcher m = PATTERN_SCHEMA.matcher(url); if (m.find()) { String schema = m.group(1); if ("http".equalsIgnoreCase(schema)) { url = m.replaceFirst(schema + "s$2"); } } return this; }
java
public boolean validateUser(String userName, String password, CmsRole requiredRole) { boolean result = false; try { CmsUser user = m_cms.readUser(userName, password); result = OpenCms.getRoleManager().hasRole(m_cms, user.getName(), requiredRole); } catch (CmsException e)...
python
def attempt(self, *kinds): """Try to get the next token if it matches one of the kinds given, otherwise returning None. If no kinds are given, any kind is accepted.""" if self._error: raise self._error token = self.next_token if not token: return N...
python
def validate_exported_interfaces(object_class, exported_intfs): # type: (List[str], List[str]) -> bool """ Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True...
python
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True): """dump vtkjs texture coordinates""" if root is None: root = {} tcoords = dataset.GetPointData().GetTCoords() if tcoords: dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress) root...
python
def create(self, _attributes=None, **attributes): """ Create a new instance of the related model. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attributes.update(_attributes) instance ...
python
def to_dictionary( self, key_selector=lambda item: item.key, value_selector=list): """Build a dictionary from the source sequence. Args: key_selector: A unary callable to extract a key from each item. By default the key of the Grouping. ...
java
public final static DateFormat getDateTimeInstance(int dateStyle, int timeStyle) { return get(dateStyle, timeStyle, ULocale.getDefault(Category.FORMAT), null); }
python
def delete(self): """ Delete all records matching the query. Warning: This is a desctructive operation. Not every model allows deletion of records and several models even restrict based on status. For example, deleting products that have been transacted is restricted. A...
java
public static void unregisterJSIncludeFromThisRequest (@Nonnull final IJSPathProvider aJSPathProvider) { final JSResourceSet aSet = _getPerRequestSet (false); if (aSet != null) aSet.removeItem (aJSPathProvider); }
java
public void pushMetric(final MetricsRecord mr) { lock.lock(); try { intervalHeartBeat(); try { mr.incrMetric(getName(), getPreviousIntervalValue()); } catch (Exception e) { LOG.info("pushMetric failed for " + getName() + "\n" + StringUtils.stringifyException(e)); ...
java
public static boolean check(String option) { if (table == null) return false; return (table.get(option.toLowerCase()) != null); }
java
private void upHeap(int idx) { Reference<E> e = entries.array[idx]; int iter = idx; while (hasParent(iter)) { int pidx = parent(iter); Reference<E> p = entries.array[pidx]; if (compare(e, p) < 0) { entries.array[pidx] = e; entr...
java
@Override protected boolean performDialogOperation() throws CmsException { // check if the current resource is a folder for single operation boolean isFolder = isOperationOnFolder(); // on folder copy display "please wait" screen, not for simple file copy if ((isMultiOperation() ||...
java
public static String encryptToBase64(String content) { byte[] val = content.getBytes(CHARSET); return DatatypeConverter.printBase64Binary(val); }
python
def npoints_towards(lon, lat, depth, azimuth, hdist, vdist, npoints): """ Find a list of specified number of points starting from a given one along a great circle arc with a given azimuth measured in a given point. :param float lon, lat, depth: Coordinates of a point to start from. The first po...
java
public static String compile( File lessFile, boolean compress ) throws IOException { String lessData = new String( Files.readAllBytes( lessFile.toPath() ), StandardCharsets.UTF_8 ); return Less.compile( lessFile.toURI().toURL(), lessData, compress, new ReaderFactory() ); }
java
public RaygunDuplicateErrorFilter create() { RaygunDuplicateErrorFilter filter = instance.get(); if (filter == null) { filter = new RaygunDuplicateErrorFilter(); instance.set(filter); return filter; } else { instance.remove(); return fi...
python
def send_login_signal(self, request, user, profile, client): """ Send a signal that a user logged in. This signal should be sent only if the user was *not* logged into Django. """ signals.login.send(sender=profile.__class__, user=user, profile=profile, client=client, ...
python
def on_connection_blocked(self, method_frame): """This method is called by pika if RabbitMQ sends a connection blocked method, to let us know we need to throttle our publishing. :param pika.amqp_object.Method method_frame: The blocked method frame """ LOGGER.warning('Connection...
python
def areaBetween(requestContext, *seriesLists): """ Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example belo...
python
async def addMachines(self, params=None): """ :param params dict: Dictionary specifying the machine to add. All keys are optional. Keys include: series: string specifying the machine OS series. constraints: string holding machine constraints, if any. We'...
python
def _actionsFreqsAngles(self,*args,**kwargs): """ NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,ar,ap,az) INPUT: Either: a) R,vR,vT,z,vz[,phi...
python
def GetFeedItems(client, feed): """Returns the Feed Items for a given Feed. Args: client: an AdWordsClient instance. feed: the Feed we are retrieving Feed Items from. Returns: The Feed Items associated with the given Feed. """ feed_item_service = client.GetService('FeedItemService', 'v201809') ...
python
def get_var(script_path, var): """ Given a script, and the name of an environment variable, returns the value of the environment variable. :param script_path: Path the a shell script :type script_path: str or unicode :param var: environment variable name :type var: str or unicode :return...
java
public String nextVASPTokenFollowing(String string) throws IOException { int index; String line; while (inputBuffer.ready()) { line = inputBuffer.readLine(); index = line.indexOf(string); if (index > 0) { index = index + string.length(); ...
java
public void clearAll() { for (int i = 0; i < textFields.size(); i++) { JTextField textField = textFields.get(i); if (textField == null) { continue; } textField.setText(""); } }
python
def content_transfer_encoding(self) \ -> Optional[ContentTransferEncodingHeader]: """The ``Content-Transfer-Encoding`` header.""" try: return cast(ContentTransferEncodingHeader, self[b'content-transfer-encoding'][0]) except (KeyError, IndexError): ...
java
public float get(int x, int y) { if (!isInBounds(x, y)) throw new ImageAccessException("Requested pixel is out of bounds: ( " + x + " , " + y + " )"); return unsafe_get(x,y); }
python
def killBatchJobs(self, jobIDs): """ Kills the given jobs, represented as Job ids, then checks they are dead by checking they are not in the list of issued jobs. """ self.killLocalJobs(jobIDs) jobIDs = set(jobIDs) logger.debug('Jobs to be killed: %r', jobIDs) ...
java
private static Long getPid(File pidFile) { FileReader reader = null; BufferedReader lineReader = null; String pidLine = null; try { reader = new FileReader(pidFile); lineReader = new BufferedReader(reader); pidLine = lineReader.readLine(); if(pidLine!=null) { ...
java
public InputHandler getInputHandler() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, "getInputHandler"); SibTr.exit(tc, "getInputHandler", inputHandler); } return inputHandler; }
java
public void start() { stop(); // Make sure any currently running dispatchers are stopped. // Create the cache dispatcher and start it. mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery); mCacheDispatcher.start(); // Create network dispatchers ...
python
def _calculate_filter(n, spacing, shift, fI, r_def, reim, name): r"""Calculate filter for this spacing, shift, n.""" # Base :: For this n/spacing/shift base = np.exp(spacing*(np.arange(n)-n//2) + shift) # r :: Start/end is defined by base AND r_def[0]/r_def[1] # Overdetermined system if r_def...
java
public @Nullable io.micronaut.inject.ast.Element visit( Element element, AnnotationMetadata annotationMetadata) { if (element instanceof VariableElement) { final JavaFieldElement e = new JavaFieldElement( (VariableElement) element, annotationMetada...
java
private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException { InputStream configStream = null; try { LoggingLogger.ROOT_LOGGER.debugf("Found logging c...
python
def create_historical_stream(directory, listener=None): """ Uses streaming listener/cache to parse betfair historical data: https://historicdata.betfair.com/#/home :param str directory: Directory of betfair data :param BaseListener listener: Listener object ...
java
public final EObject entryRuleDisjunction() throws RecognitionException { EObject current = null; EObject iv_ruleDisjunction = null; try { // InternalXtext.g:1758:52: (iv_ruleDisjunction= ruleDisjunction EOF ) // InternalXtext.g:1759:2: iv_ruleDisjunction= ruleDisjunct...
java
public static SelectColumn includes(String[] cols, String... columns) { return new SelectColumn(Utility.append(cols, columns), false); }
python
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
java
@PublicEvolving public void add_sink(SinkFunction<PyObject> sink_func) throws IOException { stream.addSink(new PythonSinkFunction(sink_func)); }
java
private static void checkTokenName(String namedOutput) { if (namedOutput == null || namedOutput.length() == 0) { throw new IllegalArgumentException( "Name cannot be NULL or emtpy"); } for (char ch : namedOutput.toCharArray()) { if ((ch >= 'A') && (ch <= 'Z')) { continue; } ...
python
def _convert_args(args): ''' Take a list of args, and convert any dicts inside the list to keyword args in the form of `key=value`, ready to be passed to salt-ssh ''' converted = [] for arg in args: if isinstance(arg, dict): for key in list(arg.keys()): if key...
java
@Override public void setCenter(final IGeoPoint point) { // If no layout, delay this call if (!mMapView.isLayoutOccurred()) { mReplayController.setCenter(point); return; } mMapView.setExpectedCenter(point); }
python
def parse(cls, root): """ Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap. """ if root.tag != utils.lxmlns("mets") + "mdRef": raise exceptions.ParseError( "MDRef can only parse mdRef elements with ME...
python
def replaceVariables(path, datetime=None, pathvars=None): """Return absolute path with path variables replaced as applicable""" if datetime is None: datetime = time.gmtime() # if path variables are not given, set as empty list if pathvars is None: pathvars = [ ] # create an init p...
java
public static void addPropertyInteger( CmsCmisTypeManager typeManager, PropertiesImpl props, String typeId, Set<String> filter, String id, long value) { addPropertyBigInteger(typeManager, props, typeId, filter, id, BigInteger.valueOf(value)); }
java
static String encodeUriComponent(String source, String encoding, Type type) throws UnsupportedEncodingException { if (source == null) { return null; } Assert.hasLength(encoding, "Encoding must not be empty"); byte[] bytes = encodeBytes(source.getBytes(encoding), type); return new String(bytes, "US-ASCII");...
java
private List<BitcoinTransactionInput> readListOfInputsFromTable(ListObjectInspector loi, Object listOfInputsObject) { int listLength=loi.getListLength(listOfInputsObject); List<BitcoinTransactionInput> result = new ArrayList<>(listLength); StructObjectInspector listOfInputsElementObjectInspector = (StructObjectInspecto...
python
def ticket_satisfaction_rating_create(self, ticket_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating" api_path = "/api/v2/tickets/{ticket_id}/satisfaction_rating.json" api_path = api_path.format(ticket_id=ticket_id) r...
java
public int getNrSelectedFeatures() { int count = 0; for (VectorLayer layer : getVectorLayers()) { count += layer.getSelectedFeatures().size(); } return count; }
java
@Deprecated public static int cuParamSetf(CUfunction hfunc, int offset, float value) { return checkResult(cuParamSetfNative(hfunc, offset, value)); }
java
public SimpleFeature convertDwgCircle( String typeName, String layerName, DwgCircle circle, int id ) { double[] center = circle.getCenter(); double radius = circle.getRadius(); Point2D[] ptos = GisModelCurveCalculator.calculateGisModelCircle(new Point2D.Double( center...
python
def _rfc822(date): """Parse RFC 822 dates and times http://tools.ietf.org/html/rfc822#section-5 There are some formatting differences that are accounted for: 1. Years may be two or four digits. 2. The month and day can be swapped. 3. Additional timezone names are supported. 4. A default tim...
java
public Observable<Page<DiagnosticCategoryInner>> listSiteDiagnosticCategoriesSlotNextAsync(final String nextPageLink) { return listSiteDiagnosticCategoriesSlotNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<DiagnosticCategoryInner>>, Page<DiagnosticCategoryInner>>() { ...