language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private Entity processInteraction(Interaction interaction, Set<String> avail, Provenance pro, boolean isComplex) { Entity bpInteraction = null; //interaction or complex boolean isGeneticInteraction = false; // get interaction name/short name String name = null; String shortName = null; if (interac...
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { int iErrorCode = this.setupGridOrder(); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; return super.fieldChanged(bDisplayOption, iMoveMode); }
java
public static MultipleAlignmentJmol display(MultipleAlignment multAln) throws StructureException { List<Atom[]> rotatedAtoms = MultipleAlignmentDisplay.getRotatedAtoms(multAln); MultipleAlignmentJmol jmol = new MultipleAlignmentJmol(multAln, rotatedAtoms); jmol.setTitle(jmol.getStructure().getPDBHeader(...
python
def get_vault_lookup_session(self): """Gets the OsidSession associated with the vault lookup service. return: (osid.authorization.VaultLookupSession) - a ``VaultLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_...
python
def get_cookie_jar(self): """Returns our cookie jar.""" cookie_file = self._get_cookie_file() cookie_jar = LWPCookieJar(cookie_file) if os.path.exists(cookie_file): cookie_jar.load() else: safe_mkdir_for(cookie_file) # Save an empty cookie jar so we can change the file perms on it ...
python
def check_handle_syntax(string): ''' Checks the syntax of a handle without an index (are prefix and suffix there, are there too many slashes?). :string: The handle without index, as string prefix/suffix. :raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError` :return: True....
python
def _get_aggregated_object(self, composite_key): """ method talks with the map of instances of aggregated objects :param composite_key presents tuple, comprising of domain_name and timeperiod""" if composite_key not in self.aggregated_objects: self.aggregated_objects[composite_ke...
java
public CollectionAssert allElementsMatch(String regex) { isNotNull(); isNotEmpty(); for (Object anActual : this.actual) { if (anActual == null) { failWithMessageRelatedToRegex(regex, anActual); } String value = anActual.toString(); if (!value.matches(regex)) { failWithMessageRelatedToRegex(reg...
java
private void outputReportFiles(List<String> reportNames, File reportDirectory, TestResult testResult, boolean tranSummary) throws IOException { if (reportNames.isEmpty()) { return; } String title = (tranSummary) ? "Transaction Summary" : "Performan...
python
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable) -> Iterable[bytes]: # pragma: nocover """ called when view is not found""" raise NotImplementedError()
java
private Set<Impact> collectResult( List<Impact> singleEntityChanges, List<Impact> wholeRepoActions, Set<String> dependentEntityIds) { Set<String> wholeRepoIds = union( wholeRepoActions.stream().map(Impact::getEntityTypeId).collect(toImmutableSet()), dependentEntityI...
python
def maybe_submit_measurement(self): """Check for configured instrumentation backends and if found, submit the message measurement info. """ if self.statsd: self.submit_statsd_measurements() if self.influxdb: self.submit_influxdb_measurement()
python
def _load_stream_py3(dc, chunks): """ Given a decompression stream and chunks, yield chunks of decompressed data until the compression window ends. """ while not dc.eof: res = dc.decompress(dc.unconsumed_tail + next(chunks)) yield res
python
def uniform(self, a: float, b: float, precision: int = 15) -> float: """Get a random number in the range [a, b) or [a, b] depending on rounding. :param a: Minimum value. :param b: Maximum value. :param precision: Round a number to a given precision in decimal digits, default...
java
protected List<BubbleGlyph> getAndExpireBubbles (Name speaker) { int num = _bubbles.size(); // first, get all the old bubbles belonging to the user List<BubbleGlyph> oldbubs = Lists.newArrayList(); if (speaker != null) { for (int ii=0; ii < num; ii++) { B...
python
def _prepare_request_json(self, kwargs): """Prepare request args for sending to device as JSON.""" # Check for python keywords in dict kwargs = self._check_for_python_keywords(kwargs) # Check for the key 'check' in kwargs if 'check' in kwargs: od = OrderedDict() ...
java
public String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGOR...
python
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])...
python
def load_path_with_default(self, path, default_constructor): ''' Same as `load_path(path)', except uses default_constructor on import errors, or if loaded a auto-generated namespace package (e.g. bare directory). ''' try: imported_obj = self.load_path(path) ...
java
public static double hypergeometric(int k, int n, int Kp, int Np) { if(k<0 || n<0 || Kp<0 || Np<0) { throw new IllegalArgumentException("All the parameters must be positive."); } Kp = Math.max(k, Kp); Np = Math.max(n, Np); /* //slow! $probabil...
java
@Override public TextColumn unique() { List<String> strings = new ArrayList<>(asSet()); return TextColumn.create(name() + " Unique values", strings); }
java
public ApiResponse<List<MarketPricesResponse>> getMarketsPricesWithHttpInfo(String datasource, String ifNoneMatch) throws ApiException { com.squareup.okhttp.Call call = getMarketsPricesValidateBeforeCall(datasource, ifNoneMatch, null); Type localVarReturnType = new TypeToken<List<MarketPrice...
python
def process(dest, rulefiles): """process rules""" deploy = False while not rulefiles.empty(): rulefile = rulefiles.get() base = os.path.basename(rulefile) dest = os.path.join(dest, base) if os.path.exists(dest): # check if older oldtime = os.stat(rulef...
java
public boolean isEditable(final int row, final int column) { if (isEditable(column)) { final int actualIndex = getTableColumn(column).getIndex(); final JKTableRecord record = getRecord(row); return record.isColumnEnabled(actualIndex); } return false; }
java
private Instance getExistingKey(final String _key) { Instance ret = null; try { final QueryBuilder queryBldr = new QueryBuilder(Type.get(DBPropertiesUpdate.TYPE_PROPERTIES)); queryBldr.addWhereAttrEqValue("Key", _key); queryBldr.addWhereAttrEqValue("BundleID", thi...
python
def guess_autoescape(self, template_name): """Given a template Name I will gues using its extension if we should autoscape or not. Default autoscaped extensions: ('html', 'xhtml', 'htm', 'xml') """ if template_name is None or '.' not in template_name: return False ...
java
public KeySnapshot filter(KVFilter kvf){ ArrayList<KeyInfo> res = new ArrayList<>(); for(KeyInfo kinfo: _keyInfos) if(kvf.filter(kinfo))res.add(kinfo); return new KeySnapshot(res.toArray(new KeyInfo[res.size()])); }
java
public static KieServicesConfiguration newJMSConfiguration( ConnectionFactory connectionFactory, Queue requestQueue, Queue responseQueue) { return new KieServicesConfigurationImpl( connectionFactory, requestQueue, responseQueue ); }
python
def _pool(self, pool_name, pool_function, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in): """Construct a pooling layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = num_channels_in name = po...
python
def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else False
java
public ByteBuffer getScaleKeyBuffer() { ByteBuffer buf = m_scaleKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; }
java
@Override public void renderBranch( PositionedText target, double x, double y, Size size, Collection<Diagram.Figure> branches, boolean forward ) { throw new UnsupportedOperationException( "not implemented" ); }
java
public GVRAndroidResource addResource(GVRAndroidResource resource) { String fileName = resource.getResourcePath(); GVRAndroidResource resourceValue = resourceMap.get(fileName); if (resourceValue != null) { return resourceValue; } // Only put the resourceKe...
python
def _add_exac(self, variant_obj, gemini_variant): """Add the gmaf frequency Args: variant_obj (puzzle.models.Variant) gemini_variant (GeminiQueryRow) """ exac = gemini_variant['aaf_exac_all'] if exac: exac = float(exac) ...
java
private TrackType findTrackType() { TrackType result = TRACK_TYPE_MAP.get(packetBytes[42]); if (result == null) { return TrackType.UNKNOWN; } return result; }
python
def reset(self): """Reset the widget, and clear the scene.""" self.minimum = None self.maximum = None self.start_time = None # datetime, absolute start time self.idx_current = None self.idx_markers = [] self.idx_annot = [] if self.scene is not None: ...
java
public static SQLiteConnectionPool open(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration configuration, com.couchbase.lite.internal.database.sqlite.SQLiteConnectionListener connectionListener) { if (configuration == null) { throw new...
python
def data2md(table): """ Creates a markdown table. The first row will be headers. Parameters ---------- table : list of lists of str A list of rows containing strings. If any of these strings consist of multiple lines, they will be converted to single line because markdown ta...
python
def lagrange_interpolate(x, y, precision=250, **kwargs): """ Interpolate x, y using Lagrange polynomials https://en.wikipedia.org/wiki/Lagrange_polynomial """ n = len(x) - 1 delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])] for i in range(n + 1): yield x[i], y[i] if i == n or d...
python
def read_pipette_id(self, mount) -> Optional[str]: ''' Reads in an attached pipette's ID The ID is unique to this pipette, and is a string of unknown length :param mount: string with value 'left' or 'right' :return id string, or None ''' res: Optional[str] = None...
java
public <T2, R> ValueTransformer<W,R> zip(Iterable<? extends T2> iterable, BiFunction<? super T, ? super T2, ? extends R> fn) { return this.unitAnyM(this.transformerStream().map(v->v.zip(iterable,fn))); }
python
def base_create_agent_configurations(cls) -> ConfigObject: """ This is used when initializing agent config via builder pattern. It also calls `create_agent_configurations` that can be used by BaseAgent subclasses for custom configs. :return: Returns an instance of a ConfigObject object. ...
java
boolean expectAutoboxesToIterable(Node n, JSType type, String msg) { // Note: we don't just use JSType.autobox() here because that removes null and undefined. // We want to keep null and undefined around. if (type.isUnionType()) { for (JSType alt : type.toMaybeUnionType().getAlternates()) { al...
python
def main(): """ Main function called from dynamic-dynamodb """ try: if get_global_option('show_config'): print json.dumps(config.get_configuration(), indent=2) elif get_global_option('daemon'): daemon = DynamicDynamoDBDaemon( '{0}/dynamic-dynamodb.{1}.pid'...
java
public <T> Completes<Optional<T>> maybeActorOf(final Class<T> protocol, final Address address) { return directoryScanner.maybeActorOf(protocol, address).andThen(proxy -> proxy); }
java
public QueryBuilder<T, ID> offset(Long startRow) throws SQLException { if (databaseType.isOffsetSqlSupported()) { offset = startRow; return this; } else { throw new SQLException("Offset is not supported by this database"); } }
python
def unchunk(self): """ Reconstitute the chunked array back into a full ndarray. Returns ------- ndarray """ if self.padding != len(self.shape)*(0,): shape = self.values.shape arr = empty(shape, dtype=object) for inds in product...
python
def escape(cls, s): """Escape a string. Calls :func:`escape` and ensures that for subclasses the correct type is returned. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv
python
def rst_add_mathjax(content): """Adds mathjax script for reStructuredText""" # .rst is the only valid extension for reStructuredText files _, ext = os.path.splitext(os.path.basename(content.source_path)) if ext != '.rst': return # If math class is present in text, add the javascript # ...
python
def pvremove(devices, override=True): ''' Remove a physical device being used as an LVM physical volume override Skip devices, if they are already not used as LVM physical volumes CLI Examples: .. code-block:: bash salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2 ''' if is...
python
def module_summary(self): """Count the malicious and suspicious sections, check for CVE description""" suspicious = 0 malicious = 0 count = 0 cve = False taxonomies = [] for section in self.results: if section['submodule_section_content']['class'] == ...
python
def copy_all(self, ctxt): ''' copies all values into the current context from given context :param ctxt: ''' for key, value in ctxt.iteritems: self.set_attribute(key, value)
java
private AttributeAtom rewriteWithRelationVariable(Atom parentAtom){ if (parentAtom.isResource() && ((AttributeAtom) parentAtom).getRelationVariable().isReturned()) return rewriteWithRelationVariable(); return this; }
java
@Override public void draw(Canvas c, Projection projection) { final double zoomLevel = projection.getZoomLevel(); if (zoomLevel < minZoom) { return; } final Rect rect = projection.getIntrinsicScreenRect(); int _screenWidth = rect.width(); int _screenHeight = rect.height(); boolean screenSizeChanged ...
java
boolean containsRule( Rule rule ) { for( int i = state.stackIdx - 1; i >= 0; i-- ) { if( rule == state.stack.get( i ).mixin ) { return true; } } return false; }
java
private void readPropertiesFiles() { if (this.configurationFileWildcard.isEmpty() || this.configurationFileExtension.isEmpty()) { // Skip configuration loading LOGGER.log(SKIP_CONF_LOADING); } else { // Assemble the regex pattern final Pattern fi...
python
def latent_prediction_model(inputs, ed_attention_bias, latents_discrete, latents_dense, hparams, vocab_size=None, name=None): """Transformer-based lat...
java
public void marshall(DescribeCustomKeyStoresRequest describeCustomKeyStoresRequest, ProtocolMarshaller protocolMarshaller) { if (describeCustomKeyStoresRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
java
@Override public BufferedReader getReader() throws IOException { try { collaborator.preInvoke(componentMetaData); return request.getReader(); } finally { collaborator.postInvoke(); } }
python
def expander_to_zone(self, address, channel, panel_type=ADEMCO): """ Convert an address and channel into a zone number. :param address: expander address :type address: int :param channel: channel :type channel: int :returns: zone number associated with an addres...
python
def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None, **kwargs): """ Adds labels to a matplotlib Axes Args: labels: dict containing the label as a key and the coordinates as value. lattice: Lattice object used to convert from reciprocal to cartesian coor...
python
def _is_dir(self, f): '''Check if the given in-dap file is a directory''' return self._tar.getmember(f).type == tarfile.DIRTYPE
java
public static ShearCaptcha createShearCaptcha(int width, int height, int codeCount, int thickness) { return new ShearCaptcha(width, height, codeCount, thickness); }
python
def _wait_and_kill(pid_to_wait, pids_to_kill): """ Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_...
java
public float getFloat(int columnIndex) { Object fieldValue = data[columnIndex]; if (fieldValue == null) { return 0.0f; } if (fieldValue instanceof Number) { return ((Number) fieldValue).floatValue(); } throw new DBFException("Unsupported type for Number at column:" + columnIndex + " " + fieldValue...
java
public Match parseUntil(String src,String delimiter) { return this.parseUntil(src,delimiter,new Options()); }
java
public Object remove(Object key) { mCacheMap.remove(key); return mBackingMap.remove(key); }
python
def on_person_update(self, people): """ People have changed Should always include all people (all that were added via on_person_new) :param people: People to update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now ...
java
public void decrease(final DeviceControllerChannel channel, final int steps) throws IOException { if (channel == null) { throw new RuntimeException("null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'"); } // decrease only work...
java
private ProjectFile handleDirectory(File directory) throws Exception { ProjectFile result = handleDatabaseInDirectory(directory); if (result == null) { result = handleFileInDirectory(directory); } return result; }
java
public Nfs3MknodResponse wrapped_sendMknod(NfsMknodRequest request) throws IOException { RpcResponseHandler<Nfs3MknodResponse> responseHandler = new NfsResponseHandler<Nfs3MknodResponse>() { /* (non-Javadoc) * @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewRespons...
python
def hscroll(clicks, x=None, y=None, pause=None, _pause=True): """Performs an explicitly horizontal scroll of the mouse scroll wheel, if this is supported by the operating system. (Currently just Linux.) The x and y parameters detail where the mouse event happens. If None, the current mouse position is ...
java
private WMenu buildMenu(final WText selectedMenuText) { WMenu menu = new WMenu(WMenu.MenuType.FLYOUT); // The Colours menu just shows simple text WSubMenu colourMenu = new WSubMenu("Colours"); addMenuItem(colourMenu, "Red", selectedMenuText); addMenuItem(colourMenu, "Green", selectedMenuText); addMenuItem(...
python
def add_qemu_path(self, instance): """ Add the qemu path to the hypervisor conf data :param instance: Hypervisor instance """ tmp_conf = {'qemu_path': self.old_top[instance]['qemupath']} if len(self.topology['conf']) == 0: self.topology['conf'].append(tmp_con...
java
public byte[] convertToXmlByteArray(BucketWebsiteConfiguration websiteConfiguration) { XmlWriter xml = new XmlWriter(); xml.start("WebsiteConfiguration", "xmlns", Constants.XML_NAMESPACE); if (websiteConfiguration.getIndexDocumentSuffix() != null) { XmlWriter indexDocumentElement = ...
java
private void add2MBR(int[] entrySorting, double[] ub, double[] lb, int index) { SpatialComparable currMBR = node.getEntry(entrySorting[index]); for(int d = 0; d < currMBR.getDimensionality(); d++) { double max = currMBR.getMax(d); if(max > ub[d]) { ub[d] = max; } double min = cur...
python
def _update_functions(self): """ Uses internal settings to update the functions. """ self.f = [] self.bg = [] self._fnames = [] self._bgnames = [] self._odr_models = [] # Like f, but different parameters, for use in ODR...
java
private boolean logIfEnabled(Level level, Throwable t, String msgTemplate, Object... arguments) { return logIfEnabled(FQCN, level, t, msgTemplate, arguments); }
python
def on_foreground_image(self, *args): """When I get a new ``foreground_image``, store its texture in my ``foreground_texture``. """ if self.foreground_image is not None: self.foreground_texture = self.foreground_image.texture
python
def summary(args): """ %prog summary gffile fastafile Print summary stats, including: - Gene/Exon/Intron - Number - Average size (bp) - Median size (bp) - Total length (Mb) - % of genome - % GC """ p = OptionParser(summary.__doc__) opts, args = p.parse_args(args) ...
java
protected void connect(InetAddress address, int port) throws SocketException { BlockGuard.getThreadPolicy().onNetwork(); connect0(address, port); connectedAddress = address; connectedPort = port; connected = true; }
python
def is_constrained_reaction(model, rxn): """Return whether a reaction has fixed constraints.""" lower_bound, upper_bound = helpers.find_bounds(model) if rxn.reversibility: return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound else: return rxn.lower_bound > 0 or rxn.upper_...
java
private double getWidthForMappingLine(RendererModel model) { double scale = model.getParameter(Scale.class).getValue(); return mappingLineWidth.getValue() / scale; }
java
@SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "We never need to synchronize with the preloader.") void preloadContainerLifecycleEvent(Class<?> eventRawType, Type... typeParameters) { executor.submit(new PreloadingTask(new ParameterizedTypeImpl(eventRawType, typeParamete...
java
@Override public synchronized int update(T dto) throws Exception { return db.update(transformer.getTableName(), transformer.transform(dto),transformer.getWhereClause(dto), null); }
java
public static final Object deserialize(byte[] bytes) throws Exception { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(tc, "deserialize"); Object o; try { ByteArrayInputStream bis = new ByteArrayInputStream(...
python
def _create_pipeline_parser(): """ Create the parser for the %pipeline magics. Note that because we use the func default handler dispatch mechanism of argparse, our handlers can take only one argument which is the parsed args. So we must create closures for the handlers that bind the cell contents and th...
java
public static JwtClaims verifyJwt(String jwt, boolean ignoreExpiry, boolean isToken) throws InvalidJwtException, ExpiredTokenException { JwtClaims claims; if(Boolean.TRUE.equals(enableJwtCache)) { claims = cache.getIfPresent(jwt); if(claims != null) { if(!ignoreE...
python
def _register_bundle_factories(self, bundle): # type: (Bundle) -> None """ Registers all factories found in the given bundle :param bundle: A bundle """ # Load the bundle factories factories = _load_bundle_factories(bundle) for context, factory_class in ...
python
def path_manager_callback(self): """Spyder path manager""" from spyder.widgets.pathmanager import PathManager self.remove_path_from_sys_path() project_path = self.projects.get_pythonpath() dialog = PathManager(self, self.path, project_path, self...
java
public static final Function<Float,Boolean> eq(final Float object) { return (Function<Float,Boolean>)((Function)FnObject.eq(object)); }
java
public boolean canImport(String label, String namespace) { if (!exported.containsKey(label)) { return false; } Set<String> scopes = exportScopes.get(label); for (String scope : scopes) { if (scope.equals(namespace)) { return true; } els...
python
def _receiveFromListener(self, quota: Quota) -> int: """ Receives messages from listener :param quota: number of messages to receive :return: number of received messages """ i = 0 incoming_size = 0 while i < quota.count and incoming_size < quota.size: ...
java
@Override public StringMap getReadOnlyContextData() { StringMap map = localMap.get(); if (map == null) { map = createStringMap(); localMap.set(map); } return map; }
python
def getMugshot(self): """ Return the L{Mugshot} associated with this L{Person}, or an unstored L{Mugshot} pointing at a placeholder mugshot image. """ mugshot = self.store.findUnique( Mugshot, Mugshot.person == self, default=None) if mugshot is not None: ...
python
def edit_file(self, filename, line): """Handle %edit magic petitions.""" if encoding.is_text_file(filename): # The default line number sent by ipykernel is always the last # one, but we prefer to use the first. self.edit_goto.emit(filename, 1, '')
java
public FieldInfo getFieldInfo(String name) { if (name != null) { if (ignoreCase) { name = name.toLowerCase(Locale.US); } name = name.intern(); } return nameToFieldInfoMap.get(name); }
java
@Override public GetDimensionValuesResult getDimensionValues(GetDimensionValuesRequest request) { request = beforeClientExecution(request); return executeGetDimensionValues(request); }
java
public SimpleFeature convertDwgPoint( String typeName, String layerName, DwgPoint point, int id ) { double[] p = point.getPoint(); Point2D pto = new Point2D.Double(p[0], p[1]); CoordinateList coordList = new CoordinateList(); Coordinate coord = new Coordinate(pto.getX(), pto.getY(), 0.0...
java
protected void invokeHandler(Event event, ApiContext apiContext) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { String topic[] = event.getTopic...