language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static <A extends Number & Comparable<?>> NumberExpression<A> min(Expression<A> left, Expression<A> right) { return NumberExpression.min(left, right); }
java
protected void compactRanges() { boolean DEBUG = false; if (this.ranges == null || this.ranges.length <= 2) return; if (this.isCompacted()) return; int base = 0; // Index of writing point int target = 0; // Index of processing point while (target < this.ranges.length) { if (base != targe...
python
def run(self, cmd): """Similar to profile.Profile.run .""" import __main__ dikt = __main__.__dict__ return self.runctx(cmd, dikt, dikt)
java
public static vpnsessionpolicy_binding get(nitro_service service, String name) throws Exception{ vpnsessionpolicy_binding obj = new vpnsessionpolicy_binding(); obj.set_name(name); vpnsessionpolicy_binding response = (vpnsessionpolicy_binding) obj.get_resource(service); return response; }
java
@Override public void readXML(final List<String> _tags, final Map<String, String> _attributes, final String _text) throws SAXException, EFapsException { if (_tags.size() == 1) { final String value = _tags.get(0); if ("uuid"....
python
def search(self, keyword, remotepath = None, recursive = True): ''' Usage: search <keyword> [remotepath] [recursive] - \ search for a file using keyword at Baidu Yun keyword - the keyword to search remotepath - remote path at Baidu Yun, if not specified, it's app's root directory resursive - search recursively ...
java
public long getLong( String key ) { verifyIsNull(); Object o = get( key ); if( o != null ){ return o instanceof Number ? ((Number) o).longValue() : (long) getDouble( key ); } throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] is not a number." ); }
java
public PhotoContext getContext(String photoId) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_GET_CONTEXT); parameters.put("photo_id", photoId); Response response = transport.get(transport.getPath(), parame...
python
def collapse(in_file): """collapse identical sequences and keep Q""" keep = Counter() with open_fastq(in_file) as handle: for line in handle: if line.startswith("@"): if line.find("UMI") > -1: logger.info("Find UMI tags in read names, collapsing by UMI...
java
private static String checkPayToHash(byte[] scriptPubKey) { // test start boolean validLength=scriptPubKey.length==25; if (!(validLength)) { return null; } boolean validStart=((scriptPubKey[0] & 0xFF)==0x76) && ((scriptPubKey[1] & 0xFF)==0xA9) && ((scriptPubKey[2] & 0xFF)==0x14); boolean validEnd=((scriptPubKey[23] & ...
python
def attach(zone, force=False, brand_opts=None): ''' Attach the specified zone. zone : string name of the zone force : boolean force the zone into the "installed" state with no validation brand_opts : string brand specific options to pass CLI Example: .. code-block:...
python
def create_route53_zone(client, zone_name): """Creates the given zone_name if it doesn't already exists. Also sets the SOA negative caching TTL to something short (300 seconds). Args: client (:class:`botocore.client.Route53`): The connection used to interact with Route53's API. ...
python
def update(self, item, dry_run=None): """Updates item info in file.""" logger.debug('Updating item. Item: {item} Path: {data_file}'.format( item=item, data_file=self.data_file )) self.delete(item, dry_run=dry_run) return self.create(item, dry_run=dry_run)
java
private boolean checkPermissions(String sentence) { sentence = sentence.toUpperCase(); // protected user from the case where they accidentally left off the condition in DELETE statements // (you can still use dummy conditions like 'WHERE 1=1' if you really want to delete everything) if...
java
private double convertToDouble(byte[] bin){ ByteBuffer bb = ByteBuffer.wrap(bin); bb.order(ByteOrder.BIG_ENDIAN); if(bin.length < 4) return bb.getShort(); else if(bin.length < 8) return bb.getInt(); else return bb.getDouble(); }
java
private void populateRelationList(Task task, TaskField field, String data) { DeferredRelationship dr = new DeferredRelationship(); dr.setTask(task); dr.setField(field); dr.setData(data); m_deferredRelationships.add(dr); }
python
def output(self, value): """ Sets the client's output (on, off, int) Sets the general purpose output on some display modules to this value. Use on to set all outputs to high state, and off to set all to low state. The meaning of the integer value depends on your specific...
java
public static <T extends Entity<ID>, ID extends Serializable> T newInstance(Class<T> clazz, ID id) { return meta.newInstance(clazz, id); }
python
def load_manifest(data): """ Helper for loading a manifest yaml doc. """ if isinstance(data, dict): return data doc = yaml.safe_load(data) if not isinstance(doc, dict): raise Exception("Manifest didn't result in dict.") return doc
python
def _check_state(self): """Check if this instance can model and/or can invert """ if(self.grid is not None and self.configs.configs is not None and self.assignments['forward_model'] is not None): self.can_model = True if(self.grid is not None and ...
python
def inet_pton(address_family, ip_string): """ Windows compatibility shim for socket.inet_ntop(). :param address_family: socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6 :param ip_string: A unicode string of an IP address :return: A byte string of the network form of the...
java
private FieldType findForeignFieldType(Class<?> clazz, Class<?> foreignClass, Dao<?, ?> foreignDao) throws SQLException { String foreignColumnName = fieldConfig.getForeignCollectionForeignFieldName(); for (FieldType fieldType : foreignDao.getTableInfo().getFieldTypes()) { if (fieldType.getType() == foreignCla...
python
def task_search(self, task_str, **kwargs): """ Query for a subset of tasks by task_id. :param task_str: :return: """ self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -...
java
public final Object asyncInvokeNext(InvocationContext ctx, VisitableCommand command, CompletionStage<?> delay) { if (delay == null || CompletionStages.isCompletedSuccessfully(delay)) { return invokeNext(ctx, command); } return asyncValue(delay).thenApply...
java
@Override public String toJson(Object object) { CharBuf buffer = CharBuf.create(255); writeObject(object, buffer); return buffer.toString(); }
python
def access_token(self): """Stores always valid OAuth2 access token. Note: Accessing this property may result in HTTP request. Returns: str """ if (self._access_token is None or self.expiration_time <= int(time.time())): resp =...
java
void onHeartbeat(Member member, long timestamp) { if (!heartbeatAwareQuorumFunction) { return; } ((HeartbeatAware) quorumFunction).onHeartbeat(member, timestamp); }
python
def set_outlet(self, latitude, longitude, outslope): """ Adds outlet point to project """ self.project_manager.setOutlet(latitude=latitude, longitude=longitude, outslope=outslope)
python
def fetch_query_from_pgdb(self, qname, query, con, cxn, limit=None, force=False): """ Supply either an already established connection, or connection parameters. The supplied connection will override any separate cxn parameter :param qname: The name of the query to save the output to ...
java
synchronized void hungup(Date dateOfRemoval, HangupCause hangupCause, String hangupCauseText) { this.dateOfRemoval = dateOfRemoval; this.hangupCause = hangupCause; this.hangupCauseText = hangupCauseText; // update state and fire PropertyChangeEvent stateChanged(dateOfRemoval,...
java
public Integer getAllocationSize() { if(childNode.getAttribute("allocation-size") != null && !childNode.getAttribute("allocation-size").equals("null")) { return Integer.valueOf(childNode.getAttribute("allocation-size")); } return null; }
java
public String describe(final Cron cron) { Preconditions.checkNotNull(cron, "Cron must not be null"); final Map<CronFieldName, CronField> expressions = cron.retrieveFieldsAsMap(); final Map<CronFieldName, FieldDefinition> fieldDefinitions = cron.getCronDefinition().retrieveFieldDefinitionsAsMap()...
python
def subgraph(graph, nodes: Iterable[BaseEntity]): """Induce a sub-graph over the given nodes. :rtype: BELGraph """ sg = graph.subgraph(nodes) # see implementation for .copy() result = graph.fresh_copy() result.graph.update(sg.graph) for node, data in sg.nodes(data=True): resul...
python
def area_uuid_from_partial_uuid(self, partial_uuid): """ Given a partial UUID (a prefix), see if we have know about an Upload Area matching it. :param (str) partial_uuid: UUID prefix :return: a matching UUID :rtype: str :raises UploadException: if no or more than one UUID...
java
@PublicEvolving public <R> SingleOutputStreamOperator<R> reduce( ReduceFunction<T> reduceFunction, AllWindowFunction<T, R, W> function) { TypeInformation<T> inType = input.getType(); TypeInformation<R> resultType = getAllWindowFunctionReturnType(function, inType); return reduce(reduceFunction, function, ...
java
@Override @Deprecated public void setImageResource(int resId) { init(getContext()); mDraweeHolder.setController(null); super.setImageResource(resId); }
java
private static final String toUTF8String(byte[] b) { String ns = null; try { ns = new String(b, "UTF8"); } catch (UnsupportedEncodingException e) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Error converting to string;...
python
def _counter(self): """Current task counter.""" count = int(self._client.kv[self._counter_path]) count += 1 count_str = str(count).zfill(self._COUNTER_FILL) self._client.kv[self._counter_path] = count_str return count_str
java
public static EditableArray newArray( Object... values ) { BasicArray array = new BasicArray(); for (Object value : values) { array.addValue(value); } return new ArrayEditor(array, DEFAULT_FACTORY); }
java
private static Object[] removeRealReceiver(Object[] args) { Object[] ar = new Object[args.length-1]; System.arraycopy(args, 1, ar, 0, args.length - 1); return ar; }
python
def _select(self, params, handler=None): """ :param params: :param handler: defaults to self.search_handler (fallback to 'select') :return: """ # specify json encoding of results params['wt'] = 'json' custom_handler = handler or self.search_handler ...
python
def reset(self): """Expand to the full scale""" import ephem, MOPcoord sun=ephem.Sun() sun.compute(self.date.get()) self.sun=MOPcoord.coord((sun.ra,sun.dec)) doplot(kbos) self.plot_pointings()
java
public String[] getConditionInfos() { String[] conds = new String[conditions.size()]; synchronized (conditions) { int i = 0; for (Iterator iterator = this.conditions.iterator(); iterator.hasNext(); i++) { IObjectReference objRef = (IObjectReference) iterator.next(...
python
def get_distributions(self): """ Retrives the distributions installed on the library path of the environment :return: A set of distributions found on the library path :rtype: iterator """ pkg_resources = self.safe_import("pkg_resources") libdirs = self.base_path...
java
private boolean isValidTaxonomy(final String label, final Double score) { return !StringUtils.isBlank(label) || score != null; }
python
def validate(self): """Validate the suite.""" for context_name in self.context_names: context = self.context(context_name) try: context.validate() except ResolvedContextError as e: raise SuiteError("Error in context %r: %s" ...
python
def kuten_to_gb2312(kuten): """ Convert GB kuten / quwei form (94 zones * 94 points) to GB2312-1980 / ISO-2022-CN hex (internal representation) """ zone, point = int(kuten[:2]), int(kuten[2:]) hi, lo = hexd(zone + 0x20), hexd(point + 0x20) gb2312 = "%s%s" % (hi, lo) assert isinstance(g...
python
def _ValidateDataTypeDefinition(cls, data_type_definition): """Validates the data type definition. Args: data_type_definition (DataTypeDefinition): data type definition. Raises: ValueError: if the data type definition is not considered valid. """ if not cls._IsIdentifier(data_type_defi...
java
@SuppressWarnings({ "unused", "unchecked" }) private static void rewriteMergeData(String key, String subKey, NamedList<Object> snl, NamedList<Object> tnl) { if (snl != null) { Object o = tnl.get(key); NamedList<Object> tnnnl; if (o != null && o instanceof NamedList) { tnnnl = (Name...
java
public void removeHttpSession(HttpSession session) { if (session == activeSession) { activeSession = null; } synchronized (this.sessions) { this.sessions.remove(session); } this.model.removeHttpSession(session); session.invalidate(); }
java
public R jsonEqualTo(String path, Object value) { expr().jsonEqualTo(_name, path, value); return _root; }
java
public static Object delayedNull(CompletionStage<Void> stage) { // If stage was null - meant we didn't notify or if it already completed, no reason to create a stage instance if (stage == null || CompletionStages.isCompletedSuccessfully(stage)) { return null; } else { return asyncVal...
java
public Job copy(String destinationDataset, String destinationTable, JobOption... options) throws BigQueryException { return copy(TableId.of(destinationDataset, destinationTable), options); }
java
public void marshall(MessageTag messageTag, ProtocolMarshaller protocolMarshaller) { if (messageTag == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(messageTag.getName(), NAME_BINDING); ...
java
public Content throwsTagOutput(ThrowsTag throwsTag) { ContentBuilder body = new ContentBuilder(); Content excName = (throwsTag.exceptionType() == null) ? new RawHtml(throwsTag.exceptionName()) : htmlWriter.getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.MEMBER, ...
python
def check_feasibility(x_bounds, lowerbound, upperbound): ''' This can have false positives. For examples, parameters can only be 0 or 5, and the summation constraint is between 6 and 7. ''' # x_bounds should be sorted, so even for "discrete_int" type, # the smallest and the largest number should...
java
public SetDomainIpACLResponse setDomainIpACL(SetDomainIpACLRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config"); internalRequest.addParameter("ipA...
python
def save_credentials(self, profile): """ Saves credentials to a dotfile so you can open them grab them later. Parameters ---------- profile: str name for your profile (i.e. "dev", "prod") """ filename = profile_path(S3_PROFILE_ID, profile) cre...
java
@Trivial public static Map<String, ZipEntryData> setLocations(ZipEntryData[] entryData) { Map<String, ZipEntryData> entryDataMap = new HashMap<String, ZipEntryData>(entryData.length); for ( int entryNo = 0; entryNo < entryData.length; entryNo++ ) { ZipEntryData entry = entryData[entryNo]; ...
python
def _is_target_region(self, stat, game_region): """Returns if the stat matches target game region. :param stat: Json of gameplay stat. :type stat: dict :param game_region: Target game region. :type game_region: str :return: return does the stat...
python
def show_frontpage(self): """ If on a subreddit, remember it and head back to the front page. If this was pressed on the front page, go back to the last subreddit. """ if self.content.name != '/r/front': target = '/r/front' self.toggled_subreddit = self.c...
java
public void dispose() { if (fLabelDecorators != null) { for (int i = 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator = (ILabelDecorator) fLabelDecorators.get(i); decorator.dispose(); } fLabelDecorators = null; } // fStorageLabelProvider.dispose(); fImageLabelProvider.disp...
python
def transformation_get(node_id): """Get all the transformations of a node. The node id must be specified in the url. You can also pass transformation_type. """ exp = Experiment(session) # get the parameters transformation_type = request_parameter( parameter="transformation_type", ...
java
public FulltextMatch setPatterns( final Collection<String> patterns ) { if (patterns == null || patterns.size() == 0) { clearPatterns(); return this; } synchronized (patterns) { for (String pattern : patterns) { ...
python
def compile_rename_column(self, blueprint, command, connection): """ Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type co...
java
void doAnimate(float ratio) { Log.v(Log.SUBSYSTEM.WIDGET, TAG, "doAnimate(): animating %s", mTarget.getName()); animate(mTarget, ratio); if (mRequestLayoutOnTargetChange && mTarget.isChanged()) { mTarget.requestLayout(); } }
java
public EntranceProcessingItem setOutputStream(Stream outputStream) { if (this.outputStream != null && this.outputStream != outputStream) { throw new IllegalStateException("Cannot overwrite output stream of EntranceProcessingItem"); } else this.outputStream = outputStream; return this; }
python
def bind_to_env(self, bound_env): ''' Get a copy of the reverse, bound to `env` object. Can be found in env.root attribute:: # done in iktomi.web.app.Application env.root = Reverse.from_handler(app).bind_to_env(env) ''' return self.__class__(self._scope, ...
java
public static Map<String, String> getQueryParams () { Map<String, String> params = new HashMap<String, String>(); String search = getSearchString(); search = search.substring(search.indexOf("?")+1); String[] bits = search.split("&"); for (String bit : bits) { int ...
python
def startJVM(jvm=None, *args, **kwargs): """ Starts a Java Virtual Machine. Without options it will start the JVM with the default classpath and jvm. The default classpath will be determined by jpype.getClassPath(). The default JVM is determined by jpype.getDefaultJVMPath(). Args: jvm...
java
public void setCommerceDiscountUserSegmentRelService( com.liferay.commerce.discount.service.CommerceDiscountUserSegmentRelService commerceDiscountUserSegmentRelService) { this.commerceDiscountUserSegmentRelService = commerceDiscountUserSegmentRelService; }
python
def select_header_content_type(self, content_types): """ Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ if not content_types: return 'applicat...
python
def getcentresurl(idcentre, *args, **kwargs): """Request Centres URL. If idcentre is set, you'll get a response adequate for a MambuCentre object. If not set, you'll get a response adequate for a MambuCentres object. See mambucentre module and pydoc for further information. Currently implemented f...
java
public Method findFirstMethod( Pattern methodNamePattern ) { final Method[] allMethods = this.targetClass.getMethods(); for (int i = 0; i < allMethods.length; i++) { final Method m = allMethods[i]; if (methodNamePattern.matcher(m.getName()).matches()) { return m; ...
python
def validate(node, source): """Call this function to validate an AST.""" # TODO: leaving strict checking off to support insert_grad_of lf = LanguageFence(source, strict=False) lf.visit(node) return node
java
void createCardSource(@NonNull Card card) { final SourceParams cardSourceParams = SourceParams.createCardParams(card); final Observable<Source> cardSourceObservable = Observable.fromCallable( new Callable<Source>() { @Override ...
java
public static TaskQueueStatistics fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, TaskQueueStatistics.class); } catch (final JsonMappingException | JsonParseException e) { ...
python
def parents(self, term, recursive=False, **kwargs): """ Returns a list of all semantic types for the given term. If recursive=True, traverses parents up to the root. """ def dfs(term, recursive=False, visited={}, **kwargs): if term in visited: # Break on cyclic relations....
java
public static List<Method> getMethods(Class<?> clazz, final Class<? extends Annotation> annotation) { final List<Method> methods = new ArrayList<Method>(); traverseHierarchy(clazz, new TraverseTask<Method>() { @Override public Method run(Class<?> clazz) { Method[...
python
def render(self, context): """Render markdown.""" import markdown content = self.get_content_from_context(context) return markdown.markdown(content)
java
protected void skipBytes(InputStream in, int n) throws IOException { // IA VISIBILITY CHANGE FOR SUBCLASS USE while (n > 0) { int len = in.read(tmpbuf, 0, n < tmpbuf.length ? n : tmpbuf.length); if (len == -1) { throw new EOFException(); } n ...
java
public SimplePageable<T> with(int pageSize) { Assert.isTrue(pageSize > 0, "Page size [%d] must be greater than 0", pageSize); this.pageSize = pageSize; return this; }
java
public String asString() { try { return EntityUtils.toString( entity, PcsUtils.UTF8.name() ); } catch ( IOException e ) { throw new CStorageException( "Can't get string from HTTP entity", e ); } }
java
protected void layoutBlockInFlowAvoidFloats(BlockBox subbox, int wlimit, BlockLayoutStatus stat) { final int minw = subbox.getMinimalDecorationWidth(); //minimal subbox width for computing the space -- content is not considered (based on other browser observations) int yoffset = stat.y + floatY; //...
python
def plot_nb(self,xdata,ydata=[],logScale=False): '''Graphs a line plot and embeds it in a Jupyter notebook. See 'help(figure.plot)' for more info.''' self.plot(xdata,ydata,logScale)
python
def set_group_member_unorphan(self, member_id, unorphan_info): """ Make an orphan member trigger into an group trigger. :param member_id: Orphan Member Trigger id to be assigned into a group trigger :param unorphan_info: Only context and dataIdMap are used when changing back to a non-or...
java
public Observable<ServiceResponse<List<BatchLabelExample>>> batchWithServiceResponseAsync(UUID appId, String versionId, List<ExampleLabelObject> exampleLabelObjectArray) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and canno...
python
def help_text(self, name, text, text_kind='plain', trim_pfx=0): """ Provide help text for the user. This method will convert the text as necessary with docutils and display it in the WBrowser plugin, if available. If the plugin is not available and the text is type 'rst' then t...
java
public boolean isConnectionHandleAlive(ThriftConnectionHandle<T> connection) { boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // 反射调用ping方法 T client = null; if (this.thriftServiceType == ThriftServiceTyp...
python
def _construct_full_hostname(self, hostname): """Create a full (scheme included) hostname from the argument given. Only HTTP and HTTP+SSL protocols are allowed. Args: hostname: The hostname to use. Returns: The full hostname. Raises: ValueErr...
python
def decode_signed_value(self, name, value, max_age_days=None): """Do what `RequestHandler.get_secure_cookie` does(when `value` is not None), but with a more friendly name What opposite to it is `RequestHandler.create_signed_value` """ kwgs = {} if max_age_days is not Non...
java
public void setWarnings(java.util.Collection<Warning> warnings) { if (warnings == null) { this.warnings = null; return; } this.warnings = new java.util.ArrayList<Warning>(warnings); }
python
def begin(self): """Load variables from checkpoint. New model variables have the following name foramt: new_model_scope/old_model_scope/xxx/xxx:0 To find the map of name to variable, need to strip the new_model_scope and then match the old_model_scope and remove the suffix :0. """ variable...
java
public <K, V> PaginatedRequestBuilder<K, V> newPaginatedRequest(Key.Type<K> keyType, Class<V> valueType) { return new PaginatedRequestBuilderImpl<K, V>(newViewRequestParameters(keyType.getType(), valueType)); }
python
def from_las(cls, path=None, remap=None, funcs=None, data=True, req=None, alias=None, max=None, encoding=None, printfname=None): """ Constructor. Essentially just wraps ``Well.from_las()``, but is more convenient for most purposes. Args: path (str): The pat...
java
public static Map<String, Object> getAttributeMap(ServletRequest req) { if (req instanceof CmsFlexRequest) { return ((CmsFlexRequest)req).getAttributeMap(); } Map<String, Object> attrs = new HashMap<String, Object>(); Enumeration<String> atrrEnum = CmsCollectionsGenericWrapp...
java
public void registerScriptEngineWrapper(ScriptEngineWrapper wrapper) { logger.debug("registerEngineWrapper " + wrapper.getLanguageName() + " : " + wrapper.getEngineName()); this.engineWrappers.add(wrapper); setScriptEngineWrapper(getTreeModel().getScriptsNode(), wrapper, wrapper); setScriptEngineWrapper(g...
java
public static File downloadMedia(String accessToken, String mediaId) { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId; File mf = null; for (int i = 0; i < 3; i++) {...
python
def timestamp_feature(catalog, soup): """The datetime the xml file was last modified. """ catalog.timestamp = int(soup.coursedb['timestamp']) catalog.datetime = datetime.datetime.fromtimestamp(catalog.timestamp) logger.info('Catalog last updated on %s' % catalog.datetime)
java
public void setTransferTime(Parameter newTransferTime) { if (newTransferTime != transferTime) { NotificationChain msgs = null; if (transferTime != null) msgs = ((InternalEObject)transferTime).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.TIME_PARAMETERS__TRANSFER_TIME, null, msgs); if (newTr...