language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def parse_degrees(cls, degrees, arcminutes, arcseconds, direction=None):
"""
Parse degrees minutes seconds including direction (N, S, E, W)
"""
degrees = float(degrees)
negative = degrees < 0
arcminutes = float(arcminutes)
arcseconds = float(arcseconds)
i... |
java | public XExtension getByPrefix(String prefix) {
for (XExtension ext : extensionList) {
if (ext.getPrefix().equals(prefix)) {
return ext;
}
}
return null;
} |
python | def __initialize_tree(self, theme):
"""
Initializes the object formats tree.
:param theme: Theme.
:type theme: dict
"""
for item in sorted(theme):
current_node = self.__root_node
for format in item.split("."):
nodes = [node for no... |
python | def upload(ctx):
"""Upload files to Azure Storage"""
settings.add_cli_options(ctx.cli_options, settings.TransferAction.Upload)
ctx.initialize(settings.TransferAction.Upload)
specs = settings.create_upload_specifications(
ctx.cli_options, ctx.config)
del ctx.cli_options
for spec in specs:... |
java | public Database asynchronous(final Scheduler nonTransactionalScheduler) {
return asynchronous(new Func0<Scheduler>() {
@Override
public Scheduler call() {
return nonTransactionalScheduler;
}
});
} |
python | def bucket(cls, bucket_name, connection=None):
"""Gives the bucket from couchbase server.
:param bucket_name: Bucket name to fetch.
:type bucket_name: str
:returns: couchbase driver's Bucket object.
:rtype: :class:`couchbase.client.Bucket`
:raises: :exc:`RuntimeError` If... |
python | def get_user_dn(self, username):
"""
Get the user distinguished name (dn)
"""
server = ldap3.Server('ldap://' + self.ldap_server)
connection = ldap3.Connection(server)
connection.open()
connection.search(
search_base=self.dn,
search_filter... |
java | @SuppressWarnings("WeakerAccess")
public static double compareChi2(TDigest dist1, TDigest dist2, double[] qCuts) {
double[][] count = new double[2][];
count[0] = new double[qCuts.length + 1];
count[1] = new double[qCuts.length + 1];
double oldQ = 0;
double oldQ2 = 0;
... |
java | public static com.liferay.commerce.product.model.CPFriendlyURLEntry createCPFriendlyURLEntry(
long CPFriendlyURLEntryId) {
return getService().createCPFriendlyURLEntry(CPFriendlyURLEntryId);
} |
java | public void addPhaseListener(PhaseListener phaseListener)
{
if (phaseListener == null)
{
throw new NullPointerException("phaseListener");
}
getStateHelper().add(PropertyKeys.phaseListeners, phaseListener);
} |
java | public EClass getIfcRelConnectsStructuralElement() {
if (ifcRelConnectsStructuralElementEClass == null) {
ifcRelConnectsStructuralElementEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(462);
}
return ifcRelConnectsStructuralElementEClass;
} |
java | @Pure
@Inline(value = "$2.valueOf($1.doubleValue())", imported = BigDecimal.class)
public static BigDecimal toBigDecimal(AtomicDouble number) {
return BigDecimal.valueOf(number.doubleValue());
} |
python | def parse(cls, query_str):
""" Parse string that represent query component from URI
:param query_str: string without '?'-sign
:return: WURIQuery
"""
parsed_query = parse_qs(query_str, keep_blank_values=True, strict_parsing=True)
result = cls()
for parameter_name in parsed_query.keys():
for parameter_v... |
python | def _sample_condition(exp_condition, frame_times, oversampling=50,
min_onset=-24):
"""Make a possibly oversampled event regressor from condition information.
Parameters
----------
exp_condition : arraylike of shape (3, n_events)
yields description of events for this conditi... |
python | def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False):
"""
Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n.
"""
cmd = ['ngram2mgram', '-n', n,
'-m', m]
if words and ascii_idngram:
... |
python | def _scroll_contents(self, adj):
"""Called when the scroll bars are adjusted by the user.
"""
if self._adjusting:
return True
try:
pos_x = self.hsb.get_value()
pos_y = self.vsb.get_value()
pct_x = pos_x / self.rng_x
# invert Y... |
java | private Shape decodeMarkInterior(int width, int height) {
int left = (width - 3) / 2 - 5;
int top = (height - 2) / 2 - 5;
path.reset();
path.moveTo(left + 1, top + 1);
path.lineTo(left + 4, top + 1);
path.lineTo(left + 5, top + 3);
path.lineTo(left + 7, top + 1)... |
python | def apply(self, mentions):
"""
Apply the Matcher to a **generator** of mentions.
Optionally only takes the longest match (NOTE: assumes this is the
*first* match)
"""
seen_spans = set()
for m in mentions:
if self.f(m) and (
not self.lon... |
python | def write_main(self):
'''
Writes out a huge string representing the main section of the python
compiled toil script.
Currently looks at and writes 5 sections:
1. JSON Variables (includes importing and preparing files as tuples)
2. TSV Variables (includes importing and pr... |
java | public String summarize()
{
return String.format(SUMMARY_FORMAT, action, responseContent,
accessToken, accessTokenExpiresAt, accessTokenDuration,
refreshToken, refreshTokenExpiresAt, refreshTokenDuration,
clientId, clientIdAlias, clientIdAliasUsed, subjec... |
java | public static void writeObject(CodedOutputStream out, int order, FieldType type, Object o, boolean list)
throws IOException {
if (o == null) {
return;
}
if (type == FieldType.OBJECT) {
Class cls = o.getClass();
Codec target = ProtobufProxy.create... |
java | public static int cudaMemcpyPeerAsync(Pointer dst, int dstDevice, Pointer src, int srcDevice, long count, cudaStream_t stream)
{
return checkResult(cudaMemcpyPeerAsyncNative(dst, dstDevice, src, srcDevice, count, stream));
} |
python | def _get_db_password(dbSystem,db,user):
"""Read through the users .dbrc file to get password for the db/user
combination suplied. If no password is found then prompt for one
"""
import string, getpass, os
dbrc = os.environ['HOME']+"/.dbrc"
password={}
if os.access(dbrc,os.R_OK):
fd=... |
python | def set_frameworkcontroller_config(experiment_config, port, config_file_name):
'''set kubeflow configuration'''
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_ur... |
python | def query_metric_tags(self, metric_type, metric_id):
"""
Returns a list of tags in the metric definition.
:param metric_type: MetricType to be matched (required)
:param metric_id: Exact string matching metric id
"""
definition = self._get(self._get_metrics_tags_url(self.... |
python | def subsets_changed(last_observed_subsets, subsets):
"""
>>> Kubernetes.subsets_changed([], [])
False
>>> Kubernetes.subsets_changed([], [k8s_client.V1EndpointSubset()])
True
>>> s1 = [k8s_client.V1EndpointSubset(addresses=[k8s_client.V1EndpointAddress(ip='1.2.3.4')])]
... |
python | def clean_prefix(self):
"""The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``."""
user = self.context.guild.me if self.context.guild else self.context.bot.user
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly... |
java | public static void put(HttpConsumer<HttpExchange> endpoint, MediaTypes... mediaTypes) {
addResource(Methods.PUT, HandlerUtil.BASE_PATH, endpoint, mediaTypes);
} |
java | @When("^I execute an elasticsearch query over index '(.*?)' and mapping '(.*?)' and column '(.*?)' with value '(.*?)' to '(.*?)'$")
public void elasticSearchQueryWithFilter(String indexName, String mappingName, String
columnName, String filterType, String value) {
try {
commonspec.se... |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSDouble br_cpu_usage_validator = new MPSDouble();
br_cpu_usage_validator.validate(operationType, br_cpu_usage, "\"br_cpu_usage\"");
MPSDouble br_memory_usage_validator = new MPSDouble();
br_memory_us... |
python | def load_multiple(paths=None, first_data_line="auto", filters="*.*", text="Select some files, FACEHEAD.", default_directory="default_directory", quiet=True, header_only=False, transpose=False, **kwargs):
"""
Loads a list of data files into a list of databox data objects.
Returns said list.
Paramete... |
java | public void realize(ApplicationContext wac, ConfigurableApplicationContext child) {
if (WebApplicationContextUtils.getWebApplicationContext(_context) == null) {
_context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
} else {
_logger.warning("Alr... |
python | def _register_order_book_channels(self):
"""
Registers the binding for the order_book channels.
:return:
"""
channels = {'order_book': self.btcusd_ob_callback,
'order_book_btceur': self.btceur_ob_callback,
'order_book_eurusd': self.eurusd_o... |
python | def cell_nodes_x(self):
"""The unstructured x-boundaries with shape (N, m) where m > 2"""
decoder = self.decoder
xcoord = self.xcoord
data = self.data
xbounds = decoder.get_cell_node_coord(
data, coords=data.coords, axis='x')
if self.plotter.convert_radian:
... |
python | def service_status(self, short_name):
"""Get the current status of a service.
Returns information about the service such as the length since the last
heartbeat, any status messages that have been posted about the service
and whether the heartbeat should be considered out of the ordinary... |
python | def nCr(n, r):
"""
Calculates nCr.
Args:
n (int): total number of items.
r (int): items to choose
Returns:
nCr.
"""
f = math.factorial
return int(f(n) / f(r) / f(n-r)) |
python | def to_string(self, ast_obj=None, fmt: str = "medium") -> str:
"""Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... |
java | @Override
public Object transform( Object input ) {
rootSpec.apply( ROOT_KEY, Optional.of( input ), new WalkedPath(), null, null );
return input;
} |
java | private void updateEntry(HashtableEntry entry)
throws IOException, EOFException, FileManagerException, ClassNotFoundException {
//
// We'll write the header, key, and data into a byte arry first,
// then allocate, seek, and write with a single write operation.
// It i... |
java | private Tree<Row> here( Element token ){
current.getContent().addToken( token );
return current;
} |
java | public final static void itosReverse(long i, int index, char[] buf) {
assert (i >= 0);
long q;
int r;
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));
... |
java | @Override
public ExecutionEntity createExecution(boolean initializeExecutionStartContext) {
// create the new child execution
ExecutionEntity createdExecution = createNewExecution();
// initialize sequence counter
createdExecution.setSequenceCounter(getSequenceCounter());
// manage the bidirecti... |
python | def update_aliases(
cr, registry, model_name, set_parent_thread_id,
alias_defaults=None, defaults_id_key=False):
"""
Update a model's aliases according to how they are configured
in the model's create() method.
:param model_name: The name of the model whose aliases are to be updated. \
... |
java | @Override
public boolean readBoolean() throws JMSException
{
backupState();
try
{
return getInput().readBoolean();
}
catch (EOFException e)
{
restoreState();
throw new MessageEOFException("End of body reached");
}
catch (... |
java | private boolean isCategorySystemService(Field field) {
if(!(field.getName().endsWith("_service")
|| field.getName().endsWith("_SERVICE"))) {
return false;
}
Field[] declaredFields = Context.class.getDeclaredFields();
for (Field declaredField : declaredFields) {
if(String.class.isAssig... |
python | def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the ps output.
Note that cmdline consumes every field up to the end of line
and as it is string, we can't perfectly see what the arguments
on the command line really were. We just assume a space is ... |
java | @Override
public Collection<ResourceBundle> bundles(Locale locale) {
Set<ResourceBundle> bundles = new LinkedHashSet<>();
for (I18nExtension extension : extensions) {
if (extension.locale().equals(locale)) {
bundles.add(extension.bundle());
}
}
... |
java | @Override
public Collection<RTMPConnection> removeConnections() {
ArrayList<RTMPConnection> list = new ArrayList<RTMPConnection>(connMap.size());
list.addAll(connMap.values());
connMap.clear();
conns.set(0);
return list;
} |
python | def on_touch_up(self, touch):
"""Delegate touch handling if possible, else select something."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
self._lasttouch = touch
touch.push()
touch.apply_transform_2d(self.to_local)
if hasattr(self, 'p... |
python | def wait_for(self, text, seconds):
"""
Returns True when the specified text has appeared in a line of the
output, or False when the specified number of seconds have passed
without that occurring.
"""
found = False
stream = self.stream
start_time = time.tim... |
python | def _parse_errorbars(self, label, err):
"""
Look for error keyword arguments and return the actual errorbar data
or return the error DataFrame/dict
Error bars can be specified in several ways:
Series: the user provides a pandas.Series object of the same
l... |
python | def get_symbol_ticker(self, **params):
"""Latest price for a symbol or symbols.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics
:param symbol:
:type symbol: str
:returns: API response
.. code-bl... |
python | def mergeidngram(output_file, input_files, n=3, ascii_input=False, ascii_output=False):
"""
Takes a set of id n-gram files (in either binary (by default) or ASCII (if specified) format - note that they should all be in the same format, however) and outputs a merged id N-gram.
Notes : This function ... |
python | def get_replacement_types(titles, reportnumbers, publishers):
"""Given the indices of the titles and reportnumbers that have been
recognised within a reference line, create a dictionary keyed by
the replacement position in the line, where the value for each
key is a string describing the type o... |
python | def render_link(self):
"""Render the page as a link."""
extra_context = {
'add_nofollow': settings.ADD_NOFOLLOW,
'page': self,
'querystring_key': self.querystring_key,
}
if self.is_current:
template_name = 'el_pagination/current_link.html'
... |
python | def create_client(access_token):
"""Create the dci client in the master realm."""
url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients'
r = requests.post(url,
data=json.dumps(client_data),
headers=get_auth_headers(access_token))
if r.status_code in (... |
python | def ensure_v8_src():
""" Ensure that v8 src are presents and up-to-date
"""
path = local_path('v8')
if not os.path.isdir(path):
fetch_v8(path)
else:
update_v8(path)
checkout_v8_version(local_path("v8/v8"), V8_VERSION)
dependencies_sync(path) |
python | def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
nginxInfo = NginxInfo(self._host, self._port,
self._user, self._password,
... |
python | def _get_intf_rb_id(rbridge_id):
""" Creates a new Netconf request based on the rbridge_id specifed
"""
intf_rb_id = ET.Element(
'get-ip-interface',
xmlns="urn:brocade.com:mgmt:brocade-interface-ext"
)
if rbridge_id is not None:
rbridge_el = E... |
python | def get_connection(self, command_name, *keys, **options):
"""
Get a connection, blocking for ``self.timeout`` until a connection
is available from the pool.
If the connection returned is ``None`` then creates a new connection.
Because we use a last-in first-out queue, the existi... |
python | def prop(self, name):
"""Search and get the value of an attribute associated to a
node This does the entity substitution. This function looks
in DTD attribute declaration for #FIXED or default
declaration values unless DTD use has been turned off.
NOTE: this function acts... |
python | def elapse_time(start, end=None, precision=3):
""" Simple time calculation utility. Given a start time, it will provide an elapse time.
"""
if end is None:
end = time_module.time()
return round(end-start, precision) |
java | public final EObject ruleGeneratedMetamodel() throws RecognitionException {
EObject current = null;
Token otherlv_0=null;
Token otherlv_2=null;
Token otherlv_3=null;
AntlrDatatypeRuleToken lv_name_1_0 = null;
AntlrDatatypeRuleToken lv_alias_4_0 = null;
enter... |
python | def _parse_w_comma_h(self, whstr, param):
"""Utility to parse "w,h" "w," or ",h" values.
Returns (w,h) where w,h are either None or ineteger. Will
throw a ValueError if there is a problem with one or both.
"""
try:
(wstr, hstr) = whstr.split(',', 2)
w = s... |
java | @Override
protected OpenedObject<T> generateOpenObject(T object) throws IOException
{
return new OpenedObject<>(
object,
new RetryingInputStream<>(object, openObjectFunction, retryCondition, getMaxFetchRetry()),
getNoopCloser()
);
} |
python | def setup_hydrocarbon_ff(graph):
"""Create a simple ForceField object for hydrocarbons based on the graph."""
# A) Define parameters.
# the bond parameters:
bond_params = {
(6, 1): 310*kcalmol/angstrom**2,
(6, 6): 220*kcalmol/angstrom**2,
}
# for every (a, b), also add (b, a)
... |
java | protected void markTime(final StringBuilder b, long t1, long t2) {
boolean time = getPhaseConfiguration().isTime();
if (time) {
String seconds = timeFormat((t2 - t1));
b.append("(");
b.append(seconds);
b.append(" seconds) ");
}
} |
python | def get_histories_fix_params(self, exp, rep, tag, **kwargs):
""" this function uses get_history(..) but returns all histories where the
subexperiments match the additional kwargs arguments. if alpha=1.0,
beta = 0.01 is given, then only those experiment histories are returned,
... |
python | def doc_sub(*sub):
"""
Decorator for performing substitutions in docstrings.
Using @doc_sub(some_note, other_note) on a function with {0} and {1} in the
docstring will substitute the contents of some_note and other_note for {0}
and {1}, respectively.
Decorator appears to work properly both wit... |
python | def stack_push(self, value: Union[int, bytes]) -> None:
"""
Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full.
"""
return self._stack.push(value) |
java | @Deprecated
private T build(Constructor<T> constructor, Object[] args) {
try {
return constructor.newInstance(args);
} catch (IllegalArgumentException | IllegalAccessException | InstantiationException ex) {
throw new IllegalArgumentException(
"Bean cannot... |
python | def determine_positions(nodes, edges):
"""
Construct the problem instance to solve the positions of contigs.
The input for spring_system() is A, K, L, which looks like the following.
A = np.array([[1, -1, 0], [0, 1, -1], [1, 0, -1]])
K = np.eye(3, dtype=int)
L = np.array([1, 2, 3])
For exa... |
python | def seek(self, offset, whence=0):
"""Move to a new offset either relative or absolute. whence=0 is
absolute, whence=1 is relative, whence=2 is relative to the end.
Any relative or absolute seek operation which would result in a
negative position is undefined and that case can be ignored... |
java | private <X extends YamlContainerNode> X putContainer(
YamlNode key, X value) {
put(key, value);
return value;
} |
java | public static TaskEntity createAndInsert(VariableScope execution) {
TaskEntity task = create();
if (execution instanceof ExecutionEntity) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
task.setExecution(executionEntity);
task.skipCustomListeners = executionEntity.isSkipCusto... |
java | public void setValue(double value) {
if(!expectingValue) {
throw new RuntimeException("Call to setValue() perfomed without prior getNextPoint() call (e.g. call performed twice).");
}
if (numberOfIterations < 3) {
/**
* Initially fill values
*/
values[numberOfIterations] = value;
if (numberOf... |
java | @Override
public double[] sample(long sampleSize) {
if (sampleSize <= 0) {
throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize);
}
// FIXME: int cast
double[] out = new double[(int) sampleSize];
for (int i = 0; i < sampleSize; i++... |
java | private void addPostParams(final Request request) {
if (target != null) {
request.addPostParam("Target", target.toString());
}
if (configurationUrl != null) {
request.addPostParam("Configuration.Url", configurationUrl);
}
if (configurationMethod != null)... |
python | def pubkey(self):
"""If the :py:obj:`PGPKey` object is a private key, this method returns a corresponding public key object with
all the trimmings. Otherwise, returns ``None``
"""
if not self.is_public:
if self._sibling is None or isinstance(self._sibling, weakref.ref):
... |
python | def _set_line_indent(src, line, indent):
'''
Indent the line with the source line.
'''
if not indent:
return line
idt = []
for c in src:
if c not in ['\t', ' ']:
break
idt.append(c)
return ''.join(idt) + line.lstrip() |
python | def set_hostname(hostname=None):
'''
Sets the hostname on the server.
.. versionadded:: 2019.2.0
Args:
hostname(str): The new hostname to set.
CLI Example:
.. code-block:: bash
salt '*' cimc.set_hostname foobar
'''
if not hostname:
raise salt.exceptions.Comm... |
python | def reconnect(self):
"""Reconnect the client after a disconnect. Can only be called after
connect()/connect_async()."""
if len(self._host) == 0:
raise ValueError('Invalid host.')
if self._port <= 0:
raise ValueError('Invalid port number.')
self._in_packet... |
java | private static Collection<? extends WMSLayer> parseLayers(Node element) {
final TileSystem tileSystem = org.osmdroid.views.MapView.getTileSystem();
List<WMSLayer> rets = new ArrayList<>();
WMSLayer ret = new WMSLayer();
Double north = null;
Double south = null;
Double ea... |
python | def stop(self):
""" Stop the primitive manager. """
for p in self.primitives[:]:
p.stop()
StoppableLoopThread.stop(self) |
java | public void setCustomKeyStores(java.util.Collection<CustomKeyStoresListEntry> customKeyStores) {
if (customKeyStores == null) {
this.customKeyStores = null;
return;
}
this.customKeyStores = new com.amazonaws.internal.SdkInternalList<CustomKeyStoresListEntry>(customKeySto... |
python | def filter_repeated(self):
'''
Determine whether a check is repeating.
'''
defaults = {
'occurrences': 1,
'interval': 30,
'refresh': 1800
}
# Override defaults with anything defined in the settings
if isinstance(self.settings['... |
python | def vectorize(fn):
"""
Allows a method to accept a list argument, but internally deal only
with a single item of that list.
"""
@functools.wraps(fn)
def vectorized_function(values, *vargs, **kwargs):
return [fn(value, *vargs, **kwargs) for value in values]
return vectorized_functio... |
java | public static boolean deregister( @Nonnull final Factory factory )
{
if ( g_factory != factory )
{
return false;
}
else
{
g_factory = null;
return true;
}
} |
python | def createNetwork(networkConfig):
"""
Create and initialize the specified network instance.
@param networkConfig: (dict) the configuration of this network.
@return network: (Network) The actual network
"""
registerAllResearchRegions()
network = Network()
if networkConfig["networkType"] == "L4L2Colum... |
java | private KubernetesCommand<?> getCommand(Message message, KubernetesEndpointConfiguration endpointConfiguration) {
Object payload = message.getPayload();
KubernetesCommand<?> command;
if (message instanceof KubernetesMessage) {
command = createCommandFromRequest(message.getPayload(Ku... |
python | def open_fake_page(self, page_text, url=None, soup_config=None):
"""Mock version of :func:`open`.
Behave as if opening a page whose text is ``page_text``, but do not
perform any network access. If ``url`` is set, pretend it is the page's
URL. Useful mainly for testing.
"""
... |
python | def syslog(server, enable=True, host=None,
admin_username=None, admin_password=None, module=None):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed b... |
python | def get_enabled_modules():
"""
<Purpose>
Returns all enabled modules.
<Arguments>
None
<Side Effects>
None
<Exceptions>
None
<Return>
The list of all enabled modules.
"""
enabled = []
directory_contents = os.listdir(MODULES_FOLDER_PATH)
for fname in get_installed_modules():
i... |
java | @Override
public synchronized RecordScan read(int scanId) throws DatabaseException {
try {
psRead.setInt(1, scanId);
try (ResultSet rs = psRead.executeQuery()) {
RecordScan result = build(rs);
return result;
}
} catch (SQLException e) {
throw new DatabaseException(e);
}
} |
python | def verifyInputs(self):
"""
Used in propagate() to verify that the network input
activations have been set.
"""
for layer in self.layers:
if (layer.verify and
layer.type == 'Input' and
layer.kind != 'Context' and
layer.a... |
java | public synchronized void forceTxRollover() {
if (async) {
try {
forceTxRolloverFlag = false;
indexCommandQueue.put(FORCE_TX_ROLLOVER);
while (!forceTxRolloverFlag) {
Thread.sleep(5);
}
} catch (Interrupte... |
java | public boolean isMatchingTopic(String topic) {
if (isFixedTopics()) {
return getFixedTopics().contains(topic);
} else {
return topicPattern.matcher(topic).matches();
}
} |
java | private AWSCredentials credentials(JsonNode credentialsJson) {
String accessKeyId = getText(credentialsJson, "AccessKeyId");
String secretAccessKey = getText(credentialsJson, "SecretAccessKey");
String sessionToken = getText(credentialsJson, "SessionToken");
ValidationUtils.assertString... |
python | def clear(self):
"""Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished
"""
try:
for peer in self._p... |
python | def copyfrom_file_object(self, query, file_object, compress=True,
compression_level=DEFAULT_COMPRESSION_LEVEL):
"""
Gets data from a readable file object into a table
:param query: The "COPY table_name [(column_name[, ...])]
FROM STDIN [WI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.