language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _unpack_observation(self, obs_batch): """Unpacks the action mask / tuple obs from agent grouping. Returns: obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size] mask (Tensor): action mask, if any """ unpacked = _unpack_obs( np.array(...
java
public void warnIfOpen() { if (allocationSite == null || !ENABLED) { return; } String message = ("A resource was acquired at attached stack trace but never released. " + "See java.io.Closeable for information on avoiding resource leaks."); R...
python
def Erdim_Akgiray_Demir(dp, voidage, vs, rho, mu, L=1): r'''Calculates pressure drop across a packed bed of spheres using a correlation developed in [1]_, claiming to be the best model to date. .. math:: f_v = 160 + 2.81Re_{Erg}^{0.904} .. math:: f_v = \frac{\Delta P d_p^2}{\mu v_s L}\...
java
public Notification getByID(String id) { //TODO maybe SORT_By_ID then make a better array searching algorithm for (Notification n: NotificationManager.notifications){ if(n.getId().equals(id)){ logger.fine("...found a match for getByID query. With id: "+id); re...
java
public void setLinearLowerLimits(float limitX, float limitY, float limitZ) { Native3DGenericConstraint.setLinearLowerLimits(getNative(), limitX, limitY, limitZ); }
python
def _create_activity2(self, parent, name, activity_type=ActivityType.TASK): """Create a new activity. .. important:: This function creates activities for KE-chain versions later than 2.9.0-135 In effect where the module 'wim' has version '>=2.0.0'. The version of 'wi...
java
public static void addGaussian(InterleavedS16 input, Random rand , double sigma , int lowerBound , int upperBound ) { int length = input.width*input.numBands; for (int y = 0; y < input.height; y++) { int index = input.getStartIndex() + y * input.getStride(); int indexEnd = index+length; while( index < in...
java
static public int encodeToByteArray(CharSequence charSeq, char[] charBuffer, int charOffset, int charLength, byte[] byteBuffer, int byteOffset) { int c = 0; int bytePos = byteOffset; // start at byte offset int charPos = charOffset; // start at char offset int charAbsLength =...
python
def update(self, document_id, update_spec, namespace, timestamp): """Apply updates given in update_spec to the document whose id matches that of doc. """ db, coll = self._db_and_collection(namespace) meta_collection_name = self._get_meta_collection(namespace) self.meta...
python
def username(self, value=None): """ Return or set the username :param string value: the new username to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, username=value) return unicode_unquote(self._t...
python
def instance(cls, *args, **kwgs): """Will be the only instance""" if not hasattr(cls, "_instance"): cls._instance = cls(*args, **kwgs) return cls._instance
python
def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE): """Load and parse dynamic config""" dynamic_configurations = {} # Insert config path so we can import it sys.path.insert(0, path.dirname(path.abspath(config_file))) try: config_module = __import__('config') dynamic_c...
java
public static Type reify(Type type, Class<?> context) { return reify(type, getTypeVariableMap(context, null)); }
python
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': 'giser@osgeo.cn', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} alre...
java
@SuppressWarnings("unchecked") @InternalFunction(operator=">", precedence=10) public Boolean gt(Object value, Object value2) { if (value2 != null && value2 instanceof Comparable) { @SuppressWarnings("rawtypes") final int ret = ((Comparable)value2).compareTo(value); ...
python
def parse_map_Ks(self): """Specular color map""" Kd = os.path.join(self.dir, " ".join(self.values[1:])) self.this_material.set_texture_specular_color(Kd)
python
def _get_nics(vm_): ''' Create network interfaces on appropriate LANs as defined in cloud profile. ''' nics = [] if 'public_lan' in vm_: firewall_rules = [] # Set LAN to public if it already exists, otherwise create a new # public LAN. if 'public_firewall_rules' in vm...
java
public static boolean delete(String file) { File f = new File(file); if (f.isDirectory()) { // first insure the directory is empty String[] children = f.list(); for (String child : children) { if (!delete(Files.buildPath(file, child))) ...
java
public static void swap(final int[][] array, final long first, final long second) { final int t = array[segment(first)][displacement(first)]; array[segment(first)][displacement(first)] = array[segment(second)][displacement(second)]; array[segment(second)][displacement(second)] = t; }
java
public Pair addElseIf(ExprBoolean condition, Statement body, Position start, Position end) { Pair pair; ifs.add(pair = new Pair(condition, body, start, end)); body.setParent(this); return pair; }
java
@Override public void write(byte []buf, int offset, int length, boolean isEnd) throws IOException { while (offset < length) { TempBuffer tail = _tail; if (tail == null || tail.buffer().length <= tail.length()) { addBuffer(TempBuffer.create()); tail = _tail; } ...
python
def on(self, event, f=None): """Registers the function ``f`` to the event name ``event``. If ``f`` isn't provided, this method returns a function that takes ``f`` as a callback; in other words, you can use this method as a decorator, like so:: @ee.on('data') def...
python
def format_time(seconds): """ Formats a string from time given in seconds. For large times (``abs(seconds) >= 60``) the format is:: dd:hh:mm:ss For small times (``abs(seconds) < 60``), the result is given in 3 significant figures, with units given in seconds and a suitable SI-prefix. "...
python
def handle_job_exception(self, exception, variables=None): """ Makes and returns a last-ditch error response. :param exception: The exception that happened :type exception: Exception :param variables: A dictionary of context-relevant variables to include in the error response ...
java
private boolean isLayoutOwnerDefault(IPerson person) { final String userName = (String) person.getAttribute("username"); final List<FragmentDefinition> definitions = this.fragmentUtils.getFragmentDefinitions(); if (userName != null && definitions != null) { for (final FragmentDefini...
java
public boolean reloadIsModified() { if (_classIsModified) { return true; } if (! _hasJNIReload || ! _classPath.canRead()) { return true; } try { long length = _classPath.length(); Class<?> cl = _clRef != null ? _clRef.get() : null; if (cl == null) { re...
java
@Nullable public final Resources getResources() { Activity activity = getActivity(); return activity != null ? activity.getResources() : null; }
python
def update(): ''' Update caches of the storage containers. Compares the md5 of the files on disk to the md5 of the blobs in the container, and only updates if necessary. Also processes deletions by walking the container caches and comparing with the list of blobs in the container ''' f...
python
def dump_system(self, filepath=None, modular=False, **kwargs): """ Dump a :class:`MolecularSystem` to a file (PDB or XYZ). Kwargs are passed to :func:`pywindow.io_tools.Output.dump2file()`. Parameters ---------- filepath : :class:`str` The filepath for the du...
java
public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemCli...
python
def bulk_get_or_create(self, data_list): """ data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time...
python
def robots(self): """Return values for robots html meta key""" r = 'noindex' if self.is_noindex else 'index' r += ',' r += 'nofollow' if self.is_nofollow else 'follow' return r
java
public final void flushAll(String host) throws TimeoutException, InterruptedException, MemcachedException { this.flushAll(AddrUtil.getOneAddress(host), this.opTimeout); }
java
public void set(Object obj, Object value) throws IllegalAccessException, InvocationTargetException { // always try the "setMethod" first if (setMethod != null) { setMethod.invoke(obj, value); // fall back to setting the field directly } else if (field != null) { f...
java
private void switchOverToHash(int numAtts) { for (int index = 0; index < numAtts; index++) { String qName = super.getQName(index); Integer i = new Integer(index); m_indexFromQName.put(qName, i); // Add quick look-up to find with uri/local ...
python
def request_args(self): """Use args_schema to parse request query arguments.""" args = flask.request.args data_raw = {} for field_name, field in self.args_schema.fields.items(): alternate_field_name = field.load_from if MA2 else field.data_key if alternate_field...
java
public void marshall(EncryptionAtRestOptionsStatus encryptionAtRestOptionsStatus, ProtocolMarshaller protocolMarshaller) { if (encryptionAtRestOptionsStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
python
def _set_duty(self, motor_duty_file, duty, friction_offset, voltage_comp): """Function to set the duty cycle of the motors.""" # Compensate for nominal voltage and round the input duty_int = int(round(duty*voltage_comp)) # Add or subtract offset and clamp the value bet...
python
def set(self, name, value=True): "set a feature value" setattr(self, name.lower(), value)
python
def update_func_body(original, updater=None): """Update all function body using the updating function.""" updated = '' regex = r'([_\w][_\w\d]*)\s*\(.*\)\s*\{' match = re.search(regex, original) while match: name = match.group(1) logging.debug(_('Found candidate: %s'), name) ...
java
public static BufferedImage toImage(INDArray matrix) { BufferedImage img = new BufferedImage(matrix.rows(), matrix.columns(), BufferedImage.TYPE_INT_ARGB); WritableRaster r = img.getRaster(); int[] equiv = new int[(int) matrix.length()]; for (int i = 0; i < equiv.length; i++) { ...
java
private String getBaseRepoPath(final String path) { int pos; if (path.contains("local-repo")) { pos = path.indexOf("local-repo" + File.separator) + 11; } else { pos = path.indexOf("repository" + File.separator) + 11; } if (pos < 0) { return pat...
java
@Override public List<String> getGroupsForUser(String userId, List<String> groupIds, List<String> allExistingGroupIds) { List<String> groups = _groupStore.get(userId); if (groups == null) { groups = new ArrayList<String>(0); } return groups; }
java
public List<EdgeIteratorState> calcEdges() { final List<EdgeIteratorState> edges = new ArrayList<>(edgeIds.size()); if (edgeIds.isEmpty()) return edges; forEveryEdge(new EdgeVisitor() { @Override public void next(EdgeIteratorState eb, int index, int prevEdgeI...
python
def _parse_action(action): """ Parses a single action item, for instance one of the following: m; m(); m(True); m(*) The brackets must match. """ i_open = action.find('(') if i_open is -1: # return action name, finished return {'name': action, 'args': [], 'event_args': ...
python
def _consolidate_repo_sources(sources): ''' Consolidate APT sources. ''' if not isinstance(sources, sourceslist.SourcesList): raise TypeError( '\'{0}\' not a \'{1}\''.format( type(sources), sourceslist.SourcesList ) ) consolida...
python
def find_comments_by_ids(self, comment_ids): """doc: http://open.youku.com/docs/doc?id=34 """ url = 'https://openapi.youku.com/v2/comments/show_batch.json' params = { 'client_id': self.client_id, 'comment_ids': comment_ids } r = requests.get(url, p...
java
@Override public void setRef(int parameterIndex, Ref x) throws SQLException { checkParameterBounds(parameterIndex); throw SQLError.noSupport(); }
java
public Object run( long clientCustomerId, final Object obj, final Method method, final Object[] args) throws Throwable { Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { return method.invoke(obj, args); ...
python
def update_fitness(objective_function, particle): """ Calculates and updates the fitness and best_fitness of a particle. Fitness is calculated using the 'problem.fitness' function. Args: problem: The optimization problem encapsulating the fitness function and optimization type. ...
java
public static LocalTime fromMillisOfDay(long millisOfDay, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono).withUTC(); return new LocalTime(millisOfDay, chrono); }
java
@Override public UpdateGameSessionQueueResult updateGameSessionQueue(UpdateGameSessionQueueRequest request) { request = beforeClientExecution(request); return executeUpdateGameSessionQueue(request); }
python
def remove_dependents(self, task, params={}, **options): """Unlinks a set of dependents from this task. Parameters ---------- task : {Id} The task to remove dependents from. [data] : {Object} Data for the request - dependents : {Array} An array of task IDs to remove a...
python
def reindex_content_structure(portal): """Reindex contents generated by Generic Setup """ logger.info("*** Reindex content structure ***") def reindex(obj, recurse=False): # skip catalog tools etc. if api.is_object(obj): obj.reindexObject() if recurse and hasattr(aq_...
python
def _write_module_descriptor_file(handle, module_dir): """Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. module_dir: Directory where a module was downloaded. """ readme = _module_descriptor_file(module_dir) readme_content = ( "Module: %s\nDow...
python
def restore(self, key, ttl, value, replace=False): """Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via :meth:`~tredis.RedisClient.dump`). If ``ttl`` is ``0`` the key is created without any expire, otherwise the sp...
java
public void apply() { if (element != null) { String uid = DOM.createUniqueId(); element.setId(uid); JsScrollfire.apply("#" + uid, offset, callback::call); } else { GWT.log("You must set the element before applying the scrollfire", new IllegalStateException...
python
def to_reduced_dict(self): """ Returns: dict with element symbol and reduced amount e.g., {"Fe": 2.0, "O":3.0}. """ d = self.composition.to_reduced_dict d['charge'] = self.charge return d
java
@Override public void removeRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) { try { if (PropertyUtils.getProperty(task, fieldName) != null) { Iterable<Project> projects = (Iterable<Project>) PropertyUtils.getProperty(task, fieldName); Iterato...
java
static void subscribeIfNotDone() { Enumeration<String > callbackKeys = failed_event_callback_map.keys(); while (callbackKeys.hasMoreElements()) { String callbackKey = callbackKeys.nextElement(); EventCallBackStruct eventCallBackStruct = failed_event_callback_map.get(callbackKey);...
java
public void addListeners() { // If there is a header record and there is a bookmark associated with it, make it current! super.addListeners(); if (this.getMainRecord() != null) this.getMainRecord().addScreenListeners(this); // Add the basic listeners to this record that belong on ...
java
public CancelSpotFleetRequestsRequest withSpotFleetRequestIds(String... spotFleetRequestIds) { if (this.spotFleetRequestIds == null) { setSpotFleetRequestIds(new com.amazonaws.internal.SdkInternalList<String>(spotFleetRequestIds.length)); } for (String ele : spotFleetRequestIds) { ...
python
def request_payload(cls, request, request_id): '''JSON v1 request (or notification) payload.''' if isinstance(request.args, dict): raise ProtocolError.invalid_args( 'JSONRPCv1 does not support named arguments') return { 'method': request.method, ...
java
final void reallySetLogWriter(final PrintWriter out) throws ResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "setting the logWriter to:", out); if (dataSourceOrDriver != null) { try { AccessController.doPrivi...
python
def relations_for_id(relid=None): """Get relations of a specific relation ID""" relation_data = [] relid = relid or relation_ids() for unit in related_units(relid): unit_data = relation_for_unit(unit, relid) unit_data['__relid__'] = relid relation_data.append(unit_data) retur...
java
public EClass getIfcControl() { if (ifcControlEClass == null) { ifcControlEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(116); } return ifcControlEClass; }
java
public void show() { if (mAnchorViewRef.get() != null) { mPopupContent = new PopupContentView(mContext); TextView body = (TextView) mPopupContent.findViewById( R.id.com_facebook_tooltip_bubble_view_text_body); body.setText(mText); if (mStyle ==...
java
public static InfluxConfig createInfluxConfig(MetricsConfig conf) { log.info("Configuring stats with direct InfluxDB at {}", conf.getInfluxDBUri()); return new InfluxConfig() { @Override public Duration step() { return Duration.ofSeconds(conf.getOutputFrequencySec...
python
def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None: """ store nick, user, host in kwargs if prefix is correct format """ if "!" in prefix and "@" in prefix: # From a user kwargs["nick"], remainder = prefix.split("!", 1) kwargs["user"], kwargs["host"] = remainder.split("@", 1) ...
python
def xinfo_consumers(self, stream, group_name): """Retrieve consumers of a consumer group""" fut = self.execute(b'XINFO', b'CONSUMERS', stream, group_name) return wait_convert(fut, parse_lists_to_dicts)
java
@Override public void sendInternal(NotificationType type, String... messages) throws NotificationException { if (producer == null) { createProducer(); } sendInternalToProducer(producer, type, messages); }
python
def extract_from_files( files: List[Path], languages: Dict[str, List[str]]) -> DataSet: """Extract arrays of features from the given files. :param files: list of paths :param languages: language name => associated file extension list :return: features """ enumerator = en...
python
def set(self, key, value): """Only need to set if the subsystem is uncut. Caches are only inherited from uncut subsystems. """ if not self.subsystem.is_cut: super().set(key, value)
python
def disableClient(self, *args, **kwargs): """ Disable Client Disable a client. If the client is already disabled, this does nothing. This is typically used by identity providers to disable clients when the corresponding identity's scopes no longer satisfy the client's scopes. ...
java
@Override public BatchGetTracesResult batchGetTraces(BatchGetTracesRequest request) { request = beforeClientExecution(request); return executeBatchGetTraces(request); }
java
public static SchemaItem parse(String sql) { try { SQLStatementParser parser = new MySqlStatementParser(sql); SQLSelectStatement statement = (SQLSelectStatement) parser.parseStatement(); MySqlSelectQueryBlock sqlSelectQueryBlock = (MySqlSelectQueryBlock) statement.getSelect()...
java
private void appendClassAnnotations(StringBuilder sb, FunctionType funType) { FunctionType superConstructor = funType.getInstanceType().getSuperClassConstructor(); if (superConstructor != null) { ObjectType superInstance = superConstructor.getInstanceType(); if (!superInstance.toString().equals("Obj...
python
def network_interface_get(name, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Get details about a specific network interface. :param name: The name of the network interface to query. :param resource_group: The resource group name assigned to the network interface. CLI Exa...
python
def support_support_param_hostip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") support_param = ET.SubElement(support, "support-param") hostip = ET.SubElement(s...
python
def append(self, network): """ Append a :class:`caspo.core.logicalnetwork.LogicalNetwork` to the list Parameters ---------- network : :class:`caspo.core.logicalnetwork.LogicalNetwork` The network to append """ arr = network.to_array(self.hg.mappings) ...
java
@Bean public BatchStubRunner batchStubRunner() { StubRunnerOptionsBuilder builder = builder(); if (this.props.getProxyHost() != null) { builder.withProxy(this.props.getProxyHost(), this.props.getProxyPort()); } StubRunnerOptions stubRunnerOptions = builder.build(); BatchStubRunner batchStubRunner = new Ba...
java
private Node findEjbRefInsertPoint(Element parent) { Element e = DomUtils.getChildElementByName(parent, "ejb-local-ref"); if (e != null) return e; return findEjbLocalRefInsertPoint(parent); }
python
def equivalent(first: T, second: T) -> bool: """Compare two objects for equivalence (identity or equality), using array_equiv if either object is an ndarray """ # TODO: refactor to avoid circular import from . import duck_array_ops if isinstance(first, np.ndarray) or isinstance(second, np.ndarra...
java
public void waitUntil(long waitTime) throws WidgetTimeoutException { long currentTimeMillis = System.currentTimeMillis(); long maxRequestTimeout = waitTime; long endTime = currentTimeMillis + maxRequestTimeout; while (System.currentTimeMillis() < endTime) { try { ...
python
def ecp_auth_request(cls, entityid=None, relay_state="", sign=False): """ Makes an authentication request. :param entityid: The entity ID of the IdP to send the request to :param relay_state: To where the user should be returned after successfull log in. :param sign: Whether the request should ...
python
def add_arguments(self, parser): """Args: parser: """ parser.description = __doc__ parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") parser.add_argument( "--f...
java
public Pair<Expr, Context> translateExpressionWithChecks(WyilFile.Expr expr, Integer selector, Context context) { // Generate expression preconditions as verification conditions checkExpressionPreconditions(expr, context); // Gather up any postconditions from function invocations. context = assumeExpressionPost...
java
public final void pcmpistrm(XMMRegister dst, XMMRegister src, Immediate imm8) { emitX86(INST_PCMPISTRM, dst, src, imm8); }
python
def _coupling_matrix(self, lmax, nwin=None, weights=None): """Return the coupling matrix of the first nwin tapers.""" if nwin is None: nwin = self.nwin if weights is None: weights = self.weights if weights is None: return _shtools.SHMTCouplingMatrix(...
python
def update_invoice_comment(self, invoice_comment_id, invoice_comment_dict): """ Updates an invoice comment :param invoice_comment_id: the invoice comment id :param invoice_comment_dict: dict :return: dict """ return self._create_put_request( resource=...
java
private void similarTransform( int k) { double t[] = QT.data; // find the largest value in this column // this is used to normalize the column and mitigate overflow/underflow double max = QrHelperFunctions_ZDRM.computeRowMax(QT,k,k+1,N); if( max > 0 ) { double gamma...
java
public void drawFlash(float x,float y,float width,float height, Color col) { init(); col.bind(); texture.bind(); if (GL.canSecondaryColor()) { GL.glEnable(SGL.GL_COLOR_SUM_EXT); GL.glSecondaryColor3ubEXT((byte)(col.r * 255), (byte)(col.g * 255), (byte)(col.b * 2...
python
def _set_data(self, action): """ capture Wikidata API response data """ if action == 'siteinfo': self._set_siteinfo() elif action == 'sitematrix': self._set_sitematrix() elif action == 'sitevisitors': self._set_sitevisitors()
python
def download(self): """Download an image file if it exists :raise GyazoError: """ if self.url: try: return requests.get(self.url).content except requests.RequestException as e: raise GyazoError(str(e)) return None
python
def main(argv=None): """The entry point of the application.""" if argv is None: argv = sys.argv[1:] usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:]) version = 'Gitpress ' + __version__ # Parse options args = docopt(usage, argv=argv, version=version) # Execute command try: ...
java
@Override public P build() { try { return buildAsync().join(); } catch (Exception e) { if (e instanceof CompletionException && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw e; } } }
python
def set_shell(self, svc_ref): """ Binds the given shell service. :param svc_ref: A service reference """ if svc_ref is None: return with self._lock: # Get the service self._shell_ref = svc_ref self._shell = self._context.g...
python
def __get_session(self): """ Opens a db session """ db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path) self.session = dal.get_session(db_path) return self.session
java
static boolean polygonContainsPolygon_(Polygon polygon_a, Polygon polygon_b, double tolerance, ProgressTracker progress_tracker) { assert(!polygon_a.isEmpty()); assert(!polygon_b.isEmpty()); RelationalOperationsMatrix relOps = new RelationalOperationsMatrix(); relOps.resetMatrix_();...
python
def hourly_relative_humidity(self): """A data collection containing hourly relative humidity over they day.""" dpt_data = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) rh_data = [rel_humid_from_db_dpt(x, y) for x, y in zip( self._dry_bulb_con...