language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static String journalIdBytesToString(byte[] jid) { char[] charArray = new char[jid.length]; for (int i = 0; i < jid.length; i++) { charArray[i] = (char) jid[i]; } return new String(charArray, 0, charArray.length); }
python
def get_os_and_browsers(self): """ Get all supported OS/browser combinations JSON response """ resp = self.session.get(os.path.join(self.api_url, 'browsers.json')) resp = self._process_response(resp) return resp.json()
java
public com.google.api.ads.adwords.axis.v201809.cm.CustomParameters getAppUrlCustomParameters() { return appUrlCustomParameters; }
python
def extract_element_internationalized_comment(element): """ Extracts the xib element's comment, if the element has been internationalized. Args: element (element): The element from which to extract the comment. Returns: The element's internationalized comment, None if it does not exist, or...
python
def bitpos(self, key, bit, start=None, end=None): """Return the position of the first bit set to ``1`` or ``0`` in a string. The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the...
java
@CheckReturnValue public static Builder fromDriverManager(String url, Properties info) { return fromDriverManager(url, Flavor.fromJdbcUrl(url), info, null, null); }
java
public Image addImage(String listId, AddImageOptionalParameter addImageOptionalParameter) { return addImageWithServiceResponseAsync(listId, addImageOptionalParameter).toBlocking().single().body(); }
java
@Override public URLConnection openConnection(URL url) throws IOException { String path = url.getPath(); int resourceDelimiterIndex = path.indexOf("!/"); URLConnection conn; if (resourceDelimiterIndex == -1) { // The "jar" protocol requires that the path contain an entr...
java
protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Long expiresIn, Map<String, Object> response) { return new AccessGrant(accessToken, scope, refreshToken, expiresIn); }
python
def labelPoints(self, sr, polygons, ): """ The labelPoints operation is performed on a geometry service resource. The labelPoints operation calculates an interior point for each polygon specified in the input array. These inte...
java
public Object createSavepoint() throws TransactionException { SavePoints savePoints = new SavePoints(); for (TransactionStatus transactionStatus : transactionStatuses.values()) { savePoints.save(transactionStatus); } return savePoints; }
python
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the pow function.TensorFluent Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the pow function. ''' return...
python
def close(self): # type: () -> None ''' Close the PyCdlib object, and re-initialize the object to the defaults. The object can then be re-used for manipulation of another ISO. Parameters: None. Returns: Nothing. ''' if not self._initiali...
java
public void parseAndInject(String[] args, T injectee) throws InvalidCommandException { this.injectee = injectee; pendingInjections.clear(); Iterator<String> argsIter = Iterators.forArray(args); ImmutableList.Builder<String> builder = ImmutableList.builder(); while (argsIter.hasNext()) { Strin...
python
def do_glob_math(self, cont): """Performs #{}-interpolation. The result is always treated as a fixed syntactic unit and will not be re-evaluated. """ # TODO that's a lie! this should be in the parser for most cases. if not isinstance(cont, six.string_types): warn(Fu...
java
public IAtom configureMM2BasedAtom(IAtom atom, String hoseCode, boolean hetRing) throws NoSuchAtomTypeException { //logger.debug("CONFIGURE MM2 ATOM"); List<Pattern> atomTypePattern = null; MM2BasedAtomTypePattern atp = new MM2BasedAtomTypePattern(); atomTypePattern = atp.getAtomTypePatt...
python
def set_chat_photo( self, chat_id: Union[int, str], photo: str ) -> bool: """Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. You must be an administrator in the chat for this to work and must have the appropriate adm...
python
def orphans_single(default_exec=False): """Remove all orphans in the site, in the single user-mode.""" if not default_exec and executable.endswith('uwsgi'): # default_exec => rq => sys.executable is sane _executable = executable[:-5] + 'python' else: _executable = executable p = ...
python
def get_sections_2d_nts(self, sortby=None): """Get high GO IDs that are actually used to group current set of GO IDs.""" sections_2d_nts = [] for section_name, hdrgos_actual in self.get_sections_2d(): hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby) section...
python
def get_stp_mst_detail_output_msti_port_if_role(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") msti = ...
python
def get_context_data(self, **kwargs): """This adds into the context of breeding_type and sets it to Active.""" context = super(BreedingList, self).get_context_data(**kwargs) context['breeding_type'] = "Active" return context
python
def stop(self, signal=None): """Stop the heroku local subprocess and all of its children. """ signal = signal or self.int_signal self.out.log("Cleaning up local Heroku process...") if self._process is None: self.out.log("No local Heroku process was running.") ...
java
protected void appendFieldStart(StringBuilder buffer, String fieldName) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } }
java
@Override public List<CommerceShipmentItem> getCommerceShipmentItems(int start, int end) { return commerceShipmentItemPersistence.findAll(start, end); }
python
def get_authors(self, entry): """ Return the authors in HTML. """ try: return format_html_join( ', ', '<a href="{}" target="blank">{}</a>', [(author.get_absolute_url(), getattr(author, author.USERNAME_FIELD)) ...
python
def current_commit_parser() -> Callable: """Current commit parser :raises ImproperConfigurationError: if ImportError or AttributeError is raised """ try: parts = config.get('semantic_release', 'commit_parser').split('.') module = '.'.join(parts[:-1]) return getattr(importlib.im...
python
def getNode(self, name, **context): """Return tree node found by name""" if name == self.name: return self else: return self.getBranch(name, **context).getNode(name, **context)
java
private static Audit getSecurityAudit(JSONArray jsonArray, JSONArray global) { LOGGER.info("NFRR Audit Collector auditing STATIC_SECURITY_ANALYSIS"); Audit audit = new Audit(); audit.setType(AuditType.STATIC_SECURITY_ANALYSIS); Audit basicAudit; if ((basicAudit = doBasicAuditChe...
python
def raise_on_failure(mainfunc): """raise if and only if mainfunc fails""" try: errors = mainfunc() if errors: exit(errors) except CalledProcessError as error: exit(error.returncode) except SystemExit as error: if error.code: raise except Keyboa...
python
def move_folder(self, to_folder): """ Change this folder name :param to_folder: folder_id/ContactFolder to move into :type to_folder: str or ContactFolder :return: Moved or Not :rtype: bool """ if self.root: return False if not to_folder: ...
python
def fit_rmsd(ras, rbs, weights=None): """Fit geometry rbs onto ras, returns more info than superpose Arguments: | ``ras`` -- a numpy array with 3D coordinates of geometry A, shape=(N,3) | ``rbs`` -- a numpy array with 3D coordinates of geometry B, ...
java
public int compare(NUMERICTYPE value1, NUMERICTYPE value2) { if (this.performCalculationsAsDoublePrimitive) { double v1 = value1.doubleValue(); double v2 = value2.doubleValue(); return Double.compare(v1, v2); } else { // evaluate as long ...
python
def creator(_, config): """Creator function for creating an instance of a Packer image script.""" packer_script = render(config.script, model=config.model, env=config.env, variables=config.variables, item=config.item) filename = "packer.dry.run.see.comment" ...
java
public static vpnvserver_vpnsessionpolicy_binding[] get(nitro_service service, String name) throws Exception{ vpnvserver_vpnsessionpolicy_binding obj = new vpnvserver_vpnsessionpolicy_binding(); obj.set_name(name); vpnvserver_vpnsessionpolicy_binding response[] = (vpnvserver_vpnsessionpolicy_binding[]) obj.get_re...
java
public ArrayList<OvhSiteBuilderDomain> packName_siteBuilderStart_options_domains_GET(String packName) throws IOException { String qPath = "/pack/xdsl/{packName}/siteBuilderStart/options/domains"; StringBuilder sb = path(qPath, packName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(re...
java
public static IAtomContainer skeleton(IAtomContainer src) { IChemObjectBuilder builder = src.getBuilder(); IAtom[] atoms = new IAtom[src.getAtomCount()]; IBond[] bonds = new IBond[src.getBondCount()]; for (int i = 0; i < atoms.length; i++) { atoms[i] = builder.newInstance(...
java
static SQLiteConnection open(SQLiteConnectionPool pool, SQLiteDatabaseConfiguration configuration, int connectionId, boolean primaryConnection) { SQLiteConnection connection = new SQLiteConnection(pool, configuration, connectionId, primaryConnection); try { ...
python
def dump (env, form): """Log environment and form.""" for var, value in env.items(): log(env, var+"="+value) for key in form: log(env, str(formvalue(form, key)))
python
def build_interfaces_by_method(interfaces): """ Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['jso...
python
def authenticate(self): """authenticate the user with the Kaggle API. This method will generate a configuration, first checking the environment for credential variables, and falling back to looking for the .kaggle/kaggle.json configuration file. """ config_data ...
java
public CreateSubnetResponse createSubnet(CreateSubnetRequest request) throws BceClientException { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); } che...
java
public Observable<ServiceResponse<UUID>> addClosedListWithServiceResponseAsync(UUID appId, String versionId, ClosedListModelCreateObject closedListModelCreateObject) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be...
python
def discard_saved_state(self, f_remove_file): """Forcibly resets the machine to "Powered Off" state if it is currently in the "Saved" state (previously created by :py:func:`save_state` ). Next time the machine is powered up, a clean boot will occur. This operation is equivalent ...
python
def rule_command_cmdlist_interface_s_interface_fc_leaf_interface_fibrechannel_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") ...
python
def keyPressEvent(self, event): """ Handles the key press event. When the user hits F5, the current code edit will be executed within the console's scope. :param event | <QtCore.QKeyEvent> """ if event.key() == QtCore.Qt.Key_F5 or \ (even...
java
@Override public Class<?> getInvokedBusinessInterface() throws IllegalStateException { // Determine if in valid state for this method. boolean validState = false; int stateCopy; synchronized (this) { stateCopy = state; validState = (state == POOLED) || (state ...
java
@Override public Object invoke(String methodName, Object argument, Type returnType) throws Throwable { return invoke(methodName, argument, returnType, new HashMap<String, String>()); }
java
public void deleteProject(CmsDbContext dbc, CmsProject deleteProject) throws CmsException { deleteProject(dbc, deleteProject, true); }
java
protected AstNode parseIgnorableStatement( DdlTokenStream tokens, String name, AstNode parentNode, String mixinType ) { CheckArg.isNotNull(tokens, "tokens"); Check...
java
@Override public void serialize(final DataOutput pOutput) throws TTIOException { try { pOutput.writeInt(IConstants.DATABUCKET); pOutput.writeLong(mBucketKey); pOutput.writeLong(mLastBucketKey); for (final IData data : getDatas()) { if (data == ...
python
def _set_active_on(self, v, load=False): """ Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_on is considered as a private method. Backends looking to popula...
java
public void free() { if (m_messageMap != null) { for (BaseMessageQueue messageQueue : m_messageMap.values()) { if (messageQueue != null) { // Don't worry about removing these, since you are removing them all. messageQu...
java
protected List<FileSource> getFiles(){ this.clear(); File f = this.source.asFile(); List<FileSource> ret = this.doScan(f); this.doInfo(); return ret; }
java
public List<Message> getFilteredList( EMessageType messageType, Long fromTsMillis, Long toTsMillis, long limit ) throws Exception { String tableName = TABLE_MESSAGES; String sql = "select " + getQueryFieldsString() + " from " + tableName; List<String> wheresList = new ArrayList<>();...
java
public DayOfTheWeek next() { if (this == PH) { return null; } final int nextId = id + 1; if (nextId == PH.id) { return MON; } for (final DayOfTheWeek dow : ALL) { if (dow.id == nextId) { return dow; } ...
java
protected String consumeQuoted(ImapRequestLineReader request) throws ProtocolException { // The 1st character must be '"' consumeChar(request, '"'); StringBuilder quoted = new StringBuilder(); char next = request.nextChar(); while (next != '"') { if (next...
java
public static Date subWeeks(@NotNull final Date date, int amount) { return DateUtils.addWeeks(date, -amount); }
java
@Override public CompletableFuture<List<Map.Entry<UUID, Long>>> getNext() { return this.indexIterator .getNext() .thenApply(this::mix); }
java
public float[] percentilesFloat(double[] pcts) { readWriteLock.readLock().lock(); try { float[] results = new float[pcts.length]; long total = count; int pctIdx = 0; long prev = 0; double prevP = 0.0; double prevB = lowerLimit; for (int i = 0; i < numBuckets; ++i) ...
java
public final UdpServer runOn(LoopResources channelResources, InternetProtocolFamily family) { return new UdpServerRunOn(this, channelResources, false, family); }
python
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: import /templates/import export /templates/export """ if which: return '{0}/{1}'.format( ...
python
def xpathNextNamespace(self, ctxt): """Traversal function for the "namespace" direction the namespace axis contains the namespace nodes of the context node; the order of nodes on this axis is implementation-defined; the axis will be empty unless the context node is an ele...
java
@Override public CreateTagOptionResult createTagOption(CreateTagOptionRequest request) { request = beforeClientExecution(request); return executeCreateTagOption(request); }
java
private URL getUrl() { ClassLoader loader = null; try { loader = Thread.currentThread().getContextClassLoader(); } catch (Exception e) { // do nothing } if (loader == null) { loader = ClassPathResource.class.getClassLoader(); } ...
python
def slice_shape(self, tensor_shape): """Shape of each slice of the Tensor. Args: tensor_shape: Shape. Returns: list of integers with length tensor_shape.ndims. Raises: ValueError: If a Tensor dimension is not divisible by the corresponding Mesh dimension. """ tensor_...
java
public static PIXConsumerAuditor getAuditor() { AuditorModuleContext ctx = AuditorModuleContext.getContext(); return (PIXConsumerAuditor)ctx.getAuditor(PIXConsumerAuditor.class); }
java
public void remove(Object data, int iOpenMode) throws DBException, RemoteException { synchronized(m_objSync) { m_tableRemote.remove(data, iOpenMode); } }
python
def load_secrets(self, secret_path): """render secrets into config object""" self._config = p_config.render_secrets(self.config_path, secret_path)
python
def get_cas_client(service_url=None, request=None): """ initializes the CASClient according to the CAS_* settigs """ # Handle CAS_SERVER_URL without protocol and hostname server_url = django_settings.CAS_SERVER_URL if server_url and request and server_url.startswith('/'): scheme = re...
python
def _get_tau(self, imt, mag): """ Returns the inter-event standard deviation (tau) """ return TAU_EXECUTION[self.tau_model](imt, mag, self.TAU)
python
def _maybe_end_of_stmt_list(attr_value): """If `attr_value` is a non-empty iterable, return its final element.""" if (attr_value is not None) and isinstance(attr_value, Iterable): result = list(attr_value) if len(result) > 0: return result[-1] return None
python
def asr_breaking(self, tol_eigendisplacements=1e-5): """ Returns the breaking of the acoustic sum rule for the three acoustic modes, if Gamma is present. None otherwise. If eigendisplacements are available they are used to determine the acoustic modes: selects the bands correspon...
java
@Override public String toNormalizedString() { String result; if(hasNoStringCache() || (result = getStringCache().normalizedString) == null) { getStringCache().normalizedString = result = toNormalizedString(IPv6StringCache.normalizedParams); } return result; }
java
@Override public CommerceCountry removeByG_N(long groupId, int numericISOCode) throws NoSuchCountryException { CommerceCountry commerceCountry = findByG_N(groupId, numericISOCode); return remove(commerceCountry); }
python
def init_db_conn(connection_name, connection_string, scopefunc=None): """ Initialize a postgresql connection by each connection string defined in the configuration file """ engine = create_engine(connection_string) session = scoped_session(sessionmaker(), scopefunc=scopefunc) session.configu...
java
public void terminateSubscription(IoSession session, String heapUri, String subscriptionId, Subscription.CloseReason reason) { Lock heapUpdateLock = null; try { HeapState state = heapStates.get(heapUri); if (state != null) { heapUpdateLock = state.getUpdateLock();...
java
public void createPath (Array<T> waypoints) { if (waypoints == null || waypoints.size < 2) throw new IllegalArgumentException("waypoints cannot be null and must contain at least two (2) waypoints"); segments = new Array<Segment<T>>(waypoints.size); pathLength = 0; T curr = waypoints.first(); T prev = null...
java
public final Operation rollbackNodePoolUpgrade( String projectId, String zone, String clusterId, String nodePoolId) { RollbackNodePoolUpgradeRequest request = RollbackNodePoolUpgradeRequest.newBuilder() .setProjectId(projectId) .setZone(zone) .setClusterId(clusterI...
python
def output(self): """ Returns the target output for this task. In this case, a successful execution of this task will create a file in HDFS. :return: the target output for this task. :rtype: object (:py:class:`~luigi.target.Target`) """ return luigi.contrib.hdfs....
java
@Override public KType get(int index) { assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ")."; return Intrinsics.<KType> cast(buffer[index]); }
java
public boolean refine( EllipseRotated_F64 ellipse ) { if( autoRefine ) throw new IllegalArgumentException("Autorefine is true, no need to refine again"); if( ellipseRefiner == null ) throw new IllegalArgumentException("Refiner has not been passed in"); if (!ellipseRefiner.process(ellipse,ellipse)) { retu...
python
def display_slitlet_arrangement(fileobj, grism=None, spfilter=None, bbox=None, adjust=None, geometry=None, debugplot=0): """...
java
public ServiceFuture<BuildInner> queueBuildAsync(String resourceGroupName, String registryName, QueueBuildRequest buildRequest, final ServiceCallback<BuildInner> serviceCallback) { return ServiceFuture.fromResponse(queueBuildWithServiceResponseAsync(resourceGroupName, registryName, buildRequest), serviceCallbac...
java
@Override public DescribeLogStreamsResult describeLogStreams(DescribeLogStreamsRequest request) { request = beforeClientExecution(request); return executeDescribeLogStreams(request); }
python
def _convert_punctuation( line ): ''' Converts given analysis line if it describes punctuation; Uses the set of predefined punctuation conversion rules from _punctConversions; _punctConversions should be a list of lists, where each outer list stands for a single conversion rule an...
java
public static UpdateResult update(String accessToken, UpdateDiscount updateDiscount) { return update(accessToken, JsonUtil.toJSONString(updateDiscount)); }
java
private void write(JSONArray jsonarray) throws JSONException { // JSONzip has three encodings for arrays: // The array is empty (zipEmptyArray). // First value in the array is a string (zipArrayString). // First value in the array is not a string (zipArrayValue). boolean stringy = false; int length = ...
python
def _get_filter(self, features): """ Gets the filter for the features in the object :param features: The features of the syslog file """ # This chops the features up into smaller lists so the api can handle them for ip_batch in (features['ips'][pos:pos + self.ip_query_b...
python
def save_data(self, trigger_id, **data): """ let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the sa...
python
def form_valid(self, form): """Override of CreateView method, sends the email.""" LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('ter...
java
public static void capture(Logger logger, Object callingObject, String methodName, FFDCProbeId probeId, Throwable throwable, Object[] data) { long ffdcTimestamp = System.currentTimeMillis(); final String className = logger.getName(); final StringBuilder sb = new StringBuilder(); sb.append("Level: ...
java
private Collection<Path> pathsInBetweenOf(final Path pParent, final Path pChild) { final Deque<Path> hierarchy = new LinkedList<>(); Path p = pChild.getParent(); while (!p.equals(pParent)) { hierarchy.addFirst(p); p = p.getParent(); } return hierarchy; ...
python
def get(input_dict, environment_dict): """ <Purpose> Gets the specified vessels. <Arguments> input_dict: The commanddict representing the user's input. environment_dict: The dictionary representing the current seash environment. <Side Effects> Connects to the Clearingh...
java
public static void e(com.couchbase.lite.LogDomain domain, String formatString, Throwable tr, Object... args) { String msg; try { msg = String.format(formatString, args); msg = String.format("%s (%s)", msg, tr.toString()); } catch (Exception e) { msg = ...
python
def bind(self, queue='', exchange='', routing_key='', virtual_host='/', arguments=None): """Bind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name ...
java
@Override protected void log(final String msg) { if (config.getLogLevel().equals(LogLevel.DEBUG)) { logger.debug(msg); } else if (config.getLogLevel().equals(LogLevel.TRACE)) { logger.trace(msg); } else if (config.getLogLevel().equals(LogLevel.INFO)) { log...
java
public ResolvableType getSuperType() { Class<?> resolved = resolve(); if (resolved == null || resolved.getGenericSuperclass() == null) { return NONE; } if (this.superType == null) { this.superType = forType(SerializableTypeWrapper.forGenericSuperclass(resolved), asVariableResolver()); } return th...
java
public RecordWriter<K,VariantContextWritable> getRecordWriter( TaskAttemptContext ctx, Path out) throws IOException { if (this.header == null) throw new IOException( "Can't create a RecordWriter without the VCF header"); final boolean wh = ctx.getConfiguration().getBoolean( WRITE_HEADER_PROPERTY, t...
java
protected void populateRuleStack( LinkedList<OptimizerRule> ruleStack, PlanHints hints ) { ruleStack.addFirst(ReorderSortAndRemoveDuplicates.INSTANCE); ruleStack.addFirst(RewritePathAndNameCriteria.INSTANCE); if (hints.hasSubqueries) { ruleStack....
python
def nas_command(f): """ indicate it's a command of nas command run with ssh :param f: function that returns the command in list :return: command execution result """ @functools.wraps(f) def func_wrapper(self, *argv, **kwargs): commands = f(self, *argv, **kwargs) return self.ssh...