language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public QueryBuilder toCommitId(CommitId commitId) { Validate.argumentIsNotNull(commitId); queryParamsBuilder.toCommitId(commitId); return this; }
java
public static final double bytesToDouble( byte[] data, int[] offset ) { long bits = bytesToLong(data, offset); return Double.longBitsToDouble(bits); }
java
public boolean containsRow(Map<String, String> row) { for (CsvRow csvRow : data) { if (csvRow.contains(row)) { return true; } } return false; }
java
public static Configuration load(String file) throws IOException, SAXException { ConfigurationImpl cfg = new ConfigurationImpl(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new ConfigHandler(cfg, file)); if (file.startsWith("classpath:")) { String resource...
java
public JsonArray getSymbols() { if (this.type.equals(ENUM)) { return getDataType().get(ENUM_SYMBOLS_KEY).getAsJsonArray(); } return new JsonArray(); }
java
private void addPostParams(final Request request) { if (hostedNumberOrderSids != null) { for (String prop : hostedNumberOrderSids) { request.addPostParam("HostedNumberOrderSids", prop); } } if (addressSid != null) { request.addPostParam("Addre...
java
@Nullable public synchronized V put(K key, V value) { // We do remove and insert instead of just replace, in order to cause a structural change // to the map, as we always want the latest inserted element to be last in the queue. V oldValue = mMap.remove(key); mSizeInBytes -= getValueSizeInBytes(oldVa...
java
public Float getAsFloat(String key) { Object value = mValues.get(key); try { return value != null ? ((Number) value).floatValue() : null; } catch (ClassCastException e) { if (value instanceof CharSequence) { try { return Float.valueOf(v...
java
public InjectionBinding<A> createInjectionBinding(A annotation, Class<?> instanceClass, Member member) throws InjectionException { return new InjectionSimpleBinding<A>(annotation, ivNameSpaceConfig); // F50309.3 }
python
def getABCD(slh, a0=None, doubled_up=True): """Calculate the ABCD-linearization of an SLH model Return the A, B, C, D and (a, c) matrices that linearize an SLH model about a coherent displacement amplitude a0. The equations of motion and the input-output relation are then: dX = (A X + a) dt + B d...
python
def login(self, **kwargs): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.login` with two enhancements: * additional logging; * login parameters can be passed through ``kwargs``, or set as default using the following ``env`` variables: * ``env.doc...
python
def assignFont(self): """ Assigns the font family and point size settings from the font picker widget. """ font = self.currentFont() font.setFamily(self._fontPickerWidget.currentFamily()) font.setPointSize(self._fontPickerWidget.pointSize()) self.s...
java
public void fill(final double[][] data, final int startRow, final int startCol) { final int rows = data.length; final int cols = data[0].length; verifyTrue(startRow < rows && startRow < getRowCount(), "illegal startRow: %s", startRow); verifyTrue(startCol < cols && startCol < getColumnCount(), "illegal st...
python
def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done m...
java
protected void createAndAddEventHandlers(PlayerSession playerSession) { // Create a network event listener for the player session. EventHandler networkEventHandler = new NetworkEventListener(playerSession); // Add the handler to the game room's EventDispatcher so that it will // pass game room network events t...
java
private int parseDateFormatStyle(String text, int defaultStyle) { if (text == null) { return defaultStyle; } if (SHORT_STYLE.equalsIgnoreCase(text)) { return DateFormat.SHORT; } else if (MEDIUM_STYLE.equalsIgnoreCase(text)) { ...
python
def reduction(input_type, output_type): """Define a user-defined reduction function that takes N pandas Series or scalar values as inputs and produces one row of output. Parameters ---------- input_type : List[ibis.expr.datatypes.DataType] A list of the types found i...
java
public void login() { // first, let's see if we're running in a hadoop cluster and have the env configured boolean isHadoopCluster = isHadoopCluster(); Configuration hadoopConfig = isHadoopCluster ? getHadoopConfiguration() : new Configuration(false); org.apache.commons.configuration.Con...
java
public String getDescriptorName() { // // The javadocs for java.beans.EventSetDescriptor suggest that the programmatic name // should start w/ a lowercase letter. So we use the unqualified event set interface // name w/ the first character lowercased. // String name...
python
def atlas_peer_table_lock(): """ Lock the global health info table. Return the table. """ global PEER_TABLE_LOCK, PEER_TABLE, PEER_TABLE_LOCK_HOLDER, PEER_TABLE_LOCK_TRACEBACK if PEER_TABLE_LOCK_HOLDER is not None: assert PEER_TABLE_LOCK_HOLDER != threading.current_thread(), "DEADLOCK" ...
python
def parse_type(cls, type_string): """Parse KATCP formatted type code into Sensor type constant. Parameters ---------- type_string : str KATCP formatted type code. Returns ------- sensor_type : Sensor type constant The corresponding Sensor...
python
def generate_from_args(self, *args): """Generates a waveform, applies a time shift and the detector response function from the given args. The args are assumed to be in the same order as the variable args. """ return self.generate(**dict(zip(self.variable_args, args)))
java
public void addWatchDirectory(File dir, String extension) { extension = removeStartingDotIfPresent(extension); List<String> fileExtensions = new ArrayList<String>(); if (extension != null && extension.length() > 0) { int i = extension.lastIndexOf('.'); if(i > -1) { ...
java
@PluginFactory public static PaxOsgiAppender createAppender( // @formatter:off @PluginAttribute("name") final String name, @PluginAttribute("filter") final String filter, @PluginConfiguration final Configuration config) { // @formatter:on if (name...
python
def _set_id(infos): ''' ID compatibility hack return: dict ''' if infos: cid = None if infos.get("Id"): cid = infos["Id"] elif infos.get("ID"): cid = infos["ID"] elif infos.get("id"): cid = infos["id"] if "Id" not in infos: infos["Id"] = cid ...
java
public SubscribeForm getSubscriptionOptions(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { PubSub packet = sendPubsubPacket(createPubsubPacket(Type.get, new OptionsExtension(jid, getId(), subscriptionId))); FormNode ext = ...
java
public static boolean isAlpha(final String cs) { if (Strings.isNullOrEmpty(cs)) { return false; } final int sz = cs.length(); for (int i = 0; i < sz; i++) { if (!Character.isLetter(cs.charAt(i))) { return false; } } retu...
python
def on_failure(self, exc, task_id, args, kwargs, einfo): """ If the task fails, persist a record of the task. """ if not FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).exists(): FailedTask.objects.create( task_name=_truncate_to_field(Failed...
java
public static void removeEqualRows(DenseMatrix64F matrix) { int rows = matrix.numRows; if (rows < 2) { return; } double[] d = matrix.data; int cols = matrix.numCols; int left = rows-1; int delta = 0; for (int i=0;i<left;i...
python
def is_list_like(obj, allow_sets=True): """ Check if the object is list-like. Objects that are considered list-like are for example Python lists, tuples, sets, NumPy arrays, and Pandas Series. Strings and datetime objects, however, are not considered list-like. Parameters ---------- o...
java
public ApiResponse<UserEnvelope> getSelfWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = getSelfValidateBeforeCall(null, null); Type localVarReturnType = new TypeToken<UserEnvelope>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
python
def encode(self, message): '''Encode a message when publishing.''' if not isinstance(message, dict): message = {'message': message} message['time'] = time.time() return json.dumps(message)
python
def purge(self): """ Purge the stream. This removes all data and clears the calculated intervals :return: None """ self.channel.purge_stream(self.stream_id, remove_definition=False, sandbox=None)
java
public static ClassLoader getClassLoader(Class clazz){ ClassLoader classLoader = clazz.getClassLoader(); return classLoader==null ? ClassLoader.getSystemClassLoader() : classLoader; }
java
public static PasswordPolicyDto fromPasswordPolicy(PasswordPolicy policy) { PasswordPolicyDto policyDto = new PasswordPolicyDto(); for (PasswordPolicyRule rule : policy.getRules()) { policyDto.rules.add(new PasswordPolicyRuleDto(rule)); } return policyDto; }
python
def resize_preview(self, dw, dh): "Resizes preview that is currently dragged" # identify preview if self._objects_moving: id_ = self._objects_moving[0] tags = self.canvas.gettags(id_) for tag in tags: if tag.startswith('preview_'): ...
python
def is_static(self, filename): """Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check ...
python
def hgetall(self, key, *, encoding=_NOTSET): """Get all the fields and values in a hash.""" fut = self.execute(b'HGETALL', key, encoding=encoding) return wait_make_dict(fut)
python
def integer_byte_size(n): '''Returns the number of bytes necessary to store the integer n.''' quanta, mod = divmod(integer_bit_size(n), 8) if mod or n == 0: quanta += 1 return quanta
python
def run(self): """Run the App using the current profile. The current profile has the install_json and args pre-loaded. """ install_json = self.profile.get('install_json') program_language = self.profile.get('install_json').get('programLanguage', 'python').lower() print(...
python
def quit(self): '''Set quit signal''' self._quit = True # stop xmlrpc server if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop)
java
public void marshall(HostVolumeProperties hostVolumeProperties, ProtocolMarshaller protocolMarshaller) { if (hostVolumeProperties == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(hostVolumePropertie...
python
def notify_exception(self, exception, run_done_callbacks=True): ''' set the exception message, stop transfer if running and set the done event ''' logger.error("%s : %s" % (exception.__class__.__name__, str(exception))) self._exception = exception if self.is_running(True): # ...
python
def absl_to_standard(level): """Converts an integer level from the absl value to the standard value. Args: level: int, an absl.logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in standard logging. """ if not isinstance(lev...
python
def read (self): """Reads a single packet from the this pcap stream, returning a tuple (PCapPacketHeader, packet) """ header = PCapPacketHeader(self._stream, self.header._swap) packet = None if not header.incomplete(): packet = self._stream.read(header.incl_l...
python
def is_encodable(self, typ: TypeStr, arg: Any) -> bool: """ Determines if the python value ``arg`` is encodable as a value of the ABI type ``typ``. :param typ: A string representation for the ABI type against which the python value ``arg`` will be checked e.g. ``'uint256'``,...
python
def check_inputs(self): """ Check for the existence of input files """ self.inputs = self.expand_filenames(self.inputs) result = False if len(self.inputs) == 0 or self.files_exist(self.inputs): result = True else: print("Not executing task. Input file(s) d...
java
private void parseEntityRef(boolean externalAllowed) throws SAXException, IOException { String name; name = readNmtoken(true); require(';'); switch (getEntityType(name)) { case ENTITY_UNDECLARED: // NOTE: XML REC describes amazingly convoluted han...
java
public void validate() throws InvalidPropertyException { final String methodName = "validate"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } final List<String> failedPropsMessages = new ArrayList<String>(); ...
java
public static Function<Iterable<?>, String> joinFunction(final Joiner joiner) { return new Function<Iterable<?>, String>() { @Override public String apply(final Iterable<?> list) { return joiner.join(list); } }; }
python
def collides(self, other): """Returns collision with axis aligned rect""" angle = self.angle width = self.width height = self.height if angle == 0: return other.collides(Rect(-0.5 * width, -0.5 * height, width, height)) ...
python
def generate_key(filtered_args): """Get a key from some input. This function should be used whenever a key is needed, to keep keys consistent. """ # Convert the value to a (potentially singleton) tuple to be consistent # with joblib.filtered_args. if isinstance(filtered_args, Iterable): ...
python
def stop(self): """Ask politely, first, with SIGINT and SIGQUIT.""" if hasattr(self, 'process'): if self.process is not None: try: is_running = self.process.poll() is None except AttributeError: is_running = False ...
java
public static String readString(ChannelBuffer buffer, int length, Charset charset) { String str = null; if (null == charset) { charset = CharsetUtil.UTF_8; } try { ChannelBuffer stringBuffer = buffer.readSlice(length); str = stringBuffer.toString(charset); } catch (Exception e) { throw...
java
public static <R> Observable<R> fromRunnable(final Runnable run, final R result, Scheduler scheduler) { return Observable.create(OperatorFromFunctionals.fromRunnable(run, result)).subscribeOn(scheduler); }
python
def prompt_terminal(path): """Prompt for a new filename via terminal.""" def rlinput(prompt_msg, prefill=''): """ One line is read from standard input. Display `prompt_msg` on standard error. `prefill` is placed into the editing buffer before editing begins. """ ...
java
public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api, final String externalAppUserId, final String... fields) { return getUsersInfoForType(api, null, null, externalAppUserId, fields); }
python
def list_users_in_course_users(self, course_id, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, search_term=None, user_id=None, user_ids=None): """ List users in course. Returns the list of users in this course. And optionally the us...
python
def GetNearestStops(self, lat, lon, n=1): """Return the n nearest stops to lat,lon""" dist_stop_list = [] for s in self.stops.values(): # TODO: Use util.ApproximateDistanceBetweenStops? dist = (s.stop_lat - lat)**2 + (s.stop_lon - lon)**2 if len(dist_stop_list) < n: bisect.insort(d...
java
private Link annotationToLink(Siren4JLink linkAnno, EntityContext context) { LinkBuilder builder = LinkBuilder.newInstance().setRelationship(linkAnno.rel()).setHref(linkAnno.href()); if (StringUtils.isNotBlank(linkAnno.title())) { builder.setTitle(linkAnno.title()); } if...
java
public static Status valueOf(int code) { Status result = null; switch (code) { case 100: result = INFO_CONTINUE; break; case 101: result = INFO_SWITCHING_PROTOCOL; break; case 102: result...
java
public static CommerceOrder[] findByShippingAddressId_PrevAndNext( long commerceOrderId, long shippingAddressId, OrderByComparator<CommerceOrder> orderByComparator) throws com.liferay.commerce.exception.NoSuchOrderException { return getPersistence() .findByShippingAddressId_PrevAndNext(commerceOrderId, ...
python
def freqpoly_plot(data): """make freqpoly plot of merged read lengths""" rel_data = OrderedDict() for key, val in data.items(): tot = sum(val.values(), 0) rel_data[key] = {k: v / tot for k, v in val.items()} fplotconfig = { 'data_labels': [ ...
java
public List<TopicRelationship> getLinkListTopicRelationships() { final ArrayList<TopicRelationship> relationships = new ArrayList<TopicRelationship>(); for (final TopicRelationship relationship : topicRelationships) { if (relationship.getType() == RelationshipType.LINKLIST) { ...
python
def close(self): """ Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client obj...
java
public static PersistentDependency createDepend(PathImpl backing) { Jar jar = create(backing); return jar.getDepend(); }
java
public final <T1 extends SourceFile, T2 extends SourceFile> void init( List<T1> externs, List<T2> sources, CompilerOptions options) { JSModule module = new JSModule(JSModule.STRONG_MODULE_NAME); for (SourceFile source : sources) { module.add(new CompilerInput(source)); } List<JSModule> modu...
java
protected IDbgpProperty parsePropertyResponse(Element response) throws DbgpException { // TODO: check length!!! NodeList properties = response.getElementsByTagName(DbgpXmlEntityParser.TAG_PROPERTY); return DbgpXmlEntityParser.parseProperty((Element) properties.item(0)); }
java
public YearMonth withChronologyRetainFields(Chronology newChronology) { newChronology = DateTimeUtils.getChronology(newChronology); newChronology = newChronology.withUTC(); if (newChronology == getChronology()) { return this; } else { YearMonth newYearMonth = new ...
java
private Object parentValue(Object pojo) { Object parentValue = parent.getValue(pojo); if (parentValue == null && autoCreateParent) { Object newParent = ReflectionUtils.newInstance(parent.getType().getRawType()); parent.setValue(pojo, newParent); return newParent; ...
python
def verify(self, sig, msg): ''' sig-->bytes msg-->str or bytes Returns-->boolean ''' return lib.ed25519_VerifySignature( sig, self.__verifyingkey, msg, len(msg)) == 1
python
def check_dependencies(): """Make sure virtualenv is in the path.""" print 'Checking dependencies...' if not HAS_VIRTUALENV: print 'Virtual environment not found.' # Try installing it via easy_install... if HAS_EASY_INSTALL: print 'Installing virtualenv via easy_install....
python
def printfile(aFileName): """ Print a mission file to demonstrate "round trip" """ print("\nMission file: %s" % aFileName) with open(aFileName) as f: for line in f: print(' %s' % line.strip())
java
public synchronized float get() { Progress node = this; while (node.parent != null) { // find the root node = parent; } return node.getInternal(); }
java
public Stream<Commit> getCommitsStream(Object projectIdOrPath, int mergeRequestIid) throws GitLabApiException { return (getCommits(projectIdOrPath, mergeRequestIid, getDefaultPerPage()).stream()); }
java
protected boolean evaluateExtracted(Object o) { String sWords = (String) o; String sFilter = getFilterString(); boolean matches = false; if (sWords != null && !sWords.isEmpty() && sFilter != null && !sFilter.isEmpty()) { String[] arrWords = sWord...
python
def plot(self, style='heatmap', legend=False, cmap=None, ax=None): """ Presents the AstonFrame using matplotlib. Parameters ---------- style : {'heatmap', 'colors', ''} legend : bool, optional cmap: matplotlib.colors.Colormap, optional ax : matplotlib.axe...
java
public boolean remove(String attribute, String value) { NameOpValue nv = rslTree.getParam(attribute); if (nv == null || nv.getOperator() != NameOpValue.EQ) return false; return nv.remove(new Value(value)); }
java
@Override protected void checkIntegrity () throws InternetSCSIException { String exceptionMessage; do { if (statusFlag && !protocolDataUnit.getBasicHeaderSegment().isFinalFlag()) { exceptionMessage = "FinalFlag must also be set, if the StatusFlag is set."; ...
java
protected GraphQLFieldDefinition getFieldDef(ExecutionContext executionContext, ExecutionStrategyParameters parameters, Field field) { GraphQLObjectType parentType = (GraphQLObjectType) parameters.getExecutionStepInfo().getUnwrappedNonNullType(); return getFieldDef(executionContext.getGraphQLSchema(), p...
java
public void marshall(BatchListObjectAttributes batchListObjectAttributes, ProtocolMarshaller protocolMarshaller) { if (batchListObjectAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batc...
java
@SuppressWarnings("unchecked") public static <T> T invokeClosure(Closure<T> closure, Object... args) { try { return closure.call(args); } catch (InvokerInvocationException e) { ExceptionUtil.sneakyThrow(e.getCause()); return null; // never reached } }
java
public static void addUniform(GrayS32 input, Random rand , int min , int max) { int range = max-min; int[] data = input.data; for (int y = 0; y < input.height; y++) { int index = input.getStartIndex() + y * input.getStride(); for (int x = 0; x < input.width; x++) { int value = (data[index] ) + rand.ne...
python
def rule_operation(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") index_key.text = kwargs.pop('index') operation = ET...
python
def _datetime_to_rfc3339(value, ignore_zone=True): """Convert a timestamp to a string. :type value: :class:`datetime.datetime` :param value: The datetime object to be converted to a string. :type ignore_zone: bool :param ignore_zone: If True, then the timezone (if any) of the datetime ...
java
public synchronized boolean isStarving(long threshold) { long now = System.currentTimeMillis(); for (QueueEntry e : entries.values()) if (now-e.submissionTime > threshold) return true; return false; }
python
def store_mo(self, state, new_mo, overwrite=True): #pylint:disable=unused-argument """ Stores a memory object. :param new_mo: the memory object :param overwrite: whether to overwrite objects already in memory (if false, just fill in the holes) """ start, end = self._reso...
python
def byLexer( lexer ): """ Looks up the language plugin by the lexer class of the inputed lexer. :param lexer | <QsciLexer> :return <XLanguage> || None """ XLanguage.load() lexerType = type(lexer) for lang in XLanguage._p...
python
def process_results(self, paragraph): """Route Zeppelin output types to corresponding handlers.""" if 'result' in paragraph and paragraph['result']['msg']: msg = paragraph['result']['msg'] self.output_options[paragraph['result']['type']](msg)
python
def get_urls(self): """ Add aditional moderate url. """ from django.conf.urls import url urls = super(AdminModeratorMixin, self).get_urls() info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^(.+)/moderate/$', ...
python
def qn(self, namespace): """Connect tag prefix to longer namespace""" nsmap = { 'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', } spl = namespace.split(':') return '{{{}}}{}'.format(nsmap[spl[0]], spl[1])
java
public Javalin wsBefore(@NotNull String path, @NotNull Consumer<WsHandler> wsHandler) { return staticInstance().wsBefore(prefixPath(path), wsHandler); }
java
public static LineString fromLngLats(@NonNull MultiPoint multiPoint) { return new LineString(TYPE, null, multiPoint.coordinates()); }
java
protected boolean isAtLeastJava8(EObject context) { return this.generatorConfigProvider.get(EcoreUtil.getRootContainer(context)).getJavaSourceVersion().isAtLeast(JavaVersion.JAVA8); }
java
public static QueryParameter getParameterByName(Report report, String parameterName) { return getParameterByName(report.getParameters(), parameterName); }
java
@PostMapping(value = "/map", produces = TEXT_PLAIN_VALUE) public ResponseEntity<String> scheduleMappingJob( @RequestParam String mappingProjectId, @RequestParam String targetEntityTypeId, @RequestParam(required = false) String label, @RequestParam(required = false, name = "package") String raw...
python
def init_argparser(self, argparser): """ This should not be called with an external argparser as it will corrupt tracking data if forced. """ def prepare_argparser(): if argparser in self.argparser_details: return False result = self.argpa...
python
def apply_dataarray_vfunc( func, *args, signature, join='inner', exclude_dims=frozenset(), keep_attrs=False ): """Apply a variable level function over DataArray, Variable and/or ndarray objects. """ from .dataarray import DataArray if len(args) > 1: args = deep_align...
python
def serialize_to_rsb(params: dict) -> bytes: """Сериализация JSON хедера rsb. @params -- параметры в формате JSON (dfparser.def_values.DEF_RSH_PARAMS) @return -- бинарный хедер (2048 bytes) """ header = bytearray(np.zeros(2048, np.byte).tostring()) if "text_header_size" in params: hea...
java
public void skip(int length) { int newcount = count + length; if (newcount > buf.length) { buf = Arrays.copyOf(buf, oversize(newcount)); } count = newcount; }