language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public BType getBuilder(int index) { ensureBuilders(); SingleFieldBuilder<MType, BType, IType> builder = builders.get(index); if (builder == null) { MType message = messages.get(index); builder = new SingleFieldBuilder<MType, BType, IType>( message, this, isClean); builders.set(i...
python
def drop_table(self, dbname, name, deleteData): """ Parameters: - dbname - name - deleteData """ self.send_drop_table(dbname, name, deleteData) self.recv_drop_table()
java
public Set<VersionResource> getVersions() throws RepositoryException, IllegalResourceTypeException { Set<VersionResource> resources = new HashSet<VersionResource>(); VersionIterator versions = versionHistory.getAllVersions(); while (versions.hasNext()) { Version version = versi...
python
def load_data(filename): """Loads data from a file. Parameters ---------- filename : :obj:`str` The file to load the collection from. Returns ------- :obj:`numpy.ndarray` of float The data read from the file. Raises -----...
java
public void closeProducersDestinationDeleted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "closeProducersDestinationDeleted"); synchronized (_producers) { _destinationDeleted = true; Iterator<MessageProducer> i = _producers.iterator(); whi...
java
public void setHttpChannelHandlers(final List<ChannelHandler> httpChannelHandlers) { this.httpChannelHandlers = httpChannelHandlers == null ? Collections.<ChannelHandler> emptyList() : httpChannelHandlers; }
java
public static AutoML startAutoML(AutoMLBuildSpec buildSpec) { Date startTime = new Date(); // this is the one and only startTime for this run synchronized (AutoML.class) { // protect against two runs whose startTime is the same second if (lastStartTime != null) { while (lastStartTime.getYe...
python
def setup(self): """Setup the networks. Setup only does stuff if there are no networks, this is so it only runs once at the start of the experiment. It first calls the same function in the super (see experiments.py in dallinger). Then it adds a source to each network. ""...
java
public final Tuple4<T3, T4, T5, T6> skip2() { return new Tuple4<>(v3, v4, v5, v6); }
java
public IntStreamEx prepend(IntStream other) { return new IntStreamEx(IntStream.concat(other, stream()), context.combine(other)); }
java
@Override public void setQueryTimeout(int seconds) throws SQLException { checkClosed(); if (seconds < 0) { throw SQLError.get(SQLError.ILLEGAL_ARGUMENT, seconds); } if (seconds == 0) { this.m_timeout = Integer.MAX_VALUE; } else { this.m...
python
def color(self, code): """ When color is given as a number, apply that color to the content While this is designed to support 256 color terminals, Windows will approximate this with 16 colors """ def func(content=''): return self._apply_color(u'38;5;%d' % cod...
python
def MI_references(self, env, objectName, resultClassName, role, propertyList): # pylint: disable=invalid-name """Return instances of an association class. Implements the WBEM operation ...
java
private CompletableFuture<Void> excludeObsolete(DirectSegmentAccess segment, CompactionArgs args, Map<UUID, TableBucket> buckets, TimeoutTimer timer) { // Exclude all those Table Entries whose buckets altogether do not exist. args.candidates.keySet().r...
java
private Connector getConnectorById(Evse evse, Long id) { return getConnectorById(evse, id, true); }
java
protected final void registClass(Class<? extends T> scriptClass,Class<?> ...depends) { if(scriptClass!=null) { boolean isAbstract=Modifier.isAbstract(scriptClass.getModifiers());//是否是抽象类 if(isAbstract) {//抽象类 _log.error("can't regist isAbstract class:"+scriptClass.getClass()); return ; }else ...
python
def get_info(df, group, info=['mean', 'std']): """ Aggregate mean and std with the given group. """ agg = df.groupby(group).agg(info) agg.columns = agg.columns.droplevel(0) return agg
python
def parse_http_header(header_line): """Parse an HTTP header from a string, and return an ``HttpHeader``. ``header_line`` should only contain one line. ``BadHttpHeaderError`` is raised if the string is an invalid header line. """ header_line = header_line.decode().strip() col_idx = header_line....
java
public void setInboundConnectionInfo(Map<String, Object> connectionInfo) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "setInboundConnectionInfo"); this.inboundConnectionInfo = connectionInfo; }
java
public static String join(Object[] elements, String glue) { return (join(Arrays.asList(elements), glue)); }
java
public void marshall(GenerateDataKeyRequest generateDataKeyRequest, ProtocolMarshaller protocolMarshaller) { if (generateDataKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(generateDataK...
java
public String getUserName() throws SQLException { ResultSet rs = execute("CALL USER()"); rs.next(); String result = rs.getString(1); rs.close(); return result; }
java
@Override public StopTriggerResult stopTrigger(StopTriggerRequest request) { request = beforeClientExecution(request); return executeStopTrigger(request); }
java
@Override public String fromSuffixToPackageName(final String suffix) { if (LdiStringUtil.isEmpty(suffix)) { throw new EmptyRuntimeException("suffix"); } return suffix.toLowerCase(); }
java
public final boolean contains(char c1, char c2) { try { String s = new String(new String(new char[]{c1, c2}).getBytes(enc), enc); return s.length() == 2 && s.charAt(0) == c1 && s.charAt(1) == c2; } catch (UnsupportedEncodingException e) { return false; } // work around gcj bug (lib...
java
private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) { int i, j; QrMode currentMode; int inputLength = inputModeUnoptimized.length; int count = 0; int alphaLength; int percent = 0; // ZINT NOTE...
python
def _dispose(self): """Dispose of the pool for this instance, closing all connections.""" self.close() # _DBProxy.dispose doesn't actually call dispose on the pool conn_params = self.get_connection_params() key = db_pool._serialize(**conn_params) try: pool = d...
java
public IMetric getRegisteredMetricByName(String name) { IMetric metric = null; for (Map<Integer, Map<String, IMetric>> taskIdToNameToMetric : _registeredMetrics.values()) { Map<String, IMetric> nameToMetric = taskIdToNameToMetric.get(_taskId); if (nameToMetric != null) { ...
python
def _parse_type(self, element, types): """Parse a 'complexType' element. @param element: The top-level complexType element @param types: A map of the elements of all available complexType's. @return: The schema for the complexType. """ name = element.attrib["name"] ...
python
def I_minus_R(self,singular_value): """get I - R at singular value Parameters ---------- singular_value : int singular value to calc R at Returns ------- I - R : pyemu.Matrix identity matrix minus resolution matrix at singular_value ...
java
private void optimizeStart() { if (configuration.isPayloadCache()) { if (configuration.getOptimizerStoreClass() == null) { store = new CacheOptimizerStore(); store.start(configuration); return; } try { store = (OptimizerStore) Class.forName(configuration.getOptimizerStoreClass()).newInstanc...
java
public Map<String, Integer> getComponentCounts() { Map<String, Integer> componentCounts = new HashMap<>(); for (ContainerPlan containerPlan : getContainers()) { for (InstancePlan instancePlan : containerPlan.getInstances()) { Integer count = 0; if (componentCounts.containsKey(instancePlan....
java
public void marshall(ListKeyPoliciesRequest listKeyPoliciesRequest, ProtocolMarshaller protocolMarshaller) { if (listKeyPoliciesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listKeyPolici...
python
def rint(x, step=1): """ Round to integer. Parameters ---------- x : Input number (integer or float) to be rounded. step : Quantization level (defaults to 1). If set to 2, the output will be the "best" even number. Result ------ The step multiple nearest to x. When x is exactly halfway b...
java
@Override public EClass getPluginBundleVersion() { if (pluginBundleVersionEClass == null) { pluginBundleVersionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(103); } return pluginBundleVersionEClass; }
java
public static void escapeJava(final char[] text, final int offset, final int len, final Writer writer, final JavaEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' ca...
python
def collect(self): # pragma: NO COVER """Collect fetches the statistics from OpenCensus and delivers them as Prometheus Metrics. Collect is invoked every time a prometheus.Gatherer is run for example when the HTTP endpoint is invoked by Prometheus. """ for v_name, view_d...
java
@Override public void sendUserAuthorizationAnswer(JUserAuthorizationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); }
java
public void initializeCms(CmsObject cms) { List<String> toRemove = new ArrayList<String>(); // Repositories which can't be fully initialized need to be removed. for (I_CmsRepository repository : m_repositoryMap.values()) { String repoName = repository.getName(); try { ...
python
def _XYZvxvyvz(self,*args,**kwargs): """Calculate X,Y,Z,U,V,W""" obs, ro, vo= self._parse_radec_kwargs(kwargs,vel=True) thiso= self(*args,**kwargs) if not len(thiso.shape) == 2: thiso= thiso.reshape((thiso.shape[0],1)) if len(thiso[:,0]) != 4 and len(thiso[:,0]) != 6: #pragma: no...
java
public static <T> boolean noneEqualForHashable(final Iterable<T> iterable) { return Iterables.size(iterable) == ImmutableSet.copyOf(iterable).size(); }
java
@Override public String transformDML(String dml) { return transformQuery(super.transformDML(dml), asTextQueryTransformer, castGeoAsVarcharQueryTransformer, pointFromTextQueryTransformer, polygonFromTextQueryTransformer, longitudeQueryTransformer, la...
python
def term_with_coeff(term, coeff): """ Change the coefficient of a PauliTerm. :param PauliTerm term: A PauliTerm object :param Number coeff: The coefficient to set on the PauliTerm :returns: A new PauliTerm that duplicates term but sets coeff :rtype: PauliTerm """ if not isinstance(coeff...
python
def pdf_rotate( input: str, counter_clockwise: bool = False, pages: [str] = None, output: str = None, ): """ Rotate the given Pdf files clockwise or counter clockwise. :param inputs: pdf files :param counter_clockwise: rotate counter clockwise if true else clockwise :param pages: lis...
python
def get_link_href(result_object, link_relation): """ Given a result_object (returned by a previous API call), return the link href for a link relation. 'result_object' a JSON object returned by a previous API call. May not be None. 'link_relation' the link relation for which href is required. ...
python
def update_fw_db_result(self, tenant_id, os_status=None, dcnm_status=None, dev_status=None): """Update the FW DB Result and commit it in DB. Calls the service object routine to commit the result of a FW operation in to DB """ serv_obj = self.get_servi...
python
def repl(optimize=True, persist=True): """Starts a simple REPL for this machine. Args: optimize: Controls whether to run inputted code through the optimizer. persist: If True, the machine is not deleted after each line. """ print("Extra commands for the REPL:") print(".code...
java
public static Connection createConnection(OntopSQLCredentialSettings settings) throws SQLException { try { // This should work in most cases (e.g. from CLI, Protege, or Jetty) return DriverManager.getConnection(settings.getJdbcUrl(), settings.getJdbcUser(), settings.getJdbcPassword()); ...
python
def is_contradictory(self, other): """ Two beliefstates are incompatible if the other beliefstates's entities are not consistent with or accessible from the caller. Note: this only compares the items in the DictCell, not `pos`, `environment_variables` or `deferred_effects`. ...
python
def to_datetime(t): """Convert 6-part time tuple into datetime object. """ if t is None: return None # extract values year, mon, day, h, m, s = t # assume the values are valid try: return datetime(year, mon, day, h, m, s) except ValueError: pass # sanitize ...
java
public final BeanConfig getConfig() { if (null == config) { config = new BeanConfig(getClass().getName()); doBinding(); } return config; }
java
public static <T> String requiredStringOfType(Map<String, T> map, String key, String type) { if (!map.containsKey(key)) { String message = String.format("Missing required %s value for key \"%s\".", type, key); ...
python
def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self...
java
public Component getNeoclassicalAffix() { Preconditions.checkState(isCompound(), MSG_NOT_COMPOUND, this); Preconditions.checkState(getCompoundType() == CompoundType.NEOCLASSICAL, MSG_NOT_NEOCLASSICAL, this); for(Component c:components) if(c.isNeoclassicalAffix()) return c; throw new IllegalArgumentExcept...
java
public static String get(String url, Map<String, String> queryParas, Map<String, String> headers) { HttpURLConnection conn = null; try { conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers); conn.connect(); return readResponseString(conn); } catch (Exception e) { throw ne...
python
def execute_request(self, url, http_method, query_params, post_data): """Makes a request to the specified url endpoint with the specified http method, params and post data. Args: url (string): The url to the API without query params. Example: "https://api.h...
java
public static Class<? extends CobolContext> getInputKeyCobolContext(Configuration conf) { return conf.getClass(CONF_INPUT_KEY_COBOL_CONTEXT, null, CobolContext.class); }
java
private void initialize() { this.setJMenuBar(getMainMenuBar()); this.setContentPane(getPaneContent()); this.setPreferredSize(new Dimension(1000, 800)); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowC...
java
private Collection<String> getS3PrefixesForTask(S3Configuration s3Configuration, SingularityTaskId taskId, Optional<Long> startArg, Optional<Long> endArg, String group, SingularityUser user) { Optional<SingularityTaskHistory> history = getTaskHistory(taskId, user); long start = taskId.getStartedAt(); if (s...
python
def expect_comment_end(self): """Expect a comment end and return the match object. """ match = self._expect_match('#}', COMMENT_END_PATTERN) self.advance(match.end())
java
protected void renderColumnHeaderCell(FacesContext facesContext, ResponseWriter writer, UIColumn uiColumn, String headerStyleClass, int colspan) throws IOException { renderColumnHeaderCell(facesContext, writer, uiColumn, uiColumn.getHeader(), headerStyleClass, colspan); }
python
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None): """ Use self as a template to build a new feature, replacing values in kwargs """ ...
java
@Override public boolean isSupport(Method m) { IgnoreNaviRpcMethod anno = m.getAnnotation(IgnoreNaviRpcMethod.class); if (anno != null) { return false; } return true; }
java
public static Router register(Vertx vertx, Object... restApi) { Assert.notNull(vertx, "Missing vertx!"); Router router = Router.router(vertx); return register(router, restApi); }
python
def IndexedDB_requestData(self, securityOrigin, databaseName, objectStoreName, indexName, skipCount, pageSize, **kwargs): """ Function path: IndexedDB.requestData Domain: IndexedDB Method name: requestData Parameters: Required arguments: 'securityOrigin' (type: string) -> Security origin. ...
java
private Double scale(Double value, Double min, Double max) { if(min.equals(max)) { if(value>max) { return 1.0; } else if(value==max && value!=0.0) { return 1.0; } else { return 0.0; } ...
python
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Preparation work for SomaticIndelDetector. """ base_config = items[0]["config"] for x in align_bams: bam.index(x, base_config) params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_...
python
def show_vcs_output_vcs_nodes_vcs_node_info_node_internal_ip_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(...
python
def save(params, filename, source): ''' Write a sequence of samples as a WAV file Currently a 16 bit mono file ''' writer = wave.open(filename, 'wb'); # Set the WAV file parameters, currently default values writer.setnchannels(1) writer.setsampwidth(2) writer.setframerate(params.samp...
python
def getMessage(self, message): ''' Conveniently retrieves message contents from a batch file. Can throw a :class:`python:RuntimeError` if the message batch filename doesn't match this batch filename. ''' if message.filename != self._filename: raise RuntimeErro...
java
public static boolean isPrefix(ByteBuffer prefix, ByteBuffer value) { if (prefix.remaining() > value.remaining()) return false; int diff = value.remaining() - prefix.remaining(); return prefix.equals(value.duplicate().limit(value.remaining() - diff)); }
java
private void startStream( RtspClient rtspClient, String streamName, String params ) throws BackendlessException { if( rtspClient.isStreaming() ) { throw new BackendlessException( "Rtsp client is working on other stream" ); } rtspClient.setServerAddress( WOWZA_SERVER_IP, WOWZA_SERVER_PORT ); ...
python
def strip_chr(bt): """Strip 'chr' from chromosomes for BedTool object Parameters ---------- bt : pybedtools.BedTool BedTool to strip 'chr' from. Returns ------- out : pybedtools.BedTool New BedTool with 'chr' stripped from chromosome names. """ try: df = pd...
java
public static cmppolicy get(nitro_service service, String name) throws Exception{ cmppolicy obj = new cmppolicy(); obj.set_name(name); cmppolicy response = (cmppolicy) obj.get_resource(service); return response; }
java
public static final BigInteger printTimeUnit(TimeUnit value) { return (BigInteger.valueOf(value == null ? TimeUnit.DAYS.getValue() + 1 : value.getValue() + 1)); }
java
private long getAppendWatermarkCutoff(ExtractType extractType) { LOG.debug("Getting append water mark cutoff"); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); AppendMaxLimitType limitType = getAppendLimitType(extra...
python
def begin(self, service_endpoint): """Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.""" if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) ...
java
public int getNumberOfActiveMessages() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getNumberOfActiveMessages"); int returnValue = (int)_targetStream.countAllMessagesOnStream(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(t...
java
public static DetailsDialog showErrorDialog (Stage stage, String text, String details) { DetailsDialog dialog = new DetailsDialog(text, Text.ERROR.get(), details); stage.addActor(dialog.fadeIn()); return dialog; }
java
private String concatDate(int rowIndex){ if(params.length != 2){ throw new IllegalArgumentException("Wrong number of Parameters for concat date expression"); } final DateTimeFormat yearFormat = DateTimeFormat.getFormat(DataType.DATE_FORMAT_YEAR_ONLY); final RecordList.Recor...
java
public Task checkConfigureEvcMode_Task(String evcModeKey) throws RuntimeFault, RemoteException { ManagedObjectReference task = getVimService().checkConfigureEvcMode_Task(getMOR(), evcModeKey); return new Task(getServerConnection(), task); }
java
public static String decode(String encoded) { try { return URLDecoder.decode(encoded, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new EsHadoopIllegalArgumentException("Cannot decode string [" + encoded + "]", e); } }
java
@Override public GetTrafficPolicyInstanceResult getTrafficPolicyInstance(GetTrafficPolicyInstanceRequest request) { request = beforeClientExecution(request); return executeGetTrafficPolicyInstance(request); }
python
def linedelimited (inlist,delimiter): """ Returns a string composed of elements in inlist, with each element separated by 'delimiter.' Used by function writedelimited. Use '\t' for tab-delimiting. Usage: linedelimited (inlist,delimiter) """ outstr = '' for item in inlist: if type(item) != Strin...
java
public final void putShort(Object parent, long offset, short value) { THE_UNSAFE.putShort(parent, offset, value); }
python
def view_exposure_info(token, dstore): """ Display info about the exposure model """ assetcol = dstore['assetcol/array'][:] taxonomies = sorted(set(dstore['assetcol'].taxonomies)) cc = dstore['assetcol/cost_calculator'] ra_flag = ['relative', 'absolute'] data = [('#assets', len(assetcol)...
python
def map_to_pdf(map_source, zoom, x, y, width, height): """ Generate a PDF at the given position. Args: map_source (str): id of the map source to print. zoom (int): zoom-level to print x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate y (float): Ce...
java
private Level toTinyLevel(cn.hutool.log.level.Level level) { Level tinyLevel; switch (level) { case TRACE: tinyLevel = Level.TRACE; break; case DEBUG: tinyLevel = Level.DEBUG; break; case INFO: tinyLevel = Level.INFO; break; case WARN: tinyLevel = Level.WARNING; break; ...
python
def generate_psms_quanted(quantdb, tsvfn, isob_header, oldheader, isobaric=False, precursor=False): """Takes dbfn and connects, gets quants for each line in tsvfn, sorts them in line by using keys in quantheader list.""" allquants, sqlfields = quantdb.select_all_psm_quants(isobaric...
python
def _set_global_isis_info(self, v, load=False): """ Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container) If this variable is read-only (config: false) in the source YANG file, then _set_global_isis_info is considered as a private method. Backends loo...
java
public final Job pauseJob(JobName name) { PauseJobRequest request = PauseJobRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return pauseJob(request); }
python
def create_connection(self): """Initialize HTTP connection with a satellite (con attribute) and set its uri attribute This is called on the satellite link initialization :return: None """ # Create the HTTP client for the connection try: self.con = HT...
java
public static Expression nullIf(Expression expression1, Expression expression2) { return x("NULLIF(" + expression1.toString() + ", " + expression2.toString() + ")"); }
python
def threshold_brier_score(observations, forecasts, threshold, issorted=False, axis=-1): """ Calculate the Brier scores of an ensemble for exceeding given thresholds. According to the threshold decomposition of CRPS, the resulting Brier scores can thus be summed along the last ...
java
@Pure public static File makeRelative(File filenameToMakeRelative, File rootPath) throws IOException { return makeRelative(filenameToMakeRelative, rootPath, true); }
java
public static RocksDbWrapper openReadOnly(String dirPath, DBOptions dbOptions, ReadOptions readOptions) throws RocksDbException, IOException { RocksDbWrapper rocksDbWrapper = new RocksDbWrapper(dirPath, true); rocksDbWrapper.setDbOptions(dbOptions).setReadOptions(readOptions); rocksD...
python
def floordiv(x, y, context=None): """ Return the floor of ``x`` divided by ``y``. The result is a ``BigFloat`` instance, rounded to the context if necessary. Special cases match those of the ``div`` function. """ return _apply_function_in_current_context( BigFloat, mpfr_fl...
python
def addSourceLocation(self, sourceLocationUri, weight): """ add a list of relevant sources by identifying them by their geographic location @param sourceLocationUri: uri of the location where the sources should be geographically located @param weight: importance of the provided list of s...
python
def swarm_init(advertise_addr=str, listen_addr=int, force_new_cluster=bool): ''' Initalize Docker on Minion as a Swarm Manager advertise_addr The ip of the manager listen_addr Listen address used for inter-manager communication, as well as determin...
java
public Observable<Page<Certificate>> listAsync(final CertificateListOptions certificateListOptions) { return listWithServiceResponseAsync(certificateListOptions) .map(new Func1<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>, Page<Certificate>>() { @Override ...