uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
76dbd2655ec977d4f99c4c2f
train
class
class TxtCorrObject(CorrObject): """ Correlation Object that reads data from a textfile into a numpy array """ def __init__(self, path, parent=None): self.parent = parent self.path = path self.ar = None self.get_array() ##############################################...
class TxtCorrObject(CorrObject):
""" Correlation Object that reads data from a textfile into a numpy array """ def __init__(self, path, parent=None): self.parent = parent self.path = path self.ar = None self.get_array() ########################################################### def get_array(...
just the 'definition' we can compare against (for example checking inputs are all correlation objects in some methods etc.) """ def __init__(self): self.ar = None ########################################################### def get_array(): raise NotImplementedError("get_array shou...
83
84
280
8
75
SamScholten/stereo_vision
correlation_tools.py
Python
TxtCorrObject
TxtCorrObject
700
738
700
700
d507100b8643507090844f40b6eb6b018f36e4bf
bigcode/the-stack
train
166d648981767da1f5d2da72
train
class
class GaussianCorrObject(CorrObject): """ create a Gaussian function (2D) object """ def __init__(self, width=0.5, height=250, parent=None): self.parent = parent self.get_array(width, height) ########################################################### def get_array(self, width...
class GaussianCorrObject(CorrObject):
""" create a Gaussian function (2D) object """ def __init__(self, width=0.5, height=250, parent=None): self.parent = parent self.get_array(width, height) ########################################################### def get_array(self, width, height): x, y = np.meshgrid(...
image_ar = np.mean(image_ar, axis=-1) else: raise RuntimeError('not sure what to do with an image ' + 'inputted with this format') # otherwise assume grayscale input image self.ar = image_ar ###############################################...
63
64
164
8
55
SamScholten/stereo_vision
correlation_tools.py
Python
GaussianCorrObject
GaussianCorrObject
808
825
808
808
62d11d22f6d96aff05250de45612c13c3d5d453c
bigcode/the-stack
train
d37e82ae90fc75063cdb9214
train
class
class TiffCorrObject(CorrObject): """ Correlation Object that reads a numpy array from a tiff image file (converts to greyscale) """ def __init__(self, path, parent=None): self.path = path self.parent = parent self.get_array() ###########################################...
class TiffCorrObject(CorrObject):
""" Correlation Object that reads a numpy array from a tiff image file (converts to greyscale) """ def __init__(self, path, parent=None): self.path = path self.parent = parent self.get_array() ########################################################### def get_arra...
_ar = np.mean(image_ar, axis=-1) else: raise RuntimeError('not sure what to do with an image ' + 'inputted with this format') # otherwise assume grayscale input image self.ar = image_ar ######################################################...
63
64
212
9
54
SamScholten/stereo_vision
correlation_tools.py
Python
TiffCorrObject
TiffCorrObject
776
802
776
776
d614a924ff6343d8128aa7a25c0a3db101879175
bigcode/the-stack
train
f826ae24d0c6e207c093d8f8
train
class
class SizeError(Exception): pass
class SizeError(Exception):
pass
self.yi >= (self.height - self.geom.t_height//2): self.yi = 0 self.xi = 0 raise StopIteration ########################################################### def get_array(self): raise RuntimeError("this shouldn't be called for this subclass") class SizeErr...
64
64
8
5
59
SamScholten/stereo_vision
correlation_tools.py
Python
SizeError
SizeError
922
923
922
922
3327e3e8a6d0ec0b93e4226d75606a3aaf855ea4
bigcode/the-stack
train
f455e109072eea12b9296fc4
train
class
class HomogRegionError(Exception): pass
class HomogRegionError(Exception):
pass
.t_height//2): self.yi = 0 self.xi = 0 raise StopIteration ########################################################### def get_array(self): raise RuntimeError("this shouldn't be called for this subclass") class SizeError(Exception): pass class Homo...
64
64
10
7
56
SamScholten/stereo_vision
correlation_tools.py
Python
HomogRegionError
HomogRegionError
926
927
926
926
466c5731b7daf52a306605c8a0f48e5214ba380f
bigcode/the-stack
train
3a8568e173b39aa19436616c
train
class
class CorrObject(object): """ general class of correlation objects -> not necessarily ever called, this is just the 'definition' we can compare against (for example checking inputs are all correlation objects in some methods etc.) """ def __init__(self): self.ar = None #############...
class CorrObject(object):
""" general class of correlation objects -> not necessarily ever called, this is just the 'definition' we can compare against (for example checking inputs are all correlation objects in some methods etc.) """ def __init__(self): self.ar = None #######################################...
png', dpi=dpi, bbox_inches='tight') else: raise RuntimeError("use 'show_corr' first") else: plt.imsave(str(self.img_dir) + '/' + filename + '.png', self.corr, dpi=dpi) ############################################################################### ...
63
64
95
5
58
SamScholten/stereo_vision
correlation_tools.py
Python
CorrObject
CorrObject
682
695
682
682
5489ef493cc60380eaafb74d26bc88f0ae51bfc2
bigcode/the-stack
train
34ffc27589adcde7b4ddfb1a
train
function
def trim_arrays(coords, t, A): """ Takes template (t) and search region (A) both of the same dimension, and trims them down only to the overlapping sections, where the bottom right of t is at 'coords' with respect to (0, 0) in A. """ dim = np.ndim(A) if dim != np.ndim(t): raise Value...
def trim_arrays(coords, t, A):
""" Takes template (t) and search region (A) both of the same dimension, and trims them down only to the overlapping sections, where the bottom right of t is at 'coords' with respect to (0, 0) in A. """ dim = np.ndim(A) if dim != np.ndim(t): raise ValueError("input arrays A and t mus...
1: net_change = A.shape[0] - t.shape[0] # left = net_change//2 # right = net_change - left left = 0 right = net_change pad_width = (left, right) return np.pad(t, pad_width, 'constant', constant_values=0) ########################################################### ...
256
256
914
9
247
SamScholten/stereo_vision
correlation_tools.py
Python
trim_arrays
trim_arrays
980
1,083
980
980
bae3c45fe0877a7d59d575dad04e3aeb62c356ab
bigcode/the-stack
train
08617e819116798ae1db5d29
train
class
class CorrSystem(object): """ This object represents a correlation system of a template and a search region. The template can be correlated against the search region, and then printed/saved. """ def __init__(self, img_dir, data_dir, parent=None): self.parent = parent self.templa...
class CorrSystem(object):
""" This object represents a correlation system of a template and a search region. The template can be correlated against the search region, and then printed/saved. """ def __init__(self, img_dir, data_dir, parent=None): self.parent = parent self.template = self.search_region = ...
_dir/'wallypuzzle.png') wally_system = corrt.CorrSystem(img_dir, data_dir) rocketman = corrt.PngCorrObject(rocketman_path) puzzle = corrt.PngCorrObject(puzzle_path) wally_system.add_template(rocketman) wally_system.add_search_region(puzzle) wally_system.cross_correlate(method='spectral') wally_system.show_corr() wa...
255
256
4,474
5
250
SamScholten/stereo_vision
correlation_tools.py
Python
CorrSystem
CorrSystem
163
677
163
163
f2ddccf8f39c823ae762917293a0f4ef17ca4539
bigcode/the-stack
train
85512570d608dfbfa226ecd4
train
function
def pad_array(t, A): """ zero pad t to the shape of A (currently pads right and down only), as this is the form that works most intuitively with spectral_corr """ if np.ndim(A) == 2: net_change = np.array(A.shape)[:2] - np.array(t.shape)[:2] # left = net_change[1]//2 # right ...
def pad_array(t, A):
""" zero pad t to the shape of A (currently pads right and down only), as this is the form that works most intuitively with spectral_corr """ if np.ndim(A) == 2: net_change = np.array(A.shape)[:2] - np.array(t.shape)[:2] # left = net_change[1]//2 # right = net_change[1] - lef...
self.yi = 0 self.xi = 0 raise StopIteration ########################################################### def get_array(self): raise RuntimeError("this shouldn't be called for this subclass") class SizeError(Exception): pass class HomogRegionError(Exception): ...
74
74
247
7
66
SamScholten/stereo_vision
correlation_tools.py
Python
pad_array
pad_array
933
958
933
933
651e74f53238226e8bc49e217edfe85c341bf3d7
bigcode/the-stack
train
1daea961b0784c28455a58b0
train
function
def _dataframe_set_geometry(self, col, drop=False, inplace=False, crs=None): if inplace: raise ValueError( "Can't do inplace setting when converting from DataFrame to GeoDataFrame" ) gf = GeoDataFrame(self) # this will copy so that BlockManager gets copied return gf.set_geome...
def _dataframe_set_geometry(self, col, drop=False, inplace=False, crs=None):
if inplace: raise ValueError( "Can't do inplace setting when converting from DataFrame to GeoDataFrame" ) gf = GeoDataFrame(self) # this will copy so that BlockManager gets copied return gf.set_geometry(col, drop=drop, inplace=False, crs=crs)
type""" warnings.warn( "'-' operator will be deprecated. Use the 'difference' method instead.", DeprecationWarning, stacklevel=2, ) return self.geometry.difference(other) def _dataframe_set_geometry(self, col, drop=False, inplace=False, crs=None):
64
64
87
20
44
onietosi/geopandas
geopandas/geodataframe.py
Python
_dataframe_set_geometry
_dataframe_set_geometry
1,143
1,150
1,143
1,143
f2adb51653e8802f843d55b3e86323a000c90499
bigcode/the-stack
train
a2be3f7dea365358460b1674
train
class
class GeoDataFrame(GeoPandasBase, DataFrame): """ A GeoDataFrame object is a pandas.DataFrame that has a column with geometry. In addition to the standard DataFrame constructor arguments, GeoDataFrame also accepts the following keyword arguments: Parameters ---------- crs : value (optional)...
class GeoDataFrame(GeoPandasBase, DataFrame):
""" A GeoDataFrame object is a pandas.DataFrame that has a column with geometry. In addition to the standard DataFrame constructor arguments, GeoDataFrame also accepts the following keyword arguments: Parameters ---------- crs : value (optional) Coordinate Reference System of the ge...
import mapping, shape from shapely.geometry.base import BaseGeometry from pyproj import CRS from geopandas.array import GeometryArray, from_shapely, GeometryDtype from geopandas.base import GeoPandasBase, is_geometry_type from geopandas.geoseries import GeoSeries import geopandas.io from geopandas.plotting import p...
256
256
8,918
13
242
onietosi/geopandas
geopandas/geodataframe.py
Python
GeoDataFrame
GeoDataFrame
46
1,140
46
46
123823291be29bb2f2f7266fadb37656165aee5f
bigcode/the-stack
train
fbd549532cdd2274b76e993d
train
function
def _ensure_geometry(data, crs=None): """ Ensure the data is of geometry dtype or converted to it. If input is a (Geo)Series, output is a GeoSeries, otherwise output is GeometryArray. If the input is a GeometryDtype with a set CRS, `crs` is ignored. """ if is_geometry_type(data): i...
def _ensure_geometry(data, crs=None):
""" Ensure the data is of geometry dtype or converted to it. If input is a (Geo)Series, output is a GeoSeries, otherwise output is GeometryArray. If the input is a GeometryDtype with a set CRS, `crs` is ignored. """ if is_geometry_type(data): if isinstance(data, Series): ...
apely, GeometryDtype from geopandas.base import GeoPandasBase, is_geometry_type from geopandas.geoseries import GeoSeries import geopandas.io from geopandas.plotting import plot_dataframe DEFAULT_GEO_COLUMN_NAME = "geometry" def _ensure_geometry(data, crs=None):
64
64
159
10
54
onietosi/geopandas
geopandas/geodataframe.py
Python
_ensure_geometry
_ensure_geometry
24
43
24
24
7a24b1cfd9b018e0c43008796e95fb40b91c5385
bigcode/the-stack
train
c3dc2af6a8daa2b4a7ad7ebb
train
class
class ResultHandlerMqtt: ''' Cihaz verilerinin NDU platformuna MQTT APİ üzerinden gönderilmesi ''' def __init__(self, access_token, mqtt_obj): host = mqtt_obj.get("host") self.host = host self.port = mqtt_obj.get("port") self.connected_devices = {} self.conne...
class ResultHandlerMqtt:
''' Cihaz verilerinin NDU platformuna MQTT APİ üzerinden gönderilmesi ''' def __init__(self, access_token, mqtt_obj): host = mqtt_obj.get("host") self.host = host self.port = mqtt_obj.get("port") self.connected_devices = {} self.connected = False self...
import os import socket import time # import paho.mqtt.client as mqtt import json import paho.mqtt.client as mqttClient from ndu_gate_camera.utility import constants class ResultHandlerMqtt:
46
256
1,312
6
39
netcadlabs/ndu-gate
ndu_gate_camera/camera/result_handlers/result_handler_mqtt.py
Python
ResultHandlerMqtt
ResultHandlerMqtt
12
191
12
12
0c8529e044ed833ab6862a5c97206c4ce5918e8a
bigcode/the-stack
train
99eaaf9e4956a4c8c6485d05
train
function
def load_mesh(mesh_path, check_is_triangle=True): # load the mesh using pyvista pv_mesh = pv.read(mesh_path) # check if all of the faces are triangles if check_is_triangle and not pv_mesh.is_all_triangles(): raise ValueError('All faces need to be triangles!') # extract faces and vertices ...
def load_mesh(mesh_path, check_is_triangle=True): # load the mesh using pyvista
pv_mesh = pv.read(mesh_path) # check if all of the faces are triangles if check_is_triangle and not pv_mesh.is_all_triangles(): raise ValueError('All faces need to be triangles!') # extract faces and vertices v = np.array(pv_mesh.points) f = pv_mesh.faces.reshape(-1, 4)[:, 1:] # r...
ainer__ = "Shervin Azadi" __email__ = "shervinazadi93@gmail.com" __status__ = "Dev" file_directory = os.path.dirname(os.path.abspath(__file__)) def load_mesh(mesh_path, check_is_triangle=True): # load the mesh using pyvista
63
64
132
20
43
shervinazadi/topoGenesis
topogenesis/geometry/load.py
Python
load_mesh
load_mesh
24
37
24
25
748fb3b58318633948a3967e9d31e28eff064f04
bigcode/the-stack
train
1223b72616faaad9e83063aa
train
class
class IconatronConfig(AppConfig): name = 'iconatron'
class IconatronConfig(AppConfig):
name = 'iconatron'
from django.apps import AppConfig class IconatronConfig(AppConfig):
14
64
14
7
6
MichailZh/Iconatron
build/lib/iconatron/apps.py
Python
IconatronConfig
IconatronConfig
4
5
4
4
123f3d924227c75377fd5ffc3243f9d53ecdf8f8
bigcode/the-stack
train
d41cf881b0832201586f993f
train
class
class adc_sar_templates__sarretslice(Module): """Module for library adc_sar_templates cell sarretslice. Fill in high level description here. """ def __init__(self, bag_config, parent=None, prj=None, **kwargs): Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs) ...
class adc_sar_templates__sarretslice(Module):
"""Module for library adc_sar_templates cell sarretslice. Fill in high level description here. """ def __init__(self, bag_config, parent=None, prj=None, **kwargs): Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs) def design(self, lch, pw, nw, m, fo, device_in...
, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ...
173
173
579
11
161
tinapiao/Software-IC-Automation
laygo/generators/splash/BagModules/adc_sar_templates_fdsoi/sarretslice.py
Python
adc_sar_templates__sarretslice
adc_sar_templates__sarretslice
40
108
40
40
7133b87a92c78ae95b4078178c115bb2bf63c670
bigcode/the-stack
train
3e5e1f0097e792fa9b0b2d50
train
function
def sigterm_handler(_signo, _stack_frame): global stopped logging.info("received SIGTERM, stopping...") stopped = True
def sigterm_handler(_signo, _stack_frame):
global stopped logging.info("received SIGTERM, stopping...") stopped = True
.is_alive() def store_data(self): self.db.writeFile(self.dbfile) # ## # ## end thread methods # ## def __str__(self): return "statsserver@{}".format(self.port) def sigterm_handler(_signo, _stack_frame):
64
64
32
12
52
hifiberry/usagecollector
usagecollector/server.py
Python
sigterm_handler
sigterm_handler
202
205
202
202
2eabb5e4d2094d91768edb6a15dcf0ecf820e8d4
bigcode/the-stack
train
dde054d6914953442875bc0c
train
class
class DataSaver(threading.Thread): def __init__( self, statsServer, interval=store_interval): super().__init__() self.statsServer = statsServer self.store_interval = interval self.stopped = False def run(self): i=0 uptime = statsServer.db.get("upti...
class DataSaver(threading.Thread):
def __init__( self, statsServer, interval=store_interval): super().__init__() self.statsServer = statsServer self.store_interval = interval self.stopped = False def run(self): i=0 uptime = statsServer.db.get("uptime", create=True) # Also record time the s...
sys import time import signal from bottle import Bottle, response from usagecollector.db import StatsDB from usagecollector import cloudsync stopped = False statsServer = None store_interval = 10000 # automatically store data every 10000 seconds class DataSaver(threading.Thread):
64
64
158
8
55
hifiberry/usagecollector
usagecollector/server.py
Python
DataSaver
DataSaver
41
62
41
42
3d003f52b7578ade9aad821180ed39ac320653e9
bigcode/the-stack
train
ddeafad3bca57fc41959dc79
train
class
class StatsWebserver(): def __init__(self, host='0.0.0.0', port=3141, dbfile="/var/lib/hifiberry/usage.json", load_data=True): super().__init__() self.port = port self.host = host self.bottle = Bottle() ...
class StatsWebserver():
def __init__(self, host='0.0.0.0', port=3141, dbfile="/var/lib/hifiberry/usage.json", load_data=True): super().__init__() self.port = port self.host = host self.bottle = Bottle() self.route() ...
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import logging import threading import json import os import sys import time import signal from bottle import Bottle, response from usagecollector.db import StatsDB from usagecollector import cloudsync stopped = False statsServer = None store_in...
247
249
830
6
240
hifiberry/usagecollector
usagecollector/server.py
Python
StatsWebserver
StatsWebserver
65
199
65
66
0872535292bd20ddf508950514bfb4a923ae148e
bigcode/the-stack
train
86dac75d33e111cdb2be7ff0
train
class
class Demarcation(object): def __init__(self, api_data): self.land_gained = [] self.land_lost = [] self.disestablished = False self.established_after_last_audit = False self.established_within_audit_years = False def date_key(x): return x["date.date"] # Watch ...
class Demarcation(object):
def __init__(self, api_data): self.land_gained = [] self.land_lost = [] self.disestablished = False self.established_after_last_audit = False self.established_within_audit_years = False def date_key(x): return x["date.date"] # Watch out: groupby's iterator is ...
""" Municipality Profile data preparation ------------------------------------- Gather data from the municipal finance API and provide values ready for display on the page with little further processing. If the API returns a null value, it can generally be treated as zero. That happens in this library and nulls that s...
198
220
735
6
191
Code4SA/municipal-data-api
scorecard/profile_data/__init__.py
Python
Demarcation
Demarcation
32
121
32
32
536af9df13e6206dac492a8a7fcdd3f2f356c0e6
bigcode/the-stack
train
745ff2739635d049b87932f2
train
function
def generate_app_best_freq_plot_sc17(data, name, output_dir): f, ax = plt.subplots() cols = data.columns bar_width = 0.7 index = numpy.arange(len(data)) series_data = data['epoch'] sys.stdout.write(str(series_data) + '\n') ax.bar(index, series_data, width=bar_width, ...
def generate_app_best_freq_plot_sc17(data, name, output_dir):
f, ax = plt.subplots() cols = data.columns bar_width = 0.7 index = numpy.arange(len(data)) series_data = data['epoch'] sys.stdout.write(str(series_data) + '\n') ax.bar(index, series_data, width=bar_width, color='gray', align='center', ...
ax.set_ylim([1.1e9, 2.3e9]) lines, labels = ax.get_legend_handles_labels() plt.legend(lines, labels, shadow=True, fancybox=True, loc='best') plt.title(name) f.tight_layout() plt.savefig(os.path.join(output_dir, '{}.{}'.format(name.replace(' ', '_'), 'png'))) plt.close() def generate_app_best_...
98
98
328
15
83
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_app_best_freq_plot_sc17
generate_app_best_freq_plot_sc17
603
654
603
603
76077a3a8985d99e67ae0bea50b8266048463136
bigcode/the-stack
train
e6c8030079bb9d4713c591cd
train
class
class Config(object): """The base class for plot configuration objects. This class contains the common options for all derived configuration types. Attributes: profile_name: The name string used for the title of the plot. misc_text: Extra text string to append to the plot title. da...
class Config(object):
"""The base class for plot configuration objects. This class contains the common options for all derived configuration types. Attributes: profile_name: The name string used for the title of the plot. misc_text: Extra text string to append to the plot title. datatype: The string nam...
import os import subprocess import argparse import math from pkg_resources import parse_version import numpy import code try: with open(os.devnull, 'w') as FNULL: subprocess.check_call("python -c 'import matplotlib.pyplot'", stdout=FNULL, stderr=FNULL, shell=True) except subprocess.CalledProcessError: ...
256
256
891
4
251
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
Config
Config
76
162
76
76
a83bffefc27314117a7437671fcf7d9fb08a3efa
bigcode/the-stack
train
7bc2089803181334f810e68f
train
function
def generate_freq_plot(trace_df, config): """Plots the per sample frequency per node per socket. This function will plot the frequency of each socket on each node per sample. It plots the sockets as seperate files denoted '...socket_0.svg', '...socket_1.svg', etc. Specifying the 'analyze' option in the c...
def generate_freq_plot(trace_df, config):
"""Plots the per sample frequency per node per socket. This function will plot the frequency of each socket on each node per sample. It plots the sockets as seperate files denoted '...socket_0.svg', '...socket_1.svg', etc. Specifying the 'analyze' option in the config object will also include a stati...
(ref_plugin, reference_median_df.unstack(level=['node_name']).describe())) fd.write('\n\nReference ({}) Aggregate (max) time statistics -\n\n{}'.format(ref_plugin, reference_median_df.unstack(level=['node_name']).mean(axis=1).describe())) ...
256
256
1,382
9
247
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_freq_plot
generate_freq_plot
979
1,116
979
979
9e32ba90d64bbf6c9782fff64982a125aeb3c8cb
bigcode/the-stack
train
7638f2be2bfb4f4ecbe3d358
train
function
def generate_epoch_plot(trace_df, config): """Plots the max elapsed time for the nodes at each sample. This function will plot the maximum elapsed time for all nodes present in the trace file for each sample. Specifying the 'analyze' option till adjust the Y-axis bounds to filter out outliers. Set '--ref_...
def generate_epoch_plot(trace_df, config):
"""Plots the max elapsed time for the nodes at each sample. This function will plot the maximum elapsed time for all nodes present in the trace file for each sample. Specifying the 'analyze' option till adjust the Y-axis bounds to filter out outliers. Set '--ref_plugin' and '--tgt_plugin' config param...
.verbose: sys.stdout.write(' {}\n'.format(full_path)) if config.analyze: full_path = os.path.join(config.output_dir, '{}_stats.txt'.format(file_name)) with open(full_path, 'w') as fd: for node_name, node_data in natsorted(median_df.groupby(level='node_...
256
256
1,562
9
247
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_epoch_plot
generate_epoch_plot
829
976
829
829
1998966d0ed064b4544433ce203fe91464b1a951
bigcode/the-stack
train
d7f0f886b1cd6f2be28451e4
train
function
def generate_box_plot(report_df, config): """Plots boxes for all the input data. This will generate a boxplot for every tree decider in the 'report_df' for the target version and profile name. It is optionally normalized by the min of the means for the reference profile name, version, and plugin. Args...
def generate_box_plot(report_df, config):
"""Plots boxes for all the input data. This will generate a boxplot for every tree decider in the 'report_df' for the target version and profile name. It is optionally normalized by the min of the means for the reference profile name, version, and plugin. Args: report_df: The multiindexed Data...
legend_fontsize=9, # Base class args to override **kwargs): # User overridden args super(TraceConfig, self).__init__(fig_size=fig_size, fontsize=fontsize, legend_fontsize=legend_fontsize, ...
256
256
859
9
246
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_box_plot
generate_box_plot
247
329
247
247
910f2a3b5affad5a5665b42e86d3e210f8df7d4b
bigcode/the-stack
train
41719148a9c9c3dd5eb25fa7
train
function
def generate_best_freq_plot_sc17(data, name, output_dir): """ Creates a plot showing the frequencies chosen by the adaptive online algorithm. """ f, ax = plt.subplots() cols = data.columns colors = ['blue', 'orange', 'green', 'red'] # todo: change to map assert len(colors) >= len(cols) ...
def generate_best_freq_plot_sc17(data, name, output_dir):
""" Creates a plot showing the frequencies chosen by the adaptive online algorithm. """ f, ax = plt.subplots() cols = data.columns colors = ['blue', 'orange', 'green', 'red'] # todo: change to map assert len(colors) >= len(cols) num_series = len(cols) bar_width = 0.7 / num_series ...
plt.legend(shadow=True, fancybox=True, fontsize=14, loc='best').set_zorder(11) plt.title(name) f.tight_layout() plt.savefig(os.path.join(output_dir, '{}_bar.png'.format(name.replace(' ', '_')))) plt.close() # TODO: generate application best frequency plot (bar with 2 horz lines) # TODO: move to...
102
102
342
14
87
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_best_freq_plot_sc17
generate_best_freq_plot_sc17
558
600
558
558
dec9bb22ef6ed64fa3e4005982a0682fd81a183e
bigcode/the-stack
train
b39100484b7dda819116f245
train
function
def generate_power_plot(trace_df, config): """Plots the power consumed per node at each sample. This function will plot the power used at each sample for every node. Specifying the 'analyze' option in the config object will also plot the power cap and aggregate power for all nodes. Specifying the 'normal...
def generate_power_plot(trace_df, config):
"""Plots the power consumed per node at each sample. This function will plot the power used at each sample for every node. Specifying the 'analyze' option in the config object will also plot the power cap and aggregate power for all nodes. Specifying the 'normalize' option in the config object will u...
_dir, '{}.{}'.format(name.replace(' ', '_'), 'png'))) plt.close() def generate_runtime_energy_plot(df, name, output_dir='.'): """ Creates a plot comparing the runtime and energy of a region on two axes. """ f, ax = plt.subplots() ax.plot(df.index, df['energy_pkg'], color='DarkBlue', label='En...
256
256
1,604
9
247
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_power_plot
generate_power_plot
681
826
681
681
04538f0a20e552cbdad22f7bbbfdce762c04e9df
bigcode/the-stack
train
d06a77ed29b4641c23992ed5
train
function
def generate_bar_plot_sc17(data, name, output_dir): """ Creates a plot comparing the energy savings or runtime increase of different energy efficiency plugin modes. """ f, ax = plt.subplots() cols = data.columns colors = ['gray', 'blue', 'orange', 'green', 'red'] # todo: change to map ...
def generate_bar_plot_sc17(data, name, output_dir):
""" Creates a plot comparing the energy savings or runtime increase of different energy efficiency plugin modes. """ f, ax = plt.subplots() cols = data.columns colors = ['gray', 'blue', 'orange', 'green', 'red'] # todo: change to map assert len(colors) >= len(cols) num_series = len...
: full_path = os.path.join(config.output_dir, '{}.{}'.format(file_name, ext)) plt.savefig(full_path) if config.verbose: sys.stdout.write(' {}\n'.format(full_path)) sys.stdout.flush() if config.show: plt.show(block=config.block) if config.shell: code.i...
96
96
320
13
83
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_bar_plot_sc17
generate_bar_plot_sc17
510
551
510
510
7a8a44d2267abf427f0a9eaea73a40c4e96d6dcb
bigcode/the-stack
train
ef84d4092c5a75de81bd560d
train
function
def generate_runtime_energy_plot(df, name, output_dir='.'): """ Creates a plot comparing the runtime and energy of a region on two axes. """ f, ax = plt.subplots() ax.plot(df.index, df['energy_pkg'], color='DarkBlue', label='Energy', marker='o', linestyle='-') ax.set_xlabel('Frequency (GHz)') ...
def generate_runtime_energy_plot(df, name, output_dir='.'):
""" Creates a plot comparing the runtime and energy of a region on two axes. """ f, ax = plt.subplots() ax.plot(df.index, df['energy_pkg'], color='DarkBlue', label='Energy', marker='o', linestyle='-') ax.set_xlabel('Frequency (GHz)') ax.set_ylabel('Energy (J)') ax2 = ax.twinx() ax2...
() plt.legend(lines, labels, shadow=True, fancybox=True, loc='best') plt.title(name) f.tight_layout() plt.savefig(os.path.join(output_dir, '{}.{}'.format(name.replace(' ', '_'), 'png'))) plt.close() def generate_runtime_energy_plot(df, name, output_dir='.'):
68
68
228
13
55
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_runtime_energy_plot
generate_runtime_energy_plot
657
678
657
657
ccfdd3ab43b6e7d656f709534e3fb52717d34fd4
bigcode/the-stack
train
fe9fb58e5a1dc1ba830eeef1
train
class
class TraceConfig(Config): """The configuration for plots based on trace data. This class extends the Config class with the parameters specific to plotting trace based data. Attributes: legend_label_spacing: The float spacing between legend labels. smooth: The number of samples to use in a...
class TraceConfig(Config):
"""The configuration for plots based on trace data. This class extends the Config class with the parameters specific to plotting trace based data. Attributes: legend_label_spacing: The float spacing between legend labels. smooth: The number of samples to use in a moving average for the plo...
datatype='runtime', fig_size=(6.3, 4.8), fontsize=14, legend_fontsize=14, # Base class args to override **kwargs): # User overridden args super(ReportConfig, self).__init__(datatype=datatype, fig_size=fig_size, f...
147
147
492
5
142
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
TraceConfig
TraceConfig
197
244
197
197
645679c0e644c4106bae6552b7417ca56cec5ff3
bigcode/the-stack
train
395f549705df4182bfddbf3c
train
class
class ReportConfig(Config): """The configuration for plots based on report data. This class extends the Config class with the parameters specific to plotting report based data. Attributes: speedup: A bool to indicate whether or not to plot the target bars as a relative speedup compared ...
class ReportConfig(Config):
"""The configuration for plots based on report data. This class extends the Config class with the parameters specific to plotting report based data. Attributes: speedup: A bool to indicate whether or not to plot the target bars as a relative speedup compared to the reference bars. ...
= self.ref_plugin if tgt_plugin is None: tgt_plugin = self.tgt_plugin agent_list = df.index.get_level_values('agent').unique().tolist() if ref_plugin is not None and ref_plugin not in agent_list: raise LookupError('Reference plugin {} not found in dataframe!'.format(ref...
109
109
365
5
104
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
ReportConfig
ReportConfig
165
194
165
165
536433d26771bef65d06759b33251cf174355253
bigcode/the-stack
train
b48b94e910b14cc7a8fd0fcb
train
function
def generate_bar_plot(report_df, config): """Plots bars comparing the reference and target plugins. This will generate a plot with 2 bars at every power budget in the 'report_df' that compares the reference plugin to the target plugin. This presently is configured only for tree decider comparisons. The b...
def generate_bar_plot(report_df, config):
"""Plots bars comparing the reference and target plugins. This will generate a plot with 2 bars at every power budget in the 'report_df' that compares the reference plugin to the target plugin. This presently is configured only for tree decider comparisons. The bars are optionally normalized by the m...
ymax = report_df.loc[idx[:, :, config.min_drop:config.max_drop, :, :, :, :, 'epoch'], config.datatype].max() ymax /= normalization_factor ymax *= 1.1 ax.set_ylim(0, ymax) # Write data/plot files file_name = '{}_{}_{}_boxplot'.format(config.profile_name.lower().replace('...
256
256
1,657
9
247
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
generate_bar_plot
generate_bar_plot
332
507
332
332
b15e3aa3a04ec2cd33681f2484321a851d8812b4
bigcode/the-stack
train
0e37cf12609d441d0b6da497
train
function
def main(argv): report_plots = {'debug', 'box', 'bar'} trace_plots = {'debug', 'power', 'epoch', 'freq'} parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data_path', metavar='PATH', ...
def main(argv):
report_plots = {'debug', 'box', 'bar'} trace_plots = {'debug', 'power', 'epoch', 'freq'} parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('data_path', metavar='PATH', ...
if config.write_csv: full_path = os.path.join(config.output_dir, '{}.csv'.format(file_name)) frequency_data.unstack(level=['node_name']).to_csv(full_path) if config.verbose: sys.stdout.write(' {}\n'.format(full_path)) if config.analyze...
256
256
1,915
4
252
dannosliwcd/geopm
scripts/geopmpy/plotter.py
Python
main
main
1,119
1,293
1,119
1,119
8682e599e00a6dbf445add592c8ae05968b9f8fc
bigcode/the-stack
train
744c1339f56b5abe405d8268
train
function
def train(cli_args, log_dir): config = load(open(cli_args.config, "rb")) if config is None: print("Please provide a config.") # Load Data + Labels DataLoader = getattr(data_loaders, config["data_loader"]) train_data_generator = DataLoader(config["train_data_dir"], config) validation_d...
def train(cli_args, log_dir):
config = load(open(cli_args.config, "rb")) if config is None: print("Please provide a config.") # Load Data + Labels DataLoader = getattr(data_loaders, config["data_loader"]) train_data_generator = DataLoader(config["train_data_dir"], config) validation_data_generator = DataLoader(conf...
import os import shutil import numpy as np import argparse from datetime import datetime from yaml import load from collections import namedtuple import models import data_loaders from evaluate import evaluate from keras.callbacks import ModelCheckpoint, TensorBoard, CSVLogger, EarlyStopping from keras.optimizers imp...
79
166
554
8
70
Abhay242/language-identification-
keras/train.py
Python
train
train
16
71
16
17
f395a319d73cefe8f7721d5e4091bed5082645ef
bigcode/the-stack
train
5844d58d28cfdb50b6555ffa
train
function
def get_noise(shape, rg): ''' ''' norm = 0 while norm < 0.0001: vec = rg.normal(size=shape) norm = np.sqrt(np.sum(vec**2)) return vec / norm
def get_noise(shape, rg):
''' ''' norm = 0 while norm < 0.0001: vec = rg.normal(size=shape) norm = np.sqrt(np.sum(vec**2)) return vec / norm
u+shift)/scale minus = (u-shift)/scale coef = 1.0 / (scale*np.sqrt(2*np.pi)) return coef * (np.exp(-minus**2/2) + np.exp(-plus**2/2)) def get_noise(shape, rg):
64
64
53
7
57
feedbackward/spectral
spectral/setup_losses.py
Python
get_noise
get_noise
82
90
82
82
ec792f7a184114dd44981ee9dcbfd50f40be5b25
bigcode/the-stack
train
98a1e8718cd79b35f3fc7257
train
function
def cdf_approx_static(u, shift=0.0, scale=1.0): ''' ''' plus = (u+shift)/(scale*np.sqrt(2)) minus = (u-shift)/(scale*np.sqrt(2)) return (erf(plus)+erf(minus))/2
def cdf_approx_static(u, shift=0.0, scale=1.0):
''' ''' plus = (u+shift)/(scale*np.sqrt(2)) minus = (u-shift)/(scale*np.sqrt(2)) return (erf(plus)+erf(minus))/2
=None): ''' ''' ref_losses = loss_base(model=model, X=X, y=y) return pdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses)) def cdf_approx_static(u, shift=0.0, scale=1.0):
64
64
67
20
44
feedbackward/spectral
spectral/setup_losses.py
Python
cdf_approx_static
cdf_approx_static
65
70
65
65
16d51db92b270ae4acc371cb42e89432c8bf36ef
bigcode/the-stack
train
3358c696fd8fd0653d17ede6
train
class
class S_Risk_Fast(Loss): ''' Fast approximation to S_Risk. Assumes that sigma is the exponential aversion function. ''' def __init__(self, loss_base, sigma, cdf, pdf, name=None): ''' ''' loss_name = "S_Risk_Fast x {}".format(str(loss_base)) super().__init__(name=...
class S_Risk_Fast(Loss):
''' Fast approximation to S_Risk. Assumes that sigma is the exponential aversion function. ''' def __init__(self, loss_base, sigma, cdf, pdf, name=None): ''' ''' loss_name = "S_Risk_Fast x {}".format(str(loss_base)) super().__init__(name=loss_name) self.l...
_grads[pn].ndim if ldim > gdim: raise ValueError("Axis dimensions are wrong; ldim > gdim.") elif ldim < gdim: losses_exp = np.expand_dims(a=losses, axis=tuple(range(ldim,gdim))) loss_grads[pn] = loss_grad...
126
126
422
9
116
feedbackward/spectral
spectral/setup_losses.py
Python
S_Risk_Fast
S_Risk_Fast
166
219
166
166
116ea6c36188a0caf9ca370bd29e56ae7ae37742
bigcode/the-stack
train
94be93860590c48591023a2b
train
class
class S_Risk(Loss): ''' Spectral risk based losses. Essentially, a special loss class that takes a base loss, spectral density, and empirical CDF as arguments for construction. The result is a loss object which amounts to an unbiased estimate of the spectral risk, though conditioned on ...
class S_Risk(Loss):
''' Spectral risk based losses. Essentially, a special loss class that takes a base loss, spectral density, and empirical CDF as arguments for construction. The result is a loss object which amounts to an unbiased estimate of the spectral risk, though conditioned on the data used to com...
def pdf_approx_static(u, shift=0.0, scale=1.0): ''' ''' plus = (u+shift)/scale minus = (u-shift)/scale coef = 1.0 / (scale*np.sqrt(2*np.pi)) return coef * (np.exp(-minus**2/2) + np.exp(-plus**2/2)) def get_noise(shape, rg): ''' ''' norm = 0 while norm < 0.0001: vec = rg...
163
163
546
7
156
feedbackward/spectral
spectral/setup_losses.py
Python
S_Risk
S_Risk
96
163
96
96
d9324f015c720670cd26fb6f1fc7a1adafbe1d56
bigcode/the-stack
train
f54f7eff63884942f92b3f55
train
function
def get_base(name): ''' ''' return dict_losses[name]
def get_base(name):
''' ''' return dict_losses[name]
## Return the gradients for all parameters being optimized. return loss_grads ## A dictionary of instantiated losses. dict_losses = { "absolute": Absolute(), "logistic": Logistic(), "quadratic": Quadratic(), "zero_one": Zero_One() } def get_base(name):
64
64
15
5
59
feedbackward/spectral
spectral/setup_losses.py
Python
get_base
get_base
232
235
232
232
58598680b6f745ebf9b9d0cb4c36a94256b6bfb1
bigcode/the-stack
train
2c1f196e878afacfb44ec9bf
train
function
def get_loss(name, cdf=None, pdf=None, **kwargs): ''' ''' if kwargs["fast"]: return S_Risk_Fast(loss_base=dict_losses[name], sigma=kwargs["sigma"], cdf=cdf, pdf=pdf) else: return S_Risk(loss_base=dict_losses...
def get_loss(name, cdf=None, pdf=None, **kwargs):
''' ''' if kwargs["fast"]: return S_Risk_Fast(loss_base=dict_losses[name], sigma=kwargs["sigma"], cdf=cdf, pdf=pdf) else: return S_Risk(loss_base=dict_losses[name], sigma=kwargs["sigma"], ...
_losses = { "absolute": Absolute(), "logistic": Logistic(), "quadratic": Quadratic(), "zero_one": Zero_One() } def get_base(name): ''' ''' return dict_losses[name] def get_loss(name, cdf=None, pdf=None, **kwargs):
64
64
97
15
49
feedbackward/spectral
spectral/setup_losses.py
Python
get_loss
get_loss
238
251
238
238
3f1b11c91a811c00b0751d90f2fbbb5c4a523b82
bigcode/the-stack
train
e6e184b7ae20739322ca180a
train
function
def cdf_helper(u, model, loss_base, X=None, y=None): ''' A helper to be used in the driver script. Estimates the loss CDF (loss evaluated at "model"), and evalutes that CDF estimator at "u". ''' ref_losses = loss_base(model=model, X=X, y=y) ## Shape checks. if u.ndim == 2 and ref_l...
def cdf_helper(u, model, loss_base, X=None, y=None):
''' A helper to be used in the driver script. Estimates the loss CDF (loss evaluated at "model"), and evalutes that CDF estimator at "u". ''' ref_losses = loss_base(model=model, X=X, y=y) ## Shape checks. if u.ndim == 2 and ref_losses.ndim == 2: if u.shape[1] == 1 and ref_l...
helper functions for our specialized losses. def sigma_default(u, c=1.0): ''' ''' return c * np.exp(-c*(1.0-u)) / (1.0-np.exp(-c)) def cdf_helper(u, model, loss_base, X=None, y=None):
64
64
175
17
47
feedbackward/spectral
spectral/setup_losses.py
Python
cdf_helper
cdf_helper
27
44
27
27
8307491e2e6b8e18adf2e6490825096e23e7496c
bigcode/the-stack
train
2ac417d0d271a1eaaa193689
train
function
def pdf_approx_static(u, shift=0.0, scale=1.0): ''' ''' plus = (u+shift)/scale minus = (u-shift)/scale coef = 1.0 / (scale*np.sqrt(2*np.pi)) return coef * (np.exp(-minus**2/2) + np.exp(-plus**2/2))
def pdf_approx_static(u, shift=0.0, scale=1.0):
''' ''' plus = (u+shift)/scale minus = (u-shift)/scale coef = 1.0 / (scale*np.sqrt(2*np.pi)) return coef * (np.exp(-minus**2/2) + np.exp(-plus**2/2))
''' plus = (u+shift)/(scale*np.sqrt(2)) minus = (u-shift)/(scale*np.sqrt(2)) return (erf(plus)+erf(minus))/2 def pdf_approx_static(u, shift=0.0, scale=1.0):
64
64
84
19
44
feedbackward/spectral
spectral/setup_losses.py
Python
pdf_approx_static
pdf_approx_static
73
79
73
73
df3669a452aafa87afd2e490a7ff26a11a142a3a
bigcode/the-stack
train
3986b92183d65c3acee93e9c
train
function
def pdf_approx_helper(u, model, loss_base, X=None, y=None): ''' ''' ref_losses = loss_base(model=model, X=X, y=y) return pdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses))
def pdf_approx_helper(u, model, loss_base, X=None, y=None):
''' ''' ref_losses = loss_base(model=model, X=X, y=y) return pdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses))
y=None): ''' ''' ref_losses = loss_base(model=model, X=X, y=y) return cdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses)) def pdf_approx_helper(u, model, loss_base, X=None, y=None):
64
64
60
18
46
feedbackward/spectral
spectral/setup_losses.py
Python
pdf_approx_helper
pdf_approx_helper
56
62
56
56
ad2e3e2dedfcfabaaaa857f8bd72de1a77109df9
bigcode/the-stack
train
7383fc7b657455abb20e67c3
train
function
def cdf_approx_helper(u, model, loss_base, X=None, y=None): ''' ''' ref_losses = loss_base(model=model, X=X, y=y) return cdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses))
def cdf_approx_helper(u, model, loss_base, X=None, y=None):
''' ''' ref_losses = loss_base(model=model, X=X, y=y) return cdf_approx_static(u=u, shift=np.mean(ref_losses), scale=np.std(ref_losses))
keepdims=True) return out else: raise ValueError("u and ref_losses have wrong 2nd axis.") else: raise ValueError("u and ref_losses have mismatched ndim.") def cdf_approx_helper(u, model, loss_base, X=None, y=None):
63
64
62
19
44
feedbackward/spectral
spectral/setup_losses.py
Python
cdf_approx_helper
cdf_approx_helper
47
53
47
47
880deecc8fa05a937207bde36cbd8adb6b7b2ed1
bigcode/the-stack
train
1f10199cb3ba2579ec3fa81e
train
function
def sigma_default(u, c=1.0): ''' ''' return c * np.exp(-c*(1.0-u)) / (1.0-np.exp(-c))
def sigma_default(u, c=1.0):
''' ''' return c * np.exp(-c*(1.0-u)) / (1.0-np.exp(-c))
.losses.absolute import Absolute from mml.losses.classification import Zero_One from mml.losses.logistic import Logistic from mml.losses.quadratic import Quadratic ############################################################################### ## All the helper functions for our specialized losses. def sigma_defaul...
64
64
40
11
53
feedbackward/spectral
spectral/setup_losses.py
Python
sigma_default
sigma_default
21
24
21
21
9fba2dd47ce825e6e5e4e18e1b884d7d024a4cb7
bigcode/the-stack
train
7a9685ca0d9692c0db302943
train
class
class APICategory(Document): pass
class APICategory(Document):
pass
# Copyright (c) 2021, Smarty Software Pvt Ltd and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document class APICategory(Document):
43
64
8
6
36
chechani/ultima
ultima/ultima/doctype/api_category/api_category.py
Python
APICategory
APICategory
7
8
7
7
84736e2d3ee8840f1bc0b5e0ced05fd82257795c
bigcode/the-stack
train
0a829aabb434140fe46c65ba
train
class
class Range(Bot): def __init__(self, own): #Constant Properties self.MAX_RANGE = 0 # set 0 for infinite self.FIRE_SPEED = 10 # speed which bullets move #Object Properties self.target = None # will not implement for this demo se...
class Range(Bot):
def __init__(self, own): #Constant Properties self.MAX_RANGE = 0 # set 0 for infinite self.FIRE_SPEED = 10 # speed which bullets move #Object Properties self.target = None # will not implement for this demo self.amuQty = 0 ...
Bot.__init__(self,own) #States def _gather(slef): pass class Melee(Bot): def __init__(self, own): self.target = None Bot.__init__(self,own) class Range(Bot):
63
64
117
6
57
Korky/BlenderGameEngineExperiments
lib/rts/env/Bots.py
Python
Range
Range
215
234
215
217
bed66a5cc24a3cecd4ab89050805fe475ec88215
bigcode/the-stack
train
11182d1adc6041b212265fab
train
class
class Bot(types.KX_GameObject): def __init__(self, own): #backword compatibility self.scene defined by default in later blender versions #self.scene = logic.getCurrentScene() #set Bot Properties self.owner = own self.cont = logic.getCurrentController() ...
class Bot(types.KX_GameObject):
def __init__(self, own): #backword compatibility self.scene defined by default in later blender versions #self.scene = logic.getCurrentScene() #set Bot Properties self.owner = own self.cont = logic.getCurrentController() self.markerFlag = 0 s...
from bge import logic, types, render from mathutils import Vector, Quaternion from math import pi, atan2, degrees class Bot(types.KX_GameObject):
37
256
1,205
9
27
Korky/BlenderGameEngineExperiments
lib/rts/env/Bots.py
Python
Bot
Bot
5
184
5
6
bb457f47b0fa895a5ddf16d67bda32635c7ad456
bigcode/the-stack
train
e82907fc62f3cdbd4fce3c28
train
class
class Melee(Bot): def __init__(self, own): self.target = None Bot.__init__(self,own)
class Melee(Bot):
def __init__(self, own): self.target = None Bot.__init__(self,own)
, own): self.MAX_HOLD = 5 self.minerals = 0 self.mineralPatch = None Bot.__init__(self,own) #States def _gather(slef): pass class Melee(Bot):
64
64
33
7
56
Korky/BlenderGameEngineExperiments
lib/rts/env/Bots.py
Python
Melee
Melee
205
212
205
207
cc408198b4e8c32b88faa66b76f2cb70b988630a
bigcode/the-stack
train
e9698e00a0edaaaeb8695029
train
class
class Worker(Bot): def __init__(self, own): self.MAX_HOLD = 5 self.minerals = 0 self.mineralPatch = None Bot.__init__(self,own) #States def _gather(slef): pass
class Worker(Bot):
def __init__(self, own): self.MAX_HOLD = 5 self.minerals = 0 self.mineralPatch = None Bot.__init__(self,own) #States def _gather(slef): pass
_flag and draw marker if needed if self.markerFlag: delta = Vector((0,0,1)) delta.magnitude = 2.5 render.drawLine(self.worldPosition, self.worldPosition + delta, [255, 0, 0]) class Worker(Bot):
63
64
69
6
57
Korky/BlenderGameEngineExperiments
lib/rts/env/Bots.py
Python
Worker
Worker
188
203
188
189
6779f7b4852e3a8036742f6ab3d6ed998ed1ac83
bigcode/the-stack
train
199272ef968fc23c342b2d33
train
function
def create_app(configuration): app = Flask(__name__) app.config.from_object(configuration) db.init_app(app) migrate.init_app(app, db) create_api(app) return app
def create_app(configuration):
app = Flask(__name__) app.config.from_object(configuration) db.init_app(app) migrate.init_app(app, db) create_api(app) return app
from flask import Flask from api.db import db, migrate from api.api import create_api def create_app(configuration):
25
64
42
5
19
stupina/books
api/api/app.py
Python
create_app
create_app
7
13
7
7
302029f2d46d425706640389c32638fbdc53dadf
bigcode/the-stack
train
11ec728cdf2a1f0635768a48
train
class
class COBYLA(Optimizer): """Constrained Optimization By Linear Approximation algorithm. Uses scipy.optimize.minimize COBYLA See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html """ _OPTIONS = ['maxiter', 'disp', 'rhobeg'] # pylint: disable=unused-argument ...
class COBYLA(Optimizer):
"""Constrained Optimization By Linear Approximation algorithm. Uses scipy.optimize.minimize COBYLA See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html """ _OPTIONS = ['maxiter', 'disp', 'rhobeg'] # pylint: disable=unused-argument def __init__(self, ...
# obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been alt...
120
120
400
7
113
aaita92/qiskit-aqua
qiskit/aqua/components/optimizers/cobyla.py
Python
COBYLA
COBYLA
26
75
26
26
b62c29eeb912e0af31193ee46d52217b13252e82
bigcode/the-stack
train
77030250cc245810ad86a540
train
class
class TestStoragepoolSettingsExtended(unittest.TestCase): """StoragepoolSettingsExtended unit test stubs""" def setUp(self): pass def tearDown(self): pass def testStoragepoolSettingsExtended(self): """Test StoragepoolSettingsExtended""" # FIXME: construct object with m...
class TestStoragepoolSettingsExtended(unittest.TestCase):
"""StoragepoolSettingsExtended unit test stubs""" def setUp(self): pass def tearDown(self): pass def testStoragepoolSettingsExtended(self): """Test StoragepoolSettingsExtended""" # FIXME: construct object with mandatory attributes with example values # model = ...
import unittest import isi_sdk_8_1_0 from isi_sdk_8_1_0.models.storagepool_settings_extended import StoragepoolSettingsExtended # noqa: E501 from isi_sdk_8_1_0.rest import ApiException class TestStoragepoolSettingsExtended(unittest.TestCase):
64
64
101
10
53
mohitjain97/isilon_sdk_python
isi_sdk_8_1_0/test/test_storagepool_settings_extended.py
Python
TestStoragepoolSettingsExtended
TestStoragepoolSettingsExtended
23
36
23
23
f80793c5f74811f587c71b2950626ac97d28d089
bigcode/the-stack
train
1bc2f194591e9439a548efef
train
class
class BaselineTrainer(DefaultTrainer): def __init__(self, cfg): """ Args: cfg (CfgNode): Use the custom checkpointer, which loads other backbone models with matching heuristics. """ cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) ...
class BaselineTrainer(DefaultTrainer):
def __init__(self, cfg): """ Args: cfg (CfgNode): Use the custom checkpointer, which loads other backbone models with matching heuristics. """ cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) model = self.build_model(cfg) ...
torch from torch.nn.parallel import DistributedDataParallel from fvcore.nn.precise_bn import get_bn_modules import numpy as np from collections import OrderedDict import detectron2.utils.comm as comm from detectron2.checkpoint import DetectionCheckpointer from detectron2.engine import DefaultTrainer, SimpleTrainer, T...
256
256
1,289
7
248
xuewengeophysics/unbiased-teacher
ubteacher/engine/trainer.py
Python
BaselineTrainer
BaselineTrainer
35
220
35
35
59bc98e67f574c5f3809920d94a59ee39bf73bb8
bigcode/the-stack
train
26b46a14d9446ba695a82649
train
class
class UBTeacherTrainer(DefaultTrainer): def __init__(self, cfg): """ Args: cfg (CfgNode): Use the custom checkpointer, which loads other backbone models with matching heuristics. """ cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) ...
class UBTeacherTrainer(DefaultTrainer):
def __init__(self, cfg): """ Args: cfg (CfgNode): Use the custom checkpointer, which loads other backbone models with matching heuristics. """ cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) data_loader = self.build_train_loader...
cpu().item() if isinstance(v, torch.Tensor) else float(v) for k, v in metrics_dict.items() } # gather metrics among all workers for logging # This assumes we do DDP-style training, which is currently the only # supported method in detectron2. all_metrics_dict = comm.g...
256
256
3,900
7
248
xuewengeophysics/unbiased-teacher
ubteacher/engine/trainer.py
Python
UBTeacherTrainer
UBTeacherTrainer
224
661
224
224
ac4a30f337eeae94340c29f384c75dbfde8799ed
bigcode/the-stack
train
5c79846bb1c9a97ec4830c54
train
class
class TestClass(): """wrawrawra""" def __init__(self): pass def context(self): print("doc string: %s" % self.__doc__) print("class: %s" % self.__class__) print("class name: %s" % self.__class__.__name__) print("class name?: %s" % __name__) print("module: %s" ...
class TestClass():
"""wrawrawra""" def __init__(self): pass def context(self): print("doc string: %s" % self.__doc__) print("class: %s" % self.__class__) print("class name: %s" % self.__class__.__name__) print("class name?: %s" % __name__) print("module: %s" % self.__module__) ...
#!/usr/bin/python class TestClass():
9
64
107
4
4
sweetporkbones/scratchpad
python/datamodel.py
Python
TestClass
TestClass
3
14
3
3
69c99301d40f6bec0c20960fdd86837cfe186704
bigcode/the-stack
train
36940e09f3b61c0113dc3663
train
class
class AzimuthMonitoring: def getAzimuth(self, instructions): c = 0 for i in instructions: if i == "LEFT": c += 270 elif i == "RIGHT": c += 90 elif i == "TURN AROUND": c += 180 elif i.startswith("LEFT"): ...
class AzimuthMonitoring:
def getAzimuth(self, instructions): c = 0 for i in instructions: if i == "LEFT": c += 270 elif i == "RIGHT": c += 90 elif i == "TURN AROUND": c += 180 elif i.startswith("LEFT"): c -= int(i...
class AzimuthMonitoring:
5
64
115
5
0
ferhatelmas/algo
topCoder/srms/300s/srm360/div2/azimuth_monitoring.py
Python
AzimuthMonitoring
AzimuthMonitoring
1
18
1
1
79289e40ccfa3f2a5a90fbcea9cc04e2af727ddc
bigcode/the-stack
train
420ec1986ad879e35223c4f4
train
class
class FastAIMixedOptim(OptimWrapper): @classmethod def create( cls, opt_func, lr, layer_groups, model, flat_master=False, loss_scale=512.0, **kwargs, ): "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." ...
class FastAIMixedOptim(OptimWrapper): @classmethod
def create( cls, opt_func, lr, layer_groups, model, flat_master=False, loss_scale=512.0, **kwargs, ): "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." opt = OptimWrapper.create(opt_func, lr, layer_g...
_groups: pg2[key] = v return val def read_val(self, key: str): "Read a hyperparameter `key` in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] retu...
105
105
350
14
90
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
FastAIMixedOptim
FastAIMixedOptim
269
306
269
270
1e73e0a0eb06b78f1f146659373d3d2b80c5b393
bigcode/the-stack
train
7f843fdf56b0af14b97020cb
train
function
def is_tuple(x) -> bool: return isinstance(x, tuple)
def is_tuple(x) -> bool:
return isinstance(x, tuple)
len mismatch ({len(p)} vs {n})" return list(p) def trainable_params(m: nn.Module): "Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res def is_tuple(x) -> bool:
64
64
15
8
55
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
is_tuple
is_tuple
113
114
113
113
3cc0865862df478f63b13a2e19657b505517b5f6
bigcode/the-stack
train
b3f6338d9b96bb3fa479397a
train
function
def master2model(model_params, master_params, flat_master: bool = False) -> None: "Copy `master_params` to `model_params`." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(model_group) != 0: for model, master in zip( ...
def master2model(model_params, master_params, flat_master: bool = False) -> None:
"Copy `master_params` to `model_params`." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(model_group) != 0: for model, master in zip( model_group, _unflatten_dense_tensors(master_group[0].data,...
model.grad is not None: if master.grad is None: master.grad = master.data.new(*master.data.size()) master.grad.data.copy_(model.grad.data) else: master.grad = None def master2model(model_params, master_params, flat_mast...
64
64
140
20
43
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
master2model
master2model
76
89
76
76
d4c82870d407ce82bca7fca8cc9bf1e643a77239
bigcode/the-stack
train
caf7c3c181af0cfa74d7aeee
train
function
def listify(p=None, q=None): "Make `p` listy and the same length as `q`." if p is None: p = [] elif isinstance(p, str): p = [p] elif not isinstance(p, Iterable): p = [p] n = q if type(q) == int else len(p) if q is None else len(q) if len(p) == 1: p = p * n ass...
def listify(p=None, q=None):
"Make `p` listy and the same length as `q`." if p is None: p = [] elif isinstance(p, str): p = [p] elif not isinstance(p, Iterable): p = [p] n = q if type(q) == int else len(p) if q is None else len(q) if len(p) == 1: p = p * n assert len(p) == n, f"List len m...
0].data, model_group), ): model.data.copy_(master) else: for model_group, master_group in zip(model_params, master_params): for model, master in zip(model_group, master_group): model.data.copy_(master.data) def listify(p=None, q=None):
64
64
128
9
55
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
listify
listify
92
104
92
92
31faa3118afb2d9995f4df3f66fe3f8761dce196
bigcode/the-stack
train
690edd082e231ff590cfa02b
train
class
class OptimWrapper: "Basic wrapper around `opt` to simplify hyper-parameters changes." def __init__(self, opt, wd, true_wd: bool = False, bn_wd: bool = True): self.opt, self.true_wd, self.bn_wd = opt, true_wd, bn_wd self.opt_keys = list(self.opt.param_groups[0].keys()) self.opt_keys.rem...
class OptimWrapper:
"Basic wrapper around `opt` to simplify hyper-parameters changes." def __init__(self, opt, wd, true_wd: bool = False, bn_wd: bool = True): self.opt, self.true_wd, self.bn_wd = opt, true_wd, bn_wd self.opt_keys = list(self.opt.param_groups[0].keys()) self.opt_keys.remove("params") ...
unflatten_dense_tensors(master_group[0].data, model_group), ): model.data.copy_(master) else: for model_group, master_group in zip(model_params, master_params): for model, master in zip(model_group, master_group): model.data.copy_(master.data) ...
256
256
1,373
4
252
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
OptimWrapper
OptimWrapper
118
266
118
118
d000c473a5fd54e1e6c961d5cbdc6403934babc2
bigcode/the-stack
train
afeb6a3b99d8d449cb28fc30
train
function
def trainable_params(m: nn.Module): "Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res
def trainable_params(m: nn.Module):
"Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res
else len(p) if q is None else len(q) if len(p) == 1: p = p * n assert len(p) == n, f"List len mismatch ({len(p)} vs {n})" return list(p) def trainable_params(m: nn.Module):
64
64
40
9
55
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
trainable_params
trainable_params
107
110
107
107
ae83dc0bd1f0db29ff4a64d524f469644f66eef3
bigcode/the-stack
train
5c8208140bd8b18eb2e75028
train
function
def get_master(layer_groups, flat_master: bool = False): "Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32." split_groups = split_bn_bias(layer_groups) model_params = [ [param for param in lg.parameters() if param.requires_grad] for lg in split...
def get_master(layer_groups, flat_master: bool = False):
"Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32." split_groups = split_bn_bias(layer_groups) model_params = [ [param for param in lg.parameters() if param.requires_grad] for lg in split_groups ] if flat_master: master_params =...
= [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) split_groups += [nn.Sequential(*l1), nn.Sequential(*l2)] return split_groups def get_master(layer_groups, flat_master: bool = False):
68
68
228
13
54
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
get_master
get_master
28
54
28
28
67a5fe1439bb45fe4368d905c374760345e45e8f
bigcode/the-stack
train
fd803380a29e0896639670a6
train
function
def model_g2master_g(model_params, master_params, flat_master: bool = False) -> None: "Copy the `model_params` gradients to `master_params` for the optimizer step." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(master_group) != 0: m...
def model_g2master_g(model_params, master_params, flat_master: bool = False) -> None:
"Copy the `model_params` gradients to `master_params` for the optimizer step." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(master_group) != 0: master_group[0].grad.data.copy_( parameters_to_vector([p.grad.data....
() for param in lg] for lg in model_params ] for mp in master_params: for param in mp: param.requires_grad = True return model_params, master_params def model_g2master_g(model_params, master_params, flat_master: bool = False) -> None:
64
64
177
22
41
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
model_g2master_g
model_g2master_g
57
73
57
57
b32a5ed4eb7e761f5ed550965048a2999c205edb
bigcode/the-stack
train
a0f5fcd093c1495488bfb25d
train
function
def split_bn_bias(layer_groups): "Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups." split_groups = [] for l in layer_groups: l1, l2 = [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: ...
def split_bn_bias(layer_groups):
"Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups." split_groups = [] for l in layer_groups: l1, l2 = [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) ...
from torch.nn.utils import parameters_to_vector from apex.parallel.optimized_sync_batchnorm import SyncBatchNorm bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.modules.batchnorm._BatchNorm, SyncBatchNorm) def split_bn_bias(layer_groups):
64
64
104
7
57
Sundrops/CenterPoint
det3d/solver/fastai_optim.py
Python
split_bn_bias
split_bn_bias
14
25
14
14
55bf9a14eb23752804cf61a6dffc275fdda3bf22
bigcode/the-stack
train
147074866570a73d1936b574
train
function
@_() @click.argument('template_name', required=True) @click.argument('path', required=False, type=click.Path(exists=True)) def new(template_name,path='.'): ''' For use a folder as template''' path = os.path.abspath(path) listdir = [] for path_, dir_, file_ in os.walk(path): listdir.append({'path':path_[len(...
@_() @click.argument('template_name', required=True) @click.argument('path', required=False, type=click.Path(exists=True)) def new(template_name,path='.'):
''' For use a folder as template''' path = os.path.abspath(path) listdir = [] for path_, dir_, file_ in os.walk(path): listdir.append({'path':path_[len(path+'/'):],'dirs':dir_ ,'files': s(path_,file_)}) tmplt[template_name] = listdir json.dump(tmplt, open(tmplt_file,'w')) click.secho(f'{path} successf...
os.path.isfile(path+'/'+name): dct[name] = str(open(path+'/'+name,'rb').read()) return dct @_() @click.argument('template_name', required=True) @click.argument('path', required=False, type=click.Path(exists=True)) def new(template_name,path='.'):
63
64
143
35
27
sayampy/Template-Manager-Tool
templater/main.py
Python
new
new
46
57
46
49
d7a3f7915508b225a50fe7974a17a4eea2bf39c8
bigcode/the-stack
train
9bb8565a3e6a1c66c7cafe17
train
function
def s(path, dlist:list): dct = {} for name in dlist: if os.path.isfile(path+'/'+name): dct[name] = str(open(path+'/'+name,'rb').read()) return dct
def s(path, dlist:list):
dct = {} for name in dlist: if os.path.isfile(path+'/'+name): dct[name] = str(open(path+'/'+name,'rb').read()) return dct
issue tracking url') def main(): ''' \t\tTemplate Project Manager\n It will help you to speed up your workflow. It loads a basic project structure on a subject. --sayam(creator)\n Happy Coding..''' pass _ = main.command def s(path, dlist:list):
64
64
50
8
55
sayampy/Template-Manager-Tool
templater/main.py
Python
s
s
37
42
37
37
40ffeedc21f5706e6b7ea6541013848ba33cc5eb
bigcode/the-stack
train
db90853d4bdd53b28f73d8e4
train
function
def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo(f'You are using templater version:{templater.__version__}') ctx.exit()
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing: return click.echo(f'You are using templater version:{templater.__version__}') ctx.exit()
''' Template Manager Tool ''' import click, os, subprocess as sp import json, templater from random import randint tmplt_file = templater.__file__.replace('__init__.py','templates.py') tmplt=json.load(open(tmplt_file,'r')) def print_version(ctx, param, value):
64
64
46
9
55
sayampy/Template-Manager-Tool
templater/main.py
Python
print_version
print_version
10
14
10
10
d2cf3d74a41b8db61718f17fe9feabfcaa7455fc
bigcode/the-stack
train
cfaca7a77501933b52679fba
train
function
@_() def show(): ''' shows available templates''' click.secho('\n'.join(tmplt.keys()), fg='blue')
@_() def show():
''' shows available templates''' click.secho('\n'.join(tmplt.keys()), fg='blue')
':dir_ ,'files': s(path_,file_)}) tmplt[template_name] = listdir json.dump(tmplt, open(tmplt_file,'w')) click.secho(f'{path} successfully Init as Template, "{template_name}"',fg='blue') @_() def show():
64
64
29
6
58
sayampy/Template-Manager-Tool
templater/main.py
Python
show
show
59
63
59
60
ee02698d281a02dcebc54611fbf25256b6df3fab
bigcode/the-stack
train
8e660f2bbae720573a0ac0da
train
function
@click.group() @click.option('--version','-V', is_flag=True, callback=print_version, expose_value=False, is_eager=True,help='shows the version of this cli app') @click.option('--issue','-i',is_flag=True, callback=print_issue, expose_value=False, is_eager=True,help='shows github issue trackin...
@click.group() @click.option('--version','-V', is_flag=True, callback=print_version, expose_value=False, is_eager=True,help='shows the version of this cli app') @click.option('--issue','-i',is_flag=True, callback=print_issue, expose_value=False, is_eager=True,help='shows github issue trackin...
''' \t\tTemplate Project Manager\n It will help you to speed up your workflow. It loads a basic project structure on a subject. --sayam(creator)\n Happy Coding..''' pass
@click.group() @click.option('--version','-V', is_flag=True, callback=print_version, expose_value=False, is_eager=True,help='shows the version of this cli app') @click.option('--issue','-i',is_flag=True, callback=print_issue, expose_value=False, is_eager=True,help='shows github issue trackin...
78
64
122
78
0
sayampy/Template-Manager-Tool
templater/main.py
Python
main
main
21
33
21
26
f277dc46ec5bf7492f8514d48c4f06e6ded0e101
bigcode/the-stack
train
45970f74c0cadd452331be6d
train
function
def print_issue(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo(f'post your issue on {templater.issue_track}') ctx.exit()
def print_issue(ctx, param, value):
if not value or ctx.resilient_parsing: return click.echo(f'post your issue on {templater.issue_track}') ctx.exit()
=json.load(open(tmplt_file,'r')) def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo(f'You are using templater version:{templater.__version__}') ctx.exit() def print_issue(ctx, param, value):
64
64
42
9
55
sayampy/Template-Manager-Tool
templater/main.py
Python
print_issue
print_issue
15
19
15
15
cdb41006b98c60c216a8581e69308a1415052c64
bigcode/the-stack
train
2b16e578f1d803cb30bb3738
train
function
@_() @click.argument('project_name', required=True) @click.argument('template_name', required=True) def load(template_name, project_name): ''' Load a template on your Project. $ tmt load <PROJECT_NAME> <TEMPLATE_NAME> after load, you will see a folder on current dir as your project name. ''' if template_name...
@_() @click.argument('project_name', required=True) @click.argument('template_name', required=True) def load(template_name, project_name):
''' Load a template on your Project. $ tmt load <PROJECT_NAME> <TEMPLATE_NAME> after load, you will see a folder on current dir as your project name. ''' if template_name not in tmplt: click.secho(f'''![ERROR]: Not Found Template \"{template_name}\" For see available templates use *tpm show*''',fg="r...
'{path} successfully Init as Template, "{template_name}"',fg='blue') @_() def show(): ''' shows available templates''' click.secho('\n'.join(tmplt.keys()), fg='blue') @_() @click.argument('project_name', required=True) @click.argument('template_name', required=True) def load(template_name, project_name):
75
75
252
29
46
sayampy/Template-Manager-Tool
templater/main.py
Python
load
load
65
92
65
68
23c5a872c89378820c1f6a3af57f675242dc42e1
bigcode/the-stack
train
91cf34bfd2a3cfc1e5e65e58
train
function
@_() @click.argument('template_name',required=True) @click.option('--confirm','-c',type=click.Choice(['yes','no'],case_sensitive=False), prompt='Confirmation[yes/no]: ') def remove(template_name,confirm): '''For Removing Templates''' if confirm == 'no': click.echo('Command Canceled') return template=tmplt...
@_() @click.argument('template_name',required=True) @click.option('--confirm','-c',type=click.Choice(['yes','no'],case_sensitive=False), prompt='Confirmation[yes/no]: ') def remove(template_name,confirm):
'''For Removing Templates''' if confirm == 'no': click.echo('Command Canceled') return template=tmplt.get(template_name) if template==None: click.secho(f"No '{template_name}' template found",fg='red') return tmplt.pop(template_name) json.dump(tmplt,open(tmplt_file,'w')) click.secho(f'{temp...
template {template_name} successfully loaded on {project_name} dir") @_() @click.argument('template_name',required=True) @click.option('--confirm','-c',type=click.Choice(['yes','no'],case_sensitive=False), prompt='Confirmation[yes/no]: ') def remove(template_name,confirm):
63
64
144
49
14
sayampy/Template-Manager-Tool
templater/main.py
Python
remove
remove
95
110
95
99
ce27031823433e7a358dfc12dca994732c6632ad
bigcode/the-stack
train
5807a09809ea1f2b89636dad
train
class
class MyTestCase(unittest.TestCase): def test_something(self): s = os.path.join('demo1/os_path_test.py', '.*path.*.json') print(s) self.assertEqual(True, True)
class MyTestCase(unittest.TestCase):
def test_something(self): s = os.path.join('demo1/os_path_test.py', '.*path.*.json') print(s) self.assertEqual(True, True)
import unittest import os class MyTestCase(unittest.TestCase):
14
64
48
8
5
54070356/python-tutorial
core/os_path_test.py
Python
MyTestCase
MyTestCase
5
9
5
5
f519e2d0fee6487e6a26176a9c911cdb63b8ff2c
bigcode/the-stack
train
2ca51b7ea64da104c146e31c
train
class
class LoginForm(FlaskForm): email = EmailField(label="Email", validators=[DataRequired(), Email()], render_kw={"autocomplete": "off"}) password = PasswordField(label="Password", validators=[DataRequired(), Length(min=8)]) submit = SubmitField(label="Log In", render_kw={"class_": "btn btn-success"})
class LoginForm(FlaskForm):
email = EmailField(label="Email", validators=[DataRequired(), Email()], render_kw={"autocomplete": "off"}) password = PasswordField(label="Password", validators=[DataRequired(), Length(min=8)]) submit = SubmitField(label="Log In", render_kw={"class_": "btn btn-success"})
more"}) confirm_password = PasswordField(label="Confirm Password", validators=[DataRequired(), Length(min=8)], render_kw={"placeholder": "Re-type password"}) submit = SubmitField(label="Register", render_kw={"class_": "btn btn-success"}) class LoginForm(FlaskForm):
63
64
72
8
55
alvin-c-cruz/accounting
accounting/blueprints/user/forms.py
Python
LoginForm
LoginForm
19
22
19
19
bc4f55c2abf5a8c3f787ab81387f45d86f4235c9
bigcode/the-stack
train
989866debd5de64167ae5516
train
class
class UserForm(FlaskForm): name = StringField(label="Name", validators=[DataRequired()], render_kw={"autocomplete": "off", "placeholder": "Type your name here"}) email = EmailField(label="Email", validators=[DataRequired(), Email()], render_kw={"autocomplete": "off"...
class UserForm(FlaskForm):
name = StringField(label="Name", validators=[DataRequired()], render_kw={"autocomplete": "off", "placeholder": "Type your name here"}) email = EmailField(label="Email", validators=[DataRequired(), Email()], render_kw={"autocomplete": "off", "placeholder": "Type your...
from flask_wtf import FlaskForm from wtforms import StringField, EmailField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class UserForm(FlaskForm):
44
64
161
8
35
alvin-c-cruz/accounting
accounting/blueprints/user/forms.py
Python
UserForm
UserForm
6
16
6
6
cc0c49211d3fd70fac817a8d901e9ddda128bb8f
bigcode/the-stack
train
634553af14cc8311bbededa0
train
class
class Notification(models.Model): #Srtp消息通知 notifi_id = models.IntegerField(default=123, unique=True, verbose_name=u'通知id') notifi_date = models.DateField(default=timezone.now, verbose_name=u'通知发布时间') notifi_title = models.CharField(blank=False, null=False, max_length=50, default='未命名消息通知', verbose_nam...
class Notification(models.Model): #Srtp消息通知
notifi_id = models.IntegerField(default=123, unique=True, verbose_name=u'通知id') notifi_date = models.DateField(default=timezone.now, verbose_name=u'通知发布时间') notifi_title = models.CharField(blank=False, null=False, max_length=50, default='未命名消息通知', verbose_name=u'通知标题') notifi_content = models.TextField(...
未选班级', unique=True, verbose_name=u'班级名') class Meta: verbose_name = u'班级信息' verbose_name_plural = verbose_name def __str__(self): return self.class_name class Notification(models.Model): #Srtp消息通知
64
64
192
13
50
LittleBai0606/TeachingSecretarySystem
TSSystem/apps/main_platform/models.py
Python
Notification
Notification
39
57
39
41
d96d1fb8ee930cf2c0fa1c9efee26766e5e20058
bigcode/the-stack
train
a4f016a8b7a68b2ef647568a
train
class
class NotifiFile(models.Model): #Srtp消息通知附件 notifi_belong = models.ForeignKey(Notification, on_delete=models.CASCADE, verbose_name=u'所属通知') notifi_file_name = models.CharField(blank=True, null=True, max_length=100, default='暂未命名' , verbose_name=u'通知附件名称') notifi_file_url = models.FileField(blank=True, ...
class NotifiFile(models.Model): #Srtp消息通知附件
notifi_belong = models.ForeignKey(Notification, on_delete=models.CASCADE, verbose_name=u'所属通知') notifi_file_name = models.CharField(blank=True, null=True, max_length=100, default='暂未命名' , verbose_name=u'通知附件名称') notifi_file_url = models.FileField(blank=True, null=True, unique=True, upload_to='SrtpNotificati...
%s]' %(self.notifi_id, self.notifi_title) def save(self, *args, **kwargs): self.notifi_id = int(time.time()) super(Notification, self).save(*args, **kwargs) class NotifiFile(models.Model): #Srtp消息通知附件
64
64
198
16
48
LittleBai0606/TeachingSecretarySystem
TSSystem/apps/main_platform/models.py
Python
NotifiFile
NotifiFile
61
78
61
63
8b2a8f8d9e9a031e135590c1130832fa6ee21cd6
bigcode/the-stack
train
9a34104eb0c3e5ceba268f30
train
class
class Grade(models.Model): GRADE_CHOICE = ( ('Grade_one', '大一'), ('Grade_two', '大二'), ('Grade_three', '大三'), ('Grade_four', '大四'), ) grade_name = models.CharField(null=False, blank=False, default='Grade_one', max_length=11, unique=True, choices=GRADE_CHOICE, verbose_name=u'...
class Grade(models.Model):
GRADE_CHOICE = ( ('Grade_one', '大一'), ('Grade_two', '大二'), ('Grade_three', '大三'), ('Grade_four', '大四'), ) grade_name = models.CharField(null=False, blank=False, default='Grade_one', max_length=11, unique=True, choices=GRADE_CHOICE, verbose_name=u'年级名') class Meta: ...
from django.db import models from django.utils import timezone import time # Create your models here. class Grade(models.Model):
26
64
127
5
21
LittleBai0606/TeachingSecretarySystem
TSSystem/apps/main_platform/models.py
Python
Grade
Grade
7
23
7
8
1c8876886f3162be5b1a30c848ad9edb271534de
bigcode/the-stack
train
9d2e125e7e51512efb5bab9b
train
class
class Class(models.Model): grade_belong = models.ForeignKey(Grade, on_delete=models.CASCADE, verbose_name=u'所属年级') class_name = models.CharField(null=False, blank=False, max_length=20, default='未选班级', unique=True, verbose_name=u'班级名') class Meta: verbose_name = u'班级信息' verbose_name_plural ...
class Class(models.Model):
grade_belong = models.ForeignKey(Grade, on_delete=models.CASCADE, verbose_name=u'所属年级') class_name = models.CharField(null=False, blank=False, max_length=20, default='未选班级', unique=True, verbose_name=u'班级名') class Meta: verbose_name = u'班级信息' verbose_name_plural = verbose_name def __st...
max_length=11, unique=True, choices=GRADE_CHOICE, verbose_name=u'年级名') class Meta: verbose_name = u'年级信息' verbose_name_plural = verbose_name def __str__(self): return self.get_grade_name_display() class Class(models.Model):
64
64
100
5
59
LittleBai0606/TeachingSecretarySystem
TSSystem/apps/main_platform/models.py
Python
Class
Class
26
36
26
27
7263bc5ee93aa89156c77714c395efd84cef8151
bigcode/the-stack
train
281a5a77c37203a5053228d0
train
function
@raises(NotImplementedError) def test_raises_type_error(): BaseController().show("")
@raises(NotImplementedError) def test_raises_type_error():
BaseController().show("")
from jinja2 import Template from nose.tools import raises from ketchlip.controllers.base_controller import BaseController from ketchlip.views.search_view import SearchView @raises(NotImplementedError) def test_raises_type_error():
48
64
19
13
34
harshp8l/deep-learning-lang-detection
data/test/python/de428bc4dfdd644bec79b9a7e2d59f5d28c8f828base_controller_test.py
Python
test_raises_type_error
test_raises_type_error
6
8
6
7
269d1363e54decaf956b7c213987d5fed9b7bd4f
bigcode/the-stack
train
1e839f7bd9e83299ad0eef24
train
function
def test_get_template(): controller = BaseController() controller.name = "search" assert isinstance(controller.get_template(), Template)
def test_get_template():
controller = BaseController() controller.name = "search" assert isinstance(controller.get_template(), Template)
from ketchlip.views.search_view import SearchView @raises(NotImplementedError) def test_raises_type_error(): BaseController().show("") def test_get_view(): controller = BaseController() controller.name = "search" assert isinstance(controller.get_view(), SearchView) def test_get_template():
64
64
27
5
59
harshp8l/deep-learning-lang-detection
data/test/python/de428bc4dfdd644bec79b9a7e2d59f5d28c8f828base_controller_test.py
Python
test_get_template
test_get_template
15
18
15
15
a5a11a0323f36e7f5a5257c31fcfcbd6c320617f
bigcode/the-stack
train
2fbcc4e3dc10f9deb72e68f3
train
function
def test_get_view(): controller = BaseController() controller.name = "search" assert isinstance(controller.get_view(), SearchView)
def test_get_view():
controller = BaseController() controller.name = "search" assert isinstance(controller.get_view(), SearchView)
from jinja2 import Template from nose.tools import raises from ketchlip.controllers.base_controller import BaseController from ketchlip.views.search_view import SearchView @raises(NotImplementedError) def test_raises_type_error(): BaseController().show("") def test_get_view():
59
64
28
5
54
harshp8l/deep-learning-lang-detection
data/test/python/de428bc4dfdd644bec79b9a7e2d59f5d28c8f828base_controller_test.py
Python
test_get_view
test_get_view
10
13
10
10
ac22f3922dbdb62b34dee38bb87bf2e9eae5ab88
bigcode/the-stack
train
5571940921495aed8dbd4ac8
train
class
class MirParser(object): """ General class for reading Mir datasets. Does lots of cool things! There are static functions that allow you low level access to mir files without needing to create an object. You can also instantiate a MirParser object with the constructor of this class which will only...
class MirParser(object):
""" General class for reading Mir datasets. Does lots of cool things! There are static functions that allow you low level access to mir files without needing to create an object. You can also instantiate a MirParser object with the constructor of this class which will only read the metadata in...
= np.dtype( [("v_name", "S12"), ("icode", np.int16), ("code", "S26"), ("ncode", np.int16)] ) we_dtype = np.dtype( [ ("scanNumber", np.int32), ("flags", np.int32, 11), ("N", np.float32, 11), ("Tamb", np.float32, 11), ("pressure", np.float32, 11), ("humid", np.flo...
255
256
5,777
5
250
e-koch/pyuvdata
pyuvdata/uvdata/mir_parser.py
Python
MirParser
MirParser
214
927
214
214
a2a234cc62cad532d5ea0df32adf89f747493bb6
bigcode/the-stack
train
b361501aa876f12e0c1ebb10
train
function
def test_Leauthaud11c(): """ """ model_highz = PrebuiltHodModelFactory('leauthaud11', redshift=2.) halocat = FakeSim(redshift=2.) model_highz.populate_mock(halocat)
def test_Leauthaud11c():
""" """ model_highz = PrebuiltHodModelFactory('leauthaud11', redshift=2.) halocat = FakeSim(redshift=2.) model_highz.populate_mock(halocat)
opulate with a different halocat raises an exception with pytest.raises(HalotoolsError) as err: model.populate_mock(halocat) # default redshift != 2 substr = "" assert substr in err.value.args[0] def test_Leauthaud11c():
64
64
56
9
55
mclaughlin6464/halotools_old
halotools/empirical_models/composite_models/tests/test_preloaded_models.py
Python
test_Leauthaud11c
test_Leauthaud11c
46
51
46
46
382985519466b9dfdef4f69916b2ce4041fb5ae3
bigcode/the-stack
train
86e48700ecdd62de83bb49f9
train
function
def test_Leauthaud11(): """ """ model = PrebuiltHodModelFactory('leauthaud11') halocat = FakeSim() model.populate_mock(halocat)
def test_Leauthaud11():
""" """ model = PrebuiltHodModelFactory('leauthaud11') halocat = FakeSim() model.populate_mock(halocat)
15b') def test_hearin15(): """ """ model = PrebuiltHodModelFactory('hearin15') try: halocat = CachedHaloCatalog() except: halocat = FakeSim() model.populate_mock(halocat) def test_Leauthaud11():
64
64
42
8
56
mclaughlin6464/halotools_old
halotools/empirical_models/composite_models/tests/test_preloaded_models.py
Python
test_Leauthaud11
test_Leauthaud11
26
31
26
26
ab8449cac4ff6b53ca7d77267a23526503cf388e
bigcode/the-stack
train
c02fa7ceec6d9a7f282d3ff2
train
function
def test_zu_mandelbaum15b(): """ """ halocat = FakeSim() model = PrebuiltHodModelFactory('zu_mandelbaum15', prim_haloprop_key='halo_mvir') model.populate_mock(halocat)
def test_zu_mandelbaum15b():
""" """ halocat = FakeSim() model = PrebuiltHodModelFactory('zu_mandelbaum15', prim_haloprop_key='halo_mvir') model.populate_mock(halocat)
_Leauthaud11c(): """ """ model_highz = PrebuiltHodModelFactory('leauthaud11', redshift=2.) halocat = FakeSim(redshift=2.) model_highz.populate_mock(halocat) def test_zu_mandelbaum15b():
64
64
55
10
54
mclaughlin6464/halotools_old
halotools/empirical_models/composite_models/tests/test_preloaded_models.py
Python
test_zu_mandelbaum15b
test_zu_mandelbaum15b
54
59
54
54
e085074fd918b68cc3990becd74b449b0b50c372
bigcode/the-stack
train
41a03a531798d87af1ae6151
train
function
def test_hearin15(): """ """ model = PrebuiltHodModelFactory('hearin15') try: halocat = CachedHaloCatalog() except: halocat = FakeSim() model.populate_mock(halocat)
def test_hearin15():
""" """ model = PrebuiltHodModelFactory('hearin15') try: halocat = CachedHaloCatalog() except: halocat = FakeSim() model.populate_mock(halocat)
Error __all__ = ('test_hearin15', 'test_Leauthaud11', 'test_Leauthaud11b', 'test_Leauthaud11c', 'test_zu_mandelbaum15', 'test_zu_mandelbaum15b') def test_hearin15():
64
64
53
6
58
mclaughlin6464/halotools_old
halotools/empirical_models/composite_models/tests/test_preloaded_models.py
Python
test_hearin15
test_hearin15
15
23
15
15
7bcb7725af68a3012b342701b122b5a850724ba4
bigcode/the-stack
train
adc54543aa4620298f2e6924
train
function
def test_Leauthaud11b(): """ """ model = PrebuiltHodModelFactory('leauthaud11') halocat = FakeSim(redshift=2.) # Test that an attempt to repopulate with a different halocat raises an exception with pytest.raises(HalotoolsError) as err: model.populate_mock(halocat) # default redshift != ...
def test_Leauthaud11b():
""" """ model = PrebuiltHodModelFactory('leauthaud11') halocat = FakeSim(redshift=2.) # Test that an attempt to repopulate with a different halocat raises an exception with pytest.raises(HalotoolsError) as err: model.populate_mock(halocat) # default redshift != 2 substr = "" ass...
ocat = FakeSim() model.populate_mock(halocat) def test_Leauthaud11(): """ """ model = PrebuiltHodModelFactory('leauthaud11') halocat = FakeSim() model.populate_mock(halocat) def test_Leauthaud11b():
64
64
102
9
55
mclaughlin6464/halotools_old
halotools/empirical_models/composite_models/tests/test_preloaded_models.py
Python
test_Leauthaud11b
test_Leauthaud11b
34
43
34
34
0aaa73ffb3327dd822b9ee7fd22b2d2e7aef3d99
bigcode/the-stack
train
def8b8df8c0dd6c16704ed5e
train
class
class Run(ConfigurationMixIn): """base class providing common behaviour for pyreverse commands""" options = OPTIONS def __init__(self, args): ConfigurationMixIn.__init__(self, usage=__doc__) insert_default_options() self.manager = ASTNGManager() self.register_options_provid...
class Run(ConfigurationMixIn):
"""base class providing common behaviour for pyreverse commands""" options = OPTIONS def __init__(self, args): ConfigurationMixIn.__init__(self, usage=__doc__) insert_default_options() self.manager = ASTNGManager() self.register_options_provider(self.manager) args =...
", dict(short="o", dest="output_format", action="store", default="dot", metavar="<format>", help="create a *.<format> output file if format available.")), ) # FIXME : quiet mode #( ('quiet', #dict(help='run quietly', action='store_true', short='q')), ) class Run(Configur...
76
76
254
6
70
tlksio/tlksio
env/lib/python3.4/site-packages/pylint/pyreverse/main.py
Python
Run
Run
87
120
87
87
7278784e5b4b60a5ec40bb58dfc88648f7b17418
bigcode/the-stack
train
d399f6894f73ce01a7711092
train
class
class ThicknessOptions(beam.utils.options.PipelineOptions): @classmethod def _add_argparse_args(cls, parser): parser.add_argument( "--input", dest="input", default="data/set_train/train_10[01].nii" ) parser.add_argument( "--output", ...
class ThicknessOptions(beam.utils.options.PipelineOptions): @classmethod
def _add_argparse_args(cls, parser): parser.add_argument( "--input", dest="input", default="data/set_train/train_10[01].nii" ) parser.add_argument( "--output", dest="output", default="output/cortical_thickness" )...
import apache_beam as beam import healthybrains import healthybrains.inputoutput import healthybrains.thickness class ThicknessOptions(beam.utils.options.PipelineOptions): @classmethod
38
64
82
15
22
Enucatl/machine-learning-healthy-brains
frontal_thickness.py
Python
ThicknessOptions
ThicknessOptions
7
20
7
9
715daa936428e20c2b30193fc5f3eda9dea20159
bigcode/the-stack
train
9cdf17f32193cc0358a0acce
train
class
class AllUrlsTest(TestCase): def setUp(self): super(AllUrlsTest, self).setUp() def test_responses(self, allowed_http_codes=None, default_kwargs=None, quiet=False): """ This is a very liberal test, we are mostly just concerned with making sure that no pages throw err...
class AllUrlsTest(TestCase):
def setUp(self): super(AllUrlsTest, self).setUp() def test_responses(self, allowed_http_codes=None, default_kwargs=None, quiet=False): """ This is a very liberal test, we are mostly just concerned with making sure that no pages throw errors (500). Adapted fro...
import importlib from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase class AllUrlsTest(TestCase):
33
238
795
7
25
divad12/studio
contentcuration/contentcuration/tests/test_urlendpoints.py
Python
AllUrlsTest
AllUrlsTest
8
93
8
9
9e71027644653172ce56e3b98b3c204881e7ca15
bigcode/the-stack
train
750b2e4e4e736600009e1cd7
train
class
class DefaultArgumentHandlerTestCase(unittest.TestCase): def setUp(self) -> None: self.handler = DefaultArgumentHandler() def test_kwargs_x(self): mono_data = {"X": "This is a sample input"} mono_args = self.handler(**mono_data) self.assertTrue(isinstance(mono_args, list)) ...
class DefaultArgumentHandlerTestCase(unittest.TestCase):
def setUp(self) -> None: self.handler = DefaultArgumentHandler() def test_kwargs_x(self): mono_data = {"X": "This is a sample input"} mono_args = self.handler(**mono_data) self.assertTrue(isinstance(mono_args, list)) self.assertEqual(len(mono_args), 1) multi_da...
largest city in France is Lyon</s>", "score": 0.21112334728240967, "token": 12790}, ], ] expected_fill_mask_target_result = [ [ { "sequence": "<s>My name is Patrick</s>", "score": 0.004992353264242411, "token": 3499, "token_str": "ĠPatrick", }, ...
180
180
601
10
170
suliuzh/transformers
tests/test_pipelines.py
Python
DefaultArgumentHandlerTestCase
DefaultArgumentHandlerTestCase
68
137
68
68
e53b14579af124adbe95e0515bb6358efa55c02c
bigcode/the-stack
train
955228c9a9f3d22bd9b3b3b3
train
class
class MonoColumnInputTestCase(unittest.TestCase): def _test_mono_column_pipeline( self, nlp: Pipeline, valid_inputs: List, output_keys: Iterable[str], invalid_inputs: List = [None], expected_multi_result: Optional[List] = None, expected_check_keys: Optional[Li...
class MonoColumnInputTestCase(unittest.TestCase):
def _test_mono_column_pipeline( self, nlp: Pipeline, valid_inputs: List, output_keys: Iterable[str], invalid_inputs: List = [None], expected_multi_result: Optional[List] = None, expected_check_keys: Optional[List[str]] = None, **kwargs, ): ...
is a second sample input 2"], } multi_args = self.handler(**multi_data) self.assertTrue(isinstance(multi_args, list)) self.assertEqual(len(multi_args), 4) def test_args(self): mono_data = "This is a sample input" mono_args = self.handler(mono_data) self.as...
256
256
4,083
10
246
suliuzh/transformers
tests/test_pipelines.py
Python
MonoColumnInputTestCase
MonoColumnInputTestCase
140
497
140
140
8b1b4cd4fc2535ebd71cb787ef556cbcceb83006
bigcode/the-stack
train
5f2814d391f058cd843e6c72
train
class
class DialoguePipelineTests(unittest.TestCase): def _test_conversation_pipeline(self, nlp): valid_inputs = [Conversation("Hi there!"), [Conversation("Hi there!"), Conversation("How are you?")]] invalid_inputs = ["Hi there!", Conversation()] self.assertIsNotNone(nlp) mono_result = nl...
class DialoguePipelineTests(unittest.TestCase):
def _test_conversation_pipeline(self, nlp): valid_inputs = [Conversation("Hi there!"), [Conversation("Hi there!"), Conversation("How are you?")]] invalid_inputs = ["Hi there!", Conversation()] self.assertIsNotNone(nlp) mono_result = nlp(valid_inputs[0]) self.assertIsInstance...
pipeline(task="zero-shot-classification", model="roberta-large-mnli") self._test_zero_shot_pipeline_outputs(nlp) @require_tf @slow def test_tf_zero_shot_outputs(self): nlp = pipeline(task="zero-shot-classification", model="roberta-large-mnli", framework="tf") self._test_zero_shot_p...
93
93
311
8
85
suliuzh/transformers
tests/test_pipelines.py
Python
DialoguePipelineTests
DialoguePipelineTests
635
666
635
635
6d4ec0284f9d1c41096e4674b2e7bccb1449d7cc
bigcode/the-stack
train
13ece86133cd1021c0c4e1cb
train
class
class PipelineCommonTests(unittest.TestCase): pipelines = SUPPORTED_TASKS.keys() @require_tf @slow def test_tf_defaults(self): # Test that pipelines can be correctly loaded without any argument for task in self.pipelines: with self.subTest(msg="Testing TF defaults with TF an...
class PipelineCommonTests(unittest.TestCase):
pipelines = SUPPORTED_TASKS.keys() @require_tf @slow def test_tf_defaults(self): # Test that pipelines can be correctly loaded without any argument for task in self.pipelines: with self.subTest(msg="Testing TF defaults with TF and {}".format(task)): pipeline(...
TF_NER_FINETUNED_MODELS: # We don't specificy framework='tf' but it gets detected automatically nlp = pipeline(task="ner", model=model_name, tokenizer=model_name) self._test_ner_pipeline(nlp, mandatory_keys) class PipelineCommonTests(unittest.TestCase):
64
64
151
8
56
suliuzh/transformers
tests/test_pipelines.py
Python
PipelineCommonTests
PipelineCommonTests
821
840
821
821
cc11c82800a2cadbaf7cee90d2eeea7b624c133f
bigcode/the-stack
train
2596e9ae8e7a04a482919fb7
train
class
class NerPipelineTests(unittest.TestCase): def _test_ner_pipeline( self, nlp: Pipeline, output_keys: Iterable[str], ): ungrouped_ner_inputs = [ [ {"entity": "B-PER", "index": 1, "score": 0.9994944930076599, "word": "Cons"}, {"entity": ...
class NerPipelineTests(unittest.TestCase):
def _test_ner_pipeline( self, nlp: Pipeline, output_keys: Iterable[str], ): ungrouped_ner_inputs = [ [ {"entity": "B-PER", "index": 1, "score": 0.9994944930076599, "word": "Cons"}, {"entity": "B-PER", "index": 2, "score": 0.80254495143...
NotNone(nlp) mono_result = nlp(valid_inputs[0]) self.assertIsInstance(mono_result, dict) for key in output_keys: self.assertIn(key, mono_result) multi_result = nlp(valid_inputs) self.assertIsInstance(multi_result, list) self.assertIsInstance(multi_result[0]...
256
256
1,392
8
248
suliuzh/transformers
tests/test_pipelines.py
Python
NerPipelineTests
NerPipelineTests
717
818
717
717
00506e09a03ba5eb8257787ce46e788ab3eab863
bigcode/the-stack
train
dee106ad69567ddba32cdff4
train
class
class ZeroShotClassificationPipelineTests(unittest.TestCase): def _test_scores_sum_to_one(self, result): sum = 0.0 for score in result["scores"]: sum += score self.assertAlmostEqual(sum, 1.0) def _test_zero_shot_pipeline(self, nlp): output_keys = {"sequence", "labels...
class ZeroShotClassificationPipelineTests(unittest.TestCase):
def _test_scores_sum_to_one(self, result): sum = 0.0 for score in result["scores"]: sum += score self.assertAlmostEqual(sum, 1.0) def _test_zero_shot_pipeline(self, nlp): output_keys = {"sequence", "labels", "scores"} valid_mono_inputs = [ {"seque...
0) # When result = nlp(conversation_1, do_sample=False, max_length=36) # Then self.assertEqual(result, conversation_1) self.assertEqual(len(result.past_user_inputs), 1) self.assertEqual(len(result.generated_responses), 1) self.assertEqual(result.past_user_inputs[...
255
256
1,649
10
245
suliuzh/transformers
tests/test_pipelines.py
Python
ZeroShotClassificationPipelineTests
ZeroShotClassificationPipelineTests
503
632
503
503
f59d6a5de9393f59d419be1359b372eb6c3531cc
bigcode/the-stack
train
0ec912949bb5dd629dde93ab
train
class
class QAPipelineTests(unittest.TestCase): def _test_qa_pipeline(self, nlp): output_keys = {"score", "answer", "start", "end"} valid_inputs = [ {"question": "Where was HuggingFace founded ?", "context": "HuggingFace was founded in Paris."}, { "question": "In wh...
class QAPipelineTests(unittest.TestCase):
def _test_qa_pipeline(self, nlp): output_keys = {"score", "answer", "start", "end"} valid_inputs = [ {"question": "Where was HuggingFace founded ?", "context": "HuggingFace was founded in Paris."}, { "question": "In what field is HuggingFace working ?", ...
_torch @slow def test_torch_conversation(self): for model_name in DIALOGUE_FINETUNED_MODELS: nlp = pipeline(task="conversational", model=model_name, tokenizer=model_name) self._test_conversation_pipeline(nlp) @require_tf @slow def test_tf_conversation(self): ...
134
134
449
9
125
suliuzh/transformers
tests/test_pipelines.py
Python
QAPipelineTests
QAPipelineTests
669
714
669
669
054ee4aca12c54c2a1814366f98dccd5ff133b83
bigcode/the-stack
train