language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def release_subnet(self, cidr, direc): """Routine to release a subnet from the DB. """ if direc == 'in': self.service_in_ip.release_subnet(cidr) else: self.service_out_ip.release_subnet(cidr)
java
public void setIntHeader(String name, int value) { try{_httpResponse.setIntField(name,value);} catch(IllegalStateException e){LogSupport.ignore(log,e);} }
java
public static <T> ExpressionList<T> applyWhere(ExpressionList<T> expressionList, Object queryObject) { if (queryObject != null) { Class clz = queryObject.getClass(); Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { field.setAccessibl...
python
def generate_identifier(result): """ Returns a fixed length identifier based on a hash of a combined set of playbook/task values which are as close as we can guess to unique for each task. """ # Determine the playbook file path to use for the ID if result.task.playbook and result.task.playbo...
java
static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { // Copy the mod to protect original return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); }
java
public static final Builder privateKey(Class<?> cls, String resource) { return new Builder().privateKey(cls, resource); }
python
def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str: """ Gets a FEN representation of the position. A FEN string (e.g., ``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists of the position part :func:`~che...
python
def setup_signal_handlers(self): """Called when a child process is spawned to register the signal handlers """ LOGGER.debug('Registering signal handlers') signal.signal(signal.SIGABRT, self.on_sigabrt)
python
def skipDryRun(logger, dryRun, level=logging.DEBUG): """ Return logging function. When logging function called, will return True if action should be skipped. Log will indicate if skipped because of dry run. """ # This is an undocumented "feature" of logging module: # logging.log() requires a nu...
java
public void addAliasForLocator(String alias, String locator) { LOG.info("Add alias: '" + alias + "' for '" + locator + "'"); aliases.put(alias, locator); }
java
public static void copyFile(File srcFile, File destFile) throws IOException { InputStream reader = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[2048]; int n = 0; while (-1 != (n = r...
java
protected void copy(final CacheEntry cacheEntry, final InputStream is, final ServletOutputStream ostream) throws IOException { IOException exception = null; InputStream resourceInputStream = null; // Optimization: If the binary content has already been loaded, send // it directly final Resource resource = c...
java
public static FluentLogger forEnclosingClass() { // NOTE: It is _vital_ that the call to "caller finder" is made directly inside the static // factory method. See getCallerFinder() for more information. String loggingClass = Platform.getCallerFinder().findLoggingClass(FluentLogger.class); return new Flu...
java
public static String verify(String value, int min, int max) { try { return validate(value, min, max); } catch (IllegalArgumentException ex) { throw new LocalizedIllegalArgumentException(ex); } }
python
def refresh(self): """ Resets the data for this navigator. """ self.setUpdatesEnabled(False) self.blockSignals(True) self.clear() tableType = self.tableType() if not tableType: self.setUpdatesEnabled(True) self.blockSignal...
python
def get_ylim(self): ''' Computes the ideal y-axis limits for the light curve plot. Attempts to set the limits equal to those of the raw light curve, but if more than 1% of the flux lies either above or below these limits, auto-expands to include those points. At the end, adds 5% ...
python
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40): """Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Inte...
python
def sdiv(computation: BaseComputation) -> None: """ Signed Division """ numerator, denominator = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) pos_or_neg = -1 if numerator * denominator < 0 else 1 if denominator == 0: re...
java
public void onUp(HumanInputEvent<?> event) { if (!isRightMouseButton(event)) { ToggleSelectionAction action = new ToggleSelectionAction(mapWidget, pixelTolerance); action.setPriorityToSelectedLayer(priorityToSelectedLayer); action.toggleSingle(getLocation(event, RenderSpace.SCREEN)); } }
java
public EEnum getIfcMemberTypeEnum() { if (ifcMemberTypeEnumEEnum == null) { ifcMemberTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(858); } return ifcMemberTypeEnumEEnum; }
python
def _set_class_parser(self, init_parser, methods_to_parse, cls): """Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated arg...
python
def create_hlamphaplot(plotman, h, v, alpha, options): '''Plot the data of the tomodir in one overview plot. ''' sizex, sizez = getfigsize(plotman) # create figure f, ax = plt.subplots(1, 3, figsize=(3 * sizex, sizez)) if options.title is not None: plt.suptitle(options.title, fontsize=18...
python
def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool: """Check that nothing will be overwritten when dictionaries are merged using `deep_merge`. Examples: >>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3}) True >>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3}) ...
python
def expand_iota_subscript(input_str, lowercase=False): """Find characters with iota subscript and replace w/ char + iota added.""" new_list = [] for char in input_str: new_char = MAP_SUBSCRIPT_NO_SUB.get(char) if not new_char: new_char = char new_list.append(new_char) ...
python
def onchange_dates(self): ''' This method gives the duration between check in and checkout if customer will leave only for some hour it would be considers as a whole day.If customer will check in checkout for more or equal hours, which configured in company as additional hours th...
python
def get_dummy_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ if settings.ALLOWED_HOSTS and settings.ALLOWED_HOSTS != "*": host = settings.ALLOWED_HOSTS[0] else: host = Site.objects.get_current().domain request = RequestFactory...
python
def cli(ctx=None, verbose=0): """Thoth solver command line interface.""" if ctx: ctx.auto_envvar_prefix = "THOTH_SOLVER" if verbose: _LOG.setLevel(logging.DEBUG) _LOG.debug("Debug mode is on")
java
public static Integer toIntegerObject(final Boolean bool) { if (bool == null) { return null; } return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; }
java
public void setRules(RuleProvider provider, List<Rule> rules) { providersToRules.put(provider, rules); }
python
def to_curve_spline(obj): ''' to_curve_spline(obj) obj if obj is a curve spline and otherwise attempts to coerce obj into a curve spline, raising an error if it cannot. ''' if is_curve_spline(obj): return obj elif is_tuple(obj) and len(obj) == 2: (crds,opts) = obj else: ...
java
public static synchronized void multipart(HttpString method, String url, HttpConsumer<MultipartExchange> endpoint, long maxSize) { checkStarted(); instance().endpoints.add(HandlerUtil.multipart(method, url, endpoint, instance().exceptionMapper, maxSize)); }
java
public BoundingBox extendDegrees(double verticalExpansion, double horizontalExpansion) { if (verticalExpansion == 0 && horizontalExpansion == 0) { return this; } else if (verticalExpansion < 0 || horizontalExpansion < 0) { throw new IllegalArgumentException("BoundingBox extend op...
python
def CallHwclock(logger): """Sync clock using hwclock. Args: logger: logger object, used to write to SysLog and serial port. """ command = ['/sbin/hwclock', '--hctosys'] try: subprocess.check_call(command) except subprocess.CalledProcessError: logger.warning('Failed to sync system time with hard...
java
public boolean alreadyPresent(ImportedKey importedKey) { if (foreignKeysByName == null) { return false; } Collection<ForeignKey> fks = foreignKeysByName.values(); if (fks == null) { return false; } for (ForeignKey fk : fks) { if (fk.g...
java
public void setIgnoredPackagings (final Set <String> aCollection) { ignoredPackagings = new HashSet <> (); if (aCollection != null) { for (final String sName : aCollection) if (StringHelper.hasText (sName)) if (!ignoredPackagings.add (sName)) getLog ().warn ("The ignore...
java
static List<AnnotatedValueResolver> ofServiceMethod(Method method, Set<String> pathParams, List<RequestObjectResolver> objectResolvers) { return of(method, pathParams, objectResolvers, true, true); }
java
public static int cusolverSpXcsrperm_bufferSizeHost( cusolverSpHandle handle, int m, int n, int nnzA, cusparseMatDescr descrA, Pointer csrRowPtrA, Pointer csrColIndA, Pointer p, Pointer q, long[] bufferSizeInBytes) {...
python
def get_reachable_volume_templates(self, start=0, count=-1, filter='', query='', sort='', networks=None, scope_uris='', private_allowed_only=False): """ Gets the storage templates that are connected on the specified networks based on the storage system port...
python
def parse(readDataInstance): """ Returns a new L{NetDirectory} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{NetDirectory} object. @rtype: L{NetDirectory} @return: A new L{NetDirec...
python
def save_tabs_when_changed(func): """Decorator for save-tabs-when-changed """ def wrapper(*args, **kwargs): func(*args, **kwargs) log.debug("mom, I've been called: %s %s", func.__name__, func) # Find me the Guake! clsname = args[0].__class__.__name__ g = None ...
python
def get_environment_paths(config, env): """ Get environment paths from given environment variable. """ if env is None: return config.get(Config.DEFAULTS, 'environment') # Config option takes precedence over environment key. if config.has_option(Config.ENVIRONMENTS, env): ...
python
def fn_with_custom_grad(grad_fn, use_global_vars=False): """Decorator to create a subgraph with a custom gradient function. The subgraph created by the decorated function is NOT put in a Defun and so does not suffer from the limitations of the Defun (all subgraph ops on the same device, no summaries). Args:...
java
public Map<String, Object> getViewMap(boolean create) { Map<String, Object> viewMap = (Map<String, Object>) getTransientStateHelper().getTransient("com.sun.faces.application.view.viewMap"); if (create && viewMap == null) { viewMap = new ViewMap(getFacesContext().getApplicat...
python
def get_jaro_distance(first, second, winkler=True, winkler_ajustment=True, scaling=0.1): """ :param first: word to calculate distance for :param second: word to calculate distance with :param winkler: same as winkler_ajustment :param winkler_ajustment: add an adjustment factor to the Jaro of the dis...
java
public Page<T> previousPage(final Page<T> page) { return previousPage(page, Twilio.getRestClient()); }
java
public void setupFields() { FieldInfo field = null; field = new FieldInfo(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); field.setDataClass(Integer.class); field = new FieldInfo(this, KEY, 128, null, null); field = new FieldInfo(this, VALUE, 255, null, null); ...
java
private boolean processQueue(K key) { Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForKey(key); if(requestQueue.isEmpty()) { return false; } // Attempt to get a resource. Pool<V> resourcePool = getResourcePoolForKey(key); V resource = null; ...
java
public synchronized void setValue(String name, String value) { if (map == null) { map = new HashMap<String,String>(); } map.put(name, value); }
java
public SecurityRuleInner createOrUpdate(String resourceGroupName, String networkSecurityGroupName, String securityRuleName, SecurityRuleInner securityRuleParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).toBlocking(...
python
def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Port must be in the [1, 65535] range, not %d.' % port) port_info = _PortInfo(port=port) self._port_queue.append(port_in...
python
def add(name, device): ''' Add new device to RAID array. CLI Example: .. code-block:: bash salt '*' raid.add /dev/md0 /dev/sda1 ''' cmd = 'mdadm --manage {0} --add {1}'.format(name, device) if __salt__['cmd.retcode'](cmd) == 0: return True return False
java
public static double getRadius(Atom atom) { if (atom.getElement()==null) { logger.warn("Unrecognised atom "+atom.getName()+" with serial "+atom.getPDBserial()+ ", assigning the default vdw radius (Nitrogen vdw radius)."); return Element.N.getVDWRadius(); } Group res = atom.getGroup(); if (res==nul...
java
@Override protected BaasStream getFromCache(BaasBox box) throws BaasException { return box.mCache.getStream(id); }
python
def init(context, reset, force): """Setup the database.""" store = Store(context.obj['database'], context.obj['root']) existing_tables = store.engine.table_names() if force or reset: if existing_tables and not force: message = f"Delete existing tables? [{', '.join(existing_tables)}]"...
java
public static <T> T[] validIndex(final T[] array, final int index) { return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); }
java
@Override public void declareOutputFields(OutputFieldsDeclarer declarer) { String streamId = getOutputStreamId(); Fields names = new Fields(outputFields); logger.info("{} declares {} for stream '{}'", new Object[] {this, names, streamId}); declarer.declareStream(streamId, names); }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "geometryMember") public JAXBElement<GeometryPropertyType> createGeometryMember(GeometryPropertyType value) { return new JAXBElement<GeometryPropertyType>(_GeometryMember_QNAME, GeometryPropertyType.class, null, value); }
python
def create(cls, cli, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): """ Configures a remote system for remote replication. :param cls: this class. :param cli: t...
java
public static String getURLString(String relativeToBase){ if(relativeToBase.startsWith("/")){ relativeToBase = relativeToBase.substring(1); } return baseURL + relativeToBase; }
python
def import_data(self, data): """Import additional data for tuning Parameters ---------- data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' """ _completed_num = 0 for trial_info in data: logger.info("I...
java
public static void addSoftEvidence(Network bn, String nodeName, HashMap<String, Double> softEvidence) throws ShanksException { String auxNodeName = softEvidenceNodePrefix + nodeName; int targetNode = bn.getNode(nodeName); boolean found = false; int[] children = bn.getChildren...
python
def update(dest, variation, path=None): """ Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return: """ if dest is None: r...
java
protected IStyleAppendable appendCluster(IStyleAppendable it, String element0, String... elements) { return appendCluster(it, true, element0, elements); }
java
public String getConfigurationOptionValue (String optionName, String defaultValue) { String optionValue; Node configurationOption = this.getConfigurationOption (optionName); if (configurationOption != null) { optionValue = configurationOption.getTextContent (); } else { optionValue = defaultValue; } r...
java
public boolean match(String str, String regex) { if (str == null || regex == null) return false; if (regex.trim().isEmpty()) return true; return Pattern.compile(regex.trim()).matcher(str).find(); }
python
def get_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, **kwargs): """Find FreeShippingPromotion Return single instance of FreeShippingPromotion by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=Tru...
python
def getBuffer(x): """ Copy @x into a (modifiable) ctypes byte array """ b = bytes(x) return (c_ubyte * len(b)).from_buffer_copy(bytes(x))
python
def select(self, names): """return the named subset of policies""" return PolicyCollection( [p for p in self.policies if p.name in names], self.options)
java
public static Workbook createWorkbook(FileFormat format, OutputStream os) throws IOException { return createWorkbook(format, os, null); }
python
def remove_rule_entry(self, rule_info): """Remove host data object from rule_info list.""" temp_list = list(self.rule_info) for rule in temp_list: if (rule.ip == rule_info.get('ip') and rule.mac == rule_info.get('mac') and rule.port == rule_info.g...
python
def updateHeader(self, wcsname=None, reusename=False): """ Update header of image with shifts computed by *perform_fit()*. """ # Insure filehandle is open and available... self.openFile() verbose_level = 1 if not self.perform_update: verbose_level = 0 ...
java
private void updateAdd() { if (willAdd) { for (final Featurable featurable : toAdd) { featurables.add(featurable); for (final HandlerListener listener : listeners) { listener.notifyHandlableAdded(fea...
python
def classname(self): """ Returns the Java classname in dot-notation. :return: the Java classname :rtype: str """ cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;") return javabridge.call(cls, "getName", "()Ljava/lang/String;")
java
@Override @Nonnull public JQueryInvocation jqinvoke (@Nonnull @Nonempty final String sMethod) { return new JQueryInvocation (this, sMethod); }
java
public static <K,V> CacheLoader<K,V> loader(Function<K,V> function) { return new FunctionCacheLoader<>(function); }
python
def get_stp_mst_detail_output_cist_port_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
java
public Converter getConverter() { if (this.converter != null) { return (this.converter); } return (Converter) getStateHelper().eval(PropertyKeys.converter); }
java
protected void setMessageListener(MessageListener messageListener) { this.messageListener = messageListener; if (messageListener == null || isClosed()) { return; } synchronized (stateLock) { if (!running || isClosed()) { return; } ...
java
public static String getVersionString() { String versionString = "UNKNOWN"; Properties propeties = getProperites(); if(propeties != null) { versionString = propeties.getProperty("finmath-lib.version"); } return versionString; }
python
def report(policies, start_date, options, output_fh, raw_output_fh=None): """Format a policy's extant records into a report.""" regions = set([p.options.region for p in policies]) policy_names = set([p.name for p in policies]) formatter = Formatter( policies[0].resource_manager.resource_type, ...
java
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; }
java
@JsonProperty("dq") @JsonSerialize(using = Base64UrlJsonSerializer.class) @JsonDeserialize(using = Base64UrlJsonDeserializer.class) public byte[] dq() { return ByteExtensions.clone(this.dq); }
python
def git_add_commit_push_all_repos(cat): """Add all files in each data repository tree, commit, push. Creates a commit message based on the current catalog version info. If either the `git add` or `git push` commands fail, an error will be raised. Currently, if `commit` fails an error *WILL NOT* be ra...
java
@BetaApi public final Operation setTargetPoolsRegionInstanceGroupManager( String instanceGroupManager, RegionInstanceGroupManagersSetTargetPoolsRequest regionInstanceGroupManagersSetTargetPoolsRequestResource) { SetTargetPoolsRegionInstanceGroupManagerHttpRequest request = SetTarget...
java
private int getPageOffset(int page) { if (pageSize <= 0) { pageSize = frame.getVdmThread().getPropertyPageSize(); } if (pageSize <= 0) { return 0; } return page * pageSize; }
python
def list_repos(self, envs=[], query='/repositories/'): """ List repositories in specified environments """ juicer.utils.Log.log_debug( "List Repos In: %s", ", ".join(envs)) repo_lists = {} for env in envs: repo_lists[env] = [] for env...
python
def get(self, key): """ Retrieves previously stored key from the storage :return value, stored in the storage """ if key not in self._keystore: return None rec = self._keystore[key] """:type rec InMemoryItemValue""" if rec.is_expired: self.delete(key) return None ...
python
def login(self, username, passwd_hash, webapi_key, country_code=1): """Log in (sets self.token). Returns token (session_handle).""" self.client = Client(self.webapi_url) self.ArrayOfLong = self.client.get_type('ns0:ArrayOfLong') # this should be done by zeep... ver_key = self.client.ser...
python
def _logout(creds_file=None): """ Logout main function, just rm ~/.onecodex more or less """ if _remove_creds(creds_file=creds_file): click.echo("Successfully removed One Codex credentials.", err=True) sys.exit(0) else: click.echo("No One Codex API keys found.", err=True) ...
python
def _cast_to_frameset(cls, other): """ Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable): item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a...
python
def find_one(self, filter_=None, *args, **kwargs): """find_one method """ wrapper = kwargs.pop('wrapper', False) if wrapper is True: return self._wrapper_find_one(filter_, *args, **kwargs) return self.__collect.find_one(filter_, *args, **kwargs)
java
public ResponseEntity handleWebFingerDiscoveryRequest(final String resource, final String rel) { if (StringUtils.isNotBlank(rel) && !OidcConstants.WEBFINGER_REL.equalsIgnoreCase(rel)) { LOGGER.warn("Handling discovery request for a non-standard OIDC relation [{}]", rel); } val issue...
java
public static base_responses expire(nitro_service client, cachecontentgroup resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { cachecontentgroup expireresources[] = new cachecontentgroup[resources.length]; for (int i=0;i<resources.length;i++){ ex...
python
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit], cz_depth: int, seed: int) -> circuits.Circuit: """ Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.or...
java
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { /* * The following valuation code requires in-depth knowledge of the model to calculate the denstiy analytically. */ BlackScholesModel blackScholesModel = null; if(model...
java
public Nfs3RemoveRequest makeRemoveRequest(byte[] parentDirectoryFileHandle, String name) throws FileNotFoundException { return new Nfs3RemoveRequest(parentDirectoryFileHandle, name, _credential); }
python
def create_summary_tear_sheet(factor_data, long_short=True, group_neutral=False): """ Creates a small summary tear sheet with returns, information, and turnover analysis. Parameters ---------- factor_data : pd.DataFrame - MultiIndex ...
java
public HttpHandler findHandler(Class handlerClass, String uri, String[] vhosts) { uri = URI.stripPath(uri); if (vhosts==null || vhosts.length==0) vhosts=__noVirtualHost; for (int h=0; h<vhosts.length ...
java
private void addCoord(Chunk chunk, BlockPos pos) { chunks(chunk).add(chunk, pos); }
java
public RunT getBuild(String id) { for (RunT r : _getRuns().values()) { if (r.getId().equals(id)) return r; } return null; }