file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index.js | /**
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
it('tells the driver to end network collection', () => {
let calledNetworkCollect = false;
const driver = {
endNetworkCollect() {
calledNetworkCollect = true;
return Promise.resolve({x: 1});
}
};
const config = {
network: true,
gatherers: [{
afterPass(... | });
}); | random_line_split |
inMageAzureV2EventDetails.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | }
},
category: {
required: false,
serializedName: 'category',
type: {
name: 'String'
}
},
component: {
required: false,
serializedName: 'component',
type: {
... | eventType: {
required: false,
serializedName: 'eventType',
type: {
name: 'String' | random_line_split |
inMageAzureV2EventDetails.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | extends models['EventProviderSpecificDetails'] {
/**
* Create a InMageAzureV2EventDetails.
* @member {string} [eventType] InMage Event type. Takes one of the values of
* {InMageDataContract.InMageMonitoringEventType}.
* @member {string} [category] InMage Event Category.
* @member {string} [component] ... | InMageAzureV2EventDetails | identifier_name |
inMageAzureV2EventDetails.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | },
eventType: {
required: false,
serializedName: 'eventType',
type: {
name: 'String'
}
},
category: {
required: false,
serializedName: 'category',
type: {
name: 'String... | {
return {
required: false,
serializedName: 'InMageAzureV2',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'instanceType',
clientName: 'instanceType'
},
uberParent: 'EventProviderSpecificDetails',
className: 'InMa... | identifier_body |
posts.py | # -*- coding: utf-8 -*-
# Copyright © 2012-2022 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights t... | ""Check if a post depends on the timeline."""
if "####MAGIC####TIMELINE" not in post.fragment_deps(lang):
return True # No dependency on timeline
elif self.tl_changed:
return False # Timeline changed
return True
| identifier_body | |
posts.py | # -*- coding: utf-8 -*-
# Copyright © 2012-2022 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights t... | elif self.tl_changed:
return False # Timeline changed
return True | random_line_split | |
posts.py | # -*- coding: utf-8 -*-
# Copyright © 2012-2022 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights t... | dest = post.translated_base_path(lang)
file_dep = [p for p in post.fragment_deps(lang) if not p.startswith("####MAGIC####")]
extra_targets = post.compiler.get_extra_targets(post, lang, dest)
task = {
'basename': self.name,
... | f p.startswith('####MAGIC####CONFIG:'):
k = p.split('####MAGIC####CONFIG:', 1)[-1]
deps_dict[k] = self.site.config.get(k)
| conditional_block |
posts.py | # -*- coding: utf-8 -*-
# Copyright © 2012-2022 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights t... | ):
self.tl_changed = True
yield {
'basename': self.name,
'name': 'timeline_changes',
'actions': [tl_ch],
'uptodate': [utils.config_changed({1: kw['timeline']})],
}
for lang in kw["translations"]:
deps_dict = copy(kw)
... | l_ch( | identifier_name |
ui.js | (function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink');
| var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length ==... | function toggleClass(element, className) { | random_line_split |
ui.js | (function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = cla... |
}(this, this.document));
| {
prettyPrint();
} | conditional_block |
ui.js | (function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink');
function toggleClass(element, className) |
menuLink.onclick = function (e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
};
$("pre").addClass("prettyprint").addClass("linenums");
if(typeof(prettyPrint)=='function')... | {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length ... | identifier_body |
ui.js | (function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink');
function | (element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not foun... | toggleClass | identifier_name |
phone_number_detection.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
try:
import regex
_regex_available = True
except ImportError:
_regex_available = False
import phonenumbers
from six.moves import zip
from language_utilities.constant import ENGLISH_LANG
from ner_v2.detectors.base_detector import B... | :return: dict with country_code if it's in phone_num or phone_number with current country code
Examples:
phone_num = '919123456789'
countryCallingCode = 'IN'
{countryCallingCode:"91",value:"9123456789"}
"""
phone_dict = {}
if len(phone_num) > 10... | phone = []
validated_original_text = []
for phone, original in zip(self.phone, self.original_phone_text):
if re.search(r'\W' + re.escape(original) + r'\W', self.text, re.UNICODE):
validated_phone.append(phone)
validated_original_text.append(original)
r... | identifier_body |
phone_number_detection.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
try:
import regex
_regex_available = True
except ImportError:
_regex_available = False
import phonenumbers
from six.moves import zip
from language_utilities.constant import ENGLISH_LANG
from ner_v2.detectors.base_detector import B... | (self, entity_name, language=ENGLISH_LANG, locale=None):
"""
Args:
entity_name (str): A string by which the detected numbers would be replaced with
on calling detect_entity()
language (str, optional): language code of number text, defaults to 'en'
locale(s... | __init__ | identifier_name |
phone_number_detection.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
try:
import regex
_regex_available = True
except ImportError:
_regex_available = False
import phonenumbers
from six.moves import zip
from language_utilities.constant import ENGLISH_LANG
from ner_v2.detectors.base_detector import B... | else:
# This means our detector has detected some other country code.
self.phone.append({"country_calling_code": str(match.number.country_code),
"value": str(match.number.national_number)})
self.original_phone_text.append(sel... | for match in phonenumbers.PhoneNumberMatcher(self.text, self.country_code, leniency=0):
if match.number.country_code == phonenumbers.country_code_for_region(self.country_code):
self.phone.append(self.check_for_country_code(str(match.number.national_number)))
self.orig... | random_line_split |
phone_number_detection.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
try:
import regex
_regex_available = True
except ImportError:
_regex_available = False
import phonenumbers
from six.moves import zip
from language_utilities.constant import ENGLISH_LANG
from ner_v2.detectors.base_detector import B... | _calling_code": str(match.number.country_code),
"value": str(match.number.national_number)})
self.original_phone_text.append(self.text[match.start:match.end])
self.phone, self.original_phone_text = self.check_for_alphas()
return self.phone, self.origina... | tch.start:match.end])
else:
# This means our detector has detected some other country code.
self.phone.append({"country | conditional_block |
feature-detection.ts | export interface DetectedFeatures {
draggable:boolean;
dragEvents:boolean;
userAgentSupportingNativeDnD:boolean;
}
export function | ():DetectedFeatures {
let features:DetectedFeatures = {
dragEvents: ("ondragstart" in document.documentElement),
draggable: ("draggable" in document.documentElement),
userAgentSupportingNativeDnD: undefined
};
const isBlinkEngine = !!((<any>window).chrome) || /chrome/i.test( naviga... | detectFeatures | identifier_name |
feature-detection.ts | export interface DetectedFeatures {
draggable:boolean;
dragEvents:boolean;
userAgentSupportingNativeDnD:boolean;
}
export function detectFeatures():DetectedFeatures {
let features:DetectedFeatures = {
dragEvents: ("ondragstart" in document.documentElement),
draggable: ("draggable" in d... | let opts = Object.defineProperty( {}, "passive", {
get: function() {
supportsPassiveEventListeners = true;
}
} );
window.addEventListener( "test", null, opts );
}
// tslint:disable-next-line:no-empty
catch( e ) {
}
return supportsP... | try { | random_line_split |
feature-detection.ts | export interface DetectedFeatures {
draggable:boolean;
dragEvents:boolean;
userAgentSupportingNativeDnD:boolean;
}
export function detectFeatures():DetectedFeatures |
export function supportsPassiveEventListener():boolean {
let supportsPassiveEventListeners = false;
// reference https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
try {
let opts = Object.defineProperty( {}, "passive", {
get: function() {
supports... | {
let features:DetectedFeatures = {
dragEvents: ("ondragstart" in document.documentElement),
draggable: ("draggable" in document.documentElement),
userAgentSupportingNativeDnD: undefined
};
const isBlinkEngine = !!((<any>window).chrome) || /chrome/i.test( navigator.userAgent );
... | identifier_body |
Literature.js | const mongoose = require('mongoose')
let literatureSchema = mongoose.Schema({
category: { type: String, required: true},
name: { type: String, required: true },
description: { type: String },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, required: true, ... |
module.exports = Literature | const Literature = mongoose.model('Literature', literatureSchema) | random_line_split |
Literature.js | const mongoose = require('mongoose')
let literatureSchema = mongoose.Schema({
category: { type: String, required: true},
name: { type: String, required: true },
description: { type: String },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, required: true, ... |
})
}
}
})
literatureSchema.set('versionKey', false);
const Literature = mongoose.model('Literature', literatureSchema)
module.exports = Literature | {
let author = comment.author
let index = author.comments.indexOf(commentId)
let count = 1
author.comments.splice(index, count);
author.save()
comment.save()
} | conditional_block |
repeat_finder_RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G.py | import glob
import numpy as np
import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G*")
def between_range(row):
|
#newdf1 = pd.DataFrame()
for filename in annofiles:
df = pd.read_table(filename)
df["hg19_repeats"] = df.apply(between_range, axis = 1)
df.to_csv(str("repeatregions_") + filename + ".csv", index=False)
| subset = repeats.loc[(row["chr"] == repeats.chr) & (row.start >= repeats.start) & (row.start <= repeats.end), :]
if subset.empty:
return np.nan
return subset.repeat_class | identifier_body |
repeat_finder_RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G.py | import glob
import numpy as np
import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G*")
def between_range(row):
subset = repeats.... | df = pd.read_table(filename)
df["hg19_repeats"] = df.apply(between_range, axis = 1)
df.to_csv(str("repeatregions_") + filename + ".csv", index=False) | conditional_block | |
repeat_finder_RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G.py | import glob
import numpy as np
import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G*")
def | (row):
subset = repeats.loc[(row["chr"] == repeats.chr) & (row.start >= repeats.start) & (row.start <= repeats.end), :]
if subset.empty:
return np.nan
return subset.repeat_class
#newdf1 = pd.DataFrame()
for filename in annofiles:
df = pd.read_table(filename)
df["hg19_repeats"] = df.apply(be... | between_range | identifier_name |
repeat_finder_RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G.py | import glob | import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G*")
def between_range(row):
subset = repeats.loc[(row["chr"] == repeats.chr)... | import numpy as np | random_line_split |
vcs_link.py | """
VCS Link
########
Copyright (c) 2021 Nordic Semiconductor ASA
SPDX-License-Identifier: Apache-2.0
Introduction
============
This Sphinx extension can be used to obtain the VCS URL for a given Sphinx page.
This is useful, for example, when adding features like "Open on GitHub" on top
of pages. The extension insta... | app.add_config_value("vcs_link_base_url", "", "")
app.add_config_value("vcs_link_prefixes", {}, "")
app.add_config_value("vcs_link_exclude", [], "")
app.connect("builder-inited", add_jinja_filter)
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe... | identifier_body | |
vcs_link.py | """
VCS Link
########
Copyright (c) 2021 Nordic Semiconductor ASA
SPDX-License-Identifier: Apache-2.0
Introduction
============
This Sphinx extension can be used to obtain the VCS URL for a given Sphinx page.
This is useful, for example, when adding features like "Open on GitHub" on top
of pages. The extension insta... |
return "/".join(
[
app.config.vcs_link_base_url,
found_prefix,
app.env.project.doc2path(pagename, basedir=False),
]
)
def add_jinja_filter(app: Sphinx):
if app.builder.name != "html":
return
app.builder.templates.environment.filters["vcs_l... | found_prefix = prefix
break | conditional_block |
vcs_link.py | """
VCS Link
########
Copyright (c) 2021 Nordic Semiconductor ASA
SPDX-License-Identifier: Apache-2.0
Introduction
============
This Sphinx extension can be used to obtain the VCS URL for a given Sphinx page.
This is useful, for example, when adding features like "Open on GitHub" on top
of pages. The extension insta... | )
def setup(app: Sphinx):
app.add_config_value("vcs_link_base_url", "", "")
app.add_config_value("vcs_link_prefixes", {}, "")
app.add_config_value("vcs_link_exclude", [], "")
app.connect("builder-inited", add_jinja_filter)
return {
"version": __version__,
"parallel_read_safe"... | random_line_split | |
vcs_link.py | """
VCS Link
########
Copyright (c) 2021 Nordic Semiconductor ASA
SPDX-License-Identifier: Apache-2.0
Introduction
============
This Sphinx extension can be used to obtain the VCS URL for a given Sphinx page.
This is useful, for example, when adding features like "Open on GitHub" on top
of pages. The extension insta... | (app: Sphinx):
app.add_config_value("vcs_link_base_url", "", "")
app.add_config_value("vcs_link_prefixes", {}, "")
app.add_config_value("vcs_link_exclude", [], "")
app.connect("builder-inited", add_jinja_filter)
return {
"version": __version__,
"parallel_read_safe": True,
"... | setup | identifier_name |
campaigns.py | # Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
def get_object(self):
return self.campaign
def delete(self, request, *args, **kwargs):
"""
Deletes a campaign
Removes a ``Campaign`` and all associated ``Sample``
from the database.
**Tags**: survey
**Examples**
.. code-block:: http
... | """
serializer_class = CampaignSerializer | random_line_split |
campaigns.py | # Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... | (self, request, *args, **kwargs):
"""
Deletes a campaign
Removes a ``Campaign`` and all associated ``Sample``
from the database.
**Tags**: survey
**Examples**
.. code-block:: http
DELETE /api/cowork/campaign/best-practices/ HTTP/1.1
"""
... | delete | identifier_name |
campaigns.py | # Copyright (c) 2020, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... | """
Deletes a campaign
Removes a ``Campaign`` and all associated ``Sample``
from the database.
**Tags**: survey
**Examples**
.. code-block:: http
DELETE /api/cowork/campaign/best-practices/ HTTP/1.1
"""
#pylint:disable=useless-super-delega... | identifier_body | |
CallNodeContextMenu.test.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { Provider } from 'react-redux';
import copy from 'copy-to-clipboa... | () {
// Create a profile that every transform can be applied to.
const {
profile,
funcNamesDictPerThread: [{ A, B }],
} = getProfileFromTextSamples(`
A A A
B[lib:XUL] B[lib:XUL] B[lib:XUL]
B[lib:XUL] B[lib:XUL] B[lib:XUL]
B[lib:XUL] B[lib:XUL] B[... | createStore | identifier_name |
CallNodeContextMenu.test.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { Provider } from 'react-redux';
import copy from 'copy-to-clipboa... | import {
changeRightClickedCallNode,
changeExpandedCallNodes,
setContextMenuVisibility,
} from '../../actions/profile-view';
import { selectedThreadSelectors } from '../../selectors/per-thread';
import { ensureExists } from '../../utils/flow';
import { fireFullClick } from '../fixtures/utils';
describe('calltree... | import { CallNodeContextMenu } from '../../components/shared/CallNodeContextMenu';
import { storeWithProfile } from '../fixtures/stores';
import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile'; | random_line_split |
CallNodeContextMenu.test.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { Provider } from 'react-redux';
import copy from 'copy-to-clipboa... |
function setup(store = createStore(), openMenuState = true) {
store.dispatch(setContextMenuVisibility(openMenuState));
const renderResult = render(
<Provider store={store}>
<CallNodeContextMenu />
</Provider>
);
return { ...renderResult, getState: store.getState };
}
descr... | {
// Create a profile that every transform can be applied to.
const {
profile,
funcNamesDictPerThread: [{ A, B }],
} = getProfileFromTextSamples(`
A A A
B[lib:XUL] B[lib:XUL] B[lib:XUL]
B[lib:XUL] B[lib:XUL] B[lib:XUL]
B[lib:XUL] B[lib:XUL] B[lib... | identifier_body |
measured-input.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
@HostListener('keydown', ['$event'])
onKeyPress(e: KeyboardEvent) {
const { key, target } = e;
if (keyCheck(key, KEYS.Enter, KEYS.Escape)) {
e.preventDefault();
(target as HTMLElement).blur();
}
}
@HostListener('focus')
onfocus() {
if (this.measureOnFocus) this.update();
}
... | {
e.stopPropagation();
} | identifier_body |
measured-input.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | })
export class MeasuredInputComponent implements OnChanges, AfterViewInit {
private _measureOnFocus = false;
private _useDefaultFontStyle = false;
private _fontStyle = '';
private _value = '';
/** An optimization to bypass the expensive
* offscreen canvas and window.getComputedStyle */
@Input()
set ... | template: ``,
styleUrls: ['./measured-text.scss', './measured-input.component.scss'],
exportAs: 'cdMeasuredInput',
changeDetection: ChangeDetectionStrategy.OnPush, | random_line_split |
measured-input.component.ts | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | (e: KeyboardEvent) {
const { key, target } = e;
if (keyCheck(key, KEYS.Enter, KEYS.Escape)) {
e.preventDefault();
(target as HTMLElement).blur();
}
}
@HostListener('focus')
onfocus() {
if (this.measureOnFocus) this.update();
}
measureText(text: string) {
const { fontStyle } =... | onKeyPress | identifier_name |
jhelum.py | # Third-party
import numpy as np
import astropy.units as u
import astropy.coordinates as coord
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.matrix_utilities import matrix_transpose
__all__ = ["JhelumBonaca19"]
class JhelumBonaca19(coord.BaseCoordinateFrame):
"""
A Heliocent... |
# TODO: remove this. This is a hack required as of astropy v3.1 in order
# to have the longitude components wrap at the desired angle
def represent_as(self, base, s='base', in_frame_units=False):
r = super().represent_as(base, s=s, in_frame_units=in_frame_units)
if hasattr(r, "lon"):
... | self._data.lon.wrap_angle = self._default_wrap_angle | conditional_block |
jhelum.py | # Third-party
import numpy as np
import astropy.units as u
import astropy.coordinates as coord
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.matrix_utilities import matrix_transpose
|
class JhelumBonaca19(coord.BaseCoordinateFrame):
"""
A Heliocentric spherical coordinate system defined by the orbit
of the Jhelum stream, as described in
Bonaca et al. 2019.
For more information about this class, see the Astropy documentation
on coordinate frames in :mod:`~astropy.coordinates... | __all__ = ["JhelumBonaca19"]
| random_line_split |
jhelum.py | # Third-party
import numpy as np
import astropy.units as u
import astropy.coordinates as coord
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.matrix_utilities import matrix_transpose
__all__ = ["JhelumBonaca19"]
class JhelumBonaca19(coord.BaseCoordinateFrame):
"""
A Heliocent... | """ Compute the transformation from heliocentric Jhelum coordinates to
spherical ICRS.
"""
return matrix_transpose(icrs_to_jhelum()) | identifier_body | |
jhelum.py | # Third-party
import numpy as np
import astropy.units as u
import astropy.coordinates as coord
from astropy.coordinates import frame_transform_graph
from astropy.coordinates.matrix_utilities import matrix_transpose
__all__ = ["JhelumBonaca19"]
class JhelumBonaca19(coord.BaseCoordinateFrame):
"""
A Heliocent... | ():
""" Compute the transformation from Galactic spherical to
heliocentric Jhelum coordinates.
"""
return R
@frame_transform_graph.transform(coord.StaticMatrixTransform, JhelumBonaca19,
coord.ICRS)
def gd1_to_icrs():
""" Compute the transformation from heliocen... | icrs_to_jhelum | identifier_name |
main.rs | extern crate structopt;
#[macro_use]
extern crate structopt_derive;
use structopt::StructOpt;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Component {
input: usize,
output: usize,
}
imp... | (start: usize, components: &BTreeSet<Component>) -> usize {
components
.iter()
.filter_map(|component| {
if component.input == start {
let mut new_set = components.clone();
new_set.remove(component);
Some(
max_strength(c... | max_strength | identifier_name |
main.rs | extern crate structopt;
#[macro_use]
extern crate structopt_derive;
use structopt::StructOpt;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Component {
input: usize,
output: usize,
}
imp... | else {
vec![]
}
})
.collect()
}
fn part2(components: &BTreeSet<Component>) -> usize {
possibilities(0, components)
.into_iter()
.max_by(|a, b| {
a.len()
.cmp(&b.len())
.then_with(|| strength(a.clone()).cmp(&str... | {
let mut new_set = components.clone();
new_set.remove(component);
let mut ps = possibilities(component.input, &new_set);
for mut p in &mut ps {
p.push(component.flip());
}
ps.push(vec![*component]);
... | conditional_block |
main.rs | extern crate structopt;
#[macro_use]
extern crate structopt_derive;
use structopt::StructOpt;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Component {
input: usize,
output: usize,
}
imp... |
fn possibilities(
start: usize,
components: &BTreeSet<Component>,
) -> Vec<Vec<Component>> {
components
.iter()
.flat_map(|component| {
if component.input == start {
let mut new_set = components.clone();
new_set.remove(component);
... | {
max_strength(0, components)
} | identifier_body |
main.rs | extern crate structopt;
#[macro_use]
extern crate structopt_derive;
use structopt::StructOpt;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Component {
input: usize,
output: usize,
}
imp... |
fn max_strength(start: usize, components: &BTreeSet<Component>) -> usize {
components
.iter()
.filter_map(|component| {
if component.input == start {
let mut new_set = components.clone();
new_set.remove(component);
Some(
... | iter.into_iter().map(|c| c.input + c.output).sum()
} | random_line_split |
Lens.defaultTo.shouldNotCompile.ts | import { createLens } from '../src/createLens'
import { Lens, Updater } from '../src/Lens'
type TodoItem = {
title: string
done: boolean
}
type User = {
name: string
address: {
street: string
city: string
}
}
type Source = {
counter: number
todo: {
input: string
list: Tod... |
const source: Source = {} as any
const lens = createLens<Source>()
const counterLens = lens.focusPath('counter')
const todoLens = lens.focusPath('todo')
const todoListLens = todoLens.focusPath('list')
const todoListItemLens = todoListLens.focusIndex(0)
const userLens = lens.focusPath('user')
////////////////////////... | }
user: User | undefined
matrix: number[][]
} | random_line_split |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | () {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("test_symbols.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, ["GL_ARB_debug_output"])
.write_bindings(GlobalGenerator, &mut file)
.unwrap();
}
| main | identifier_name |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate gl_generator;
use gl_generator::*;
use std::env;
use st... | // Unless required by applicable law or agreed to in writing, software | random_line_split |
build.rs | // Copyright 2015 Brendan Zabarauskas and the gl-rs developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required b... | {
let dest = env::var("OUT_DIR").unwrap();
let mut file = File::create(&Path::new(&dest).join("test_symbols.rs")).unwrap();
Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, ["GL_ARB_debug_output"])
.write_bindings(GlobalGenerator, &mut file)
.unwrap();
} | identifier_body | |
soccer_PK_reward.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
import numpy as np
import soccer_PK.utils
rospy.init_node("reward")
pub = rospy.Publisher("reward", Float32, queue_size=10)
rate = rospy.Rate(3)
rospy.wait_for_service('/gazebo/get_model_state')
soccer_PK.utils.reset_world()
# intial postion
ball_p... | rospy.set_param("reward_value",[reward, done])
tic = rospy.get_time()
soccer_PK.utils.reset_world()
rospy.sleep(1)
# if the ball don't achieve goal
reward = (ball_prev - ball_locationx) / ball_prev
if prev_reward != reward:
rospy.set_pa... | random_line_split | |
soccer_PK_reward.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
import numpy as np
import soccer_PK.utils
rospy.init_node("reward")
pub = rospy.Publisher("reward", Float32, queue_size=10)
rate = rospy.Rate(3)
rospy.wait_for_service('/gazebo/get_model_state')
soccer_PK.utils.reset_world()
# intial postion
ball_p... |
prev_reward = reward
toc = rospy.get_time()
reward = -10
done = True
prev_reward = reward
# pub.publish(reward)
rospy.set_param("reward_value",[reward, done])
ball_locationx ,ball_locationy = soccer_PK.utils.get_ball_location()
f = open('episode_result.log', 'a')
f.write... | rospy.set_param("reward_value",[reward, done]) | conditional_block |
device.py | from __future__ import unicode_literals
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the ca... | """
from mezzanine.conf import settings
if not isinstance(templates, (list, tuple)):
templates = [templates]
device = device_from_request(request)
device_templates = []
for template in templates:
if device:
device_templates.append("%s/%s" % (device, template))
... | Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list. | random_line_split |
device.py | from __future__ import unicode_literals
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the ca... | (request, templates):
"""
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list.
"""
from mezzanine.conf import settings
if not isinstance(templates, (list, tuple)):
... | templates_for_device | identifier_name |
device.py | from __future__ import unicode_literals
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the ca... | """
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list.
"""
from mezzanine.conf import settings
if not isinstance(templates, (list, tuple)):
templates = [templ... | identifier_body | |
device.py | from __future__ import unicode_literals
def device_from_request(request):
"""
Determine's the device name from the request by first looking for an
overridding cookie, and if not found then matching the user agent.
Used at both the template level for choosing the template to load and
also at the ca... |
return ""
def templates_for_device(request, templates):
"""
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list.
"""
from mezzanine.conf import settings
if n... | if ua_string.lower() in user_agent:
return device | conditional_block |
trainer_utils_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
@parameterized.named_parameters(('case1', 3, 4), ('case2', 3, 5),
('case3', 2, 3))
def test_create_federated_eval_fns_skips_rounds(self, rounds_per_eval,
round_num):
"""Test that create_federated_eval_fns skips the appropriate... | metrics_dict = eval_fn(server_state, 0)
self.assertEqual(list(metrics_dict.keys()), expected_keys) | conditional_block |
trainer_utils_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def get_input_spec():
return create_dataset().element_spec
def metrics_builder():
return [tf.keras.metrics.MeanSquaredError()]
def tff_model_builder():
return tff.learning.from_keras_model(
keras_model=keras_model_builder_with_zeros(),
input_spec=get_input_spec(),
loss=tf.keras.losses.Mea... | x1 = [[1.0]]
y1 = [[3.0]]
dataset1 = (x1, y1)
x2 = [[2.0]]
y2 = [[5.0]]
dataset2 = (x2, y2)
x3 = [[3.0]]
y3 = [[7.0]]
dataset3 = (x3, y3)
return tff.simulation.datasets.TestClientData({
1: dataset1,
2: dataset2,
3: dataset3
}).preprocess(lambda ds: ds.batch(1)) | identifier_body |
trainer_utils_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ():
model = tf.keras.Sequential([
tf.keras.layers.Dense(
1,
kernel_initializer='ones',
bias_initializer='ones',
input_shape=(1,))
])
return model
def create_dataset():
# Create data satisfying y = 2*x + 1
x = [[1.0], [2.0], [3.0]]
y = [[3.0], [5.0], [7.0]]
r... | keras_model_builder_with_ones | identifier_name |
trainer_utils_test.py | # Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn)
for eval_fn in eval_fns_to_test:
metrics_dict = eval_fn(keras_model)
self.assertEqual(list(metrics_dict.keys()), expected_keys)
if __name__ == '__main__':
tf.test.main() | if use_test_cd:
self.assertIsNotNone(test_fn)
eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn, test_fn)
else:
self.assertIsNone(test_fn) | random_line_split |
karma.config.js | 'use strict';
|
module.exports = {
//This is the list of file patterns to load into the browser during testing.
files: [
baseDir + '/src/vendor/angular/angular.js',
baseDir + '/src/vendor/angular-mocks/angular-mocks.js',
baseDir + '/src/vendor/angular-ui-router/release/angular-ui-router.js',
baseDir + '/src/**/*.... | var baseDir = 'client'; | random_line_split |
BrothersRobes.js | const DrawCard = require('../../drawcard.js');
class BrothersRobes extends DrawCard {
setupCardAbilities() | }
}
BrothersRobes.code = '10043';
module.exports = BrothersRobes;
| {
this.attachmentRestriction({ trait: 'The Seven' });
this.reaction({
when: {
onCardKneeled: event => event.card === this.parent
},
target: {
activePrompTitle: 'Select a location or attachment',
cardCondition: card => ca... | identifier_body |
BrothersRobes.js | const DrawCard = require('../../drawcard.js');
class BrothersRobes extends DrawCard {
| () {
this.attachmentRestriction({ trait: 'The Seven' });
this.reaction({
when: {
onCardKneeled: event => event.card === this.parent
},
target: {
activePrompTitle: 'Select a location or attachment',
cardCondition: card =>... | setupCardAbilities | identifier_name |
BrothersRobes.js | const DrawCard = require('../../drawcard.js');
class BrothersRobes extends DrawCard {
setupCardAbilities() {
this.attachmentRestriction({ trait: 'The Seven' });
this.reaction({
when: { | },
target: {
activePrompTitle: 'Select a location or attachment',
cardCondition: card => card.location === 'play area' && ['location', 'attachment'].includes(card.getType())
},
handler: context => {
this.untilEndOfPhase(abil... | onCardKneeled: event => event.card === this.parent | random_line_split |
ioapic.rs | /* SPDX-License-Identifier: GPL-2.0-only */
// to do: add a channel such that a local apic can send messages to io apic.
use crate::err::Error;
use crate::hv::interrupt_vcpu;
use crate::{GuestThread, VCPU};
use crossbeam_channel::{Receiver, Sender};
#[allow(unused_imports)]
use log::*;
use std::sync::{Arc, Mutex, RwL... | let ioapic = ioapic.read().unwrap();
let vcpu_ids = vcpu_ids.read().unwrap();
let entry = ioapic.value[2 * irq as usize] as u64
| ((ioapic.value[2 * irq as usize + 1] as u64) << 32);
let vector = (entry & 0xff) as u8;
let dest = entry >> 56;
... | ioapic: Arc<RwLock<IoApic>>,
vcpu_ids: Arc<RwLock<Vec<u32>>>, // the actual Hypervisor vcpu id of each guest thread
) {
for irq in irq_receiver.iter() { | random_line_split |
ioapic.rs | /* SPDX-License-Identifier: GPL-2.0-only */
// to do: add a channel such that a local apic can send messages to io apic.
use crate::err::Error;
use crate::hv::interrupt_vcpu;
use crate::{GuestThread, VCPU};
use crossbeam_channel::{Receiver, Sender};
#[allow(unused_imports)]
use log::*;
use std::sync::{Arc, Mutex, RwL... |
}
pub fn ioapic_access(
_vcpu: &VCPU,
gth: &mut GuestThread,
gpa: usize,
reg_val: &mut u64,
_size: u8,
store: bool,
) -> Result<(), Error> {
let offset = gpa & 0xfffff;
if offset != 0 && offset != 0x10 {
error!(
"Bad register offset: {:x} and has to be 0x0 or 0x10",... | {
if offset == 0 {
self.reg
} else {
match self.reg {
0 => self.id,
1 => (IOAPIC_NUM_PINS << 16) | IOAPIC_VERSION, // 0x170011,
2 => self.arbid,
0x10..=IOAPIC_REG_MAX => self.value[self.reg as usize - 0x10],
... | identifier_body |
ioapic.rs | /* SPDX-License-Identifier: GPL-2.0-only */
// to do: add a channel such that a local apic can send messages to io apic.
use crate::err::Error;
use crate::hv::interrupt_vcpu;
use crate::{GuestThread, VCPU};
use crossbeam_channel::{Receiver, Sender};
#[allow(unused_imports)]
use log::*;
use std::sync::{Arc, Mutex, RwL... | (&self, offset: usize) -> u32 {
if offset == 0 {
self.reg
} else {
match self.reg {
0 => self.id,
1 => (IOAPIC_NUM_PINS << 16) | IOAPIC_VERSION, // 0x170011,
2 => self.arbid,
0x10..=IOAPIC_REG_MAX => self.value[self.... | read | identifier_name |
ioapic.rs | /* SPDX-License-Identifier: GPL-2.0-only */
// to do: add a channel such that a local apic can send messages to io apic.
use crate::err::Error;
use crate::hv::interrupt_vcpu;
use crate::{GuestThread, VCPU};
use crossbeam_channel::{Receiver, Sender};
#[allow(unused_imports)]
use log::*;
use std::sync::{Arc, Mutex, RwL... |
let ioapic = >h.vm.ioapic;
if store {
ioapic.write().unwrap().write(offset, *reg_val as u32);
} else {
*reg_val = ioapic.read().unwrap().read(offset) as u64;
}
Ok(())
}
| {
error!(
"Bad register offset: {:x} and has to be 0x0 or 0x10",
offset
);
return Ok(());
} | conditional_block |
conf.py | # -*- coding: utf-8 -*-
#
# Viper documentation build configuration file, created by
# sphinx-quickstart on Mon May 5 18:24:15 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | #html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_fav... | # A shorter title for the navigation bar. Default is the same as html_title. | random_line_split |
dragscroll.js | /**
* @fileoverview dragscroll - scroll area by dragging
* @version 0.0.6
*
* @license MIT, see http://github.com/asvd/intence
* @copyright 2015 asvd <heliosframework@gmail.com>
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} els... | lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}, 0
);
_window[addEventListener](
mouseup, cont.mu = function() {... | ) == cont
) {
pushed = 1; | random_line_split |
meminfo.rs | extern crate linux_stats;
use linux_stats::MemInfo;
const MEMINFO_1: MemInfo = MemInfo {
mem_total: 3521920,
mem_free: 1878240,
mem_available: 2275916,
bufers: 35428,
cached: 386132,
swap_cached: 0,
active: 134352,
inactive: 266336,
active_anon: 1094728,
inactive_anon: 17664,
... | () {
assert_eq!("".parse::<MemInfo>().unwrap(), Default::default());
}
#[test]
fn meminfo_1() {
assert_eq!(MEMINFO_1_RAW.parse::<MemInfo>().unwrap(), MEMINFO_1);
}
#[test]
fn meminfo_2() {
assert_eq!(MEMINFO_2_RAW.parse::<MemInfo>().unwrap(), MEMINFO_2);
}
| meminfo_empty | identifier_name |
meminfo.rs | extern crate linux_stats;
use linux_stats::MemInfo;
const MEMINFO_1: MemInfo = MemInfo {
mem_total: 3521920,
mem_free: 1878240,
mem_available: 2275916,
bufers: 35428,
cached: 386132,
swap_cached: 0,
active: 134352,
inactive: 266336,
active_anon: 1094728,
inactive_anon: 17664,
... | huge_pages_total: 0,
huge_pages_free: 0,
huge_pages_rsvd: 0,
huge_pages_surp: 0,
hugepagesize: 2048,
direct_map_4k: 67520,
direct_map_2m: 3602432,
};
const MEMINFO_2: MemInfo = MemInfo {
mem_total: 32828552,
mem_free: 12195628,
mem_available: 13725248,
bufers: 185048,
ca... | random_line_split | |
meminfo.rs | extern crate linux_stats;
use linux_stats::MemInfo;
const MEMINFO_1: MemInfo = MemInfo {
mem_total: 3521920,
mem_free: 1878240,
mem_available: 2275916,
bufers: 35428,
cached: 386132,
swap_cached: 0,
active: 134352,
inactive: 266336,
active_anon: 1094728,
inactive_anon: 17664,
... |
#[test]
fn meminfo_1() {
assert_eq!(MEMINFO_1_RAW.parse::<MemInfo>().unwrap(), MEMINFO_1);
}
#[test]
fn meminfo_2() {
assert_eq!(MEMINFO_2_RAW.parse::<MemInfo>().unwrap(), MEMINFO_2);
}
| {
assert_eq!("".parse::<MemInfo>().unwrap(), Default::default());
} | identifier_body |
process.py | from tornado.process import cpu_count, _reseed_random
from tornado import ioloop
import logging
import os
import signal
import sys
from tornado.util import errno_from_exception
import errno
logger = logging.getLogger(__name__)
_task_id = None
exiting = False
def fork_processes(num_processes, max_restar... | (i):
pid = os.fork()
if pid == 0:
# child process
_reseed_random()
global _task_id
_task_id = i
return i
else:
children[pid] = i
return None
for i in range(num_processes):
id = start_chi... | start_child | identifier_name |
process.py | from tornado.process import cpu_count, _reseed_random
from tornado import ioloop
import logging
import os
import signal
import sys
from tornado.util import errno_from_exception
import errno
logger = logging.getLogger(__name__)
_task_id = None
exiting = False
def fork_processes(num_processes, max_restar... |
signal.signal(signal.SIGTERM, receive_signal)
signal.signal(signal.SIGINT, receive_signal)
num_restarts = 0
while children and not exiting:
logger.debug('Exiting : %s' % exiting)
try:
pid, status = os.wait()
except OSError as e:
if errno_from... | os.kill(pid, signal.SIGTERM) | conditional_block |
process.py | from tornado.process import cpu_count, _reseed_random
from tornado import ioloop
import logging
import os
import signal
import sys
from tornado.util import errno_from_exception
import errno
logger = logging.getLogger(__name__)
_task_id = None
exiting = False
def fork_processes(num_processes, max_restar... |
signal.signal(signal.SIGTERM, receive_signal)
signal.signal(signal.SIGINT, receive_signal)
num_restarts = 0
while children and not exiting:
logger.debug('Exiting : %s' % exiting)
try:
pid, status = os.wait()
except OSError as e:
if errno_from... | logger.debug('Received signal')
global exiting
exiting = True
for pid, taskid in children.items():
os.kill(pid, signal.SIGTERM) | identifier_body |
process.py | from tornado.process import cpu_count, _reseed_random
from tornado import ioloop
import logging
import os
import signal
import sys
from tornado.util import errno_from_exception
import errno
logger = logging.getLogger(__name__)
_task_id = None
exiting = False
def fork_processes(num_processes, max_restar... | Note that multiple processes are not compatible with the autoreload
module (or the ``autoreload=True`` option to `tornado.web.Application`
which defaults to True when ``debug=True``).
When using multiple processes, no IOLoops can be created or
referenced until after the call to ``fork_processes`... | specific number of sub-processes.
Since we use processes and not threads, there is no shared memory
between any server code.
| random_line_split |
index.js | /*
* Copyright 2012-2015 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language go... | * | random_line_split |
jss-plugin-props-sort.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jssPluginPropsSort = {}));
}(this, (... | () {
var sort = function sort(prop0, prop1) {
if (prop0.length === prop1.length) {
return prop0 > prop1 ? 1 : -1;
}
return prop0.length - prop1.length;
};
return {
onProcessStyle: function onProcessStyle(style, rule) {
if (rule.type !== 'style') return style;
... | jssPropsSort | identifier_name |
jss-plugin-props-sort.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jssPluginPropsSort = {}));
}(this, (... | }
};
}
exports.default = jssPropsSort;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=jss-plugin-props-sort.js.map
| {
var sort = function sort(prop0, prop1) {
if (prop0.length === prop1.length) {
return prop0 > prop1 ? 1 : -1;
}
return prop0.length - prop1.length;
};
return {
onProcessStyle: function onProcessStyle(style, rule) {
if (rule.type !== 'style') return style;
v... | identifier_body |
jss-plugin-props-sort.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jssPluginPropsSort = {}));
}(this, (... |
return newStyle;
}
};
}
exports.default = jssPropsSort;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=jss-plugin-props-sort.js.map
| {
newStyle[props[i]] = style[props[i]];
} | conditional_block |
jss-plugin-props-sort.js | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jssPluginPropsSort = {}));
}(this, (... | var props = Object.keys(style).sort(sort);
for (var i = 0; i < props.length; i++) {
newStyle[props[i]] = style[props[i]];
}
return newStyle;
}
};
}
exports.default = jssPropsSort;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sour... |
return {
onProcessStyle: function onProcessStyle(style, rule) {
if (rule.type !== 'style') return style;
var newStyle = {}; | random_line_split |
dependency.py | # Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... | Execute the actions that should run prior to a converge and return a
tuple.
:param exit: (Unused) Provided to complete method signature.
:return: Return a tuple provided by :meth:`.AnsiblePlaybook.execute`.
"""
debug = self.args.get('debug')
if self.molecule.stat... | def execute(self, exit=True):
""" | random_line_split |
dependency.py | # Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... |
return (None, None)
@click.command()
@click.pass_context
def dependency(ctx): # pragma: no cover
""" Perform dependent actions on the current role. """
d = Dependency(ctx.obj.get('args'), {})
d.execute
util.sysexit(d.execute()[0])
| dd = self.molecule.config.config.get('dependency')
if dd.get('command'):
msg = "Downloading dependencies with '{}'...".format(
dependency_name)
util.print_info(msg)
s = shell.Shell(self.molecule.config.config, debug=debug)
s... | conditional_block |
dependency.py | # Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... | """ Perform dependent actions on the current role. """
d = Dependency(ctx.obj.get('args'), {})
d.execute
util.sysexit(d.execute()[0]) | identifier_body | |
dependency.py | # Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge... | (base.Base):
def execute(self, exit=True):
"""
Execute the actions that should run prior to a converge and return a
tuple.
:param exit: (Unused) Provided to complete method signature.
:return: Return a tuple provided by :meth:`.AnsiblePlaybook.execute`.
"""
d... | Dependency | identifier_name |
__openerp__.py | # -*- coding: utf-8 -*-
############################################################################## | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that... | #
# Author: Yannick Vaucher
# Copyright 2013 Camptocamp SA | random_line_split |
plugin-more-menu-item.d.ts | import { Dashicon, MenuItem } from '@wordpress/components';
import { ComponentType, ReactNode } from 'react';
declare namespace PluginMoreMenuItem {
interface Props extends Omit<MenuItem.Props, 'href'> {
children: ReactNode;
/**
* When `href` is provided then the menu item is represented a... | }
/**
* Renders a menu item in `Plugins` group in `More Menu` drop down, and can be used to as a button
* or link depending on the props provided. The text within the component appears as the menu item
* label.
*
* @example
* ```jsx
* const { PluginMoreMenuItem } = wp.editPost;
*
* const MyButtonMoreMenuItem... | /**
* The callback function to be executed when the user clicks the menu item.
*/
onClick?(): void;
} | random_line_split |
fileset.py | 2]
return [f for f in mctx.subset if f in s]
def deleted(mctx, x):
"""``deleted()``
File that is deleted according to status.
"""
# i18n: "deleted" is a keyword
getargs(x, 0, 0, _("deleted takes no arguments"))
s = mctx.status()[3]
return [f for f in mctx.subset if f in s]
def unknown(... | s.append(f) | conditional_block | |
fileset.py | += 1
while pos < l: # find end of symbol
d = program[pos]
if not (d.isalnum() or d in globchars or ord(d) > 127):
break
pos += 1
sym = program[s:pos]
if sym in keywords: # operator keywords
yield (sy... |
def listset(mctx, a, b):
raise error.ParseError(_("can't use a list in this context"))
def modified(mctx, x):
"""``modified()``
File that is modified according to status.
"""
# i18n: "modified" is a keyword
getargs(x, 0, 0, _("modified takes no arguments"))
s = mctx.status()[0]
return... | s = set(getset(mctx, x))
return [r for r in mctx.subset if r not in s] | identifier_body |
fileset.py | += 1
while pos < l: # find end of symbol
d = program[pos]
if not (d.isalnum() or d in globchars or ord(d) > 127):
break
pos += 1
sym = program[s:pos]
if sym in keywords: # operator keywords
yield (sy... | (mctx, x):
"""``ignored()``
File that is ignored according to status. These files will only be
considered if this predicate is used.
"""
# i18n: "ignored" is a keyword
getargs(x, 0, 0, _("ignored takes no arguments"))
s = mctx.status()[5]
return [f for f in mctx.subset if f in s]
def cl... | ignored | identifier_name |
fileset.py | i18n: "modified" is a keyword
getargs(x, 0, 0, _("modified takes no arguments"))
s = mctx.status()[0]
return [f for f in mctx.subset if f in s]
def added(mctx, x):
"""``added()``
File that is added according to status.
"""
# i18n: "added" is a keyword
getargs(x, 0, 0, _("added takes no... | random_line_split | ||
harfbuzz.rs | (buffer: *mut hb_buffer_t) -> ShapedGlyphData {
unsafe {
let mut glyph_count = 0;
let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mut glyph_count);
assert!(!glyph_infos.is_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positio... | new | identifier_name | |
harfbuzz.rs | !("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyph_span = 0..0;
let mut byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ ... | Shaper::float_to_fixed(advance)
}
} | random_line_split | |
harfbuzz.rs | !(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
(*glyph_info_i).cluster
}
}
pub fn len(&self) -> usize {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn entr... | i);
}
debug!("{} -> {}", i, loc);
}
debug!("text: {:?}", text);
debug!("(char idx): char->(glyph index):");
for (i, ch) in text.char_indices() {
debug!("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyp... | {
let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len();
let byte_max = text.len();
debug!("Shaped text[byte count={}], got back {} glyph info records.",
byte_max,
glyph_count);
// make map of what chars have glyphs
... | identifier_body |
chemistry.py | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas ... |
else:
def wmean(g):
return (g.atomic_weight * g.percent).sum() / 100
iel = el.groupby('element').apply(wmean)
iel.name = 'atomic_weight'
return iel
def periodic_table():
"""
Loads dict containing all elements and associated metadata.
Scraped from https://w... | return el | conditional_block |
chemistry.py | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas ... | """
sw = {"Cl": 0.54586,
"SO4": 0.02824,
"Br": 0.00084,
"F": 0.00007,
"Na": 0.46906,
"Mg": 0.05282,
"Ca": 0.01028,
"K": 0.01021,
"Sr": 0.00009,
"B": 0.00042}
for s in sw.keys():
sw[s] *= Sal / 35.
... |
Returns
-------
Seawater composition in chosen units at specified salinity : dict | random_line_split |
chemistry.py | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas ... |
Returns
-------
Seawater composition in chosen units at specified salinity : dict
"""
sw = {"Cl": 0.54586,
"SO4": 0.02824,
"Br": 0.00084,
"F": 0.00007,
"Na": 0.46906,
"Mg": 0.05282,
"Ca": 0.01028,
"K": 0.01021,
"Sr... | """
Standard mean composition of seawater.
From Dickson, Sabine and Christian (2007), Chapter 5, Table 3
@book{dickson2007guide,
title={Guide to best practices for ocean CO2 measurements.},
author={Dickson, Andrew Gilmore and Sabine, Christopher L and Christian, James Robert},
... | identifier_body |
chemistry.py | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas ... | (molecule):
"""
Returns molecular weight of molecule.
Parameters
----------
molecule : str
A molecule in standard chemical notation,
e.g. 'CO2', 'HCO3' or 'B(OH)4'.
Returns
-------
Molecular weight of molecule : dict
"""
# load periodic table
els = elem... | calc_M | identifier_name |
4f8bd7cac829_clean_db.py | """Clean db
Revision ID: 4f8bd7cac829
Revises: 3f249e0d2769
Create Date: 2014-01-09 14:03:13.997656
"""
# revision identifiers, used by Alembic.
revision = '4f8bd7cac829'
down_revision = '3f249e0d2769'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Drop the columns calendar_multiple_meeting... | ():
''' Add the columns calendar_multiple_meetings and
calendar_regional_meetings and rename meeting_location into
meeting_region.
'''
op.add_column(
'calendars',
sa.Column(
'calendar_multiple_meetings',
sa.Boolean, default=False,
nullable=False
... | downgrade | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.