language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def sdm2ms(sdmfile, msfile, scan, inttime='0'):
""" Converts sdm to ms format for a single scan.
msfile defines the name template for the ms. Should end in .ms,
but "s<scan>" will be put in.
scan is string of (sdm counted) scan number.
inttime is string to feed to split command.
gives option of ... |
python | def render_pep440_bare(pieces):
"""TAG[.DISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.DISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".%d" % pieces["distan... |
python | def _verbose_print(self, desc, init, arr):
"""Internal verbose print function
Parameters
----------
desc : InitDesc or str
name of the array
init : str
initializer pattern
arr : NDArray
initialized array
"""
if self._ve... |
python | def get_config_value_from_file(key, config_path=None, default=None):
"""Return value if key exists in file.
Return default if key not in config.
"""
config = _get_config_dict_from_file(config_path)
if key not in config:
return default
return config[key] |
java | public static <K, V> HashMap<K, V> sizedHashMap(final int size) {
return new HashMap<K, V>(size);
} |
java | @Override
public JFieldVar apply(String nodeName, JsonNode node, JsonNode parent, JFieldVar field, Schema currentSchema) {
boolean defaultPresent = node != null && isNotEmpty(node.asText());
String fieldType = field.type().fullName();
if (defaultPresent && !field.type().isPrimitive() && n... |
java | public void assertExecuteMethodResponseDefined(ActionResponse response) {
if (response.isUndefined()) {
final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
br.addNotice("Cannot return undefined resopnse from the execute method.");
br.addItem("Advice");
... |
java | @SuppressWarnings("unchecked")
public void writeObjectField(final EnMember member, Object obj) {
Object value = member.attribute.get(obj);
if (value == null) return;
if (tiny()) {
if (member.istring) {
if (((CharSequence) value).length() == 0) return;
... |
python | def get_possible_initializer_keys(cls, num_layers):
"""Returns the keys the dictionary of variable initializers may contain.
The set of all possible initializer keys are:
wt: weight for input -> T gate
wh: weight for input -> H gate
wtL: weight for prev state -> T gate for layer L (indexed fr... |
python | def eigvec_to_eigdispl(v, q, frac_coords, mass):
"""
Converts a single eigenvector to an eigendisplacement in the primitive cell
according to the formula::
exp(2*pi*i*(frac_coords \\dot q) / sqrt(mass) * v
Compared to the modulation option in phonopy, here all the additional
mu... |
java | public java.util.List<ProductCode> getProductCodes() {
if (productCodes == null) {
productCodes = new com.amazonaws.internal.SdkInternalList<ProductCode>();
}
return productCodes;
} |
java | private Comparator<String> getInitedAliasComparator() {
if (MapUtil.isEmpty(this.headerAlias)) {
return null;
}
Comparator<String> aliasComparator = this.aliasComparator;
if (null == aliasComparator) {
Set<String> keySet = this.headerAlias.keySet();
aliasComparator = new IndexedComparator<>(keyS... |
java | private void encodeMarkup(final FacesContext context, final Social social) throws IOException {
final ResponseWriter writer = context.getResponseWriter();
final String clientId = social.getClientId(context);
final String widgetVar = social.resolveWidgetVar();
final String styleClass = so... |
java | private int doBatchKmeans () {
System.out.println("\nBegining a new iteration of K-Means...");
int numReassigned = 0;
/* Clear records for incremental k-means */
for (int i = 0; i < this.centroids.length; ++i) {
this.newClusters[i] = new ArrayList<Instance>();
this.newCentroids[i] = new Hash... |
java | double string2Fraction(CharSequence cs, int readed) {
if (cs.length() > 16) {
throw new JsonParseException("Number string is too long.", readed);
}
double d = 0.0;
for (int i = 0; i < cs.length(); i++) {
int n = cs.charAt(i) - '0';
d = d + (n == 0 ? 0 : n / Math.pow(10, i + 1));
}
return d;
} |
java | public static boolean zipFolder(File folder, String fileName){
boolean success = false;
if(!folder.isDirectory()){
return false;
}
if(fileName == null){
fileName = folder.getAbsolutePath()+ZIP_EXT;
}
ZipArchiveOutputStream zipOutput = null;
try {
zipOutput = new ZipArchiveOutputStream(new F... |
python | def fetch_image(self, path, dest, user='root'):
"""Store in the user home directory an image from a remote location.
"""
self.run('test -f %s || curl -L -s -o %s %s' % (dest, dest, path),
user=user, ignore_error=True) |
java | @Override
public T deserializeWrapped( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params,
IdentityDeserializationInfo identityInfo, TypeDeserializationInfo typeInfo, String typeInformation ) {
return instanceBuilder.newInstance( reader, ctx... |
python | def delete_nve_member(self, nexus_host, nve_int_num, vni):
"""Delete a member configuration on the NVE interface."""
starttime = time.time()
path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
... |
java | public String getNodeDistributionRootUrl() {
String ret = nodeDistributionRootUrl;
if (nodeDistributionRootUrl == null) {
ret = Constants.NODE_DIST_ROOT_URL;
}
return ret;
} |
python | def _get_filename_from_url(url):
""" Return a filename from a URL
Args:
url (str): URL to extract filename from
Returns:
(str): Filename in URL
"""
parse = urlparse(url)
return os.path.basename(parse.path) |
python | def writeSAM(sam,SAMfile,header=None):
"""
Writes a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ','QUAL' into a sam file
:param sam: pandas dataframe to be writen
:param SAMfile: /path/to/file.sam
:returns: nothing
""... |
java | public void setAdjustmentTimeSeries(com.google.api.ads.admanager.axis.v201902.TimeSeries adjustmentTimeSeries) {
this.adjustmentTimeSeries = adjustmentTimeSeries;
} |
python | def update_user(self, id, **kwargs): # noqa: E501
"""Update user with given user groups and permissions. # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.updat... |
python | def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias,
sampled_values, remove_accidental_hits=True):
""" Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
"""
# inputs = (n, in_dim)
... |
java | public ServiceFuture<DataLakeAnalyticsAccountInner> beginUpdateAsync(String resourceGroupName, String accountName, UpdateDataLakeAnalyticsAccountParameters parameters, final ServiceCallback<DataLakeAnalyticsAccountInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(re... |
java | private static <T> Constructor<T> lookupConstructor(Class<T> clazz, Object[] pArguments) throws NoSuchMethodException {
Class[] argTypes = extractArgumentTypes(pArguments);
return clazz.getConstructor(argTypes);
} |
python | def listen_many(*rooms):
"""Listen for changes in all registered listeners in all specified rooms"""
rooms = set(r.conn for r in rooms)
for room in rooms:
room.validate_listeners()
with ARBITRATOR.condition:
while any(r.connected for r in rooms):
ARBITRATOR.condition.wait()
... |
python | async def deserialize(data: dict):
"""
Create the object from a previously serialized object.
:param data: The output of the "serialize" call
Example:
data = await connection1.serialize()
connection2 = await Connection.deserialize(data)
:return: A re-instantiated... |
java | private void processPropertySeq(LevState levState, short _prop,
int start, int limit) {
byte cell;
byte[][] impTab = levState.impTab;
short[] impAct = levState.impAct;
short oldStateSeq,actionSeq;
byte level, addLevel;
int start0, k;
start0 = start; ... |
python | def interpolate(features, hparams, decode_hp):
"""Interpolate between the first input frame and last target frame.
Args:
features: dict of tensors
hparams: HParams, training hparams.
decode_hp: HParams, decode hparams.
Returns:
images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C)
... |
python | def save_intermediate_array(self, array, name):
"""Save intermediate array object as FITS."""
if self.intermediate_results:
fits.writeto(name, array, overwrite=True) |
java | public void set(String propName, Object value) {
if (propName.equals(PROP_IDENTIFIER)) {
setIdentifier(((IdentifierType) value));
}
if (propName.equals(PROP_VIEW_IDENTIFIERS)) {
getViewIdentifiers().add(((com.ibm.wsspi.security.wim.model.ViewIdentifierType) value));
... |
python | def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
normalize=True, name=None, closed=None, **kwargs):
"""
Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the
default frequency
.. deprecated:: 0.21.0
Parameters
----------
start : string ... |
java | public int moveIndex(int delta) {
int x = Math.max(0, Math.min(getIndex() + delta, getLength()));
setIndex(x);
return x;
} |
python | def assign_handler(query, category):
"""assign_handler(query, category) -- assign the user's query to a
particular category, and call the appropriate handler.
"""
if(category == 'count lines'):
handler.lines(query)
elif(category == 'count words'):
handler.words(query)
elif(category == 'weather'):
web.weath... |
java | protected void initTableInfoForeignKeys(final Connection _con,
final String _sql,
final Map<String, TableInformation> _cache4Name)
throws SQLException
{
Statement stmt = null;
final ResultSet rs;
... |
java | @Override
public T addAsWebResource(Asset resource, String target) throws IllegalArgumentException {
Validate.notNull(resource, "Resource should be specified");
Validate.notNull(target, "Target should be specified");
return addAsWebResource(resource, new BasicPath(target));
} |
java | private Object serializeCollection(Collection pArg) {
JSONArray array = new JSONArray();
for (Object value : ((Collection) pArg)) {
array.add(serializeArgumentToJson(value));
}
return array;
} |
java | @Override
public String key(String key, Object[] args) {
if (hasConfigValue(key)) {
return getConfigValue(key, args);
}
return m_messages.key(key, args);
} |
python | def send(self, to, subject=None, body=None, reply_to=None, template=None, **kwargs):
"""
To send email
:param to: the recipients, list or string
:param subject: the subject
:param body: the body
:param reply_to: reply_to
:param template: template, will use the tem... |
python | def handle_items(repo, **kwargs):
""":return: repo.files()"""
log.info('items: %s %s' %(repo, kwargs))
if not hasattr(repo, 'items'):
return []
return [i.serialize() for i in repo.items(**kwargs)] |
java | private static PBXObjectRef createPBXSourcesBuildPhase(final int buildActionMask, final List files,
final boolean runOnly) {
final Map map = new HashMap();
map.put("buildActionMask", String.valueOf(buildActionMask));
map.put("files", files);
map.put("isa", "PBXSourcesBuildPhase");
map.put("run... |
java | public static Color colorWithoutAlpha( Color color ) {
return new Color(color.getRed(), color.getGreen(), color.getBlue());
} |
python | def configure_containers(self, current_options):
""" Configures the container dict """
containers = [
("default", "Default container. For Bash and Python 2 tasks"),
("cpp", "Contains gcc and g++ for compiling C++"),
("java7", "Contains Java 7"),
("java8sca... |
python | def _get_series_list(self, others, ignore_index=False):
"""
Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index).
Parameters
----------
others : Se... |
python | def filter_genes_dispersion(data, flavor='seurat', min_disp=None, max_disp=None, min_mean=None, max_mean=None,
n_bins=20, n_top_genes=None, log=True, copy=False):
"""Extract highly variable genes.
The normalized dispersion is obtained by scaling with the mean and standard
deviati... |
python | def uninstall(self, pkgname, *args, **kwargs):
"""A context manager which allows uninstallation of packages from the virtualenv
:param str pkgname: The name of a package to uninstall
>>> venv = VirtualEnv("/path/to/venv/root")
>>> with venv.uninstall("pytz", auto_confirm=True, verbose=... |
java | public byte minValue() {
if (data.length == 0)
return 0;
byte min = Byte.MAX_VALUE;
for (byte b : data)
if (b < min)
min = b;
return min;
} |
python | def describe(self, tablename, refresh=False, metrics=False, require=False):
""" Get the :class:`.TableMeta` for a table """
table = self.cached_descriptions.get(tablename)
if refresh or table is None or (metrics and not table.consumed_capacity):
desc = self.connection.describe_table(... |
python | def teams(self, page=None, year=None, simple=False, keys=False):
"""
Get list of teams.
:param page: Page of teams to view. Each page contains 500 teams.
:param year: View teams from a specific year.
:param simple: Get only vital data.
:param keys: Set to true if you onl... |
python | def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Ro... |
java | public void marshall(AdminListUserAuthEventsRequest adminListUserAuthEventsRequest, ProtocolMarshaller protocolMarshaller) {
if (adminListUserAuthEventsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshalle... |
java | @Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// check size limit
if(maxSizeReached(solution)){
// size limit would be exceeded
return null;
}
// get set of candidate IDs for addition (possibly fixed IDs are discarded)
... |
java | public static String paragraph(int sentenceCount, boolean supplemental, int randomSentencesToAdd) {
String paragraphString = sentences(sentenceCount + RandomUtils.nextInt(randomSentencesToAdd), supplemental);
return paragraphString;
} |
java | public static IType getByRelativeName( String relativeName, ITypeUsesMap typeUses ) throws ClassNotFoundException
{
return CommonServices.getTypeSystem().getByRelativeName(relativeName, typeUses);
} |
java | private void measureFloater() {
int specWidth = View.MeasureSpec.makeMeasureSpec(screenSize.x, View.MeasureSpec.EXACTLY);
int specHeight = View.MeasureSpec.makeMeasureSpec(screenSize.y, View.MeasureSpec.AT_MOST);
mPopupView.measure(specWidth, specHeight);
} |
java | private FileDetails getOldestInactive() {
for (FileDetails curFd : fileList) {
if (curFd.pid == null)
return curFd ;
synchronized(activeFilesMap) {
FileDetails cur4Pid = activeFilesMap.get(curFd.pid) ;
if ( cur4Pid == null || cur4Pid != curFd) {
return curFd ;
}
}
}
return null ;
} |
java | public static Date getRandomDate(Date begin, Date end, Random random) {
long delay = end.getTime() - begin.getTime();
return new Date(begin.getTime() + (Math.abs(random.nextLong() % delay)));
} |
java | @Override
public ListTrafficPoliciesResult listTrafficPolicies(ListTrafficPoliciesRequest request) {
request = beforeClientExecution(request);
return executeListTrafficPolicies(request);
} |
python | def move_group(self, group, parent, index=None):
"""
Move group to be a child of new parent.
:param group: The group to move.
:type group: :class:`keepassdb.model.Group`
:param parent: The new parent for the group.
:type parent: :class:`keepassdb.model.Group`
... |
java | public String haikunate() {
if (tokenHex) {
tokenChars = "0123456789abcdef";
}
String adjective = randomString(adjectives);
String noun = randomString(nouns);
StringBuilder token = new StringBuilder();
if (tokenChars != null && tokenChars.length() > 0) {
... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "MultiSolidCoverage", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_DiscreteCoverage")
public JAXBElement<MultiSolidCoverageType> createMultiSolidCoverage(MultiSolidCoverageType value) {
return new JAXBElem... |
python | def validate(self):
"""
Perform options validation.
"""
# TODO: at the moment only required_languages is validated.
# Maybe check other options as well?
if self.required_languages:
if isinstance(self.required_languages, (tuple, list)):
self._ch... |
python | def sync_hue_db(self, *servers):
"""
Synchronize the Hue server's database.
@param servers: Name of Hue Server roles to synchronize. Not required starting with API v10.
@return: List of submitted commands.
"""
actual_version = self._get_resource_root().version
if actual_version < 10:
... |
java | @Override
public <T> T onlyOne(Class<T> serviceClass) {
Collection<T> all = all(serviceClass);
if (all.size() == 1) {
return all.iterator().next();
}
if (all.size() > 1) {
throw new IllegalStateException(
"Multiple service implementations found... |
java | protected boolean internalEquals(ValueData another)
{
if (another instanceof LongValueData)
{
return ((LongValueData)another).value == value;
}
return false;
} |
python | def _translate_src_oprnd(self, operand):
"""Translate source operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(... |
java | public DeviceData command_inout(TacoTangoDevice tacoDevice, String command, DeviceData argin) throws DevFailed {
Except.throw_exception("Api_TacoFailed",
"Taco protocol not supported",
"TacoTangoDeviceDAODefaultImpl.command_inout()");
return null;
} |
python | def _multicall(hook_impls, caller_kwargs, firstresult=False):
"""Execute a call into multiple python functions/methods and return the
result(s).
``caller_kwargs`` comes from _HookCaller.__call__().
"""
__tracebackhide__ = True
results = []
excinfo = None
try: # run impl and wrapper set... |
java | public UserManagedCacheBuilder<K, V, T> withValueSerializingCopier() {
UserManagedCacheBuilder<K, V, T> otherBuilder = new UserManagedCacheBuilder<>(this);
otherBuilder.valueCopier = null;
otherBuilder.useValueSerializingCopier = true;
return otherBuilder;
} |
java | public String getLicenseKey() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new HazelcastRuntimePermission("com.hazelcast.config.Config.getLicenseKey"));
}
return licenseKey;
} |
python | def rebase_all_branches(self):
""" Rebase all branches, if possible. """
col_width = max(len(b.name) for b in self.branches) + 1
if self.repo.head.is_detached:
raise GitError("You're not currently on a branch. I'm exiting"
" in case you're in the middl... |
java | public void onUnknownHost(String host, SshPublicKey pk) {
try {
System.out.println("The host " + host
+ " is currently unknown to the system");
System.out.println("The MD5 host key " + "(" + pk.getAlgorithm()
+ ") fingerprint is: " + pk.getFingerprint());
System.out.println("The SHA1 host key "
... |
python | def rasterToPolygon(raster_file, polygon_file):
"""
Converts watershed raster to polygon and then dissolves it.
It dissolves features based on the LINKNO attribute.
"""
log("Process: Raster to Polygon ...")
time_start = datetime.utcnow()
temp_polygon_file = \
... |
java | public void init(final String path) throws IOException
{
SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>()
{
public Object run() throws Exception
{
baseDir = new File(path);
return null;
}
});
} |
python | def parse_runtime_limit(value, now=None):
"""Parsing CLI option for runtime limit, supplied as VALUE.
Value could be something like: Sunday 23:00-05:00, the format being
[Wee[kday]] [hh[:mm][-hh[:mm]]].
The function will return two valid time ranges. The first could be in the
past, containing the p... |
python | def inference(self, kern, X, likelihood, Y, Y_metadata=None):
"""
Returns a GridPosterior class containing essential quantities of the posterior
"""
N = X.shape[0] #number of training points
D = X.shape[1] #number of dimensions
Kds = np.zeros(D, dtype=object) #vector fo... |
python | def draw_tree_grid(self,
nrows=None,
ncols=None,
start=0,
fixed_order=False,
shared_axis=False,
**kwargs):
"""
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
N... |
java | public static void run(final Properties properties) throws IOException {
// read parameters for output (do this at the beginning to avoid unnecessary reading)
File outputFile = new File(properties.getProperty(OUTPUT_FILE));
Boolean overwrite = Boolean.parseBoolean(properties.getProperty(OUTPUT_O... |
java | @Override
public QueryObjectsResult queryObjects(QueryObjectsRequest request) {
request = beforeClientExecution(request);
return executeQueryObjects(request);
} |
python | def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
"""split a list of closed issues into non-PR Issues and Pull Requests"""
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.a... |
java | public void init(FilterConfig filterConfig) throws ServletException {
// need the Context for Logging, instantiating ClassLoader, etc
ServletContextAccess sca=new ServletContextAccess(filterConfig);
if(access==null) {
access = sca;
}
// Set Protected getter with base Access, for internal class i... |
java | @Pure
public boolean isTemporaryChange() {
final Object src = getSource();
if (src instanceof MapLayer) {
return ((MapLayer) src).isTemporaryLayer();
}
return false;
} |
python | def violin(adata, keys, groupby=None, log=False, use_raw=None, stripplot=True, jitter=True,
size=1, scale='width', order=None, multi_panel=None, show=None,
xlabel='', rotation=None, save=None, ax=None, **kwds):
"""\
Violin plot.
Wraps `seaborn.violinplot` for :class:`~anndata.AnnData`... |
java | public void setLabel(java.lang.String label) {
getStateHelper().put(PropertyKeys.label, label);
} |
java | protected void writeEntityMetawidget(final Map<Object, Object> context, final int entityMetawidgetIndent,
final Map<String, String> existingNamespaces)
{
StringWriter stringWriter = new StringWriter();
this.entityMetawidget.write(stringWriter, entityMetawidgetIndent);
context.put("metaw... |
python | def GetDateRange(self):
"""Return the range over which this ServicePeriod is valid.
The range includes exception dates that add service outside of
(start_date, end_date), but doesn't shrink the range if exception
dates take away service at the edges of the range.
Returns:
A tuple of "YYYYMMD... |
java | boolean isAuthorized(String accountId) {
try {
DataStore<StoredCredential> sc = StoredCredential.getDefaultDataStore(dataStoreFactory);
return sc.containsKey(accountId);
} catch (IOException e) {
return false;
}
} |
python | def delete_rater(self):
"""Action: create dialog to delete rater."""
answer = QInputDialog.getText(self, 'Delete Rater',
'Enter rater\'s name')
if answer[1]:
self.annot.remove_rater(answer[0])
self.display_notes()
self.par... |
python | def set_cognitive_process(self, grade_id):
"""Sets the cognitive process.
arg: grade_id (osid.id.Id): the new cognitive process
raise: InvalidArgument - ``grade_id`` is invalid
raise: NoAccess - ``grade_id`` cannot be modified
raise: NullArgument - ``grade_id`` is ``null``... |
python | def get_used_in_func(node):
'''Get names, but ignore variables names to the left hand side
That is to say, in case of
a = b + 1
we consider b as "being accessed", while a is not.
'''
if isinstance(node, ast.FunctionDef):
return {node.name: get_accessed(node.body)}
names = {}
f... |
java | public OvhOrder dedicated_nasha_new_duration_POST(String duration, OvhNasHAZoneEnum datacenter, OvhNasHAOfferEnum model) throws IOException {
String qPath = "/order/dedicated/nasha/new/{duration}";
StringBuilder sb = path(qPath, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "da... |
python | def encode(self, name, as_map_key=False):
"""Returns the name the first time and the key after that"""
if name in self.key_to_value:
return self.key_to_value[name]
return self.encache(name) if is_cacheable(name, as_map_key) else name |
python | def do_decode(cls, obj, obj_type):
# type: (Any, ConjureTypeType) -> Any
"""Decodes json into the specified type
Args:
obj: the json object to decode
element_type: a class object which is the type we're decoding into.
"""
if inspect.isclass(obj_type) and ... |
java | private int getToolbarHeightAdjustment(boolean bToolbarShown) {
int adjustAmount = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
boolean translucentStatus = false;
// check theme attrs to see if translucent statusbar is set explicitly
int[] attrs = {android.R.attr.windowTranslucentStatus};
... |
java | private int nextChar() {
String filter = mFilter;
int pos = mPos;
int c = (pos >= filter.length()) ? -1 : mFilter.charAt(pos);
mPos = pos + 1;
return c;
} |
java | public static double loss(double pred, double y)
{
final double x = -y * pred;
if (x >= 30)//as x -> inf, L(x) -> x. At 30 exp(x) is O(10^13), getting unstable. L(x)-x at this value is O(10^-14), also avoids exp and log ops
return x;
else if (x <= -30)
return 0;
... |
python | def vagalume(song):
"""
Returns the lyrics found in vagalume.com.br for the specified mp3 file or
an empty string if not found.
"""
translate = {
'@': 'a',
URLESCAPE: '',
' ': '-'
}
artist = song.artist.lower()
artist = normalize(artist, translate)
artist = re... |
java | private IMolecularFormulaSet returnOrdered(double mass, IMolecularFormulaSet formulaSet) {
IMolecularFormulaSet solutions_new = null;
if (formulaSet.size() != 0) {
double valueMin = 100;
int i_final = 0;
solutions_new = formulaSet.getBuilder().newInstance(IMolecular... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.