language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public int getConnectedLonePairsCount(IAtom atom) { int count = 0; for (int i = 0; i < lonePairCount; i++) { if (lonePairs[i].contains(atom)) ++count; } return count; }
python
def multiline_frame_function(frame_function: types.FrameFunction, height: int, offset: int = 0, *args, **kwargs) -> types.FrameGenerator: """Multiline a singlelined frame function. Simply chains sever...
java
public boolean isSarlBehavior(LightweightTypeReference type) { return !type.isInterfaceType() && (getSarlElementEcoreType(type) == SarlPackage.SARL_BEHAVIOR || type.isSubtypeOf(Behavior.class)); }
python
def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed": """ Build a new feed by restricting this one to only the stops, trips, shapes, etc. used by the routes with the given list of route IDs. Return the resulting feed. """ # Initialize the new feed as the old feed. # Restr...
java
@SuppressWarnings("unchecked") public Object[] getEnumValues() { if (this.kind != Kind.ENUM) throw new RuntimeException("getEnumValues() can only be called on an enum"); try { return MappingUtil.getEnumValues((Class<? extends Enum<?>>) getRawType()); } catch (ClassNotFoundException e) { throw new Runtim...
java
public void sendConfigurationForm(Form form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { MUCOwner iq = new MUCOwner(); iq.setTo(room); iq.setType(IQ.Type.set); iq.addExtension(form.getDataFormToSend()); connection.createStanzaCol...
java
public void start() { if (outputThread != null) { outputThread.start(); } if (errorThread != null) { errorThread.start(); } if (inputThread != null) { inputThread.start(); } }
python
def preferred_forms_check(text, list, err, msg, ignore_case=True, offset=0, max_errors=float("inf")): """Build a checker that suggests the preferred form.""" if ignore_case: flags = re.IGNORECASE else: flags = 0 msg = " ".join(msg.split()) errors = [] ...
python
def add_route(self, template, controller, **kwargs): """ Add a route definition `controller` can be either a controller instance, or the name of a callable that will be imported. """ if isinstance(controller, basestring): controller = pymagic.import_name(cont...
java
@Override public List<CommerceOrderNote> findAll(int start, int end) { return findAll(start, end, null); }
java
public Process exec(String namespace, String name, String[] command, boolean stdin) throws ApiException, IOException { return exec(namespace, name, command, null, stdin, false); }
python
def list_filters(self): """Lists available filters in a readable DataFrame format. Returns: pd.DataFrame: Frame listing available filters. """ def _row_gen(attributes): for attr in attributes.values(): yield (attr.name, attr.type, attr.descriptio...
python
def action_findip(reader, *args): """Find Flow Log records involving a specific IP or IPs.""" target_ips = set(args) for record in reader: if (record.srcaddr in target_ips) or (record.dstaddr in target_ips): print(record.to_message())
python
def WrapCFTypeInPython(self, obj): """Package a CoreFoundation object in a Python wrapper. Args: obj: The CoreFoundation object. Returns: One of CFBoolean, CFNumber, CFString, CFDictionary, CFArray. Raises: TypeError: If the type is not supported. """ obj_type = self.dll.CFGet...
python
def update_thresh(self): """Emits a Qt signal thresholdUpdated with the current threshold value""" thresh_val = self.threshLine.value() self.threshold_field.setValue(thresh_val) self.thresholdUpdated.emit(thresh_val, self.getTitle())
python
def authorize(self): """Send this ticket to AFIP for authorization.""" request = self.__create_request_xml() request = self.__sign_request(request) request = b64encode(request).decode() client = clients.get_client('wsaa', self.owner.is_sandboxed) try: raw_res...
python
def tab_change(self, event): """When tab changes remove error, and enable widget if on url tab""" self.remove_error() if event.new == 1: self.widget.disabled = False
java
@Override public EClass getIfcClassification() { if (ifcClassificationEClass == null) { ifcClassificationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(96); } return ifcClassificationEClass; }
python
def process(self, content): """ Process (marshal) the tag with the specified value using the optional type information. @param content: The content to process. @type content: L{Object} """ log.debug('processing:\n%s', content) self.reset() if conte...
python
def _generate_date_with_wildcard_query(self, date_value): """Helper for generating a date keyword query containing a wildcard. Returns: (dict): The date query containing the wildcard or an empty dict in case the date value is malformed. The policy followed here is quite conservativ...
python
async def createSecret(self, *args, **kwargs): """ Create new Secret Insert a secret into the secret storage. The supplied secrets will be provided verbatime via `getSecret`, while the supplied scopes will be converted into credentials by `getSecret`. This method is no...
python
def is_younger(path, age): """ :param str|None path: Path to file :param int|float age: How many seconds to consider the file too old :return bool: True if file exists and is younger than 'age' seconds """ try: return time.time() - os.path.getmtime(path) < age except (OSError, TypeE...
java
public int[] getTrace (String base) throws CompoundNotFoundException { if (base.equals("A")) { return A; } else if (base.equals("C")) { return C; } else if (base.equals("G")) { return G; } else if (base.equals("T")) { return T; } else { throw new CompoundNotFoundException("Don't know base: " + ...
python
def get_module_part(dotted_name, context_file=None): """given a dotted name return the module part of the name : >>> get_module_part('astroid.as_string.dump') 'astroid.as_string' :type dotted_name: str :param dotted_name: full name of the identifier we are interested in :type context_file: st...
python
def enable_request_loader(): """ Enable request loader Optional user loader based on incomin request object. This is useful to enable on top of default user loader if you want to authenticate API requests via bearer token header. :return: """ @login_manager.request_loader def load_us...
python
def parse_plays_stream(self): """Generate and yield a stream of parsed plays. Useful for per play processing.""" lx_doc = self.html_doc() if lx_doc is not None: parser = PlayParser(self.game_key.season, self.game_key.game_type) plays = lx_doc.xpath('//tr[@class =...
java
public char[] getCurrentSegment() { /* Since the intention of the caller is to directly add stuff into * buffers, we should NOT have anything in shared buffer... ie. may * need to unshare contents. */ if (mInputStart >= 0) { unshare(1); } else { ...
python
def get(self): """ Constructs a TaskActionsContext :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext """ return TaskActionsContext( self._version, ...
java
void analyseRevision(R revision, List<E> previous) { if (currentRevision == null) { return; } if (previous == null || previous.isEmpty()) { resolveRemainingToCurrent(); } else { resolveToCurrent(DiffUtils.diff(currentRevisionContent, previous).get...
java
public Entry get( String path ) { if ( path.startsWith( "/" ) ) { path = path.substring( 1 ); } if ( path.length() == 0 ) { return root; } String[] parts = path.split( "/" ); if ( parts.length == 0 ) { return...
java
private byte[] loadIntern(final ChunkCacheKey key) throws IOException { final String fileName = key.getFileName(); final long chunkId = key.getChunkId(); //needs to be long to upcast following operations int bufferSize = key.getBufferSize(); final long seekTo = chunkId * bufferSize; final ...
python
def find(self, *args, **kwargs): """Create a :class:`MotorCursor`. Same parameters as for PyMongo's :meth:`~pymongo.collection.Collection.find`. Note that ``find`` does not require an ``await`` expression, because ``find`` merely creates a :class:`MotorCursor` without performing...
java
public static Iterable<Element> elementIterable(final Element element, final String name) { return new Iterable<Element>() { public Iterator<Element> iterator() { return elementIterator(element, name); } }; }
python
def post_request( self, alias, uri, data=None, json=None, params=None, headers=None, files=None, allow_redirects=None, timeout=None): """ Send a POST request on the session object found using ...
python
def create_async_sns_topic(self, lambda_name, lambda_arn): """ Create the SNS-based async topic. """ topic_name = get_topic_name(lambda_name) # Create SNS topic topic_arn = self.sns_client.create_topic( Name=topic_name)['TopicArn'] # Create subscriptio...
python
def __callHandler(self, callback, event, *params): """ Calls a "pre" or "post" handler, if set. @type callback: function @param callback: Callback function to call. @type event: L{ExceptionEvent} @param event: Breakpoint hit event. @type params: tuple ...
java
@Deprecated public void setAccessExpiresIn(String expiresInSecsFromNow) { checkUserSession("setAccessExpiresIn"); if (expiresInSecsFromNow != null) { long expires = expiresInSecsFromNow.equals("0") ? 0 : System.currentTimeMillis() + Long.parseLong(expiresInSecsFromNow...
python
def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0): ''' Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 ...
java
AmqpClient closeConnection(int replyCode, String replyText, int classId, int methodId1) { this.closeConnection(replyCode, replyText, classId, methodId1, null, null); return this; }
python
def get_yield_stress(self, n): """ Gets the yield stress for a given direction Args: n (3x1 array-like): direction for which to find the yield stress """ # TODO: root finding could be more robust comp = root(self.get_stability_criteria, -1, ar...
java
public void prapareForInferred() { log.info("Adding additional axioms to calculate inferred axioms"); int key = 0; int numNf3 = 0; int numNf8 = 0; for(final IntIterator itr = ontologyNF2.keyIterator(); itr.hasNext();) { MonotonicCollection<NF2> nf2s = ontolog...
python
def hash(self): """Returns a hash of the cursor as an int.""" if not hasattr(self, '_hash'): self._hash = conf.lib.clang_hashCursor(self) return self._hash
java
public final int end(int id) { MemReg b = bounds(id); if(b == null) return -1; return b.out - offset; }
java
public List<IssueCategory> getCategories(int projectID) throws RedmineException { return transport.getChildEntries(Project.class, Integer.toString(projectID), IssueCategory.class); }
java
public CredentialsConfig getResolvingCredentialsConfig() { if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) { return getResolverCredentialsConfig(); } if (deployerCredentialsConfig != null) { return getDeployerCredentialsConfig()...
java
@Override public Protos.TaskInfo launch(Protos.SlaveID slaveId, MesosResourceAllocation allocation) { ContaineredTaskManagerParameters tmParams = params.containeredParameters(); final Configuration dynamicProperties = new Configuration(); // incorporate the dynamic properties set by the template dynamicProp...
java
Type readType(int i) { int index = poolIdx[i]; return sigToType(buf, index + 3, getChar(index + 1)); }
python
def cmd_shodan(ip, no_cache, verbose, output): """Simple shodan API client. Prints the JSON result of a shodan query. Example: \b $ habu.shodan 8.8.8.8 { "hostnames": [ "google-public-dns-a.google.com" ], "country_code": "US", "org": "Google", ...
python
def check_pow(block_number, header_hash, mixhash, nonce, difficulty): """Check if the proof-of-work of the block is valid. :param nonce: if given the proof of work function will be evaluated with this nonce instead of the one already present in the header :returns: `True...
java
@Override public ListCertificatesResult listCertificates(ListCertificatesRequest request) { request = beforeClientExecution(request); return executeListCertificates(request); }
python
def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ ...
java
public static boolean isWebcamPresent(){ try { Webcam.getDefault(WebcamConstants.DEFAULT_WEBCAM_LOOKUP_TIMEOUT); return true; } catch (Throwable exception) { LOG.debug("Problem occurred when detecting the webcam. Returning false.", exception); return false...
java
private boolean isInMultipleLvalueDecl(Var v) { Token declarationType = v.declarationType(); switch (declarationType) { case LET: case CONST: case VAR: Node nameDecl = NodeUtil.getEnclosingNode(v.getNode(), NodeUtil::isNameDeclaration); return NodeUtil.findLhsNodesInNode(nameDe...
python
def fit(self, X, C): """ Fit a filter tree classifier Note ---- Shifting the order of the classes within the cost array will produce different results, as it will build a different binary tree comparing different classes at each node. Par...
java
@Pure public static boolean intersectsSphereCapsule( double sphereCenterx, double sphereCentery, double sphereCenterz, double sphereRadius, double capsuleAx, double capsuleAy, double capsuleAz, double capsuleBx, double capsuleBy, double capsuleBz, double capsuleRadius) { // Compute (squared) distance bet...
python
def read_namespaced_replication_controller_scale(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replication_controller_scale # noqa: E501 read scale of the specified ReplicationController # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
java
public String retrieveEndpointName(J2EEName j2eeName) { for (Entry<String, J2EEName> entry : endpointNameJ2EENameMap.entrySet()) { if (entry.getValue().equals(j2eeName)) { return entry.getKey(); } } return null; }
python
def put (self, ch): '''This puts a characters at the current cursor position. ''' if isinstance(ch, bytes): ch = self._decode(ch) self.put_abs (self.cur_r, self.cur_c, ch)
java
public static AuditEncryptionImpl getInstance(String keyStoreName, String keyStorePath, String keyStoreType, String keyStoreProvider, String keyStorePassword, String keyAlias) throws AuditEncryptionException { try { if (ae == null) ae...
java
public int getMessageSizeForPriorityCalc() { int size = getMessageSize(); for (TransactionInput input : inputs) { // 41: min size of an input // 110: enough to cover a compressed pubkey p2sh redemption (somewhat arbitrary). int benefit = 41 + Math.min(110, input.getSc...
java
@Override protected void informSynchronizations(boolean isCompleting) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "informSynchronizations: isCompleting="+isCompleting); ensureActive(); boolean shouldContinue = true; if (_stat...
java
private void validateTimeoutCallbackMethod(BeanMetaData bmd, MethodMap.MethodInfo methodInfo) // d666251 throws EJBConfigurationException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "validateTimeoutC...
python
def get_comment_group_for_path(self, pathname, default_content_type=None): """ Obtains the comment group for a specified pathname. :param pathname: The path for which the comment group will be obtained. :return: Returns the comment group for the specified pathnam...
python
def curve_primitive(self): """`Primitive` of the super-helical curve.""" curve = self.curve curve.axis_start = self.helix_start curve.axis_end = self.helix_end coords = curve.get_coords( n_points=(self.num_monomers + 1), spacing=self.minor_rise_per_residue) if...
java
public static String getCaller() { StackTraceElement[] stes = new Exception().getStackTrace(); String caller; if (stes.length > 2) { StackTraceElement callerSte = stes[2]; caller = callerSte.getClassName() + "." + callerSte.getMethodName(); } else { caller = "<unknown>"; } return caller; }
python
def connection_info_and_slot(target_node_info): """Process the input `target_node_info` entry which may be a libpq connection string or uri, or a dict containing key:value pairs of connection info entries or just the connection string with a replication slot name. Return the connection info dict and a ...
python
def _perform_replacements(self, chars): ''' Performs simple key/value string replacements that require no logic. This is used to convert the fullwidth rōmaji, several ligatures, and the punctuation characters. ''' for n in range(len(chars)): char = chars[n] ...
python
def create_bravado_core_config(settings): """Create a configuration dict for bravado_core based on pyramid_swagger settings. :param settings: pyramid registry settings with configuration for building a swagger schema :type settings: dict :returns: config dict suitable for passing into ...
java
public void interrupt() { if (!aborted) { aborted = true; if (executeThread != null) { executeThread.interrupt(); } if(helperExecutable != null) { helperExecutable.interrupt(); } } }
java
public static void addSpanErrorInfo(Span span, Throwable exception) { String methodName = "addSpanErrorInfo"; span.setTag(Tags.ERROR.getKey(), true); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName + " error", Boolean.TRUE); } ...
python
def get_hostinfo(self,callb=None): """Convenience method to request the device info from the device This will request the information from the device and request that callb be executed when a response is received. The is no default callback :param callb: Callable to be used when the r...
java
public CompletableFuture<CopycatServer> bootstrap(Collection<Address> cluster) { return start(() -> cluster().bootstrap(cluster)); }
java
public void prepareUpdateStep1b() { if (!isInitialized()) { return; } if ((m_dbUpdateThread != null) && (m_dbUpdateThread.isFinished())) { // update is already finished, just wait for client to collect final data return; } if (m_dbUpdateThre...
python
def _read_keyvals(filename): """Read the key/values if the file exists. returns -- a dictionary with key/values, or empty dictionary if the file does not exist. """ assert isinstance(filename, str) if os.path.exists(filename): return _KeyValuePers...
python
def label_tree(n,lookup): '''label tree will again recursively label the tree :param n: the root node, usually d3['children'][0] :param lookup: the node/id lookup ''' if len(n["children"]) == 0: leaves = [lookup[n["node_id"]]] else: leaves = reduce(lambda ls, c: ls + label_tree(c...
python
async def post(self, public_key=None): """Creates new offer Accepts: - buyer public key - cid - buyer access string Returns: - offer parameters as dictionary """ if settings.SIGNATURE_VERIFICATION: super().verify() try: body = json.loads(self.request.body) except: self.set_status(40...
python
def update_experiment(): '''Update the experiment status in config file''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: return None for key in experiment_dict.keys(): if isinstance(experiment_dict[key], dict): ...
java
private static String openTag(String tag, String clazz, String style, boolean contentIsHtml, String... content) { StringBuilder result = new StringBuilder("<").append(tag); if (clazz != null && !"".equals(clazz)) { result.append(" ").append(Html.Attribute.CLASS).append("='").append(clazz).append("'"); } i...
java
public static void setState(ParseState state) { if (state == null) { System.err.println("Null state found"); Environment.logInfo("Null state found"); } persData.setProperty(state.filename, state.firstLine + SEPARATOR + state.offset); }
python
def get_object(self): """Implements the GetObjectMixin interface and calls :meth:`DBObjectMixin.get_query`. Using this mixin requires usage of a response handler capable of serializing SQLAlchemy query result objects. :returns: Typically a SQLALchemy Query result. :rtype: mixed...
java
static VcfSliceProtos.Fields buildDefaultFields(List<Variant> variants) { return buildDefaultFields(variants, null, null); }
python
def _convert_to_cwl_json(data, fnargs, input_files): """Convert world data object (or list of data objects) into outputs for CWL ingestion. """ out = {} for outvar in _get_output_cwl_keys(fnargs): keys = [] for key in outvar.split("__"): try: key = int(key) ...
java
public static Image getInstance(int width, int height, boolean reverseBits, int typeCCITT, int parameters, byte[] data, int transparency[]) throws BadElementException { if (transparency != null && transparency.length != 2) throw new BadElementException( "Transparency length must be equal to 2 with CCITT...
python
def parse_rule(cls, txt): """Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance. """ types = {"glob": GlobRule, "regex": RegexRul...
java
public <T, V extends Comparable<T>> V exclusiveBetween(final T start, final T end, final V value, final String message) { if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { fail(message); } return value; }
python
def download_arcrest(): """downloads arcrest to disk""" arcrest_name = "arcrest.zip" arcresthelper_name = "arcresthelper.zip" url = "https://github.com/Esri/ArcREST/archive/master.zip" file_name = os.path.join(arcpy.env.scratchFolder, os.path.basename(url)) scratch_folder = os.path.join(arcpy.e...
python
def add_called_sequence(self, section, name, sequence, qstring): """ Add basecalled sequence data :param section: ['template', 'complement' or '2D'] :param name: The record ID to use for the fastq. :param sequence: The called sequence. :param qstring: The quality string....
java
protected void cacheExtension(URI uri) { // extract extension file name from URI String uriStr = uri.toString().toLowerCase(); if (uriStr.endsWith("/")) { uriStr = uriStr.substring(0, uriStr.length() - 1); } String f...
java
@Nonnull public static LByteToIntFunction byteToIntFunctionFrom(Consumer<LByteToIntFunctionBuilder> buildingFunction) { LByteToIntFunctionBuilder builder = new LByteToIntFunctionBuilder(); buildingFunction.accept(builder); return builder.build(); }
java
public static Cookie[] getCookies(final URI url, final CookieStore cookieStore, final int cookieMaxByteSize) { int overallLength = 0, i = 0; final List<Cookie> cookies = cookieStore.getCookies(); for (final Cookie cookie : cookies) { /* Just an approximation, and doesn't take attributes into account, but *...
python
async def _read_rowdata_packet(self): """Read a rowdata packet for each data row in the result set.""" rows = [] while True: packet = await self.connection._read_packet() if self._check_packet_is_eof(packet): # release reference to kill cyclic reference. ...
java
public EClass getIfcDraughtingCalloutRelationship() { if (ifcDraughtingCalloutRelationshipEClass == null) { ifcDraughtingCalloutRelationshipEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(175); } return ifcDraughtingCalloutRelationshipEClass; ...
java
private void doTopicPass(final BuildData buildData, final Map<String, BaseTopicWrapper<?>> topics) throws BuildProcessingException { log.info("Doing " + buildData.getBuildLocale() + " First topic pass"); // Check that we have some topics to process if (topics != null) { log.info("\t...
java
public T clear() { if (view != null) { if (view instanceof ImageView) { ImageView iv = ((ImageView) view); iv.setImageBitmap(null); } else if (view instanceof WebView) { WebView wv = ((WebView) view); wv.stopLoading(); ...
java
public void registerBThread(String name, Function func) { program.registerBThread(new BThreadSyncSnapshot(name, func)); }
java
private String _read(String rowKey) throws RowNotFoundException { Row row = CqlUtils.executeOne(sessionHelper.getSession(), cqlGetMetadata, ConsistencyLevel.LOCAL_ONE, rowKey); String jsonString = row != null ? row.getString(CqlTemplate.COL_METADATA_METADATA) : null; if (jsonStri...
python
def get_manager(cls): """ Returns the appropriate Manager class for a given Model class. It does this by looking in the boto config for a section like this:: [DB] db_type = SimpleDB db_user = <aws access key id> db_passwd = <aws secret access key> db_name = my_d...
java
public static JdbcCpoAdapter getInstance(JdbcCpoMetaDescriptor metaDescriptor, DataSourceInfo<DataSource> jdsiWrite, DataSourceInfo<DataSource> jdsiRead) throws CpoException { String adapterKey = metaDescriptor + ":" + jdsiWrite.getDataSourceName() + ":" + jdsiRead.getDataSourceName(); JdbcCpoAdapter adapter = ...
python
def _initialize(self, path): """ Find metadata tree root, detect format version """ # Find the tree root root = os.path.abspath(path) try: while ".fmf" not in next(os.walk(root))[1]: if root == "/": raise utils.RootError( ...
java
Integer getBRIScope() { return (table.isWritable()) ? ValuePool.getInt(bestRowTemporary) : ValuePool.getInt(bestRowSession); }