language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_screen_size_range(self): """Retrieve the range of possible screen sizes. The screen may be set to any size within this range. """ return GetScreenSizeRange( display=self.display, opcode=self.display.get_extension_major(extname), window=self, )
java
private ResourceMethod computeMethod(ExecutableElement ee, List<ResourceArgument> arguments) { final String javaDoc = processingEnv.getElementUtils().getDocComment(ee); final Path pathAnnotation = ee.getAnnotation(Path.class); final Produces producesAnnotation = ee.getAnnotation(Produces.class); return ...
python
def update_goes_and_comes(self): """ Once the block is a Basic one, check the last instruction and updates goes_to and comes_from set of the receivers. Note: jp, jr and ret are already done in update_next_block() """ # Remove any block from the comes_from and goes_to list except ...
python
def user_save_event(user): """ Handle persist event for user entities """ msg = 'User ({}){} updated/saved'.format(user.id, user.email) current_app.logger.info(msg)
java
private void readCalendars() { // // Create the calendars // for (MapRow row : getTable("NCALTAB")) { ProjectCalendar calendar = m_projectFile.addCalendar(); calendar.setUniqueID(row.getInteger("UNIQUE_ID")); calendar.setName(row.getString("NAME")); c...
java
public static BorderStyle getBorderLeft(final Cell cell) { ArgUtils.notNull(cell, "cell"); final Sheet sheet = cell.getSheet(); CellRangeAddress mergedRegion = getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex()); final Cell target; if(mergedRegion == null...
java
public static double weightedMovingAverage(FlatDataList flatDataList, int N) { double WMA=0; double denominator=0.0; int counter=0; for(int i=flatDataList.size()-1;i>=0;--i) { double Yti = flatDataList.getDouble(i); if(counter>=N) { b...
python
def makeQ(r1, r2, r3, r4=0): """ matrix involved in quaternion rotation """ Q = np.asarray([ [r4, -r3, r2, r1], [r3, r4, -r1, r2], [-r2, r1, r4, r3], [-r1, -r2, -r3, r4]]) return Q
java
@Override public List<Group> getSeqResGroups(GroupType type) { List<Group> tmp = new ArrayList<>() ; for (Group g : seqResGroups) { if (g.getType().equals(type)) { tmp.add(g); } } return tmp ; }
java
public JavaDoubleRDD scoreExamplesMultiDataSet(JavaRDD<MultiDataSet> data, boolean includeRegularizationTerms) { return scoreExamplesMultiDataSet(data, includeRegularizationTerms, DEFAULT_EVAL_SCORE_BATCH_SIZE); }
python
def many_init(cls, *args, **kwargs): """ This method implements the creation of a `ListSerializer` parent class when `many=True` is used. You can customize it if you need to control which keyword arguments are passed to the parent, and which are passed to the child. Note...
python
def systemd(service, start=True, enabled=True, unmask=False, restart=False): """ manipulates systemd services """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): if restart: sudo('systemctl restart %s' % service) else:...
python
def _initial_proposal_distribution(self, parameters, theta, size, default_std=1e-4): """ Generate an initial proposal distribution around the point theta. """ missing_parameters = set(parameters).difference(theta) if missing_parameters: raise ValueError("cann...
python
def collapse_spaces(text): """Remove newlines, tabs and multiple spaces with single spaces.""" if not isinstance(text, six.string_types): return text return COLLAPSE_RE.sub(WS, text).strip(WS)
java
public void tagUsers(int tagId, List<String> openIds){ Map<String, Object> map = new HashMap<>(); map.put("tagid", tagId); map.put("openid_list", openIds); String url = WxEndpoint.get("url.tag.user.tag"); logger.debug("add tag for users: {}", JsonMapper.defaultMapper().toJso...
python
def list_containers(list_all=True, short_image=True, full_ids=False, full_cmd=False): """ Lists containers on the Docker remote host, similar to ``docker ps``. :param list_all: Shows all containers. Default is ``False``, which omits exited containers. :type list_all: bool :param short_image: Hides ...
java
protected List<String> getIgnoredProperties() { if (m_ignoredProperties == null) { // get list of ignored properties m_ignoredProperties = OpenCms.getImportExportManager().getIgnoredProperties(); if (m_ignoredProperties == null) { m_ignoredProperties = Collec...
python
def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
python
def expand_defaults(schema, features): """Add to features any default transformations. Not every column in the schema has an explicit feature transformation listed in the featurs file. For these columns, add a default transformation based on the schema's type. The features dict is modified by this function cal...
python
def prepare_dependencies(self): """ Prepares a FileBuildInfo object for explaining what changed The bsources, bdepends and bimplicit lists have all been stored on disk as paths relative to the top-level SConstruct directory. Convert the strings to actual Nodes (for use by the ...
python
def list_frontdoor_resource_property(resource, prop): """ Factory method for creating list functions. """ def list_func(cmd, resource_group_name, resource_name): client = cf_frontdoor(cmd.cli_ctx, None) return client.get(resource_group_name, resource_name).__getattribute__(prop) func_name ...
java
@Override public int getColumnDisplaySize(int column) throws RemoteException { String fldname = getColumnName(column); Type fldtype = schema.type(fldname); if (fldtype.isFixedSize()) // 6 and 12 digits for int and double respectively return fldtype.maxSize() * 8 / 5; return schema.type(fldname).ge...
java
public java.lang.String getOnmouseout() { return (java.lang.String) getStateHelper().eval(PropertyKeys.onmouseout); }
python
def _convert_credentials(token_url, username=None, password=None, refresh_token=None): """ Converts username/password credentials to token credentials by using Yamcs as the authenticaton server. """ if username and password: data = {'grant_type': 'password', 'username': username, 'password':...
python
def list_files(self, project_name): """ Return a list of file paths that make up project_name :param project_name: str: specifies the name of the project to list contents of :return: [str]: returns a list of remote paths for all files part of the specified project qq """ ...
java
@Deprecated public static void checkRange(Number value, Number minimum, Number maximum, Object valueSource) throws ValueOutOfRangeException { double d = value.doubleValue(); if ((d < minimum.doubleValue()) || (d > maximum.doubleValue())) { if (valueSource == null) { throw new ValueOutOfRa...
python
def http_method(self, data): """The HTTP Method for this resource request.""" data = data.upper() if data in ['DELETE', 'GET', 'POST', 'PUT']: self._request.http_method = data self._http_method = data
python
def selfSimilarityMatrix(featureVectors): ''' This function computes the self-similarity matrix for a sequence of feature vectors. ARGUMENTS: - featureVectors: a numpy matrix (nDims x nVectors) whose i-th column corresponds to the i-th feature vector RETURNS: ...
python
def res_layer(self, output_channels, filter_size=3, stride=1, activation_fn=tf.nn.relu, bottle=False, trainable=True): """ Residual Layer: Input -> BN, Act_fn, Conv1, BN, Act_fn, Conv 2 -> Output. Return: Input + Output If stride > 1 or number of filters changes, decrease dims...
java
static boolean isCharsetSupported() throws IOException { try { ZipFile.class.getConstructor(new Class[] { File.class, Charset.class }); return true; } catch (NoSuchMethodException e) { return false; } }
python
def evalop(op,left,right): "this takes evaluated left and right (i.e. values not expressions)" if op in ('=','!=','>','<'): return threevl.ThreeVL.compare(op,left,right) elif op in ('+','-','*','/'): # todo: does arithmetic require threevl? if op=='/': raise NotImplementedError('todo: spec about int/float div...
python
def insert(self, val, position=0): """Insert in position :param val: Object to insert :param position: Index of insertion :return: bool: True iff insertion completed successfully """ if position <= 0: # at beginning return self.insert_first(val) cou...
java
public void setZoomSliderVisible(boolean zoomSliderVisible) { boolean old = this.isZoomSliderVisible(); this.zoomSliderVisible = zoomSliderVisible; zoomSlider.setVisible(zoomSliderVisible); firePropertyChange("zoomSliderVisible", old, this.isZoomSliderVisible()); }
java
public void marshall(Messages messages, ProtocolMarshaller protocolMarshaller) { if (messages == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(messages.getErrors(), ERRORS_BINDING); } catch ...
python
def escape_meta(self, string, pos): """ Checks if a meta character is escaped or else warns about it. If the meta character has an escape character ('\') preceding it, the meta character is escaped. If it does not, a warning is emitted that the user should escape it. Arguments: string (str): The relev...
python
def learn(self): """ Learn on the current dataset, either for many timesteps and even episodes (batchMode = True) or for a single timestep (batchMode = False). Batch mode is possible, because Q-Learning is an off-policy method. In batchMode, the algorithm goes through all the sa...
java
public T get(Supplier<? extends T> preferred) { return explicitOrElseGet(() -> { T value = preferred.get(); if (value != null) { return value; } return defaultValue.get(false); }); }
java
protected void configureMessageController(ApplicationContext context) { if (context.containsBean(MESSAGE_CONTROLLER_BEAN_NAME)) { HttpMessageController messageController = context.getBean(MESSAGE_CONTROLLER_BEAN_NAME, HttpMessageController.class); EndpointAdapter endpointAdapter = httpSe...
java
public static <K, V, R extends Map<K, V>> R selectMapOnEntry( Map<K, V> map, final Predicate2<? super K, ? super V> predicate, R target) { final Procedure2<K, V> mapTransferProcedure = new MapPutProcedure<K, V>(target); Procedure2<K, V> procedure = new Procedure2<...
python
def get_block(self, block_name): """getblock 获取板块, block_name是list或者是单个str Arguments: block_name {[type]} -- [description] Returns: [type] -- [description] """ # block_name = [block_name] if isinstance( # block_name, str) else block_name ...
python
def from_s3_json(cls, bucket_name, key, json_path=None, key_mapping=None, aws_profile=None, aws_access_key_id=None, aws_secret_access_key=None, region_name=None): # pragma: no cover """ Load databas...
java
@Trivial private void addAttributes(Attributes sourceAttrs, Attributes descAttrs) { for (NamingEnumeration<?> neu = sourceAttrs.getAll(); neu.hasMoreElements();) { descAttrs.put((Attribute) neu.nextElement()); } }
java
public static Mirror newInstanceForClassName(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { className = className.trim(); Class<?> objClass = Class.forName(className); return new Mirror(ClassPath.newInstance(objClass)); }
java
public void keyReleased(KeyEvent e) { char ch = e.getKeyChar(); if (ch == KeyEvent.CHAR_UNDEFINED || Character.isISOControl(ch)) return; int pos = editor.getCaretPosition(); String str = editor.getText(); if (str.length() == 0) return; boolean mat...
python
def get_out_of_date(self) -> Sequence[DataObjectReplica]: """ Gets any data object replica that are marked as out of date/not in date. :return: the out of data object replica """ out_of_date = [] for number, data_object_replica in self._data.items(): if not da...
java
FunctionType buildAndRegister() { if (returnType == null) { provideDefaultReturnType(); checkNotNull(returnType); } if (parametersNode == null) { throw new IllegalStateException( "All Function types must have params and a return type"); } FunctionType fnType; if (is...
python
def _getParameters(self): """Returns the result of this decorator.""" param = self.query._getParameters() index = self._getFilterIndex() param.update({ 'filter['+str(index)+'][columnAlias]' : self.__column, 'filter['+str(index)+'][data][type]' : self.__type, 'fil...
python
def adjustMinimumWidth( self ): """ Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown. """ if not self.showTitle(): return metrics = ...
python
def merge(a, b): """Merge two unicode Robot Framework reports so that report 'b' is merged into report 'a'. This merge may not be complete and may be is lossy. Still, note that the original single test reports will remain untouched. """ global loglevel # Iterate throughout the currently merged...
java
public final BooleanExpression loe(T right) { return Expressions.booleanOperation(Ops.LOE, mixin, ConstantImpl.create(right)); }
python
def _mk_connectivity_flats(self, i12, j1, j2, mat_data, flats, elev, mag): """ Helper function for _mk_adjacency_matrix. This calcualtes the connectivity for flat regions. Every pixel in the flat will drain to a random pixel in the flat. This accumulates all the area in the flat ...
java
public static ServerSocketBar createJNI(InetAddress host, int port) throws IOException { return currentFactory().create(host, port, 0, true); }
java
public Observable<Void> stopAsync(String resourceGroupName, String automationAccountName, UUID jobId) { return stopWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> res...
java
public Frustum setToFrustum ( double left, double right, double bottom, double top, double near, double far) { return setToProjection(left, right, bottom, top, near, far, Vector3.UNIT_Z, false, false); }
python
def reload(self): """ Reload file info and metadata * name * sha * pickcode """ res = self.api._req_file(self.fid) data = res['data'][0] self.name = data['file_name'] self.sha = data['sha1'] self.pickcode = data['pick_code']
python
def update(self, value: Union[RawValue, Value], raw: bool = False) -> "InstanceNode": """Update the receiver's value. Args: value: New value. raw: Flag to be set if `value` is raw. Returns: Copy of the receiver with the updated value. ...
python
def intersect_range_array(bed1,beds2,payload=None,is_sorted=False): """ Does not do a merge if the payload has been set :param bed1: :param bed2: :param payload: payload=1 return the payload of bed1 on each of the intersect set, payload=2 return the payload of bed2 on each of the union set, payload=3 return th...
java
void changedValue(Object value) { Object oldValue = super.putSilent(VALUE, value); if (!Objects.equals(oldValue, value)) { fireChange(); } }
python
def chained_get(container, path, default=None): """Helper function to perform a series of .get() methods on a dictionary and return a default object type in the end. Parameters ---------- container : dict The dictionary on which the .get() methods should be performed. path : list or tu...
java
public static double eigen(Matrix A, double[] v, double p, double tol, int maxIter) { if (A.nrows() != A.ncols()) { throw new IllegalArgumentException("Matrix is not square."); } if (tol <= 0.0) { throw new IllegalArgumentException("Invalid tolerance: " + tol); }...
java
@InterfaceAudience.Private DatabaseOptions getDefaultOptions(String databaseName) { DatabaseOptions options = new DatabaseOptions(); options.setEncryptionKey(encryptionKeys.get(databaseName)); return options; }
java
@GET @Path("search/dsl") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response searchUsingQueryDSL(@QueryParam("query") String dslQuery, @DefaultValue(LIMIT_OFFSET_DEFAULT) @QueryParam("limit") int limit, ...
python
def has_next_assessment_part(self, assessment_part_id): """This supports the basic simple sequence case. Can be overriden in a record for other cases""" if not self.supports_child_ordering or not self.supports_simple_child_sequencing: raise AttributeError() # Only available through a record...
python
def protocol_names(self): """Returns all registered protocol names""" l = self.protocols() retval = [str(k.name) for k in l] return retval
java
private void parseMethodSpec(String methodSpec) { methodName = null; methodInterface = null; methodSig = null; if (methodSpec != null) { StringTokenizer tokenizer = new StringTokenizer(methodSpec, ",", true); // Method name if (tokenizer.hasMoreTokens()) ...
java
@Override public List<NexusIQApplication> getApplications(String instanceUrl) { List<NexusIQApplication> nexusIQApplications = new ArrayList<>(); String url = instanceUrl + API_V2_APPLICATIONS; try { JSONObject jsonObject = parseAsObject(url); JSONArray jsonArray = (...
java
public static boolean isDateInThePast(final Date date) { boolean inPast = false; final Calendar compare = Calendar.getInstance(); compare.setTime(date); final Calendar now = Calendar.getInstance(); now.setTime(new Date(System.currentTimeMillis())); inPast = now.after(compare); return inPast; }
java
public boolean hasNewHeader(int position, boolean isReverseLayout) { if (indexOutOfBounds(position)) { return false; } long headerId = mAdapter.getHeaderId(position); if (headerId < 0) { return false; } long nextItemHeaderId = -1; int nextItemPosition = position + (isReverseLa...
python
def all(cls, start_position="", max_results=100, qb=None): """ :param start_position: :param max_results: The max number of entities that can be returned in a response is 1000. :param qb: :return: Returns list """ return cls.where("", start_position=start_position...
java
@Nullable public static TtlTimerTask get(@Nullable TimerTask timerTask) { return get(timerTask, false, false); }
java
public static void setGISCoordinateSystemAsDefault() { String v; try { v = System.getProperty("fr.utbm.set.math.defaultCoordinateSystem2D"); //$NON-NLS-1$ } catch (Throwable exception) { v = null; } CoordinateSystem2D cs2d = null; if (v != null) { cs2d = CoordinateSystem2D.valueOf(v); } if (cs...
java
@Override public UpdateDeviceStateResult updateDeviceState(UpdateDeviceStateRequest request) { request = beforeClientExecution(request); return executeUpdateDeviceState(request); }
python
def ForceRefresh(self, *args, **kwargs): """Refresh hook""" wx.grid.Grid.ForceRefresh(self, *args, **kwargs) for video_cell_key in self.grid_renderer.video_cells: if video_cell_key[2] == self.current_table: video_cell = self.grid_renderer.video_cells[video_cell_key]...
java
public boolean isAuthorized(HttpServletRequest req) { if(all)return true; if(roles!=null) { for(String srole : roles) { if(req.isUserInRole(srole)) return true; } } return false; }
python
def _get_module(module_name=None, module=None, register=True): """ finds module in sys.modules based on module name unless the module has already been found and is passed in """ if module is None and module_name is not None: try: module = sys.modules[module_name] except KeyError ...
java
@Nonnull private NonBlockingProperties _overrideWithSysProps (@Nonnull final NonBlockingProperties props) { Properties sysProps = null; try { sysProps = System.getProperties (); } catch (final AccessControlException e) { LOGGER.warn ("Skipping overriding MiniQuartz properties wit...
python
def target_to_ipv4_long(target): """ Attempt to return a IPv4 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) ...
python
def print_version(): """ Print out the current version, and at least try to fetch the latest from PyPi to print alongside it. It may seem odd that this isn't in globus_cli.version , but it's done this way to separate concerns over printing the version from looking it up. """ latest, current...
java
public void addImportName(ClassDesc classDesc, Class<?> importedClass) { String canonicalName = importedClass.getCanonicalName(); String packageName = ClassUtil.getPackageName(canonicalName); if (isImportTargetPackage(classDesc, packageName)) { classDesc.addImportName(canonicalName); } }
java
@Override public URL buildURLToFetchImage(long txid) { Preconditions.checkArgument(txid >= -1, "Invalid segment: %s", txid); Preconditions.checkState(httpPort != -1, "HTTP port not set yet"); try { // for now we disable throttling for image downloads String path = GetJournalImageServlet.build...
python
def _parse_linear_expression(expression, expanded=False, **kwargs): """ Parse the coefficients of a linear expression (linearity is assumed). Returns a dictionary of variable: coefficient pairs. """ offset = 0 constant = None if expression.is_Add: coefficients = expression.as_coeff...
java
public static PropertyBuilder getInstance(Context context, TypeElement typeElement, PropertyWriter writer) { return new PropertyBuilder(context, typeElement, writer); }
java
@Override public boolean removeFirstOccurrence(DelayedEntry entry) { DelayedEntry removedEntry = deque.pollFirst(); if (removedEntry == null) { return false; } decreaseCountIndex(entry); return true; }
java
protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){ String controllerPath = Router.getControllerPath(controllerClass); String contextPath = RequestContext.getHttpRequest().getContextPath(); String action = params.get("action") != null? params.get("acti...
python
def ignore( self, other ): """ Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('abl...
java
public Contact[] getSelectedContacts() { int[] selected = getTable().getSelectedRows(); Contact[] contacts = new Contact[selected.length]; for (int i = 0; i < selected.length; i++) { contacts[i] = (Contact) getTableModel().getElementAt(selected[i]); } return contacts; }
python
def in_casapy (helper, caltable=None, selectcals={}, plotoptions={}, xaxis=None, yaxis=None, figfile=None): """This function is run inside the weirdo casapy IPython environment! A strange set of modules is available, and the `pwkit.environments.casa.scripting` system sets up a very particular...
java
@Path("{id}") public InstanceResource getInstanceInfo(@PathParam("id") String id) { return new InstanceResource(this, id, serverConfig, registry); }
java
public static void debug(Object source, String message, Throwable t) { LoggerFactory.getInstance().log(LoggerLevel.DEBUG, source, message, t); }
python
def add_handler(self, event, handler): """Adds a handler for a particular event. Handlers are appended to the list, so a handler added earlier will be called before a handler added later. If you wish to insert a handler at another position, you should modify the event_handlers p...
python
def convert_to_shape(self, origin_x=0, origin_y=0): """Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. ...
python
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True): ''' Make a zip file `fn` from the contents of source_dis. ''' # selector function def select(fn): rfn = realpath(fn) for p in ignore_path: if p.endswith('/'): p = p[:-1] if ...
python
def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of ar...
python
def get(self, url): # type: (str) -> List[Model] """Get an arbitrary page. This resets the iterator and then fully consumes it to return the specific page **only**. :param str url: URL to arbitrary page results. """ self.reset() self.next_link = url ...
python
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response. """ info = get_user_info(remote) user_id = get_user_id(remote, info['preferred_username']) ...
java
private static void fillButtonSlot(CmsListItemWidget listItemWidget, int index, Widget widget, int[] slotMapping) { int realIndex = slotMapping[index]; if (realIndex >= 0) { SimplePanel panel = (SimplePanel)listItemWidget.getButton(slotMapping[index]); panel.clear(); ...
java
static String getServletPath(HttpServletRequest request) { String servletPath = request.getServletPath(); if (hackWorks && PACKAGE.equals(request.getClass().getPackage().getName())) { try { Object outer = get(request, "this$0"); Object servletPipeline = get(outer, "servletPipeline"); ...
python
def announcement_posted_email(request, obj, send_all=False): """Send a notification posted email. obj: The announcement object """ if settings.EMAIL_ANNOUNCEMENTS: subject = "Announcement: {}".format(obj.title) if send_all: users = User.objects.all() else: ...
python
def partition_expiration(self): """Union[int, None]: Expiration time in milliseconds for a partition. If :attr:`partition_expiration` is set and :attr:`type_` is not set, :attr:`type_` will default to :attr:`~google.cloud.bigquery.table.TimePartitioningType.DAY`. """ war...
java
void registerMBean(Configuration conf) { // We wrap to bypass standard mbean naming convention. // This wraping can be removed in java 6 as it is more flexible in // package naming for mbeans and their impl. StandardMBean bean; try { versionBeanName = VersionInfo.registerJMX("NameNode"); ...