language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static boolean installRserve(String Rcmd, String http_proxy, String repository) { if (repository == null || repository.length() == 0) { repository = Rsession.DEFAULT_REPOS; } if (http_proxy == null) { http_proxy = ""; } Log.Out.println("Install Rserve from " + repository + " ... (http_proxy='" + http_proxy + "') "); Process p = doInR((http_proxy != null ? "Sys.setenv(http_proxy='" + http_proxy + "');" : "") + "install.packages('Rserve',repos='" + repository + "',lib='" + RserveDaemon.app_dir() + "')", Rcmd, "--vanilla --silent", false); if (p == null) { Log.Err.println("Failed to launch Rserve install"); return false; } try { StringBuffer result = new StringBuffer(); // we need to fetch the output - some platforms will die if you don't ... StreamHog error = new StreamHog(p.getErrorStream(), true); StreamHog output = new StreamHog(p.getInputStream(), true); error.join(); output.join(); if (!RserveDaemon.isWindows()) /* on Windows the process will never return, so we cannot wait */ { p.waitFor(); } else { Thread.sleep(2000); } result.append(output.getOutput()); result.append(error.getOutput()); //Logger.err.println("output=\n===========\n" + result.toString() + "\n===========\n"); if (result.toString().contains("package 'Rserve' successfully unpacked and MD5 sums checked") || result.toString().contains("* DONE (Rserve)")) { Log.Out.println("Rserve install succeded: " + result.toString().replace("\n", "\n | ")); //return true; } else if (result.toString().contains("FAILED") || result.toString().contains("Error")) { Log.Out.println("Rserve install failed: " + result.toString().replace("\n", "\n| ")); return false; } else { Log.Err.println("Rserve install unknown: " + result.toString().replace("\n", "\n| ")); return false; } } catch (InterruptedException e) { return false; } int n = 5; while (n > 0) { try { Thread.sleep(2000); Log.Out.print("."); } catch (InterruptedException ex) { } if (isRserveInstalled(Rcmd)) { Log.Out.print("Rserve is installed"); return true; } n--; } Log.Out.print("Rserve is not installed"); return false; }
java
@Override public String sessionId() { String sessionId = cookie(SESSION_COOKIE, null); if (U.isEmpty(sessionId)) { sessionId = UUID.randomUUID().toString(); synchronized (cookies) { if (cookie(SESSION_COOKIE, null) == null) { cookies.put(SESSION_COOKIE, sessionId); response().cookie(SESSION_COOKIE, sessionId, "HttpOnly"); } } } return sessionId; }
python
def GetFrequencyStartTimes(self): """Return a list of start time for each headway-based run. Returns: a sorted list of seconds since midnight, the start time of each run. If this trip doesn't have headways returns an empty list.""" start_times = [] # for each headway period of the trip for freq_tuple in self.GetFrequencyTuples(): (start_secs, end_secs, headway_secs) = freq_tuple[0:3] # reset run secs to the start of the timeframe run_secs = start_secs while run_secs < end_secs: start_times.append(run_secs) # increment current run secs by headway secs run_secs += headway_secs return start_times
python
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_file(value) if version != value: version = version.strip() # Be strict about versions loaded from file because it's easy to # accidentally include newlines and other unintended content if isinstance(parse(version), LegacyVersion): tmpl = ( 'Version loaded from {value} does not ' 'comply with PEP 440: {version}' ) raise DistutilsOptionError(tmpl.format(**locals())) return version version = self._parse_attr(value, self.package_dir) if callable(version): version = version() if not isinstance(version, string_types): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: version = '%s' % version return version
java
public static String getHbInfo(Map<String, String> params, String certPath, String certPassword) { return HttpUtils.postSSL(getHbInfo, PaymentKit.toXml(params), certPath, certPassword); }
java
public static String detokenize(List<String> tokens) { return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens)); }
python
def overplot_boundaries_from_params(ax, params, parmodel, list_islitlet, list_csu_bar_slit_center, micolors=('m', 'c'), linetype='--', labels=True, alpha_fill=None, global_offset_x_pix=0, global_offset_y_pix=0): """Overplot boundaries computed from fitted parameters. Parameters ---------- ax : matplotlib axes Current plot axes. params : :class:`~lmfit.parameter.Parameters` Parameters to be employed in the prediction of the distorted boundaries. parmodel : str Model to be assumed. Allowed values are 'longslit' and 'multislit'. list_islitlet : list of integers Slitlet numbers to be considered. longslits. list_csu_bar_slit_center : list of floats CSU bar slit centers of the considered slitlets. micolors : Python list List with two characters corresponding to alternating colors for odd and even slitlets. linetype : str Line type. labels : bool If True, display slilet label alpha_fill : float or None Alpha factor to be employed to fill slitlet region. global_integer_offset_x_pix : int or float Global offset in the X direction to be applied after computing the expected location. global_offset_y_pix : int or float Global offset in the Y direction to be applied after computing the expected location. Returns ------- list_pol_lower_boundaries : python list List of numpy.polynomial.Polynomial instances with the lower polynomial boundaries computed for the requested slitlets. list_pol_upper_boundaries : python list List of numpy.polynomial.Polynomial instances with the upper polynomial boundaries computed for the requested slitlets. """ # duplicate to shorten the variable names xoff = float(global_offset_x_pix) yoff = float(global_offset_y_pix) list_pol_lower_boundaries = [] list_pol_upper_boundaries = [] for islitlet, csu_bar_slit_center in \ zip(list_islitlet, list_csu_bar_slit_center): tmpcolor = micolors[islitlet % 2] pol_lower_expected = expected_distorted_boundaries( islitlet, csu_bar_slit_center, [0], params, parmodel, numpts=101, deg=5, debugplot=0 )[0].poly_funct list_pol_lower_boundaries.append(pol_lower_expected) pol_upper_expected = expected_distorted_boundaries( islitlet, csu_bar_slit_center, [1], params, parmodel, numpts=101, deg=5, debugplot=0 )[0].poly_funct list_pol_upper_boundaries.append(pol_upper_expected) xdum = np.linspace(1, EMIR_NAXIS1, num=EMIR_NAXIS1) ydum1 = pol_lower_expected(xdum) ax.plot(xdum + xoff, ydum1 + yoff, tmpcolor + linetype) ydum2 = pol_upper_expected(xdum) ax.plot(xdum + xoff, ydum2 + yoff, tmpcolor + linetype) if alpha_fill is not None: ax.fill_between(xdum + xoff, ydum1 + yoff, ydum2 + yoff, facecolor=tmpcolor, alpha=alpha_fill) if labels: # slitlet label yc_lower = pol_lower_expected(EMIR_NAXIS1 / 2 + 0.5) yc_upper = pol_upper_expected(EMIR_NAXIS1 / 2 + 0.5) xcsu = EMIR_NAXIS1 * csu_bar_slit_center / 341.5 ax.text(xcsu + xoff, (yc_lower + yc_upper) / 2 + yoff, str(islitlet), fontsize=10, va='center', ha='center', bbox=dict(boxstyle="round,pad=0.1", fc="white", ec="grey"), color=tmpcolor, fontweight='bold', backgroundcolor='white') # return lists with boundaries return list_pol_lower_boundaries, list_pol_upper_boundaries
java
public static void setPropertiesDir(String propertiesDir) { if (propertiesDir == null) propertiesDir = ""; propertiesDir = propertiesDir.trim(); if (!propertiesDir.endsWith("/")) propertiesDir += "/"; ConfigFactory.propertiesDir = propertiesDir; init(); }
java
public ServiceFuture<List<ApplicationGatewaySslPredefinedPolicyInner>> listAvailableSslPredefinedPoliciesAsync(final ListOperationCallback<ApplicationGatewaySslPredefinedPolicyInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listAvailableSslPredefinedPoliciesSinglePageAsync(), new Func1<String, Observable<ServiceResponse<Page<ApplicationGatewaySslPredefinedPolicyInner>>>>() { @Override public Observable<ServiceResponse<Page<ApplicationGatewaySslPredefinedPolicyInner>>> call(String nextPageLink) { return listAvailableSslPredefinedPoliciesNextSinglePageAsync(nextPageLink); } }, serviceCallback); }
java
private void upgradeIfNeeded(File oldPidGenDir) throws IOException { if (oldPidGenDir != null && oldPidGenDir.isDirectory()) { String[] names = oldPidGenDir.list(); Arrays.sort(names); if (names.length > 0) { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(oldPidGenDir, names[names.length - 1])))); String lastLine = null; String line; while ((line = in.readLine()) != null) { lastLine = line; } in.close(); if (lastLine != null) { String[] parts = lastLine.split("|"); if (parts.length == 2) { neverGeneratePID(parts[0]); } } } } }
python
def default_set(self, obj): 'Set passed sink or source to be used as default one by pulseaudio server.' assert_pulse_object(obj) method = { PulseSinkInfo: self.sink_default_set, PulseSourceInfo: self.source_default_set }.get(type(obj)) if not method: raise NotImplementedError(type(obj)) method(obj)
java
public SmartBinder castReturn(Class<?> type) { return new SmartBinder(this, signature().changeReturn(type), binder.cast(type, binder.type().parameterArray())); }
java
private Path getOrGenerateSchemaFile(Schema schema) throws IOException { Preconditions.checkNotNull(schema, "Avro Schema should not be null"); String hashedSchema = Hashing.sha256().hashString(schema.toString(), StandardCharsets.UTF_8).toString(); if (!this.schemaPaths.containsKey(hashedSchema)) { Path schemaFilePath = new Path(this.schemaDir, String.valueOf(System.currentTimeMillis() + ".avsc")); AvroUtils.writeSchemaToFile(schema, schemaFilePath, fs, true); this.schemaPaths.put(hashedSchema, schemaFilePath); } return this.schemaPaths.get(hashedSchema); }
python
def list_files(self, remote_path, by="name", order="desc", limit=None, extra_params=None, is_share=False, **kwargs): """获取目录下的文件列表. :param remote_path: 网盘中目录的路径,必须以 / 开头。 .. warning:: * 路径长度限制为1000; * 径中不能包含以下字符:``\\\\ ? | " > < : *``; * 文件名或路径名开头结尾不能是 ``.`` 或空白字符,空白字符包括: ``\\r, \\n, \\t, 空格, \\0, \\x0B`` 。 :param by: 排序字段,缺省根据文件类型排序: * time(修改时间) * name(文件名) * size(大小,注意目录无大小) :param order: “asc”或“desc”,缺省采用降序排序。 * asc(升序) * desc(降序) :param limit: 返回条目控制,参数格式为:n1-n2。 返回结果集的[n1, n2)之间的条目,缺省返回所有条目; n1从0开始。 :param is_share: 是否是分享的文件夹(大概) :return: requests.Response 对象 .. note:: 返回正确时返回的 Reponse 对象 content 中的数据结构 { "errno":0, "list":[ {"fs_id":服务器文件识别号"path":"路径","server_filename":"服务器文件名(不汗含路径)","size":文件大小,"server_mtime":服务器修改时间,"server_ctime":服务器创建时间,"local_mtime":本地修改时间,"local_ctime":本地创建时间,"isdir":是否是目录,"category":类型,"md5":"md5值"}……等等 ], "request_id":请求识别号 } """ if order == "desc": desc = "1" else: desc = "0" params = dict() if extra_params: params.update(extra_params) params['dir'] = remote_path params['order'] = by params['desc'] = desc if is_share: return self._request('/share/list', None, extra_params=params, url="https://pan.baidu.com/share/list", **kwargs) return self._request('list', 'list', extra_params=params, **kwargs)
java
@SuppressWarnings("resource") private boolean doPack(final File targetArchiveFile, List<FileData> fileDatas, final ArchiveRetriverCallback<FileData> callback) { // 首先判断下对应的目标文件是否存在,如存在则执行删除 if (true == targetArchiveFile.exists() && false == NioUtils.delete(targetArchiveFile, 3)) { throw new ArchiveException(String.format("[%s] exist and delete failed", targetArchiveFile.getAbsolutePath())); } boolean exist = false; ZipOutputStream zipOut = null; Set<String> entryNames = new HashSet<String>(); BlockingQueue<Future<ArchiveEntry>> queue = new LinkedBlockingQueue<Future<ArchiveEntry>>(); // 下载成功的任务列表 ExecutorCompletionService completionService = new ExecutorCompletionService(executor, queue); final File targetDir = new File(targetArchiveFile.getParentFile(), FilenameUtils.getBaseName(targetArchiveFile.getPath())); try { // 创建一个临时目录 FileUtils.forceMkdir(targetDir); zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetArchiveFile))); zipOut.setLevel(Deflater.BEST_SPEED); // 进行并发压缩处理 for (final FileData fileData : fileDatas) { if (fileData.getEventType().isDelete()) { continue; // 忽略delete类型的数据打包,因为只需直接在目标进行删除 } String namespace = fileData.getNameSpace(); String path = fileData.getPath(); boolean isLocal = StringUtils.isBlank(namespace); String entryName = null; if (true == isLocal) { entryName = FilenameUtils.getPath(path) + FilenameUtils.getName(path); } else { entryName = namespace + File.separator + path; } // 过滤一些重复的文件数据同步 if (entryNames.contains(entryName) == false) { entryNames.add(entryName); } else { continue; } final String name = entryName; if (true == isLocal && !useLocalFileMutliThread) { // 采用串行处理,不走临时文件 queue.add(new DummyFuture(new ArchiveEntry(name, callback.retrive(fileData)))); } else { completionService.submit(new Callable<ArchiveEntry>() { public ArchiveEntry call() throws Exception { // 处理下异常,可能失败 InputStream input = null; OutputStream output = null; try { input = callback.retrive(fileData); if (input instanceof LazyFileInputStream) { input = ((LazyFileInputStream) input).getInputSteam();// 获取原始的stream } if (input != null) { File tmp = new File(targetDir, name); NioUtils.create(tmp.getParentFile(), false, 3);// 尝试创建父路径 output = new FileOutputStream(tmp); NioUtils.copy(input, output);// 拷贝到文件 return new ArchiveEntry(name, new File(targetDir, name)); } else { return new ArchiveEntry(name); } } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } }); } } for (int i = 0; i < entryNames.size(); i++) { // 读入流 ArchiveEntry input = null; InputStream stream = null; try { input = queue.take().get(); if (input == null) { continue; } stream = input.getStream(); if (stream == null) { continue; } if (stream instanceof LazyFileInputStream) { stream = ((LazyFileInputStream) stream).getInputSteam();// 获取原始的stream } exist = true; zipOut.putNextEntry(new ZipEntry(input.getName())); NioUtils.copy(stream, zipOut);// 输出到压缩流中 zipOut.closeEntry(); } finally { IOUtils.closeQuietly(stream); } } if (exist) { zipOut.finish(); } } catch (Exception e) { throw new ArchiveException(e); } finally { IOUtils.closeQuietly(zipOut); try { FileUtils.deleteDirectory(targetDir);// 删除临时目录 } catch (IOException e) { // ignore } } return exist; }
python
def auth(config): """ Perform authentication with Twitter and return a client instance to communicate with Twitter :param config: ResponseBot config :type config: :class:`~responsebot.utils.config_utils.ResponseBotConfig` :return: client instance to execute twitter action :rtype: :class:`~responsebot.responsebot_client.ResponseBotClient` :raises: :class:`~responsebot.common.exceptions.AuthenticationError`: If failed to authenticate :raises: :class:`~responsebot.common.exceptions.APIQuotaError`: If API call rate reached limit """ auth = tweepy.OAuthHandler(config.get('consumer_key'), config.get('consumer_secret')) auth.set_access_token(config.get('token_key'), config.get('token_secret')) api = tweepy.API(auth) try: api.verify_credentials() except RateLimitError as e: raise APIQuotaError(e.args[0][0]['message']) except TweepError as e: raise AuthenticationError(e.args[0][0]['message']) else: logging.info('Successfully authenticated as %s' % api.me().screen_name) return ResponseBotClient(config=config, client=api)
java
public ByteBuffer getPosKeyBuffer() { ByteBuffer buf = m_posKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; }
python
def evaluator(evaluate): """Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the following signature:: fitness = evaluate(candidate, args) This function is most commonly used as a function decorator with the following usage:: @evaluator def evaluate(candidate, args): # Implementation of evaluation pass The generated function also contains an attribute named ``single_evaluation`` which holds the original evaluation function. In this way, the original single-candidate function can be retrieved if necessary. """ @functools.wraps(evaluate) def inspyred_evaluator(candidates, args): fitness = [] for candidate in candidates: fitness.append(evaluate(candidate, args)) return fitness inspyred_evaluator.single_evaluation = evaluate return inspyred_evaluator
java
private String findRememberMeCookieValue(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return null; } for (Cookie cookie : cookies) { if (ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY.equals(cookie.getName())) { return cookie.getValue(); } } return null; }
java
public static void zip(File[] sources, File target, String compressFileName) throws IOException { $.notEmpty(sources); $.notNull(target); if (!target.isDirectory()) { throw new IllegalArgumentException("The target can be a directory"); } // 压缩后文件的名称 compressFileName = $.notEmpty(compressFileName) ? compressFileName : sources[0].getName() + ".zip"; FileOutputStream fileOut = new FileOutputStream(target.getAbsolutePath() + File.separator + compressFileName); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(fileOut); for (int i = 0; i < sources.length; i++) { compress(sources[i], zipOut, null); } zipOut.close(); }
python
def plotConvergenceByObject(results, objectRange, featureRange, numTrials, linestyle='-'): """ Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of unique features. """ ######################################################################## # # Accumulate all the results per column in a convergence array. # # Convergence[f,o] = how long it took it to converge with f unique features # and o objects. convergence = numpy.zeros((max(featureRange), max(objectRange) + 1)) for r in results: if r["numFeatures"] in featureRange: convergence[r["numFeatures"] - 1, r["numObjects"]] += r["convergencePoint"] convergence /= numTrials ######################################################################## # # Create the plot. x-axis= # Plot each curve legendList = [] colorList = ['r', 'b', 'g', 'm', 'c', 'k', 'y'] for i in range(len(featureRange)): f = featureRange[i] print "features={} objectRange={} convergence={}".format( f,objectRange, convergence[f-1,objectRange]) legendList.append('Unique features={}'.format(f)) plt.plot(objectRange, convergence[f-1, objectRange], color=colorList[i], linestyle=linestyle) # format plt.legend(legendList, loc="lower right", prop={'size':10}) plt.xlabel("Number of objects in training set") plt.xticks(range(0,max(objectRange)+1,10)) plt.yticks(range(0,int(convergence.max())+2)) plt.ylabel("Average number of touches") plt.title("Number of touches to recognize one object (single column)")
java
public void setMolecule(IAtomContainer mol, boolean clone, Set<IAtom> afix, Set<IBond> bfix) { if (clone) { if (!afix.isEmpty() || !bfix.isEmpty()) throw new IllegalArgumentException("Laying out a cloned molecule, can't fix atom or bonds."); try { this.molecule = (IAtomContainer) mol.clone(); } catch (CloneNotSupportedException e) { logger.error("Should clone, but exception occurred: ", e.getMessage()); logger.debug(e); } } else { this.molecule = mol; } this.afix = afix; this.bfix = bfix; for (IAtom atom : molecule.atoms()) { boolean afixed = afix.contains(atom); if (afixed && atom.getPoint2d() == null) { afixed = false; afix.remove(atom); } if (afixed) { atom.setFlag(CDKConstants.ISPLACED, true); atom.setFlag(CDKConstants.VISITED, true); } else { atom.setPoint2d(null); atom.setFlag(CDKConstants.ISPLACED, false); atom.setFlag(CDKConstants.VISITED, false); atom.setFlag(CDKConstants.ISINRING, false); atom.setFlag(CDKConstants.ISALIPHATIC, false); } } atomPlacer.setMolecule(this.molecule); ringPlacer.setMolecule(this.molecule); ringPlacer.setAtomPlacer(this.atomPlacer); macroPlacer = new MacroCycleLayout(mol); selectOrientation = afix.isEmpty(); }
python
def cancel_ride(self, ride_id, cancel_confirmation_token=None): """Cancel an ongoing ride on behalf of a user. Params ride_id (str) The unique ID of the Ride Request. cancel_confirmation_token (str) Optional string containing the cancellation confirmation token. Returns (Response) A Response object with successful status_code if ride was canceled. """ args = { "cancel_confirmation_token": cancel_confirmation_token } endpoint = 'v1/rides/{}/cancel'.format(ride_id) return self._api_call('POST', endpoint, args=args)
python
def filter_batched_data(data, mapping): """ Iterates over the data and mapping for a ColumnDataSource and replaces columns with repeating values with a scalar. This is purely and optimization for scalar types. """ for k, v in list(mapping.items()): if isinstance(v, dict) and 'field' in v: if 'transform' in v: continue v = v['field'] elif not isinstance(v, basestring): continue values = data[v] try: if len(unique_array(values)) == 1: mapping[k] = values[0] del data[v] except: pass
python
def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. """ if len(args) == 1: self._vshare.gl_state['preset'] = args[0] elif len(args) != 0: raise TypeError("Only one positional argument allowed.") self._vshare.gl_state.update(kwargs)
python
def _setup_eventloop(self): """ Sets up a new eventloop as the current one according to the OS. """ if os.name == 'nt': self.eventloop = asyncio.ProactorEventLoop() else: self.eventloop = asyncio.new_event_loop() asyncio.set_event_loop(self.eventloop) if os.name == 'posix' and isinstance(threading.current_thread(), threading._MainThread): asyncio.get_child_watcher().attach_loop(self.eventloop)
java
public synchronized ServletHolder addServlet(String name, String pathSpec, String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return getServletHandler().addServlet(name,pathSpec,className,null); }
python
def get(self, url): """ Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. """ logger.debug('Making GET request to %s', url) return self.oauth_session.get(url)
python
def send(self, obj): """Send a push notification""" if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
python
def get_go2obj(self, goids): """Return GO Terms for each user-specified GO ID. Note missing GO IDs.""" goids = goids.intersection(self.go2obj.keys()) if len(goids) != len(goids): goids_missing = goids.difference(goids) print(" {N} MISSING GO IDs: {GOs}".format(N=len(goids_missing), GOs=goids_missing)) return {go:self.go2obj[go] for go in goids}
python
def config(name, reset=False, **kwargs): ''' Modify configuration options for a given port. Multiple options can be specified. To see the available options for a port, use :mod:`ports.showconfig <salt.modules.freebsdports.showconfig>`. name The port name, in ``category/name`` format reset : False If ``True``, runs a ``make rmconfig`` for the port, clearing its configuration before setting the desired options CLI Examples: .. code-block:: bash salt '*' ports.config security/nmap IPV6=off ''' portpath = _check_portname(name) if reset: rmconfig(name) configuration = showconfig(name, dict_return=True) if not configuration: raise CommandExecutionError( 'Unable to get port configuration for \'{0}\''.format(name) ) # Get top-level key for later reference pkg = next(iter(configuration)) conf_ptr = configuration[pkg] opts = dict( (six.text_type(x), _normalize(kwargs[x])) for x in kwargs if not x.startswith('_') ) bad_opts = [x for x in opts if x not in conf_ptr] if bad_opts: raise SaltInvocationError( 'The following opts are not valid for port {0}: {1}' .format(name, ', '.join(bad_opts)) ) bad_vals = [ '{0}={1}'.format(x, y) for x, y in six.iteritems(opts) if y not in ('on', 'off') ] if bad_vals: raise SaltInvocationError( 'The following key/value pairs are invalid: {0}' .format(', '.join(bad_vals)) ) conf_ptr.update(opts) _write_options(name, configuration) new_config = showconfig(name, dict_return=True) try: new_config = new_config[next(iter(new_config))] except (StopIteration, TypeError): return False return all(conf_ptr[x] == new_config.get(x) for x in conf_ptr)
python
def get_name(): '''Get desktop environment or OS. Get the OS name or desktop environment. **List of Possible Values** +-------------------------+---------------+ | Windows | windows | +-------------------------+---------------+ | Mac OS X | mac | +-------------------------+---------------+ | GNOME 3+ | gnome | +-------------------------+---------------+ | GNOME 2 | gnome2 | +-------------------------+---------------+ | XFCE | xfce4 | +-------------------------+---------------+ | KDE | kde | +-------------------------+---------------+ | Unity | unity | +-------------------------+---------------+ | LXDE | lxde | +-------------------------+---------------+ | i3wm | i3 | +-------------------------+---------------+ | \*box | \*box | +-------------------------+---------------+ | Trinity (KDE 3 fork) | trinity | +-------------------------+---------------+ | MATE | mate | +-------------------------+---------------+ | IceWM | icewm | +-------------------------+---------------+ | Pantheon (elementaryOS) | pantheon | +-------------------------+---------------+ | LXQt | lxqt | +-------------------------+---------------+ | Awesome WM | awesome | +-------------------------+---------------+ | Enlightenment | enlightenment | +-------------------------+---------------+ | AfterStep | afterstep | +-------------------------+---------------+ | WindowMaker | windowmaker | +-------------------------+---------------+ | [Other] | unknown | +-------------------------+---------------+ Returns: str: The name of the desktop environment or OS. ''' if sys.platform in ['win32', 'cygwin']: return 'windows' elif sys.platform == 'darwin': return 'mac' else: desktop_session = os.environ.get( 'XDG_CURRENT_DESKTOP') or os.environ.get('DESKTOP_SESSION') if desktop_session is not None: desktop_session = desktop_session.lower() # Fix for X-Cinnamon etc if desktop_session.startswith('x-'): desktop_session = desktop_session.replace('x-', '') if desktop_session in ['gnome', 'unity', 'cinnamon', 'mate', 'xfce4', 'lxde', 'fluxbox', 'blackbox', 'openbox', 'icewm', 'jwm', 'afterstep', 'trinity', 'kde', 'pantheon', 'i3', 'lxqt', 'awesome', 'enlightenment']: return desktop_session #-- Special cases --# # Canonical sets environment var to Lubuntu rather than # LXDE if using LXDE. # There is no guarantee that they will not do the same # with the other desktop environments. elif 'xfce' in desktop_session: return 'xfce4' elif desktop_session.startswith('ubuntu'): return 'unity' elif desktop_session.startswith('xubuntu'): return 'xfce4' elif desktop_session.startswith('lubuntu'): return 'lxde' elif desktop_session.startswith('kubuntu'): return 'kde' elif desktop_session.startswith('razor'): return 'razor-qt' elif desktop_session.startswith('wmaker'): return 'windowmaker' if os.environ.get('KDE_FULL_SESSION') == 'true': return 'kde' elif os.environ.get('GNOME_DESKTOP_SESSION_ID'): if not 'deprecated' in os.environ.get('GNOME_DESKTOP_SESSION_ID'): return 'gnome2' elif is_running('xfce-mcs-manage'): return 'xfce4' elif is_running('ksmserver'): return 'kde' return 'unknown'
java
public boolean remove(Object e) { if (e == null) return false; Class<?> eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) return false; int eOrdinal = ((Enum<?>)e).ordinal(); int eWordNum = eOrdinal >>> 6; long oldElements = elements[eWordNum]; elements[eWordNum] &= ~(1L << eOrdinal); boolean result = (elements[eWordNum] != oldElements); if (result) size--; return result; }
python
def body(self, value): """Sets the request body; handles logging and length measurement.""" self.__body = value if value is not None: # Avoid calling len() which cannot exceed 4GiB in 32-bit python. body_length = getattr( self.__body, 'length', None) or len(self.__body) self.headers['content-length'] = str(body_length) else: self.headers.pop('content-length', None) # This line ensures we don't try to print large requests. if not isinstance(value, (type(None), six.string_types)): self.loggable_body = '<media body>'
java
public void checkParentLinks() { this.visit(new NodeVisitor() { @Override public boolean visit(AstNode node) { int type = node.getType(); if (type == Token.SCRIPT) return true; if (node.getParent() == null) throw new IllegalStateException ("No parent for node: " + node + "\n" + node.toSource(0)); return true; } }); }
python
def simxLoadUI(clientID, uiPathAndName, options, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' count = ct.c_int() uiHandles = ct.POINTER(ct.c_int)() if (sys.version_info[0] == 3) and (type(uiPathAndName) is str): uiPathAndName=uiPathAndName.encode('utf-8') ret = c_LoadUI(clientID, uiPathAndName, options, ct.byref(count), ct.byref(uiHandles), operationMode) handles = [] if ret == 0: for i in range(count.value): handles.append(uiHandles[i]) #free C buffers c_ReleaseBuffer(uiHandles) return ret, handles
java
private static void bisectTokeRange( DeepTokenRange range, final IPartitioner partitioner, final int bisectFactor, final List<DeepTokenRange> accumulator) { final AbstractType tkValidator = partitioner.getTokenValidator(); Token leftToken = partitioner.getTokenFactory().fromByteArray(tkValidator.decompose(range.getStartToken())); Token rightToken = partitioner.getTokenFactory().fromByteArray(tkValidator.decompose(range.getEndToken())); Token midToken = partitioner.midpoint(leftToken, rightToken); Comparable midpoint = (Comparable) tkValidator.compose(tkValidator.fromString(midToken.toString())); DeepTokenRange left = new DeepTokenRange(range.getStartToken(), midpoint, range.getReplicas()); DeepTokenRange right = new DeepTokenRange(midpoint, range.getEndToken(), range.getReplicas()); if (bisectFactor / 2 <= 1) { accumulator.add(left); accumulator.add(right); } else { bisectTokeRange(left, partitioner, bisectFactor / 2, accumulator); bisectTokeRange(right, partitioner, bisectFactor / 2, accumulator); } }
java
static void publishBundle(XMPPConnection connection, OmemoDevice userDevice, OmemoBundleElement bundle) throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException { PubSubManager pm = PubSubManager.getInstanceFor(connection, connection.getUser().asBareJid()); pm.tryToPublishAndPossibleAutoCreate(userDevice.getBundleNodeName(), new PayloadItem<>(bundle)); }
python
def data(args): """ %prog data data.bin samples.ids STR.ids meta.tsv Make data.tsv based on meta.tsv. """ p = OptionParser(data.__doc__) p.add_option("--notsv", default=False, action="store_true", help="Do not write data.tsv") opts, args = p.parse_args(args) if len(args) != 4: sys.exit(not p.print_help()) databin, sampleids, strids, metafile = args final_columns, percentiles = read_meta(metafile) df, m, samples, loci = read_binfile(databin, sampleids, strids) # Clean the data m %= 1000 # Get the larger of the two alleles m[m == 999] = -1 # Missing data final = set(final_columns) remove = [] for i, locus in enumerate(loci): if locus not in final: remove.append(locus) continue pf = "STRs_{}_SEARCH".format(timestamp()) filteredstrids = "{}.STR.ids".format(pf) fw = open(filteredstrids, "w") print("\n".join(final_columns), file=fw) fw.close() logging.debug("Dropped {} columns; Retained {} columns (`{}`)".\ format(len(remove), len(final_columns), filteredstrids)) # Remove low-quality columns! df.drop(remove, inplace=True, axis=1) df.columns = final_columns filtered_bin = "{}.data.bin".format(pf) if need_update(databin, filtered_bin): m = df.as_matrix() m.tofile(filtered_bin) logging.debug("Filtered binary matrix written to `{}`".format(filtered_bin)) # Write data output filtered_tsv = "{}.data.tsv".format(pf) if not opts.notsv and need_update(databin, filtered_tsv): df.to_csv(filtered_tsv, sep="\t", index_label="SampleKey")
python
def close(self): """Close open resources.""" super(RarExtFile, self).close() if self._fd: self._fd.close() self._fd = None
java
public static List<ResourceBuilder> builders(ClassLoader classLoader, ResourcesModel resourcesModel) { List<ResourceBuilder> builders = new ArrayList<ResourceBuilder>(); if (resourcesModel != null) { for (ResourceModel resourceModel : resourcesModel.getResources()) { builders.add(new ResourceBuilder(classLoader, resourceModel)); } } return builders; }
python
def register(self, fd, events): """ Register an USB-unrelated fd to poller. Convenience method. """ if fd in self.__fd_set: raise ValueError( 'This fd is a special USB event fd, it cannot be polled.' ) self.__poller.register(fd, events)
java
public static OptionalEntity<RequestHeader> getEntity(final CreateForm form, final String username, final long currentTime) { switch (form.crudMode) { case CrudMode.CREATE: return OptionalEntity.of(new RequestHeader()).map(entity -> { entity.setCreatedBy(username); entity.setCreatedTime(currentTime); return entity; }); case CrudMode.EDIT: if (form instanceof EditForm) { return ComponentUtil.getComponent(RequestHeaderService.class).getRequestHeader(((EditForm) form).id); } break; default: break; } return OptionalEntity.empty(); }
java
public ContainerDefinition withResourceRequirements(ResourceRequirement... resourceRequirements) { if (this.resourceRequirements == null) { setResourceRequirements(new com.amazonaws.internal.SdkInternalList<ResourceRequirement>(resourceRequirements.length)); } for (ResourceRequirement ele : resourceRequirements) { this.resourceRequirements.add(ele); } return this; }
python
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' # A token that is finished or revoked is not valid subid = None if not token.endswith(('finished','revoked')): subid = self.generate_subid(token=token) data_base = "%s/%s" %(self.data_base, subid) if not os.path.exists(data_base): subid = None return subid
python
def energy(self, hamiltonian=None): r""" The total energy *per unit mass*: Returns ------- E : :class:`~astropy.units.Quantity` The total energy. """ if self.hamiltonian is None and hamiltonian is None: raise ValueError("To compute the total energy, a hamiltonian" " object must be provided!") from ..potential import PotentialBase if isinstance(hamiltonian, PotentialBase): from ..potential import Hamiltonian warnings.warn("This function now expects a `Hamiltonian` instance " "instead of a `PotentialBase` subclass instance. If " "you are using a static reference frame, you just " "need to pass your potential object in to the " "Hamiltonian constructor to use, e.g., Hamiltonian" "(potential).", DeprecationWarning) hamiltonian = Hamiltonian(hamiltonian) if hamiltonian is None: hamiltonian = self.hamiltonian return hamiltonian(self)
java
public static <O> Function<Object, O> getParseFunction(Class<O> type) { return new StructBehavior<Function<Object, O>>(type) { @SuppressWarnings("unchecked") @Override protected Function<Object, O> booleanIf() { return (Function<Object, O>) TO_BOOLEAN; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> byteIf() { return (Function<Object, O>) TO_BYTE; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> characterIf() { return (Function<Object, O>) TO_CHARACTER; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> doubleIf() { return (Function<Object, O>) TO_DOUBLE; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> floatIf() { return (Function<Object, O>) TO_FLOAT; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> integerIf() { return (Function<Object, O>) TO_INTEGER; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> longIf() { return (Function<Object, O>) TO_LONG; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> shortIf() { return (Function<Object, O>) TO_SHORT; } @Override protected Function<Object, O> nullIf() { return null; } @Override protected Function<Object, O> noneMatched() { return new ValueBehaviorAdapter<Function<Object, O>>(delegate) { @SuppressWarnings("unchecked") @Override protected Function<Object, O> dateIf(Date resolvedP) { return (Function<Object, O>) TO_DATE; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> bigDecimalIf(BigDecimal resolvedP) { return (Function<Object, O>) TO_BIGDECIMAL; } @SuppressWarnings("unchecked") @Override protected Function<Object, O> bigIntegerIf(BigInteger resolvedP) { return (Function<Object, O>) TO_BIGINTEGER; } @Override protected Function<Object, O> defaultBehavior() { return null; } }.doDetect(); } }.doDetect(); }
java
public boolean checkAliasAccess(Subject authenticatedSubject, String destination, String aliasDestination, int destinationType, String operationType) throws MessagingAuthorizationException { SibTr.entry(tc, CLASS_NAME + "checkAliasAccess", new Object[] { authenticatedSubject, destination, operationType, aliasDestination }); boolean result = false; if (!runtimeSecurityService.isMessagingSecure()) { result = true; } else { if (messagingAuthorizationService != null) { result = messagingAuthorizationService.checkAliasAccess(authenticatedSubject, destination, aliasDestination, destinationType, operationType, true); } } SibTr.exit(tc, CLASS_NAME + "checkAliasAccess", result); return result; }
java
public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; }
java
@Override public boolean satisfies(Match match, int... ind) { Collection<BioPAXElement> set = con.generate(match, ind); switch (type) { case EQUAL: return set.size() == size; case GREATER: return set.size() > size; case GREATER_OR_EQUAL: return set.size() >= size; case LESS: return set.size() < size; case LESS_OR_EQUAL: return set.size() <= size; default: throw new RuntimeException( "Should not reach here. Did somebody modify Type enum?"); } }
java
public CoronaTaskTrackerProtocol getClient( String host, int port) throws IOException { String key = makeKey(host, port); Node ttNode = topologyCache.getNode(host); CoronaTaskTrackerProtocol client = null; synchronized (ttNode) { client = trackerClients.get(key); if (client == null) { client = createClient(host, port); trackerClients.put(key, client); } } return client; }
python
def recognize(mol): """ Detect cycle basis, biconnected and isolated components (DFS). This will add following attribute to the molecule instance object. mol.ring: Cycle basis mol.scaffold: biconnected components mol.isolated: isolated components other than the largest one To find minimum set of rings, additionally execute topology.minify_ring. Reference: networkx cycle_basis function """ g = set(i for i, _ in mol.atoms_iter()) bccs = {} # BiConnected Components isoc = [] # ISOlated Components while g: start = g.pop() stack = [start] pred = {start: start} used = {start: set()} root = {start: start} while stack: tail = stack.pop() for nbr in mol.neighbors(tail): if nbr not in used: # New node pred[nbr] = tail stack.append(nbr) used[nbr] = {tail} root[nbr] = nbr elif nbr in stack: # Cycle found pn = used[nbr] cyc = [nbr, tail] p = pred[tail] end = pred[nbr] root[nbr] = root[tail] = root[end] while p not in pn: # Backtrack cyc.append(p) root[p] = root[end] if p in bccs: # Append scaffold to new cycle if root[end] not in bccs: bccs[root[end]] = [] bccs[root[end]].extend(bccs[p]) del bccs[p] p = pred[p] cyc.append(p) if root[end] not in bccs: # Append new cycle to scaffold bccs[root[end]] = [] bccs[root[end]].append(cyc) used[nbr].add(tail) isoc.append(list(pred.keys())) # print(pred) g -= set(pred) mol.rings = [] mol.scaffolds = [] for cycles in bccs.values(): rcnt = len(mol.rings) mol.rings.extend(cycles) mol.scaffolds.append(list(range(rcnt, rcnt + len(cycles)))) mol.isolated = list(sorted(isoc, key=len, reverse=True))[1:] mol.descriptors.add("Topology")
java
private void adjustTarget( DeleteNode point) { int s = point.targetType(); GBSNode t = point.targetNode(); GBSNode d = point.deleteNode(); int tx; switch (s) { case DeleteNode.NONE: /* Nothing to do. Delete point is in a leaf. */ break; case DeleteNode.ADD_LEFT: /* Migrate up high key of a leaf into its upper successor node. */ tx = point.targetIndex(); t.addLeftMostKeyByDelete(tx, d.rightMostKey()); break; case DeleteNode.ADD_RIGHT: /* Migrate up low key of a leaf into its upper predecessor node. */ tx = point.targetIndex(); t.addRightMostKeyByDelete(tx, d.leftMostKey()); break; case DeleteNode.OVERLAY_RIGHT: /* Migrate up low key of a leaf into high key of upper predecessor. */ t.overlayRightMostKey(d.leftMostKey()); break; case DeleteNode.OVERLAY_LEFT: /* Migrate up high key of a leaf into low key of upper successor. */ t.overlayLeftMostKey(d.rightMostKey()); break; default: throw new RuntimeException("s = " + s); } }
java
public void filter(ClientRequestContext request) throws IOException { if(!request.getHeaders().containsKey("X-License-Key")) request.getHeaders().add("X-License-Key", this.licensekey); }
python
def which(name): """ Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``. """ # we were given a filename, return it if it's executable if os.path.dirname(name) != '': if not os.path.isdir(name) and os.access(name, os.X_OK): return name else: return None # fetch PATH env var and split path_val = os.environ.get('PATH', None) or os.defpath # return the first match in the paths for path in path_val.split(os.pathsep): filename = os.path.join(path, name) if os.access(filename, os.X_OK): return filename return None
java
private static <V> boolean colorOf(TreeEntry<V> p) { return p == null ? BLACK : p.color; }
java
private static float angleDeg(final float ax, final float ay, final float bx, final float by) { final double angleRad = Math.atan2(ay - by, ax - bx); double angle = Math.toDegrees(angleRad); if (angleRad < 0) { angle += 360; } return (float) angle; }
python
def s3_read(source, profile_name=None): """ Read a file from an S3 source. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile Returns ------- content : bytes Raises ------ botocore.exceptions.NoCredentialsError Botocore is not able to find your credentials. Either specify profile_name or add the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN. See https://boto3.readthedocs.io/en/latest/guide/configuration.html """ session = boto3.Session(profile_name=profile_name) s3 = session.client('s3') bucket_name, key = _s3_path_split(source) s3_object = s3.get_object(Bucket=bucket_name, Key=key) body = s3_object['Body'] return body.read()
java
public static String executeRemoveText(String text, String parseExpression) { LOGGER.debug("removeText抽取函数之前:" + text); String parameter = parseExpression.replace("removeText(", ""); parameter = parameter.substring(0, parameter.length() - 1); text = text.replace(parameter, ""); LOGGER.debug("removeText抽取函数之后:" + text); return text; }
java
protected AJP13Connection createConnection(Socket socket) throws IOException { return new AJP13Connection(this,socket.getInputStream(),socket.getOutputStream(),socket,getBufferSize()); }
java
public static MutableIntTuple multiply( IntTuple t0, int factor, MutableIntTuple result) { return IntTupleFunctions.apply( t0, (a)->(a*factor), result); }
java
private static <T> int indexOfNullElement(T[] array) { for (int i = 0; i < array.length; i++) { if (array[i] == null) { return i; } } return -1; }
python
def from_indexed_arrays(cls, name, verts, normals): """Takes MxNx3 verts, Mx3 normals to build obj file""" # Put header in string wavefront_str = "o {name}\n".format(name=name) new_verts, face_indices = face_index(verts) assert new_verts.shape[1] == 3, "verts should be Nx3 array" assert face_indices.ndim == 2 face_indices = fan_triangulate(face_indices) # Write Vertex data from vert_dict for vert in new_verts: wavefront_str += "v {0} {1} {2}\n".format(*vert) # Write (false) UV Texture data wavefront_str += "vt 1.0 1.0\n" for norm in normals: wavefront_str += "vn {0} {1} {2}\n".format(*norm) assert len(face_indices) == len(normals) * 2 for norm_idx, vert_idx, in enumerate(face_indices): wavefront_str += "f" for vv in vert_idx: wavefront_str += " {}/{}/{}".format(vv + 1, 1, (norm_idx // 2) + 1 ) wavefront_str += "\n" return cls(string=wavefront_str)
java
private void popLastItem() { KeyValue<K,V> lastKV = items.last(); items.remove(lastKV); index.remove(lastKV.key); }
java
private void repairBrokenLatticeAfter(ViterbiLattice lattice, int nodeEndIndex) { ViterbiNode[][] nodeEndIndices = lattice.getEndIndexArr(); for (int endIndex = nodeEndIndex + 1; endIndex < nodeEndIndices.length; endIndex++) { if (nodeEndIndices[endIndex] != null) { ViterbiNode glueBase = findGlueNodeCandidate(nodeEndIndex, nodeEndIndices[endIndex], endIndex); if (glueBase != null) { int delta = endIndex - nodeEndIndex; String glueBaseSurface = glueBase.getSurface(); String surface = glueBaseSurface.substring(glueBaseSurface.length() - delta); ViterbiNode glueNode = createGlueNode(nodeEndIndex, glueBase, surface); lattice.addNode(glueNode, nodeEndIndex, nodeEndIndex + glueNode.getSurface().length()); return; } } } }
python
def _create_controls(self, can_kill): """ Creates the button controls, and links them to event handlers """ DEBUG_MSG("_create_controls()", 1, self) # Need the following line as Windows toolbars default to 15x16 self.SetToolBitmapSize(wx.Size(16,16)) self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'), 'Left', 'Scroll left') self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'), 'Right', 'Scroll right') self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase X axis magnification') self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease X axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_Y_PAN_UP,_load_bitmap('stock_up.xpm'), 'Up', 'Scroll up') self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'), 'Down', 'Scroll down') self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase Y axis magnification') self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease Y axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'), 'Save', 'Save plot contents as images') self.AddSeparator() bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT) bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT) bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN) bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP) bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN) bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN) bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE) bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId()) if can_kill: bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel)
java
public static short byteArrayToShort(byte[] ba) throws WsocBufferException { short num = 0; if ((ba == null) || (ba.length == 0)) { IllegalArgumentException x = new IllegalArgumentException("Array of no size passed in"); throw new WsocBufferException(x); } if (ba.length >= 2) { num = (short) (ba[0] << 8 + ba[1]); } else { num = ba[0]; } return num; }
java
private void storeUpperBound(Token tok, Token simTok, List usefulTokens, Map upperBoundOnWeight, double sim) { double upperBound = tfidfDistance.getWeight(tok)*maxTFIDFScore[simTok.getIndex()]*sim; if (DEBUG) System.out.println("upper-bounding tok "+simTok+" sim="+sim+" to "+tok+" upperBound "+upperBound); if (DEBUG) System.out.println("upperBound = "+tfidfDistance.getWeight(tok)+"*"+maxTFIDFScore[simTok.getIndex()]+"*"+sim); usefulTokens.add( simTok ); upperBoundOnWeight.put( simTok, new Double(upperBound) ); }
java
protected static String[] getMultipartDataBoundary(String contentType) { // Check if Post using "multipart/form-data; boundary=--89421926422648 [; charset=xxx]" String[] headerContentType = splitHeaderContentType(contentType); final String multiPartHeader = HttpHeaderValues.MULTIPART_FORM_DATA.toString(); if (headerContentType[0].regionMatches(true, 0, multiPartHeader, 0 , multiPartHeader.length())) { int mrank; int crank; final String boundaryHeader = HttpHeaderValues.BOUNDARY.toString(); if (headerContentType[1].regionMatches(true, 0, boundaryHeader, 0, boundaryHeader.length())) { mrank = 1; crank = 2; } else if (headerContentType[2].regionMatches(true, 0, boundaryHeader, 0, boundaryHeader.length())) { mrank = 2; crank = 1; } else { return null; } String boundary = StringUtil.substringAfter(headerContentType[mrank], '='); if (boundary == null) { throw new ErrorDataDecoderException("Needs a boundary value"); } if (boundary.charAt(0) == '"') { String bound = boundary.trim(); int index = bound.length() - 1; if (bound.charAt(index) == '"') { boundary = bound.substring(1, index); } } final String charsetHeader = HttpHeaderValues.CHARSET.toString(); if (headerContentType[crank].regionMatches(true, 0, charsetHeader, 0, charsetHeader.length())) { String charset = StringUtil.substringAfter(headerContentType[crank], '='); if (charset != null) { return new String[] {"--" + boundary, charset}; } } return new String[] {"--" + boundary}; } return null; }
java
public void connectBeginToBegin(SGraphSegment segment) { if (segment.getGraph() != getGraph()) { throw new IllegalArgumentException(); } final SGraphPoint point = new SGraphPoint(getGraph()); setBegin(point); segment.setBegin(point); final SGraph g = getGraph(); assert g != null; g.updatePointCount(-1); }
java
@SuppressWarnings("NarrowingCompoundAssignment") private String hexAV() { if (pos + 4 >= length) { // encoded byte array must be not less then 4 c throw new IllegalStateException("Unexpected end of DN: " + dn); } beg = pos; // store '#' position pos++; while (true) { // check for end of attribute value // looks for space and component separators if (pos == length || chars[pos] == '+' || chars[pos] == ',' || chars[pos] == ';') { end = pos; break; } if (chars[pos] == ' ') { end = pos; pos++; // skip trailing space chars before comma or semicolon. // (compatibility with RFC 1779) for (; pos < length && chars[pos] == ' '; pos++) { } break; } else if (chars[pos] >= 'A' && chars[pos] <= 'F') { chars[pos] += 32; //to low case } pos++; } // verify length of hex string // encoded byte array must be not less then 4 and must be even number int hexLen = end - beg; // skip first '#' char if (hexLen < 5 || (hexLen & 1) == 0) { throw new IllegalStateException("Unexpected end of DN: " + dn); } // get byte encoding from string representation byte[] encoded = new byte[hexLen / 2]; for (int i = 0, p = beg + 1; i < encoded.length; p += 2, i++) { encoded[i] = (byte) getByte(p); } return new String(chars, beg, hexLen); }
java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ensureList(); }
java
@Override public void dropRetentionPolicy(final String rpName, final String database) { Preconditions.checkNonEmptyString(rpName, "retentionPolicyName"); Preconditions.checkNonEmptyString(database, "database"); StringBuilder queryBuilder = new StringBuilder("DROP RETENTION POLICY \""); queryBuilder.append(rpName) .append("\" ON \"") .append(database) .append("\""); executeQuery(this.influxDBService.postQuery(Query.encode(queryBuilder.toString()))); }
java
public final Operation setMonitoringService( String projectId, String zone, String clusterId, String monitoringService) { SetMonitoringServiceRequest request = SetMonitoringServiceRequest.newBuilder() .setProjectId(projectId) .setZone(zone) .setClusterId(clusterId) .setMonitoringService(monitoringService) .build(); return setMonitoringService(request); }
java
public DfuServiceInitiator setCustomUuidsForLegacyDfu(@Nullable final UUID dfuServiceUuid, @Nullable final UUID dfuControlPointUuid, @Nullable final UUID dfuPacketUuid, @Nullable final UUID dfuVersionUuid) { final ParcelUuid[] uuids = new ParcelUuid[4]; uuids[0] = dfuServiceUuid != null ? new ParcelUuid(dfuServiceUuid) : null; uuids[1] = dfuControlPointUuid != null ? new ParcelUuid(dfuControlPointUuid) : null; uuids[2] = dfuPacketUuid != null ? new ParcelUuid(dfuPacketUuid) : null; uuids[3] = dfuVersionUuid != null ? new ParcelUuid(dfuVersionUuid) : null; legacyDfuUuids = uuids; return this; }
java
final public void increment(long incVal) { if (enabled) { // synchronize the update of lastValue lastSampleTime = updateIntegral(); synchronized (this) { current += incVal; } updateWaterMark(); } else { current += incVal; } }
java
public final void conditionalAndExpression() throws RecognitionException { int conditionalAndExpression_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 112) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1146:5: ( inclusiveOrExpression ( '&&' inclusiveOrExpression )* ) // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1146:9: inclusiveOrExpression ( '&&' inclusiveOrExpression )* { pushFollow(FOLLOW_inclusiveOrExpression_in_conditionalAndExpression5102); inclusiveOrExpression(); state._fsp--; if (state.failed) return; // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1146:31: ( '&&' inclusiveOrExpression )* loop144: while (true) { int alt144=2; int LA144_0 = input.LA(1); if ( (LA144_0==33) ) { alt144=1; } switch (alt144) { case 1 : // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1146:33: '&&' inclusiveOrExpression { match(input,33,FOLLOW_33_in_conditionalAndExpression5106); if (state.failed) return; pushFollow(FOLLOW_inclusiveOrExpression_in_conditionalAndExpression5108); inclusiveOrExpression(); state._fsp--; if (state.failed) return; } break; default : break loop144; } } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving if ( state.backtracking>0 ) { memoize(input, 112, conditionalAndExpression_StartIndex); } } }
java
@Override public String getDatabaseUrlForDatabase(DatabaseType databaseType, String hostname, int port, String databaseName) { String scheme = this.getSchemeNames().get(databaseType); String authenticationInfo = this.getAuthenticationInfo().get(databaseType); Assert.notNull(databaseType, String .format("No scheme name found for database :'%s'", databaseType.name())); try { return new URI(scheme, authenticationInfo, hostname, port, databaseName != null ? "/" + databaseName : null, null, null) .toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException( "Error constructing URI from Host:'" + hostname + "' and port:'" + port + "' and database name:'" + databaseName + "'!"); } }
python
def print_torrent(self): """ Print the details of a torrent """ print('Title: %s' % self.title) print('URL: %s' % self.url) print('Category: %s' % self.category) print('Sub-Category: %s' % self.sub_category) print('Magnet Link: %s' % self.magnet_link) print('Torrent Link: %s' % self.torrent_link) print('Uploaded: %s' % self.created) print('Comments: %d' % self.comments) print('Has Cover Image: %s' % self.has_cover) print('User Status: %s' % self.user_status) print('Size: %s' % self.size) print('User: %s' % self.user) print('Seeders: %d' % self.seeders) print('Leechers: %d' % self.leechers)
java
@Override public <T> void insert(Collection<? extends T> batchToSave, Class<T> entityClass) { insert(batchToSave, Util.determineCollectionName(entityClass)); }
java
private void buildPropertiesFile(String path) throws IOException { Properties properties = new Properties(); properties.put(MetaInf.PACKAGE_FORMAT_VERSION, Integer.toString(MetaInf.FORMAT_VERSION_2)); properties.put(PackageProperties.NAME_REQUIRES_ROOT, Boolean.toString(false)); for (Map.Entry<String, Object> entry : metadata.getVars().entrySet()) { String value = Objects.toString(entry.getValue()); if (StringUtils.isNotEmpty(value)) { properties.put(entry.getKey(), value); } } zip.putNextEntry(new ZipEntry(path)); try { properties.storeToXML(zip, null); } finally { zip.closeEntry(); } }
java
public static String dateIncreaseByYearforString(String date, int mnt) { Date date1 = stringToDate(date); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date1); cal.add(Calendar.YEAR, mnt); String ss = dateToString(cal.getTime(), ISO_DATE_FORMAT); return dateIncreaseByDay(ss, -1); }
java
public static GeoLocationRequest getHttpServletRequestGeoLocation(final HttpServletRequest request) { val loc = new GeoLocationRequest(); if (request != null) { val geoLocationParam = request.getParameter("geolocation"); if (StringUtils.isNotBlank(geoLocationParam)) { val geoLocation = Splitter.on(",").splitToList(geoLocationParam); loc.setLatitude(geoLocation.get(GEO_LOC_LAT_INDEX)); loc.setLongitude(geoLocation.get(GEO_LOC_LONG_INDEX)); loc.setAccuracy(geoLocation.get(GEO_LOC_ACCURACY_INDEX)); loc.setTimestamp(geoLocation.get(GEO_LOC_TIME_INDEX)); } } return loc; }
java
@Conditioned @Et("Je m'attends à avoir '(.*)-(.*)' avec le texte '(.*)'[\\.|\\?]") @And("I expect to have '(.*)-(.*)' with the text '(.*)'[\\.|\\?]") public void expectText(String page, String elementName, String textOrKey, List<GherkinStepCondition> conditions) throws FailureException, TechnicalException { expectText(Page.getInstance(page).getPageElementByKey('-' + elementName), textOrKey); }
python
def thousands(x): """ >>> thousands(12345) '12,345' """ import locale try: locale.setlocale(locale.LC_ALL, "en_US.utf8") except Exception: locale.setlocale(locale.LC_ALL, "en_US.UTF-8") finally: s = '%d' % x groups = [] while s and s[-1].isdigit(): groups.append(s[-3:]) s = s[:-3] return s + ','.join(reversed(groups)) return locale.format('%d', x, True)
python
def _initialize_model_diagnostics(self): """Extra diagnostics for two-layer model""" self.add_diagnostic('entspec', description='barotropic enstrophy spectrum', function= (lambda self: np.abs(self.del1*self.qh[0] + self.del2*self.qh[1])**2.) ) self.add_diagnostic('APEflux', description='spectral flux of available potential energy', function= (lambda self: self.rd**-2 * self.del1*self.del2 * np.real((self.ph[0]-self.ph[1])*np.conj(self.Jptpc)) ) ) self.add_diagnostic('KEflux', description='spectral flux of kinetic energy', function= (lambda self: np.real(self.del1*self.ph[0]*np.conj(self.Jpxi[0])) + np.real(self.del2*self.ph[1]*np.conj(self.Jpxi[1])) ) ) self.add_diagnostic('APEgenspec', description='spectrum of APE generation', function= (lambda self: self.U[:,np.newaxis] * self.rd**-2 * self.del1 * self.del2 * np.real(1j*self.k*(self.del1*self.ph[0] + self.del2*self.ph[1]) * np.conj(self.ph[0] - self.ph[1])) ) ) self.add_diagnostic('APEgen', description='total APE generation', function= (lambda self: self.U * self.rd**-2 * self.del1 * self.del2 * np.real((1j*self.k* (self.del1*self.ph[0] + self.del2*self.ph[1]) * np.conj(self.ph[0] - self.ph[1])).sum() +(1j*self.k[:,1:-2]* (self.del1*self.ph[0,:,1:-2] + self.del2*self.ph[1,:,1:-2]) * np.conj(self.ph[0,:,1:-2] - self.ph[1,:,1:-2])).sum()) / (self.M**2) ) )
java
@Override public SerIterator createChild(final Object value, final SerIterator parent) { Class<?> declaredType = parent.valueType(); List<Class<?>> childGenericTypes = parent.valueTypeTypes(); if (value instanceof BiMap) { if (childGenericTypes.size() == 2) { return biMap((BiMap<?, ?>) value, declaredType, childGenericTypes.get(0), childGenericTypes.get(1), EMPTY_VALUE_TYPES); } return biMap((BiMap<?, ?>) value, Object.class, Object.class, Object.class, EMPTY_VALUE_TYPES); } if (value instanceof Multimap) { if (childGenericTypes.size() == 2) { return multimap((Multimap<?, ?>) value, declaredType, childGenericTypes.get(0), childGenericTypes.get(1), EMPTY_VALUE_TYPES); } return multimap((Multimap<?, ?>) value, Object.class, Object.class, Object.class, EMPTY_VALUE_TYPES); } if (value instanceof Multiset) { if (childGenericTypes.size() == 1) { return multiset((Multiset<?>) value, declaredType, childGenericTypes.get(0), EMPTY_VALUE_TYPES); } return multiset((Multiset<?>) value, Object.class, Object.class, EMPTY_VALUE_TYPES); } if (value instanceof Table) { if (childGenericTypes.size() == 3) { return table((Table<?, ?, ?>) value, declaredType, childGenericTypes.get(0), childGenericTypes.get(1), childGenericTypes.get(2), EMPTY_VALUE_TYPES); } return table((Table<?, ?, ?>) value, Object.class, Object.class, Object.class, Object.class, EMPTY_VALUE_TYPES); } return super.createChild(value, parent); }
python
def stop(self): """Tell the sender thread to finish and wait for it to stop sending (should be at most "timeout" seconds). """ if self.interval is not None: self._queue.put_nowait(None) self._thread.join() self.interval = None
java
public void search() { if (layer != null) { // First we try to get the list of criteria: List<SearchCriterion> criteria = getSearchCriteria(); if (criteria != null && !criteria.isEmpty()) { SearchFeatureRequest request = new SearchFeatureRequest(); String value = (String) logicalOperatorRadio.getValue(); if (value.equals(I18nProvider.getSearch().radioOperatorAnd())) { request.setBooleanOperator("AND"); } else { request.setBooleanOperator("OR"); } request.setCriteria(criteria.toArray(new SearchCriterion[criteria.size()])); request.setCrs(mapModel.getCrs()); request.setLayerId(layer.getServerLayerId()); request.setMax(maximumResultSize); request.setFilter(layer.getFilter()); request.setFeatureIncludes(GwtCommandDispatcher.getInstance().getLazyFeatureIncludesSelect()); GwtCommand command = new GwtCommand(SearchFeatureRequest.COMMAND); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<SearchFeatureResponse>() { public void execute(SearchFeatureResponse response) { List<Feature> features = new ArrayList<Feature>(); for (org.geomajas.layer.feature.Feature dtoFeature : response.getFeatures()) { Feature feature = new Feature(dtoFeature, layer); layer.getFeatureStore().addFeature(feature); features.add(feature); } SearchEvent event = new SearchEvent(layer, features); FeatureSearch.this.fireEvent(event); } }); } } }
java
public static <T> ConflictHandler<T> localWins() { return new ConflictHandler<T>() { @Override public T resolveConflict( final BsonValue documentId, final ChangeEvent<T> localEvent, final ChangeEvent<T> remoteEvent ) { return localEvent.getFullDocument(); } }; }
python
def render_block_to_string(template_name, block_name, context=None): """ Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template. """ # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create the context instance. context = context or {} # The Django backend. if isinstance(t, DjangoTemplate): return django_render_block(t, block_name, context) elif isinstance(t, Jinja2Template): from render_block.jinja2 import jinja2_render_block return jinja2_render_block(t, block_name, context) else: raise UnsupportedEngine( 'Can only render blocks from the Django template backend.')
python
def addSplits(self, login, tableName, splits): """ Parameters: - login - tableName - splits """ self.send_addSplits(login, tableName, splits) self.recv_addSplits()
python
def parse(self, fp, headersonly=True): """Create a message structure from the data in a file.""" feedparser = FeedParser(self._class) feedparser._set_headersonly() try: mp = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) except: mp = fp data = "" # While parsing the header we can convert to us-ascii? while True: line = mp.readline() data = data + line.decode("us-ascii") if line == b"\n": break feedparser.feed(data) # mp[0:5000]) return feedparser.close()
java
@Override public <U extends ApiBaseUser> ResponseToRoom exclude(Collection<U> users) { for(U user : users) this.excludedUsers.add(user.getName()); return this; }
java
public Observable<Page<PolicyAssignmentInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<PolicyAssignmentInner>>, Page<PolicyAssignmentInner>>() { @Override public Page<PolicyAssignmentInner> call(ServiceResponse<Page<PolicyAssignmentInner>> response) { return response.body(); } }); }
java
@Override public void println(String s) throws IOException { print(s); this.output.write(CRLF, 0, 2); }
java
static UserLimits getLimitsFromUserAccount(HTTPServerConfig config, String username, String password) { Objects.requireNonNull(username); Objects.requireNonNull(password); String token = cache.getUnchecked(new Account(username, password)); return getLimitsFromToken(config, token); }
python
def rmlinenumber(linenumber, infile, dryrun=False): """ Sed-like line deletion function based on given line number.. Usage: pysed.rmlinenumber(<Unwanted Line Number>, <Text File>) Example: pysed.rmlinenumber(10, '/path/to/file.txt') Example 'DRYRUN': pysed.rmlinenumber(10, '/path/to/file.txt', dryrun=True) #This will dump the output to STDOUT instead of changing the input file. """ linelist = [] linecounter = 0 if isinstance(linenumber, int): exit("""'linenumber' argument must be an integer.""") with open(infile) as reader: for item in reader: linecounter = linecounter + 1 if linecounter != linenumber: linelist.append(item) if dryrun is False: with open(infile, "w") as writer: writer.truncate() for line in linelist: writer.writelines(line) elif dryrun is True: for line in linelist: print(line, end='') else: exit("""Unknown option specified to 'dryrun' argument, Usage: dryrun=<True|False>.""")
python
def _set_ma_type(self, v, load=False): """ Setter method for ma_type, mapped from YANG variable /cfm_state/cfm_detail/domain/ma/ma_type (ma-types) If this variable is read-only (config: false) in the source YANG file, then _set_ma_type is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ma_type() directly. YANG Description: Bridge Domain or VLAN MA """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'ma-bridge-domain-type': {'value': 1}, u'ma-vlan-type': {'value': 0}, u'ma-vll-type': {'value': 2}},), is_leaf=True, yang_name="ma-type", rest_name="ma-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-dot1ag-operational', defining_module='brocade-dot1ag-operational', yang_type='ma-types', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """ma_type must be of a type compatible with ma-types""", 'defined-type': "brocade-dot1ag-operational:ma-types", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'ma-bridge-domain-type': {'value': 1}, u'ma-vlan-type': {'value': 0}, u'ma-vll-type': {'value': 2}},), is_leaf=True, yang_name="ma-type", rest_name="ma-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='urn:brocade.com:mgmt:brocade-dot1ag-operational', defining_module='brocade-dot1ag-operational', yang_type='ma-types', is_config=False)""", }) self.__ma_type = t if hasattr(self, '_set'): self._set()
python
def potential_cloud_layer(self, pcp, water, tlow, land_cloud_prob, land_threshold, water_cloud_prob, water_threshold=0.5): """Final step of determining potential cloud layer Equation 18 (Zhu and Woodcock, 2012) Saturation (green or red) test is not in the algorithm Parameters ---------- pcps: ndarray potential cloud pixels water: ndarray water mask tirs1: ndarray tlow: float low percentile of land temperature land_cloud_prob: ndarray probability of cloud over land land_threshold: float cutoff for cloud over land water_cloud_prob: ndarray probability of cloud over water water_threshold: float cutoff for cloud over water Output ------ ndarray: potential cloud layer, boolean """ # Using pcp and water as mask todo # change water threshold to dynamic, line 132 in Zhu, 2015 todo part1 = (pcp & water & (water_cloud_prob > water_threshold)) part2 = (pcp & ~water & (land_cloud_prob > land_threshold)) temptest = self.tirs1 < (tlow - 35) # 35degrees C colder if self.sat in ['LT5', 'LE7']: saturation = self.blue_saturated | self.green_saturated | self.red_saturated return part1 | part2 | temptest | saturation else: return part1 | part2 | temptest