language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def validate(self, class_, tag, contents): """ Ensures that the class and tag specified exist as an alternative :param class_: The integer class_ from the encoded value header :param tag: The integer tag from the encoded value header :param contents: ...
python
def local_run(): """Whether we should hit GCS dev appserver stub.""" server_software = os.environ.get('SERVER_SOFTWARE') if server_software is None: return True if 'remote_api' in server_software: return False if server_software.startswith(('Development', 'testutil')): return True return False
python
def add_data_point(self, x, y): """Adds a data point to the series. :param x: The numerical x value to be added. :param y: The numerical y value to be added.""" if not is_numeric(x): raise TypeError("x value must be numeric, not '%s'" % str(x)) if not is_numeric(y):...
python
def GetMemReservationMB(self): '''Retrieves the minimum amount of memory that is reserved for the virtual machine. For information about setting a memory reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemReservati...
java
private void reportFailedCheckpoint(FailedCheckpointStats failed) { statsReadWriteLock.lock(); try { counts.incrementFailedCheckpoints(); history.replacePendingCheckpointById(failed); dirty = true; } finally { statsReadWriteLock.unlock(); } }
java
public void marshall(EndpointConfiguration endpointConfiguration, ProtocolMarshaller protocolMarshaller) { if (endpointConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(endpointConfigur...
python
def for_executor(cls, executor: Optional[Executor]) -> 'Subsystem': """Return a subsystem based on the given executor. If ``executor`` is None, use :mod:`asyncio`. If ``executor`` is a :class:`concurrent.futures.ThreadPoolExecutor`, use :mod:`threading`. Args: executor: The ...
java
public Pager<Namespace> findNamespaces(String query, int itemsPerPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm().withParam("search", query, true); return (new Pager<Namespace>(this, Namespace.class, itemsPerPage, formData.asMap(), "namespaces")); }
java
@Override public void doInit() throws IOException, RepositoryException { QueryHandlerContext context = getContext(); setPath(context.getIndexDirectory()); if (path == null) { throw new IOException("SearchIndex requires 'path' parameter in configuration!"); } final Fil...
java
public String getFirst(String name) { HeaderName hn = getHeaderName(name); return getFirst(hn); }
python
def convert_convolution1d(builder, layer, input_names, output_names, keras_layer): """ Convert convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get...
java
public static boolean isReservedVariable( String variableName ){ return ReservedVariables.NOW.equalsIgnoreCase( variableName ) || ReservedVariables.WORKFLOW_INSTANCE_ID.equalsIgnoreCase( variableName ); }
python
def _get_interpreter_info(interpreter=None): """Return the interpreter's full path using pythonX.Y format.""" if interpreter is None: # If interpreter is None by default returns the current interpreter data. major, minor = sys.version_info[:2] executable = sys.executable else: ...
java
@SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.MCFRG__RG_LENGTH: setRGLength((Integer)newValue); return; case AfplibPackage.MCFRG__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Tr...
java
protected void addModifiers(MemberDoc member, Content htmltree) { String mod = modifierString(member); // According to JLS, we should not be showing public modifier for // interface methods. if ((member.isField() || member.isMethod()) && writer instanceof ClassWriterImpl && ...
python
def load_MACHO(macho_id): """lightcurve of 2 bands (R, B) from the MACHO survey. Notes ----- The files are gathered from the original FATS project tutorial: https://github.com/isadoranun/tsfeat """ tarfname = "{}.tar.bz2".format(macho_id) tarpath = os.path.join(DATA_PATH, tarfname) ...
java
public Boolean getBooleanProperty(String key, Boolean defaultValue) { String val = getProperty(key, defaultValue.toString()); Boolean booleanVal = Boolean.parseBoolean(val); return booleanVal; }
java
public void setNetworkInterfaceIds(java.util.Collection<String> networkInterfaceIds) { if (networkInterfaceIds == null) { this.networkInterfaceIds = null; return; } this.networkInterfaceIds = new java.util.ArrayList<String>(networkInterfaceIds); }
python
def recv_msg(self): '''message receive routine''' if self._index >= self._count: return None m = self._msgs[self._index] type = m.get_type() self._index += 1 self.percent = (100.0 * self._index) / self._count self.messages[type] = m self._times...
python
def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) self._cf.packet_received.add_callback(self._got_packet)
python
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
python
def Nu_cylinder_Perkins_Leppert_1962(Re, Pr, mu=None, muw=None): r'''Calculates Nusselt number for crossflow across a single tube as shown in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream temperature. Recommends a viscosity exponent correction of 0.25, which is applied only if pro...
java
public static List<Class<?>> convertArgumentClassesToPrimitives( Class<?>... arguments ) { if (arguments == null || arguments.length == 0) return Collections.emptyList(); List<Class<?>> result = new ArrayList<Class<?>>(arguments.length); for (Class<?> clazz : arguments) { if (clazz =...
java
public static int[] getHeaderToViewPosition(JTextArea view, String header, int start, int end) { validateView(view); validateHeader(header); validateStartEnd(start, end); if (!isValidStartEndForLength(start, end, header.length())) { return INVALID_POSITION; } ...
java
public void run(String[] args) { System.out.println("SampleStarter.run(String[])"); System.out.println("- args.length: " + args.length); for (String arg : args) System.out.println(" - " + arg); System.out.println(this); }
python
def threeD_seismplot(stations, nodes, size=(10.5, 7.5), **kwargs): """ Plot seismicity and stations in a 3D, movable, zoomable space. Uses matplotlibs Axes3D package. :type stations: list :param stations: list of one tuple per station of (lat, long, elevation), \ with up positive. :typ...
java
private static void addDeleteDirective( Element compViewNode, String elementID, IPerson person, Document plf, Element delSet) throws PortalException { String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { ...
python
def fix_line_range(source_code, start, end, options): """Apply autopep8 (and docformatter) between the lines start and end of source.""" # TODO confirm behaviour outside range (indexing starts at 1) start = max(start, 1) options.line_range = [start, end] from autopep8 import fix_code fixed ...
python
def cmd(self, cmd_name): """ Returns tarantool queue command name for current tube. """ return "{0}.tube.{1}:{2}".format(self.queue.lua_queue_name, self.name, cmd_name)
java
private JCheckBox getChkParseRobotsTxt() { if (parseRobotsTxt == null) { parseRobotsTxt = new JCheckBox(); parseRobotsTxt.setText(Constant.messages.getString("spider.options.label.robotstxt")); } return parseRobotsTxt; }
python
def kosaraju(graph): """Strongly connected components by Kosaraju :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ n = len(graph) order = [] sccp = [] kosaraju_dfs(graph, range(n), order, []) k...
java
public Packer inset(final Insets insets) { gc.insets = insets; setConstraints(comp, gc); return this; }
python
def setAttributeType(self, namespaceURI, localName): '''set xsi:type Keyword arguments: namespaceURI -- namespace of attribute value localName -- name of new attribute value ''' self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName) value...
python
def _send_update_port_statuses(self, port_ids, status): """Sends update notifications to set the operational status of the list of router ports provided. To make each notification doesn't exceed the RPC length, each message contains a maximum of MAX_PORTS_IN_BATCH port ids. :par...
java
public void marshall(GetProtectionStatusRequest getProtectionStatusRequest, ProtocolMarshaller protocolMarshaller) { if (getProtectionStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(g...
java
@Override public DescribeHostReservationsResult describeHostReservations(DescribeHostReservationsRequest request) { request = beforeClientExecution(request); return executeDescribeHostReservations(request); }
python
def parse_0134_013b(v): """ Parses the O2 Sensor Value (0134 - 013B) and returns two values parsed from it: 1. Fuel-Air Equivalence [Ratio] as a float from 0 - 2 2. Current in [mA] as a float from -128 - 128 :param str v: :return tuple of float, float: """ try: trim_val = trim_ob...
java
public static Tracing getTracing(String serviceName, CurrentTraceContext context) { Tracing tracing = Tracing.current(); if (tracing == null) { // TODO reporter based on prop/config tracing = getBuilder(serviceName, context).build(); } return tracing; }
python
def check(self, url_data): """Check content for invalid anchors.""" headers = [] for name, value in url_data.headers.items(): if name.startswith(self.prefixes): headers.append(name) if headers: items = [u"%s=%s" % (name.capitalize(), url_data.heade...
java
public static <T extends User, V extends EditorWithErrorHandling<?, ?>, // M extends LoginMessages, H extends HttpMessages> LoginCallback<T, V, M, H> buildLoginCallback( final V pview, final Session psession, final M ploginErrorMessage) { return new LoginCallback<>(pview, psession, ploginErrorMessag...
java
public HMap removeAll(HMap hMap) { return alter(t -> t.keySet().removeAll(hMap.table.keySet())); }
python
def cross_v3(vec_a, vec_b): """Return the crossproduct between vec_a and vec_b.""" return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y, vec_a.z * vec_b.x - vec_a.x * vec_b.z, vec_a.x * vec_b.y - vec_a.y * vec_b.x)
python
def python_file_with_version(self): """Return Python filename with ``__version__`` marker, if configured. Enable this by adding a ``python-file-with-version`` option:: [zest.releaser] python-file-with-version = reinout/maurits.py Return None when nothing has been confi...
java
public String processModification(Properties attributes) throws XDocletException { String name = attributes.getProperty(ATTRIBUTE_NAME); Properties mods = _curClassDef.getModification(name); String key; String value; if (mods == null) { ...
java
public long skip(long numToSkip) throws IOException { // REVIEW // This is horribly inefficient, but it ensures that we // properly skip over bytes via the TarBuffer... // byte[] skipBuf = new byte[8 * 1024]; long skip = numToSkip; while (skip > 0) { i...
python
def authenticate(username, password): """ Returns: a dict with: pk: the pk of the user token: dict containing all the data from the api (access_token, refresh_token, expires_at etc.) user_data: dict containing user data such as first_na...
java
public String printColumnTypes(FixedWidthReadOptions options) throws IOException { Table structure = read(options, true).structure(); return getTypeString(structure); }
java
private static InputStreamReader decompressWithBZip2( final String archivePath) throws ConfigurationException { Bzip2Archiver archiver = new Bzip2Archiver(); InputStreamReader reader = null; try { reader = archiver.getDecompressionStream(archivePath, WIKIPEDIA_ENCODING); } catch (IOException e) { ...
java
public static boolean injectionNeeded() { // first check whether we need to modify ObjectInputStream boolean debugEnabled = PreMainUtil.isDebugEnabled(); InputStream is = String.class.getResourceAsStream("/java/io/ObjectInputStream.class"); if (is == null) { if (debugEnabled)...
java
@Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
public MonetaryRounding getRounding(RoundingQuery query) { Collection<MonetaryRounding> roundings = getRoundings(query); if (roundings.isEmpty()) { return null; } return roundings.iterator().next(); }
python
def validate_multiindex(self, obj): """validate that we can store the multi-index; reset and return the new object """ levels = [l if l is not None else "level_{0}".format(i) for i, l in enumerate(obj.index.names)] try: return obj.reset_index(), leve...
java
private void addSingleProjectToProjects(ProjectsDetails projectsDetails, String projectName, ProjectsDetails projects) { if (projectsDetails == null || projects == null || projectName == null) { logger.debug("projectsDetails {} , projects {} , projectName {}", projectsDetails, projectName, projects)...
java
@Deprecated public synchronized void sendJobEndingMessageToClient(final Optional<Throwable> exception) { if (!this.isClosing()) { LOG.log(Level.SEVERE, "Sending message in a state different that SHUTTING_DOWN or FAILING. " + "This is likely a illegal call to clock.close() at play. Current state: ...
java
private static Node replaceReturns( Node block, String resultName, String labelName, boolean resultMustBeSet) { checkNotNull(block); checkNotNull(labelName); Node root = block; boolean hasReturnAtExit = false; int returnCount = NodeUtil.getNodeTypeReferenceCount( block, Token.R...
java
public static boolean delete(File file) { if (file == null) { return false; } else if (!file.isFile()) { return false; } return file.delete(); }
python
def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ...
python
def image_url(self, pixel_size=None): """ Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image. """ if "profile" not in self._raw: return profile = self._raw["profile"] if (...
java
@Override public boolean isEqual(String data1, String data2) { return LangUtils.isEqual(data1, data2); }
python
def find(self, instance_id): """ find an instance Create a new instance and populate it with data stored if it exists. Args: instance_id (str): UUID of the instance Returns: AtlasServiceInstance.Instance: An instance """ ...
python
def _shapeletOutput(self, r, phi, beta, shapelets): """ returns the the numerical values of a set of shapelets at polar coordinates :param shapelets: set of shapelets [l=,r=,a_lr=] :type shapelets: array of size (n,3) :param coordPolar: set of coordinates in polar units :...
java
protected void requestAttributeChange (String name, Object value, Object oldValue) { requestAttributeChange(name, value, oldValue, Transport.DEFAULT); }
python
def format_permission_object(self, permissions): """Formats a list of permission key names into something the SLAPI will respect. :param list permissions: A list of SLAPI permissions keyNames. keyName of ALL will return all permissions. :returns: list of diction...
python
def get_module_can_publish(cursor, id): """Return userids allowed to publish this book.""" cursor.execute(""" SELECT DISTINCT user_id FROM document_acl WHERE uuid = %s AND permission = 'publish'""", (id,)) return [i[0] for i in cursor.fetchall()]
python
def op(self, i, o): """ Tries to update the registers values with the given instruction. """ for ii in range(len(o)): if is_register(o[ii]): o[ii] = o[ii].lower() if i == 'ld': self.set(o[0], o[1]) return if i == 'push...
java
protected void registerEditorsWithSubClasses(PropertyEditor editor, Class<? extends BioPAXElement> domain) { for (Class<? extends BioPAXElement> c : classToEditorMap.keySet()) { if (domain.isAssignableFrom(c)) { //workaround for participants - can be replaced w/ a general ...
java
public Delete createDelete(URI id, String tableName) throws IOException { Delete del = null; Object tTable = getTable(tableName); if (tTable != null) { del = new Delete(Bytes.toBytes(id.toString())); } return del; }
java
private static AccessType getAccessTypeInCaseElementIsRoot(TypeElement searchedElement, Context context) { List<? extends Element> myMembers = searchedElement.getEnclosedElements(); for ( Element subElement : myMembers ) { List<? extends AnnotationMirror> entityAnnotations = context.getElementUtils().getAll...
python
def fobj_to_tempfile(f, suffix=''): """Context manager which copies a file object to disk and return its name. When done the file is deleted. """ with tempfile.NamedTemporaryFile( dir=TEMPDIR, suffix=suffix, delete=False) as t: shutil.copyfileobj(f, t) try: yield t.name ...
python
def plot_overlaps(otus, group_otus, group_colors, out_fp, fig_size=None, title="", filter_common=False): """ Given a list of OTUs and a number of groups containing subsets of the OTU set, plot a presence/absence bar chart showing which species belong to which groups....
java
public static Config load(final ClassLoader loader) { return ConfigImpl.computeCachedConfig(loader, "load", new Callable<Config>() { @Override public Config call() { return loadDefaultConfig(loader); } }); }
java
public final void addFields(Document document, CellName cellName) { String serializedKey = ByteBufferUtils.toString(cellName.toByteBuffer()); Field field = new StringField(FIELD_NAME, serializedKey, Field.Store.YES); document.add(field); }
python
def ASHRAE_k(ID): r'''Returns thermal conductivity of a building or insulating material from a table in [1]_. Thermal conductivity is independent of temperature here. Many entries in the table are listed for varying densities, but the appropriate ID from the table must be selected to account for that. ...
python
def getDeltaLogLike(self, dlnl, upper=True): """Find the point at which the log-likelihood changes by a given value with respect to its value at the MLE.""" mle_val = self.mle() # A little bit of paranoia to avoid zeros if mle_val <= 0.: mle_val = self._interp.xmin ...
java
@Throws(IllegalPositionIndexException.class) public static int positionIndex(final int index, final int size) { final boolean isIndexValid = (size >= 0) && (index >= 0) && (index < size); if (!isIndexValid) { throw new IllegalPositionIndexException(index, size); } return index; }
java
public HttpCopy createCopyMethod(final String sourcePath, final String destinationPath) { return new HttpCopy(repositoryURL + sourcePath, repositoryURL + destinationPath); }
python
def visit_Attribute(self, node): """ Compute typing for an attribute node. """ obj, path = attr_to_path(node) # If no type is given, use a decltype if obj.isliteral(): typename = pytype_to_ctype(obj.signature) self.result[node] = self.builder.NamedType(typename) ...
java
@Override public int available() throws IOException { if (_readOffset < _readLength) { return _readLength - _readOffset; } StreamImpl source = _source; if (source != null) { return source.getAvailable(); } else { return -1; } }
python
def namedb_read_version(path): """ Get the db version """ con = sqlite3.connect( path, isolation_level=None, timeout=2**30 ) con.row_factory = namedb_row_factory sql = 'SELECT version FROM db_version;' args = () try: rowdata = namedb_query_execute(con, sql, args, abort=False) ...
python
def get_map(self, create_html=True): """Strike data should be a pd.DF from the WWLN data files read by read_WWLN()""" strike_data = self.df num_rows = len(self.df) if num_rows > 1000: print("Warning, you have requested lots of data be mapped." / " Li...
python
def _reprJSON(self): """Returns a JSON serializable represenation of a ``Ci`` class instance. Use :func:`maspy.core.Ci._fromJSON()` to generate a new ``Ci`` instance from the return value. :returns: a JSON serializable python object """ return {'__Ci__': (self.id, self.s...
python
def setup_profile(self, firebug=True, netexport=True): """ Setup the profile for firefox :param firebug: whether add firebug extension :param netexport: whether add netexport extension :return: a firefox profile object """ profile = webdriver.FirefoxProfile() ...
java
@Override @Trivial public void cancel() throws IllegalStateException, NoSuchObjectLocalException, EJBException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "cancel: " + this); boolean removed; /...
python
def get_segmentid_range(self, orchestrator_id): """Get segment id range from DCNM. """ url = "%s/%s" % (self._segmentid_ranges_url, orchestrator_id) res = self._send_request('GET', url, None, 'segment-id range') if res and res.status_code in self._resp_ok: return res.json()
python
def async_stats_job_data(klass, account, url, **kwargs): """ Returns the results of the specified async job IDs """ resource = urlparse(url) domain = '{0}://{1}'.format(resource.scheme, resource.netloc) response = Request(account.client, 'get', resource.path, domain=doma...
python
def revoke_user_access( self, access_id ): ''' Takes an access_id, probably obtained from the get_access_list structure, and revokes that access. No return value, but may raise ValueError. ''' path = "/api/v3/publisher/user/access/revoke" data = { 'a...
python
def get_gradebook_column_gradebook_session(self): """Gets the session for retrieving gradebook column to gradebook mappings. return: (osid.grading.GradebookColumnGradebookSession) - a ``GradebookColumnGradebookSession`` raise: OperationFailed - unable to complete request ...
java
@Override public void trace(String o, Throwable t) { log.trace(o, t); }
java
@Nonnull public static LBoolToByteFunction boolToByteFunctionFrom(Consumer<LBoolToByteFunctionBuilder> buildingFunction) { LBoolToByteFunctionBuilder builder = new LBoolToByteFunctionBuilder(); buildingFunction.accept(builder); return builder.build(); }
java
public static HullWhiteModel of( AbstractRandomVariableFactory randomVariableFactory, TimeDiscretization liborPeriodDiscretization, AnalyticModel analyticModel, ForwardCurve forwardRateCurve, DiscountCurve discountCurve, ShortRateVolatilityModel volatilityModel, CalibrationProduct[] ...
python
def send_video(self, user_id, media_id, title=None, description=None, account=None): """ 发送视频消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param media_id: 发送的视频的媒体ID。 可...
python
def _create_signing_params(self, url, keypair_id, expire_time=None, valid_after_time=None, ip_address=None, policy_url=None, private_key_file=None, private_key_string=None): """ Creates the required URL parameters for a signed...
python
def recruit_participants(self, n=1): """Recruit n participants.""" auto_recruit = os.environ['auto_recruit'] == 'true' if auto_recruit: print "Starting Wallace's recruit_participants." hit_id = str( Participant.query. with_entities(Parti...
python
def user_assigned_policies(user): """Return sequence of policies assigned to a user (or the anonymous user is ``user`` is ``None``). (Also installed as ``assigned_policies`` method on ``User`` model. """ key = user_cache_key(user) cached = cache.get(key) if cached is not None: retu...
python
def accumulate_from_superclasses(cls, propname): ''' Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__``, ...
python
def resolvables_from_iterable(iterable, builder, interpreter=None): """Given an iterable of resolvable-like objects, return list of Resolvable objects. :param iterable: An iterable of :class:`Resolvable`, :class:`Requirement`, :class:`Package`, or `str` to map into an iterable of :class:`Resolvable` objects....
python
def command_umount(self, system_id, *system_ids): """Unmounts the specified sftp system. Usage: sftpman umount {id}.. """ system_ids = (system_id,) + system_ids has_failed = False for system_id in system_ids: try: system = SystemModel.create_by...
java
public Observable<ServiceResponse<VirtualMachineExtensionsListResultInner>> getExtensionsWithServiceResponseAsync(String resourceGroupName, String vmName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } ...
java
public static Query createQueryForNodesWithFieldEqualTo(String constraintValue, String fieldName, Function<String, String> caseOperation) { return FieldComparison.EQ.createQueryForNodesWithFie...
java
public double add(int index, double delta) { magnitude -= vector[index] * vector[index]; vector[index] += delta; magnitude += vector[index] * vector[index]; return vector[index]; }