language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public byte[] get(byte[] key){ byte[] value = null; Jedis jedis = jedisPool.getResource(); try{ value = jedis.get(key); }finally{ jedisPool.returnResource(jedis); } return value; }
java
public static String decode_escaped(String str) { if(str.indexOf('\\')==-1) return str; StringBuilder sb=new StringBuilder(str.length()); for(int i=0; i<str.length(); ++i) { char c=str.charAt(i); if(c=='\\') { // possible escape sequence char c2=str.charAt(++i); switch(c2) { ca...
java
private void aztecAutoSizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aztecAutoSizeActionPerformed // TODO add your handling code here: aztecUserSizeCombo.setEnabled(false); aztecUserEccCombo.setEnabled(false); encodeData(); }
python
def _retf16(ins): """ Returns from a procedure / function a Fixed Point (32bits) value """ output = _f16_oper(ins.quad[1]) output.append('#pragma opt require hl,de') output.append('jp %s' % str(ins.quad[2])) return output
python
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): """Rounding accuracy for L1/L2 losses: round down the predictions to ints.""" outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) ...
python
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked. """ if self.data is True: return Qt.Checked elif self.data is False: return Qt.Unchecked else: raise ValueError("Unexpected data: {!r}".format(self.data))
python
def _set_debug_handler(self, v, load=False): """ Setter method for debug_handler, mapped from YANG variable /isis_state/router_isis_config/debug_handler (container) If this variable is read-only (config: false) in the source YANG file, then _set_debug_handler is considered as a private method. Backe...
python
def remove_other_cflags(self, flags, target_name=None, configuration_name=None): """ Removes the given flags from the OTHER_CFLAGS section of the target on the configurations :param flags: A string or array of strings. If none, removes all values from the flag. :param target_name: Target...
java
private void setInactivityTimer(long ms) { if (sessionInactivityTimer == null) { sessionInactivityTimer = new SessionInactivityTimer(sessionHandler.getScheduler(), this); } sessionInactivityTimer.setIdleTimeout(ms); }
python
def determine_plasma_store_config(object_store_memory=None, plasma_directory=None, huge_pages=False): """Figure out how to configure the plasma object store. This will determine which directory to use for the plasma store (e.g., /tmp or /d...
java
public SqlApplicationConfigurationUpdate withReferenceDataSourceUpdates(ReferenceDataSourceUpdate... referenceDataSourceUpdates) { if (this.referenceDataSourceUpdates == null) { setReferenceDataSourceUpdates(new java.util.ArrayList<ReferenceDataSourceUpdate>(referenceDataSourceUpdates.length)); ...
java
public void setAttachmentSet(java.util.Collection<AttachmentDetails> attachmentSet) { if (attachmentSet == null) { this.attachmentSet = null; return; } this.attachmentSet = new com.amazonaws.internal.SdkInternalList<AttachmentDetails>(attachmentSet); }
java
public static Stream<MutableIntTuple> lexicographicalStream( IntTuple max) { return stream(Order.LEXICOGRAPHICAL, IntTuples.zero(max.getSize()), max); }
java
@SuppressWarnings("static-method") @Pure @Inline(value = "$1.getCaller()", imported = Capacities.class, constantExpression = true) protected AgentTrait getCaller() { return Capacities.getCaller(); }
python
def average(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the mean of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return...
java
public Entry[] listEntries( DirectoryEntry directory ) { Map<String, Entry> result = new TreeMap<String, Entry>(); for ( FileSystem delegate : delegates ) { Entry[] entries = delegate.listEntries( DefaultDirectoryEntry.equivalent( delegate, directory ) ); if ( entries...
python
def get_walk_after(filename, optimize_after=None): """ Figure out the which mtime to check against. If we have to look up the path return that. """ if Settings.optimize_after is not None: return Settings.optimize_after dirname = os.path.dirname(filename) if optimize_after is None: ...
python
def get_command(self, name): """Wrap command class in constructor.""" def command(options): client = ZookeeperClient( "%s:%d" % (options.pop('host'), options.pop('port')), session_timeout=1000 ) path = options.pop('path_prefix') ...
java
public static void computeCameraControl(double beta[], List<Point3D_F64> nullPts[], FastQueue<Point3D_F64> cameraPts , int numControl ) { cameraPts.reset(); for( int i = 0; i < numControl; i++ ) { cameraPts.grow().set(0,0,0); } for( int i = 0; i < numControl; i++ ) { dou...
python
def HasColumn(self, table_name, column_name): """Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSErr...
java
@Override public ByteArrayInputStream getImage(String jsonModels) throws JsonProcessingException, ApiException { return getImage(null, null, jsonModels); }
java
@Override public FieldComparator<?> newComparator(String propertyName, int numHits, int sortPos, boolean reversed) throws IOException { try { QPath path = locationFactory.parseJCRPath(propertyName).getInternalPath(); SimpleFieldComparator simple = (SimpleFieldComparator)create...
java
private <T> void destroyReference(final Bean<T> bean, final T beanInstance) { bean.destroy(beanInstance); }
python
def query(self, attributes=None, filters=None, only_unique=True, use_attr_names=False, dtypes = None ): """Queries the dataset to retrieve the contained data. Args: attributes (list[str]): Names of attribute...
python
def trace(self, request, response, error, latency): """ Collects the data from the given parameters and emit it. :param request: The Flask request. :param response: The Flask response. :param error: The error occurred if any. :param latency: The time elapsed to process t...
java
@Override public FeatureEpicResult getIssues(Scope project) { Map<String, Epic> epicMap = new HashMap<>(); FeatureEpicResult featureEpicResult = new FeatureEpicResult(); String lookBackDate = getUpdatedSince(project.getLastCollected()); String issueTypes = featureSettings.getJiraIs...
java
@SuppressWarnings("unchecked") public static <T> T handleRow(int columnCount, ResultSetMetaData meta, ResultSet rs, Class<T> beanClass) throws SQLException { Assert.notNull(beanClass, "Bean Class must be not null !"); if(beanClass.isArray()) { //返回数组 final Class<?> componentType = beanClass.getCompo...
python
def _status_change(id, new_status): """Update the status of a job The status associated with the id is updated, an update command is issued to the job's pubsub, and and the old status is returned. Parameters ---------- id : str The job ID new_status : str The status change ...
java
public static byte[] longToUID(final long uid, final short width) { // Verify that we're going to drop bytes that are 0. final byte[] padded = Bytes.fromLong(uid); for (int i = 0; i < padded.length - width; i++) { if (padded[i] != 0) { final String message = "UID " + Long.toString(uid) + ...
python
def get_cli_argument(self, command, name): """ Get the argument for the command after applying the scope hierarchy :param command: The command that we want the argument for :type command: str :param name: The name of the argument :type name: str :return: The CLI command ...
python
def check_phonefy(self, query, kwargs={}): """ Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The elem...
python
def contains_glob(path_to_directory, pattern, wanted=None): """Whether the given path contains an item matching the given glob""" if not path_to_directory: return False needed = make_needed(pattern, path_to_directory, wanted) for name in _names_in_directory(path_to_directory): if needed(...
java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final String remoteUser = StringUtils.trimToNull(FileUtils.readFileToString(this.remoteUserFile)); if (remoteUser != null) { ...
java
public void error(final Object parameterizedMsg, final Object param1) { parameterizedLog(ERROR_STR, parameterizedMsg, param1, null); }
java
private static final int binarySearchForRootPrimaryNode( int[] rootPrimaryIndexes, int length, long[] nodes, long p) { if(length == 0) { return ~0; } int start = 0; int limit = length; for (;;) { int i = (int)(((long)start + (long)limit) / 2); long nod...
python
def shortcut_str(self, path, cmd): """ Get a string with colors describing a shortcut """ s = colored('| path = ', 'cyan') + colored(path, 'yellow') + '\n' \ + colored('| cmd = ', 'cyan') + \ colored(cmd, 'green', attrs=['bold']) return s
python
def print_resolve_diff(self, other, heading=None): """Print the difference between the resolve of two contexts. Args: other (`ResolvedContext`): Context to compare to. heading: One of: - None: Do not display a heading; - True: Display the filename...
java
public static <TResult> Task<TResult> call(final Callable<TResult> callable, CancellationToken ct) { return call(callable, IMMEDIATE_EXECUTOR, ct); }
java
protected void encodeSortVar(final FacesContext context, final Sheet sheet, final WidgetBuilder wb) throws IOException { final JavascriptVarBuilder vb = new JavascriptVarBuilder(null, false); for (final SheetColumn column : sheet.getColumns()) { if (!column.isRendered()) { ...
java
public synchronized K reverseLookup(final V value) { if (tmap == null) { throw new IllegalStateException("not open"); } return invTmap.findKeyForValue(value); }
java
private boolean publish(String channel, Message message, IMessageProducer producer, Recipient[] recipients) { if (producer != null) { prepare(channel, message, recipients); return producer.publish(channel, message); } return false; }
python
def local_datafile(self): """Return the datafile for this partition, from the build directory, the remote, or the warehouse""" from ambry_sources import MPRowsFile from fs.errors import ResourceNotFoundError from ambry.orm.exc import NotFoundError try: return MPRowsF...
python
def describe_table(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str) -> List[List[Any]]: """Returns details on a specific table.""" raise RuntimeError(_MSG_NO_FLAVOUR)
python
def pick(self, connections): """Picks a connection with the earliest backoff time. As a result, the first connection is picked for as long as it has no backoff time. Otherwise, the connections are tried in a round robin fashion. Args: connections (:obj:list...
python
def attach(obj, schema): """Attach the given schema to the given object.""" # We have a silly exception for lists, since they have no 'attach_schema' # method, and I don't feel like making a subclass for List just to add it. # So, we recursively search the list for tuples and attach the schema in # there. ...
java
public void setMessageDeletionMode(final String messageDeletionMode) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr .debug(this, TRACE, "MessageDeletionMode", messageDeletionMode); } _messa...
java
public void removeSpace(String spaceId) { // Will throw if bucket does not exist String bucketName = getBucketName(spaceId); try { s3Client.deleteBucket(bucketName); } catch (AmazonClientException e) { String err = "Could not delete S3 bucket with name " + bucket...
java
public boolean contains(Collection<Data> dataSet) { for (Data data : dataSet) { boolean contains = false; for (QueueItem item : getItemQueue()) { if (item.getData() != null && item.getData().equals(data)) { contains = true; break; ...
python
def _to_spherical(flds, header): """Convert vector field to spherical.""" cth = np.cos(header['t_mesh'][:, :, :-1]) sth = np.sin(header['t_mesh'][:, :, :-1]) cph = np.cos(header['p_mesh'][:, :, :-1]) sph = np.sin(header['p_mesh'][:, :, :-1]) fout = np.copy(flds) fout[0] = cth * cph * flds[0]...
java
private void createQueryFutureMethod(JavaClass jClass, Method method) { Class<?> []parameterTypes = method.getParameterTypes(); Annotation [][]parameterAnns = method.getParameterAnnotations(); int paramLength = parameterTypes.length; addMethod(method); ...
python
def set_midplane(self, midplane): """ Sets the midplane model. :returns: midplane model string (e.g. "vxr" or "std") """ yield from self._hypervisor.send('c7200 set_midplane "{name}" {midplane}'.format(name=self._name, midplane=midplane)) log.info('Router "{name}" [{id...
python
def generate_address(self, passphrase): """ Make sure the confirm code is valid for the given password and address. """ inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt) public_key = privtopub(inter.passpoint) # from Bip38EncryptedPrivateKey.c...
python
def get_source_pars(src): """Extract the parameters associated with a pyLikelihood Source object. """ fnmap = src.getSrcFuncs() keys = fnmap.keys() if 'Position' in keys: ppars = get_function_pars(src.getSrcFuncs()[str('Position')]) elif 'SpatialDist' in keys: ppars = get_fun...
python
def get_independencies(self, latex=False): """ Computes independencies in the DAG, by checking d-seperation. Parameters ---------- latex: boolean If latex=True then latex string of the independence assertion would be created. Examples ---...
java
public MessageProtocol withVersion(String version) { return new MessageProtocol(contentType, charset, Optional.ofNullable(version)); }
java
public Dispatchable removeDispatchableForGlobalTransaction(int clientId, XidProxy xid) { if (tc.isEntryEnabled()) SibTr.entry(this, tc, "removeDispatchableForGlobalTransaction", new Object[] { "" + clientId }); AbstractFirstLevelMapEntry firstLevelEntry = null; if (idToFirstLevelEntr...
java
public static Object getGenInstance(Class<?> cls, Object... args) throws ParserException { Class<?> parserClass = getGenClass(cls); try { if (args.length == 0) { return parserClass.newInstance(); } else { ...
python
def remove_bookmark(self, time): """User removes bookmark. Parameters ---------- time : tuple of float start and end of the new bookmark, in s """ self.annot.remove_bookmark(time=time) self.update_annotations()
java
public Matrix3x2f scale(Vector2fc xy, Matrix3x2f dest) { return scale(xy.x(), xy.y(), dest); }
python
def set_state(self, state): """ Call the set_state method in SimStatePlugin class, and then perform the delayed initialization. :param state: The SimState instance """ SimStatePlugin.set_state(self, state) # Delayed initialization stack_region_map, generic_regio...
java
private IAtomContainer setInitialCharges(IAtomContainer ac) throws CDKException { Matcher matOC = null; Matcher matOP = null; Matcher matOS = null; Matcher mat_p = null; Matcher mat_n = null; String hoseCode = ""; for (int i = 0; i < ac.getAtomCount(); i++) { ...
java
public void setCaptionSelectors(java.util.Collection<CaptionSelector> captionSelectors) { if (captionSelectors == null) { this.captionSelectors = null; return; } this.captionSelectors = new java.util.ArrayList<CaptionSelector>(captionSelectors); }
java
public void onServerStart(String ip) { closeDialog(); mBtnStart.setVisibility(View.GONE); mBtnStop.setVisibility(View.VISIBLE); mBtnBrowser.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(ip)) { List<String> addressList = new LinkedList<>(); mRootUrl ...
python
def is_config_file(filename, extensions=['.yml', '.yaml', '.json']): """ Return True if file has a valid config file type. Parameters ---------- filename : str filename to check (e.g. ``mysession.json``). extensions : str or list filetypes to check (e.g. ``['.yaml', '.json']``)....
python
def firmware_manifest_list(self, **kwargs): # noqa: E501 """List manifests # noqa: E501 List firmware manifests. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.firmware...
python
def on_menu_criteria_file(self, event): """ read pmag_criteria.txt file and open change criteria dialog """ if self.data_model == 3: dlg = wx.FileDialog( self, message="choose a file in MagIC Data Model 3.0 format", defaultDir=self.WD,...
java
@CanIgnoreReturnValue public Ordered containsAllOf( @NullableDecl Object firstExpected, @NullableDecl Object secondExpected, @NullableDecl Object... restOfExpected) { return delegate().containsAllOf(firstExpected, secondExpected, restOfExpected); }
java
public Consumer<LoadGroupOp> asDoLoadFinishConsumer() { return new Consumer<LoadGroupOp>() { @Override public void accept(LoadGroupOp result) throws Exception { Card card = result.getArg1(); card.loading = false; List<BaseCell> cells = resu...
java
static GenericObject newEmptyInstance(ZooClassDef def, AbstractCache cache) { long oid = def.getProvidedContext().getNode().getOidBuffer().allocateOid(); return newEmptyInstance(oid, def, cache); }
java
public static long getFirstShortInProgress(Map<Long, TransactionManager.InProgressTx> inProgress) { long firstShort = Transaction.NO_TX_IN_PROGRESS; for (Map.Entry<Long, TransactionManager.InProgressTx> entry : inProgress.entrySet()) { if (!entry.getValue().isLongRunning()) { firstShort = entry.ge...
java
public static Condition newRefererCondition(StringComparisonType comparisonType, String value) { return new StringCondition(comparisonType, REFERER_CONDITION_KEY, value); }
python
def run_inference_on_image(image): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. cr...
java
private <T extends Number> Gauge<Long> createKeyspaceGauge(String name, final MetricValue extractor) { allMetrics.add(name); return Metrics.newGauge(factory.createMetricName(name), new Gauge<Long>() { public Long value() { long sum = 0; ...
java
public MongoQuery in(String key, List values) { if ("_id".equals(key)) { List<ObjectId> idList = new ArrayList<ObjectId>(); Iterator iter = values.iterator(); while (iter.hasNext()) { Object value = (Object) iter.next(); idList.add(new ObjectI...
python
def populate_tabs(self): """Populating tabs based on layer metadata.""" self.delete_tabs() layer_purpose = self.metadata.get('layer_purpose') if not layer_purpose: message = tr( 'Key layer_purpose is not found in the layer {layer_name}' ).format(la...
python
def get_ad_leads(self, start_date=None, end_date=None, filtering=(), page=1, page_size=100, version='v1.0'): """ 获取朋友圈销售线索数据接口 :param start_date: 开始日期 默认今天 :param end_date: 结束日期 默认今天 :param filtering: 过滤条件 [{field: 过滤字段, operator: 操作符, values: 字段取值}] :param page: 页码,获取指...
python
def filter(self, predicates): """Summary Args: grouping_column_name (TYPE): Description Returns: TYPE: Description """ tys = [] for col_name, raw_column in self.raw_columns.items(): dtype = str(raw_column.dtype) if dtype =...
java
public void parseSequenceFlow(Element processElement, ScopeImpl scope, Map<String, Element> compensationHandlers) { for (Element sequenceFlowElement : processElement.elements("sequenceFlow")) { String id = sequenceFlowElement.attribute("id"); String sourceRef = sequenceFlowElement.attribute("sourceRef"...
python
def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. """ if options.files == sys.stdin: results = validate(options.files, options) return [FileVa...
java
public boolean doSeek(String strSeekSign) throws DBException { m_iPhysicalIndex = NO_INDEX; // A seek messes up the current query. m_iLogicalIndex = NO_INDEX; return super.doSeek(strSeekSign); }
python
def _process_pubs(self, limit): """ Flybase publications. :param limit: :return: """ if self.test_mode: graph = self.testgraph else: graph = self.graph model = Model(graph) line_counter = 0 raw = '/'.join((self.ra...
java
private AccessControlList getAcl(String bucketName, String key, String versionId, boolean isRequesterPays, AmazonWebServiceRequest originalRequest) { if (originalRequest == null) originalRequest = new GenericBucketRequest(bucketName); Request<AmazonWebServiceRequest> request = createRequest...
java
public static syslog_params[] get(nitro_service client) throws Exception { syslog_params resource = new syslog_params(); resource.validate("get"); return (syslog_params[]) resource.get_resources(client); }
java
private void timeoutHasExpired(final Timeout timeout, final TimeoutExpirationContext context) { try { addMessage(timeout, context.getOriginalHeaders()); } catch (Exception ex) { LOG.error("Error handling timeout {}", timeout, ex); } }
java
private JPanel getMainPanel() { if (mainPanel == null) { mainPanel = new JPanel(); mainPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(5, 5, 5, 5); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = ...
python
def run_guest(): """ A sample for quickly deploy and start a virtual guest. """ # user input the properties of guest, image and network. _user_input_properties() # run a guest. _run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE, GUEST_VCPUS, GUEST_MEMORY, ...
java
@Override public Result<Response> handleAsync(JsonPath jsonPath, QueryAdapter queryAdapter, Document requestBody) { Serializable id = jsonPath.getId(); RegistryEntry rootEntry = jsonPath.getRootEntry(); ResourceRepositoryAdapter resourceRepository = rootEntry.getResourceRepository(); DocumentMappingConfig do...
python
def overlaps(self, contig, start, end, strand=None): """ Does this locus overlap with a given range of positions? Since locus position ranges are inclusive, we should make sure that e.g. chr1:10-10 overlaps with chr1:10-10 """ return ( self.can_overlap(contig...
java
public int doEndTag() throws JspException { String key = null; LocalizationContext locCtxt = null; // determine the message key by... if (keySpecified) { // ... reading 'key' attribute key = keyAttrValue; } else { // ... r...
java
public static DepIoChart insideOutsideSingleRoot(double[] fracRoot, double[][] fracChild) { final boolean singleRoot = true; return insideOutside(fracRoot, fracChild, singleRoot); }
python
def check_reservation_rooms(self): ''' This method is used to validate the reservation_line. ----------------------------------------------------- @param self: object pointer @return: raise a warning depending on the validation ''' ctx = dict(self._context) or {} ...
python
def get_fd_from_freqtau(template=None, **kwargs): """Return frequency domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute for keyword arguments. A common example would be a row in an ...
java
private Class[] makeParameterTypes(Object owner, MetaMethod m) { Class[] newParameterTypes; if (owner instanceof Class && !m.isStatic()) { Class[] nativeParameterTypes = m.getNativeParameterTypes(); newParameterTypes = new Class[nativeParameterTypes.length + 1]; Sys...
java
private void setResponseElements(IntuitMessage intuitMessage, HttpURLConnection httpUrlConnection) throws FMSException { LOG.debug("Response headers:"+httpUrlConnection.getHeaderFields()); ResponseElements responseElements = intuitMessage.getResponseElements(); responseElements.setEncodingHeader(httpUrlConnection...
java
public void marshall(BatchRetryStrategy batchRetryStrategy, ProtocolMarshaller protocolMarshaller) { if (batchRetryStrategy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batchRetryStrategy.getAtt...
java
public static <T, V> Collection<V> collect( Iterable<T> iterable, Function<? super T, ? extends V> function) { if (iterable instanceof MutableCollection) { return ((MutableCollection<T>) iterable).collect(function); } if (iterable instanceof ArrayL...
python
def replace_series_data(self, chartSpace): """ Rewrite the series data under *chartSpace* using the chart data contents. All series-level formatting is left undisturbed. If the chart data contains fewer series than *chartSpace*, the extra series in *chartSpace* are deleted. If *c...
python
def GetVersion(): """Gets the version from googleads/common.py. We can't import this directly because new users would get ImportErrors on our third party dependencies. Returns: The version of the library. """ with open(os.path.join('googleads', 'common.py')) as versions_file: source = versions_fil...
python
def call(self, method, args, kwargs, one_way=False): """Calls the requested method and returns the result. If an error occured, an :py:class:`~tinyrpc.exc.RPCError` instance is raised. :param method: Name of the method to call. :param args: Arguments to pass to the method. ...
java
public static String getStateStyle(CmsResourceState state) { String stateStyle = ""; if (state != null) { if (state.isDeleted()) { stateStyle = OpenCmsTheme.STATE_DELETED; } else if (state.isNew()) { stateStyle = OpenCmsTheme.STATE_NEW; ...