language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def _init_parameters_random(self, X_bin):
"""Initialise parameters for unsupervised learning.
"""
_, n_features = X_bin.shape
# The parameter class_log_prior_ has shape (2,). The values represent
# 'match' and 'non-match'.
rand_vals = np.random.rand(2)
class_prior = rand_vals / np.sum(rand_vals)
# make empty array of feature log probs
# dimensions 2xn_features
feature_prob = np.zeros((2, n_features))
feat_i = 0
for i, bin in enumerate(self._binarizers):
bin_len = bin.classes_.shape[0]
rand_vals_0 = np.random.rand(bin_len)
feature_prob[0, feat_i:feat_i + bin_len] = \
rand_vals_0 / np.sum(rand_vals_0)
rand_vals_1 = np.random.rand(bin_len)
feature_prob[1, feat_i:feat_i + bin_len] = \
rand_vals_1 / np.sum(rand_vals_1)
feat_i += bin_len
return np.log(class_prior), np.log(feature_prob) |
python | def maybe_show_tree(walker, ast):
"""
Show the ast based on the showast flag (or file object), writing to the
appropriate stream depending on the type of the flag.
:param show_tree: Flag which determines whether the parse tree is
written to sys.stdout or not. (It is also to pass a file
like object, into which the ast will be written).
:param ast: The ast to show.
"""
if walker.showast:
if hasattr(walker.showast, 'write'):
stream = walker.showast
else:
stream = sys.stdout
if walker.showast == 'Full':
walker.str_with_template(ast)
else:
stream.write(str(ast))
stream.write('\n') |
java | public static String toFullJobPath(final String jobName) {
final String[] parts = jobName.split("/");
if (parts.length == 1) return parts[0];
final StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE);
for (int i = 0; i < parts.length; i++) {
sb.append(parts[i]);
if (i != parts.length -1) sb.append("/job/");
}
return sb.toString();
} |
python | def queue_delete(self, queue, if_unused=False, if_empty=False):
"""Delete queue by name."""
return self.channel.queue_delete(queue, if_unused, if_empty) |
java | public static Intent createUriIntent(String intentAction, String intentUri) {
if (intentAction == null) {
intentAction = Intent.ACTION_VIEW;
}
return new Intent(intentAction, Uri.parse(intentUri))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
} |
python | def predict_mean_and_var(self, Fmu, Fvar, epsilon=None):
r"""
Given a Normal distribution for the latent function,
return the mean of Y
if
q(f) = N(Fmu, Fvar)
and this object represents
p(y|f)
then this method computes the predictive mean
\int\int y p(y|f)q(f) df dy
and the predictive variance
\int\int y^2 p(y|f)q(f) df dy - [ \int\int y p(y|f)q(f) df dy ]^2
Here, we implement a default Monte Carlo routine.
"""
integrand2 = lambda *X: self.conditional_variance(*X) + tf.square(self.conditional_mean(*X))
E_y, E_y2 = self._mc_quadrature([self.conditional_mean, integrand2],
Fmu, Fvar, epsilon=epsilon)
V_y = E_y2 - tf.square(E_y)
return E_y, V_y |
python | def get_balance(self, t: datetime):
"""
Returns account balance before specified datetime (excluding entries on the datetime).
:param t: datetime
:return: Decimal
"""
return sum_queryset(self.accountentry_set.all().filter(timestamp__lt=t)) |
python | def find_lexer_class_by_name(_alias):
"""Lookup a lexer class by alias.
Like `get_lexer_by_name`, but does not instantiate the class.
.. versionadded:: 2.2
"""
if not _alias:
raise ClassNotFound('no lexer for alias %r found' % _alias)
# lookup builtin lexers
for module_name, name, aliases, _, _ in itervalues(LEXERS):
if _alias.lower() in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cache[name]
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if _alias.lower() in cls.aliases:
return cls
raise ClassNotFound('no lexer for alias %r found' % _alias) |
python | def create_app(self):
"""Send a POST to spinnaker to create a new application with class variables.
Raises:
AssertionError: Application creation failed.
"""
self.appinfo['accounts'] = self.get_accounts()
self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
self.log.debug('App info:\n%s', pformat(self.appinfo))
jsondata = self.retrieve_template()
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
return jsondata |
java | public final hqlParser.bitwiseAndExpression_return bitwiseAndExpression() throws RecognitionException {
hqlParser.bitwiseAndExpression_return retval = new hqlParser.bitwiseAndExpression_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token BAND197=null;
ParserRuleReturnScope additiveExpression196 =null;
ParserRuleReturnScope additiveExpression198 =null;
CommonTree BAND197_tree=null;
try {
// hql.g:535:2: ( additiveExpression ( BAND ^ additiveExpression )* )
// hql.g:535:4: additiveExpression ( BAND ^ additiveExpression )*
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_additiveExpression_in_bitwiseAndExpression2401);
additiveExpression196=additiveExpression();
state._fsp--;
adaptor.addChild(root_0, additiveExpression196.getTree());
// hql.g:535:23: ( BAND ^ additiveExpression )*
loop69:
while (true) {
int alt69=2;
int LA69_0 = input.LA(1);
if ( (LA69_0==BAND) ) {
alt69=1;
}
switch (alt69) {
case 1 :
// hql.g:535:24: BAND ^ additiveExpression
{
BAND197=(Token)match(input,BAND,FOLLOW_BAND_in_bitwiseAndExpression2404);
BAND197_tree = (CommonTree)adaptor.create(BAND197);
root_0 = (CommonTree)adaptor.becomeRoot(BAND197_tree, root_0);
pushFollow(FOLLOW_additiveExpression_in_bitwiseAndExpression2407);
additiveExpression198=additiveExpression();
state._fsp--;
adaptor.addChild(root_0, additiveExpression198.getTree());
}
break;
default :
break loop69;
}
}
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
python | def execute(self, *args, **options):
"""
Executes whole process of parsing arguments, running command and
trying to catch errors.
"""
try:
self.handle(*args, **options)
except CommandError, e:
if options['debug']:
try:
import ipdb
ipdb.set_trace()
except ImportError:
import pdb
pdb.set_trace()
sys.stderr.write(colorize('ERROR: ', fg='red'))
self.stderr.write('%s\n' % e)
sys.exit(1)
except Exception, e:
if isinstance(e, IOError) and getattr(e, 'errno') == errno.EPIPE:
sys.exit(0)
if options['debug']:
try:
import ipdb
ipdb.set_trace()
except ImportError:
import pdb
pdb.set_trace()
if options.get('traceback'):
import traceback
self.stderr.write(u'\n'.join((
'=========',
'TRACEBACK',
'=========', '', '',
)))
traceback.print_exc(file=self.stderr)
sys.stderr.write(colorize('ERROR: ', fg='red'))
self.stderr.write('%s\n' % e)
sys.exit(1) |
java | public void setParent( IVarDef parent)
{
super.setParent( parent);
// Reset ancestry for all descendants.
if( members_ != null)
{
for( IVarDef member : members_)
{
member.setParent( this);
}
}
} |
python | def getNextContextStack(self, contextStack, data=None):
"""Apply modification to the contextStack.
This method never modifies input parameter list
"""
if self._popsCount:
contextStack = contextStack.pop(self._popsCount)
if self._contextToSwitch is not None:
if not self._contextToSwitch.dynamic:
data = None
contextStack = contextStack.append(self._contextToSwitch, data)
return contextStack |
python | def from_row_and_group(row: int, group: int):
"""
Returns an element from a row and group number.
Args:
row (int): Row number
group (int): Group number
.. note::
The 18 group number system is used, i.e., Noble gases are group 18.
"""
for sym in _pt_data.keys():
el = Element(sym)
if el.row == row and el.group == group:
return el
raise ValueError("No element with this row and group!") |
python | def token(self):
"""
:rtype: str
"""
if self._session_context is not None:
return self.session_context.token
elif self._installation_context is not None:
return self.installation_context.token
else:
return None |
python | def determine_types(self):
""" Determine ES type names from request data.
In particular `request.matchdict['collections']` is used to
determine types names. Its value is comma-separated sequence
of collection names under which views have been registered.
"""
from nefertari.elasticsearch import ES
collections = self.get_collections()
resources = self.get_resources(collections)
models = set([res.view.Model for res in resources])
es_models = [mdl for mdl in models if mdl
and getattr(mdl, '_index_enabled', False)]
types = [ES.src2type(mdl.__name__) for mdl in es_models]
return types |
python | def get_stp_mst_detail_output_msti_port_designated_port_id(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")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
python | def check_process_counts(self):
"""Check for the minimum consumer process levels and start up new
processes needed.
"""
LOGGER.debug('Checking minimum consumer process levels')
for name in self.consumers:
processes_needed = self.process_spawn_qty(name)
if processes_needed:
LOGGER.info('Need to spawn %i processes for %s',
processes_needed, name)
self.start_processes(name, processes_needed) |
python | def authors():
"""
Updates the AUTHORS file with a list of committers from GIT.
"""
fmt_re = re.compile(r'([^<]+) <([^>]+)>')
authors = local('git shortlog -s -e -n | cut -f 2-', capture=True)
with open('AUTHORS', 'w') as fh:
fh.write('Project contributors\n')
fh.write('====================\n\n')
for line in authors.splitlines():
match = fmt_re.match(line)
name, email = match.groups()
if email in env.ignored_authors:
continue
fh.write(' * ')
fh.write(line)
fh.write('\n') |
python | def platform_default():
"""Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture.
"""
osname = os.name
if osname == 'java':
osname = os._osType
if osname == 'posix':
if sys.platform == 'cygwin':
return 'cygwin'
elif sys.platform.find('irix') != -1:
return 'irix'
elif sys.platform.find('sunos') != -1:
return 'sunos'
elif sys.platform.find('hp-ux') != -1:
return 'hpux'
elif sys.platform.find('aix') != -1:
return 'aix'
elif sys.platform.find('darwin') != -1:
return 'darwin'
else:
return 'posix'
elif os.name == 'os2':
return 'os2'
else:
return sys.platform |
java | public static Object[] appendArray(Object[] arr, Object obj) {
Object[] newArr = new Object[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, arr.length);
newArr[arr.length] = obj;
return newArr;
} |
python | def check_config_integrity(self):
""" Make sure the scheduler config is valid """
tasks_by_hash = {_hash_task(t): t for t in self.config_tasks}
if len(tasks_by_hash) != len(self.config_tasks):
raise Exception("Fatal error: there was a hash duplicate in the scheduled tasks config.")
for h, task in tasks_by_hash.items():
if task.get("monthday") and not task.get("dailytime"):
raise Exception("Fatal error: you can't schedule a task with 'monthday' and without 'dailytime' (%s)" % h)
if task.get("weekday") and not task.get("dailytime"):
raise Exception("Fatal error: you can't schedule a task with 'weekday' and without 'dailytime' (%s)" % h)
if not task.get("monthday") and not task.get("weekday") and not task.get("dailytime") and not task.get("interval"):
raise Exception("Fatal error: scheduler must be specified one of monthday,weekday,dailytime,interval. (%s)" % h) |
python | def write_psd(self, psds, group=None):
"""Writes PSD for each IFO to file.
Parameters
-----------
psds : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the psd to. Default is ``data_group``.
"""
subgroup = self.data_group + "/{ifo}/psds/0"
if group is None:
group = subgroup
else:
group = '/'.join([group, subgroup])
for ifo in psds:
self[group.format(ifo=ifo)] = psds[ifo]
self[group.format(ifo=ifo)].attrs['delta_f'] = psds[ifo].delta_f |
python | def connect(self, funct):
"""Call funct when the text was changed.
Parameters
----------
funct : function
function that broadcasts a change.
Notes
-----
There is something wrong here. When you run this function, it calls
for opening a directory three or four times. This is obviously wrong
but I don't understand why this happens three times. Traceback did not
help.
"""
def get_directory():
rec = QFileDialog.getExistingDirectory(self,
'Path to Recording'
' Directory')
if rec == '':
return
self.setText(rec)
funct()
self.clicked.connect(get_directory) |
python | def reload(self, reload_timeout=300, save_config=True):
"""Reload the device and waits for device to boot up.
It posts the informational message to the log if not implemented by device driver.
"""
self.log("Reload not implemented on {} platform".format(self.platform)) |
java | @Override
public ZeroCopyFileWriter write(String event) {
// String realPath = FileHandlerUtil.generateOutputFilePath(path);
String realPath = FileHandlerUtil.generateOutputFilePath(
path,
FileHandlerUtil.generateAuditFileName());
try {
/** Close last instance for random access file. **/
if (randomAccessFile != null && !realPath.equals(lastRealPath)) {
this.stop();
}
if (randomAccessFile == null) {
lastRealPath = realPath;
randomAccessFile = new RandomAccessFile(new File(realPath), CoreConstants.READ_WRITE);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileChannel = randomAccessFile.getChannel();
String str2 = event + CoreConstants.NEW_LINE;
long numBytes = str2.getBytes().length;
InputStream inputStream = new ByteArrayInputStream(str2.getBytes(Charset.forName("UTF-8")));
try {
// move the cursor to the end of the file
randomAccessFile.seek(randomAccessFile.length());
// obtain the a file channel from the RandomAccessFile
try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream);) {
fileChannel.transferFrom(inputChannel, randomAccessFile.length(), numBytes);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return this;
} |
java | public PythonDataStream from_collection(Iterator<Object> iter) throws Exception {
return new PythonDataStream<>(env.addSource(new PythonIteratorFunction(iter), TypeExtractor.getForClass(Object.class))
.map(new AdapterMap<>()));
} |
java | public CountDownLatch routeChat() {
info("*** RouteChat");
final CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<RouteNote> requestObserver =
asyncStub.routeChat(new StreamObserver<RouteNote>() {
@Override
public void onNext(RouteNote note) {
info("Got message \"{0}\" at {1}, {2}", note.getMessage(), note.getLocation()
.getLatitude(), note.getLocation().getLongitude());
if (testHelper != null) {
testHelper.onMessage(note);
}
}
@Override
public void onError(Throwable t) {
warning("RouteChat Failed: {0}", Status.fromThrowable(t));
if (testHelper != null) {
testHelper.onRpcError(t);
}
finishLatch.countDown();
}
@Override
public void onCompleted() {
info("Finished RouteChat");
finishLatch.countDown();
}
});
try {
RouteNote[] requests =
{newNote("First message", 0, 0), newNote("Second message", 0, 1),
newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)};
for (RouteNote request : requests) {
info("Sending message \"{0}\" at {1}, {2}", request.getMessage(), request.getLocation()
.getLatitude(), request.getLocation().getLongitude());
requestObserver.onNext(request);
}
} catch (RuntimeException e) {
// Cancel RPC
requestObserver.onError(e);
throw e;
}
// Mark the end of requests
requestObserver.onCompleted();
// return the latch while receiving happens asynchronously
return finishLatch;
} |
java | public boolean accountSupportsFeatures(Collection<? extends CharSequence> features)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
EntityBareJid accountJid = connection().getUser().asEntityBareJid();
return supportsFeatures(accountJid, features);
} |
python | def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
server_id = self._servers.host_to_server_id(host)
server = self._servers._storage[server_id]
server.restart(timeout, config_callback)
self.waiting_member_state() |
python | def Union(self, t2, off):
"""Union initializes any Table-derived type to point to the union at
the given offset."""
assert type(t2) is Table
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
t2.Pos = off + self.Get(N.UOffsetTFlags, off)
t2.Bytes = self.Bytes |
python | def wb010(self, value=None):
""" Corresponds to IDD Field `wb010`
Wet-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `wb010`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
"""
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError('value {} need to be of type float '
'for field `wb010`'.format(value))
self._wb010 = value |
java | @Override
public List<CommerceSubscriptionEntry> findByG_U(long groupId, long userId) {
return findByG_U(groupId, userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
null);
} |
python | def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ
"""
List all the submissions that the connected user made. Returns list of the form
::
[
{
"id": "submission_id1",
"submitted_on": "date",
"status" : "done", #can be "done", "waiting", "error" (execution status of the task).
"grade": 0.0,
"input": {}, #the input data. File are base64 encoded.
"result" : "success" #only if status=done. Result of the execution.
"feedback": "" #only if status=done. the HTML global feedback for the task
"problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent.
{
"pid1": "feedback1",
#...
}
}
#...
]
If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid,
this dict will contain one entry or the page will return 404 Not Found.
"""
with_input = "input" in web.input()
return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app._translations, courseid, taskid, with_input, submissionid) |
java | public static void mergePdf(File[] inputPdfFiles, File outputPdfFile) {
//get Ghostscript instance
Ghostscript gs = Ghostscript.getInstance();
//prepare Ghostscript interpreter parameters
//refer to Ghostscript documentation for parameter usage
//gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -sOutputFile=out.pdf in1.pdf in2.pdf in3.pdf
List<String> gsArgs = new ArrayList<String>();
gsArgs.add("-gs");
gsArgs.add("-dNOPAUSE");
gsArgs.add("-dQUIET");
gsArgs.add("-dBATCH");
gsArgs.add("-sDEVICE=pdfwrite");
gsArgs.add("-sOutputFile=" + outputPdfFile.getPath());
for (File inputPdfFile : inputPdfFiles) {
gsArgs.add(inputPdfFile.getPath());
}
//execute and exit interpreter
try {
synchronized (gs) {
gs.initialize(gsArgs.toArray(new String[0]));
gs.exit();
}
} catch (UnsatisfiedLinkError e) {
logger.error(e.getMessage());
throw new RuntimeException(getMessage(e.getMessage()));
} catch (NoClassDefFoundError e) {
logger.error(e.getMessage());
throw new RuntimeException(getMessage(e.getMessage()));
} catch (GhostscriptException e) {
logger.error(e.getMessage());
throw new RuntimeException(e.getMessage());
} finally {
//delete interpreter instance (safer)
try {
Ghostscript.deleteInstance();
} catch (GhostscriptException e) {
//nothing
}
}
} |
java | public Tile tile (float x, float y, float width, float height) {
final float tileX = x, tileY = y, tileWidth = width, tileHeight = height;
return new Tile() {
@Override public Texture texture () { return Texture.this; }
@Override public float width () { return tileWidth; }
@Override public float height () { return tileHeight; }
@Override public float sx () { return tileX/displayWidth; }
@Override public float sy () { return tileY/displayHeight; }
@Override public float tx () { return (tileX+tileWidth)/displayHeight; }
@Override public float ty () { return (tileY+tileWidth)/displayHeight; }
@Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx,
float x, float y, float width, float height) {
batch.addQuad(texture(), tint, tx, x, y, width, height, tileX, tileY, tileWidth, tileHeight);
}
@Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx,
float dx, float dy, float dw, float dh,
float sx, float sy, float sw, float sh) {
batch.addQuad(texture(), tint, tx, dx, dy, dw, dh, tileX+sx, tileY+sy, sw, sh);
}
};
} |
java | @VisibleForTesting
static int getNextAvailablePort(InetAddress address, PortAllocator portAllocator) {
for (int i = 0; i < PORT_MAX_TRIES; i++) {
int port = portAllocator.getAvailable(address);
if (isValidPort(port)) {
PORTS_ALREADY_ALLOCATED.add(port);
return port;
}
}
throw new IllegalStateException("Fail to find an available port on " + address);
} |
python | def decorator(caller, func=None):
"""
decorator(caller) converts a caller function into a decorator;
decorator(caller, func) decorates a function using a caller.
"""
if func is None: # returns a decorator
fun = FunctionMaker(caller)
first_arg = inspect.getargspec(caller)[0][0]
src = 'def %s(%s): return _call_(caller, %s)' % (
caller.__name__, first_arg, first_arg)
return fun.make(src, dict(caller=caller, _call_=decorator),
undecorated=caller)
else: # returns a decorated function
fun = FunctionMaker(func)
src = """def %(name)s(%(signature)s):
return _call_(_func_, %(signature)s)"""
return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func) |
python | def create_example(self,
workspace_id,
intent,
text,
mentions=None,
**kwargs):
"""
Create user input example.
Add a new user input example to an intent.
This operation is limited to 1000 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
:param str intent: The intent name.
:param str text: The text of a user input example. This string must conform to the
following restrictions:
- It cannot contain carriage return, newline, or tab characters.
- It cannot consist of only whitespace characters.
- It must be no longer than 1024 characters.
:param list[Mention] mentions: An array of contextual entity mentions.
:param dict headers: A `dict` containing the request headers
:return: A `DetailedResponse` containing the result, headers and HTTP status code.
:rtype: DetailedResponse
"""
if workspace_id is None:
raise ValueError('workspace_id must be provided')
if intent is None:
raise ValueError('intent must be provided')
if text is None:
raise ValueError('text must be provided')
if mentions is not None:
mentions = [self._convert_model(x, Mention) for x in mentions]
headers = {}
if 'headers' in kwargs:
headers.update(kwargs.get('headers'))
sdk_headers = get_sdk_headers('conversation', 'V1', 'create_example')
headers.update(sdk_headers)
params = {'version': self.version}
data = {'text': text, 'mentions': mentions}
url = '/v1/workspaces/{0}/intents/{1}/examples'.format(
*self._encode_path_vars(workspace_id, intent))
response = self.request(
method='POST',
url=url,
headers=headers,
params=params,
json=data,
accept_json=True)
return response |
java | @Throws(IllegalNaNArgumentException.class)
public static double notNaN(final double value, @Nullable final String name) {
// most efficient check for NaN, see Double.isNaN(value))
if (value != value) {
throw new IllegalNaNArgumentException(name);
}
return value;
} |
java | public Response remove(Object object) {
assertNotEmpty(object, "object");
JsonObject jsonObject = getGson().toJsonTree(object).getAsJsonObject();
final String id = getAsString(jsonObject, "_id");
final String rev = getAsString(jsonObject, "_rev");
return remove(id, rev);
} |
java | public DeleteNotificationResponse deleteNotification(DeleteNotificationRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.DELETE, request, NOTIFICATION, request
.getName());
return invokeHttpClient(internalRequest, DeleteNotificationResponse.class);
} |
java | public OperationFuture<AlertPolicy> delete(AlertPolicy policyRef) {
client.deleteAlertPolicy(findByRef(policyRef).getId());
return new OperationFuture<>(
policyRef,
new NoWaitingJobFuture()
);
} |
python | def wrap_many(self, *args, strict=False):
"""Wraps different copies of this element inside all empty tags
listed in params or param's (non-empty) iterators.
Returns list of copies of this element wrapped inside args
or None if not succeeded, in the same order and same structure,
i.e. args = (Div(), (Div())) -> value = (A(...), (A(...)))
If on some args it must raise TagError, it will only if strict is True,
otherwise it will do nothing with them and return Nones on their positions"""
for arg in args:
is_elem = arg and isinstance(arg, DOMElement)
is_elem_iter = (
not is_elem and arg and isinstance(arg, Iterable) and isinstance(iter(arg).__next__(), DOMElement)
)
if not (is_elem or is_elem_iter):
raise WrongArgsError(
self,
"Argument {} is not DOMElement nor iterable of DOMElements".format(
arg
),
)
wcopies = []
failure = []
def wrap_next(tag, idx):
nonlocal wcopies, failure
next_copy = self.__copy__()
try:
return next_copy.wrap(tag)
except TagError:
failure.append(idx)
return next_copy
for arg_idx, arg in enumerate(args):
if isinstance(arg, DOMElement):
wcopies.append(wrap_next(arg, (arg_idx, -1)))
else:
iter_wcopies = []
for iter_idx, t in enumerate(arg):
iter_wcopies.append(wrap_next(t, (arg_idx, iter_idx)))
wcopies.append(type(arg)(iter_wcopies))
if failure and strict:
raise TagError(
self,
"Wrapping in a non empty Tag is forbidden, failed on arguments " +
", ".join(
list(
map(
lambda idx: str(idx[0])
if idx[1] == -1
else "[{1}] of {0}".format(*idx),
failure,
)
)
),
)
return wcopies |
java | public Observable<VpnClientIPsecParametersInner> setVpnclientIpsecParametersAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams) {
return setVpnclientIpsecParametersWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams).map(new Func1<ServiceResponse<VpnClientIPsecParametersInner>, VpnClientIPsecParametersInner>() {
@Override
public VpnClientIPsecParametersInner call(ServiceResponse<VpnClientIPsecParametersInner> response) {
return response.body();
}
});
} |
java | public void push (final T newVal)
{
final int index = (int) (m_aCurrentIndex.incrementAndGet () % m_nMaxSize);
m_aCircularArray[index].set (newVal);
} |
java | private void flushBuffer(ByteBuffer buffer, WritableByteChannel output) throws IOException {
buffer.flip();
output.write(buffer);
buffer.flip();
buffer.limit(buffer.capacity());
} |
java | @Override
protected void replaceEditor(JComponent oldEditor, JComponent newEditor) {
spinner.remove(oldEditor);
spinner.add(newEditor, "Editor");
if (oldEditor instanceof JSpinner.DefaultEditor) {
JTextField tf = ((JSpinner.DefaultEditor)oldEditor).getTextField();
if (tf != null) {
tf.removeFocusListener(editorFocusHandler);
}
}
if (newEditor instanceof JSpinner.DefaultEditor) {
JTextField tf = ((JSpinner.DefaultEditor)newEditor).getTextField();
if (tf != null) {
tf.addFocusListener(editorFocusHandler);
}
}
} |
java | @Override
public void paint(final RenderContext renderContext) {
boolean enabled = ConfigurationProperties.getWhitespaceFilter();
if (enabled && renderContext instanceof WebXmlRenderContext) {
PrintWriter writer = ((WebXmlRenderContext) renderContext).getWriter();
writer = new WhiteSpaceFilterPrintWriter(writer);
WebXmlRenderContext filteredContext = new WebXmlRenderContext(writer, UIContextHolder.
getCurrent().getLocale());
super.paint(filteredContext);
} else {
super.paint(renderContext);
}
} |
java | public <T> CompletableFuture<T> traceAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> trace(type, configuration), getExecutor());
} |
java | public <T> LazyCursorList<T> toLazyCursorList(Function<? super Cursor, T> singleRowTransform) {
return new LazyCursorList<>(this, singleRowTransform);
} |
python | def assert_regex(text, regex, msg_fmt="{msg}"):
"""Fail if text does not match the regular expression.
regex can be either a regular expression string or a compiled regular
expression object.
>>> assert_regex("Hello World!", r"llo.*rld!$")
>>> assert_regex("Hello World!", r"\\d")
Traceback (most recent call last):
...
AssertionError: 'Hello World!' does not match '\\\\d'
The following msg_fmt arguments are supported:
* msg - the default error message
* text - text that is matched
* pattern - regular expression pattern as string
"""
compiled = re.compile(regex)
if not compiled.search(text):
msg = "{!r} does not match {!r}".format(text, compiled.pattern)
fail(msg_fmt.format(msg=msg, text=text, pattern=compiled.pattern)) |
python | def etd_ms_dict2xmlfile(filename, metadata_dict):
"""Create an ETD MS XML file."""
try:
f = open(filename, 'w')
f.write(generate_etd_ms_xml(metadata_dict).encode("utf-8"))
f.close()
except:
raise MetadataGeneratorException(
'Failed to create an XML file. Filename: %s' % (filename)
) |
java | public Observable<Page<VirtualNetworkPeeringInner>> listAsync(final String resourceGroupName, final String virtualNetworkName) {
return listWithServiceResponseAsync(resourceGroupName, virtualNetworkName)
.map(new Func1<ServiceResponse<Page<VirtualNetworkPeeringInner>>, Page<VirtualNetworkPeeringInner>>() {
@Override
public Page<VirtualNetworkPeeringInner> call(ServiceResponse<Page<VirtualNetworkPeeringInner>> response) {
return response.body();
}
});
} |
python | def derive_resource_name(name):
"""A stable, human-readable name and identifier for a resource."""
if name.startswith("Anon"):
name = name[4:]
if name.endswith("Handler"):
name = name[:-7]
if name == "Maas":
name = "MAAS"
return name |
java | public static int floatToIntBits(float value) {
int result = floatToRawIntBits(value);
// Check for NaN based on values of bit fields, maximum
// exponent and nonzero significand.
if ( ((result & FloatConsts.EXP_BIT_MASK) ==
FloatConsts.EXP_BIT_MASK) &&
(result & FloatConsts.SIGNIF_BIT_MASK) != 0)
result = 0x7fc00000;
return result;
} |
python | def objname(self, obj=None):
""" Formats object names in a pretty fashion """
obj = obj or self.obj
_objname = self.pretty_objname(obj, color=None)
_objname = "'{}'".format(colorize(_objname, "blue"))
return _objname |
python | def update_title(self, title):
"""Renames the worksheet.
:param title: A new title.
:type title: str
"""
body = {
'requests': [{
'updateSheetProperties': {
'properties': {
'sheetId': self.id,
'title': title
},
'fields': 'title'
}
}]
}
response = self.spreadsheet.batch_update(body)
self._properties['title'] = title
return response |
java | public static <P extends Enum<P>> PointF optPointF(final JSONObject json, P e) {
return optPointF(json, e, null);
} |
python | def bit_flip_operators(p):
"""
Return the phase flip kraus operators
"""
k0 = np.sqrt(1 - p) * I
k1 = np.sqrt(p) * X
return k0, k1 |
python | def clone_surface(self, source_name, target_name, target_position=-1,
alpha=1.):
'''
Clone surface from existing layer to a new name, inserting new surface
at specified position.
By default, new surface is appended as the top surface layer.
Args
----
source_name (str) : Name of layer to clone.
target_name (str) : Name of new layer.
'''
source_surface = self.df_surfaces.surface.ix[source_name]
source_width = source_surface.get_width()
source_height = source_surface.get_height()
source_format = source_surface.get_format()
target_surface = cairo.ImageSurface(source_format, source_width,
source_height)
target_cairo_context = cairo.Context(target_surface)
target_cairo_context.set_source_surface(source_surface, 0, 0)
target_cairo_context.paint()
self.insert_surface(target_position, target_name, target_surface,
alpha) |
python | def password_attributes_min_length(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa")
min_length = ET.SubElement(password_attributes, "min-length")
min_length.text = kwargs.pop('min_length')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
java | public HBCIMsgStatus rawDoIt(Message message, boolean signit, boolean cryptit) {
HBCIMsgStatus msgStatus = new HBCIMsgStatus();
try {
message.complete();
log.debug("generating raw message " + message.getName());
passport.getCallback().status(HBCICallback.STATUS_MSG_CREATE, message.getName());
// liste der rewriter erzeugen
ArrayList<Rewrite> rewriters = getRewriters(passport.getProperties().get("kernel.rewriter"));
// alle rewriter durchlaufen und plaintextnachricht patchen
for (Rewrite rewriter1 : rewriters) {
message = rewriter1.outgoingClearText(message);
}
// wenn nachricht signiert werden soll
if (signit) {
message = signMessage(message, rewriters);
}
processMessage(message, msgStatus);
String messageName = message.getName();
// soll nachricht verschlüsselt werden?
if (cryptit) {
message = cryptMessage(message, rewriters);
}
sendMessage(message, messageName, msgStatus, rewriters);
} catch (Exception e) {
// TODO: hack to be able to "disable" HKEND response message analysis
// because some credit institutes are buggy regarding HKEND responses
String paramName = "client.errors.ignoreDialogEndErrors";
if (message.getName().startsWith("DialogEnd")) {
log.error(e.getMessage(), e);
log.warn("error while receiving DialogEnd response - " +
"but ignoring it because of special setting");
} else {
msgStatus.addException(e);
}
}
return msgStatus;
} |
python | def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT):
'''Gets the domains that have been registered with a nameserver or
nameservers'''
if not isinstance(nameservers, list):
uri = self._uris["whois_ns"].format(nameservers)
params = {'limit': limit, 'offset': offset, 'sortField': sort_field}
else:
uri = self._uris["whois_ns"].format('')
params = {'emailList' : ','.join(nameservers), 'limit': limit, 'offset': offset, 'sortField': sort_field}
resp_json = self.get_parse(uri, params=params)
return resp_json |
python | def get_memory_layout(device):
"""Returns an array which identifies the memory layout. Each entry
of the array will contain a dictionary with the following keys:
addr - Address of this memory segment
last_addr - Last address contained within the memory segment.
size - size of the segment, in bytes
num_pages - number of pages in the segment
page_size - size of each page, in bytes
"""
cfg = device[0]
intf = cfg[(0, 0)]
mem_layout_str = get_string(device, intf.iInterface)
mem_layout = mem_layout_str.split('/')
result = []
for mem_layout_index in range(1, len(mem_layout), 2):
addr = int(mem_layout[mem_layout_index], 0)
segments = mem_layout[mem_layout_index + 1].split(',')
seg_re = re.compile(r'(\d+)\*(\d+)(.)(.)')
for segment in segments:
seg_match = seg_re.match(segment)
num_pages = int(seg_match.groups()[0], 10)
page_size = int(seg_match.groups()[1], 10)
multiplier = seg_match.groups()[2]
if multiplier == 'K':
page_size *= 1024
if multiplier == 'M':
page_size *= 1024 * 1024
size = num_pages * page_size
last_addr = addr + size - 1
result.append(named((addr, last_addr, size, num_pages, page_size),
"addr last_addr size num_pages page_size"))
addr += size
return result |
python | def sort_args(args):
"""Put flags at the end"""
args = args.copy()
flags = [i for i in args if FLAGS_RE.match(i[1])]
for i in flags:
args.remove(i)
return args + flags |
java | public Client getClient() throws Exception {
ClientConfig config = new ClientConfig();
// turn off the timeout for debugging
config.setProcedureCallTimeout(0);
Client client = ClientFactory.createClient(config);
// track this client so it can be closed at shutdown
trackedClients.add(client);
client.createConnection("localhost");
return client;
} |
java | protected void addCustomBindings(final DocWorkUnit currentWorkUnit) {
final String tagFilterPrefix = getTagPrefix();
Arrays.stream(currentWorkUnit.getClassDoc().inlineTags())
.filter(t -> t.name().startsWith(tagFilterPrefix))
.forEach(t -> currentWorkUnit.setProperty(t.name().substring(tagFilterPrefix.length()), t.text()));
} |
java | public static HtmlTree HTML(String lang, Content head, Content body) {
HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body));
htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang));
return htmltree;
} |
java | public static <T> T fromJSON(String json, Class<T> classOfT) {
return gson.fromJson(json, classOfT);
} |
python | def _sample_point(self, sample=None):
""" Returns a dict that represents the sample point assigned to
the sample specified
Keys: obj, id, title, url
"""
samplepoint = sample.getSamplePoint() if sample else None
data = {}
if samplepoint:
data = {'obj': samplepoint,
'id': samplepoint.id,
'title': samplepoint.Title(),
'url': samplepoint.absolute_url()}
return data |
python | def sample(self, n=None, frac=None, replace=False, weights=None,
random_state=None, axis=None):
"""
Return a random sample of items from an axis of object.
You can use `random_state` for reproducibility.
Parameters
----------
n : int, optional
Number of items from axis to return. Cannot be used with `frac`.
Default = 1 if `frac` = None.
frac : float, optional
Fraction of axis items to return. Cannot be used with `n`.
replace : bool, default False
Sample with or without replacement.
weights : str or ndarray-like, optional
Default 'None' results in equal probability weighting.
If passed a Series, will align with target object on index. Index
values in weights not found in sampled object will be ignored and
index values in sampled object not in weights will be assigned
weights of zero.
If called on a DataFrame, will accept the name of a column
when axis = 0.
Unless weights are a Series, weights must be same length as axis
being sampled.
If weights do not sum to 1, they will be normalized to sum to 1.
Missing values in the weights column will be treated as zero.
Infinite values not allowed.
random_state : int or numpy.random.RandomState, optional
Seed for the random number generator (if int), or numpy RandomState
object.
axis : int or string, optional
Axis to sample. Accepts axis number or name. Default is stat axis
for given data type (0 for Series and DataFrames, 1 for Panels).
Returns
-------
Series or DataFrame
A new object of same type as caller containing `n` items randomly
sampled from the caller object.
See Also
--------
numpy.random.choice: Generates a random sample from a given 1-D numpy
array.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
... 'num_wings': [2, 0, 0, 0],
... 'num_specimen_seen': [10, 2, 1, 8]},
... index=['falcon', 'dog', 'spider', 'fish'])
>>> df
num_legs num_wings num_specimen_seen
falcon 2 2 10
dog 4 0 2
spider 8 0 1
fish 0 0 8
Extract 3 random elements from the ``Series`` ``df['num_legs']``:
Note that we use `random_state` to ensure the reproducibility of
the examples.
>>> df['num_legs'].sample(n=3, random_state=1)
fish 0
spider 8
falcon 2
Name: num_legs, dtype: int64
A random 50% sample of the ``DataFrame`` with replacement:
>>> df.sample(frac=0.5, replace=True, random_state=1)
num_legs num_wings num_specimen_seen
dog 4 0 2
fish 0 0 8
Using a DataFrame column as weights. Rows with larger value in the
`num_specimen_seen` column are more likely to be sampled.
>>> df.sample(n=2, weights='num_specimen_seen', random_state=1)
num_legs num_wings num_specimen_seen
falcon 2 2 10
fish 0 0 8
"""
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)
axis_length = self.shape[axis]
# Process random_state argument
rs = com.random_state(random_state)
# Check weights for compliance
if weights is not None:
# If a series, align with frame
if isinstance(weights, pd.Series):
weights = weights.reindex(self.axes[axis])
# Strings acceptable if a dataframe and axis = 0
if isinstance(weights, str):
if isinstance(self, pd.DataFrame):
if axis == 0:
try:
weights = self[weights]
except KeyError:
raise KeyError("String passed to weights not a "
"valid column")
else:
raise ValueError("Strings can only be passed to "
"weights when sampling from rows on "
"a DataFrame")
else:
raise ValueError("Strings cannot be passed as weights "
"when sampling from a Series or Panel.")
weights = pd.Series(weights, dtype='float64')
if len(weights) != axis_length:
raise ValueError("Weights and axis to be sampled must be of "
"same length")
if (weights == np.inf).any() or (weights == -np.inf).any():
raise ValueError("weight vector may not include `inf` values")
if (weights < 0).any():
raise ValueError("weight vector many not include negative "
"values")
# If has nan, set to zero.
weights = weights.fillna(0)
# Renormalize if don't sum to 1
if weights.sum() != 1:
if weights.sum() != 0:
weights = weights / weights.sum()
else:
raise ValueError("Invalid weights: weights sum to zero")
weights = weights.values
# If no frac or n, default to n=1.
if n is None and frac is None:
n = 1
elif n is not None and frac is None and n % 1 != 0:
raise ValueError("Only integers accepted as `n` values")
elif n is None and frac is not None:
n = int(round(frac * axis_length))
elif n is not None and frac is not None:
raise ValueError('Please enter a value for `frac` OR `n`, not '
'both')
# Check for negative sizes
if n < 0:
raise ValueError("A negative number of rows requested. Please "
"provide positive value.")
locs = rs.choice(axis_length, size=n, replace=replace, p=weights)
return self.take(locs, axis=axis, is_copy=False) |
java | public static Schema fieldSchema(Schema schema, PartitionStrategy strategy,
String name) {
if (strategy != null && Accessor.getDefault().hasPartitioner(strategy, name)) {
return partitionFieldSchema(Accessor.getDefault().getPartitioner(strategy, name),
schema);
}
Schema nested = fieldSchema(schema, name);
if (nested != null) {
return nested;
}
throw new IllegalArgumentException(
"Not a schema or partition field: " + name);
} |
java | public final Promise get(String key) {
byte[] binaryKey = key.getBytes(StandardCharsets.UTF_8);
if (client != null) {
return new Promise(client.get(binaryKey));
}
if (clusteredClient != null) {
return new Promise(clusteredClient.get(binaryKey));
}
return Promise.resolve();
} |
java | public Set<String> setEscapeJava(final Set<?> target) {
if (target == null) {
return null;
}
final Set<String> result = new LinkedHashSet<String>(target.size() + 2);
for (final Object element : target) {
result.add(escapeJava(element));
}
return result;
} |
java | @Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (DBG) Log.d(LOG_TAG, "runQueryOnBackgroundThread(" + constraint + ")");
String query = (constraint == null) ? "" : constraint.toString();
/**
* for in app search we show the progress spinner until the cursor is returned with
* the results.
*/
Cursor cursor = null;
if (mSearchView.getVisibility() != View.VISIBLE
|| mSearchView.getWindowVisibility() != View.VISIBLE) {
return null;
}
//mSearchView.getWindow().getDecorView().post(mStartSpinnerRunnable); // TODO:
try {
cursor = getSuggestions(query, QUERY_LIMIT);
// trigger fill window so the spinner stays up until the results are copied over and
// closer to being ready
if (cursor != null) {
cursor.getCount();
return cursor;
}
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Search suggestions query threw an exception.", e);
}
// If cursor is null or an exception was thrown, stop the spinner and return null.
// changeCursor doesn't get called if cursor is null
// mSearchView.getWindow().getDecorView().post(mStopSpinnerRunnable); // TODO:
return null;
} |
java | int getFirstChar(int category) {
RangeDescriptor rlRange;
int retVal = -1;
for (rlRange = fRangeList; rlRange!=null; rlRange=rlRange.fNext) {
if (rlRange.fNum == category) {
retVal = rlRange.fStartChar;
break;
}
}
return retVal;
} |
java | Rule XcomStaffbreak() {
return Sequence("staffbreak",
OneOrMore(WSP()).suppressNode(),
XcomNumber(), XcomUnit())
.label(XcomStaffbreak);
} |
python | def load_ui_type(uifile):
"""Pyside equivalent for the loadUiType function in PyQt.
From the PyQt4 documentation:
Load a Qt Designer .ui file and return a tuple of the generated form
class and the Qt base class. These can then be used to create any
number of instances of the user interface without having to parse the
.ui file more than once.
Note:
Pyside lacks the "loadUiType" command, so we have to convert the ui
file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
Args:
uifile (str): Absolute path to .ui file
Returns:
tuple: the generated form class, the Qt base class
"""
import pysideuic
import xml.etree.ElementTree as ElementTree
from cStringIO import StringIO
parsed = ElementTree.parse(uifile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uifile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec(pyc) in frame
# Fetch the base_class and form class based on their type in
# the xml from designer
form_class = frame['Ui_%s' % form_class]
base_class = eval('QtWidgets.%s' % widget_class)
return form_class, base_class |
java | @Nullable
private String getPastTenseVerbSuggestion(String word) {
if (word.endsWith("e")) {
// strip trailing "e"
String wordStem = word.substring(0, word.length()-1);
try {
String lemma = baseForThirdPersonSingularVerb(wordStem);
if (lemma != null) {
AnalyzedToken token = new AnalyzedToken(lemma, null, lemma);
String[] forms = synthesizer.synthesize(token, "VER:3:SIN:PRT:.*", true);
if (forms.length > 0) {
return forms[0];
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
} |
python | def get_stp_mst_detail_output_cist_port_edge_delay(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")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
java | protected void doUpdate(final ItemData item, final WorkspaceStorageConnection con, ChangedSizeHandler sizeHandler)
throws RepositoryException, InvalidItemStateException
{
if (item.isNode())
{
con.update((NodeData)item);
}
else
{
con.update((PropertyData)item, sizeHandler);
}
} |
python | def setCurrentIndex(self, y, x):
"""Set current selection."""
self.dataTable.selectionModel().setCurrentIndex(
self.dataTable.model().index(y, x),
QItemSelectionModel.ClearAndSelect) |
python | def wheel(self, direction, steps):
""" Clicks the wheel the specified number of steps in the given direction.
Use Mouse.WHEEL_DOWN, Mouse.WHEEL_UP
"""
self._lock.acquire()
if direction == 1:
wheel_moved = steps
elif direction == 0:
wheel_moved = -1*steps
else:
raise ValueError("Expected direction to be 1 or 0")
self._lock.release()
return mouse.wheel(wheel_moved) |
java | public static OMMapManager getInstance() {
if (instanceRef.get() == null) {
synchronized (instanceRef) {
if (instanceRef.compareAndSet(null, createInstance())) {
instanceRef.get().init();
}
}
}
return instanceRef.get();
} |
java | @Override
public void recycle() {
for (int i = first; i != last; i = next(i)) {
bufs[i].recycle();
}
first = last = 0;
} |
java | private static final String coerceToString(final Object obj) {
if (obj == null) {
return "";
} else if (obj instanceof String) {
return (String) obj;
} else if (obj instanceof Enum<?>) {
return ((Enum<?>) obj).name();
} else {
return obj.toString();
}
} |
java | public static <E> Iterator<E> takeWhile(Iterable<E> iterable, Predicate<E> predicate) {
dbc.precondition(iterable != null, "cannot takeWhile from a null iterable");
return new TakeWhileIterator<E>(iterable.iterator(), predicate);
} |
python | def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s (%s)',
level_map_int[self.default_level], self.default_level)
for i, handler in enumerate(self.handlers):
fmtr = handler.formatter
debug(' + Handler: %s %r', i, handler)
debug(' + Formatter: %r', fmtr)
debug(' .datefmt: %r', fmtr.datefmt)
debug(' .msgfmt: %r', fmtr._fmt)
debug(' fmt_style: %r', fmtr._style)
try:
debug(' theme styles: %r', fmtr._theme_style)
debug(' theme icons:\n%r', fmtr._theme_icons)
debug(' lexer: %r\n', fmtr._lexer)
except AttributeError:
pass |
java | public int read(byte[] b, int off, int len) throws IOException {
// Sanity checks
ensureOpen();
if (b == null) {
throw new NullPointerException("Null buffer for read");
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
// Read and compress (deflate) input data bytes
int cnt = 0;
while (len > 0 && !def.finished()) {
int n;
// Read data from the input stream
if (def.needsInput()) {
n = in.read(buf, 0, buf.length);
if (n < 0) {
// End of the input stream reached
def.finish();
} else if (n > 0) {
def.setInput(buf, 0, n);
}
}
// Compress the input data, filling the read buffer
n = def.deflate(b, off, len);
cnt += n;
off += n;
len -= n;
}
// Android-changed: set reachEOF eagerly (not just when the number of bytes is zero).
// so that available is more accurate.
if (def.finished()) {
reachEOF =true;
if (cnt == 0) {
cnt = -1;
}
}
return cnt;
} |
python | def decode_chain_list(in_bytes):
"""Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the input bytes
:return the decoded list of strings"""
tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN
out_strings = []
for i in range(tot_strings):
out_s = in_bytes[i * mmtf.utils.constants.CHAIN_LEN:i * mmtf.utils.constants.CHAIN_LEN + mmtf.utils.constants.CHAIN_LEN]
out_strings.append(out_s.decode("ascii").strip(mmtf.utils.constants.NULL_BYTE))
return out_strings |
java | public static EquivalenceClasser<List<String>, String> typedDependencyClasser() {
return new EquivalenceClasser<List<String>, String>() {
public String equivalenceClass(List<String> s) {
if(s.get(5).equals(leftHeaded))
return s.get(2) + '(' + s.get(3) + "->" + s.get(4) + ')';
return s.get(2) + '(' + s.get(4) + "<-" + s.get(3) + ')';
}
};
} |
python | def get_option_pool(self, id_option_pool):
"""Search Option Pool by id.
:param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero.
:return: Following dictionary:
::
{‘id’: < id_option_pool >,
‘type’: < tipo_opcao >,
‘name’: < nome_opcao_txt >}
:raise InvalidParameterError: Option Pool identifier is null and invalid.
:raise optionpoolNotFoundError: Option Pool not registered.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_option_pool):
raise InvalidParameterError(
u'The identifier of Option Pool is invalid or was not informed.')
url = 'api/pools/options/' + str(id_option_pool) + '/'
return self.get(url) |
python | def get_category_lists(init_kwargs=None, additional_parents_aliases=None, obj=None):
"""Returns a list of CategoryList objects, optionally associated with
a given model instance.
:param dict|None init_kwargs:
:param list|None additional_parents_aliases:
:param Model|None obj: Model instance to get categories for
:rtype: list
:return:
"""
init_kwargs = init_kwargs or {}
additional_parents_aliases = additional_parents_aliases or []
parent_aliases = additional_parents_aliases
if obj is not None:
ctype = ContentType.objects.get_for_model(obj)
cat_ids = [
item[0] for item in
get_tie_model().objects.filter(content_type=ctype, object_id=obj.id).values_list('category_id').all()
]
parent_aliases = list(get_cache().get_parents_for(cat_ids).union(additional_parents_aliases))
lists = []
aliases = get_cache().sort_aliases(parent_aliases)
categories_cache = get_cache().get_categories(aliases, obj)
for parent_alias in aliases:
catlist = CategoryList(parent_alias, **init_kwargs) # TODO Burned in class name. Make more customizable.
if obj is not None:
catlist.set_obj(obj)
# Optimization. To get DB hits down.
cache = []
try:
cache = categories_cache[parent_alias]
except KeyError:
pass
catlist.set_get_categories_cache(cache)
lists.append(catlist)
return lists |
java | @Trivial
private static final String createSessionAttributeKey(String sessionId, String attributeId) {
return new StringBuilder(sessionId.length() + 1 + attributeId.length())
.append(sessionId)
.append('.')
.append(attributeId)
.toString();
} |
java | private void allClustersEqual(final List<String> clusterUrls) {
Validate.notEmpty(clusterUrls, "clusterUrls cannot be null");
// If only one clusterUrl return immediately
if (clusterUrls.size() == 1)
return;
AdminClient adminClientLhs = adminClientPerCluster.get(clusterUrls.get(0));
Cluster clusterLhs = adminClientLhs.getAdminClientCluster();
for (int index = 1; index < clusterUrls.size(); index++) {
AdminClient adminClientRhs = adminClientPerCluster.get(clusterUrls.get(index));
Cluster clusterRhs = adminClientRhs.getAdminClientCluster();
if (!areTwoClustersEqual(clusterLhs, clusterRhs))
throw new VoldemortException("Cluster " + clusterLhs.getName()
+ " is not the same as " + clusterRhs.getName());
}
} |
python | def bed(args):
"""
%prog bed xmlfile
Print summary of optical map alignment in BED format.
"""
from jcvi.formats.bed import sort
p = OptionParser(bed.__doc__)
p.add_option("--blockonly", default=False, action="store_true",
help="Only print out large blocks, not fragments [default: %default]")
p.add_option("--point", default=False, action="store_true",
help="Print accesssion as single point instead of interval")
p.add_option("--scale", type="float",
help="Scale the OM distance by factor")
p.add_option("--switch", default=False, action="store_true",
help="Switch reference and aligned map elements [default: %default]")
p.add_option("--nosort", default=False, action="store_true",
help="Do not sort bed [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
xmlfile, = args
bedfile = xmlfile.rsplit(".", 1)[0] + ".bed"
om = OpticalMap(xmlfile)
om.write_bed(bedfile, point=opts.point, scale=opts.scale,
blockonly=opts.blockonly, switch=opts.switch)
if not opts.nosort:
sort([bedfile, "--inplace"]) |
java | private CmsResource getResource(CmsObject cms, String resourcename, CmsResourceFilter filter) throws CmsException {
// the path without trailing slash
String path = CmsResource.getParentFolder(resourcename);
if (path == null) {
return null;
}
// the parent path
String parent = CmsResource.getParentFolder(path);
// the name of the resource
String name = CmsResource.getName(resourcename);
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
// read the resource for the property dir
if (name.equals(PROPERTY_DIR)) {
return cms.readResource(path, filter);
}
if ((path.endsWith(PROPERTY_DIR + "/")) && (name.endsWith(CmsResourceWrapperUtils.EXTENSION_PROPERTIES))) {
CmsResource res = null;
if (name.startsWith(FOLDER_PREFIX)) {
name = name.substring(2);
}
try {
String resPath = CmsResourceWrapperUtils.removeFileExtension(
cms,
parent + name,
CmsResourceWrapperUtils.EXTENSION_PROPERTIES);
res = cms.readResource(resPath, filter);
} catch (CmsException ex) {
// noop
}
return res;
}
return null;
} |
java | public void load(InputStream input) throws IOException {
ParameterReader reader = null;
try {
reader = new ParameterReader(new InputStreamReader(input, CmsEncoder.ENCODING_ISO_8859_1));
} catch (UnsupportedEncodingException ex) {
reader = new ParameterReader(new InputStreamReader(input));
}
while (true) {
String line = reader.readParameter();
if (line == null) {
return; // EOF
}
int equalSign = line.indexOf('=');
if (equalSign > 0) {
String key = line.substring(0, equalSign).trim();
String value = line.substring(equalSign + 1).trim();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
continue;
}
add(key, value, true);
}
}
} |
java | public void cookieMatches(double seconds, String cookieName, String expectedCookiePattern) {
double end = System.currentTimeMillis() + (seconds * 1000);
while (app.is().cookiePresent(cookieName) && System.currentTimeMillis() < end) ;
if (app.is().cookiePresent(cookieName)) {
while (!app.get().cookieValue(cookieName).matches(expectedCookiePattern) && System.currentTimeMillis() < end) ;
}
double timeTook = Math.min((seconds * 1000) - (end - System.currentTimeMillis()), seconds * 1000) / 1000;
checkCookieMatches(cookieName, expectedCookiePattern, seconds, timeTook);
} |