language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def addJobShape(self, jobShape): """ Function adds the job to the first node reservation in which it will fit (this is the bin-packing aspect). """ chosenNodeShape = None for nodeShape in self.nodeShapes: if NodeReservation(nodeShape).fits(jobShape): ...
java
public String getString() { String string = super.getString(); if ((string != null) && (string.length() > 0)) string = this.decodeString(string); return string; }
java
protected void unsetSecurityService(SecurityService securityService) { SibTr.entry(tc, CLASS_NAME + "unsetSecurityService", securityService); SibTr.exit(tc, CLASS_NAME + "unsetSecurityService"); }
java
public Selector intern(InternTable table) { // This implementation is inherited by Identifier and Literal which have no children, // but is overridden in Operator, which does. Selector me = (Selector) table.get(this); if (me != null) { me.incRefCount(); return me; } else { ...
java
public int locateIndex(int index) { int min = 0; int max = this.indexValues.length - 1; if (max == -1) { return -1; } // Binary search while ((this.indexValues[min] <= index) && (this.indexValues[max] >= index)) { int current = (max + min) / 2; ...
java
public void leverageTo(String id) { if (fwdPassOutput != null) fwdPassOutput = fwdPassOutput.leverageTo(id); if (fwdPassOutputAsArrays != null) for (int i = 0; i < fwdPassOutputAsArrays.length; i++) fwdPassOutputAsArrays[i] = fwdPassOutputAsArrays[i].leverageTo(...
java
public boolean hasClass(String className) { final String classAttr = attributes().getIgnoreCase("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } // if both lengths are equa...
java
public static Map<String, String> processArchiveManifest(final JarFile jarFile) throws Throwable { Map<String, String> manifestAttrs = null; if (jarFile != null) { try { manifestAttrs = AccessController.doPrivileged(new PrivilegedExceptionAction<Map<String, String>>() { ...
python
def mu(self): """See docs for `Model` abstract base class.""" mu = self._models[0].mu assert all([mu == model.mu for model in self._models]) return mu
python
def fprocess(infilep,outfilep): """ Scans an input file for LA equations between double square brackets, e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression with a comment containing the equation followed by nested function calls that implement the equation as C code. A trailin...
python
def distill_resnet_32_to_15_cifar20x5(): """Set of hyperparameters.""" hparams = distill_base() hparams.teacher_model = "resnet" hparams.teacher_hparams = "resnet_cifar_32" hparams.student_model = "resnet" hparams.student_hparams = "resnet_cifar_15" hparams.optimizer_momentum_nesterov = True # (base_lr...
python
def load(self, target_type, target_id, target_parent_id=None): """ Constructs and immediately loads the object, circumventing the lazy-loading scheme by immediately making an API request. Does not load related objects. For example, if you wanted to load an :any:`Instance` objec...
java
@NoAuth @RequestMapping(value = "/session", method = RequestMethod.GET) @ResponseBody public JsonObjectBase get() { VisitorVo visitorVo = userMgr.getCurVisitor(); if (visitorVo != null) { return buildSuccess("visitor", visitorVo); } else { // 没有登录啊 ...
python
def team_settings_edit_event(self, value=None): """ Handles the events when editing a value regarding the team settings :param value: the new value to store in the config :return: """ sender = self.sender() if value is None: value = sender.text() ...
python
def report_device_attributes(self, mode=0, **kwargs): """Report terminal identity. .. versionadded:: 0.5.0 .. versionchanged:: 0.7.0 If ``private`` keyword argument is set, the method does nothing. This behaviour is consistent with VT220 manual. """ # We ...
python
def compiler_preprocessor_verbose(compiler, extraflags): """Capture the compiler preprocessor stage in verbose mode """ lines = [] with open(os.devnull, 'r') as devnull: cmd = [compiler, '-E'] cmd += extraflags cmd += ['-', '-v'] p = Popen(cmd, stdin=devnull, stdout=PIPE...
python
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" files = list(files) patterns = self._get_platform_patterns( self.exclude_package_data, package, src_dir, ) match_groups = ( ...
python
def prepare(self): """No percolator XML for protein tables""" self.target = self.fn self.targetheader = reader.get_tsv_header(self.target) self.decoyheader = reader.get_tsv_header(self.decoyfn)
python
def is_port_default(self): '''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
java
public boolean matches(URL url) { boolean matches = false; if(wildcardMatches(protocol, url.getProtocol()) && wildcardMatches(host, url.getHost()) && wildcardMatches(getPath(), url.getPath())) { matches = true; } return matches; }
python
def ising_to_qubo(h, J, offset=0.0): """Convert an Ising problem to a QUBO problem. Map an Ising model defined on spins (variables with {-1, +1} values) to quadratic unconstrained binary optimization (QUBO) formulation :math:`x' Q x` defined over binary variables (0 or 1 values), where the linear ter...
java
public static Integer parseInteger(String value, Integer defaultValue) { if (isNullOrEmpty(value)) { return defaultValue; } return Integer.parseInt(value); }
python
def annotate(self, ax, **kwargs): """ Draws the annotation box for the given axis *ax*. Additional kwargs are passed on to ``annotate``. """ def update_from_defaults(key, kwargs): if kwargs.get(key, None) is not None: new = copy.deepcopy(self.default_a...
java
public String get(String code, Object... arguments) { try { return getMessage(code, null, arguments); } catch (NoSuchMessageException ex) { logger.warn("Tried to retrieve message with code [{}] that does not exist", code); return "!" + code; } }
python
def record(self): # type: () -> bytes ''' A method to generate the string representing this UDF Logical Volume Descriptor. Parameters: None. Returns: A string representing this UDF Logical Volume Descriptor. ''' if not self._initialized: ...
java
@Override @SuppressWarnings("unchecked") //welcomes a ClassCastException on misuse of @Serialize(Custom.class) protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) { try { if(request instanceof HttpEntityEnclosingRequestBase) { List<Entry<Entity, Object>> entities = Met...
python
def receive(self, msg): ''' Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function ''' handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None) if handler is None: raise Invali...
java
public static CmsRectangle fromPoints(CmsPoint topLeft, CmsPoint bottomRight) { CmsRectangle result = new CmsRectangle(); result.m_left = topLeft.getX(); result.m_top = topLeft.getY(); result.m_width = bottomRight.getX() - topLeft.getX(); result.m_height = bottomRight.getY() - t...
python
def vm_state(name='', cwd=None): ''' Return list of information for all the vms indicating their state. If you pass a VM name in as an argument then it will return info for just the named VM, otherwise it will return all VMs defined by the Vagrantfile in the `cwd` directory. CLI Example: ...
python
def ToDeltas(self): """Convert the sequence to the sequence of differences between points. The value of each point v[i] is replaced by v[i+1] - v[i], except for the last point which is dropped. """ if len(self.data) < 2: self.data = [] return for i in range(0, len(self.data) - 1): ...
java
@SuppressWarnings("unchecked") public EList<Double> getCoordinates() { return (EList<Double>) eGet(Ifc2x3tc1Package.Literals.IFC_CARTESIAN_POINT__COORDINATES, true); }
java
@Override protected ProcessOutput executeProcessImpl(ConfigurationHolder configurationHolder,String command) throws IOException,InterruptedException { //parse command List<String> commandList=this.parseCommand(configurationHolder,command); //invoke process ProcessBuilder...
java
protected UserAction getUserAction(User user, String path, Object content, Map<String,String> headers) { Action action = getAction(path, content, headers); Entity entity = getEntity(path, content, headers); Long entityId = getEntityId(path, content, headers); String descrip = getEntityDe...
java
public static DownloadProperties forRelease(final String release, final File destination) { return new DownloadProperties(new WgetGithubDownloader(release), destination); }
java
public static boolean isStandaloneRunning(final ModelControllerClient client) { try { final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, "server-state")); if (Operations.isSuccessfulOutcome(response)) { final String state = Op...
python
def i2c_read_request(self, address, register, number_of_bytes, read_type, cb=None, cb_type=None): """ This method issues an i2c read request for a single read,continuous read or a stop, specified by the read_type. Because different i2c devices return data at diff...
python
def format(self, record): """ Apply level-specific styling to log records. :param record: A :class:`~logging.LogRecord` object. :returns: The result of :func:`logging.Formatter.format()`. This method injects ANSI escape sequences that are specific to the level of each l...
python
def _copy_files(source, target): """ Copy all the files in source directory to target. Ignores subdirectories. """ source_files = listdir(source) if not exists(target): makedirs(target) for filename in source_files: full_filename = join(source, filename) if isfile(fu...
java
public static String encodeUrlSafe(String source, String charset) { return encodeUrlSafe(StrUtil.bytes(source, charset), charset); }
java
@Nullable private ThreadPoolExecutor unwrapThreadPoolExecutor(ExecutorService executor, Class<?> wrapper) { try { Field e = wrapper.getDeclaredField("e"); e.setAccessible(true); return (ThreadPoolExecutor) e.get(executorService); } catch (NoSuchFieldException | Il...
python
def subcommand(f): """ Define a subcommand for the psychic_disco function Expects functions to supply a list of their arguments Converts these to arg_parse arguments, and transforms the argparse Namespace object so that commands can be invoked as though they are normal functions (which they are)""" ...
java
public SettingsPack maxPeerlistSize(int value) { sp.set_int(settings_pack.int_types.max_peerlist_size.swigValue(), value); return this; }
python
def count(start=0, step=1, *, interval=0): """Generate consecutive numbers indefinitely. Optional starting point and increment can be defined, respectively defaulting to ``0`` and ``1``. An optional interval can be given to space the values out. """ agen = from_iterable.raw(itertools.count(sta...
java
@Nonnull public static Point fromMicroDeg(final int latMicroDeg, final int lonMicroDeg) { final Point p = new Point(); p.latMicroDeg = latMicroDeg; p.latFractionOnlyDeg = 0; p.lonMicroDeg = lonMicroDeg; p.lonFractionOnlyDeg = 0; p.defined = true; return p.wrap...
java
protected RuntimeEnvironmentBuilder boostrapRuntimeEnvironmentBuilder(KModuleDeploymentUnit deploymentUnit, DeployedUnit deployedUnit, KieContainer kieContainer, MergeMode mode) { DeploymentDescriptor descriptor = deploymentUnit.getDeploymentDescriptor(); if (descriptor == null || ((DeploymentDescriptor...
java
private static boolean tryEncoding(byte[] sig, byte b1, byte b2, byte b3, byte b4) { return ((sig[0] == b1) && (sig[1] == b2) && (sig[2] == b3) && (sig[3] == b4)); }
python
def copy_pkg(self, filename, _): """Copy a package to the repo's Package subdirectory. Args: filename: Path for file to copy. _: Ignored. Used for compatibility with JDS repos. """ basename = os.path.basename(filename) self._copy(filename, os.path.join(se...
python
async def unlock(self, device): """ Unlock the device if not already unlocked. :param device: device object, block device path or mount path :returns: whether the device is unlocked """ device = self._find_device(device) if not self.is_handleable(device) or not d...
python
def longestNumber(self, inp): """Extracts the longest valid numerical description from a string. Not guaranteed to return a result even if some valid numerical description exists (i.e., method is not particularly advanced). Args: inp (str): An arbitrary string, hopefully con...
java
@ProbeAtEntry @ProbeSite(clazz="com.ibm.ws.session.SessionEventDispatcher",method="sessionLiveCountInc",args="java.lang.Object") public void IncrementLiveCount(@Args Object[] myargs ) { if(tc.isEntryEnabled()){ Tr.entry(tc, "IncrementLiveCount"); } ...
java
public static Predicate<Triple> filterWithLDF(final String subject, final String predicate, final String object) { return triple -> !(notCompareWithString(triple.getSubject(), subject) || notCompareWithString(triple.getPredicate(), predicate) || notCompareWith...
python
def _is_lang_change(self, request): """Return True if the lang param is present and URL isn't exempt.""" if 'lang' not in request.GET: return False return not any(request.path.endswith(url) for url in self.exempt_urls)
java
public Future<?> submit(Runnable task) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask<Void> futureTask = new InternalFutureTask<Void>(new FutureTask<Void>(task, null)); executorService.execute(futureTask); return futureTask; }
java
public void marshall(DescribeMatchmakingRuleSetsRequest describeMatchmakingRuleSetsRequest, ProtocolMarshaller protocolMarshaller) { if (describeMatchmakingRuleSetsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
java
public LockResult lock( final TaskLockType lockType, final Task task, final Interval interval ) throws InterruptedException { giant.lockInterruptibly(); try { LockResult lockResult; while (!(lockResult = tryLock(lockType, task, interval)).isOk()) { if (lockResult.isRevo...
java
public static cuDoubleComplex cuCmul (cuDoubleComplex x, cuDoubleComplex y) { cuDoubleComplex prod; prod = cuCmplx ((cuCreal(x) * cuCreal(y)) - (cuCimag(x) * cuCimag(y)), (cuCreal(x) * cuCimag(y)) + (cuCimag(x) * cuCreal(y))); return prod; }
python
def length_longest_path(input): """ :type input: str :rtype: int """ curr_len, max_len = 0, 0 # running length and max length stack = [] # keep track of the name length for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') #...
java
public boolean send(String topic, String message) throws IOException { List<Session> sessions = topicSubscribers.get(topic); if (sessions != null) { for (Session session : sessions) { session.getBasicRemote().sendText(message); } } return sessions ...
python
def snapshot_data_item(self, data_item: DataItem) -> DataItem: """Snapshot a data item. Similar to copy but with a data snapshot. .. versionadded:: 1.0 Scriptable: No """ data_item = data_item._data_item.snapshot() self.__document_model.append_data_item(data_item) ...
java
public final CompletableFuture<Integer> sendMap(boolean last, Object... messages) { return send(true, messages, last); }
java
public FilterList getFilter(XPath condition, boolean passAll, String []famNames, String []qualNames, String []params) { FilterList list = new FilterList((passAll)?FilterList.Operator.MUST_PASS_ALL: FilterList.Operator.MUST_PASS_ONE); for (int iCont = 0; iCont < famNames.length; iCont...
java
@Override public Long getIdPartAsLong() { String val = getIdPart(); if (isBlank(val)) { return null; } return Long.parseLong(val); }
python
def delete_file( source_path, allow_undo=True, no_confirm=False, silent=False, extra_flags=0, hWnd=None ): """Perform a shell-based file delete. Deleting in this way uses the system recycle bin, allows the possibility of undo, and showing the "flying file" animation during the de...
python
def runCmd(cls, cmd): """run command and show if success or failed Args: cmd: string Returns: bool: if this command run successfully """ cit.echo(cmd, "command") result = os.system(cmd) cls.checkResult(result)
python
def dissolved_fardal_stream(hamiltonian, prog_orbit, prog_mass, t_disrupt, release_every=1, Integrator=DOPRI853Integrator, Integrator_kwargs=dict(), snapshot_filename=None, output_every=1, seed=None): """ Generate a mock stellar stream in the specified pot...
python
def parse_token(self, token): """ Obtain a user from a signed token. """ try: data = self.unsign(token) except signing.SignatureExpired: logger.debug("Expired token: %s", token) return except signing.BadSignature: logger.de...
java
public static Map<String, IDLProxyObject> create(Reader reader, boolean debug, File path) throws IOException { return create(reader, debug, path, true); }
java
public void setNamespace(String prefix, String uri) { Namespace namespace = new Namespace(prefix, uri); this.namespace.add(namespace); }
java
public static CPDefinitionGroupedEntry fetchByUuid_Last(String uuid, OrderByComparator<CPDefinitionGroupedEntry> orderByComparator) { return getPersistence().fetchByUuid_Last(uuid, orderByComparator); }
python
def apply(self, func, shortcut=False, args=(), **kwargs): """Apply a function over each array in the group and concatenate them together into a new array. `func` is called like `func(ar, *args, **kwargs)` for each array `ar` in this group. Apply uses heuristics (like `pandas.Gr...
java
public EList<AbstractRule> getRules() { if (rules == null) { rules = new EObjectContainmentEList<AbstractRule>(AbstractRule.class, this, XtextPackage.GRAMMAR__RULES); } return rules; }
python
def delete_event_view(request, id): """Delete event page. You may only delete an event if you were the creator or you are an administrator. Confirmation page if not POST. id: event id """ event = get_object_or_404(Event, id=id) if not request.user.has_admin_permission('events'): raise ...
java
static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException { final ProcessedLayers layers = new ProcessedLayers(conf); // Process module roots final LayerPathSetter moduleSetter = new LayerPathSetter() { ...
java
private String filterCategoryJS() { StringBuffer result = new StringBuffer(); // fool the widget with a hidden categories input field result.append("<input name=\"dummysearchcategory\" id=\"dummysearchcategory\" type=\"hidden\" value=\"\">\n"); result.append("<input name=\"dummysearchpa...
python
def disable_host_flap_detection(self, host): """Disable flap detection for a host Format of the line that triggers function call:: DISABLE_HOST_FLAP_DETECTION;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ i...
java
public static Object sum(Iterator<Object> self) { return sum(toList(self), null, true); }
python
def _get_esxcluster_proxy_details(): ''' Returns the running esxcluster's proxy details ''' det = __salt__['esxcluster.get_details']() return det.get('vcenter'), det.get('username'), det.get('password'), \ det.get('protocol'), det.get('port'), det.get('mechanism'), \ det.get(...
python
def oneshot(self, query, **params): """Run a oneshot search and returns a streaming handle to the results. The ``InputStream`` object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to :class:`splunklib.results.ResultsReader`:: ...
java
public Stat exists(final String path, Watcher watcher) throws KeeperException, InterruptedException { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); // the watch contains the un-chroot path WatchRegistration wcb = null; ...
java
public ArrayList<MtasTokenString> getObjectsByPosition(String field, int docId, int position) throws IOException { IndexDoc doc = getDoc(field, docId); IndexInput inIndexObjectPosition = indexInputList .get("indexObjectPosition"); ArrayList<MtasTreeHit<?>> hits = CodecSearchTree.searchMtasTree...
python
def set_calibration(self, delta: Point): """ Called by save calibration in order to update the offset on the object. """ self._calibrated_offset = Point(x=self._offset.x + delta.x, y=self._offset.y + delta.y, ...
java
@Override public C add(final T child) { child.removeFromParent(); super.add(child); child.attachToLayerColorMap(); return cast(); }
python
def compactspace(scale, n): r""" Returns points :math:`x` spaced in the open interval :math:`(-\infty, \infty)` by linearly spacing in the compactified coordinate :math:`s(x) = e^{-\alpha x} / (1 + e^{-\alpha x})^2`, where :math:`\alpha` is a scale factor. """ logit = logistic(scale=scale)....
python
def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debug', log_callback=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, ...
java
public Pose[] getPose() { Pose[] ret = new Pose[psa.length]; for (int i = 0; i < ret.length; i++) { ret[i] = psa[i].getPose(); } return ret; }
python
def restore_row(self, row, schema): """Restore row from SQL """ row = list(row) for index, field in enumerate(schema.fields): if self.__dialect == 'postgresql': if field.type in ['array', 'object']: continue row[index] = field.c...
java
public boolean isSuperAdmin(UserIdentityContext userIdentityContext) { //SuperAdmin Account is the one the is //1. Has no parent, this is the top account //2. Is ACTIVE return (userIdentityContext.getEffectiveAccount().getParentSid() == null) && (userIdentityContext.getEf...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "Transformation", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_GeneralTransformation") public JAXBElement<TransformationType> createTransformation(TransformationType value) { return new JAXBElement<Transfo...
java
private void handleListMechsResponse(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception { String remote = ctx.channel().remoteAddress().toString(); String[] supportedMechanisms = SaslListMechsResponse.supportedMechs(msg); if (supportedMechanisms.length == 0) { throw new Authenticatio...
python
def restore_directory_state(self, fname): """Restore directory expanded state""" root = osp.normpath(to_text_string(fname)) if not osp.exists(root): # Directory has been (re)moved outside Spyder return for basename in os.listdir(root): path = os...
python
def validate(self): """ Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. """ validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt validation_scope = {} exec(val...
python
def _make_request(self, method, params): """Make request to API endpoint Note: Ignoring SSL cert validation due to intermittent failures http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification """ if self.blocked_until is not None and \ dat...
python
def extract(self, destination, format='csv', csv_delimiter=None, csv_header=True, compress=False): """Exports the table to GCS; blocks until complete. Args: destination: the destination URI(s). Can be a single URI or a list. format: the format to use for the exported data; one of 'csv', 'json', or ...
python
def parse(self, filename, code): """Read and parse a RiveScript document. Returns a data structure that represents all of the useful contents of the document, in this format:: { "begin": { # "begin" data "global": {}, # map of !global vars ...
python
def add_res(acc, elem): """ Adds results to the accumulator :param acc: :param elem: :return: """ if not isinstance(elem, list): elem = [elem] if acc is None: acc = [] for x in elem: acc.append(x) return acc
python
def _parse_conll(self, conll_filepath): """ parses a CoNLL2009/2010 file into a multidigraph. """ assert self.conll_format in ('2009', '2010'), \ "We only support CoNLL2009 and CoNLL2010 format." if self.conll_format == '2009': word_class = Conll2009Word ...
python
def convert_body(url, body): """ :return: the url string with extra data in the body Extract the data in the body and convert to URL query string """ new_url = "%s.Post" % url params = json.loads(body) for key in params: new_url = "%s&%s=%s" % (new_url...
java
private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef) { IndexDef indexDef = tableDef.getIndex(indexDescDef.getName()); if (indexDef == null) { indexDef = new IndexDef(indexDescDef.getName(), indexDescDef.getBooleanPr...
java
public List<String> getSubItems() { if (isGroupContainer()) { return m_subItems; } else if (isInheritContainer()) { List<String> result = new ArrayList<String>(); for (CmsInheritanceInfo info : m_inheritanceInfos) { if (info.isVisible()) { ...
java
public boolean printData(PrintWriter out, int iPrintOptions) { boolean bFieldsFound = false; String strFieldName = this.getScreenField().getSFieldParam(); String string = DBConstants.BLANK; int iIndex = 0; Convert converter = this.getScreenField().getConverter(); if ...