language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { time = timeout; tu = unit; try { if (!latch.await(timeout, unit) || te != null) { throw te == null ? new TimeoutException() : te; ...
java
public String convertIOBXoaOrentToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public Object[] singletonArray(Object value) { Object[] result = new Object[1]; result[0] = value; return result; }
python
def StartClients(cls, hunt_id, client_ids, token=None): """This method is called by the foreman for each client it discovers. Note that this function is performance sensitive since it is called by the foreman for every client which needs to be scheduled. Args: hunt_id: The hunt to schedule. ...
java
private boolean isValid(VariantAnnotation variantAnnotation) { return (variantAnnotation.getAlternate().matches(VARIANT_STRING_PATTERN) // && variantAnnotation.getReference().matches(VARIANT_STRING_PATTERN) && !variantAnnotation.getAlternate().equals(variantAnnotation.getReference...
java
protected void initialize() { eventManager.subscribe(Constants.REFRESH_EVENT, refreshListener); appFramework.registerObject(FrameworkController.this); comp.addEventListener("destroy", (event) -> { cleanup(); }
java
public boolean isDetailPage(CmsObject cms, CmsResource resource) { return getCache(isOnline(cms)).isDetailPage(cms, resource); }
java
@Override protected void register(ServiceInstance instance) { // step 1 get domain from config // set service from config // check if service exists // register service if not // register instance to service Map<String, String> instanceAttributes = new HashMap<>(); ...
java
public Set<String> getCssResources(String containerName) { CmsFormatterConfig formatterConfig = getFormatterConfig(containerName); return formatterConfig != null ? formatterConfig.getCssResources() : Collections.<String> emptySet(); }
java
public static double[] transposeTimes(final double[][] m1, final double[] v2) { final int rowdim = m1.length, coldim = getColumnDimensionality(m1); assert v2.length == rowdim : ERR_MATRIX_INNERDIM; final double[] re = new double[coldim]; // multiply it with each row from A for(int i = 0; i < coldim;...
java
@Override public final Class<?> getColumnClass(int columnIndex) { Column column = getColumn(columnIndex); if (column == Column.CUSTOM) { return getCustomColumnClass(columnIndex); } return getColumnClass(column); }
python
def _extract_params(request_dict, param_list, param_fallback=False): ''' Extract pddb parameters from request ''' if not param_list or not request_dict: return dict() query = dict() for param in param_list: # Retrieve all items in the form of {param: value} and ...
java
@Override public Entity toEntity() { Entity entity = toProtoEntity(); entity.setProperty(JOB_INSTANCE_PROPERTY, jobInstanceKey); entity.setProperty(FINALIZE_BARRIER_PROPERTY, finalizeBarrierKey); entity.setProperty(RUN_BARRIER_PROPERTY, runBarrierKey); entity.setProperty(OUTPUT_SLOT_PROPERTY, outp...
java
public java.util.List<String> getVolumeARNs() { if (volumeARNs == null) { volumeARNs = new com.amazonaws.internal.SdkInternalList<String>(); } return volumeARNs; }
java
private E unlinkLast() { // assert lock.isHeldByCurrentThread(); Node<E> l = last; if (l == null) return null; Node<E> p = l.prev; E item = l.item; l.item = null; l.prev = l; // help GC last = p; if (p == null) first = null;...
python
def preview_request(self, region, endpoint_name, method_name, url, query_params): """ called before a request is processed. :param string endpoint_name: the name of the endpoint being requested :param string method_name: the name of the method being requested :param url: the URL...
python
def configparser(self): """ Adapter to dump/load INI format strings and files using standard library's ``ConfigParser`` (or the backported configparser module in Python 2). Returns: ConfigPersistenceAdapter """ if self._configparser_adapter is None: ...
python
def minimize(loss, train, valid=None, params=None, inputs=None, algo='rmsprop', updates=(), monitors=(), monitor_gradients=False, batch_size=32, train_batches=None, valid_batches=None, **kwargs): '''Minimize a loss function with respect to some symbolic parameters. Additional keyword ...
java
public QueryResult execute(KeenQueryRequest request) throws IOException { Map<String, Object> response = getMapResponse(request); return rawMapResponseToQueryResult(request, response); }
java
public void setDuration(float start, float end) { for (GVRAnimation anim : mAnimations) { anim.setDuration(start,end); } }
java
public final void sinkEvents(Widget widget, Set<String> typeNames) { if (typeNames == null) { return; } int eventsToSink = 0; for (String typeName : typeNames) { int typeInt = Event.getTypeInt(typeName); if (typeInt < 0) { widget.sinkBitlessEvent(typeName); } else { ...
python
def get_callee_account( global_state: GlobalState, callee_address: str, dynamic_loader: DynLoader ): """Gets the callees account from the global_state. :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Accoun...
java
private boolean findFirstSameBuildRow( MemorySegment bucket, int searchHashCode, int bucketInSegmentOffset, BinaryRow buildRowToInsert) { int posInSegment = bucketInSegmentOffset + BUCKET_HEADER_LENGTH; int countInBucket = bucket.getShort(bucketInSegmentOffset + HEADER_COUNT_OFFSET); int numInBucket =...
python
def get_grade_systems(self): """Gets the grade system list resulting from the search. return: (osid.grading.GradeSystemList) - the grade system list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.ret...
java
private OJBIterator getRsIteratorFromQuery(Query query, ClassDescriptor cld, RsIteratorFactory factory) throws PersistenceBrokerException { query.setFetchSize(1); if (query instanceof QueryBySQL) { if(logger.isDebugEnabled()) logger.debug("Creating SQL-RsIterator for clas...
python
def renderer_doc(*args): ''' Return the docstrings for all renderers. Optionally, specify a renderer or a function to narrow the selection. The strings are aggregated into a single document on the master for easy reading. Multiple renderers can be specified. .. versionadded:: 2015.5.0 ...
java
public final void mEscapeSequence() throws RecognitionException { try { // src/riemann/Query.g:112:9: ( '\\\\' ( UnicodeEscape | 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\\\' ) ) // src/riemann/Query.g:112:13: '\\\\' ( UnicodeEscape | 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\\\' ) ...
python
def convert_date(d, custom_date_string=None, fallback=None): """ for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incident...
java
public CommitStatus addCommitStatus(Object projectIdOrPath, String sha, CommitBuildState state, CommitStatus status) throws GitLabApiException { if (projectIdOrPath == null) { throw new RuntimeException("projectIdOrPath cannot be null"); } if (sha == null || sha.trim().isEmpty()) {...
java
@Override public boolean isMonitored(HttpServletRequest httpServletRequest) { String uri = httpServletRequest.getRequestURI().toLowerCase(); return !(uri.endsWith(".css") || uri.endsWith(".png") || uri.endsWith(".gif") || uri.endsWith(".jpg") || uri.endsWith(".js")); }
java
@Override public final void init() throws CoreException { try { super.init(); notifyPreloader(new ProgressNotification(0.1)); notifyPreloader(new ProgressNotification(100)); // 200 , 300 preInit(); notifyPreloader(new ProgressNotifica...
java
public com.google.api.ads.adwords.axis.v201809.cm.Image getCollapsedImage() { return collapsedImage; }
java
public void addDestPath(String in, Properties repl) throws IOException { Path dPath = new Path(in); if (!dPath.isAbsolute() || !dPath.toUri().isAbsolute()) { throw new IOException("Path " + in + " is not absolute."); } PathInfo pinfo = new PathInfo(dPath, repl); if (this.destPath == null) { ...
python
def changelist_view(self, request, extra_context=None): """Add advanced_filters form to changelist context""" if extra_context is None: extra_context = {} response = self.adv_filters_handle(request, extra_context=extra_context) if re...
python
def wait(self): '''This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is ...
java
private List<ValueDataWrapper> readValues(String cid, int cptype, String identifier, int cversion) throws IOException, SQLException, ValueStorageNotFoundException { List<ValueDataWrapper> data = new ArrayList<ValueDataWrapper>(); final ResultSet valueRecords = findValuesByPropertyId(cid); tr...
python
def set_face_colors(self, colors, indexed=None): """Set the face color array Parameters ---------- colors : array Array of colors. Must have shape (Nf, 4) (indexed by face), or shape (Nf, 3, 4) (face colors indexed by faces). indexed : str | None ...
java
protected void closeEhcache(final String alias, final InternalCache<?, ?> ehcache) { for (ResourceType<?> resourceType : ehcache.getRuntimeConfiguration().getResourcePools().getResourceTypeSet()) { if (resourceType.isPersistable()) { ResourcePool resourcePool = ehcache.getRuntimeConfiguration() ...
python
def lock(self): """Close the charger door.""" if not self.__lock_state: data = self._controller.command(self._id, 'charge_port_door_close', wake_if_asleep=True) if data['response']['result']: self.__lock_state = True ...
java
public static <T> WindowOver<T> firstValue(Expression<T> expr) { return new WindowOver<T>(expr.getType(), SQLOps.FIRSTVALUE, expr); }
python
def per_version_data(self): """ Return download data by version. :return: dict of cache data; keys are datetime objects, values are dict of version (str) to count (int) :rtype: dict """ ret = {} for cache_date in self.cache_dates: data = sel...
python
def add_option(self, parser): """ Add option group and all children options. """ group = parser.add_argument_group(self.name) for stat in self.stats: stat.add_option(group) group.add_argument( "--{0}".format(self.option), action="store_true", help="All above")
python
def AgregarUbicacionTambo(self, latitud, longitud, domicilio, cod_localidad, cod_provincia, codigo_postal, nombre_partido_depto, **kwargs): "Agrego los datos del productor a la liq." ubic_tambo = {'latitud': latitud, 'lon...
python
def ranks(self) -> List[str]: """:class:`list` of :class:`str`: Ranks in their hierarchical order.""" return list(OrderedDict.fromkeys((m.rank for m in self.members)))
java
@SuppressWarnings("unchecked") public static <T> Object insert(Object array, int index, T... newElements) { if (isEmpty(newElements)) { return array; } if(isEmpty(array)) { return newElements; } final int len = length(array); if (index < 0) { index = (index % len) + len; } ...
python
def build_matlab(static=False): """build the messenger mex for MATLAB static : bool Determines if the zmq library has been statically linked. If so, it will append the command line option -DZMQ_STATIC when compiling the mex so it matches libzmq. """ cfg = get_config() # To d...
java
protected void loadQueryProperties(String propertyFilename) { Properties properties = new Properties(); try { properties.load(getClass().getClassLoader().getResourceAsStream(propertyFilename)); m_queries.putAll(CmsCollectionsGenericWrapper.<String, String> map(properties)); ...
python
def prop_samples(self,prop,return_values=True,conf=0.683): """Returns samples of given property, based on MCMC sampling :param prop: Name of desired property. Must be column of ``self.samples``. :param return_values: (optional) If ``True`` (default), then also return (...
java
protected synchronized void indexSearcherUpdate() { IndexSearcher oldSearcher = m_indexSearcher; if ((oldSearcher != null) && (oldSearcher.getIndexReader() != null)) { // in case there is an index searcher available close it try { if (oldSearcher.getIndexReader()...
java
public void removeChannel( T channel, String functionalityName, String requesterID, String conversationID) { synchronized (this.channelsWithId) { this.channelsWithId.remove(calculateId(functionalityName, requesterID, conversationID)); ...
python
def pad_position_w(self, i): """ Determines the position of the ith pad in the width direction. Assumes equally spaced pads. :param i: ith number of pad in width direction (0-indexed) :return: """ if i >= self.n_pads_w: raise ModelError("pad index out...
java
public static SendableTextMessageBuilder plain(String text) { return builder().message(text).parseMode(ParseMode.NONE); }
java
public ServiceCall<Classifier> createClassifier(CreateClassifierOptions createClassifierOptions) { Validator.notNull(createClassifierOptions, "createClassifierOptions cannot be null"); String[] pathSegments = { "v1/classifiers" }; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(...
python
def execute(self, command, *args, **kw): """Executes redis command in a free connection and returns future waiting for result. Picks connection from free pool and send command through that connection. If no connection is found, returns coroutine waiting for free connecti...
python
def _to_ufo_kerning(self, ufo, kerning_data): """Add .glyphs kerning to an UFO.""" warning_msg = "Non-existent glyph class %s found in kerning rules." for left, pairs in kerning_data.items(): match = re.match(r"@MMK_L_(.+)", left) left_is_class = bool(match) if left_is_class: ...
java
public static boolean isValid(final String json) { if (Strings.isEmpty(json)) { return false; } try { return parse(json) != null; } catch (ParseException e) { return false; } }
python
def delete(self, project, params={}, **options): """A specific, existing project can be deleted by making a DELETE request on the URL for that project. Returns an empty data record. Parameters ---------- project : {Id} The project to delete. """ ...
python
def getAnalysis(self): """Return the primary analysis this attachment is linked """ analysis = None ans = self.getLinkedAnalyses() if len(ans) > 1: # Attachment is assigned to more than one Analysis. This might # happen when the AR was invalidated ...
java
@Override public void setObjectProperty(String name, Object value) throws JMSException { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Property name can not be null or empty."); } if (value == null || "".equals(value)) { throw new IllegalAr...
java
public static BaseResult menuDelete(String access_token){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI+"/cgi-bin/menu/delete") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); ...
java
public String getContextConfig(final String configName) { String configValue = null; AccessPoint context = getWbRequest().getAccessPoint(); if(context != null) { Properties configs = context.getConfigs(); if(configs != null) { configValue = configs.getProperty(configName); } } return configValue...
java
private void lockFlowsForProject(Project project, List<String> lockedFlows) { for (String flowId: lockedFlows) { Flow flow = project.getFlow(flowId); if (flow != null) { flow.setLocked(true); } } }
python
def get_prefix(self, name): """ Retrieve a prefix, resolving the current one if needed Args: name(str): name of the prefix to retrieve, or current to get the current one Returns: self.prefix_class: instance of the prefix with the given name ...
python
def parse_stream_raw(self, stream, debug=False): """Parse a stream and return the syntax tree.""" tokens = tokenize.generate_tokens(stream.readline) return self.parse_tokens(tokens, debug)
java
private static String getType(Database db, VoltXMLElement elm) { final String type = elm.getStringAttribute("valuetype", ""); if (! type.isEmpty()) { return type; } else if (elm.name.equals("columnref")) { final String tblName = elm.getStringAttribute("table", ""); ...
java
@Override public ListDocumentsResult listDocuments(ListDocumentsRequest request) { request = beforeClientExecution(request); return executeListDocuments(request); }
python
def _add(self, symbol_name, namespace, node, module): """Helper function for adding symbols. See add_symbol(). """ result = symbol_name in namespace namespace[symbol_name] = node, module return not result
python
def get_client_info(self): """ A query is sent to the server to obtain the client's data stored at the server. :return: :class:`~aioxmpp.ibr.Query` """ iq = aioxmpp.IQ( to=self.client.local_jid.bare().replace(localpart=None), type_=aioxmpp.IQType....
python
def create(input_width, input_height, input_channels=1, output_dim=512): """ Vel factory function """ def instantiate(**_): return NatureCnn( input_width=input_width, input_height=input_height, input_channels=input_channels, output_dim=output_dim ) return ModelFactor...
java
public boolean contains(float xp, float yp) { return (xp >= x) && (xp < x+width) && (yp >= y) && (yp < y+height); }
python
def format_expose(expose): """ Converts a port number or multiple port numbers, as used in the Dockerfile ``EXPOSE`` command, to a tuple. :param: Port numbers, can be as integer, string, or a list/tuple of those. :type expose: int | unicode | str | list | tuple :return: A tuple, to be separated by ...
java
public <T> T getOnce(final Class<T> clazz, final String name) { return new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz).get(); }
python
def do_terminateInstance(self,args): """Terminate an EC2 instance""" parser = CommandArgumentParser("terminateInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] try: ...
java
public static String subst(String string, Map dictionary) { LOGGER.entering(CLASS_NAME, "subst", new Object[]{string, dictionary}); Pattern pattern = Pattern.compile(VARIABLE_PATTERN); Matcher matcher = pattern.matcher(string); while (matcher.find()) { String va...
java
@Override public boolean exists(String resource, String[] paths) throws IOException { for (ResourceLoader loader : loaders) { if (loader.exists(resource, paths)) { return true; } } return false; }
java
final void checkConformance(Node node, ErrorReporter errorReporter) { if (nodeClass.isAssignableFrom(node.getClass())) { doCheckConformance(nodeClass.cast(node), errorReporter); } }
java
private long fileSizeAdjusted(long alignedPointerToRaw, long readSize) { // end of section outside the file --> cut at file.length() if (readSize + alignedPointerToRaw > file.length()) { readSize = file.length() - alignedPointerToRaw; } // start of section outside the file --...
python
def scanFolderForRegexp(folder = None, listRegexp = None, recursive = False, verbosity=1, logFolder= "./logs", quiet=False): """ [Optionally] recursive method to scan the files in a given folder. Args: ----- folder: the folder to be scanned. listRegexp: listRegexp is an array of <Regexp...
java
public static boolean isEligibleType(Class<?> type) { return type.isAnnotationPresent(Type.class) && !ReflectionUtils.getAnnotatedFields(type, Id.class, true).isEmpty(); }
python
def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None): """ Convert categorical variable into dummy/indicator variables. Parameters ---------- data : array-like, Series, or DataFrame Data of which to get d...
java
public Observable<ServiceResponse<PersistedFace>> getFaceWithServiceResponseAsync(String personGroupId, UUID personId, UUID persistedFaceId) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); }...
python
def key_CV(key, kcv_length=6): """ Get DES key check value. The key is binary hex e.g. b'DF1267EEDCBA9876' """ cipher = DES3.new(B2raw(key), DES3.MODE_ECB) encrypted = raw2B(cipher.encrypt(B2raw(b'00000000000000000000000000000000'))) return encrypted[:kcv_length]
python
def SolveServiceArea(self, facilities=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, defaultBreaks=None, excludeSourcesF...
java
public static Vec numericToCategorical(Vec src) { if (src.isInt()) { int min = (int) src.min(), max = (int) src.max(); // try to do the fast domain collection long dom[] = (min >= 0 && max < Integer.MAX_VALUE - 4) ? new CollectDomainFast(max).doAll(src).domain() : new CollectIntegerDomain().doAll(...
python
def has_title(self): """Read/write boolean, specifying whether this chart has a title. Assigning |True| causes a title to be added if not already present. Assigning |False| removes any existing title along with its text and settings. """ title = self._chartSpace.chart.ti...
python
def get_locations_from_coords(self, longitude, latitude, levels=None): """ Returns a list of geographies containing this point. """ resp = requests.get(SETTINGS['url'] + '/point/4326/%s,%s?generation=%s' % (longitude, latitude, SETTINGS['generation'])) resp.raise_for_status() ...
python
def _product(k, v): """ Perform the product between two objects even if they don't support iteration """ if not _can_iterate(k): k = [k] if not _can_iterate(v): v = [v] return list(product(k, v))
java
public final AntlrDatatypeRuleToken ruleGrammarID() throws RecognitionException { AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken(); Token kw=null; AntlrDatatypeRuleToken this_ValidID_0 = null; AntlrDatatypeRuleToken this_ValidID_2 = null; enterRule(); ...
python
def fire_exception(exc, opts, job=None, node='minion'): ''' Fire raw exception across the event bus ''' if job is None: job = {} event = salt.utils.event.SaltEvent(node, opts=opts, listen=False) event.fire_event(pack_exception(exc), '_salt_error')
python
def connectivity(self, bus): """check connectivity of network using Goderya's algorithm""" if not self.n: return n = self.nb fr = self.a1 to = self.a2 os = [0] * self.n # find islanded buses diag = list( matrix( spm...
python
def download_and_transfer_sample(job, sample, inputs): """ Downloads a sample from CGHub via GeneTorrent, then uses S3AM to transfer it to S3 input_args: dict Dictionary of input arguments analysis_id: str An analysis ID for a sample in CGHub """ analysis_id = sample[0] work_...
java
public static <ReqT, RespT> ListenableFuture<RespT> futureUnaryCall( ClientCall<ReqT, RespT> call, ReqT req) { GrpcFuture<RespT> responseFuture = new GrpcFuture<>(call); asyncUnaryRequestCall(call, req, new UnaryStreamToFuture<>(responseFuture), false); return responseFuture; }
java
protected void customizeRequest(Socket socket, HttpRequest request) { super.customizeRequest(socket, request); if (!(socket instanceof javax.net.ssl.SSLSocket)) return; // I'm tempted to let it throw an // exception... try ...
java
@Override public void load(String persistenceUnit, Map<String, Object> puProperties) { setPersistenceUnit(persistenceUnit); // Load Client Specific Stuff logger.info("Loading client metadata for persistence unit : " + persistenceUnit); loadClientMetadata(puProperties); ...
java
@Override public final boolean getCapacity (final Session session, final TargetCapacityInformations capacityInformation) throws Exception { if (capacityInformation == null) { throw new NullPointerException(); } final Connection connection = session.getNextFreeConnection(); if (connection =...
python
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): ...
java
IAsyncFuture multiIO(ByteBuffer[] buffers, long position, boolean isRead, boolean forceQueue, long bytesRequested, boolean useJITBuffer, VirtualConnection vci, boolean asyncIO) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "multiIO(.," + ...
java
public static Class<?> findGenericClass(final Class<?> mainClass, final Class<?>[] excludedClasses) { final boolean excludeMode = excludedClasses.length > 1; // Retrieve the generic super class Parameterized type final ParameterizedType paramType = (ParameterizedType) mainClass.getGenericSuper...
python
def master_send_callback(self, m, master): '''called on sending a message''' if self.status.watch is not None: for msg_type in self.status.watch: if fnmatch.fnmatch(m.get_type().upper(), msg_type.upper()): self.mpstate.console.writeln('> '+ str(m)) ...
java
private static int getPhaseNumberAsInt(VersionIdentifier version) { Integer phaseNumberInteger = version.getPhaseNumber(); if (phaseNumberInteger == null) { return 0; } else { return phaseNumberInteger.intValue(); } }