body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
3106eafbeb541ae8ab72e332c8724747e2c48824c08f5c6da25a74416b80b251 | def components_mass(self):
'Returns a dictionary with the mass of each a/c component'
factors = self.factors
areas = self.areas
MTOW = self.data['MTOW']
ME = self.data['ME']
area_w = areas['wing']
area_f = areas['fuselage']
area_v = areas['vertical_tail']
area_h = areas['horizontal_t... | Returns a dictionary with the mass of each a/c component | aircraft/cg_calculation.py | components_mass | iamlucassantos/tutorial-systems-engineering | 1 | python | def components_mass(self):
factors = self.factors
areas = self.areas
MTOW = self.data['MTOW']
ME = self.data['ME']
area_w = areas['wing']
area_f = areas['fuselage']
area_v = areas['vertical_tail']
area_h = areas['horizontal_tail']
mass = {}
mass['wing'] = (((factors['wing'] ... | def components_mass(self):
factors = self.factors
areas = self.areas
MTOW = self.data['MTOW']
ME = self.data['ME']
area_w = areas['wing']
area_f = areas['fuselage']
area_v = areas['vertical_tail']
area_h = areas['horizontal_tail']
mass = {}
mass['wing'] = (((factors['wing'] ... |
fbcbc6d56b3542174344054d409abf617b062f364bacf3401cc99652cd2c78e5 | def cg_distance_from_nose(self, x_loc, y, surface='w'):
'Returns the cg distance of the wing, vertical tail, and horizontal tail'
if (surface == 'w'):
tr = self.data['taper']
quarter_sweep = self.data['quart_sweep']
A = self.data['A']
distance_to_root = self.data['nose_distance_w... | Returns the cg distance of the wing, vertical tail, and horizontal tail | aircraft/cg_calculation.py | cg_distance_from_nose | iamlucassantos/tutorial-systems-engineering | 1 | python | def cg_distance_from_nose(self, x_loc, y, surface='w'):
if (surface == 'w'):
tr = self.data['taper']
quarter_sweep = self.data['quart_sweep']
A = self.data['A']
distance_to_root = self.data['nose_distance_w']
elif (surface == 'v'):
tr = self.data['taper_v']
q... | def cg_distance_from_nose(self, x_loc, y, surface='w'):
if (surface == 'w'):
tr = self.data['taper']
quarter_sweep = self.data['quart_sweep']
A = self.data['A']
distance_to_root = self.data['nose_distance_w']
elif (surface == 'v'):
tr = self.data['taper_v']
q... |
e3cefd562d14098d7a49ed613c46c24ad0c1a9e667184602b8b19e21ecd77230 | def chord_at_pctg(self, span_pctg, surface='w'):
"Returns the chord length at n% from the\n\n args:\n root_pctg (float): pctg of the root where the chord is wanted\n surface (str): 'w' for wing, 'v' for vertical tail, 'h' for horizontal tail\n "
if (surface == 'w'):
t... | Returns the chord length at n% from the
args:
root_pctg (float): pctg of the root where the chord is wanted
surface (str): 'w' for wing, 'v' for vertical tail, 'h' for horizontal tail | aircraft/cg_calculation.py | chord_at_pctg | iamlucassantos/tutorial-systems-engineering | 1 | python | def chord_at_pctg(self, span_pctg, surface='w'):
"Returns the chord length at n% from the\n\n args:\n root_pctg (float): pctg of the root where the chord is wanted\n surface (str): 'w' for wing, 'v' for vertical tail, 'h' for horizontal tail\n "
if (surface == 'w'):
t... | def chord_at_pctg(self, span_pctg, surface='w'):
"Returns the chord length at n% from the\n\n args:\n root_pctg (float): pctg of the root where the chord is wanted\n surface (str): 'w' for wing, 'v' for vertical tail, 'h' for horizontal tail\n "
if (surface == 'w'):
t... |
9b0d5cdb54c07464f7568be0c4a8c2c54504e94026bd29fd1b66ce6706bd769c | def components_cg(self):
'Returns a dictionary with the cg of each a/c component'
cgs = {}
(chord_cg_w, dist_le_w) = self.chord_at_pctg(0.4, surface='w')
cgs['wing'] = self.cg_distance_from_nose((chord_cg_w * 0.38), dist_le_w, surface='w')
(chord_cg_h, dist_le_h) = self.chord_at_pctg(0.38, surface='... | Returns a dictionary with the cg of each a/c component | aircraft/cg_calculation.py | components_cg | iamlucassantos/tutorial-systems-engineering | 1 | python | def components_cg(self):
cgs = {}
(chord_cg_w, dist_le_w) = self.chord_at_pctg(0.4, surface='w')
cgs['wing'] = self.cg_distance_from_nose((chord_cg_w * 0.38), dist_le_w, surface='w')
(chord_cg_h, dist_le_h) = self.chord_at_pctg(0.38, surface='h')
cgs['horizontal_tail'] = self.cg_distance_from_n... | def components_cg(self):
cgs = {}
(chord_cg_w, dist_le_w) = self.chord_at_pctg(0.4, surface='w')
cgs['wing'] = self.cg_distance_from_nose((chord_cg_w * 0.38), dist_le_w, surface='w')
(chord_cg_h, dist_le_h) = self.chord_at_pctg(0.38, surface='h')
cgs['horizontal_tail'] = self.cg_distance_from_n... |
440fad02280d4095b27f683ce56490a9320db817a7cfdd84bacde4250fb9b24c | def aircraft_cg(self):
'Returns the aircraft cg wrt the three main groups: wing, fuselage and tail'
(numerator, denominator) = (0, 0)
for group in ['wing', 'horizontal_tail', 'vertical_tail', 'fuselage']:
numerator += (self.mass[group] * self.cgs[group])
denominator += self.mass[group]
X... | Returns the aircraft cg wrt the three main groups: wing, fuselage and tail | aircraft/cg_calculation.py | aircraft_cg | iamlucassantos/tutorial-systems-engineering | 1 | python | def aircraft_cg(self):
(numerator, denominator) = (0, 0)
for group in ['wing', 'horizontal_tail', 'vertical_tail', 'fuselage']:
numerator += (self.mass[group] * self.cgs[group])
denominator += self.mass[group]
XLEMAC = self.data['XLEMAC']
mac = self.data['mac']
aircraft_cg = (((... | def aircraft_cg(self):
(numerator, denominator) = (0, 0)
for group in ['wing', 'horizontal_tail', 'vertical_tail', 'fuselage']:
numerator += (self.mass[group] * self.cgs[group])
denominator += self.mass[group]
XLEMAC = self.data['XLEMAC']
mac = self.data['mac']
aircraft_cg = (((... |
302833e0cf4d4c1ebb9e39018f87d42aed0af929694eea631afccdc9474e17f2 | def check_projects(config: Configuration, username: str) -> Dict[(str, Any)]:
" Crawl through all projects to check for errors on loading or accessing imporant fields.\n Warning: This method may take a while.\n\n Args:\n config: Configuration to include root gigantum directory\n username: Active... | Crawl through all projects to check for errors on loading or accessing imporant fields.
Warning: This method may take a while.
Args:
config: Configuration to include root gigantum directory
username: Active username - if none provided crawl for all users.
Returns:
Dictionary mapping a project path to erro... | packages/gtmapi/lmsrvcore/telemetry.py | check_projects | gigabackup/gigantum-client | 60 | python | def check_projects(config: Configuration, username: str) -> Dict[(str, Any)]:
" Crawl through all projects to check for errors on loading or accessing imporant fields.\n Warning: This method may take a while.\n\n Args:\n config: Configuration to include root gigantum directory\n username: Active... | def check_projects(config: Configuration, username: str) -> Dict[(str, Any)]:
" Crawl through all projects to check for errors on loading or accessing imporant fields.\n Warning: This method may take a while.\n\n Args:\n config: Configuration to include root gigantum directory\n username: Active... |
ac2455b0a0cf732ab3a2c13842720189e28afd0040f1d9b8296a2b7e5884aff3 | def _calc_disk_free_gb() -> Tuple[(float, float)]:
'Call `df` from the Client Container, parse and return as GB'
disk_results = call_subprocess('df -BMB /'.split(), cwd='/').split('\n')
(_, disk_size, disk_used, disk_avail, use_pct, _) = disk_results[1].split()
(disk_size_num, disk_size_unit) = ((float(... | Call `df` from the Client Container, parse and return as GB | packages/gtmapi/lmsrvcore/telemetry.py | _calc_disk_free_gb | gigabackup/gigantum-client | 60 | python | def _calc_disk_free_gb() -> Tuple[(float, float)]:
disk_results = call_subprocess('df -BMB /'.split(), cwd='/').split('\n')
(_, disk_size, disk_used, disk_avail, use_pct, _) = disk_results[1].split()
(disk_size_num, disk_size_unit) = ((float(disk_used[:(- 2)]) / 1000), disk_used[(- 2):])
if (disk_s... | def _calc_disk_free_gb() -> Tuple[(float, float)]:
disk_results = call_subprocess('df -BMB /'.split(), cwd='/').split('\n')
(_, disk_size, disk_used, disk_avail, use_pct, _) = disk_results[1].split()
(disk_size_num, disk_size_unit) = ((float(disk_used[:(- 2)]) / 1000), disk_used[(- 2):])
if (disk_s... |
a59b915eb3ac772617bb6bf12cd2a896b97c44a57a47ef4c3da4c3a7e8a4196b | def _calc_rq_free() -> Dict[(str, Any)]:
'Parses the output of `rq info` to return total number\n of workers and the count of workers currently idle.'
conn = default_redis_conn()
with rq.Connection(connection=conn):
workers: List[rq.Worker] = [w for w in rq.Worker.all()]
idle_workers = [w for... | Parses the output of `rq info` to return total number
of workers and the count of workers currently idle. | packages/gtmapi/lmsrvcore/telemetry.py | _calc_rq_free | gigabackup/gigantum-client | 60 | python | def _calc_rq_free() -> Dict[(str, Any)]:
'Parses the output of `rq info` to return total number\n of workers and the count of workers currently idle.'
conn = default_redis_conn()
with rq.Connection(connection=conn):
workers: List[rq.Worker] = [w for w in rq.Worker.all()]
idle_workers = [w for... | def _calc_rq_free() -> Dict[(str, Any)]:
'Parses the output of `rq info` to return total number\n of workers and the count of workers currently idle.'
conn = default_redis_conn()
with rq.Connection(connection=conn):
workers: List[rq.Worker] = [w for w in rq.Worker.all()]
idle_workers = [w for... |
ca900bf67765f13253be83262caba7d1985444b91a68bcd10a2257938b4d1fdf | def get_conv_mixer_256_8(image_size=32, filters=256, depth=8, kernel_size=5, patch_size=2, num_classes=10):
'ConvMixer-256/8: https://openreview.net/pdf?id=TVHS5Y4dNvM.\n The hyperparameter values are taken from the paper.\n '
inputs = keras.Input((image_size, image_size, 3))
x = layers.Rescaling(scal... | ConvMixer-256/8: https://openreview.net/pdf?id=TVHS5Y4dNvM.
The hyperparameter values are taken from the paper. | examples/vision/convmixer.py | get_conv_mixer_256_8 | k-w-w/keras-io | 1,542 | python | def get_conv_mixer_256_8(image_size=32, filters=256, depth=8, kernel_size=5, patch_size=2, num_classes=10):
'ConvMixer-256/8: https://openreview.net/pdf?id=TVHS5Y4dNvM.\n The hyperparameter values are taken from the paper.\n '
inputs = keras.Input((image_size, image_size, 3))
x = layers.Rescaling(scal... | def get_conv_mixer_256_8(image_size=32, filters=256, depth=8, kernel_size=5, patch_size=2, num_classes=10):
'ConvMixer-256/8: https://openreview.net/pdf?id=TVHS5Y4dNvM.\n The hyperparameter values are taken from the paper.\n '
inputs = keras.Input((image_size, image_size, 3))
x = layers.Rescaling(scal... |
025fe97f88ae7c95b6878c52fe0c1c65f60131a3935b4baffa47bc0596938038 | def __init__(self, device='cpu'):
"\n Initialize the class.\n\n Parameters\n ----------\n device : str, optional\n The device where to put the data. The default is 'cpu'.\n "
self.device = device | Initialize the class.
Parameters
----------
device : str, optional
The device where to put the data. The default is 'cpu'. | profrage/generate/reconstruct.py | __init__ | federicoVS/ProFraGe | 0 | python | def __init__(self, device='cpu'):
"\n Initialize the class.\n\n Parameters\n ----------\n device : str, optional\n The device where to put the data. The default is 'cpu'.\n "
self.device = device | def __init__(self, device='cpu'):
"\n Initialize the class.\n\n Parameters\n ----------\n device : str, optional\n The device where to put the data. The default is 'cpu'.\n "
self.device = device<|docstring|>Initialize the class.
Parameters
----------
device : str,... |
94e5b958af674dafdd29fa82601efb387902990a67b053f3be1c2f49c6474eb2 | def reconstruct(self, D):
'\n Multidimensional scaling algorithm to reconstruct the data.\n\n Parameters\n ----------\n D : torch.Tensor\n The distance matrix.\n\n Returns\n -------\n X : numpy.ndarray\n The coordinate matrix.\n '
n =... | Multidimensional scaling algorithm to reconstruct the data.
Parameters
----------
D : torch.Tensor
The distance matrix.
Returns
-------
X : numpy.ndarray
The coordinate matrix. | profrage/generate/reconstruct.py | reconstruct | federicoVS/ProFraGe | 0 | python | def reconstruct(self, D):
'\n Multidimensional scaling algorithm to reconstruct the data.\n\n Parameters\n ----------\n D : torch.Tensor\n The distance matrix.\n\n Returns\n -------\n X : numpy.ndarray\n The coordinate matrix.\n '
n =... | def reconstruct(self, D):
'\n Multidimensional scaling algorithm to reconstruct the data.\n\n Parameters\n ----------\n D : torch.Tensor\n The distance matrix.\n\n Returns\n -------\n X : numpy.ndarray\n The coordinate matrix.\n '
n =... |
1f4c2a7cd419b43e669528a76e0a3cef7a227a0ceb8d8e1659ae44029701d2c1 | def get_activation(activation):
' returns the activation function represented by the input string '
if (activation and callable(activation)):
return activation
activation = [x for x in SUPPORTED_ACTIVATION_MAP if (activation.lower() == x.lower())]
assert ((len(activation) == 1) and isinstance(ac... | returns the activation function represented by the input string | util/ml_and_math/layers.py | get_activation | pchlenski/NeuroSEED | 39 | python | def get_activation(activation):
' '
if (activation and callable(activation)):
return activation
activation = [x for x in SUPPORTED_ACTIVATION_MAP if (activation.lower() == x.lower())]
assert ((len(activation) == 1) and isinstance(activation[0], str)), 'Unhandled activation function'
activat... | def get_activation(activation):
' '
if (activation and callable(activation)):
return activation
activation = [x for x in SUPPORTED_ACTIVATION_MAP if (activation.lower() == x.lower())]
assert ((len(activation) == 1) and isinstance(activation[0], str)), 'Unhandled activation function'
activat... |
c5f0267fc9445900c179cf67705c8f8b42063d68fd015c1d5642e8aa6aa9de57 | def kronecker_product(t1, t2):
'\n Computes the Kronecker product between two tensors\n See https://en.wikipedia.org/wiki/Kronecker_product\n '
(t1_height, t1_width) = t1.size()
(t2_height, t2_width) = t2.size()
out_height = (t1_height * t2_height)
out_width = (t1_width * t2_width)
tile... | Computes the Kronecker product between two tensors
See https://en.wikipedia.org/wiki/Kronecker_product | rlkit/torch/pytorch_util.py | kronecker_product | Asap7772/railrl_evalsawyer | 0 | python | def kronecker_product(t1, t2):
'\n Computes the Kronecker product between two tensors\n See https://en.wikipedia.org/wiki/Kronecker_product\n '
(t1_height, t1_width) = t1.size()
(t2_height, t2_width) = t2.size()
out_height = (t1_height * t2_height)
out_width = (t1_width * t2_width)
tile... | def kronecker_product(t1, t2):
'\n Computes the Kronecker product between two tensors\n See https://en.wikipedia.org/wiki/Kronecker_product\n '
(t1_height, t1_width) = t1.size()
(t2_height, t2_width) = t2.size()
out_height = (t1_height * t2_height)
out_width = (t1_width * t2_width)
tile... |
d28344d44185fa1ad322933efa05b19b702bc4ca0b4c38d12b188d9535443996 | def double_moments(x, y):
'\n Returns the first two moments between x and y.\n\n Specifically, for each vector x_i and y_i in x and y, compute their\n outer-product. Flatten this resulting matrix and return it.\n\n The first moments (i.e. x_i and y_i) are included by appending a `1` to x_i\n and y_i ... | Returns the first two moments between x and y.
Specifically, for each vector x_i and y_i in x and y, compute their
outer-product. Flatten this resulting matrix and return it.
The first moments (i.e. x_i and y_i) are included by appending a `1` to x_i
and y_i before taking the outer product.
:param x: Shape [batch_siz... | rlkit/torch/pytorch_util.py | double_moments | Asap7772/railrl_evalsawyer | 0 | python | def double_moments(x, y):
'\n Returns the first two moments between x and y.\n\n Specifically, for each vector x_i and y_i in x and y, compute their\n outer-product. Flatten this resulting matrix and return it.\n\n The first moments (i.e. x_i and y_i) are included by appending a `1` to x_i\n and y_i ... | def double_moments(x, y):
'\n Returns the first two moments between x and y.\n\n Specifically, for each vector x_i and y_i in x and y, compute their\n outer-product. Flatten this resulting matrix and return it.\n\n The first moments (i.e. x_i and y_i) are included by appending a `1` to x_i\n and y_i ... |
ced03cdd42ac0e5224f8fbcd46f362d08762ed0550e44fcc883ea5b9344d0049 | def batch_square_vector(vector, M):
'\n Compute x^T M x\n '
vector = vector.unsqueeze(2)
return torch.bmm(torch.bmm(vector.transpose(2, 1), M), vector).squeeze(2) | Compute x^T M x | rlkit/torch/pytorch_util.py | batch_square_vector | Asap7772/railrl_evalsawyer | 0 | python | def batch_square_vector(vector, M):
'\n \n '
vector = vector.unsqueeze(2)
return torch.bmm(torch.bmm(vector.transpose(2, 1), M), vector).squeeze(2) | def batch_square_vector(vector, M):
'\n \n '
vector = vector.unsqueeze(2)
return torch.bmm(torch.bmm(vector.transpose(2, 1), M), vector).squeeze(2)<|docstring|>Compute x^T M x<|endoftext|> |
ba33e708327ebdc8e6f5e67d22e93c1d7e2e18b638800ed7c621916fd3f00c74 | def almost_identity_weights_like(tensor):
'\n Set W = I + lambda * Gaussian no\n :param tensor:\n :return:\n '
shape = tensor.size()
init_value = np.eye(*shape)
init_value += (0.01 * np.random.rand(*shape))
return FloatTensor(init_value) | Set W = I + lambda * Gaussian no
:param tensor:
:return: | rlkit/torch/pytorch_util.py | almost_identity_weights_like | Asap7772/railrl_evalsawyer | 0 | python | def almost_identity_weights_like(tensor):
'\n Set W = I + lambda * Gaussian no\n :param tensor:\n :return:\n '
shape = tensor.size()
init_value = np.eye(*shape)
init_value += (0.01 * np.random.rand(*shape))
return FloatTensor(init_value) | def almost_identity_weights_like(tensor):
'\n Set W = I + lambda * Gaussian no\n :param tensor:\n :return:\n '
shape = tensor.size()
init_value = np.eye(*shape)
init_value += (0.01 * np.random.rand(*shape))
return FloatTensor(init_value)<|docstring|>Set W = I + lambda * Gaussian no
:para... |
c38b313289f5e8b362267c52342a2a59e06247fd246ed0a0909c5756fcc052fa | def debounce(func):
'Decorator function. Debounce callbacks form HomeKit.'
@ha_callback
def call_later_listener(self, *args):
'Callback listener called from call_later.'
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(... | Decorator function. Debounce callbacks form HomeKit. | homeassistant/components/homekit/accessories.py | debounce | ellsclytn/home-assistant | 0 | python | def debounce(func):
@ha_callback
def call_later_listener(self, *args):
'Callback listener called from call_later.'
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(func, self, *debounce_params[1:])
@wraps(func)
... | def debounce(func):
@ha_callback
def call_later_listener(self, *args):
'Callback listener called from call_later.'
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(func, self, *debounce_params[1:])
@wraps(func)
... |
3226cf1f407d093140dfe2ac02425aff41bef4d7fe928b81d0dee389235c986f | @ha_callback
def call_later_listener(self, *args):
'Callback listener called from call_later.'
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(func, self, *debounce_params[1:]) | Callback listener called from call_later. | homeassistant/components/homekit/accessories.py | call_later_listener | ellsclytn/home-assistant | 0 | python | @ha_callback
def call_later_listener(self, *args):
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(func, self, *debounce_params[1:]) | @ha_callback
def call_later_listener(self, *args):
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
self.hass.async_add_job(func, self, *debounce_params[1:])<|docstring|>Callback listener called from call_later.<|endoftext|> |
dfdba27c96f0d278201e3ef3cfe07de3e5e8c377c09fbb8d30180392e33fb67d | @wraps(func)
def wrapper(self, *args):
'Wrapper starts async timer.'
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
debounce_params[0]()
remove_listener = track_point_in_utc_time(self.hass, partial(call_later_listener, self), (dt_util.utcnow() + timedelta(seconds=DE... | Wrapper starts async timer. | homeassistant/components/homekit/accessories.py | wrapper | ellsclytn/home-assistant | 0 | python | @wraps(func)
def wrapper(self, *args):
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
debounce_params[0]()
remove_listener = track_point_in_utc_time(self.hass, partial(call_later_listener, self), (dt_util.utcnow() + timedelta(seconds=DEBOUNCE_TIMEOUT)))
self.de... | @wraps(func)
def wrapper(self, *args):
debounce_params = self.debounce.pop(func.__name__, None)
if debounce_params:
debounce_params[0]()
remove_listener = track_point_in_utc_time(self.hass, partial(call_later_listener, self), (dt_util.utcnow() + timedelta(seconds=DEBOUNCE_TIMEOUT)))
self.de... |
27dc5ad998c7b411c16f952e6feb93d7fba869c61b81ccd3a6c2b38eb9fae159 | def __init__(self, hass, driver, name, entity_id, aid, config, category=CATEGORY_OTHER):
'Initialize a Accessory object.'
super().__init__(driver, name, aid=aid)
model = split_entity_id(entity_id)[0].replace('_', ' ').title()
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER... | Initialize a Accessory object. | homeassistant/components/homekit/accessories.py | __init__ | ellsclytn/home-assistant | 0 | python | def __init__(self, hass, driver, name, entity_id, aid, config, category=CATEGORY_OTHER):
super().__init__(driver, name, aid=aid)
model = split_entity_id(entity_id)[0].replace('_', ' ').title()
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER, model=model, serial_number=ent... | def __init__(self, hass, driver, name, entity_id, aid, config, category=CATEGORY_OTHER):
super().__init__(driver, name, aid=aid)
model = split_entity_id(entity_id)[0].replace('_', ' ').title()
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER, model=model, serial_number=ent... |
d017fed2018cf8f6b20a861835cacb617112b5b70d038c66f5d8c947a4def09c | async def run(self):
'Method called by accessory after driver is started.\n\n Run inside the HAP-python event loop.\n '
state = self.hass.states.get(self.entity_id)
self.hass.add_job(self.update_state_callback, None, None, state)
async_track_state_change(self.hass, self.entity_id, self.upd... | Method called by accessory after driver is started.
Run inside the HAP-python event loop. | homeassistant/components/homekit/accessories.py | run | ellsclytn/home-assistant | 0 | python | async def run(self):
'Method called by accessory after driver is started.\n\n Run inside the HAP-python event loop.\n '
state = self.hass.states.get(self.entity_id)
self.hass.add_job(self.update_state_callback, None, None, state)
async_track_state_change(self.hass, self.entity_id, self.upd... | async def run(self):
'Method called by accessory after driver is started.\n\n Run inside the HAP-python event loop.\n '
state = self.hass.states.get(self.entity_id)
self.hass.add_job(self.update_state_callback, None, None, state)
async_track_state_change(self.hass, self.entity_id, self.upd... |
5206ec7f6ef4475a6445e3773e31172a3db0902c91b7b2102b2af99405c19554 | @ha_callback
def update_state_callback(self, entity_id=None, old_state=None, new_state=None):
'Callback from state change listener.'
_LOGGER.debug('New_state: %s', new_state)
if (new_state is None):
return
self.hass.async_add_job(self.update_state, new_state) | Callback from state change listener. | homeassistant/components/homekit/accessories.py | update_state_callback | ellsclytn/home-assistant | 0 | python | @ha_callback
def update_state_callback(self, entity_id=None, old_state=None, new_state=None):
_LOGGER.debug('New_state: %s', new_state)
if (new_state is None):
return
self.hass.async_add_job(self.update_state, new_state) | @ha_callback
def update_state_callback(self, entity_id=None, old_state=None, new_state=None):
_LOGGER.debug('New_state: %s', new_state)
if (new_state is None):
return
self.hass.async_add_job(self.update_state, new_state)<|docstring|>Callback from state change listener.<|endoftext|> |
bce0ddc35f700ff7b1d55480e931900cc9c02dce11bcf7d7d9e25a7ffa83b9af | def update_state(self, new_state):
'Method called on state change to update HomeKit value.\n\n Overridden by accessory types.\n '
raise NotImplementedError() | Method called on state change to update HomeKit value.
Overridden by accessory types. | homeassistant/components/homekit/accessories.py | update_state | ellsclytn/home-assistant | 0 | python | def update_state(self, new_state):
'Method called on state change to update HomeKit value.\n\n Overridden by accessory types.\n '
raise NotImplementedError() | def update_state(self, new_state):
'Method called on state change to update HomeKit value.\n\n Overridden by accessory types.\n '
raise NotImplementedError()<|docstring|>Method called on state change to update HomeKit value.
Overridden by accessory types.<|endoftext|> |
208c83e858615b7732439c27315501406b84981670fb7d18e468ac6275b569f8 | def __init__(self, hass, driver, name=BRIDGE_NAME):
'Initialize a Bridge object.'
super().__init__(driver, name)
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER, model=BRIDGE_MODEL, serial_number=BRIDGE_SERIAL_NUMBER)
self.hass = hass | Initialize a Bridge object. | homeassistant/components/homekit/accessories.py | __init__ | ellsclytn/home-assistant | 0 | python | def __init__(self, hass, driver, name=BRIDGE_NAME):
super().__init__(driver, name)
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER, model=BRIDGE_MODEL, serial_number=BRIDGE_SERIAL_NUMBER)
self.hass = hass | def __init__(self, hass, driver, name=BRIDGE_NAME):
super().__init__(driver, name)
self.set_info_service(firmware_revision=__version__, manufacturer=MANUFACTURER, model=BRIDGE_MODEL, serial_number=BRIDGE_SERIAL_NUMBER)
self.hass = hass<|docstring|>Initialize a Bridge object.<|endoftext|> |
97b4c4d7d22ce779a21ebb2d4539cfcb9f51afab13712bc1dfaef633280b4712 | def setup_message(self):
'Prevent print of pyhap setup message to terminal.'
pass | Prevent print of pyhap setup message to terminal. | homeassistant/components/homekit/accessories.py | setup_message | ellsclytn/home-assistant | 0 | python | def setup_message(self):
pass | def setup_message(self):
pass<|docstring|>Prevent print of pyhap setup message to terminal.<|endoftext|> |
8f3552e6cde56b40f055e704cf3f6cdcd91ba88f52a1aac7b947050fff864f81 | def __init__(self, hass, **kwargs):
'Initialize a AccessoryDriver object.'
super().__init__(**kwargs)
self.hass = hass | Initialize a AccessoryDriver object. | homeassistant/components/homekit/accessories.py | __init__ | ellsclytn/home-assistant | 0 | python | def __init__(self, hass, **kwargs):
super().__init__(**kwargs)
self.hass = hass | def __init__(self, hass, **kwargs):
super().__init__(**kwargs)
self.hass = hass<|docstring|>Initialize a AccessoryDriver object.<|endoftext|> |
a84f79174930d627b987ad80582999f6d9ef5c3dc51f632eb4bf1d908f7f3b23 | def pair(self, client_uuid, client_public):
'Override super function to dismiss setup message if paired.'
success = super().pair(client_uuid, client_public)
if success:
dismiss_setup_message(self.hass)
return success | Override super function to dismiss setup message if paired. | homeassistant/components/homekit/accessories.py | pair | ellsclytn/home-assistant | 0 | python | def pair(self, client_uuid, client_public):
success = super().pair(client_uuid, client_public)
if success:
dismiss_setup_message(self.hass)
return success | def pair(self, client_uuid, client_public):
success = super().pair(client_uuid, client_public)
if success:
dismiss_setup_message(self.hass)
return success<|docstring|>Override super function to dismiss setup message if paired.<|endoftext|> |
e8611daa867adc70fd29108886708c881911433dcd51fc470a3390c9e93671b5 | def unpair(self, client_uuid):
'Override super function to show setup message if unpaired.'
super().unpair(client_uuid)
show_setup_message(self.hass, self.state.pincode) | Override super function to show setup message if unpaired. | homeassistant/components/homekit/accessories.py | unpair | ellsclytn/home-assistant | 0 | python | def unpair(self, client_uuid):
super().unpair(client_uuid)
show_setup_message(self.hass, self.state.pincode) | def unpair(self, client_uuid):
super().unpair(client_uuid)
show_setup_message(self.hass, self.state.pincode)<|docstring|>Override super function to show setup message if unpaired.<|endoftext|> |
6b8667ce0beee80458a2de6d576ce233f99f2adb1e4c7a03c4814c8aa40284a8 | def cumulative_sum_minus_last(l, offset=0):
'Returns cumulative sums for set of counts, removing last entry.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5]. Note last sum element 9 is missing.\n Useful for reindexing\n\n Parameters\n ... | Returns cumulative sums for set of counts, removing last entry.
Returns the cumulative sums for a set of counts with the first returned value
starting at 0. I.e [3,2,4] -> [0, 3, 5]. Note last sum element 9 is missing.
Useful for reindexing
Parameters
----------
l: list
List of integers. Typically small counts. | dcCustom/feat/mol_graphs.py | cumulative_sum_minus_last | simonfqy/DTI_prediction | 31 | python | def cumulative_sum_minus_last(l, offset=0):
'Returns cumulative sums for set of counts, removing last entry.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5]. Note last sum element 9 is missing.\n Useful for reindexing\n\n Parameters\n ... | def cumulative_sum_minus_last(l, offset=0):
'Returns cumulative sums for set of counts, removing last entry.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5]. Note last sum element 9 is missing.\n Useful for reindexing\n\n Parameters\n ... |
ec02e999486e876c26b5dee085e80527a55df56300eebb6aa2155448ed0a55d9 | def cumulative_sum(l, offset=0):
'Returns cumulative sums for set of counts.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5, 9]. Keeps final sum for searching. \n Useful for reindexing.\n\n Parameters\n ----------\n l: list\n List ... | Returns cumulative sums for set of counts.
Returns the cumulative sums for a set of counts with the first returned value
starting at 0. I.e [3,2,4] -> [0, 3, 5, 9]. Keeps final sum for searching.
Useful for reindexing.
Parameters
----------
l: list
List of integers. Typically small counts. | dcCustom/feat/mol_graphs.py | cumulative_sum | simonfqy/DTI_prediction | 31 | python | def cumulative_sum(l, offset=0):
'Returns cumulative sums for set of counts.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5, 9]. Keeps final sum for searching. \n Useful for reindexing.\n\n Parameters\n ----------\n l: list\n List ... | def cumulative_sum(l, offset=0):
'Returns cumulative sums for set of counts.\n\n Returns the cumulative sums for a set of counts with the first returned value\n starting at 0. I.e [3,2,4] -> [0, 3, 5, 9]. Keeps final sum for searching. \n Useful for reindexing.\n\n Parameters\n ----------\n l: list\n List ... |
c070946fbdcdd7153a52e8c66481d8edb3c48e9eff35ccceff983cd49fda461b | def __init__(self, atom_features, adj_list, smiles=None, max_deg=10, min_deg=0):
'\n Parameters\n ----------\n atom_features: np.ndarray\n Has shape (n_atoms, n_feat)\n canon_adj_list: list\n List of length n_atoms, with neighor indices of each atom.\n max_deg: int, optional\n Maximum ... | Parameters
----------
atom_features: np.ndarray
Has shape (n_atoms, n_feat)
canon_adj_list: list
List of length n_atoms, with neighor indices of each atom.
max_deg: int, optional
Maximum degree of any atom.
min_deg: int, optional
Minimum degree of any atom. | dcCustom/feat/mol_graphs.py | __init__ | simonfqy/DTI_prediction | 31 | python | def __init__(self, atom_features, adj_list, smiles=None, max_deg=10, min_deg=0):
'\n Parameters\n ----------\n atom_features: np.ndarray\n Has shape (n_atoms, n_feat)\n canon_adj_list: list\n List of length n_atoms, with neighor indices of each atom.\n max_deg: int, optional\n Maximum ... | def __init__(self, atom_features, adj_list, smiles=None, max_deg=10, min_deg=0):
'\n Parameters\n ----------\n atom_features: np.ndarray\n Has shape (n_atoms, n_feat)\n canon_adj_list: list\n List of length n_atoms, with neighor indices of each atom.\n max_deg: int, optional\n Maximum ... |
d5cd78eff2bf038a17034f881190013fd046f6cb159a8e7634c1fa84a7c85902 | def get_atoms_with_deg(self, deg):
'Retrieves atom_features with the specific degree'
start_ind = self.deg_slice[((deg - self.min_deg), 0)]
size = self.deg_slice[((deg - self.min_deg), 1)]
return self.atom_features[(start_ind:(start_ind + size), :)] | Retrieves atom_features with the specific degree | dcCustom/feat/mol_graphs.py | get_atoms_with_deg | simonfqy/DTI_prediction | 31 | python | def get_atoms_with_deg(self, deg):
start_ind = self.deg_slice[((deg - self.min_deg), 0)]
size = self.deg_slice[((deg - self.min_deg), 1)]
return self.atom_features[(start_ind:(start_ind + size), :)] | def get_atoms_with_deg(self, deg):
start_ind = self.deg_slice[((deg - self.min_deg), 0)]
size = self.deg_slice[((deg - self.min_deg), 1)]
return self.atom_features[(start_ind:(start_ind + size), :)]<|docstring|>Retrieves atom_features with the specific degree<|endoftext|> |
78741cae9dd904c8b7e7f08917e8c291c414a087b19b63b099731b47736c0b39 | def get_num_atoms_with_deg(self, deg):
'Returns the number of atoms with the given degree'
return self.deg_slice[((deg - self.min_deg), 1)] | Returns the number of atoms with the given degree | dcCustom/feat/mol_graphs.py | get_num_atoms_with_deg | simonfqy/DTI_prediction | 31 | python | def get_num_atoms_with_deg(self, deg):
return self.deg_slice[((deg - self.min_deg), 1)] | def get_num_atoms_with_deg(self, deg):
return self.deg_slice[((deg - self.min_deg), 1)]<|docstring|>Returns the number of atoms with the given degree<|endoftext|> |
a0d09c51a034ec95651671807a769a64461a9df13537a3430e7f82c47104f4b5 | def _deg_sort(self):
'Sorts atoms by degree and reorders internal data structures.\n\n Sort the order of the atom_features by degree, maintaining original order\n whenever two atom_features have the same degree. \n '
old_ind = range(self.get_num_atoms())
deg_list = self.deg_list
new_ind = list(... | Sorts atoms by degree and reorders internal data structures.
Sort the order of the atom_features by degree, maintaining original order
whenever two atom_features have the same degree. | dcCustom/feat/mol_graphs.py | _deg_sort | simonfqy/DTI_prediction | 31 | python | def _deg_sort(self):
'Sorts atoms by degree and reorders internal data structures.\n\n Sort the order of the atom_features by degree, maintaining original order\n whenever two atom_features have the same degree. \n '
old_ind = range(self.get_num_atoms())
deg_list = self.deg_list
new_ind = list(... | def _deg_sort(self):
'Sorts atoms by degree and reorders internal data structures.\n\n Sort the order of the atom_features by degree, maintaining original order\n whenever two atom_features have the same degree. \n '
old_ind = range(self.get_num_atoms())
deg_list = self.deg_list
new_ind = list(... |
ef00b610a2e35c1a6d1787628085c754e9197546a3552fbf547d7f2280a0bb6c | def get_atom_features(self):
'Returns canonicalized version of atom features.\n\n Features are sorted by atom degree, with original order maintained when\n degrees are same.\n '
return self.atom_features | Returns canonicalized version of atom features.
Features are sorted by atom degree, with original order maintained when
degrees are same. | dcCustom/feat/mol_graphs.py | get_atom_features | simonfqy/DTI_prediction | 31 | python | def get_atom_features(self):
'Returns canonicalized version of atom features.\n\n Features are sorted by atom degree, with original order maintained when\n degrees are same.\n '
return self.atom_features | def get_atom_features(self):
'Returns canonicalized version of atom features.\n\n Features are sorted by atom degree, with original order maintained when\n degrees are same.\n '
return self.atom_features<|docstring|>Returns canonicalized version of atom features.
Features are sorted by atom degree, wi... |
cb5dc576f0f84cd602e50eb972e03294bfbd058c5e2e994a242bdbece0112771 | def get_adjacency_list(self):
'Returns a canonicalized adjacency list.\n\n Canonicalized means that the atoms are re-ordered by degree.\n\n Returns\n -------\n list\n Canonicalized form of adjacency list.\n '
return self.canon_adj_list | Returns a canonicalized adjacency list.
Canonicalized means that the atoms are re-ordered by degree.
Returns
-------
list
Canonicalized form of adjacency list. | dcCustom/feat/mol_graphs.py | get_adjacency_list | simonfqy/DTI_prediction | 31 | python | def get_adjacency_list(self):
'Returns a canonicalized adjacency list.\n\n Canonicalized means that the atoms are re-ordered by degree.\n\n Returns\n -------\n list\n Canonicalized form of adjacency list.\n '
return self.canon_adj_list | def get_adjacency_list(self):
'Returns a canonicalized adjacency list.\n\n Canonicalized means that the atoms are re-ordered by degree.\n\n Returns\n -------\n list\n Canonicalized form of adjacency list.\n '
return self.canon_adj_list<|docstring|>Returns a canonicalized adjacency list.
Can... |
189f343f5711a1beaaa809d3280a0bba710a7f8cf6b707f843c15f5e11cc8fee | def get_deg_adjacency_lists(self):
'Returns adjacency lists grouped by atom degree.\n\n Returns\n -------\n list\n Has length (max_deg+1-min_deg). The element at position deg is\n itself a list of the neighbor-lists for atoms with degree deg.\n '
return self.deg_adj_lists | Returns adjacency lists grouped by atom degree.
Returns
-------
list
Has length (max_deg+1-min_deg). The element at position deg is
itself a list of the neighbor-lists for atoms with degree deg. | dcCustom/feat/mol_graphs.py | get_deg_adjacency_lists | simonfqy/DTI_prediction | 31 | python | def get_deg_adjacency_lists(self):
'Returns adjacency lists grouped by atom degree.\n\n Returns\n -------\n list\n Has length (max_deg+1-min_deg). The element at position deg is\n itself a list of the neighbor-lists for atoms with degree deg.\n '
return self.deg_adj_lists | def get_deg_adjacency_lists(self):
'Returns adjacency lists grouped by atom degree.\n\n Returns\n -------\n list\n Has length (max_deg+1-min_deg). The element at position deg is\n itself a list of the neighbor-lists for atoms with degree deg.\n '
return self.deg_adj_lists<|docstring|>Retur... |
7f5e166f22f7912dd53667a2f51e496b6caa52c23779dbc1f869d17f30c58a8f | def get_deg_slice(self):
"Returns degree-slice tensor.\n \n The deg_slice tensor allows indexing into a flattened version of the\n molecule's atoms. Assume atoms are sorted in order of degree. Then\n deg_slice[deg][0] is the starting position for atoms of degree deg in\n flattened list, and deg_slice[d... | Returns degree-slice tensor.
The deg_slice tensor allows indexing into a flattened version of the
molecule's atoms. Assume atoms are sorted in order of degree. Then
deg_slice[deg][0] is the starting position for atoms of degree deg in
flattened list, and deg_slice[deg][1] is the number of atoms with degree deg.
Note ... | dcCustom/feat/mol_graphs.py | get_deg_slice | simonfqy/DTI_prediction | 31 | python | def get_deg_slice(self):
"Returns degree-slice tensor.\n \n The deg_slice tensor allows indexing into a flattened version of the\n molecule's atoms. Assume atoms are sorted in order of degree. Then\n deg_slice[deg][0] is the starting position for atoms of degree deg in\n flattened list, and deg_slice[d... | def get_deg_slice(self):
"Returns degree-slice tensor.\n \n The deg_slice tensor allows indexing into a flattened version of the\n molecule's atoms. Assume atoms are sorted in order of degree. Then\n deg_slice[deg][0] is the starting position for atoms of degree deg in\n flattened list, and deg_slice[d... |
7956509d9c996527bc0e9dac0764163fc73d3971c1455350fe3e6d1349135376 | @staticmethod
def get_null_mol(n_feat, max_deg=10, min_deg=0):
'Constructs a null molecules\n\n Get one molecule with one atom of each degree, with all the atoms \n connected to themselves, and containing n_feat features.\n \n Parameters \n ----------\n n_feat : int\n number of features for... | Constructs a null molecules
Get one molecule with one atom of each degree, with all the atoms
connected to themselves, and containing n_feat features.
Parameters
----------
n_feat : int
number of features for the nodes in the null molecule | dcCustom/feat/mol_graphs.py | get_null_mol | simonfqy/DTI_prediction | 31 | python | @staticmethod
def get_null_mol(n_feat, max_deg=10, min_deg=0):
'Constructs a null molecules\n\n Get one molecule with one atom of each degree, with all the atoms \n connected to themselves, and containing n_feat features.\n \n Parameters \n ----------\n n_feat : int\n number of features for... | @staticmethod
def get_null_mol(n_feat, max_deg=10, min_deg=0):
'Constructs a null molecules\n\n Get one molecule with one atom of each degree, with all the atoms \n connected to themselves, and containing n_feat features.\n \n Parameters \n ----------\n n_feat : int\n number of features for... |
ee42d244ca5de7ca0be930f713b549c3f4799e9095cbbce8a49a47907e57d0b9 | @staticmethod
def agglomerate_mols(mols, max_deg=10, min_deg=0):
"Concatenates list of ConvMol's into one mol object that can be used to feed \n into tensorflow placeholders. The indexing of the molecules are preserved during the\n combination, but the indexing of the atoms are greatly changed.\n \n Par... | Concatenates list of ConvMol's into one mol object that can be used to feed
into tensorflow placeholders. The indexing of the molecules are preserved during the
combination, but the indexing of the atoms are greatly changed.
Parameters
----
mols: list
ConvMol objects to be combined into one molecule. | dcCustom/feat/mol_graphs.py | agglomerate_mols | simonfqy/DTI_prediction | 31 | python | @staticmethod
def agglomerate_mols(mols, max_deg=10, min_deg=0):
"Concatenates list of ConvMol's into one mol object that can be used to feed \n into tensorflow placeholders. The indexing of the molecules are preserved during the\n combination, but the indexing of the atoms are greatly changed.\n \n Par... | @staticmethod
def agglomerate_mols(mols, max_deg=10, min_deg=0):
"Concatenates list of ConvMol's into one mol object that can be used to feed \n into tensorflow placeholders. The indexing of the molecules are preserved during the\n combination, but the indexing of the atoms are greatly changed.\n \n Par... |
2685e744e30a413d93b3d5c2d18ca438fcc7dbb80a0e5ab72e340265f115bbea | @pytest.fixture(scope='session', autouse=True)
def torch_single_threaded():
'Make PyTorch execute code single-threaded.\n\n This allows us to run the test suite with greater across-test parallelism.\n This is faster, since:\n - There are diminishing returns to more threads within a test.\n - Man... | Make PyTorch execute code single-threaded.
This allows us to run the test suite with greater across-test parallelism.
This is faster, since:
- There are diminishing returns to more threads within a test.
- Many tests cannot be multi-threaded (e.g. most not using PyTorch training),
and we have to set betw... | tests/conftest.py | torch_single_threaded | NJFreymuth/imitation | 438 | python | @pytest.fixture(scope='session', autouse=True)
def torch_single_threaded():
'Make PyTorch execute code single-threaded.\n\n This allows us to run the test suite with greater across-test parallelism.\n This is faster, since:\n - There are diminishing returns to more threads within a test.\n - Man... | @pytest.fixture(scope='session', autouse=True)
def torch_single_threaded():
'Make PyTorch execute code single-threaded.\n\n This allows us to run the test suite with greater across-test parallelism.\n This is faster, since:\n - There are diminishing returns to more threads within a test.\n - Man... |
c28bdd0dd852bff848f1eeca0235def561cd4e2cd3260d3c85af4d535e687876 | def speech_transcription(input_uri):
'Transcribe speech from a video stored on GCS.'
from google.cloud import videointelligence_v1p1beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION]
config = ... | Transcribe speech from a video stored on GCS. | video/cloud-client/analyze/beta_snippets.py | speech_transcription | namrathaPullalarevu/python-docs-samples | 3 | python | def speech_transcription(input_uri):
from google.cloud import videointelligence_v1p1beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION]
config = videointelligence.types.SpeechTranscriptionConf... | def speech_transcription(input_uri):
from google.cloud import videointelligence_v1p1beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION]
config = videointelligence.types.SpeechTranscriptionConf... |
77581943d67c81bb1902f4810e3349cc6f837701ef7243171165f95e1e021d5a | def video_detect_text_gcs(input_uri):
'Detect text in a video stored on GCS.'
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
operation = video_clie... | Detect text in a video stored on GCS. | video/cloud-client/analyze/beta_snippets.py | video_detect_text_gcs | namrathaPullalarevu/python-docs-samples | 3 | python | def video_detect_text_gcs(input_uri):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
operation = video_client.annotate_video(input_uri=input_uri, ... | def video_detect_text_gcs(input_uri):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
operation = video_client.annotate_video(input_uri=input_uri, ... |
c43af4577a8d63a8b0f5fdc3a12ef052017cdbef2d40832bcb712bc5dd75ba1a | def video_detect_text(path):
'Detect text in a local video.'
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
video_context = videointelligence.types... | Detect text in a local video. | video/cloud-client/analyze/beta_snippets.py | video_detect_text | namrathaPullalarevu/python-docs-samples | 3 | python | def video_detect_text(path):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
video_context = videointelligence.types.VideoContext()
with io.ope... | def video_detect_text(path):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.TEXT_DETECTION]
video_context = videointelligence.types.VideoContext()
with io.ope... |
a06a1061dc364fd1a84cf1cad6ed24a5586072f108a7d0693910a18eb8a45b7c | def track_objects_gcs(gcs_uri):
'Object Tracking.'
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(input_ur... | Object Tracking. | video/cloud-client/analyze/beta_snippets.py | track_objects_gcs | namrathaPullalarevu/python-docs-samples | 3 | python | def track_objects_gcs(gcs_uri):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(input_uri=gcs_uri, feature... | def track_objects_gcs(gcs_uri):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(input_uri=gcs_uri, feature... |
80b27b10ae7b98517bcc746b6a8365be5c0d27ec4bf504cbc0f545e93384ca11 | def track_objects(path):
'Object Tracking.'
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
with io.open(path, 'rb') as file:
input_content... | Object Tracking. | video/cloud-client/analyze/beta_snippets.py | track_objects | namrathaPullalarevu/python-docs-samples | 3 | python | def track_objects(path):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
with io.open(path, 'rb') as file:
input_content = file.read()
... | def track_objects(path):
from google.cloud import videointelligence_v1p2beta1 as videointelligence
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
with io.open(path, 'rb') as file:
input_content = file.read()
... |
da2ef139a3a78549d7166f3fa69b0e0e3413c70d8a83f288ab40a432d9c5a5ee | def decision_function(self, history, point, **configuration):
'\n Return False while number of measurements less than max_repeats_of_experiment (inherited from abstract class).\n In other case - compute result as average between all experiments.\n :param history: history class object that store... | Return False while number of measurements less than max_repeats_of_experiment (inherited from abstract class).
In other case - compute result as average between all experiments.
:param history: history class object that stores all experiments results
:param point: concrete experiment configuration that is evaluating
:r... | main-node/repeater/default_repeater.py | decision_function | Valavanca/benchmark | 0 | python | def decision_function(self, history, point, **configuration):
'\n Return False while number of measurements less than max_repeats_of_experiment (inherited from abstract class).\n In other case - compute result as average between all experiments.\n :param history: history class object that store... | def decision_function(self, history, point, **configuration):
'\n Return False while number of measurements less than max_repeats_of_experiment (inherited from abstract class).\n In other case - compute result as average between all experiments.\n :param history: history class object that store... |
c755b6a1dcedc7bbd8b192cc6eda298505b2c3530e325d90e6b46c1e4b9bbb14 | def get_all_data():
"\n Main routine that grabs all COVID and covariate data and\n returns them as a single dataframe that contains:\n\n * count of cumulative cases and deaths by country (by today's date)\n * days since first case for each country\n * CPI gov't transparency index\n * World Bank da... | Main routine that grabs all COVID and covariate data and
returns them as a single dataframe that contains:
* count of cumulative cases and deaths by country (by today's date)
* days since first case for each country
* CPI gov't transparency index
* World Bank data on population, healthcare, etc. by country | services/server/dashboard/nb_mortality_rate.py | get_all_data | adriangrepo/covid-19_virus | 0 | python | def get_all_data():
"\n Main routine that grabs all COVID and covariate data and\n returns them as a single dataframe that contains:\n\n * count of cumulative cases and deaths by country (by today's date)\n * days since first case for each country\n * CPI gov't transparency index\n * World Bank da... | def get_all_data():
"\n Main routine that grabs all COVID and covariate data and\n returns them as a single dataframe that contains:\n\n * count of cumulative cases and deaths by country (by today's date)\n * days since first case for each country\n * CPI gov't transparency index\n * World Bank da... |
132eff4bde34f35537df2ebe22c74518d7eeda189883a5b546a2d4544a6c8ece | def _get_latest_covid_timeseries():
' Pull latest time-series data from JHU CSSE database '
repo = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/'
data_path = 'csse_covid_19_data/csse_covid_19_time_series/'
all_data = {}
for status in ['Confirmed', 'Deaths', 'Recovered']:
... | Pull latest time-series data from JHU CSSE database | services/server/dashboard/nb_mortality_rate.py | _get_latest_covid_timeseries | adriangrepo/covid-19_virus | 0 | python | def _get_latest_covid_timeseries():
' '
repo = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/'
data_path = 'csse_covid_19_data/csse_covid_19_time_series/'
all_data = {}
for status in ['Confirmed', 'Deaths', 'Recovered']:
file_name = ('time_series_19-covid-%s.csv' % statu... | def _get_latest_covid_timeseries():
' '
repo = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/'
data_path = 'csse_covid_19_data/csse_covid_19_time_series/'
all_data = {}
for status in ['Confirmed', 'Deaths', 'Recovered']:
file_name = ('time_series_19-covid-%s.csv' % statu... |
d7d5325c0b0471e5d190136f2e58e660eb53a8e6971a47fccc0f47adaeaeff68 | def _rollup_by_country(df):
'\n Roll up each raw time-series by country, adding up the cases\n across the individual states/provinces within the country\n\n :param df: Pandas DataFrame of raw data from CSSE\n :return: DataFrame of country counts\n '
gb = df.groupby('Country/Region')
df_rollup... | Roll up each raw time-series by country, adding up the cases
across the individual states/provinces within the country
:param df: Pandas DataFrame of raw data from CSSE
:return: DataFrame of country counts | services/server/dashboard/nb_mortality_rate.py | _rollup_by_country | adriangrepo/covid-19_virus | 0 | python | def _rollup_by_country(df):
'\n Roll up each raw time-series by country, adding up the cases\n across the individual states/provinces within the country\n\n :param df: Pandas DataFrame of raw data from CSSE\n :return: DataFrame of country counts\n '
gb = df.groupby('Country/Region')
df_rollup... | def _rollup_by_country(df):
'\n Roll up each raw time-series by country, adding up the cases\n across the individual states/provinces within the country\n\n :param df: Pandas DataFrame of raw data from CSSE\n :return: DataFrame of country counts\n '
gb = df.groupby('Country/Region')
df_rollup... |
5b84092b028444bec87e27e597fa7ff0d0c563c69ec8ab2336f6d61d7a3db599 | def _clean_country_list(df):
' Clean up input country list in df '
country_rename = {'Hong Kong SAR': 'Hong Kong', 'Taiwan*': 'Taiwan', 'Czechia': 'Czech Republic', 'Brunei': 'Brunei Darussalam', 'Iran (Islamic Republic of)': 'Iran', 'Viet Nam': 'Vietnam', 'Russian Federation': 'Russia', 'Republic of Korea': 'S... | Clean up input country list in df | services/server/dashboard/nb_mortality_rate.py | _clean_country_list | adriangrepo/covid-19_virus | 0 | python | def _clean_country_list(df):
' '
country_rename = {'Hong Kong SAR': 'Hong Kong', 'Taiwan*': 'Taiwan', 'Czechia': 'Czech Republic', 'Brunei': 'Brunei Darussalam', 'Iran (Islamic Republic of)': 'Iran', 'Viet Nam': 'Vietnam', 'Russian Federation': 'Russia', 'Republic of Korea': 'South Korea', 'Republic of Moldova... | def _clean_country_list(df):
' '
country_rename = {'Hong Kong SAR': 'Hong Kong', 'Taiwan*': 'Taiwan', 'Czechia': 'Czech Republic', 'Brunei': 'Brunei Darussalam', 'Iran (Islamic Republic of)': 'Iran', 'Viet Nam': 'Vietnam', 'Russian Federation': 'Russia', 'Republic of Korea': 'South Korea', 'Republic of Moldova... |
39390b4d55630026e1e2fc7c5d9263b84437aac31b10c089d354dcc112460e1d | def _compute_days_since_first_case(df_cases):
' Compute the country-wise days since first confirmed case\n\n :param df_cases: country-wise time-series of confirmed case counts\n :return: Series of country-wise days since first case\n '
date_first_case = df_cases[(df_cases > 0)].idxmin(axis=1)
days_... | Compute the country-wise days since first confirmed case
:param df_cases: country-wise time-series of confirmed case counts
:return: Series of country-wise days since first case | services/server/dashboard/nb_mortality_rate.py | _compute_days_since_first_case | adriangrepo/covid-19_virus | 0 | python | def _compute_days_since_first_case(df_cases):
' Compute the country-wise days since first confirmed case\n\n :param df_cases: country-wise time-series of confirmed case counts\n :return: Series of country-wise days since first case\n '
date_first_case = df_cases[(df_cases > 0)].idxmin(axis=1)
days_... | def _compute_days_since_first_case(df_cases):
' Compute the country-wise days since first confirmed case\n\n :param df_cases: country-wise time-series of confirmed case counts\n :return: Series of country-wise days since first case\n '
date_first_case = df_cases[(df_cases > 0)].idxmin(axis=1)
days_... |
e78bbecdff62922c0d284811ffec0ea84d7e9aec01a919deaca0ef60cee990d3 | def _add_cpi_data(df_input):
'\n Add the Government transparency (CPI - corruption perceptions index)\n data (by country) as a column in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add CPI data to df_input in place\n '
cpi_data = pd.read_e... | Add the Government transparency (CPI - corruption perceptions index)
data (by country) as a column in the COVID cases dataframe.
:param df_input: COVID-19 data rolled up country-wise
:return: None, add CPI data to df_input in place | services/server/dashboard/nb_mortality_rate.py | _add_cpi_data | adriangrepo/covid-19_virus | 0 | python | def _add_cpi_data(df_input):
'\n Add the Government transparency (CPI - corruption perceptions index)\n data (by country) as a column in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add CPI data to df_input in place\n '
cpi_data = pd.read_e... | def _add_cpi_data(df_input):
'\n Add the Government transparency (CPI - corruption perceptions index)\n data (by country) as a column in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add CPI data to df_input in place\n '
cpi_data = pd.read_e... |
7f1e73413ca814c6f1c193d152f597239f2079364dadc7926cd6287f1a98100f | def _add_wb_data(df_input):
'\n Add the World Bank data covariates as columns in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add World Bank data to df_input in place\n '
wb_data = pd.read_csv('https://raw.githubusercontent.com/jwrichar/COVID1... | Add the World Bank data covariates as columns in the COVID cases dataframe.
:param df_input: COVID-19 data rolled up country-wise
:return: None, add World Bank data to df_input in place | services/server/dashboard/nb_mortality_rate.py | _add_wb_data | adriangrepo/covid-19_virus | 0 | python | def _add_wb_data(df_input):
'\n Add the World Bank data covariates as columns in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add World Bank data to df_input in place\n '
wb_data = pd.read_csv('https://raw.githubusercontent.com/jwrichar/COVID1... | def _add_wb_data(df_input):
'\n Add the World Bank data covariates as columns in the COVID cases dataframe.\n\n :param df_input: COVID-19 data rolled up country-wise\n :return: None, add World Bank data to df_input in place\n '
wb_data = pd.read_csv('https://raw.githubusercontent.com/jwrichar/COVID1... |
786eba64a752f381df6e388801c16009391bf59026a8a0deb17a1d82a85c4e65 | def _get_most_recent_value(wb_series):
'\n Get most recent non-null value for each country in the World Bank\n time-series data\n '
ts_data = wb_series[wb_series.columns[3:]]
def _helper(row):
row_nn = row[row.notnull()]
if len(row_nn):
return row_nn[(- 1)]
else... | Get most recent non-null value for each country in the World Bank
time-series data | services/server/dashboard/nb_mortality_rate.py | _get_most_recent_value | adriangrepo/covid-19_virus | 0 | python | def _get_most_recent_value(wb_series):
'\n Get most recent non-null value for each country in the World Bank\n time-series data\n '
ts_data = wb_series[wb_series.columns[3:]]
def _helper(row):
row_nn = row[row.notnull()]
if len(row_nn):
return row_nn[(- 1)]
else... | def _get_most_recent_value(wb_series):
'\n Get most recent non-null value for each country in the World Bank\n time-series data\n '
ts_data = wb_series[wb_series.columns[3:]]
def _helper(row):
row_nn = row[row.notnull()]
if len(row_nn):
return row_nn[(- 1)]
else... |
b5d2703d552c479852c92a87fcd8686a95d86d9bcb154535a4ba036b6d9ccbe2 | def _normalize_col(df, colname, how='mean'):
'\n Normalize an input column in one of 3 ways:\n\n * how=mean: unit normal N(0,1)\n * how=upper: normalize to [-1, 0] with highest value set to 0\n * how=lower: normalize to [0, 1] with lowest value set to 0\n\n Returns df modified in place with extra col... | Normalize an input column in one of 3 ways:
* how=mean: unit normal N(0,1)
* how=upper: normalize to [-1, 0] with highest value set to 0
* how=lower: normalize to [0, 1] with lowest value set to 0
Returns df modified in place with extra column added. | services/server/dashboard/nb_mortality_rate.py | _normalize_col | adriangrepo/covid-19_virus | 0 | python | def _normalize_col(df, colname, how='mean'):
'\n Normalize an input column in one of 3 ways:\n\n * how=mean: unit normal N(0,1)\n * how=upper: normalize to [-1, 0] with highest value set to 0\n * how=lower: normalize to [0, 1] with lowest value set to 0\n\n Returns df modified in place with extra col... | def _normalize_col(df, colname, how='mean'):
'\n Normalize an input column in one of 3 ways:\n\n * how=mean: unit normal N(0,1)\n * how=upper: normalize to [-1, 0] with highest value set to 0\n * how=lower: normalize to [0, 1] with lowest value set to 0\n\n Returns df modified in place with extra col... |
ec94e2fa135f62bc0895421bde1b1afed04f8ee215c2e778aaacf6d7c2ba6695 | def getDisplay(self):
'Retrieve the currently-bound, or the default, display'
from OpenGL.EGL import eglGetCurrentDisplay, eglGetDisplay, EGL_DEFAULT_DISPLAY
return (eglGetCurrentDisplay() or eglGetDisplay(EGL_DEFAULT_DISPLAY)) | Retrieve the currently-bound, or the default, display | OpenGL/raw/EGL/_types.py | getDisplay | keunhong/pyopengl | 210 | python | def getDisplay(self):
from OpenGL.EGL import eglGetCurrentDisplay, eglGetDisplay, EGL_DEFAULT_DISPLAY
return (eglGetCurrentDisplay() or eglGetDisplay(EGL_DEFAULT_DISPLAY)) | def getDisplay(self):
from OpenGL.EGL import eglGetCurrentDisplay, eglGetDisplay, EGL_DEFAULT_DISPLAY
return (eglGetCurrentDisplay() or eglGetDisplay(EGL_DEFAULT_DISPLAY))<|docstring|>Retrieve the currently-bound, or the default, display<|endoftext|> |
3f3dedb8c6cb1a656d5efe797d27f5dc56eb803f48a1ffd6ea92147ba25ca538 | def set_size(width, fraction=1):
' Set figure dimensions to avoid scaling in LaTeX.\n\n Parameters\n ----------\n width: float\n Document textwidth or columnwidth in pts\n fraction: float, optional\n Fraction of the width which you wish the figure to occupy\n\n Returns\n ----... | Set figure dimensions to avoid scaling in LaTeX.
Parameters
----------
width: float
Document textwidth or columnwidth in pts
fraction: float, optional
Fraction of the width which you wish the figure to occupy
Returns
-------
fig_dim: tuple
Dimensions of figure in inches | src/utils/plot-results-aug-resisc.py | set_size | Berkeley-Data/hpt | 1 | python | def set_size(width, fraction=1):
' Set figure dimensions to avoid scaling in LaTeX.\n\n Parameters\n ----------\n width: float\n Document textwidth or columnwidth in pts\n fraction: float, optional\n Fraction of the width which you wish the figure to occupy\n\n Returns\n ----... | def set_size(width, fraction=1):
' Set figure dimensions to avoid scaling in LaTeX.\n\n Parameters\n ----------\n width: float\n Document textwidth or columnwidth in pts\n fraction: float, optional\n Fraction of the width which you wish the figure to occupy\n\n Returns\n ----... |
8bb3506bac41b4845d9320c5bacf5d50f660608c7e10ab20c57053fc7b230840 | @register.assignment_tag(takes_context=True)
def feincms_nav_reverse(context, feincms_page, level=1, depth=1):
'\n Saves a list of pages into the given context variable.\n '
if isinstance(feincms_page, HttpRequest):
try:
feincms_page = Page.objects.for_request(feincms_page, best_match=... | Saves a list of pages into the given context variable. | website/templatetags/website_tags.py | feincms_nav_reverse | acaciawater/wfn | 0 | python | @register.assignment_tag(takes_context=True)
def feincms_nav_reverse(context, feincms_page, level=1, depth=1):
'\n \n '
if isinstance(feincms_page, HttpRequest):
try:
feincms_page = Page.objects.for_request(feincms_page, best_match=True)
except Page.DoesNotExist:
re... | @register.assignment_tag(takes_context=True)
def feincms_nav_reverse(context, feincms_page, level=1, depth=1):
'\n \n '
if isinstance(feincms_page, HttpRequest):
try:
feincms_page = Page.objects.for_request(feincms_page, best_match=True)
except Page.DoesNotExist:
re... |
0fe7d14222e4b863be08b5745a90f9428128c78e34cb865932a94671ee877ed6 | def relative_dispersion(x: np.ndarray) -> float:
' Relative dispersion of vector\n '
out = (np.std(x) / np.std(np.diff(x)))
return out | Relative dispersion of vector | vest/aggregations/relative_dispersion.py | relative_dispersion | vcerqueira/vest-python | 5 | python | def relative_dispersion(x: np.ndarray) -> float:
' \n '
out = (np.std(x) / np.std(np.diff(x)))
return out | def relative_dispersion(x: np.ndarray) -> float:
' \n '
out = (np.std(x) / np.std(np.diff(x)))
return out<|docstring|>Relative dispersion of vector<|endoftext|> |
83802d7de66dd77fbf44b24dc569289ce6b20c243d6dd9ec3835b07f81405289 | @callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
'Exclude large and chatty update attributes from being recorded in the database.'
return {ATTR_ENTITY_PICTURE, ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY} | Exclude large and chatty update attributes from being recorded in the database. | homeassistant/components/update/recorder.py | exclude_attributes | a-p-z/core | 30,023 | python | @callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
return {ATTR_ENTITY_PICTURE, ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY} | @callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
return {ATTR_ENTITY_PICTURE, ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY}<|docstring|>Exclude large and chatty update attributes from being recorded in the database.<|endoftext|> |
20ccd210266b8119f335b06aed48a02f75b21a1f8edb9ee7d0360a6397780d7b | @mock.patch('coverage.get_json_from_url', return_value={'fuzzer_stats_dir': 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'})
def test_get_valid_project(self, mocked_get_json_from_url):
'Tests that a project\'s coverage report can be downloaded and parsed.\n\n NOTE: This test relies on the PROJECT_NAME re... | Tests that a project's coverage report can be downloaded and parsed.
NOTE: This test relies on the PROJECT_NAME repo's coverage report.
The "example" project was not used because it has no coverage reports. | infra/cifuzz/coverage_test.py | test_get_valid_project | mejo1024/oss-fuzz | 3 | python | @mock.patch('coverage.get_json_from_url', return_value={'fuzzer_stats_dir': 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'})
def test_get_valid_project(self, mocked_get_json_from_url):
'Tests that a project\'s coverage report can be downloaded and parsed.\n\n NOTE: This test relies on the PROJECT_NAME re... | @mock.patch('coverage.get_json_from_url', return_value={'fuzzer_stats_dir': 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'})
def test_get_valid_project(self, mocked_get_json_from_url):
'Tests that a project\'s coverage report can be downloaded and parsed.\n\n NOTE: This test relies on the PROJECT_NAME re... |
10ba315cef0ec60d5b85dd7100618909557767f1995732be564f4c85ef38cf15 | def test_get_invalid_project(self):
'Tests that passing a bad project returns None.'
self.assertIsNone(coverage._get_fuzzer_stats_dir_url('not-a-proj')) | Tests that passing a bad project returns None. | infra/cifuzz/coverage_test.py | test_get_invalid_project | mejo1024/oss-fuzz | 3 | python | def test_get_invalid_project(self):
self.assertIsNone(coverage._get_fuzzer_stats_dir_url('not-a-proj')) | def test_get_invalid_project(self):
self.assertIsNone(coverage._get_fuzzer_stats_dir_url('not-a-proj'))<|docstring|>Tests that passing a bad project returns None.<|endoftext|> |
6eee18a836a7b7b4c67c98251a2135ed8b4f95b1312cce0df246783f94cb92ff | @mock.patch('coverage.get_json_from_url', return_value={})
def test_valid_target(self, mocked_get_json_from_url):
"Tests that a target's coverage report can be downloaded and parsed."
self.coverage_getter.get_target_coverage_report(FUZZ_TARGET)
((url,), _) = mocked_get_json_from_url.call_args
self.asser... | Tests that a target's coverage report can be downloaded and parsed. | infra/cifuzz/coverage_test.py | test_valid_target | mejo1024/oss-fuzz | 3 | python | @mock.patch('coverage.get_json_from_url', return_value={})
def test_valid_target(self, mocked_get_json_from_url):
self.coverage_getter.get_target_coverage_report(FUZZ_TARGET)
((url,), _) = mocked_get_json_from_url.call_args
self.assertEqual('https://storage.googleapis.com/oss-fuzz-coverage/curl/fuzzer_... | @mock.patch('coverage.get_json_from_url', return_value={})
def test_valid_target(self, mocked_get_json_from_url):
self.coverage_getter.get_target_coverage_report(FUZZ_TARGET)
((url,), _) = mocked_get_json_from_url.call_args
self.assertEqual('https://storage.googleapis.com/oss-fuzz-coverage/curl/fuzzer_... |
0ca69591285e95505f3e773a1b8fb9b43f1037db5eac90327e8cc057a29cc9ed | def test_invalid_target(self):
'Tests that passing an invalid target coverage report returns None.'
self.assertIsNone(self.coverage_getter.get_target_coverage_report(INVALID_TARGET)) | Tests that passing an invalid target coverage report returns None. | infra/cifuzz/coverage_test.py | test_invalid_target | mejo1024/oss-fuzz | 3 | python | def test_invalid_target(self):
self.assertIsNone(self.coverage_getter.get_target_coverage_report(INVALID_TARGET)) | def test_invalid_target(self):
self.assertIsNone(self.coverage_getter.get_target_coverage_report(INVALID_TARGET))<|docstring|>Tests that passing an invalid target coverage report returns None.<|endoftext|> |
ced573ecb1759378dc45d1e9af86a33a8314ba5382d81e197978a9254df41c98 | @mock.patch('coverage._get_latest_cov_report_info', return_value=None)
def test_invalid_project_json(self, _):
'Tests an invalid project JSON results in None being returned.'
coverage_getter = coverage.OssFuzzCoverageGetter(PROJECT_NAME, REPO_PATH)
self.assertIsNone(coverage_getter.get_target_coverage_repor... | Tests an invalid project JSON results in None being returned. | infra/cifuzz/coverage_test.py | test_invalid_project_json | mejo1024/oss-fuzz | 3 | python | @mock.patch('coverage._get_latest_cov_report_info', return_value=None)
def test_invalid_project_json(self, _):
coverage_getter = coverage.OssFuzzCoverageGetter(PROJECT_NAME, REPO_PATH)
self.assertIsNone(coverage_getter.get_target_coverage_report(FUZZ_TARGET)) | @mock.patch('coverage._get_latest_cov_report_info', return_value=None)
def test_invalid_project_json(self, _):
coverage_getter = coverage.OssFuzzCoverageGetter(PROJECT_NAME, REPO_PATH)
self.assertIsNone(coverage_getter.get_target_coverage_report(FUZZ_TARGET))<|docstring|>Tests an invalid project JSON resul... |
cfc9a7655980de607ff34771e9cc7ae46e92a7546c28f768efdbd588420f2bab | def test_valid_target(self):
'Tests that covered files can be retrieved from a coverage report.'
with open(os.path.join(TEST_DATA_PATH, FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
fuzzer_cov_info = json.loads(file_handle.read())
with mock.patch('coverage.OssFuzzCoverageGetter.get_target_coverage... | Tests that covered files can be retrieved from a coverage report. | infra/cifuzz/coverage_test.py | test_valid_target | mejo1024/oss-fuzz | 3 | python | def test_valid_target(self):
with open(os.path.join(TEST_DATA_PATH, FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
fuzzer_cov_info = json.loads(file_handle.read())
with mock.patch('coverage.OssFuzzCoverageGetter.get_target_coverage_report', return_value=fuzzer_cov_info):
file_list = self.c... | def test_valid_target(self):
with open(os.path.join(TEST_DATA_PATH, FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
fuzzer_cov_info = json.loads(file_handle.read())
with mock.patch('coverage.OssFuzzCoverageGetter.get_target_coverage_report', return_value=fuzzer_cov_info):
file_list = self.c... |
a99a0336d2866035b9d2194e88bc7a777e4480dcdeb39e8ffc2105ed20ed10ca | def test_invalid_target(self):
'Tests passing invalid fuzz target returns None.'
self.assertIsNone(self.coverage_getter.get_files_covered_by_target(INVALID_TARGET)) | Tests passing invalid fuzz target returns None. | infra/cifuzz/coverage_test.py | test_invalid_target | mejo1024/oss-fuzz | 3 | python | def test_invalid_target(self):
self.assertIsNone(self.coverage_getter.get_files_covered_by_target(INVALID_TARGET)) | def test_invalid_target(self):
self.assertIsNone(self.coverage_getter.get_files_covered_by_target(INVALID_TARGET))<|docstring|>Tests passing invalid fuzz target returns None.<|endoftext|> |
0a38fe62000a1bed932be7d1e84b9b9b398460a8952d1d1049f60610cb85707d | def test_is_file_covered_covered(self):
'Tests that is_file_covered returns True for a covered file.'
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 200, 'notcovered': 200, 'percent': 98.03}}}
self.assertTrue(coverage.is_file_covered(fil... | Tests that is_file_covered returns True for a covered file. | infra/cifuzz/coverage_test.py | test_is_file_covered_covered | mejo1024/oss-fuzz | 3 | python | def test_is_file_covered_covered(self):
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 200, 'notcovered': 200, 'percent': 98.03}}}
self.assertTrue(coverage.is_file_covered(file_coverage)) | def test_is_file_covered_covered(self):
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 200, 'notcovered': 200, 'percent': 98.03}}}
self.assertTrue(coverage.is_file_covered(file_coverage))<|docstring|>Tests that is_file_covered returns T... |
63fcc25d361e49f98005480cbc683d63aebee62ea1b6aeb1cfeaa86019bf85b6 | def test_is_file_covered_not_covered(self):
'Tests that is_file_covered returns False for a not covered file.'
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 0, 'notcovered': 0, 'percent': 0}}}
self.assertFalse(coverage.is_file_covered(f... | Tests that is_file_covered returns False for a not covered file. | infra/cifuzz/coverage_test.py | test_is_file_covered_not_covered | mejo1024/oss-fuzz | 3 | python | def test_is_file_covered_not_covered(self):
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 0, 'notcovered': 0, 'percent': 0}}}
self.assertFalse(coverage.is_file_covered(file_coverage)) | def test_is_file_covered_not_covered(self):
file_coverage = {'filename': '/src/systemd/src/basic/locale-util.c', 'summary': {'regions': {'count': 204, 'covered': 0, 'notcovered': 0, 'percent': 0}}}
self.assertFalse(coverage.is_file_covered(file_coverage))<|docstring|>Tests that is_file_covered returns Fals... |
11c496b3e1ade9a1a91cd3d866efb7cd97d12e9fd9143d1d66317067ca04d9d3 | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value={'coverage': 1})
def test_get_latest_cov_report_info(self, mocked_get_json_from_url, mocked_error):
'Tests that _get_latest_cov_report_info works as intended.'
result = coverage._get_latest_cov_report_info(self.PROJECT)
self... | Tests that _get_latest_cov_report_info works as intended. | infra/cifuzz/coverage_test.py | test_get_latest_cov_report_info | mejo1024/oss-fuzz | 3 | python | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value={'coverage': 1})
def test_get_latest_cov_report_info(self, mocked_get_json_from_url, mocked_error):
result = coverage._get_latest_cov_report_info(self.PROJECT)
self.assertEqual(result, {'coverage': 1})
mocked_error.asse... | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value={'coverage': 1})
def test_get_latest_cov_report_info(self, mocked_get_json_from_url, mocked_error):
result = coverage._get_latest_cov_report_info(self.PROJECT)
self.assertEqual(result, {'coverage': 1})
mocked_error.asse... |
c9e8da8b539a9d1bde1621dd112978cd9d15e9228003fb78ac8e6729ee3c67bd | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value=None)
def test_get_latest_cov_report_info_fail(self, _, mocked_error):
"Tests that _get_latest_cov_report_info works as intended when we can't\n get latest report info."
result = coverage._get_latest_cov_report_info('project'... | Tests that _get_latest_cov_report_info works as intended when we can't
get latest report info. | infra/cifuzz/coverage_test.py | test_get_latest_cov_report_info_fail | mejo1024/oss-fuzz | 3 | python | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value=None)
def test_get_latest_cov_report_info_fail(self, _, mocked_error):
"Tests that _get_latest_cov_report_info works as intended when we can't\n get latest report info."
result = coverage._get_latest_cov_report_info('project'... | @mock.patch('logging.error')
@mock.patch('coverage.get_json_from_url', return_value=None)
def test_get_latest_cov_report_info_fail(self, _, mocked_error):
"Tests that _get_latest_cov_report_info works as intended when we can't\n get latest report info."
result = coverage._get_latest_cov_report_info('project'... |
434413146874aeca1d00e26201ef72641d3fe574ea3b04bd62fa0d610731752e | def logging_function(_=None):
'Logs start, sleeps for 0.5s, logs end'
logging.info(multiprocessing.current_process().name)
time.sleep(0.5)
logging.info(multiprocessing.current_process().name) | Logs start, sleeps for 0.5s, logs end | core/eolearn/tests/test_eoexecutor.py | logging_function | chorng/eo-learn | 0 | python | def logging_function(_=None):
logging.info(multiprocessing.current_process().name)
time.sleep(0.5)
logging.info(multiprocessing.current_process().name) | def logging_function(_=None):
logging.info(multiprocessing.current_process().name)
time.sleep(0.5)
logging.info(multiprocessing.current_process().name)<|docstring|>Logs start, sleeps for 0.5s, logs end<|endoftext|> |
f59fd177e38fe1a2fcfa4e4aaf7c36f1bd2270b1680bd0decb74ea41786a84eb | def as_atom(document_or_set: Union[(Error, DocumentSet, Document)], query: Optional[ClassicAPIQuery]=None) -> str:
'Serialize a :class:`DocumentSet` as Atom.'
if isinstance(document_or_set, Error):
return AtomXMLSerializer().serialize_error(document_or_set, query=query)
elif ('paper_id' in document_... | Serialize a :class:`DocumentSet` as Atom. | search/serialize/atom.py | as_atom | f380cedric/arxiv-search | 35 | python | def as_atom(document_or_set: Union[(Error, DocumentSet, Document)], query: Optional[ClassicAPIQuery]=None) -> str:
if isinstance(document_or_set, Error):
return AtomXMLSerializer().serialize_error(document_or_set, query=query)
elif ('paper_id' in document_or_set):
return AtomXMLSerializer()... | def as_atom(document_or_set: Union[(Error, DocumentSet, Document)], query: Optional[ClassicAPIQuery]=None) -> str:
if isinstance(document_or_set, Error):
return AtomXMLSerializer().serialize_error(document_or_set, query=query)
elif ('paper_id' in document_or_set):
return AtomXMLSerializer()... |
3bb442890697bce2e790fa3603f48411b47bbc8c3338405cb843b2e6fd44ffe2 | def transform_document(self, fg: FeedGenerator, doc: Document, query: Optional[ClassicAPIQuery]=None) -> None:
'Select a subset of :class:`Document` properties for public API.'
entry = fg.add_entry()
entry.id(self._fix_url(url_for('abs', paper_id=doc['paper_id'], version=doc['version'], _external=True)))
... | Select a subset of :class:`Document` properties for public API. | search/serialize/atom.py | transform_document | f380cedric/arxiv-search | 35 | python | def transform_document(self, fg: FeedGenerator, doc: Document, query: Optional[ClassicAPIQuery]=None) -> None:
entry = fg.add_entry()
entry.id(self._fix_url(url_for('abs', paper_id=doc['paper_id'], version=doc['version'], _external=True)))
entry.title(doc['title'])
entry.summary(doc['abstract'])
... | def transform_document(self, fg: FeedGenerator, doc: Document, query: Optional[ClassicAPIQuery]=None) -> None:
entry = fg.add_entry()
entry.id(self._fix_url(url_for('abs', paper_id=doc['paper_id'], version=doc['version'], _external=True)))
entry.title(doc['title'])
entry.summary(doc['abstract'])
... |
38ac6003b3abce233b4529658702a89e48ce78d6ed5c5ff781081f52e43a7d0a | def serialize(self, document_set: DocumentSet, query: Optional[ClassicAPIQuery]=None) -> str:
'Generate Atom response for a :class:`DocumentSet`.'
fg = self._get_feed(query)
fg.opensearch.totalResults(document_set['metadata'].get('total_results'))
fg.opensearch.itemsPerPage(document_set['metadata'].get(... | Generate Atom response for a :class:`DocumentSet`. | search/serialize/atom.py | serialize | f380cedric/arxiv-search | 35 | python | def serialize(self, document_set: DocumentSet, query: Optional[ClassicAPIQuery]=None) -> str:
fg = self._get_feed(query)
fg.opensearch.totalResults(document_set['metadata'].get('total_results'))
fg.opensearch.itemsPerPage(document_set['metadata'].get('size'))
fg.opensearch.startIndex(document_set['... | def serialize(self, document_set: DocumentSet, query: Optional[ClassicAPIQuery]=None) -> str:
fg = self._get_feed(query)
fg.opensearch.totalResults(document_set['metadata'].get('total_results'))
fg.opensearch.itemsPerPage(document_set['metadata'].get('size'))
fg.opensearch.startIndex(document_set['... |
be5116e96fe170c80ca4887d01df986ff0958b2e6df4d5203567221fb4d81bfc | def serialize_error(self, error: Error, query: Optional[ClassicAPIQuery]=None) -> str:
'Generate Atom error response.'
fg = self._get_feed(query)
fg.opensearch.totalResults(1)
fg.opensearch.itemsPerPage(1)
fg.opensearch.startIndex(0)
entry = fg.add_entry()
entry.id(error.id)
entry.title(... | Generate Atom error response. | search/serialize/atom.py | serialize_error | f380cedric/arxiv-search | 35 | python | def serialize_error(self, error: Error, query: Optional[ClassicAPIQuery]=None) -> str:
fg = self._get_feed(query)
fg.opensearch.totalResults(1)
fg.opensearch.itemsPerPage(1)
fg.opensearch.startIndex(0)
entry = fg.add_entry()
entry.id(error.id)
entry.title('Error')
entry.summary(erro... | def serialize_error(self, error: Error, query: Optional[ClassicAPIQuery]=None) -> str:
fg = self._get_feed(query)
fg.opensearch.totalResults(1)
fg.opensearch.itemsPerPage(1)
fg.opensearch.startIndex(0)
entry = fg.add_entry()
entry.id(error.id)
entry.title('Error')
entry.summary(erro... |
c1e74618f11a8af2354cf63502c77e7c857b9022b5e4dedacc94b7aa20d777db | def serialize_document(self, document: Document, query: Optional[ClassicAPIQuery]=None) -> str:
'Generate Atom feed for a single :class:`Document`.'
document_set = document_set_from_documents([document])
return self.serialize(document_set, query=query) | Generate Atom feed for a single :class:`Document`. | search/serialize/atom.py | serialize_document | f380cedric/arxiv-search | 35 | python | def serialize_document(self, document: Document, query: Optional[ClassicAPIQuery]=None) -> str:
document_set = document_set_from_documents([document])
return self.serialize(document_set, query=query) | def serialize_document(self, document: Document, query: Optional[ClassicAPIQuery]=None) -> str:
document_set = document_set_from_documents([document])
return self.serialize(document_set, query=query)<|docstring|>Generate Atom feed for a single :class:`Document`.<|endoftext|> |
1cca491b754c1ee7cfa28a1bf4f39a8a5442680a4ba9240229817685f7d012a1 | def _compute_covariance(self, lpost, res):
"\n Compute the covariance of the parameters using inverse of the Hessian, i.e.\n the second-order derivative of the log-likelihood. Also calculates an estimate\n of the standard deviation in the parameters, using the square root of the diagonal\n ... | Compute the covariance of the parameters using inverse of the Hessian, i.e.
the second-order derivative of the log-likelihood. Also calculates an estimate
of the standard deviation in the parameters, using the square root of the diagonal
of the covariance matrix.
The Hessian is either estimated directly by the chosen ... | stingray/modeling/parameterestimation.py | _compute_covariance | nimeshvashistha/stingray | 133 | python | def _compute_covariance(self, lpost, res):
"\n Compute the covariance of the parameters using inverse of the Hessian, i.e.\n the second-order derivative of the log-likelihood. Also calculates an estimate\n of the standard deviation in the parameters, using the square root of the diagonal\n ... | def _compute_covariance(self, lpost, res):
"\n Compute the covariance of the parameters using inverse of the Hessian, i.e.\n the second-order derivative of the log-likelihood. Also calculates an estimate\n of the standard deviation in the parameters, using the square root of the diagonal\n ... |
ec871b78411320124d1520ffb89b07d35179bb0b4442558121a96b6810f2111b | def _compute_model(self, lpost):
'\n Compute the values of the best-fit model for all ``x``.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n in the regression... | Compute the values of the best-fit model for all ``x``.
Parameters
----------
lpost: instance of :class:`Posterior` or one of its subclasses
The object containing the function that is being optimized
in the regression | stingray/modeling/parameterestimation.py | _compute_model | nimeshvashistha/stingray | 133 | python | def _compute_model(self, lpost):
'\n Compute the values of the best-fit model for all ``x``.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n in the regression... | def _compute_model(self, lpost):
'\n Compute the values of the best-fit model for all ``x``.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n in the regression... |
4b55a418e39850d945eefce59d6c123d9d342cceab31506c622f5afab7511c8c | def _compute_criteria(self, lpost):
'\n Compute various information criteria useful for model comparison in\n non-nested models.\n\n Currently implemented are the Akaike Information Criterion [#]_ and the\n Bayesian Information Criterion [#]_.\n\n Parameters\n ----------\n ... | Compute various information criteria useful for model comparison in
non-nested models.
Currently implemented are the Akaike Information Criterion [#]_ and the
Bayesian Information Criterion [#]_.
Parameters
----------
lpost: instance of :class:`Posterior` or one of its subclasses
The object containing the functio... | stingray/modeling/parameterestimation.py | _compute_criteria | nimeshvashistha/stingray | 133 | python | def _compute_criteria(self, lpost):
'\n Compute various information criteria useful for model comparison in\n non-nested models.\n\n Currently implemented are the Akaike Information Criterion [#]_ and the\n Bayesian Information Criterion [#]_.\n\n Parameters\n ----------\n ... | def _compute_criteria(self, lpost):
'\n Compute various information criteria useful for model comparison in\n non-nested models.\n\n Currently implemented are the Akaike Information Criterion [#]_ and the\n Bayesian Information Criterion [#]_.\n\n Parameters\n ----------\n ... |
dc240bc66aaa50b64afc4839f7345b7e7b8398362c453a7f95e30517a6de5adc | def _compute_statistics(self, lpost):
'\n Compute some useful fit statistics, like the degrees of freedom and the\n figure of merit.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is... | Compute some useful fit statistics, like the degrees of freedom and the
figure of merit.
Parameters
----------
lpost: instance of :class:`Posterior` or one of its subclasses
The object containing the function that is being optimized
in the regression | stingray/modeling/parameterestimation.py | _compute_statistics | nimeshvashistha/stingray | 133 | python | def _compute_statistics(self, lpost):
'\n Compute some useful fit statistics, like the degrees of freedom and the\n figure of merit.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is... | def _compute_statistics(self, lpost):
'\n Compute some useful fit statistics, like the degrees of freedom and the\n figure of merit.\n\n Parameters\n ----------\n lpost: instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is... |
c9f72c279d38f7dbd54cd411ed5d6a81023bfafd1dc712546dcdad82052527f3 | def print_summary(self, lpost):
'\n Print a useful summary of the fitting procedure to screen or\n a log file.\n\n Parameters\n ----------\n lpost : instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n ... | Print a useful summary of the fitting procedure to screen or
a log file.
Parameters
----------
lpost : instance of :class:`Posterior` or one of its subclasses
The object containing the function that is being optimized
in the regression | stingray/modeling/parameterestimation.py | print_summary | nimeshvashistha/stingray | 133 | python | def print_summary(self, lpost):
'\n Print a useful summary of the fitting procedure to screen or\n a log file.\n\n Parameters\n ----------\n lpost : instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n ... | def print_summary(self, lpost):
'\n Print a useful summary of the fitting procedure to screen or\n a log file.\n\n Parameters\n ----------\n lpost : instance of :class:`Posterior` or one of its subclasses\n The object containing the function that is being optimized\n ... |
747f356f060d0bbe24582e77ec37bc131cd98aad8232158befa3f0e9bdbc75e9 | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the data.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`Posterior` (or subclass) ins... | Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)
fit to the data.
MAP fits include priors, ML fits do not.
Parameters
-----------
lpost : :class:`Posterior` (or subclass) instance
and instance of class :class:`Posterior` or one of its subclasses
that defines the function to be minimized (eith... | stingray/modeling/parameterestimation.py | fit | nimeshvashistha/stingray | 133 | python | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the data.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`Posterior` (or subclass) ins... | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the data.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`Posterior` (or subclass) ins... |
6bf741c549b1a46f72e0667086c23812782a5d280c33dd5acbd52f66c11d9a85 | def compute_lrt(self, lpost1, t1, lpost2, t2, neg=True, max_post=False):
'\n This function computes the Likelihood Ratio Test between two\n nested models.\n\n Parameters\n ----------\n lpost1 : object of a subclass of :class:`Posterior`\n The :class:`Posterior` object f... | This function computes the Likelihood Ratio Test between two
nested models.
Parameters
----------
lpost1 : object of a subclass of :class:`Posterior`
The :class:`Posterior` object for model 1
t1 : iterable
The starting parameters for model 1
lpost2 : object of a subclass of :class:`Posterior`
The :class:... | stingray/modeling/parameterestimation.py | compute_lrt | nimeshvashistha/stingray | 133 | python | def compute_lrt(self, lpost1, t1, lpost2, t2, neg=True, max_post=False):
'\n This function computes the Likelihood Ratio Test between two\n nested models.\n\n Parameters\n ----------\n lpost1 : object of a subclass of :class:`Posterior`\n The :class:`Posterior` object f... | def compute_lrt(self, lpost1, t1, lpost2, t2, neg=True, max_post=False):
'\n This function computes the Likelihood Ratio Test between two\n nested models.\n\n Parameters\n ----------\n lpost1 : object of a subclass of :class:`Posterior`\n The :class:`Posterior` object f... |
5849c5a0176bbd70c8ce3ee81e16282ff4c7a7c61cde2af8873a0c326225071c | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test', pool=False):
'\n Sample the :class:`Posterior` distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n ... | Sample the :class:`Posterior` distribution defined in ``lpost`` using MCMC.
Here we use the ``emcee`` package, but other implementations could
in principle be used.
Parameters
----------
lpost : instance of a :class:`Posterior` subclass
and instance of class :class:`Posterior` or one of its subclasses
that def... | stingray/modeling/parameterestimation.py | sample | nimeshvashistha/stingray | 133 | python | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test', pool=False):
'\n Sample the :class:`Posterior` distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n ... | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test', pool=False):
'\n Sample the :class:`Posterior` distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n ... |
e55394ec781e30ebeb79b3ea7dfff04830426c01fcfffbbfc1fe21dd0f9284b8 | def _generate_model(self, lpost, pars):
'\n Helper function that generates a fake PSD similar to the\n one in the data, but with different parameters.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object ... | Helper function that generates a fake PSD similar to the
one in the data, but with different parameters.
Parameters
----------
lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass
The object containing the relevant information about the
data and the model
pars : iterable
A list of p... | stingray/modeling/parameterestimation.py | _generate_model | nimeshvashistha/stingray | 133 | python | def _generate_model(self, lpost, pars):
'\n Helper function that generates a fake PSD similar to the\n one in the data, but with different parameters.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object ... | def _generate_model(self, lpost, pars):
'\n Helper function that generates a fake PSD similar to the\n one in the data, but with different parameters.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object ... |
d8929f8b77c16e860ddbd7d569057edd556c97458256b53912268859935e4d15 | @staticmethod
def _compute_pvalue(obs_val, sim):
'\n Compute the p-value given an observed value of a test statistic\n and some simulations of that same test statistic.\n\n Parameters\n ----------\n obs_value : float\n The observed value of the test statistic in questio... | Compute the p-value given an observed value of a test statistic
and some simulations of that same test statistic.
Parameters
----------
obs_value : float
The observed value of the test statistic in question
sim: iterable
A list or array of simulated values for the test statistic
Returns
-------
pval : float ... | stingray/modeling/parameterestimation.py | _compute_pvalue | nimeshvashistha/stingray | 133 | python | @staticmethod
def _compute_pvalue(obs_val, sim):
'\n Compute the p-value given an observed value of a test statistic\n and some simulations of that same test statistic.\n\n Parameters\n ----------\n obs_value : float\n The observed value of the test statistic in questio... | @staticmethod
def _compute_pvalue(obs_val, sim):
'\n Compute the p-value given an observed value of a test statistic\n and some simulations of that same test statistic.\n\n Parameters\n ----------\n obs_value : float\n The observed value of the test statistic in questio... |
ece94194c86392914bec07b1f0563b365edee6f083b60ef6fbb003fb42252bc1 | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, max_post=True, seed=None):
'\n Simulate likelihood ratios.\n For details, see definitions in the subclasses that implement this\n task.\n '
raise NotImplementedError('The behaviour of `simulate_lrts` should be defined in the subc... | Simulate likelihood ratios.
For details, see definitions in the subclasses that implement this
task. | stingray/modeling/parameterestimation.py | simulate_lrts | nimeshvashistha/stingray | 133 | python | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, max_post=True, seed=None):
'\n Simulate likelihood ratios.\n For details, see definitions in the subclasses that implement this\n task.\n '
raise NotImplementedError('The behaviour of `simulate_lrts` should be defined in the subc... | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, max_post=True, seed=None):
'\n Simulate likelihood ratios.\n For details, see definitions in the subclasses that implement this\n task.\n '
raise NotImplementedError('The behaviour of `simulate_lrts` should be defined in the subc... |
f603631119a631a834427079e5bcdc8eb3a79b04e8e3eafa6aed104f55d387cc | def calibrate_lrt(self, lpost1, t1, lpost2, t2, sample=None, neg=True, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
"Calibrate the outcome of a Likelihood Ratio Test via MCMC.\n\n In order to compare models via likelihood ratio test, one generally\n aims ... | Calibrate the outcome of a Likelihood Ratio Test via MCMC.
In order to compare models via likelihood ratio test, one generally
aims to compute a p-value for the null hypothesis (generally the
simpler model). There are two special cases where the theoretical
distribution used to compute that p-value analytically given ... | stingray/modeling/parameterestimation.py | calibrate_lrt | nimeshvashistha/stingray | 133 | python | def calibrate_lrt(self, lpost1, t1, lpost2, t2, sample=None, neg=True, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
"Calibrate the outcome of a Likelihood Ratio Test via MCMC.\n\n In order to compare models via likelihood ratio test, one generally\n aims ... | def calibrate_lrt(self, lpost1, t1, lpost2, t2, sample=None, neg=True, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
"Calibrate the outcome of a Likelihood Ratio Test via MCMC.\n\n In order to compare models via likelihood ratio test, one generally\n aims ... |
f05a2040d651f68acc0ffab9ac780d69f32fdc684293ab109a9ffcc458597ced | def _check_convergence(self, sampler):
'\n Compute common statistics for convergence of the MCMC\n chains. While you can never be completely sure that your chains\n converged, these present reasonable heuristics to give an\n indication whether convergence is very far off or reasonably cl... | Compute common statistics for convergence of the MCMC
chains. While you can never be completely sure that your chains
converged, these present reasonable heuristics to give an
indication whether convergence is very far off or reasonably close.
Currently implemented are the autocorrelation time [#]_ and the
Gelman-Rubi... | stingray/modeling/parameterestimation.py | _check_convergence | nimeshvashistha/stingray | 133 | python | def _check_convergence(self, sampler):
'\n Compute common statistics for convergence of the MCMC\n chains. While you can never be completely sure that your chains\n converged, these present reasonable heuristics to give an\n indication whether convergence is very far off or reasonably cl... | def _check_convergence(self, sampler):
'\n Compute common statistics for convergence of the MCMC\n chains. While you can never be completely sure that your chains\n converged, these present reasonable heuristics to give an\n indication whether convergence is very far off or reasonably cl... |
a086717be2f372e4efe0a4e171213ae55c470ea64e1e58dfb19ae0a30941031b | def _compute_rhat(self, sampler):
'\n Compute Gelman-Rubin convergence criterion [#]_.\n\n Parameters\n ----------\n sampler : an `emcee.EnsembleSampler` object\n\n References\n ----------\n .. [#] https://projecteuclid.org/euclid.ss/1177011136\n '
chain =... | Compute Gelman-Rubin convergence criterion [#]_.
Parameters
----------
sampler : an `emcee.EnsembleSampler` object
References
----------
.. [#] https://projecteuclid.org/euclid.ss/1177011136 | stingray/modeling/parameterestimation.py | _compute_rhat | nimeshvashistha/stingray | 133 | python | def _compute_rhat(self, sampler):
'\n Compute Gelman-Rubin convergence criterion [#]_.\n\n Parameters\n ----------\n sampler : an `emcee.EnsembleSampler` object\n\n References\n ----------\n .. [#] https://projecteuclid.org/euclid.ss/1177011136\n '
chain =... | def _compute_rhat(self, sampler):
'\n Compute Gelman-Rubin convergence criterion [#]_.\n\n Parameters\n ----------\n sampler : an `emcee.EnsembleSampler` object\n\n References\n ----------\n .. [#] https://projecteuclid.org/euclid.ss/1177011136\n '
chain =... |
07263bd8b894cfca38551dca6e81f6c3777baf29ae6ef686aae3ebbd613a11cd | def _infer(self, ci_min=5, ci_max=95):
'\n Infer the :class:`Posterior` means, standard deviations and credible intervals\n (i.e. the Bayesian equivalent to confidence intervals) from the :class:`Posterior` samples\n for each parameter.\n\n Parameters\n ----------\n ci_min ... | Infer the :class:`Posterior` means, standard deviations and credible intervals
(i.e. the Bayesian equivalent to confidence intervals) from the :class:`Posterior` samples
for each parameter.
Parameters
----------
ci_min : float
Lower bound to the credible interval, given as percentage between
0 and 100
ci_max ... | stingray/modeling/parameterestimation.py | _infer | nimeshvashistha/stingray | 133 | python | def _infer(self, ci_min=5, ci_max=95):
'\n Infer the :class:`Posterior` means, standard deviations and credible intervals\n (i.e. the Bayesian equivalent to confidence intervals) from the :class:`Posterior` samples\n for each parameter.\n\n Parameters\n ----------\n ci_min ... | def _infer(self, ci_min=5, ci_max=95):
'\n Infer the :class:`Posterior` means, standard deviations and credible intervals\n (i.e. the Bayesian equivalent to confidence intervals) from the :class:`Posterior` samples\n for each parameter.\n\n Parameters\n ----------\n ci_min ... |
e17f198a74da30a15c95eb60f700053b6ca5a067e5f2dcd47aef79b7ec49d9a8 | def print_results(self):
'\n Print results of the MCMC run on screen or to a log-file.\n\n\n '
self.log.info(('-- The acceptance fraction is: %f.5' % self.acceptance))
try:
self.log.info('-- The autocorrelation time is: {}'.format(self.acor))
except AttributeError:
pass
... | Print results of the MCMC run on screen or to a log-file. | stingray/modeling/parameterestimation.py | print_results | nimeshvashistha/stingray | 133 | python | def print_results(self):
'\n \n\n\n '
self.log.info(('-- The acceptance fraction is: %f.5' % self.acceptance))
try:
self.log.info('-- The autocorrelation time is: {}'.format(self.acor))
except AttributeError:
pass
self.log.info(('R_hat for the parameters is: ' + str(sel... | def print_results(self):
'\n \n\n\n '
self.log.info(('-- The acceptance fraction is: %f.5' % self.acceptance))
try:
self.log.info('-- The autocorrelation time is: {}'.format(self.acor))
except AttributeError:
pass
self.log.info(('R_hat for the parameters is: ' + str(sel... |
65091dbd2960bd93e884ce1d4381c42651244623ec667c28c1290bb825248aae | def plot_results(self, nsamples=1000, fig=None, save_plot=False, filename='test.pdf'):
'\n Plot some results in a triangle plot.\n If installed, will use [corner]_\n for the plotting, if not,\n uses its own code to make a triangle plot.\n\n By default, this method returns a ``matp... | Plot some results in a triangle plot.
If installed, will use [corner]_
for the plotting, if not,
uses its own code to make a triangle plot.
By default, this method returns a ``matplotlib.Figure`` object, but
if ``save_plot=True`` the plot can be saved to file automatically,
Parameters
----------
nsamples : int, defa... | stingray/modeling/parameterestimation.py | plot_results | nimeshvashistha/stingray | 133 | python | def plot_results(self, nsamples=1000, fig=None, save_plot=False, filename='test.pdf'):
'\n Plot some results in a triangle plot.\n If installed, will use [corner]_\n for the plotting, if not,\n uses its own code to make a triangle plot.\n\n By default, this method returns a ``matp... | def plot_results(self, nsamples=1000, fig=None, save_plot=False, filename='test.pdf'):
'\n Plot some results in a triangle plot.\n If installed, will use [corner]_\n for the plotting, if not,\n uses its own code to make a triangle plot.\n\n By default, this method returns a ``matp... |
f5406800dbbd884f72104109991ebd9203311ab5975a010a3d5eb565894efb35 | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the power spectrum.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`stingray.modeling.... | Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)
fit to the power spectrum.
MAP fits include priors, ML fits do not.
Parameters
-----------
lpost : :class:`stingray.modeling.PSDPosterior` object
An instance of class :class:`stingray.modeling.PSDPosterior` that defines the
function to be minim... | stingray/modeling/parameterestimation.py | fit | nimeshvashistha/stingray | 133 | python | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the power spectrum.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`stingray.modeling.... | def fit(self, lpost, t0, neg=True, scipy_optimize_options=None):
'\n Do either a Maximum-A-Posteriori (MAP) or Maximum Likelihood (ML)\n fit to the power spectrum.\n\n MAP fits include priors, ML fits do not.\n\n Parameters\n -----------\n lpost : :class:`stingray.modeling.... |
f2336a72e1d51dbb986c9970e6f8fb407428513cd4a5eacbaa48ac425b557d7d | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test'):
'\n Sample the posterior distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n in principle be us... | Sample the posterior distribution defined in ``lpost`` using MCMC.
Here we use the ``emcee`` package, but other implementations could
in principle be used.
Parameters
----------
lpost : instance of a :class:`Posterior` subclass
and instance of class :class:`Posterior` or one of its subclasses
that defines the ... | stingray/modeling/parameterestimation.py | sample | nimeshvashistha/stingray | 133 | python | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test'):
'\n Sample the posterior distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n in principle be us... | def sample(self, lpost, t0, cov=None, nwalkers=500, niter=100, burnin=100, threads=1, print_results=True, plot=False, namestr='test'):
'\n Sample the posterior distribution defined in ``lpost`` using MCMC.\n Here we use the ``emcee`` package, but other implementations could\n in principle be us... |
1297afd13e1e45212fc1f2845edc7dc5b87c55e2cc9f4b8aa59b324dac8fd58b | def _generate_data(self, lpost, pars, rng=None):
'\n Generate a fake power spectrum from a model.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object containing the relevant information about the\n d... | Generate a fake power spectrum from a model.
Parameters
----------
lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass
The object containing the relevant information about the
data and the model
pars : iterable
A list of parameters to be passed to ``lpost.model`` in oder
to gen... | stingray/modeling/parameterestimation.py | _generate_data | nimeshvashistha/stingray | 133 | python | def _generate_data(self, lpost, pars, rng=None):
'\n Generate a fake power spectrum from a model.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object containing the relevant information about the\n d... | def _generate_data(self, lpost, pars, rng=None):
'\n Generate a fake power spectrum from a model.\n\n Parameters\n ----------\n lpost : instance of a :class:`Posterior` or :class:`LogLikelihood` subclass\n The object containing the relevant information about the\n d... |
7b84feaf5f53163cdd09bd20cb038f4754f3fc4c0e856f3818a92ab22f0ead1f | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, seed=None):
'\n Simulate likelihood ratios for two given models based on MCMC samples\n for the simpler model (i.e. the null hypothesis).\n\n Parameters\n ----------\n s_all : numpy.ndarray of shape ``(nsamples, lpost1.npar)``... | Simulate likelihood ratios for two given models based on MCMC samples
for the simpler model (i.e. the null hypothesis).
Parameters
----------
s_all : numpy.ndarray of shape ``(nsamples, lpost1.npar)``
An array with MCMC samples derived from the null hypothesis model in
``lpost1``. Its second dimension must mat... | stingray/modeling/parameterestimation.py | simulate_lrts | nimeshvashistha/stingray | 133 | python | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, seed=None):
'\n Simulate likelihood ratios for two given models based on MCMC samples\n for the simpler model (i.e. the null hypothesis).\n\n Parameters\n ----------\n s_all : numpy.ndarray of shape ``(nsamples, lpost1.npar)``... | def simulate_lrts(self, s_all, lpost1, t1, lpost2, t2, seed=None):
'\n Simulate likelihood ratios for two given models based on MCMC samples\n for the simpler model (i.e. the null hypothesis).\n\n Parameters\n ----------\n s_all : numpy.ndarray of shape ``(nsamples, lpost1.npar)``... |
a2887d7aeb0a90a7b59b7759eaa19d965c9f5a3b44071fc7bc501309eb2fca98 | def calibrate_highest_outlier(self, lpost, t0, sample=None, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
'\n Calibrate the highest outlier in a data set using MCMC-simulated\n power spectra.\n\n In short, the procedure does a MAP fit to the data, c... | Calibrate the highest outlier in a data set using MCMC-simulated
power spectra.
In short, the procedure does a MAP fit to the data, computes the
statistic
.. math::
\max{(T_R = 2(\mathrm{data}/\mathrm{model}))}
and then does an MCMC run using the data and the model, or generates parameter samples
from the likel... | stingray/modeling/parameterestimation.py | calibrate_highest_outlier | nimeshvashistha/stingray | 133 | python | def calibrate_highest_outlier(self, lpost, t0, sample=None, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
'\n Calibrate the highest outlier in a data set using MCMC-simulated\n power spectra.\n\n In short, the procedure does a MAP fit to the data, c... | def calibrate_highest_outlier(self, lpost, t0, sample=None, max_post=False, nsim=1000, niter=200, nwalkers=500, burnin=200, namestr='test', seed=None):
'\n Calibrate the highest outlier in a data set using MCMC-simulated\n power spectra.\n\n In short, the procedure does a MAP fit to the data, c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.