language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | @Override
public GetGeoMatchSetResult getGeoMatchSet(GetGeoMatchSetRequest request) {
request = beforeClientExecution(request);
return executeGetGeoMatchSet(request);
} |
java | public Float loadPreferenceAsFloat(String key, Float defaultValue) {
Float value = defaultValue;
if (hasPreference(key)) {
value = getSharedPreferences().getFloat(key, 0);
}
logLoad(key, value);
return value;
} |
java | public static CachedInstanceQuery get4Request(final Type _type)
throws EFapsException
{
return new CachedInstanceQuery(Context.getThreadContext().getRequestId(), _type).setLifespan(5)
.setLifespanUnit(TimeUnit.MINUTES);
} |
python | def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get country name from ISO3 code
Args:
iso3 (str): ISO3 code for which to get country name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.
Returns:
Optional[str]: Country name
"""
countryinfo = cls.get_country_info_from_iso3(iso3, use_live=use_live, exception=exception)
if countryinfo is not None:
return countryinfo.get('#country+name+preferred')
return None |
python | def check_in_out_dates(self):
"""
When date_order is less then check-in date or
Checkout date should be greater than the check-in date.
"""
if self.checkout and self.checkin:
if self.checkin < self.date_order:
raise ValidationError(_('Check-in date should be greater than \
the current date.'))
if self.checkout < self.checkin:
raise ValidationError(_('Check-out date should be greater \
than Check-in date.')) |
java | private void countPropertyQualifier(PropertyIdValue property, int count) {
PropertyRecord propertyRecord = getPropertyRecord(property);
propertyRecord.qualifierCount = propertyRecord.qualifierCount + count;
} |
java | public void beginStep(int step, String stepTitle, Logging logger) {
setProcessed(step - 1);
this.stepTitle = stepTitle;
logger.progress(this);
} |
java | private SecureRandom createSecureRandom() {
SecureRandom result;
try {
result = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
result = new SecureRandom();
}
// Force seeding to take place.
result.nextInt();
return result;
} |
python | def end(self):
"""Finalise lz4 frame, outputting any remaining as return from this function or by writing to fp)"""
with self.__lock:
if self.__write:
self.__write(compress_end(self.__ctx))
else:
return compress_end(self.__ctx) |
java | private void generateStaticInjection(TypeElement type, List<Element> fields) throws IOException {
ClassName typeName = ClassName.get(type);
ClassName adapterClassName = adapterName(ClassName.get(type), STATIC_INJECTION_SUFFIX);
TypeSpec.Builder result = TypeSpec.classBuilder(adapterClassName.simpleName())
.addOriginatingElement(type)
.addJavadoc(AdapterJavadocs.STATIC_INJECTION_TYPE, type)
.addModifiers(PUBLIC, FINAL)
.superclass(StaticInjection.class);
for (Element field : fields) {
result.addField(memberBindingField(false, field));
}
result.addMethod(attachMethod(null, fields, false, typeName, null, true));
result.addMethod(staticInjectMethod(fields, typeName));
String packageName = getPackage(type).getQualifiedName().toString();
JavaFile javaFile = JavaFile.builder(packageName, result.build())
.addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER)
.build();
javaFile.writeTo(processingEnv.getFiler());
} |
java | public void register(Class<?> aClass) {
List<ConstantField> tmp = inspector.getConstants(aClass);
constantList.addAll(tmp);
for (ConstantField constant : tmp)
constants.put(constant.name, constant);
} |
java | public PropertyBuilder booleanType(final String name) {
name(name);
type(Property.Type.Boolean);
return this;
} |
python | def partial_fit(self, X, y, classes=None):
"""
Runs a single epoch using the provided data
:return: This instance
"""
return self.fit(X, y, epochs=1) |
java | public void removeOverride(String operation) {
if (this.overrideOnce.containsKey(operation) == true) {
this.overrideOnce.remove(operation);
}
if (this.override.containsKey(operation) == true) {
this.override.remove(operation);
}
} |
python | def joint(letters, marks):
""" joint the letters with the marks
the length ot letters and marks must be equal
return word
@param letters: the word letters
@type letters: unicode
@param marks: the word marks
@type marks: unicode
@return: word
@rtype: unicode
"""
# The length ot letters and marks must be equal
if len(letters) != len(marks):
return ""
stack_letter = stack.Stack(letters)
stack_letter.items.reverse()
stack_mark = stack.Stack(marks)
stack_mark.items.reverse()
word_stack = stack.Stack()
last_letter = stack_letter.pop()
last_mark = stack_mark.pop()
vowels = HARAKAT
while last_letter != None and last_mark != None:
if last_letter == SHADDA:
top = word_stack.pop()
if top not in vowels:
word_stack.push(top)
word_stack.push(last_letter)
if last_mark != NOT_DEF_HARAKA:
word_stack.push(last_mark)
else:
word_stack.push(last_letter)
if last_mark != NOT_DEF_HARAKA:
word_stack.push(last_mark)
last_letter = stack_letter.pop()
last_mark = stack_mark.pop()
if not (stack_letter.is_empty() and stack_mark.is_empty()):
return False
else:
return ''.join(word_stack.items) |
python | def patch_lustre_path(f_path):
"""Patch any 60-character pathnames, to avoid a current Lustre bug."""
if CHECK_LUSTRE_PATH_LEN and len(f_path) == 60:
if os.path.isabs(f_path):
f_path = '/.' + f_path
else:
f_path = './' + f_path
return f_path |
java | private void createInstanceUsingConstructor() throws InvocationTargetException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "createInstanceUsingConstructor");
try {
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "calling Constructor.newInstance");
Constructor<?> con = home.beanMetaData.getEnterpriseBeanClassConstructor();
setEnterpriseBean(con.newInstance());
} catch (InvocationTargetException e) {
FFDCFilter.processException(e, CLASS_NAME + ".createInstanceUsingConstructor", "360", this);
throw e;
} catch (Exception e) {
// Reflection exceptions are unexpected.
FFDCFilter.processException(e, CLASS_NAME + ".createInstanceUsingConstructor", "364", this);
throw new EJBException(home.beanMetaData.enterpriseBeanClassName, e);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "createInstanceUsingConstructor");
} |
java | public void execNoOutput() throws Failure {
String result;
result = exec();
if (result.trim().length() > 0) {
throw new Failure(this, builder.command().get(0) + ": unexpected output " + result);
}
} |
java | public boolean revert() {
try {
setWrongValueMessage(null);
setValue(propInfo.getPropertyValue(target));
updateValue();
return true;
} catch (Exception e) {
setWrongValueException(e);
return false;
}
} |
python | def md5(self):
"""
An MD5 hash of the current vertices and entities.
Returns
------------
md5: str, two appended MD5 hashes
"""
# first MD5 the points in every entity
target = '{}{}'.format(
util.md5_object(bytes().join(e._bytes()
for e in self.entities)),
self.vertices.md5())
return target |
python | def system(session, py):
"""Run the system test suite."""
# Sanity check: Only run system tests if the environment variable is set.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
session.skip('Credentials must be set via environment variable.')
# Run the system tests against latest Python 2 and Python 3 only.
session.interpreter = 'python{}'.format(py)
# Set the virtualenv dirname.
session.virtualenv_dirname = 'sys-' + py
# Install all test dependencies.
session.install('-r', 'requirements-test.txt')
# Install dev packages into the virtualenv's dist-packages.
_install_dev_packages(session)
# Run py.test against the system tests.
session.run(
'py.test',
'-s',
'tests/system/',
*session.posargs
) |
java | public void addTermReferences(TableDefinition tableDef, int shardNumber,
Map<String, Set<String>> fieldTermsRefMap) {
StringBuilder rowKey = new StringBuilder();
for (String fieldName : fieldTermsRefMap.keySet()) {
for (String term : fieldTermsRefMap.get(fieldName)) {
rowKey.setLength(0);
if (shardNumber > 0) {
rowKey.append(shardNumber);
rowKey.append("/");
}
rowKey.append(TERMS_REGISTRY_ROW_PREFIX);
rowKey.append("/");
rowKey.append(fieldName);
addColumn(SpiderService.termsStoreName(tableDef), rowKey.toString(), term);
}
}
} |
python | def salsa20_8(B, x, src, s_start, dest, d_start):
"""Salsa20/8 http://en.wikipedia.org/wiki/Salsa20"""
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in xrange(4):
a = (x[0]+x[12]) & 0xffffffff
b = (x[5]+x[1]) & 0xffffffff
x[4] ^= (a << 7) | (a >> 25)
x[9] ^= (b << 7) | (b >> 25)
a = (x[10]+x[6]) & 0xffffffff
b = (x[15]+x[11]) & 0xffffffff
x[14] ^= (a << 7) | (a >> 25)
x[3] ^= (b << 7) | (b >> 25)
a = (x[4]+x[0]) & 0xffffffff
b = (x[9]+x[5]) & 0xffffffff
x[8] ^= (a << 9) | (a >> 23)
x[13] ^= (b << 9) | (b >> 23)
a = (x[14]+x[10]) & 0xffffffff
b = (x[3]+x[15]) & 0xffffffff
x[2] ^= (a << 9) | (a >> 23)
x[7] ^= (b << 9) | (b >> 23)
a = (x[8]+x[4]) & 0xffffffff
b = (x[13]+x[9]) & 0xffffffff
x[12] ^= (a << 13) | (a >> 19)
x[1] ^= (b << 13) | (b >> 19)
a = (x[2]+x[14]) & 0xffffffff
b = (x[7]+x[3]) & 0xffffffff
x[6] ^= (a << 13) | (a >> 19)
x[11] ^= (b << 13) | (b >> 19)
a = (x[12]+x[8]) & 0xffffffff
b = (x[1]+x[13]) & 0xffffffff
x[0] ^= (a << 18) | (a >> 14)
x[5] ^= (b << 18) | (b >> 14)
a = (x[6]+x[2]) & 0xffffffff
b = (x[11]+x[7]) & 0xffffffff
x[10] ^= (a << 18) | (a >> 14)
x[15] ^= (b << 18) | (b >> 14)
a = (x[0]+x[3]) & 0xffffffff
b = (x[5]+x[4]) & 0xffffffff
x[1] ^= (a << 7) | (a >> 25)
x[6] ^= (b << 7) | (b >> 25)
a = (x[10]+x[9]) & 0xffffffff
b = (x[15]+x[14]) & 0xffffffff
x[11] ^= (a << 7) | (a >> 25)
x[12] ^= (b << 7) | (b >> 25)
a = (x[1]+x[0]) & 0xffffffff
b = (x[6]+x[5]) & 0xffffffff
x[2] ^= (a << 9) | (a >> 23)
x[7] ^= (b << 9) | (b >> 23)
a = (x[11]+x[10]) & 0xffffffff
b = (x[12]+x[15]) & 0xffffffff
x[8] ^= (a << 9) | (a >> 23)
x[13] ^= (b << 9) | (b >> 23)
a = (x[2]+x[1]) & 0xffffffff
b = (x[7]+x[6]) & 0xffffffff
x[3] ^= (a << 13) | (a >> 19)
x[4] ^= (b << 13) | (b >> 19)
a = (x[8]+x[11]) & 0xffffffff
b = (x[13]+x[12]) & 0xffffffff
x[9] ^= (a << 13) | (a >> 19)
x[14] ^= (b << 13) | (b >> 19)
a = (x[3]+x[2]) & 0xffffffff
b = (x[4]+x[7]) & 0xffffffff
x[0] ^= (a << 18) | (a >> 14)
x[5] ^= (b << 18) | (b >> 14)
a = (x[9]+x[8]) & 0xffffffff
b = (x[14]+x[13]) & 0xffffffff
x[10] ^= (a << 18) | (a >> 14)
x[15] ^= (b << 18) | (b >> 14)
# While we are handling the data, write it to the correct dest.
# The latter half is still part of salsa20
for i in xrange(16):
dest[d_start + i] = B[i] = (x[i] + B[i]) & 0xffffffff |
java | public static aaagroup_vpntrafficpolicy_binding[] get(nitro_service service, String groupname) throws Exception{
aaagroup_vpntrafficpolicy_binding obj = new aaagroup_vpntrafficpolicy_binding();
obj.set_groupname(groupname);
aaagroup_vpntrafficpolicy_binding response[] = (aaagroup_vpntrafficpolicy_binding[]) obj.get_resources(service);
return response;
} |
java | public <U> BaseSimpleReactStream<U> from(final IntStream stream) {
return (BaseSimpleReactStream<U>) from(stream.boxed());
} |
java | public static Transport UDPInstance(SocketAddress addr) throws IOException {
DatagramSocket sock = new DatagramSocket();
sock.setSoTimeout(getTimeout());
sock.connect(addr);
StreamTransport trans = new StreamTransport();
trans.setStreams(new UDPInputStream(sock), new UDPOutputStream(sock));
trans.setAddressLabel(addr.toString());
return trans;
} |
java | private View getNextView(RecyclerView parent) {
View firstView = parent.getChildAt(0);
// draw the first visible child's header at the top of the view
int firstPosition = parent.getChildPosition(firstView);
View firstHeader = getHeaderView(parent, firstPosition);
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
if (child.getTop() - layoutParams.topMargin > firstHeader.getHeight()) {
return child;
}
} else {
if (child.getLeft() - layoutParams.leftMargin > firstHeader.getWidth()) {
return child;
}
}
}
return null;
} |
python | def load_config():
"""
Validate the config
"""
configuration = MyParser()
configuration.read(_config)
d = configuration.as_dict()
if 'jira' not in d:
raise custom_exceptions.NotConfigured
# Special handling of the boolean for error reporting
d['jira']['error_reporting'] = configuration.getboolean('jira', 'error_reporting')
return d |
java | public static void encodeToFile(byte[] dataToEncode, String filename) throws IOException {
if (dataToEncode == null) {
throw new NullPointerException("Data to encode was null.");
}
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(new java.io.FileOutputStream(filename), Base64.ENCODE);
bos.write(dataToEncode);
} catch (IOException e) {
throw e; // Catch and throw to execute finally{} block
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
}
}
} |
java | public String getParameter( String name )
{
if (_parameters == null || !_parameters.hasParameters())
return null;
List parameters = _parameters.getParameterValues(name);
if(parameters != null && parameters.size() > 0)
return (String)parameters.get(0);
else return null;
} |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = GetObject.class)
public JAXBElement<CmisExtensionType> createGetObjectExtension(
CmisExtensionType value) {
return new JAXBElement<CmisExtensionType>(
_GetPropertiesExtension_QNAME, CmisExtensionType.class,
GetObject.class, value);
} |
java | @SuppressWarnings("unchecked")
public static Object proprietaryEvaluate(final String expression,
final Class expectedType, final PageContext pageContext,
final ProtectedFunctionMapper functionMap, final boolean escape)
throws ELException {
Object retValue;
ExpressionFactory exprFactorySetInPageContext = (ExpressionFactory)pageContext.getAttribute(Constants.JSP_EXPRESSION_FACTORY_OBJECT);
if (exprFactorySetInPageContext==null) {
exprFactorySetInPageContext = JspFactory.getDefaultFactory().getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory();
}
final ExpressionFactory exprFactory = exprFactorySetInPageContext;
//if (SecurityUtil.isPackageProtectionEnabled()) {
ELContextImpl ctx = (ELContextImpl) pageContext.getELContext();
ctx.setFunctionMapper(new FunctionMapperImpl(functionMap));
ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType);
retValue = ve.getValue(ctx);
if (escape && retValue != null) {
retValue = XmlEscape(retValue.toString());
}
return retValue;
} |
java | public void beginStop(String groupName, String serviceName) {
beginStopWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} |
java | protected Object getValue( QueryContext context,
StaticOperand operand ) {
if (operand instanceof Literal) {
Literal literal = (Literal)operand;
return literal.value();
}
BindVariableName variable = (BindVariableName)operand;
return context.getVariables().get(variable.getBindVariableName());
} |
java | public void requestValue(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
ZWaveGetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SENSOR_BINARY, ZWaveCommandClass.CommandClass.SENSOR_ALARM, ZWaveCommandClass.CommandClass.SENSOR_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveGetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.getValueMessage(), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} |
python | def argscope(layers, **kwargs):
"""
Args:
layers (list or layer): layer or list of layers to apply the arguments.
Returns:
a context where all appearance of these layer will by default have the
arguments specified by kwargs.
Example:
.. code-block:: python
with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, out_channel=32):
x = Conv2D('conv0', x)
x = Conv2D('conv1', x)
x = Conv2D('conv2', x, out_channel=64) # override argscope
"""
if not isinstance(layers, list):
layers = [layers]
# def _check_args_exist(l):
# args = inspect.getargspec(l).args
# for k, v in six.iteritems(kwargs):
# assert k in args, "No argument {} in {}".format(k, l.__name__)
for l in layers:
assert hasattr(l, 'symbolic_function'), "{} is not a registered layer".format(l.__name__)
# _check_args_exist(l.symbolic_function)
new_scope = copy.copy(get_arg_scope())
for l in layers:
new_scope[l.__name__].update(kwargs)
_ArgScopeStack.append(new_scope)
yield
del _ArgScopeStack[-1] |
java | public double getProd() {
double prod = s.one();
for (int c = 0; c < this.values.length; c++) {
prod = s.times(prod, values[c]);
}
return prod;
} |
python | def place_limit_order(self, side: Side, amount: Number, price: Number) -> Order:
"""Place a limit order."""
return self.place_order(side, OrderType.LIMIT, amount, price) |
java | private Collection<FsItemEx> findRecursively(FsItemFilter filter,
FsItem root)
{
List<FsItemEx> results = new ArrayList<FsItemEx>();
FsVolume vol = root.getVolume();
for (FsItem child : vol.listChildren(root))
{
if (vol.isFolder(child))
{
results.addAll(findRecursively(filter, child));
}
else
{
FsItemEx item = new FsItemEx(child, this);
if (filter.accepts(item))
results.add(item);
}
}
return results;
} |
java | public void addExcludes(Set<String> properties) {
String[] sa = new String[properties.size()];
addTo(excludes, properties.toArray(sa));
} |
python | def get_command_class(self, cmd):
"""
Returns command class from the registry for a given ``cmd``.
:param cmd: command to run (key at the registry)
"""
try:
cmdpath = self.registry[cmd]
except KeyError:
raise CommandError("No such command %r" % cmd)
if isinstance(cmdpath, basestring):
Command = import_class(cmdpath)
else:
Command = cmdpath
return Command |
java | public static boolean nullSafeEquals(@Nullable final Object o1, @Nullable final Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return ObjectUtils.arrayEquals(o1, o2);
}
return false;
} |
python | def _json_default_encoder(func):
"""
Monkey-Patch the core json encoder library.
This isn't as bad as it sounds.
We override the default method so that if an object
falls through and can't be encoded normally, we see if it is
a Future object and return the result to be encoded.
I set a special attribute on the Struct object so I can tell
that's what it is.
If that doesn't work, I fall back to the earlier behavior.
The nice thing about patching the library this way is that it
won't inerfere with existing code and it can itself be wrapped
by other methods.
So it's very extensible.
:param func: the JSONEncoder.default method.
:return: an object that can be json serialized.
"""
@wraps(func)
def inner(self, o):
try:
return o._redpipe_struct_as_dict # noqa
except AttributeError:
pass
return func(self, o)
return inner |
java | public void removeConnection(WebSocketConnection conn) {
if (conn != null) {
WebSocketScope scope = getScope(conn);
if (scope != null) {
scope.removeConnection(conn);
if (!scope.isValid()) {
// scope is not valid. delete this.
removeWebSocketScope(scope);
}
}
}
} |
python | def phenotype_to_res_set(phenotype, resources):
"""
Converts a binary string to a set containing the resources indicated by
the bits in the string.
Inputs: phenotype - a binary string
resources - a list of string indicating which resources correspond
to which indices of the phenotype
returns: A set of strings indicating resources
"""
assert(phenotype[0:2] == "0b")
phenotype = phenotype[2:]
# Fill in leading zeroes
while len(phenotype) < len(resources):
phenotype = "0" + phenotype
res_set = set()
for i in range(len(phenotype)):
if phenotype[i] == "1":
res_set.add(resources[i])
assert(phenotype.count("1") == len(res_set))
return res_set |
java | public static int getHtmlCodeByWikiSymbol(String wikiEntity)
{
Entity entity = fWikiToHtml.get(wikiEntity);
return entity != null ? entity.fHtmlCode : 0;
} |
python | def when_closed(self):
"""
Returns a Deferred that callback()'s (with this Circuit instance)
when this circuit hits CLOSED or FAILED.
"""
if self.state in ['CLOSED', 'FAILED']:
return defer.succeed(self)
return self._when_closed.when_fired() |
python | def update(self, new_details, old_details=None):
''' a method to upsert changes to a record in the table
:param new_details: dictionary with updated record fields
:param old_details: [optional] dictionary with original record fields
:return: list of dictionaries with updated field details
NOTE: if old_details is empty, method will poll database for the
most recent version of the record with which to compare the
new details for changes
'''
title = '%s.update' % self.__class__.__name__
# validate inputs
input_fields = {
'new_details': new_details,
'old_details': old_details
}
for key, value in input_fields.items():
if value:
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
if old_details:
if new_details['id'] != old_details['id']:
raise ValueError('%s old_details["id"] value must match new_details["id"]' % title)
# extract primary key
primary_key = new_details['id']
# # handle missing id
# if not '.id' in self.model.keyMap.keys():
# del new_details['id']
# if old_details:
# del old_details['id']
# validate new details against record model
new_details = self.model.validate(new_details)
# retrieve old record if not specified
if not old_details:
try:
old_details = self.read(primary_key)
except:
raise ValueError('%s new_details["id"] does not exist.' % title)
# determine record differences
from labpack.parsing.comparison import compare_records
update_list = compare_records(new_details, old_details)
# construct update keywords
update_kwargs = {}
for update in update_list:
if update['action'] not in ('DELETE', 'REMOVE'):
current_details = new_details
save_path = ''
for segment in update['path']:
if save_path:
save_path += '.'
save_path += segment
if isinstance(current_details[segment], dict):
current_details = current_details[segment]
continue
elif isinstance(current_details[segment], list):
update_kwargs[save_path] = pickle.dumps(current_details[segment])
break
else:
update_kwargs[save_path] = current_details[segment]
else:
current_details = old_details
save_path = ''
for i in range(len(update['path'])):
segment = update['path'][i]
if save_path:
save_path += '.'
save_path += segment
if update['action'] == 'DELETE' and i + 1 == len(update['path']):
update_kwargs[save_path] = None
elif isinstance(current_details[segment], dict):
current_details = current_details[segment]
continue
elif isinstance(current_details[segment], list):
update_kwargs[save_path] = pickle.dumps(new_details[segment])
break
else:
update_kwargs[save_path] = None
# send update command
if update_kwargs:
update_statement = self.table.update(self.table.c.id==primary_key).values(**update_kwargs)
self.session.execute(update_statement)
return update_list |
java | public void theBestAttributes(Instance instance,
AutoExpandVector<AttributeClassObserver> observersParameter) {
for(int z = 0; z < instance.numAttributes() - 1; z++){
if(!instance.isMissing(z)){
int instAttIndex = modelAttIndexToInstanceAttIndex(z, instance);
ArrayList<Double> attribBest = new ArrayList<Double>();
if(instance.attribute(instAttIndex).isNominal()){
this.minEntropyNominalAttrib=Double.MAX_VALUE;
AutoExpandVector<DoubleVector> attribNominal = ((NominalAttributeClassObserver)observersParameter.get(z)).attValDistPerClass;
findBestValEntropyNominalAtt(attribNominal, instance.attribute(z).numValues()); // The best value (lowest entropy) of a nominal attribute.
attribBest.add(this.saveBestEntropyNominalAttrib.getValue(0));
attribBest.add(this.saveBestEntropyNominalAttrib.getValue(1));
attribBest.add(this.saveBestEntropyNominalAttrib.getValue(2));
this.saveBestValGlobalEntropy.add(attribBest);
this.saveBestGlobalEntropy.setValue(z, this.saveBestEntropyNominalAttrib.getValue(1));
} else {
this.root=((BinaryTreeNumericAttributeClassObserver)observersParameter.get(z)).root;
mainFindBestValEntropy(this.root); // The best value (lowest entropy) of a numeric attribute.
attribBest.add(this.saveBestEntropy.getValue(0));
attribBest.add(this.saveBestEntropy.getValue(1));
attribBest.add(this.saveBestEntropy.getValue(2));
attribBest.add(this.saveBestEntropy.getValue(4));
this.saveBestValGlobalEntropy.add(attribBest);
this.saveBestGlobalEntropy.setValue(z, this.saveBestEntropy.getValue(1));
}
}else{
double value = Double.MAX_VALUE;
this.saveBestGlobalEntropy.setValue(z, value);
}
}
} |
python | def autocorrelation_plot(series, ax=None, **kwds):
"""
Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
kwds : keywords
Options to pass to matplotlib plotting method
Returns:
-----------
class:`matplotlib.axis.Axes`
"""
import matplotlib.pyplot as plt
n = len(series)
data = np.asarray(series)
if ax is None:
ax = plt.gca(xlim=(1, n), ylim=(-1.0, 1.0))
mean = np.mean(data)
c0 = np.sum((data - mean) ** 2) / float(n)
def r(h):
return ((data[:n - h] - mean) *
(data[h:] - mean)).sum() / float(n) / c0
x = np.arange(n) + 1
y = lmap(r, x)
z95 = 1.959963984540054
z99 = 2.5758293035489004
ax.axhline(y=z99 / np.sqrt(n), linestyle='--', color='grey')
ax.axhline(y=z95 / np.sqrt(n), color='grey')
ax.axhline(y=0.0, color='black')
ax.axhline(y=-z95 / np.sqrt(n), color='grey')
ax.axhline(y=-z99 / np.sqrt(n), linestyle='--', color='grey')
ax.set_xlabel("Lag")
ax.set_ylabel("Autocorrelation")
ax.plot(x, y, **kwds)
if 'label' in kwds:
ax.legend()
ax.grid()
return ax |
java | public static Builder overriding(
ExecutableElement method, DeclaredType enclosing, Types types) {
ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
List<? extends TypeMirror> resolvedThrownTypes = executableType.getThrownTypes();
TypeMirror resolvedReturnType = executableType.getReturnType();
Builder builder = overriding(method);
builder.returns(TypeName.get(resolvedReturnType));
for (int i = 0, size = builder.parameters.size(); i < size; i++) {
ParameterSpec parameter = builder.parameters.get(i);
TypeName type = TypeName.get(resolvedParameterTypes.get(i));
builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
}
builder.exceptions.clear();
for (int i = 0, size = resolvedThrownTypes.size(); i < size; i++) {
builder.addException(TypeName.get(resolvedThrownTypes.get(i)));
}
return builder;
} |
python | def module_selected(self, module_name, module_ui):
"""
Called when a module is selected
Args:
module_name (str): The name of the module
module_ui: The function to call to create the module's UI
"""
if self.current_button == self.module_buttons[module_name]:
return
self.module_buttons[module_name].config(bg="#cacaca")
if self.current_button is not None:
self.current_button.config(bg="white")
self.current_button = self.module_buttons[module_name]
self.clear_ui()
try:
# Create the UI
module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui)
module_ui_frame.grid(column=0, row=0, sticky="W E N S")
except Exception as e:
logger.error("Could not load UI for {}".format(module_name))
logger.exception(e)
# Create a error UI
tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid(
column=0, row=0, padx=0, pady=0, sticky="W E N S") |
python | def find_vcs_root(cls, path):
"""Try to find a version control root directory of this type for the
given path.
If successful, returns (vcs_root, levels_up), where vcs_root is the
path to the version control root directory it found, and levels_up is an
integer indicating how many parent directories it had to search through
to find it, where 0 means it was found in the indicated path, 1 means it
was found in that path's parent, etc. If not sucessful, returns None
"""
if cls.search_parents_for_root():
valid_dirs = walk_up_dirs(path)
else:
valid_dirs = [path]
for i, current_path in enumerate(valid_dirs):
if cls.is_valid_root(current_path):
return current_path, i
return None |
python | def delete_zombie_actions(self):
"""Remove actions that have a zombie status (usually timeouts)
:return: None
"""
id_to_del = []
for act in list(self.actions.values()):
if act.status == ACT_STATUS_ZOMBIE:
id_to_del.append(act.uuid)
# une petite tape dans le dos et tu t'en vas, merci...
# *pat pat* GFTO, thks :)
for a_id in id_to_del:
del self.actions[a_id] |
python | def AddEventTag(self, event_tag):
"""Adds an event tag.
Args:
event_tag (EventTag): event tag.
Raises:
IOError: when the storage file is closed or read-only or
if the event identifier type is not supported.
OSError: when the storage file is closed or read-only or
if the event identifier type is not supported.
"""
self._RaiseIfNotWritable()
event_identifier = event_tag.GetEventIdentifier()
if not isinstance(event_identifier, identifiers.SQLTableIdentifier):
raise IOError('Unsupported event identifier type: {0:s}'.format(
type(event_identifier)))
event_tag.event_row_identifier = event_identifier.row_identifier
self._AddAttributeContainer(self._CONTAINER_TYPE_EVENT_TAG, event_tag) |
java | private List<OrcDataOutput> bufferFileFooter()
throws IOException
{
List<OrcDataOutput> outputData = new ArrayList<>();
Metadata metadata = new Metadata(closedStripes.stream()
.map(ClosedStripe::getStatistics)
.collect(toList()));
Slice metadataSlice = metadataWriter.writeMetadata(metadata);
outputData.add(createDataOutput(metadataSlice));
long numberOfRows = closedStripes.stream()
.mapToLong(stripe -> stripe.getStripeInformation().getNumberOfRows())
.sum();
List<ColumnStatistics> fileStats = toFileStats(
closedStripes.stream()
.map(ClosedStripe::getStatistics)
.map(StripeStatistics::getColumnStatistics)
.collect(toList()));
recordValidation(validation -> validation.setFileStatistics(fileStats));
Map<String, Slice> userMetadata = this.userMetadata.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, entry -> utf8Slice(entry.getValue())));
Footer footer = new Footer(
numberOfRows,
rowGroupMaxRowCount,
closedStripes.stream()
.map(ClosedStripe::getStripeInformation)
.collect(toList()),
orcTypes,
fileStats,
userMetadata);
closedStripes.clear();
closedStripesRetainedBytes = 0;
Slice footerSlice = metadataWriter.writeFooter(footer);
outputData.add(createDataOutput(footerSlice));
recordValidation(validation -> validation.setVersion(metadataWriter.getOrcMetadataVersion()));
Slice postscriptSlice = metadataWriter.writePostscript(footerSlice.length(), metadataSlice.length(), compression, maxCompressionBufferSize);
outputData.add(createDataOutput(postscriptSlice));
outputData.add(createDataOutput(Slices.wrappedBuffer((byte) postscriptSlice.length())));
return outputData;
} |
java | @Deprecated
public static String encodeRFC2396(String url) {
try {
return new URI(null,url,null).toASCIIString();
} catch (URISyntaxException e) {
LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen?
return url;
}
} |
python | def iso_abundance(self,isos):
'''
This routine returns the abundance of a specific isotope.
Isotope given as, e.g., 'Si-28' or as list
['Si-28','Si-29','Si-30']
'''
if type(isos) == list:
dumb = []
for it in range(len(isos)):
dumb.append(isos[it].split('-'))
ssratio = []
isos = dumb
for it in range(len(isos)):
ssratio.append(self.habu[isos[it][0].ljust(2).lower() + str(int(isos[it][1])).rjust(3)])
else:
isos = isos.split('-')
ssratio = self.habu[isos[0].ljust(2).lower() + str(int(isos[1])).rjust(3)]
return ssratio |
java | @SuppressWarnings("rawtypes")
private List<InetAddress> resolveCname(String hostname) throws NamingException {
List<InetAddress> inetAddresses = new ArrayList<>();
Attributes attrs = context.getAttributes(hostname, new String[] { "CNAME" });
Attribute attr = attrs.get("CNAME");
if (attr != null && attr.size() > 0) {
NamingEnumeration e = attr.getAll();
while (e.hasMore()) {
String h = (String) e.next();
if (h.endsWith(".")) {
h = h.substring(0, h.lastIndexOf('.'));
}
try {
InetAddress[] resolved = resolve(h);
for (InetAddress inetAddress : resolved) {
inetAddresses.add(InetAddress.getByAddress(hostname, inetAddress.getAddress()));
}
} catch (UnknownHostException e1) {
// ignore
}
}
}
return inetAddresses;
} |
python | def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continue
if qsid not in self:
self[qsid] = QSDev(data=qspacket)
dev = self[qsid]
dev.data = qspacket
# Decode value from QSUSB
newqs = _legacy_status(qspacket[QS_VALUE])
if dev.is_dimmer:
# Adjust dimmer exponentially to get a smoother effect
newqs = min(round(math.pow(newqs, self.dim_adj)), 100)
newin = round(newqs * _MAX / 100)
if abs(dev.value - newin) > 1: # Significant change
_LOGGER.debug("%s qs=%s --> %s", qsid, newqs, newin)
dev.value = newin
self._cb_value_changed(self, qsid, newin) |
java | public static boolean objectInstanceOf(Object object, String className) {
AssertUtils.assertNotNull(object);
boolean result = false;
Class clazz = object.getClass();
if (clazz.getName().equals(className) == true) {
result = true;
}
return result;
} |
java | private void backupCoords(Point2d[] dest, IntStack stack) {
for (int i = 0; i < stack.len; i++) {
int v = stack.xs[i];
dest[v].x = atoms[v].getPoint2d().x;
dest[v].y = atoms[v].getPoint2d().y;
}
} |
python | def cut_value(graph, flow, cut):
"""
Calculate the value of a cut.
@type graph: digraph
@param graph: Graph
@type flow: dictionary
@param flow: Dictionary containing a flow for each edge.
@type cut: dictionary
@param cut: Dictionary mapping each node to a subset index. The function only considers the flow between
nodes with 0 and 1.
@rtype: float
@return: The value of the flow between the subsets 0 and 1
"""
#max flow/min cut value calculation
S = []
T = []
for node in cut.keys():
if cut[node] == 0:
S.append(node)
elif cut[node] == 1:
T.append(node)
value = 0
for node in S:
for neigh in graph.neighbors(node):
if neigh in T:
value = value + flow[(node,neigh)]
for inc in graph.incidents(node):
if inc in T:
value = value - flow[(inc,node)]
return value |
java | public ServiceFuture<AccountFilterInner> getAsync(String resourceGroupName, String accountName, String filterName, final ServiceCallback<AccountFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, filterName), serviceCallback);
} |
java | public ServiceFuture<Void> exportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(exportDataWithServiceResponseAsync(resourceGroupName, name, parameters), serviceCallback);
} |
python | def delete(self, request, bot_id, id, format=None):
"""
Delete existing state
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(StateDetail, self).delete(request, bot_id, id, format) |
python | def write_short_ascii(s):
"""
Encode a Kafka short string which represents text.
:param str s:
Text string (`str` on Python 3, `str` or `unicode` on Python 2) or
``None``. The string will be ASCII-encoded.
:returns: length-prefixed `bytes`
:raises:
`struct.error` for strings longer than 32767 characters
"""
if s is None:
return _NULL_SHORT_STRING
if not isinstance(s, string_types):
raise TypeError('{!r} is not text'.format(s))
return write_short_bytes(s.encode('ascii')) |
python | def create_or_update(cls, *props, **kwargs):
"""
Call to MERGE with parameters map. A new instance will be created and saved if does not already exists,
this is an atomic operation. If an instance already exists all optional properties specified will be updated.
Note that the post_create hook isn't called after create_or_update
:param props: List of dict arguments to get or create the entities with.
:type props: tuple
:param relationship: Optional, relationship to get/create on when new entity is created.
:param lazy: False by default, specify True to get nodes with id only without the parameters.
:rtype: list
"""
lazy = kwargs.get('lazy', False)
relationship = kwargs.get('relationship')
# build merge query, make sure to update only explicitly specified properties
create_or_update_params = []
for specified, deflated in [(p, cls.deflate(p, skip_empty=True)) for p in props]:
create_or_update_params.append({"create": deflated,
"update": dict((k, v) for k, v in deflated.items() if k in specified)})
query, params = cls._build_merge_query(create_or_update_params, update_existing=True, relationship=relationship,
lazy=lazy)
if 'streaming' in kwargs:
warnings.warn('streaming is not supported by bolt, please remove the kwarg',
category=DeprecationWarning, stacklevel=1)
# fetch and build instance for each result
results = db.cypher_query(query, params)
return [cls.inflate(r[0]) for r in results[0]] |
java | public String getApplicationId() {
String applicationId = null;
Integer applicationIdObject = querySingleTypedResult(
"PRAGMA application_id", null, GeoPackageDataType.MEDIUMINT);
if (applicationIdObject != null) {
try {
applicationId = new String(ByteBuffer.allocate(4)
.putInt(applicationIdObject).array(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new GeoPackageException(
"Unexpected application id character encoding", e);
}
}
return applicationId;
} |
python | def from_array(array):
"""
Deserialize a new Update from a given dictionary.
:return: new Update instance.
:rtype: Update
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.inline import ChosenInlineResult
from pytgbot.api_types.receivable.inline import InlineQuery
from pytgbot.api_types.receivable.payments import PreCheckoutQuery
from pytgbot.api_types.receivable.payments import ShippingQuery
from pytgbot.api_types.receivable.updates import CallbackQuery
from pytgbot.api_types.receivable.updates import Message
data = {}
data['update_id'] = int(array.get('update_id'))
data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None
data['edited_message'] = Message.from_array(array.get('edited_message')) if array.get('edited_message') is not None else None
data['channel_post'] = Message.from_array(array.get('channel_post')) if array.get('channel_post') is not None else None
data['edited_channel_post'] = Message.from_array(array.get('edited_channel_post')) if array.get('edited_channel_post') is not None else None
data['inline_query'] = InlineQuery.from_array(array.get('inline_query')) if array.get('inline_query') is not None else None
data['chosen_inline_result'] = ChosenInlineResult.from_array(array.get('chosen_inline_result')) if array.get('chosen_inline_result') is not None else None
data['callback_query'] = CallbackQuery.from_array(array.get('callback_query')) if array.get('callback_query') is not None else None
data['shipping_query'] = ShippingQuery.from_array(array.get('shipping_query')) if array.get('shipping_query') is not None else None
data['pre_checkout_query'] = PreCheckoutQuery.from_array(array.get('pre_checkout_query')) if array.get('pre_checkout_query') is not None else None
data['_raw'] = array
return Update(**data) |
java | public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case OPERATION_ID:
return isSetOperationId();
case HAS_RESULT_SET:
return isSetHasResultSet();
}
throw new IllegalStateException();
} |
python | def _strip_invisible(s):
"Remove invisible ANSI color codes."
if isinstance(s, _text_type):
return re.sub(_invisible_codes, "", s)
else: # a bytestring
return re.sub(_invisible_codes_bytes, "", s) |
python | def union(self, other):
"""Constructs an unminimized DFA recognizing the union of the languages of two given DFAs.
Args:
other (DFA): The other DFA that will be used
for the union operation
Returns:
DFA: The resulting DFA
"""
operation = bool.__or__
self.cross_product(other, operation)
return self |
java | public static <T, U> void consumeIfTrue(T target1, U target2,
BiPredicate<T, U> targetTester, BiConsumer<T, U> biConsumer) {
consumeIfTrue(targetTester.test(target1, target2), target1, target2,
biConsumer);
} |
python | def users(self, username=None, pk=None, **kwargs):
"""
Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param pk: (optional) id of the user to filter
:type pk: basestring or None
:param kwargs: Additional filtering keyword=value arguments
:type kwargs: dict or None
:return: List of :class:`Users`
:raises NotFoundError: when a user could not be found
"""
request_params = {
'username': username,
'pk': pk,
}
if kwargs:
request_params.update(**kwargs)
r = self._request('GET', self._build_url('users'), params=request_params)
if r.status_code != requests.codes.ok: # pragma: no cover
raise NotFoundError("Could not find users: '{}'".format(r.json()))
data = r.json()
return [User(user, client=self) for user in data['results']] |
java | private void saveParameters(String outputDir) throws IOException
{
logger.info("save parameters");
// save param
File paramFile = new File(outputDir + "param");
//File paramFile = File.createTempFile("param", null);
//paramFile.deleteOnExit();
//parameter.store(new FileOutputStream(paramFile), "model parameters");
parameter.store(new FileOutputStream(paramFile), null);
// add the param to the model
//model.add(paramFile, "param");
} |
python | def get_pty(self, term='vt100', width=80, height=24, width_pixels=0,
height_pixels=0):
"""
Request a pseudo-terminal from the server. This is usually used right
after creating a client channel, to ask the server to provide some
basic terminal semantics for a shell invoked with `invoke_shell`.
It isn't necessary (or desirable) to call this method if you're going
to exectue a single command with `exec_command`.
:param str term: the terminal type to emulate (for example, ``'vt100'``)
:param int width: width (in characters) of the terminal screen
:param int height: height (in characters) of the terminal screen
:param int width_pixels: width (in pixels) of the terminal screen
:param int height_pixels: height (in pixels) of the terminal screen
:raises SSHException:
if the request was rejected or the channel was closed
"""
if self.closed or self.eof_received or self.eof_sent or not self.active:
raise SSHException('Channel is not open')
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string('pty-req')
m.add_boolean(True)
m.add_string(term)
m.add_int(width)
m.add_int(height)
m.add_int(width_pixels)
m.add_int(height_pixels)
m.add_string(bytes())
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event() |
python | def get_assessment_part_item_design_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment part item design service.
return: (osid.assessment.authoring.AssessmentPartItemDesignSession)
- an ``AssessmentPartItemDesignSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_assessment_part_item_design()`` is
``false``
*compliance: optional -- This method must be implemented if
``supports_assessment_part_lookup()`` is ``true``.*
"""
if not self.supports_assessment_part_lookup(): # This is kludgy, but only until Tom fixes spec
raise errors.Unimplemented()
# pylint: disable=no-member
return sessions.AssessmentPartItemDesignSession(proxy=proxy, runtime=self._runtime) |
java | public static DMatrixRMaj projectiveToFundamental( DMatrixRMaj P1 , DMatrixRMaj P2 , @Nullable DMatrixRMaj F21 )
{
if( F21 == null )
F21 = new DMatrixRMaj(3,3);
ProjectiveToIdentity p2i = new ProjectiveToIdentity();
if( !p2i.process(P1) )
throw new RuntimeException("Failed!");
DMatrixRMaj P1inv = p2i.getPseudoInvP();
DMatrixRMaj U = p2i.getU();
DMatrixRMaj e = new DMatrixRMaj(3,1);
CommonOps_DDRM.mult(P2,U,e);
DMatrixRMaj tmp = new DMatrixRMaj(3,4);
DMatrixRMaj e_skew = new DMatrixRMaj(3,3);
GeometryMath_F64.crossMatrix(e.data[0],e.data[1],e.data[2],e_skew);
CommonOps_DDRM.mult(e_skew,P2,tmp);
CommonOps_DDRM.mult(tmp,P1inv,F21);
return F21;
} |
java | protected void registerSuperClassMultipleJoinedTables(ClassDescriptor cld)
{
/*
arminw: Sadly, we can't map to sub class-descriptor, because it's not guaranteed
that they exist when this method is called. Thus we map the class instance instead
of the class-descriptor.
*/
if(cld.getBaseClass() != null)
{
try
{
Class superClass = ClassHelper.getClass(cld.getBaseClass());
Class currentClass = cld.getClassOfObject();
synchronized(descriptorTable)
{
List subClasses = (List) superClassMultipleJoinedTablesMap.get(superClass);
if(subClasses == null)
{
subClasses = new ArrayList();
superClassMultipleJoinedTablesMap.put(superClass, subClasses);
}
if(!subClasses.contains(currentClass))
{
if(log.isDebugEnabled())
{
log.debug("(MultipleJoinedTables): Register sub-class '" + currentClass
+ "' for class '" + superClass);
}
subClasses.add(currentClass);
}
}
}
catch(Exception e)
{
throw new MetadataException("Can't register super class '" + cld.getBaseClass()
+ "' for class-descriptor: " + cld, e);
}
}
} |
python | def set_key(dotenv_path, key_to_set, value_to_set, quote_mode="always"):
"""
Adds or Updates a key/value to the given .env
If the .env path given doesn't exist, fails instead of risking creating
an orphan .env somewhere in the filesystem
"""
value_to_set = value_to_set.strip("'").strip('"')
if not os.path.exists(dotenv_path):
warnings.warn("can't write to %s - it doesn't exist." % dotenv_path)
return None, key_to_set, value_to_set
if " " in value_to_set:
quote_mode = "always"
line_template = '{}="{}"\n' if quote_mode == "always" else '{}={}\n'
line_out = line_template.format(key_to_set, value_to_set)
with rewrite(dotenv_path) as (source, dest):
replaced = False
for mapping in parse_stream(source):
if mapping.key == key_to_set:
dest.write(line_out)
replaced = True
else:
dest.write(mapping.original)
if not replaced:
dest.write(line_out)
return True, key_to_set, value_to_set |
java | int CalcSubrOffsetSize(int Offset,int Size)
{
// Set the size to 0
int OffsetSize = 0;
// Go to the beginning of the private dict
seek(Offset);
// Go until the end of the private dict
while (getPosition() < Offset+Size)
{
int p1 = getPosition();
getDictItem();
int p2 = getPosition();
// When reached to the subrs offset
if (key=="Subrs") {
// The Offsize (minus the subrs key)
OffsetSize = p2-p1-1;
}
// All other keys are ignored
}
// return the size
return OffsetSize;
} |
java | public Schema flatten(Schema schema, boolean flattenComplexTypes) {
Preconditions.checkNotNull(schema);
// To help make it configurable later
this.flattenedNameJoiner = FLATTENED_NAME_JOINER;
this.flattenedSourceJoiner = FLATTENED_SOURCE_JOINER;
Schema flattenedSchema = flatten(schema, false, flattenComplexTypes);
LOG.debug("Original Schema : " + schema);
LOG.debug("Flattened Schema: " + flattenedSchema);
return flattenedSchema;
} |
java | public boolean containsMetrics(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
return internalGetMetrics().getMap().containsKey(key);
} |
python | def generate_parameters(self, parameter_id):
"""Returns a set of trial graph config, as a serializable object.
An example configuration:
```json
{
"shared_id": [
"4a11b2ef9cb7211590dfe81039b27670",
"370af04de24985e5ea5b3d72b12644c9",
"11f646e9f650f5f3fedc12b6349ec60f",
"0604e5350b9c734dd2d770ee877cfb26",
"6dbeb8b022083396acb721267335f228",
"ba55380d6c84f5caeb87155d1c5fa654"
],
"graph": {
"layers": [
...
{
"hash_id": "ba55380d6c84f5caeb87155d1c5fa654",
"is_delete": false,
"size": "x",
"graph_type": 0,
"output": [
6
],
"output_size": 1,
"input": [
7,
1
],
"input_size": 2
},
...
]
},
"restore_dir": "/mnt/nfs/nni/ga_squad/87",
"save_dir": "/mnt/nfs/nni/ga_squad/95"
}
```
`restore_dir` means the path in which to load the previous trained model weights. if null, init from stratch.
`save_dir` means the path to save trained model for current trial.
`graph` is the configuration of model network.
Note: each configuration of layers has a `hash_id` property,
which tells tuner & trial code whether to share trained weights or not.
`shared_id` is the hash_id of layers that should be shared with previously trained model.
"""
logger.debug('acquiring lock for param {}'.format(parameter_id))
self.thread_lock.acquire()
logger.debug('lock for current thread acquired')
if not self.population:
logger.debug("the len of poplution lower than zero.")
raise Exception('The population is empty')
pos = -1
for i in range(len(self.population)):
if self.population[i].result is None:
pos = i
break
if pos != -1:
indiv = copy.deepcopy(self.population[pos])
self.population.pop(pos)
graph_param = json.loads(graph_dumps(indiv.config))
else:
random.shuffle(self.population)
if self.population[0].result < self.population[1].result:
self.population[0] = self.population[1]
indiv = copy.deepcopy(self.population[0])
self.population.pop(1)
indiv.mutation(indiv_id = self.generate_new_id())
graph_param = json.loads(graph_dumps(indiv.config))
param_json = {
'graph': graph_param,
'restore_dir': self.save_dir(indiv.parent_id),
'save_dir': self.save_dir(indiv.indiv_id),
'shared_id': list(indiv.shared_ids) if indiv.parent_id is not None else None,
}
logger.debug('generate_parameter return value is:')
logger.debug(param_json)
logger.debug('releasing lock')
self.thread_lock.release()
if indiv.parent_id is not None:
logger.debug("new trial {} pending on parent experiment {}".format(indiv.indiv_id, indiv.parent_id))
self.events[indiv.parent_id].wait()
logger.debug("trial {} ready".format(indiv.indiv_id))
return param_json |
java | public void update(final Throwable t) {
// see if the exception indicates an authorization problem
boolean isAuthorized = true;
if (t instanceof HttpException) {
HttpException httpException = (HttpException) t;
if (httpException.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
isAuthorized = false;
}
}
// adjust the schedule delay based on the type of error
if (isAuthorized) {
// Set the schedule delay to 15 seconds
scheduleDelay = FIFTEEN_SECONDS;
} else {
// Set the schedule delay to five minutes
scheduleDelay = FIVE_MINUTES;
}
} |
python | def process_view(self, request, view_func, view_args, view_kwargs):
"""
Collect data on Class-Based Views
"""
# Purge data in view method cache
# Python 3's keys() method returns an iterator, so force evaluation before iterating.
view_keys = list(VIEW_METHOD_DATA.keys())
for key in view_keys:
del VIEW_METHOD_DATA[key]
self.view_data = {}
try:
cbv = view_func.view_class
except AttributeError:
cbv = False
if cbv:
self.view_data['cbv'] = True
klass = view_func.view_class
self.view_data['bases'] = [base.__name__ for base in inspect.getmro(klass)]
# Inject with drugz
for member in inspect.getmembers(view_func.view_class):
# Check that we are interested in capturing data for this method
# and ensure that a decorated method is not decorated multiple times.
if member[0] in VIEW_METHOD_WHITEIST and member[0] not in PATCHED_METHODS[klass]:
decorate_method(klass, member[0])
PATCHED_METHODS[klass].append(member[0]) |
python | def load(fh, single=False, version=_default_version,
strict=False, errors='warn'):
"""
Deserialize SimpleMRSs from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single: if `True`, only return the first read Xmrs object
strict: deprecated; a `True` value is the same as
`errors='strict'`, and a `False` value is the same as
`errors='warn'`
errors: if `'strict'`, ill-formed MRSs raise an error; if
`'warn'`, raise a warning instead; if `'ignore'`, do not
warn or raise errors for ill-formed MRSs
Returns:
a generator of Xmrs objects (unless the *single* option is
`True`)
"""
if isinstance(fh, stringtypes):
s = open(fh, 'r').read()
else:
s = fh.read()
return loads(s, single=single, version=version,
strict=strict, errors=errors) |
java | public void voteFor(WeightedItem<T> weightedItem) {
reorganizationCounter++;
weightedItem.vote();
if (reorganizationCounter == maxVotesBeforeReorganization) {
reorganizationCounter = 0;
organizeAndAdd(null);
}
} |
python | def kdeconf(kde,conf=0.683,xmin=None,xmax=None,npts=500,
shortest=True,conftol=0.001,return_max=False):
"""
Returns desired confidence interval for provided KDE object
"""
if xmin is None:
xmin = kde.dataset.min()
if xmax is None:
xmax = kde.dataset.max()
x = np.linspace(xmin,xmax,npts)
return conf_interval(x,kde(x),shortest=shortest,conf=conf,
conftol=conftol,return_max=return_max) |
python | def box_ids(creds: dict, cred_ids: list = None) -> dict:
"""
Given a credentials structure and an optional list of credential identifiers
(aka wallet cred-ids, referents; specify None to include all), return dict mapping each
credential identifier to a box ids structure (i.e., a dict specifying its corresponding
schema identifier, credential definition identifier, and revocation registry identifier,
the latter being None if cred def does not support revocation).
:param creds: creds structure returned by (HolderProver agent) get_creds()
:param cred_ids: list of credential identifiers for which to find corresponding schema identifiers, None for all
:return: dict mapping each credential identifier to its corresponding box ids (empty dict if
no matching credential identifiers present)
"""
rv = {}
for inner_creds in {**creds.get('attrs', {}), **creds.get('predicates', {})}.values():
for cred in inner_creds: # cred is a dict in a list of dicts
cred_info = cred['cred_info']
cred_id = cred_info['referent']
if (cred_id not in rv) and (not cred_ids or cred_id in cred_ids):
rv[cred_id] = {
'schema_id': cred_info['schema_id'],
'cred_def_id': cred_info['cred_def_id'],
'rev_reg_id': cred_info['rev_reg_id']
}
return rv |
python | def main():
"""
Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another players
character
character
stats
world
locations
"""
character1 = Character('Albogh', str=4,int=7,sta=50)
character2 = Character('Zoltor', str=6,int=6,sta=70)
print('PLAYER1 [start]:', character1)
print('PLAYER2 [start]:', character2)
b = Battle(character1, character2)
print(b)
print('PLAYER1 [end]:', character1)
print('PLAYER2 [end]:', character2) |
python | def get_import_update_hash_from_outputs( outputs ):
"""
This is meant for NAME_IMPORT operations, which
have five outputs: the OP_RETURN, the sender (i.e.
the namespace owner), the name's recipient, the
name's update hash, and the burn output.
This method extracts the name update hash from
the list of outputs.
By construction, the update hash address is the 3rd output.
"""
if len(outputs) < 3:
raise Exception("No update hash found")
update_addr = None
try:
update_addr = virtualchain.script_hex_to_address(outputs[2]['script'])
assert update_addr
except:
log.warning("Invalid update output: {}".format(outputs[2]['script']))
raise Exception("No update hash found")
return hexlify(keylib.b58check.b58check_decode(update_addr)) |
java | @Nonnull
public BiMap<String, String> getOutputMapper() {
final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();
if (outputMapper == null) {
return HashBiMap.create();
}
return outputMapper;
} |
java | public Object getResultForContext(Context context) {
if (context == null) {
return null;
}
Object object = this.contextObjectResolver.resolveForObjectAndContext(null, context);
if (object == null) {
return null;
}
return object;
} |
python | def pgettext(
self, context: str, message: str, plural_message: str = None, count: int = None
) -> str:
"""Allows to set context for translation, accepts plural forms.
Usage example::
pgettext("law", "right")
pgettext("good", "right")
Plural message example::
pgettext("organization", "club", "clubs", len(clubs))
pgettext("stick", "club", "clubs", len(clubs))
To generate POT file with context, add following options to step 1
of `load_gettext_translations` sequence::
xgettext [basic options] --keyword=pgettext:1c,2 --keyword=pgettext:1c,2,3
.. versionadded:: 4.2
"""
if plural_message is not None:
assert count is not None
msgs_with_ctxt = (
"%s%s%s" % (context, CONTEXT_SEPARATOR, message),
"%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message),
count,
)
result = self.ngettext(*msgs_with_ctxt)
if CONTEXT_SEPARATOR in result:
# Translation not found
result = self.ngettext(message, plural_message, count)
return result
else:
msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
result = self.gettext(msg_with_ctxt)
if CONTEXT_SEPARATOR in result:
# Translation not found
result = message
return result |
python | def _find_neighbors(self, inst, avg_dist):
""" Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array.
This works the same regardless of endpoint type. """
NN_near = []
NN_far = []
min_indices = []
max_indices = []
for i in range(self._datalen):
if inst != i:
locator = [inst, i]
if i > inst:
locator.reverse()
d = self._distance_array[locator[0]][locator[1]]
if d < avg_dist:
min_indices.append(i)
if d > avg_dist:
max_indices.append(i)
for i in range(len(min_indices)):
NN_near.append(min_indices[i])
for i in range(len(max_indices)):
NN_far.append(max_indices[i])
return np.array(NN_near, dtype=np.int32), np.array(NN_far, dtype=np.int32) |
java | protected ListenableFuture<Boolean> setData(String path, byte[] data, boolean overwrite) {
final SettableFuture<Boolean> future = SettableFuture.create();
boolean ret = FileUtils.writeToFile(path, data, overwrite);
safeSetFuture(future, ret);
return future;
} |
java | public CreateGrantRequest withOperations(String... operations) {
if (this.operations == null) {
setOperations(new com.amazonaws.internal.SdkInternalList<String>(operations.length));
}
for (String ele : operations) {
this.operations.add(ele);
}
return this;
} |
java | public ResultList<Artwork> getEpisodeImages(int tvID, int seasonNumber, int episodeNumber) throws MovieDbException {
return tmdbEpisodes.getEpisodeImages(tvID, seasonNumber, episodeNumber);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.