language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def extend_substation(grid, critical_stations, grid_level):
"""
Reinforce MV or LV substation by exchanging the existing trafo and
installing a parallel one if necessary.
First, all available transformers in a `critical_stations` are extended to
maximum power. If this does not solve all present iss... |
java | @Override
public void handleRequest(final Request request) {
if (plainBtn.isPressed()) {
WMessages.getInstance(this).info("Plain button pressed.");
}
if (linkBtn.isPressed()) {
WMessages.getInstance(this).info("Link button pressed.");
}
} |
python | def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install("black", "flake8", *LOCAL_DEPS)
session.install(".")
session.run("flake8", os.path.join("google", "cloud", "bigquery"))
session.run("... |
python | def format_cmd(args):
"""
Format the arg list appropriate for display as a command line with
individual arguments quoted appropriately. This is intended for logging
or display and not as input to a command interpreter (shell).
"""
if args is None:
return ''
out = ''
if not isinstanc... |
python | def seed_instance(self, seed=None):
"""Calls random.seed"""
if self.__random == random:
# create per-instance random obj when first time seed_instance() is
# called
self.__random = random_module.Random()
self.__random.seed(seed)
return self |
python | def generateLinearRDD(sc, nexamples, nfeatures, eps,
nParts=2, intercept=0.0):
"""
Generate an RDD of LabeledPoints.
"""
return callMLlibFunc(
"generateLinearRDDWrapper", sc, int(nexamples), int(nfeatures),
float(eps), int(nParts), float(... |
python | def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd):
"""
just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return:
"""
return gen_toy(f, nsample * ntoy, bo... |
java | public <S, D> TypeMap<S, D> getOrCreate(S source, Class<S> sourceType, Class<D> destinationType,
String typeMapName, MappingEngineImpl engine) {
return getOrCreate(source, sourceType, destinationType, typeMapName, null, null,
engine);
} |
python | def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... |
java | public static Comparator<LongTuple> comparator(Order order)
{
if (order == Order.LEXICOGRAPHICAL)
{
return (t0, t1) -> compareLexicographically(t0, t1);
}
if (order == Order.COLEXICOGRAPHICAL)
{
return (t0, t1) -> compareColexicographically(t0,... |
python | def human_xor_00(X, y, model_generator, method_name):
""" XOR (false/false)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following fu... |
java | public Observable<ExtensionInner> getAsync(String resourceGroupName, String clusterName, String extensionName) {
return getWithServiceResponseAsync(resourceGroupName, clusterName, extensionName).map(new Func1<ServiceResponse<ExtensionInner>, ExtensionInner>() {
@Override
public Extension... |
python | def find_products(self, product_type):
"""Search for products of a given type.
Search through the products declared by this IOTile component and
return only those matching the given type. If the product is described
by the path to a file, a complete normalized path will be returned.
... |
python | def deposit(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#deposit-funds"""
for required in ['payment_method', 'amount', 'currency']:
if required not in params:
raise ValueError("Missing required parameter: %s" % required)
response = self._post... |
python | def startswith(self, prefix):
"""
Construct a Filter matching values starting with ``prefix``.
Parameters
----------
prefix : str
String prefix against which to compare values produced by ``self``.
Returns
-------
matches : Filter
... |
python | def _is_non_Exif_APP1_segment(cls, stream, offset):
"""
Return True if the APP1 segment at *offset* in *stream* is NOT an
Exif segment, as determined by the ``'Exif\x00\x00'`` signature at
offset 2 in the segment.
"""
stream.seek(offset+2)
exif_signature = stream.... |
python | def invert_dict(dict_, unique_vals=True):
"""
Reverses the keys and values in a dictionary. Set unique_vals to False if
the values in the dict are not unique.
Args:
dict_ (dict_): dictionary
unique_vals (bool): if False, inverted keys are returned in a list.
Returns:
dict: ... |
python | def _compound_column_value(k1, k2):
"""
Like :py:meth:`~._column_value` but collapses two unknowns into one.
:param k1: first (top-level) value
:param k2: second (bottom-level) value
:return: display key
:rtype: str
"""
k1 = ProjectStats._column_value(k1)... |
python | def parse_token_contents(parser, token):
"""
Parse template tag contents
"""
bits = token.split_contents()
tag = bits.pop(0)
args = []
kwargs = {}
asvar = None
if len(bits) >= 2 and bits[-2] == "as":
asvar = bits[-1]
bits = bits[:-2]
for bit in bits:
match... |
java | protected void createEventTimeStamp(RepositoryLogRecord record, StringBuilder buffer) {
if (null == record) {
throw new IllegalArgumentException("Record cannot be null");
}
if (null == buffer) {
throw new IllegalArgumentException("Buffer cannot be null");
}
// Create the time stamp
buffer.append('[');... |
python | def update_pmag_tables(self):
"""
Reads pmag tables from data model 2.5 and updates them with updates
their data
"""
pmag_specimens, pmag_samples, pmag_sites = [], [], []
print("-I- Reading previous interpretations from specimen/sample/site tables")
try:
... |
java | public void addKeyField(Field field, boolean bKeyOrder)
{ // Get the field with this seq
if (m_vKeyFieldList.size() == 0)
m_bKeyOrder = bKeyOrder;
m_vKeyFieldList.add(field); // init the key field seq
} |
java | public static String unwrap(final String str, final String prefix, final String suffix) {
N.checkArgNotNull(prefix);
N.checkArgNotNull(suffix);
if (N.isNullOrEmpty(str)) {
return N.EMPTY_STRING;
} else if (str.length() - prefix.length() >= suffix.length() && str.starts... |
python | def parse_host(cls, host):
'''Parse the host and return hostname and port.'''
if host.endswith(']'):
return cls.parse_hostname(host), None
else:
hostname, sep, port = host.rpartition(':')
if sep:
port = int(port)
if port < 0 or port > 6553... |
python | def console_list_save_xp(
console_list: Sequence[tcod.console.Console],
filename: str,
compress_level: int = 9,
) -> bool:
"""Save a list of consoles to a REXPaint `.xp` file."""
tcod_list = lib.TCOD_list_new()
try:
for console in console_list:
lib.TCOD_list_push(tcod_list, _... |
java | public void hkManage(final Class<?> type) {
if (!JerseyBinding.isHK2Managed(type, options.get(JerseyExtensionsManagedByGuice))) {
throw new WrongContextException("HK2 creates service %s which must be managed by guice.",
type.getName());
}
hkManaged.add(type);
... |
python | def scale_axes_from_data(self):
"""Restrict data limits for Y-axis based on what you can see
"""
# get tight limits for X-axis
if self.args.xmin is None:
self.args.xmin = min(fs.xspan[0] for fs in self.spectra)
if self.args.xmax is None:
self.args.xmax = m... |
java | private void setValues(int position, Button view) {
if (position == 10) {
view.setText("0");
} else if (position == 9) {
view.setVisibility(View.INVISIBLE);
} else {
view.setText(String.valueOf((position + 1) % 10));
}
} |
python | def get_rpn_anchor_input(im, boxes, is_crowd):
"""
Args:
im: an image
boxes: nx4, floatbox, gt. shoudn't be changed
is_crowd: n,
Returns:
The anchor labels and target boxes for each pixel in the featuremap.
fm_labels: fHxfWxNA
fm_boxes: fHxfWxNAx4
NA ... |
python | def _handle_pagerange(pagerange):
"""
Yields start and end pages from DfR pagerange field.
Parameters
----------
pagerange : str or unicode
DfR-style pagerange, e.g. "pp. 435-444".
Returns
-------
start : str
Start page.
end : str
End page.
"""
try:... |
java | private Long handleToId(Object handle) {
if (handle instanceof Long) {
return (Long) handle;
} else {
throw new IllegalArgumentException("Expected handle to be a Long, but was: " +
handle.getClass().getCanonicalName());
}
} |
python | def _run_asyncio(loop, zmq_context):
"""
Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends
:param loop:
:param zmq_context:
:return:
"""
try:
asyncio.set_event_loop(loop)
loop.run_forever()
except:
pass
fina... |
java | public NotificationChain basicSetGuard(Expression newGuard, NotificationChain msgs)
{
Expression oldGuard = guard;
guard = newGuard;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SimpleAntlrPackage.RULE_ELEMENT__GUARD, oldGuard, new... |
java | @Override
public List<CPFriendlyURLEntry> findByG_C_U(long groupId, long classNameId,
String urlTitle, int start, int end) {
return findByG_C_U(groupId, classNameId, urlTitle, start, end, null);
} |
java | public int getFrequency(String key)
{
TermFrequency termFrequency = get(key);
if (termFrequency == null) return 0;
return termFrequency.getFrequency();
} |
java | @ResponseOverride(
description = "Set a JSON value.",
parameters = {"name", "value", "path"}
)
public static void set_json_value(PluginArguments args, String name, String value, String path) throws Exception {
HttpServletResponse response = args.getResponse();
String cont... |
python | def _set_configspec(self, section, copy):
"""
Called by validate. Handles setting the configspec on subsections
including sections to be validated by __many__
"""
configspec = section.configspec
many = configspec.get('__many__')
if isinstance(many, dict):
... |
java | boolean nextIsMixinParam( boolean isBlock ) {
boolean isFirst = true;
for( int i=cachePos; i < cache.length(); i++ ) {
char ch = cache.charAt( i );
switch( ch ) {
case ')':
return true;
case '@':
return cache... |
python | def add_protein_data(proteins, pgdb, headerfields, genecentric=False,
pool_to_output=False):
"""First creates a map with all master proteins with data,
then outputs protein data dicts for rows of a tsv. If a pool
is given then only output for that pool will be shown in the
protein t... |
python | def render_image(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the pixel space.
*** internal method-- do not use ***
"""
if self.surface is None:
return
self.logger.debug("redraw surface")
# get window con... |
java | public String get(String events, String defaultValue) {
return get(parseEvents(events), defaultValue);
} |
java | public void remove(int profileId, String clientUUID) throws Exception {
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
// first try selecting the row we want to deal with
statement = sqlConnectio... |
python | async def _command_dispatcher(self):
"""
This is a private method.
It continually accepts and interprets data coming from Firmata,and then
dispatches the correct handler to process the data.
:returns: This method never returns
"""
# sysex commands are assembled i... |
java | public TempDir createTempDir(String originalName) throws IOException {
if (!open.get()) {
throw VFSMessages.MESSAGES.tempFileProviderClosed();
}
final String name = createTempName(originalName + "-", "");
final File f = new File(providerRoot, name);
for (int i = 0; i ... |
python | def add_scope_ip(hostipaddress, name, description, auth, url, scopeid=None, network_address=None):
"""
Function to add new host IP address allocation to existing scope ID
:param hostipaddress: ipv4 address of the target host to be added to the target scope
:param name: name of the owner of this host
... |
java | private static void unregister(ObjectName objectName) {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
for (ObjectName name : server.queryNames(objectName, null)) {
server.unregisterMBean(name);
}
} catch (MBeanRegistrationException | InstanceNotFoundException e) ... |
python | def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specif... |
java | public static <T> T copy(T orig) {
if (orig == null)
return null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(orig);
oos.flush();
ByteArrayInpu... |
java | public static OptionalFloat createFloat(final String str) {
if (N.isNullOrEmpty(str)) {
return OptionalFloat.empty();
}
try {
return OptionalFloat.of(Float.parseFloat(str));
} catch (NumberFormatException e) {
return OptionalFloat.empty();
... |
java | public static List<CommerceWishListItem> findByCommerceWishListId(
long commerceWishListId, int start, int end,
OrderByComparator<CommerceWishListItem> orderByComparator) {
return getPersistence()
.findByCommerceWishListId(commerceWishListId, start, end,
orderByComparator);
} |
python | def _clone_block_and_wires(block_in):
"""
This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the re... |
java | @SuppressWarnings("unchecked")
public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {
return new SimpleAttachmentKey(valueClass);
} |
java | public HttpConnection setHttpsInfo(HostnameVerifier hostnameVerifier, SSLSocketFactory ssf) throws HttpException {
final HttpURLConnection conn = this.conn;
if (conn instanceof HttpsURLConnection) {
// Https请求
final HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
// 验证域
httpsConn.setHo... |
python | def from_date_time_string(cls, datetime_string, leap_year=False):
"""Create Ladybug DateTime from a DateTime string.
Usage:
dt = DateTime.from_date_time_string("31 Dec 12:00")
"""
dt = datetime.strptime(datetime_string, '%d %b %H:%M')
return cls(dt.month, dt.day, dt... |
java | public StreamPlan requestRanges(InetAddress from, InetAddress connecting, String keyspace, Collection<Range<Token>> ranges, String... columnFamilies)
{
StreamSession session = coordinator.getOrCreateNextSession(from, connecting);
session.addStreamRequest(keyspace, ranges, Arrays.asList(columnFamilie... |
python | def clear(self):
"""Clear current state."""
self.exposures = []
self.exposure_labels = []
self.exposure_combo_boxes = []
self.exposure_edit_buttons = []
self.mode = CHOOSE_MODE
self.layer_purpose = None
self.layer_mode = None
self.special_case_ind... |
java | public ClusterInner createOrUpdate(String resourceGroupName, String clusterName, ClusterInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().last().body();
} |
python | def option(*args, **kwargs):
"""Decorator to add an option to the optparser argument of a Cmdln
subcommand.
Example:
class MyShell(cmdln.Cmdln):
@cmdln.option("-f", "--force", help="force removal")
def do_remove(self, subcmd, opts, *args):
#...
"""
#... |
java | public static final String getStringAttribute(Path path, String attribute, LinkOption... options) throws IOException
{
attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute;
byte[] attr = (byte[]) Files.getAttribute(path, attribute, options);
if (attr == null)
... |
python | def reduce_by(self, package_request):
"""Reduce this scope wrt a package request.
Returns:
A (_PackageScope, [Reduction]) tuple, where the scope is a new
scope copy with reductions applied, or self if there were no
reductions, or None if the scope was completely redu... |
python | def extra_args_from_config(cp, section, skip_args=None, dtypes=None):
"""Gets any additional keyword in the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
section : str
The name of the section to read.
... |
python | def submission_filenames(round_num=None, tournament=None):
"""Get filenames of your submissions"""
click.echo(prettify(
napi.get_submission_filenames(tournament, round_num))) |
python | def _get_service_port(self, instance):
"""
Get the ntp server port
"""
host = instance.get('host', DEFAULT_HOST)
port = instance.get('port', DEFAULT_PORT)
# default port is the name of the service but lookup would fail
# if the /etc/services file is missing. In th... |
python | def group_sources(self, radius='', plot=False):
"""
Calculate the centers of the point clusters given the
radius and minimum number of points
Parameters
----------
coords: array-like
The list of (x,y) coordinates of all clicks
radius: int
... |
java | public Destination getReplyTo() {
Object replyTo = getHeader(JmsMessageHeaders.REPLY_TO);
if (replyTo != null) {
return (Destination) replyTo;
}
return null;
} |
java | public static Invocable findMostSpecificInvocable(
Class<?>[] idealMatch, List<Invocable> methods )
{
// copy signatures into array for findMostSpecificMethod()
List<Class<?>[]> candidateSigs = new ArrayList<>();
List<Invocable> methodList = new ArrayList<>();
... |
python | def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns True or a timeout is reached.
Note: The function may return anything which evaluates to implicit True. This
function will loop calling it as long as it continues to retur... |
python | def load_bcah98_mass_radius (tablelines, metallicity=0, heliumfrac=0.275,
age_gyr=5., age_tol=0.05):
"""Load mass and radius from the main data table for the famous models of
Baraffe+ (1998A&A...337..403B).
tablelines
An iterable yielding lines from the table data file.
... |
java | public static <T extends Annotation> void trim(Collection<T> annotations) {
for (final T anno : annotations) {
trim(anno, ' ', '\n', '\t', '\r', '\f');
}
} |
java | public void setExportOnlyColumns(final String[] exportOnlyColumns) {
if (exportOnlyColumns != null) {
this.exportOnlyColumns = exportOnlyColumns.clone();
} else {
this.exportOnlyColumns = null;
}
} |
python | def walktree(classes, children, parent):
"""Recursive helper function for getclasstree()."""
results = []
classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
for c in classes:
results.append((c, c.__bases__))
if children.has_key(c):
results.append(walktree(children[c], chi... |
python | def attach_vpn_gateway(self, vpn_gateway_id, vpc_id):
"""
Attaches a VPN gateway to a VPC.
:type vpn_gateway_id: str
:param vpn_gateway_id: The ID of the vpn_gateway to attach
:type vpc_id: str
:param vpc_id: The ID of the VPC you want to attach the gateway to.
... |
java | @SuppressWarnings("unchecked")
public EList<IfcAppliedValueRelationship> getValueOfComponents() {
return (EList<IfcAppliedValueRelationship>) eGet(
Ifc2x3tc1Package.Literals.IFC_APPLIED_VALUE__VALUE_OF_COMPONENTS, true);
} |
python | def at(self, root):
"""Set root where PyJsonq start to prepare
:@param root
:@type root: string
:@return self
:@throws KeyError
"""
leafs = root.strip(" ").split('.')
for leaf in leafs:
if leaf:
self._json_data = self.__get_va... |
java | public void billingAccount_ovhPabx_serviceName_dialplan_dialplanId_extension_extensionId_conditionTime_conditionId_PUT(String billingAccount, String serviceName, Long dialplanId, Long extensionId, Long conditionId, OvhOvhPabxDialplanExtensionConditionTime body) throws IOException {
String qPath = "/telephony/{billing... |
python | def to_json(self):
"""
Returns:
str: Json for commands array object and all of the commands inside the array."""
commands = ",".join(map(lambda x: x.to_json(), self._commands))
return "{\"commands\": [" + commands + "]}" |
python | def send_data(self, stream_id, data, *, end_stream=False):
"""
Send request or response body on the given stream.
This will block until either whole data is sent, or the stream gets
closed. Meanwhile, a paused underlying transport or a closed flow
control window will also help w... |
java | public void send(Command command) {
logger.finest(command.toString());
byte[] payload = command.toByteArray();
int totalSize = payload.length + 1; // increment 1 for message type
ByteBuffer outMessageSize = encodeMessageSize(totalSize);
// create the message
ByteBuffer buffer = ByteBuffer.allo... |
java | protected boolean isSameSnakSet(Iterator<Snak> snaks1, Iterator<Snak> snaks2) {
ArrayList<Snak> snakList1 = new ArrayList<>(5);
while (snaks1.hasNext()) {
snakList1.add(snaks1.next());
}
int snakCount2 = 0;
while (snaks2.hasNext()) {
snakCount2++;
Snak snak2 = snaks2.next();
boolean found = false... |
python | def etcal(et, lenout=_default_len_out):
"""
Convert from an ephemeris epoch measured in seconds past
the epoch of J2000 to a calendar string format using a
formal calendar free of leapseconds.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/etcal_c.html
:param et: Ephemeris time measur... |
java | @Override
public Jingle parse(XmlPullParser parser, int intialDepth, XmlEnvironment xmlEnvironment) throws IOException, XmlPullParserException, SmackParsingException {
Jingle jingle = new Jingle();
String sid = "";
JingleActionEnum action;
Jid initiator, responder;
boolean d... |
java | @Override
public final void setJMSMessageID(String id) throws JMSException
{
assertDeserializationLevel(MessageSerializationLevel.FULL);
this.id = id;
} |
python | def animation_control(object, sequence_length=None, add=True, interval=200):
"""Animate scatter, quiver or mesh by adding a slider and play button.
:param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
control multiple.
:param sequ... |
python | def _dispatch(self, method_name):
"""
Top-level dispatch method
"""
URLENCODING_CLASS = r'[a-zA-Z0-9\-_.~%]'
routes = {
r'^/v1/ping$': {
'routes': {
'GET': self.GET_ping,
},
},
r'^/v1/info$':... |
java | private static void buildInvertedDependencyGraph(IServiceManager manager, List<DependencyNode> roots,
List<Service> infraServices, List<Service> freeServices, Accessors accessors) {
final Map<Class<? extends Service>, DependencyNode> dependentServices = new TreeMap<>(Comparators.CLASS_COMPARATOR);
final Map<Clas... |
java | @Override
public CommerceWarehouseItem findByCWI_CPIU(long commerceWarehouseId,
String CPInstanceUuid) throws NoSuchWarehouseItemException {
CommerceWarehouseItem commerceWarehouseItem = fetchByCWI_CPIU(commerceWarehouseId,
CPInstanceUuid);
if (commerceWarehouseItem == null) {
StringBundler msg = new Str... |
java | public Matrix4f rotation(float angle, float x, float y, float z) {
float sin = (float) Math.sin(angle);
float cos = (float) Math.cosFromSin(sin, angle);
float C = 1.0f - cos;
float xy = x * y, xz = x * z, yz = y * z;
if ((properties & PROPERTY_IDENTITY) == 0)
MemUtil.... |
python | def record_deployed_values(deployed_values, filename):
# type: (Dict[str, Any], str) -> None
"""Record deployed values to a JSON file.
This allows subsequent deploys to lookup previously deployed values.
"""
final_values = {} # type: Dict[str, Any]
if os.path.isfile(filename):
with op... |
python | def aggregate_keywords(keywords, sep, prefix, raw=False):
""" take our keyword arguments, and a separator, and compose the list of
flat long (and short) arguments. example
{'color': 'never', 't': True, 'something': True} with sep '='
becomes
['--color=never', '-t', '--something']
th... |
java | public String[] findInstalledSipApplications() {
Iterator<SipContext> apps = findSipApplications();
ArrayList<String> appList = new ArrayList<String>();
while(apps.hasNext()){
SipContext ctx = apps.next();
appList.add(ctx.getApplicationName());
}
String[] ret = new String[appList.size()];
for(int q=0;... |
java | @Override
public String getRemoteHost() {
String addr = this.connection.getRemoteHostName(true);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "getRemoteHost: " + addr);
}
return addr;
} |
python | def QA_fetch_stock_divyield(code, start, end=None, format='pd', collections=DATABASE.stock_divyield):
'获取股票日线'
#code= [code] if isinstance(code,str) else code
# code checking
code = QA_util_code_tolist(code)
if QA_util_date_valid(end):
__data = []
cursor = collections.find({
... |
python | def get_event_loop(self):
"""Get the event loop.
This may be None or an instance of EventLoop.
"""
if (self._event_loop is None and
threading.current_thread().name == 'MainThread'):
self._event_loop = self.new_event_loop()
return self._event_loop |
python | def _clean(self):
"""Remove references of inactive workers periodically."""
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
else:
self._current_worker = None
self._timer.stop() |
python | def multipart_uploadpart(self, multipart):
"""Upload a part.
:param multipart: A :class:`invenio_files_rest.models.MultipartObject`
instance.
:returns: A Flask response.
"""
content_length, part_number, stream, content_type, content_md5, tags =\
current_f... |
python | def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bo... |
java | public Invoices getAccountInvoices(final String accountCode, final InvoiceState state, final QueryParams params) {
if (state != null) params.put("state", state.getType());
return doGET(Accounts.ACCOUNTS_RESOURCE + "/" + accountCode + Invoices.INVOICES_RESOURCE,
Invoices.class, params);
... |
python | def __create_channel_run(self, channel, username, token):
"""Sends a post request to create the channel run."""
data = {
'channel_id': channel.get_node_id().hex,
'chef_name': self.__get_chef_name(),
'ricecooker_version': __version__,
'started_by_user': use... |
java | @Override
public int compareTo(IVersion other)
{
if (other instanceof SemanticVersion) {
SemanticVersion sv = (SemanticVersion) other;
// If neither is named, then compare them as semantic values
return this.head.compareTo(sv.head);
}
else {
// Fall back to simple string comparis... |
java | public synchronized Name getServiceName() {
if (size() < 2) {
return null;
}
if (cachedServiceName == null) {
cachedServiceName = getCompositeKey().getPrefix(size() - 1);
}
return cachedServiceName;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.