language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def online(note, github_repository, github_username): """Upload the repository to GitHub and enable testing on Travis CI.""" callbacks.git_installed() try: repo = git.Repo() except git.InvalidGitRepositoryError: LOGGER.critical( "'memote online' requires a git repository in o...
python
def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ r = form.save(commit=False) parent_id = request.REQUEST.get('parent_id', None) if pa...
java
public void processLocalTransactionCommittedEvent(Object handle) throws ResourceException { // A application level local transaction has been committed. final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn) { if (tc.isEntryEnabled()) ...
python
def really_unicode(in_string): """Make a string unicode. Really. Ensure ``in_string`` is returned as unicode through a series of progressively relaxed decodings. Args: in_string (str): The string to convert. Returns: str: Unicode. Raises: ValueError """ if...
java
private void fillOrder(JsonObject summary) { if (summary != null) { order = summary.getString("order", order); } if (order == null && openGraphCommentOrder != null) { order = openGraphCommentOrder; } }
python
def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> Awaitable["HTTPResponse"]: """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. ...
python
def _routes_updated(self, ri): """Update the state of routes in the router. Compares the current routes with the (configured) existing routes and detect what was removed or added. Then configure the logical router in the hosting device accordingly. :param ri: RouterInfo correspo...
python
def build_arch(self, arch): """ Creates expected build and symlinks system Python version. """ self.ctx.hostpython = '/usr/bin/false' # creates the sub buildir (used by other recipes) # https://github.com/kivy/python-for-android/issues/1154 sub_build_dir = join(se...
java
public static void main(String[] args) { try { final NetworkMonitor m = new NetworkMonitor(args, null); // supply a log writer for System.out (console) m.w = new ConsoleWriter(m.options.containsKey("verbose")); m.run(m.new MonitorListener()); } catch (final Throwable t) { if (t.getMessage...
python
def color_mod(self): """Tuple[int, int, int]: The additional color value used in render copy operations in (red, green, blue) format. """ rgb = ffi.new('Uint8[]', 3) check_int_err(lib.SDL_GetTextureColorMod(self._ptr, rgb + 0, rgb + 1, rgb + 2)) r...
java
public static<T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception { T result = null; RetryLoop retryLoop = client.newRetryLoop(); while ( retryLoop.shouldContinue() ) { try { client.inte...
python
def filter_paragraph(p): """Simple filter to remove obviously bad paragraphs (bad text extraction). Note this needs to run very quickly as it is applied to every paragraph in the corpus, so nothing fancy! This whole method should be linear expected time in len(p). Args: p: string, paragraph Returns: ...
python
def spkpos(targ, et, ref, abcorr, obs): """ Return the position of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpos_c.html :param targ: Target body name...
java
public synchronized void add(int index, Layer layer, boolean redraw) { checkIsNull(layer); layer.setDisplayModel(this.displayModel); this.layersList.add(index, layer); layer.assign(this.redrawer); if (redraw) { this.redrawer.redrawLayers(); } }
java
public VertexElement addVertexElement(Schema.BaseType baseType) { Vertex vertex = graph.addVertex(baseType.name()); return new VertexElement(tx, vertex); }
java
public Job playJob(Object projectIdOrPath, int jobId) throws GitLabApiException { GitLabApiForm formData = null; Response response = post(Status.CREATED, formData, "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "play"); return (response.readEntity(Job.class)); }
java
public List<String> getInterfaces() { int size = readValue(endOfPool + 6); if (size == 0) return Collections.emptyList(); List<String> result = new ArrayList<String>(); for (int i = 0; i < size; i++) { result.add(getClassName(readValue(endOfPool + 8 + (i * 2)))); } return result; }
python
def free_norm(self, name, free=True, **kwargs): """Free/Fix normalization of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False). """ name = self.get_source_name(nam...
java
public static long count(nitro_service service, String certkey) throws Exception{ sslcertkey_crldistribution_binding obj = new sslcertkey_crldistribution_binding(); obj.set_certkey(certkey); options option = new options(); option.set_count(true); sslcertkey_crldistribution_binding response[] = (sslcertkey_crl...
python
def run(self, *args): """Get and set configuration parameters. This command gets or sets parameter values from the user configuration file. On Linux systems, configuration will be stored in the file '~/.sortinghat'. """ params = self.parser.parse_args(args) conf...
python
def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='Scale set name') arg_parser.add_argument('--rgname', '-g', required=True, action='sto...
java
protected String getHeader( final ITransaction transaction, final String path, final WebdavResponse resp, final WebdavRequest req ) { return "<h1>Content of folder " + path + "</h1>"; }
java
public void update( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"update write-locked "+_key+" by job "+job_key); new Update(job_key).invoke(_key); }
java
@Override public void prepare(FeatureProvider provider) { super.prepare(provider); animator = provider.getFeature(Animatable.class); transformable = provider.getFeature(Transformable.class); if (provider instanceof AttackerListener) { addListener((...
java
DatanodeCommand[] handleHeartbeat(DatanodeRegistration nodeReg, long capacity, long dfsUsed, long remaining, long namespaceUsed, int xceiverCount, int xmitsInProgress) throws IOException { DatanodeCommand cmd = null; synchronized (heart...
python
def _get_next_object(self, object_class): """stub""" next_object = OsidList.next(self) if isinstance(next_object, dict): next_object = object_class(osid_object_map=next_object, runtime=self._runtime, proxy=self._proxy) elif is_string(next_object) and object_class == Id: ...
java
public boolean read(DataInputStream daIn, boolean bFixedLength) // Fixed length = false { try { String string = null; if (bFixedLength) { // HACK Change this to use the system's default byte to char encoding byte[] byData = new byte[this.getMaxLength()...
java
protected InvocationHandler createHandler(Class<? extends NlsBundle> bundleInterface) { String bundleName = NlsBundleHelper.getInstance().getQualifiedLocation(bundleInterface); NlsBundleOptions options = getBundleOptions(bundleInterface); return new NlsBundleInvocationHandler(bundleInterface, bundleName, o...
java
public boolean add(Boolean value) { if (value == null) { stateList.add(Type.NULL); } else { stateList.add(Type.BOOLEAN); } return super.add(value); }
java
protected void preemptTasksIfNecessary() { if (!preemptionEnabled || jobComparator == JobComparator.FIFO) return; long curTime = clock.getTime(); if (curTime - lastPreemptCheckTime < preemptionInterval) return; lastPreemptCheckTime = curTime; int currentMaxPreemptibleTasks = maxPreempt...
python
def _get_v(self, rho): """ convert density in g/cm^3 to unit-cell volume :param rho: density in g/cm^3 :return: unit-cell volume in A^3 :note: internal function """ v_mol = self.mass / rho # in cm^3 v = vol_mol2uc(v_mol * 1.e-6, self.z) print(v)...
java
protected void reportCastWarnings(JvmTypeReference concreteSyntax, LightweightTypeReference toType, LightweightTypeReference fromType) { if (!isIgnored(OBSOLETE_CAST) && toType.isAssignableFrom(fromType)) { addIssue(MessageFormat.format(Messages.SARLValidator_96, fromType.getHumanReadableName(), toType.getHum...
python
def handle_payload(self, payload): """ Given a crash report (JSON represented payload), attempts to upload the crash reports. Calls the default exception handler (sys.__except_hook__) upon completion. :param payload: JSON structure containing crash report along with metadata :ret...
python
def create_key(key_type='RSA', key_length=1024, name_real='Autogenerated Key', name_comment='Generated by SaltStack', name_email=None, subkey_type=None, subkey_length=None, expire_date=None, use_passp...
python
def load_response_microservices(plugin_path, plugins, internal_attributes, base_url): """ Loads response micro services (handling outgoing responses). :type plugin_path: list[str] :type plugins: list[str] :type internal_attributes: dict[string, dict[str, str | list[str]]] :type base_url: str ...
python
def _redundant_stack_variable_removal(self, function, data_graph): """ If an argument passed from the stack (i.e. dword ptr [ebp+4h]) is saved to a local variable on the stack at the beginning of the function, and this local variable was never modified anywhere in this function, and no pointer ...
python
def parse_slab_stats(slab_stats): """Convert output from memcached's `stats slabs` into a Python dict. Newlines are returned by memcached along with carriage returns (i.e. '\r\n'). >>> parse_slab_stats( "STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT " "active_sla...
java
public boolean abandonBlock(Block b, String src, String holder ) throws IOException { writeLock(); try { // // Remove the block from the pending creates list // if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " ...
python
def insert_column_with_attributes(self, position, title, cell, **kwargs): """ :param position: The position to insert the new column in :type position: :obj:`int` :param title: The title to set the header to :type title: :obj:`str` :param cell: The :obj:`Gtk.CellRendere...
python
def _check_response(response, items, default, indexed, stream, insensitive, fuzzy): '''Check the response against the items''' # Set selection selection = None # if indexed, check for index if indexed: if response.isdigit(): index_response = int(response) if index_res...
java
public boolean addProperty(String propertyName) { if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(propertyName)) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ADD_PROP_1, propertyName)); } return m_properties.add(propertyNam...
java
public static void setSessionTicketKeys(long ctx, SessionTicketKey[] keys) { if (keys == null || keys.length == 0) { throw new IllegalArgumentException("Length of the keys should be longer than 0."); } byte[] binaryKeys = new byte[keys.length * SessionTicketKey.TICKET_KEY_SIZE]; ...
java
public static final void texture(final Shape shape, final Image image, final float scaleX, final float scaleY, final ShapeFill fill) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float center...
python
def ops(self, start=None, stop=None, only_virtual_ops=False): """ Yields all operations (including virtual operations) starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between ...
python
def nvmlDeviceRegisterEvents(handle, eventTypes, eventSet): r""" /** * Starts recording of events on a specified devices and add the events to specified \ref nvmlEventSet_t * * For Fermi &tm; or newer fully supported devices. * Ecc events are available only on ECC enabled devices (see \ref n...
java
public void marshall(GetJobTemplateRequest getJobTemplateRequest, ProtocolMarshaller protocolMarshaller) { if (getJobTemplateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getJobTemplateRe...
java
private void validateJobName(String jobName) throws NoSuchJobException { if (!getJobNames().contains(jobName)) { logger.fine("Job Name " + jobName + " not found"); throw new NoSuchJobException("Job Name " + jobName + " not found"); } }
python
def collect_program_info(self, fname): """ gets details on the program, size, date, list of functions and produces a Markdown file for documentation """ md = '#AIKIF Technical details\n' md += 'Autogenerated list of programs with comments and progress\n' md += '\n...
java
@Override public R finish(Collection<? extends OutputWriter<O>> writers) throws IOException { ImmutableList.Builder<OutputWriter<ByteBuffer>> sinkWriters = ImmutableList.builder(); for (OutputWriter<O> w : writers) { Writer<O> writer = (Writer<O>) w; sinkWriters.add(writer.out); } return s...
java
private void initDescriptor() throws CmsXmlException, CmsException { if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) { m_desc = m_resource; } else { //First try to read from same folder like resource, if it fails use CmsMessageBundleEditorTypes.getDes...
python
def get_settings(self): '''get all settings for a client, if defined in config. ''' config = self._load_config_user() if self.name in config: return config[self.name]
java
private void handleWanSyncMap(HttpPostCommand command) throws UnsupportedEncodingException { String res; final String[] params = decodeParams(command, 3); final String wanRepName = params[0]; final String publisherId = params[1]; final String mapName = params[2]; try { ...
python
def query_user_page(url, retry=10): """ Returns the scraped user data from a twitter user page. :param url: The URL to get the twitter user info from (url contains the user page) :param retry: Number of retries if something goes wrong. :return: Returns the scraped user data from a twitter user page...
java
public OcrResult recognizePrintedTextInStream(boolean detectOrientation, byte[] image, RecognizePrintedTextInStreamOptionalParameter recognizePrintedTextInStreamOptionalParameter) { return recognizePrintedTextInStreamWithServiceResponseAsync(detectOrientation, image, recognizePrintedTextInStreamOptionalParamete...
java
private Segment segupdate(double xend, double yend, int dir, boolean tail, Segment[] seg) { Segment seglist = seg[0]; if (seglist == null) { seg[1] = null; return null; } switch (dir) { case 1: case 3: if (YMATCH(yend, segl...
java
private void parseFile(File schemaSourceFile, CourierParseResult result) throws IOException { if (wasResolved(schemaSourceFile)) { return; } final List<DataSchema> schemas = parseSchema(schemaSourceFile, result); for (DataSchema schema : schemas) { validateSchemaWithFilePat...
java
public static IntSummary of(final IntSummaryStatistics statistics) { return new IntSummary( statistics.getCount(), statistics.getMin(), statistics.getMax(), statistics.getSum(), statistics.getAverage() ); }
java
@Override public boolean hasKey(String scope, Object key) throws Exception { return getScopeCache(scope).isKeyInCache(key); }
python
def __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. try: ...
python
def show_std_icons(): """ Show all standard Icons """ app = qapplication() dialog = ShowStdIcons(None) dialog.show() sys.exit(app.exec_())
python
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *...
java
@Override public boolean getRendersChildren() { boolean value = super.getRendersChildren(); FacesContext context = FacesContext.getCurrentInstance(); if (context.getPartialViewContext().isAjaxRequest()) { value = true; } return value; }
python
def _prepare_data(data, transformed, klass, *args, **kwargs): """Transform data for binning. Returns ------- np.ndarray """ # TODO: Maybe include in the class itself? data = np.asarray(data) if not transformed: data = klass.transform(data) dropna = kwargs.get("dropna", Fals...
python
def hash_coloured_escapes(text): """Return the ANSI hash colour prefix and suffix for a given text""" ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230 prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT') return prefix, suffix
java
public String captureEntirePageScreenshot() { String imageName = generateImageName(); String imageLink = generateImageLink(imageName); try { app.takeScreenshot(imageName); screenshots.add(imageName); } catch (Exception e) { log.error(e); im...
java
protected void doConvert(IProject project, IProgressMonitor monitor) throws ExecutionException { monitor.setTaskName(MessageFormat.format(Messages.RemoveSarlNatureHandler_2, project.getName())); final SubMonitor mon = SubMonitor.convert(monitor, 2); if (this.configurator.canUnconfigure(project, mon.newChild(1))) ...
java
public static List<String> complementaryPyCcLib() throws IOException { if (complementaryLibs == null) { complementaryLibs = new LinkedList<String>(); InputStream inputStream = API.class.getClassLoader().getResourceAsStream(FILE); PropertyResourceBundle labels = new PropertyResourceBundle(inputStream); Enu...
python
def cast( source: Union[DataType, str], target: Union[DataType, str], **kwargs ) -> DataType: """Attempts to implicitly cast from source dtype to target dtype""" source, result_target = dtype(source), dtype(target) if not castable(source, result_target, **kwargs): raise com.IbisTypeError( ...
java
public void createLaunchConfig(String launchConfigName, String imageId, String instanceType, String keyName, String securityGroups, Optional<String> kernelId, Optional<String> ramdiskId, Optional<BlockDeviceMapping> blockDeviceMapping, Optional<String> iamInstanceProfile,...
python
def get_resources(self, type: Type[T_Resource]) -> Set[T_Resource]: """ Retrieve all the resources of the given type in this context and its parents. Any matching resource factories are also triggered if necessary. :param type: type of the resources to get :return: a set of all...
java
private static SubstUnitInfo genFinalSubstUnitInfoMapsHelper( RepresentativeNodes representativeNodes) { // ------ Step 1: Build final map of var name to representative node. ------ // // The final map substUnitVarNameToRepNodeMap must be a one-to-one mapping. If a base name only // maps to one r...
python
def attr_membership(attr_val, value_set, attr_type=basestring, modifier_fn=lambda x: x): """ Helper function passed to netCDF4.Dataset.get_attributes_by_value Checks that `attr_val` exists, has the same type as `attr_type`, and is contained in `value_set` attr_val: The valu...
python
def requests_session(self, *args, **kwargs): """ Create :class:`requests.Session` that is authorized for the current user. `args` and `kwargs` are passed directly to :class:`requests.Session` """ import requests auth1 = self.generate_auth() return request...
java
public void setGlobalVariable(String name, Element value) { assert (name != null); GlobalVariable gvar = globalVariables.get(name); gvar.setValue(value); }
python
def check_sub_path_create(sub_path): """ 检查当前路径下的某个子路径是否存在, 不存在则创建; :param: * sub_path: (string) 下一级的某路径名称 :return: * 返回类型 (tuple),有两个值 * True: 路径存在,False: 不需要创建 * False: 路径不存在,True: 创建成功 举例如下:: print('--- check_sub_path_create demo ---') #...
python
def add_listener(self, on_message=None): """ Subscribes to this topic. When someone publishes a message on this topic, on_message() function is called if provided. :param on_message: (Function), function to be called when a message is published. :return: (str), a registration id...
java
@Override protected void resizeDynamicText() { double maxWidth = width - size * 0.1; double fontSize = size * 0.3; timeText.setFont(Fonts.latoRegular(fontSize)); timeText.setText(timeFormatter.format(tile.getTime())); Helper.adjustTextSize(timeText, maxWidth, fontSize); ...
python
def get_queryset(self): ''' Only serve site-specific languages ''' request = self.request return (Languages.for_site(request.site) .languages.filter().order_by('pk'))
python
def register_interaction(key=None): """Decorator registering an interaction class in the registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot interaction type so that the frontend can use this key regardless of the kernal language. """ def wra...
python
def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)): """ maximum filter of given size Parameters ---------- data: 2 or 3 dimensional ndarray or OCLArray of type float32 input data size: scalar, tuple the size of the patch to consider res_g: OCLArray st...
python
def save(self, file_path): """ Method to save the dataset to disk. Parameters ---------- file_path : str File path to save the current dataset to Raises ------ IOError If saving to disk is not successful. """ # T...
java
@Override public synchronized void close() throws IOException { // cancel synchronization try { if (syncTask != null) { syncTask.cancel(); } sync(); unmapFile(); } finally { super.close(); } }
python
def validate(self, instance, value): """Checks if value is an open PNG file, valid filename, or png.Image Returns an open bytestream of the image """ # Pass if already validated if getattr(value, '__valid__', False): return value # Validate that value is PNG ...
java
public com.squareup.okhttp.Call getUniverseStargatesStargateIdAsync(Integer stargateId, String datasource, String ifNoneMatch, final ApiCallback<StargateResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getUniverseStargatesStargateIdValidateBeforeCall(stargateId, datasource,...
java
public AuthorizationIssueRequest setClaims(Map<String, Object> claims) { if (claims == null || claims.size() == 0) { this.claims = null; return this; } String json = Utils.toJson(claims); return setClaims(json); }
python
def read_node_status(self, name, **kwargs): # noqa: E501 """read_node_status # noqa: E501 read status of the specified Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api....
python
def postinit(self, items=None, body=None, type_annotation=None): """Do some setup after initialisation. :param items: The pairs of context managers and the names they are assigned to. :type items: list(tuple(NodeNG, AssignName or None)) or None :param body: The contents of ...
python
def deriv(self, p): """ Derivative of the power transform Parameters ---------- p : array-like Mean parameters Returns -------- g'(p) : array Derivative of power transform of `p` Notes ----- g'(`p`) = `pow...
python
def get_file(self, filename): """Get file source from cache""" import linecache # Hack for frozen importlib bootstrap if filename == '<frozen importlib._bootstrap>': filename = os.path.join( os.path.dirname(linecache.__file__), 'importlib', '_b...
python
def getToC(doc, simple = True): """Create a table of contents. Args: simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. """ def recurse(olItem, liste...
python
def ad_unif_inf(statistic): """ Approximates the limiting distribution to about 5 decimal digits. """ z = statistic if z < 2: return (exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (.247105 - (.0649821 - (.0347962 - (.011672 - .0016...
java
public static <T> Collection<T> removeNull(Collection<T> collection) { return filter(collection, new Editor<T>() { @Override public T edit(T t) { // 返回null便不加入集合 return t; } }); }
python
def mad(v): """MAD -- Median absolute deviation. More robust than standard deviation. """ return np.median(np.abs(v - np.median(v)))
java
private void showHiddenTabPopup() { JPopupMenu menu = new JPopupMenu(); if (getMousePosition() == null) { // Startup return; } Collections.sort(this.hiddenTabs, NAME_COMPARATOR); for (Component c : this.hiddenTabs) { if (c instanceof AbstractPanel) { final AbstractPanel ap = (AbstractPanel)c; ...
python
def get_tname(self, var, coords=None): """Get the name of the t-dimension This method gives the name of the time dimension Parameters ---------- var: xarray.Variables The variable to get the dimension for coords: dict The coordinates to use for c...
java
public void addLinkRef(final String key, final LinkRef linkRef) { this.linkRefs.put(key.toLowerCase(), linkRef); }
python
def parse (cls, line, lineno, log, cmddict=None): """Parses the SeqDelay from a line of text. Warning and error messages are logged via the SeqMsgLog log. """ delay = -1 token = line.split()[0] start = line.find(token) pos = SeqPos(line, lineno, start + 1, start + len(token)) try: ...
python
def popup(self): """ Show the notification from code. This will initialize and activate if needed. Notes ------ This does NOT block. Callbacks should be used to handle click events or the `show` state should be observed to know when it is closed. ...
python
def gets(self, keyword): """Return the element of the list after the given keyword as string. Parameters ---------- keyword : str The keyword parameter to find in the list. Putting a colon before the keyword is optional, if no colon is given, it is ad...
java
static <D, S> TypeAdapter<D, S> getTypeAdapter(Class<D> cls) { return (TypeAdapter<D, S>) sAdapterHolder.getTypeAdapter(cls); }