content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" netrd ----- netrd stands for Network Reconstruction and Distances. It is a repository of different algorithms for constructing a network from time series data, as well as for comparing two networks. It is the product of the Network Science Insitute 2019 Collabathon. """ from . import distance # noqa from . import reconstruction # noqa from . import dynamics # noqa from . import utilities # noqa
[ 37811, 198, 3262, 4372, 198, 30934, 198, 198, 3262, 4372, 6296, 329, 7311, 45060, 290, 4307, 1817, 13, 632, 318, 257, 16099, 198, 1659, 1180, 16113, 329, 30580, 257, 3127, 422, 640, 2168, 1366, 11, 198, 292, 880, 355, 329, 14176, 734,...
4.049505
101
from transformer import Encoder from torch import nn,optim from torch.nn.functional import cross_entropy,softmax, relu from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate import torch import utils import os import pickle if __name__ == "__main__": train()
[ 6738, 47385, 1330, 14711, 12342, 198, 6738, 28034, 1330, 299, 77, 11, 40085, 198, 6738, 28034, 13, 20471, 13, 45124, 1330, 3272, 62, 298, 28338, 11, 4215, 9806, 11, 823, 84, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 19...
3.057143
105
import numpy as np import pandas as pd from bokeh.core.json_encoder import serialize_json from bokeh.core.properties import List, String from bokeh.document import Document from bokeh.layouts import row, column from bokeh.models import CustomJS, HoverTool, Range1d, Slider, Button from bokeh.models.widgets import CheckboxGroup, TextInput, Panel, Tabs from bokeh.palettes import viridis from bokeh.plotting import figure, ColumnDataSource from bokeh.util.compiler import bundle_all_models from bokeh.util.serialization import make_id from matplotlib import cm from matplotlib.colors import rgb2hex import os from skyportal.models import ( DBSession, Obj, Photometry, Group, Instrument, Telescope, PHOT_ZP, ) import sncosmo DETECT_THRESH = 5 # sigma SPEC_LINES = { 'H': ([3970, 4102, 4341, 4861, 6563], '#ff0000'), 'He': ([3886, 4472, 5876, 6678, 7065], '#002157'), 'He II': ([3203, 4686], '#003b99'), 'C II': ([3919, 4267, 6580, 7234, 9234], '#570199'), 'C III': ([4650, 5696], '#a30198'), 'C IV': ([5801], '#ff0073'), 'O': ([7772, 7774, 7775, 8447, 9266], '#007236'), 'O II': ([3727], '#00a64d'), 'O III': ([4959, 5007], '#00bf59'), 'Na': ([5890, 5896, 8183, 8195], '#aba000'), 'Mg': ([2780, 2852, 3829, 3832, 3838, 4571, 5167, 5173, 5184], '#8c6239'), 'Mg II': ([2791, 2796, 2803, 4481], '#bf874e'), 'Si II': ([3856, 5041, 5056, 5670, 6347, 6371], '#5674b9'), 'S II': ([5433, 5454, 5606, 5640, 5647, 6715], '#a38409'), 'Ca II': ([3934, 3969, 7292, 7324, 8498, 8542, 8662], '#005050'), 'Fe II': ([5018, 5169], '#f26c4f'), 'Fe III': ([4397, 4421, 4432, 5129, 5158], '#f9917b'), } # TODO add groups # Galaxy lines # # 'H': '4341, 4861, 6563; # 'N II': '6548, 6583; # 'O I': '6300;' # 'O II': '3727; # 'O III': '4959, 5007; # 'Mg II': '2798; # 'S II': '6717, 6731' # 'H': '3970, 4102, 4341, 4861, 6563' # 'Na': '5890, 5896, 8183, 8195' # 'He': '3886, 4472, 5876, 6678, 7065' # 'Mg': '2780, 2852, 3829, 3832, 3838, 4571, 5167, 5173, 5184' # 'He II': '3203, 4686' # 'Mg II': '2791, 2796, 2803, 4481' # 'O': '7772, 7774, 7775, 8447, 9266' # 'Si II': '3856, 5041, 5056, 5670 6347, 6371' # 'O II': '3727' # 'Ca II': '3934, 3969, 7292, 7324, 8498, 8542, 8662' # 'O III': '4959, 5007' # 'Fe II': '5018, 5169' # 'S II': '5433, 5454, 5606, 5640, 5647, 6715' # 'Fe III': '4397, 4421, 4432, 5129, 5158' # # Other # # 'Tel: 6867-6884, 7594-7621' # 'Tel': '#b7b7b7', # 'H: 4341, 4861, 6563; # 'N II': 6548, 6583; # 'O I': 6300; # 'O II': 3727; # 'O III': 4959, 5007; # 'Mg II': 2798; # 'S II': 6717, 6731' # TODO replace with (script, div) method def _plot_to_json(plot): """Convert plot to JSON objects necessary for rendering with `bokehJS`. Parameters ---------- plot : bokeh.plotting.figure.Figure Bokeh plot object to be rendered. Returns ------- (str, str) Returns (docs_json, render_items) json for the desired plot. """ render_items = [{'docid': plot._id, 'elementid': make_id()}] doc = Document() doc.add_root(plot) docs_json_inner = doc.to_json() docs_json = {render_items[0]['docid']: docs_json_inner} docs_json = serialize_json(docs_json) render_items = serialize_json(render_items) custom_model_js = bundle_all_models() return docs_json, render_items, custom_model_js tooltip_format = [ ('mjd', '@mjd{0.000000}'), ('flux', '@flux'), ('filter', '@filter'), ('fluxerr', '@fluxerr'), ('mag', '@mag'), ('magerr', '@magerr'), ('lim_mag', '@lim_mag'), ('instrument', '@instrument'), ('stacked', '@stacked'), ] cmap = cm.get_cmap('jet_r') # TODO make async so that thread isn't blocked def photometry_plot(obj_id, user, width=600, height=300): """Create scatter plot of photometry for object. Parameters ---------- obj_id : str ID of Obj to be plotted. Returns ------- (str, str) Returns (docs_json, render_items) json for the desired plot. """ data = pd.read_sql( DBSession() .query( Photometry, Telescope.nickname.label("telescope"), Instrument.name.label("instrument"), ) .join(Instrument, Instrument.id == Photometry.instrument_id) .join(Telescope, Telescope.id == Instrument.telescope_id) .filter(Photometry.obj_id == obj_id) .filter( Photometry.groups.any(Group.id.in_([g.id for g in user.accessible_groups])) ) .statement, DBSession().bind, ) if data.empty: return None, None, None data['color'] = [get_color(f) for f in data['filter']] data['label'] = [ f'{i} {f}-band' for i, f in zip(data['instrument'], data['filter']) ] data['zp'] = PHOT_ZP data['magsys'] = 'ab' data['alpha'] = 1.0 data['lim_mag'] = -2.5 * np.log10(data['fluxerr'] * DETECT_THRESH) + data['zp'] # Passing a dictionary to a bokeh datasource causes the frontend to die, # deleting the dictionary column fixes that del data['original_user_data'] # keep track of things that are only upper limits data['hasflux'] = ~data['flux'].isna() # calculate the magnitudes - a photometry point is considered "significant" # or "detected" (and thus can be represented by a magnitude) if its snr # is above DETECT_THRESH obsind = data['hasflux'] & ( data['flux'].fillna(0.0) / data['fluxerr'] >= DETECT_THRESH ) data.loc[~obsind, 'mag'] = None data.loc[obsind, 'mag'] = -2.5 * np.log10(data[obsind]['flux']) + PHOT_ZP # calculate the magnitude errors using standard error propagation formulae # https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulae data.loc[~obsind, 'magerr'] = None coeff = 2.5 / np.log(10) magerrs = np.abs(coeff * data[obsind]['fluxerr'] / data[obsind]['flux']) data.loc[obsind, 'magerr'] = magerrs data['obs'] = obsind data['stacked'] = False split = data.groupby('label', sort=False) finite = np.isfinite(data['flux']) fdata = data[finite] lower = np.min(fdata['flux']) * 0.95 upper = np.max(fdata['flux']) * 1.05 plot = figure( plot_width=width, plot_height=height, active_drag='box_zoom', tools='box_zoom,wheel_zoom,pan,reset,save', y_range=(lower, upper), ) imhover = HoverTool(tooltips=tooltip_format) plot.add_tools(imhover) model_dict = {} for i, (label, sdf) in enumerate(split): # for the flux plot, we only show things that have a flux value df = sdf[sdf['hasflux']] key = f'obs{i}' model_dict[key] = plot.scatter( x='mjd', y='flux', color='color', marker='circle', fill_color='color', alpha='alpha', source=ColumnDataSource(df), ) imhover.renderers.append(model_dict[key]) key = f'bin{i}' model_dict[key] = plot.scatter( x='mjd', y='flux', color='color', marker='circle', fill_color='color', source=ColumnDataSource( data=dict( mjd=[], flux=[], fluxerr=[], filter=[], color=[], lim_mag=[], mag=[], magerr=[], stacked=[], instrument=[], ) ), ) imhover.renderers.append(model_dict[key]) key = 'obserr' + str(i) y_err_x = [] y_err_y = [] for d, ro in df.iterrows(): px = ro['mjd'] py = ro['flux'] err = ro['fluxerr'] y_err_x.append((px, px)) y_err_y.append((py - err, py + err)) model_dict[key] = plot.multi_line( xs='xs', ys='ys', color='color', alpha='alpha', source=ColumnDataSource( data=dict( xs=y_err_x, ys=y_err_y, color=df['color'], alpha=[1.0] * len(df) ) ), ) key = f'binerr{i}' model_dict[key] = plot.multi_line( xs='xs', ys='ys', color='color', source=ColumnDataSource(data=dict(xs=[], ys=[], color=[])), ) plot.xaxis.axis_label = 'MJD' plot.yaxis.axis_label = 'Flux (Jy)' plot.toolbar.logo = None toggle = CheckboxWithLegendGroup( labels=list(data.label.unique()), active=list(range(len(data.label.unique()))), colors=list(data.color.unique()), ) # TODO replace `eval` with Namespaces # https://github.com/bokeh/bokeh/pull/6340 toggle.callback = CustomJS( args={'toggle': toggle, **model_dict}, code=open( os.path.join(os.path.dirname(__file__), '../static/js/plotjs', 'togglef.js') ).read(), ) slider = Slider(start=0.0, end=15.0, value=0.0, step=1.0, title='Binsize (days)') callback = CustomJS( args={'slider': slider, 'toggle': toggle, **model_dict}, code=open( os.path.join(os.path.dirname(__file__), '../static/js/plotjs', 'stackf.js') ) .read() .replace('default_zp', str(PHOT_ZP)) .replace('detect_thresh', str(DETECT_THRESH)), ) slider.js_on_change('value', callback) # Mark the first and last detections detection_dates = data[data['hasflux']]['mjd'] if len(detection_dates) > 0: first = round(detection_dates.min(), 6) last = round(detection_dates.max(), 6) first_color = "#34b4eb" last_color = "#8992f5" midpoint = (upper + lower) / 2 line_top = 5 * upper - 4 * midpoint line_bottom = 5 * lower - 4 * midpoint first_x = np.full(5000, first) last_x = np.full(5000, last) y = np.linspace(line_bottom, line_top, num=5000) first_r = plot.line( x=first_x, y=y, line_alpha=0.5, line_color=first_color, line_width=2, ) plot.add_tools( HoverTool(tooltips=[("First detection", f'{first}')], renderers=[first_r],) ) last_r = plot.line( x=last_x, y=y, line_alpha=0.5, line_color=last_color, line_width=2 ) plot.add_tools( HoverTool(tooltips=[("Last detection", f'{last}')], renderers=[last_r],) ) layout = row(plot, toggle) layout = column(slider, layout) p1 = Panel(child=layout, title='Flux') # now make the mag light curve ymax = np.nanmax(data['mag']) + 0.1 ymin = np.nanmin(data['mag']) - 0.1 plot = figure( plot_width=width, plot_height=height, active_drag='box_zoom', tools='box_zoom,wheel_zoom,pan,reset,save', y_range=(ymax, ymin), toolbar_location='above', ) # Mark the first and last detections again if len(detection_dates) > 0: midpoint = (ymax + ymin) / 2 line_top = 5 * ymax - 4 * midpoint line_bottom = 5 * ymin - 4 * midpoint y = np.linspace(line_bottom, line_top, num=5000) first_r = plot.line( x=first_x, y=y, line_alpha=0.5, line_color=first_color, line_width=2, ) plot.add_tools( HoverTool(tooltips=[("First detection", f'{first}')], renderers=[first_r],) ) last_r = plot.line( x=last_x, y=y, line_alpha=0.5, line_color=last_color, line_width=2 ) plot.add_tools( HoverTool( tooltips=[("Last detection", f'{last}')], renderers=[last_r], point_policy='follow_mouse', ) ) imhover = HoverTool(tooltips=tooltip_format) plot.add_tools(imhover) model_dict = {} for i, (label, df) in enumerate(split): key = f'obs{i}' model_dict[key] = plot.scatter( x='mjd', y='mag', color='color', marker='circle', fill_color='color', alpha='alpha', source=ColumnDataSource(df[df['obs']]), ) imhover.renderers.append(model_dict[key]) unobs_source = df[~df['obs']].copy() unobs_source.loc[:, 'alpha'] = 0.8 key = f'unobs{i}' model_dict[key] = plot.scatter( x='mjd', y='lim_mag', color='color', marker='inverted_triangle', fill_color='white', line_color='color', alpha='alpha', source=ColumnDataSource(unobs_source), ) imhover.renderers.append(model_dict[key]) key = f'bin{i}' model_dict[key] = plot.scatter( x='mjd', y='mag', color='color', marker='circle', fill_color='color', source=ColumnDataSource( data=dict( mjd=[], flux=[], fluxerr=[], filter=[], color=[], lim_mag=[], mag=[], magerr=[], instrument=[], stacked=[], ) ), ) imhover.renderers.append(model_dict[key]) key = 'obserr' + str(i) y_err_x = [] y_err_y = [] for d, ro in df[df['obs']].iterrows(): px = ro['mjd'] py = ro['mag'] err = ro['magerr'] y_err_x.append((px, px)) y_err_y.append((py - err, py + err)) model_dict[key] = plot.multi_line( xs='xs', ys='ys', color='color', alpha='alpha', source=ColumnDataSource( data=dict( xs=y_err_x, ys=y_err_y, color=df[df['obs']]['color'], alpha=[1.0] * len(df[df['obs']]), ) ), ) key = f'binerr{i}' model_dict[key] = plot.multi_line( xs='xs', ys='ys', color='color', source=ColumnDataSource(data=dict(xs=[], ys=[], color=[])), ) key = f'unobsbin{i}' model_dict[key] = plot.scatter( x='mjd', y='lim_mag', color='color', marker='inverted_triangle', fill_color='white', line_color='color', alpha=0.8, source=ColumnDataSource( data=dict( mjd=[], flux=[], fluxerr=[], filter=[], color=[], lim_mag=[], mag=[], magerr=[], instrument=[], stacked=[], ) ), ) imhover.renderers.append(model_dict[key]) key = f'all{i}' model_dict[key] = ColumnDataSource(df) key = f'bold{i}' model_dict[key] = ColumnDataSource( df[ [ 'mjd', 'flux', 'fluxerr', 'mag', 'magerr', 'filter', 'zp', 'magsys', 'lim_mag', 'stacked', ] ] ) plot.xaxis.axis_label = 'MJD' plot.yaxis.axis_label = 'AB mag' plot.toolbar.logo = None toggle = CheckboxWithLegendGroup( labels=list(data.label.unique()), active=list(range(len(data.label.unique()))), colors=list(data.color.unique()), ) # TODO replace `eval` with Namespaces # https://github.com/bokeh/bokeh/pull/6340 toggle.callback = CustomJS( args={'toggle': toggle, **model_dict}, code=open( os.path.join(os.path.dirname(__file__), '../static/js/plotjs', 'togglem.js') ).read(), ) slider = Slider(start=0.0, end=15.0, value=0.0, step=1.0, title='Binsize (days)') button = Button(label="Export Bold Light Curve to CSV") button.callback = CustomJS( args={'slider': slider, 'toggle': toggle, **model_dict}, code=open( os.path.join( os.path.dirname(__file__), '../static/js/plotjs', "download.js" ) ) .read() .replace('objname', obj_id) .replace('default_zp', str(PHOT_ZP)), ) toplay = row(slider, button) callback = CustomJS( args={'slider': slider, 'toggle': toggle, **model_dict}, code=open( os.path.join(os.path.dirname(__file__), '../static/js/plotjs', 'stackm.js') ) .read() .replace('default_zp', str(PHOT_ZP)) .replace('detect_thresh', str(DETECT_THRESH)), ) slider.js_on_change('value', callback) layout = row(plot, toggle) layout = column(toplay, layout) p2 = Panel(child=layout, title='Mag') tabs = Tabs(tabs=[p2, p1]) return _plot_to_json(tabs) # TODO make async so that thread isn't blocked def spectroscopy_plot(obj_id, spec_id=None): """TODO normalization? should this be handled at data ingestion or plot-time?""" obj = Obj.query.get(obj_id) spectra = Obj.query.get(obj_id).spectra if spec_id is not None: spectra = [spec for spec in spectra if spec.id == int(spec_id)] if len(spectra) == 0: return None, None, None color_map = dict(zip([s.id for s in spectra], viridis(len(spectra)))) data = pd.concat( [ pd.DataFrame( { 'wavelength': s.wavelengths, 'flux': s.fluxes, 'id': s.id, 'instrument': s.instrument.telescope.nickname, } ) for i, s in enumerate(spectra) ] ) split = data.groupby('id') hover = HoverTool( tooltips=[('wavelength', '$x'), ('flux', '$y'), ('instrument', '@instrument')] ) plot = figure( plot_width=600, plot_height=300, sizing_mode='scale_both', tools='box_zoom,wheel_zoom,pan,reset', active_drag='box_zoom', ) plot.add_tools(hover) model_dict = {} for i, (key, df) in enumerate(split): model_dict['s' + str(i)] = plot.line( x='wavelength', y='flux', color=color_map[key], source=ColumnDataSource(df) ) plot.xaxis.axis_label = 'Wavelength ()' plot.yaxis.axis_label = 'Flux' plot.toolbar.logo = None # TODO how to choose a good default? plot.y_range = Range1d(0, 1.03 * data.flux.max()) toggle = CheckboxWithLegendGroup( labels=[s.instrument.telescope.nickname for s in spectra], active=list(range(len(spectra))), width=100, colors=[color_map[k] for k, df in split], ) toggle.callback = CustomJS( args={'toggle': toggle, **model_dict}, code=""" for (let i = 0; i < toggle.labels.length; i++) { eval("s" + i).visible = (toggle.active.includes(i)) } """, ) elements = CheckboxWithLegendGroup( labels=list(SPEC_LINES.keys()), active=[], width=80, colors=[c for w, c in SPEC_LINES.values()], ) z = TextInput(value=str(obj.redshift), title="z:") v_exp = TextInput(value='0', title="v_exp:") for i, (wavelengths, color) in enumerate(SPEC_LINES.values()): el_data = pd.DataFrame({'wavelength': wavelengths}) el_data['x'] = el_data['wavelength'] * (1 + obj.redshift) model_dict[f'el{i}'] = plot.segment( x0='x', x1='x', # TODO change limits y0=0, y1=1e-13, color=color, source=ColumnDataSource(el_data), ) model_dict[f'el{i}'].visible = False # TODO callback policy: don't require submit for text changes? elements.callback = CustomJS( args={'elements': elements, 'z': z, 'v_exp': v_exp, **model_dict}, code=""" let c = 299792.458; // speed of light in km / s for (let i = 0; i < elements.labels.length; i++) { let el = eval("el" + i); el.visible = (elements.active.includes(i)) el.data_source.data.x = el.data_source.data.wavelength.map( x_i => (x_i * (1 + parseFloat(z.value)) / (1 + parseFloat(v_exp.value) / c)) ); el.data_source.change.emit(); } """, ) z.callback = elements.callback v_exp.callback = elements.callback layout = row(plot, toggle, elements, column(z, v_exp)) return _plot_to_json(layout)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 1489, 365, 71, 13, 7295, 13, 17752, 62, 12685, 12342, 1330, 11389, 1096, 62, 17752, 198, 6738, 1489, 365, 71, 13, 7295, 13, 48310, 1330, 7343, 11, ...
1.924805
10,905
# coding:utf-8 import uuid import string import hashlib import logging from lib.errors import SessionExpiredError, SessionConsumedError from datetime import datetime as dt from random import SystemRandom LOG = logging.getLogger("errbot.plugin.st2.session")
[ 2, 19617, 25, 40477, 12, 23, 198, 11748, 334, 27112, 198, 11748, 4731, 198, 11748, 12234, 8019, 198, 11748, 18931, 198, 6738, 9195, 13, 48277, 1330, 23575, 3109, 6474, 12331, 11, 23575, 9444, 18940, 12331, 198, 6738, 4818, 8079, 1330, 4...
3.561644
73
# -*- coding: utf-8 -*- from .lib import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 764, 8019, 1330, 1635, 198 ]
2.15
20
from django.db.models.signals import post_save from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.dispatch import receiver from .models import Usuario, LoginLog post_save.connect(user_profile, sender=User)
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12683, 874, 1330, 2836, 62, 6404, 2004, 62, 259, 11, 2836, 62, 6404, 2004, 62, 448, 11, 2836, 62,...
3.160714
112
import mysql.connector from mysql.connector.errors import ProgrammingError from mysql.connector import Error from DvdOperations import DvdStore database = "db4" Function2()
[ 11748, 48761, 13, 8443, 273, 198, 6738, 48761, 13, 8443, 273, 13, 48277, 1330, 30297, 12331, 198, 6738, 48761, 13, 8443, 273, 1330, 13047, 198, 6738, 360, 20306, 18843, 602, 1330, 360, 20306, 22658, 198, 198, 48806, 796, 366, 9945, 19, ...
3.723404
47
#!/usr/bin/python # -*- coding: utf-8 -*- import os import json try: import urllib2 except: import urllib.request as urllib2 from requests import delete, get, post, put from cloudshell.rest.exceptions import ShellNotFoundException, FeatureUnavailable
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 28311, 25, 198, 220, 220, 220, 1330, 2956, 297, 571, 17, 198, 16341, 25, 198, 220...
2.94382
89
from classes import oracles_headers
[ 6738, 6097, 1330, 393, 9928, 62, 50145, 198, 220, 220, 220, 220 ]
3.333333
12
#TODO put this inside of rixscam def rixscam_get_threshold(Ei = None): '''Calculate the minimum and maximum threshold for RIXSCAM single photon counting (LS mode) Ei\t:\t float - incident energy (default is beamline current energy) ''' if Ei is None: Ei = pgm.en.user_readback.value t_min = 0.7987 * Ei - 97.964 t_max = 1.4907 * Ei + 38.249 print('\n\n\tMinimum value for RIXSCAM threshold (LS mode):\t{}'.format(t_min)) print('\tMaximum value for RIXSCAM threshold (LS mode):\t{}'.format(t_max)) print('\tFor Beamline Energy:\t\t\t\t{}'.format(Ei)) return t_min, t_max #TODO put this insdie of rixscam #TODO make official so that there is a m1_fbk device like m1fbk.setpoint m1_fbk = EpicsSignal('XF:02IDA-OP{FBck}Sts:FB-Sel', name = 'm1_fbk') m1_fbk_sp = EpicsSignal('XF:02IDA-OP{FBck}PID-SP', name = 'm1_fbk_sp') m1_fbk_th = extslt_cam.stats1.centroid_threshold #m1_fbk_pix_x = extslt_cam.stats1.centroid.x.value m1_fbk_cam_time = extslt_cam.cam.acquire_time #(mv(m1_fbk_th,1500) m1_simple_fbk = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-Ena', name = 'm1_simple_fbk') m1_simple_fbk_target_ratio = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-TarRat', name = 'm1_simple_fbk_target_ratio') m1_simple_fbk_ratio = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-Ratio', name = 'm1_simple_fbk_ratio') m3_simple_fbk = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB-Ena', name = 'm3_simple_fbk') m3_simple_fbk_target = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB-Targ', name = 'm3_simple_fbk_target') m3_simple_fbk_cen = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB_inpbuf', name = 'm3_simple_fbk_cen')
[ 628, 628, 198, 2, 51, 3727, 46, 1234, 428, 2641, 286, 374, 844, 1416, 321, 198, 4299, 374, 844, 1416, 321, 62, 1136, 62, 400, 10126, 7, 36, 72, 796, 6045, 2599, 198, 220, 220, 220, 705, 7061, 9771, 3129, 378, 262, 5288, 290, 541...
2.078382
791
from __future__ import absolute_import # flake8: noqa # import apis into api package import speechpro.cloud.speech.synthesis.rest.cloud_client.api.session_api import speechpro.cloud.speech.synthesis.rest.cloud_client.api.synthesize_api
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 2, 781, 539, 23, 25, 645, 20402, 198, 198, 2, 1330, 2471, 271, 656, 40391, 5301, 198, 11748, 4046, 1676, 13, 17721, 13, 45862, 13, 1837, 429, 8497, 13, 2118, 13, 17721, 62, ...
3.051282
78
# _*_ coding:utf-8 _*_ # author:ls # time:2020/3/19 0019 import sys from PyQt5.QtWidgets import QApplication,QAction,QMainWindow from PyQt5.QtGui import QIcon if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
[ 2, 4808, 9, 62, 19617, 25, 40477, 12, 23, 4808, 9, 62, 198, 2, 1772, 25, 7278, 198, 2, 640, 25, 42334, 14, 18, 14, 1129, 3571, 1129, 198, 11748, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416...
2.315789
114
#!/usr/bin/env python import pika import time import json import StringIO #from fca.concept import Concept from casa import Casa #from fca.readwrite import cxt connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='task_queue', durable=True, exclusive=False) channel.queue_declare(queue='msg_queue', durable=True, exclusive=False) #channel.exchange_declare(exchange='', # type="topic", # durable=True, # auto_delete=False) #channel.queue_declare(queue="task_queue", # durable=True, # exclusive=False, # auto_delete=False, # callback=on_queue_declared) print ' [*] Waiting for messages. To exit press CTRL+C' channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='task_queue') channel.basic_consume(msg_callback, queue='msg_queue') channel.start_consuming()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 279, 9232, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 10903, 9399, 198, 2, 6738, 277, 6888, 13, 43169, 1330, 26097, 198, 6738, 6124, 64, 1330, 11294, 64, 198, 2, 6738, 277,...
2.184891
503
from .selection import Selection import numpy as np
[ 6738, 764, 49283, 1330, 29538, 198, 11748, 299, 32152, 355, 45941, 198 ]
4.333333
12
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Over 25k semiautomatically generated sentence pairs illustrating well-studied pragmatic inference types. IMPPRES is an NLI dataset following the format of SNLI (Bowman et al., 2015), MultiNLI (Williams et al., 2018) and XNLI (Conneau et al., 2018), which was created to evaluate how well trained NLI models recognize several classes of presuppositions and scalar implicatures.""" from __future__ import absolute_import, division, print_function import json import os import datasets # Find for instance the citation on arxiv or on the dataset repo/website _CITATION = """\ @inproceedings{jeretic-etal-2020-natural, title = "Are Natural Language Inference Models {IMPPRESsive}? {L}earning {IMPlicature} and {PRESupposition}", author = "Jereti\v{c}, Paloma and Warstadt, Alex and Bhooshan, Suvrat and Williams, Adina", booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics", month = jul, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.acl-main.768", doi = "10.18653/v1/2020.acl-main.768", pages = "8690--8705", abstract = "Natural language inference (NLI) is an increasingly important task for natural language understanding, which requires one to infer whether a sentence entails another. However, the ability of NLI models to make pragmatic inferences remains understudied. We create an IMPlicature and PRESupposition diagnostic dataset (IMPPRES), consisting of 32K semi-automatically generated sentence pairs illustrating well-studied pragmatic inference types. We use IMPPRES to evaluate whether BERT, InferSent, and BOW NLI models trained on MultiNLI (Williams et al., 2018) learn to make pragmatic inferences. Although MultiNLI appears to contain very few pairs illustrating these inference types, we find that BERT learns to draw pragmatic inferences. It reliably treats scalar implicatures triggered by {``}some{''} as entailments. For some presupposition triggers like {``}only{''}, BERT reliably recognizes the presupposition as an entailment, even when the trigger is embedded under an entailment canceling operator like negation. BOW and InferSent show weaker evidence of pragmatic reasoning. We conclude that NLI training encourages models to learn some, but not all, pragmatic inferences.", } """ # You can copy an official description _DESCRIPTION = """Over >25k semiautomatically generated sentence pairs illustrating well-studied pragmatic inference types. IMPPRES is an NLI dataset following the format of SNLI (Bowman et al., 2015), MultiNLI (Williams et al., 2018) and XNLI (Conneau et al., 2018), which was created to evaluate how well trained NLI models recognize several classes of presuppositions and scalar implicatures.""" _HOMEPAGE = "https://github.com/facebookresearch/Imppres" _LICENSE = "Creative Commons Attribution-NonCommercial 4.0 International Public License" # The HuggingFace dataset library don't host the datasets but only point to the original files # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method) _URLs = {"default": "https://github.com/facebookresearch/Imppres/blob/master/dataset/IMPPRES.zip?raw=true"}
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 12131, 383, 12905, 2667, 32388, 16092, 292, 1039, 46665, 290, 262, 1459, 27039, 4226, 18920, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 3415...
3.763308
1,052
# Standard library imports import logging import os # Third party imports import dash import dash_bootstrap_components as dbc from flask_caching import Cache import plotly.io as pio # Local application imports from modules.gitlab import GitLab import settings # Initialize logging mechanism logging.basicConfig(level=settings.LOGLEVEL, format=settings.LOGFORMAT) logger = logging.getLogger(__name__) gl = GitLab() logger.info("Current GitLab version: {}".format(GitLab.version)) # App instance app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.title = settings.APP_NAME # App caching # CACHE_CONFIG = { # # Note that filesystem cache doesn't work on systems with ephemeral # # filesystems like Heroku. # 'CACHE_TYPE': 'filesystem', # 'CACHE_DIR': 'cache-directory', # # should be equal to maximum number of users on the app at a single time # # higher numbers will store more data in the filesystem / redis cache # 'CACHE_THRESHOLD': 200 # } CACHE_CONFIG = { # try 'filesystem' if you don't want to setup redis 'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': settings.REDIS_URL } cache = Cache() cache.init_app(app.server, config=CACHE_CONFIG) pio.templates.default = "plotly_dark"
[ 2, 8997, 5888, 17944, 201, 198, 11748, 18931, 201, 198, 11748, 28686, 201, 198, 201, 198, 2, 10467, 2151, 17944, 201, 198, 11748, 14470, 201, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 201, 198, 6738, 42903, ...
2.748441
481
# Copyright 2018 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fake Retention scanner data.""" import json from datetime import datetime, timedelta import collections from google.cloud.forseti.common.gcp_type import organization from google.cloud.forseti.common.gcp_type import project from google.cloud.forseti.common.gcp_type import bucket from google.cloud.forseti.scanner.audit import retention_rules_engine as rre ORGANIZATION = organization.Organization( '123456', display_name='Default Organization', full_name='organization/123456/', data='fake_org_data_123456', ) PROJECT1 = project.Project( 'def-project-1', project_number=11223344, display_name='default project 1', parent=ORGANIZATION, full_name='organization/123456/project/def-project-1/', data='fake_project_data_11223344', ) PROJECT2 = project.Project( 'def-project-2', project_number=55667788, display_name='default project 2', parent=ORGANIZATION, full_name='organization/123456/project/def-project-2/', data='fake_project_data_55667788', ) PROJECT3 = project.Project( 'def-project-3', project_number=12121212, display_name='default project 3', parent=ORGANIZATION, full_name='organization/123456/project/def-project-3/', data='fake_project_data_12121212', ) PROJECT4 = project.Project( 'def-project-4', project_number=34343434, display_name='default project 4', parent=ORGANIZATION, full_name='organization/123456/project/def-project-4/', data='fake_project_data_34343434', ) FakeBucketDataInput = collections.namedtuple( 'FakeBucketDataInput', ['id', 'project', 'lifecycles']) LifecycleInput = collections.namedtuple( 'LifecycleInput', ['action', 'conditions'])
[ 2, 15069, 2864, 383, 27325, 316, 72, 4765, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11...
2.945293
786
import socket import requests import json import xml.etree.ElementTree as ET
[ 11748, 17802, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 628, 198 ]
3.761905
21
#!/usr/bin/env python """ This module defines functions to facilitate operations with data specific to Flu trees and alignments. """ import numpy as np from Bio import AlignIO, Phylo from Bio.Align import MultipleSeqAlignment import random import subprocess import datetime import os, copy import matplotlib.pyplot as plt from scipy.stats import linregress from collections import Counter import StringIO import treetime from utility_functions_general import remove_polytomies from utility_functions_beast import run_beast, create_beast_xml, read_beast_log import xml.etree.ElementTree as XML from external_binaries import BEAST_BIN def date_from_seq_name(name): """ Parse flu sequence name to the date in numeric format (YYYY.F) Args: - name(str): name of the flu sequence. Returns: - sequence sampling date if succeeded to parse. None otherwise. """ def str2date_time(instr): """ Convert input string to datetime object. Args: - instr (str): input string. Accepts one of the formats: {MM.DD.YYYY, MM.YYYY, MM/DD/YYYY, MM/YYYY, YYYY}. Returns: - date (datetime.datetime): parsed date object. If the parsing failed, None is returned """ instr = instr.replace('/', '.') # import ipdb; ipdb.set_trace() try: date = datetime.datetime.strptime(instr, "%m.%d.%Y") except ValueError: date = None if date is not None: return date try: date = datetime.datetime.strptime(instr, "%m.%Y") except ValueError: date = None if date is not None: return date try: date = datetime.datetime.strptime(instr, "%Y") except ValueError: date = None return date try: date = str2date_time(name.split('|')[3].strip()) return date.year + (date - datetime.datetime(date.year, 1, 1)).days / 365.25 except: return None def dates_from_flu_tree(tree): """ Iterate over the Flu tree, parse each leaf name and return dates for the leaves as dictionary. Args: - tree(str or Biopython tree): Flu tree Returns: - dates(dict): dictionary of dates in format {seq_name: numdate}. Only the entries which were parsed successfully are included. """ if isinstance(tree, str): tree = Phylo.read(tree, 'newick') dates = {k.name:date_from_seq_name(k.name) for k in tree.get_terminals() if date_from_seq_name(k.name) is not None} return dates def subtree_with_same_root(tree, Nleaves, outfile, optimize=True): """ Sample subtree of the given tree so that the root of the subtree is that of the original tree. Args: - tree(str or Biopython tree): initial tree - Nleaves(int): number of leaves in the target subtree - outfile(str): path to save the resulting subtree optimize(bool): perform branch length optimization for the subtree? Returns: - tree(Biopython tree): the subtree """ if isinstance(tree, str): treecopy = Phylo.read(tree, 'newick') else: treecopy = copy.deepcopy(tree) remove_polytomies(treecopy) assert(len(treecopy.root.clades) == 2) tot_terminals = treecopy.count_terminals() # sample to the left of the root left = treecopy.root.clades[0] n_left = left.count_terminals() right = treecopy.root.clades[1] n_right = right.count_terminals() n_left_sampled = np.min((n_left, Nleaves * n_left / (n_left + n_right))) n_left_sampled = np.max((n_left_sampled, 5)) # make sure we have at least one left_terminals = left.get_terminals() left_sample_idx = np.random.choice(np.arange(len(left_terminals)), size=n_left_sampled, replace=False) left_sample = [left_terminals[i] for i in left_sample_idx] # sample to the right of the root n_right_sampled = np.min((n_right, Nleaves * n_right / (n_left + n_right))) n_right_sampled = np.max((n_right_sampled, 5)) # make sure we have at least one right_terminals = right.get_terminals() right_sample_idx = np.random.choice(np.arange(len(right_terminals)), size=n_right_sampled, replace=False) right_sample = [right_terminals[i] for i in right_sample_idx] for leaf in treecopy.get_terminals(): if leaf not in right_sample and leaf not in left_sample: treecopy.prune(leaf) else: pass #print ("leaving leaf {} in the tree".format(leaf.name)) if optimize: import treetime dates = dates_from_flu_tree(treecopy) aln = './resources/flu_H3N2/H3N2_HA_2011_2013.fasta' tt = treetime.TreeAnc(tree=treecopy, aln=aln,gtr='Jukes-Cantor') tt.optimize_seq_and_branch_len(prune_short=False) Phylo.write(tt.tree, outfile, 'newick') return tt.tree else: Phylo.write(treecopy, outfile, 'newick') return treecopy def subtree_year_vol(tree, N_per_year, outfile): """ Sample subtree of the given tree with equal number of samples per year. Note: - if there are not enough leaves sampled at a given year, all leaves for this year will be included in the subtree. Args: - tree(str or Biopython object): Initial tree - N_per_year(int): number of samples per year. - outfile (str): path to save the subtree Returns: - tree(Biopython tree): the subtree """ if isinstance(tree, str): treecopy = Phylo.read(tree, 'newick') else: treecopy = copy.deepcopy(tree) remove_polytomies(treecopy) dates = dates_from_flu_tree(treecopy) sample = [] cntr = Counter(map (int, dates.values())) years = cntr.keys() min_year = np.min(years) for year in years: all_names = [k for k in dates if int(dates[k]) == year] if len(all_names) <= N_per_year or year == min_year: sample += all_names else: sample += list(np.random.choice(all_names, size=N_per_year, replace=False)) for leaf in treecopy.get_terminals(): if leaf.name not in sample: treecopy.prune(leaf) else: pass #print ("leaving leaf {} in the tree".format(leaf.name)) Phylo.write(treecopy, outfile, 'newick') return treecopy def create_LSD_dates_file_from_flu_tree(tree, outfile): """ Parse dates from the flu tree and write to the file in the LSD format. Args: - tree(str or Biopython object): Initial tree - outfile(str): path to save the LSD dates file. Returns: - dates(dict): dates parsed from the tree as dictionary. """ dates = dates_from_flu_tree(tree) with open(outfile, 'w') as df: df.write(str(len(dates)) + "\n") df.write("\n".join([str(k) + "\t" + str(dates[k]) for k in dates])) return dates def make_known_dates_dict(alnfile, dates_known_fraction=1.0): """ Read all the dates of the given flu sequences, and make the dates dictionary for only a fraction of them. The sequences in the resulting dict are chosen randomly. """ aln = AlignIO.read(alnfile, 'fasta') dates = {k.name: date_from_seq_name(k.name) for k in aln} # randomly choose the dates so that only the known_ratio number of dates is known if dates_known_fraction != 1.0: assert(dates_known_fraction > 0 and dates_known_fraction < 1.0) knonw_keys = np.random.choice(dates.keys(), size=int (len(dates) * dates_known_fraction), replace=False) dates = {k : dates[k] for k in knonw_keys} return dates def create_treetime_with_missing_dates(alnfile, treefile, dates_known_fraction=1.0): """dates = {k.name: date_from_seq_name(k.name) for k in aln} Create TreeTime object with fraction of leaves having no sampling dates. The leaves to earse sampling dates are chosen randomly. Args: - alnfile(str): path to the flu alignment - treefiule(str): path to the Flu newixk tree - dates_known_fraction(float): fraction of leaves, which should have sampling date information. """ aln = AlignIO.read(alnfile, 'fasta') tt = Phylo.read(treefile, 'newick') dates = make_known_dates_dict(alnfile, dates_known_fraction) myTree = treetime.TreeTime(gtr='Jukes-Cantor', tree = treefile, aln = alnfile, verbose = 4, dates = dates, debug=False) myTree.optimize_seq_and_branch_len(reuse_branch_len=True, prune_short=True, max_iter=5, infer_gtr=False) return myTree def create_subtree(tree, n_seqs, out_file, st_type='equal_sampling'): """ Args: - tree(filename or Biopython tree): original tree - n_seqs: number of leaves in the resulting subtree - out_file: output locaton to store the resulting subtree - st_type: type of the subtree generation algorithm. Available types: - random: just choose n_leaves randomly - equal_sampling: choose equal leaves each year (if possible) - preserve_root: sample from right and left subtrees of the tree root. The root of the resulting subtree is therefore the same as of the original tree """ if isinstance(tree, str): tree = Phylo.read(tree, 'newick') pass if __name__ == '__main__': pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 1212, 8265, 15738, 5499, 284, 15570, 4560, 351, 1366, 2176, 198, 1462, 34070, 7150, 290, 10548, 902, 13, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 16024...
2.487125
3,767
from asyncio import get_event_loop from dataclasses import dataclass, field from typing import Dict, List, Optional, Union from aiohttp import ClientSession from pydantic import BaseModel from sgqlc.endpoint.base import BaseEndpoint from sgqlc.operation import Operation from sgqlc_schemas.github.schema import ( AddLabelsToLabelableInput, AddLabelsToLabelablePayload, MergePullRequestInput, Mutation, Query, Repository, ) def build_merge(ids: List[str]): op = Operation(Mutation) for i, ident in enumerate(ids): op.merge_pull_request( input=MergePullRequestInput(pull_request_id=ident), __alias__=f'merge_{i}' ).pull_request.title() return op if __name__ == "__main__": get_event_loop().run_until_complete(main())
[ 6738, 30351, 952, 1330, 651, 62, 15596, 62, 26268, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 32233, 11, 4479, 198, 198, 6738, 257, 952, 4023, 1330, 20985, 36044, 198...
2.66
300
import time import datetime from apscheduler.schedulers.background import BackgroundScheduler from financialdata.producer import Update from loguru import logger if __name__ == "__main__": main() while True: time.sleep(600)
[ 11748, 640, 198, 11748, 4818, 8079, 198, 198, 6738, 257, 862, 1740, 18173, 13, 1416, 704, 377, 364, 13, 25249, 1330, 25353, 50, 1740, 18173, 198, 6738, 3176, 7890, 13, 18230, 2189, 1330, 10133, 198, 6738, 2604, 14717, 1330, 49706, 628, ...
3.024691
81
import matplotlib.pyplot as plt from matplotlib import cm import numpy as np def scatter_tokamak_source(source, quantity=None, **kwargs): """Create a 2D scatter plot of the tokamak source. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html for more arguments. Args: source (ops.TokamakSource): the plasma source quantity ("str", optional): value by which the lines should be coloured. Defaults to None. Raises: ValueError: If the quantity is unknown """ quantity_to_attribute = { "ion_temperature": source.temperatures, "neutron_source_density": source.strengths } if quantity in quantity_to_attribute: colours = quantity_to_attribute[quantity] elif quantity is None: colours = None else: raise ValueError("Unknown quantity") plt.gca().set_aspect("equal") return plt.scatter(source.RZ[0], source.RZ[1], c=colours, **kwargs) def plot_tokamak_source_3D(source, quantity=None, angles=[0, 1/2*np.pi], colorbar="viridis", **kwargs): """Creates a 3D plot of the tokamak source. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot for more arguments. Args: source (ops.TokamakSource): the plasma source quantity ("str", optional): value by which the lines should be coloured. Defaults to None. angles (list, optional): iterable of two floats defining the coverage. Defaults to [0, 1/2*np.pi]. colorbar (str, optional): colorbar used if quantity is not None. Defaults to "viridis". Raises: ValueError: If the quantity is unknown """ quantity_to_attribute = { "ion_temperature": source.temperatures, "neutron_source_density": source.strengths } if quantity in quantity_to_attribute: values = quantity_to_attribute[quantity] elif quantity is None: values = None else: raise ValueError("Unknown quantity") colorbar = cm.get_cmap(colorbar) axes = plt.axes(projection="3d") theta = np.linspace(*angles, 100) for i in range(source.sample_size): if values is not None: colour = colorbar(values[i]/max(values)) else: colour = None x = source.RZ[0][i] * np.sin(theta) y = source.RZ[0][i] * np.cos(theta) z = source.RZ[1][i] plt.plot(x, y, z, color=colour, **kwargs) axes.set_xlim(-source.major_radius, source.major_radius) axes.set_ylim(-source.major_radius, source.major_radius) axes.set_zlim(-source.major_radius, source.major_radius)
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 1330, 12067, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4299, 41058, 62, 83, 482, 321, 461, 62, 10459, 7, 10459, 11, 12040, 28, 14202, 11, 12429...
2.420863
1,112
#Exerccio046 from time import sleep import emoji print('\033[32mCONTAGEM REGRESSIVA PARA O ANO NOVO:\033[m') sleep(1) for c in range(10, 0 - 1, -1):#repete os nmeros de 10 at o 0 print(c) sleep(1) print(emoji.emojize("\033[31m:boom::boom::boom:KABUM:boom::boom::boom:", use_aliases=True)) print(emoji.emojize("\033[32m:boom::boom::boom:FOGUETE:boom::boom::boom:", use_aliases=True)) print(emoji.emojize("\033[33m:boom::boom::boom:FOGOS E MAIS FOGOS:boom::boom::boom:", use_aliases=True)) print(emoji.emojize("\033[34m:boom::boom::boom:GUANAGARA VIADO:boom::boom::boom:", use_aliases=True)) print('\033[32mxD')
[ 2, 3109, 263, 535, 952, 45438, 198, 6738, 640, 1330, 3993, 198, 11748, 44805, 198, 4798, 10786, 59, 44427, 58, 2624, 76, 37815, 4760, 3620, 4526, 10761, 7597, 3824, 32, 350, 24401, 440, 3537, 46, 8005, 29516, 7479, 44427, 58, 76, 1153...
2.084459
296
import abc import math from ... import constants class NumericValueExists(Rule): # Test succeeds if value is numeric and not -999 field_name = None field_name_verbose = None class BmdExists(NumericValueExists): default_rule_name = "BMD exists" field_name = "BMD" class BmdlExists(NumericValueExists): default_rule_name = "BMDL exists" field_name = "BMDL" class BmduExists(NumericValueExists): default_rule_name = "BMDU exists" field_name = "BMDU" class AicExists(NumericValueExists): default_rule_name = "AIC exists" field_name = "AIC" class RoiExists(NumericValueExists): default_rule_name = "Residual of interest exists" field_name = "residual_of_interest" field_name_verbose = "Residual of Interest" class ShouldBeGreaterThan(Rule): # Test fails if value is less-than threshold. field_name = "" field_name_verbose = "" class GlobalFit(ShouldBeGreaterThan): default_rule_name = "GGOF" field_name = "p_value4" field_name_verbose = "Goodness of fit p-value" class ShouldBeLessThan(Rule, abc.ABC): # Test fails if value is greater-than threshold. msg = "" # w/ arguments for value and threshold class BmdBmdlRatio(ShouldBeLessThan): default_rule_name = "BMD to BMDL ratio" field_name_verbose = "BMD/BMDL ratio" class RoiFit(ShouldBeLessThan): default_rule_name = "Residual of interest" field_name_verbose = "Residual of interest" class HighBmd(ShouldBeLessThan): default_rule_name = "High BMD" field_name_verbose = "BMD/high dose ratio" class HighBmdl(ShouldBeLessThan): default_rule_name = "High BMDL" field_name_verbose = "BMDL/high dose ratio" class LowBmd(ShouldBeLessThan): default_rule_name = "Low BMD" field_name_verbose = "minimum dose/BMD ratio" class LowBmdl(ShouldBeLessThan): default_rule_name = "Low BMDL" field_name_verbose = "minimum dose/BMDL ratio" class ControlResidual(ShouldBeLessThan): default_rule_name = "Control residual" field_name_verbose = "Residual at lowest dose" class ControlStdevResiduals(ShouldBeLessThan): default_rule_name = "Control stdev" field_name_verbose = "Ratio of modeled to actual stdev. at control" class CorrectVarianceModel(Rule): # Check variance model (continuous datasets-only) default_rule_name = "Variance type" class VarianceModelFit(Rule): default_rule_name = "Variance fit" class NoDegreesOfFreedom(Rule): """ Check to ensure at least one degree of freedom exist to prevent recommendation of an overfit model. """ default_rule_name = "Degrees of freedom" class Warnings(Rule): # Test fails if any warnings exist. default_rule_name = "Warnings"
[ 11748, 450, 66, 198, 11748, 10688, 198, 198, 6738, 2644, 1330, 38491, 628, 198, 198, 4871, 399, 39223, 11395, 3109, 1023, 7, 31929, 2599, 198, 220, 220, 220, 1303, 6208, 31137, 611, 1988, 318, 35575, 290, 407, 532, 17032, 198, 220, 22...
2.692913
1,016
# Copyright 2022 Maximilien Le Clei. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.nn as nn from nets.static.base import StaticNetBase
[ 2, 15069, 33160, 5436, 26641, 2013, 1004, 3779, 72, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.745763
177
from sys import argv from os.path import splitext from lxml import etree from struct import pack if __name__ == "__main__": main()
[ 6738, 25064, 1330, 1822, 85, 198, 6738, 28686, 13, 6978, 1330, 4328, 578, 742, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 6738, 2878, 1330, 2353, 628, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 361, 11593, 36...
2.631579
57
import pandas as pd import smartplots3_setup scenarios_lables = { "Base_CL_CT": "Base0", "Base_STL_STT_BAU": "Base2", "Base_STL_STT_VTO": "Base3", "Base_LTL_LTT_BAU": "Base5", "Base_LTL_LTT_VTO": "Base6", "A_STL_STT_BAU": "A2", "A_STL_STT_VTO": "A3", "B_LTL_LTT_BAU": "B5", "B_LTL_LTT_VTO": "B6", "C_LTL_LTT_BAU": "C5", "C_LTL_LTT_VTO": "C6" } output_folder = "/home/ubuntu/git/jupyter/data/28thOct2019" # Base_CL_CT # A_STL_STT_BAU settings=[] settings.append(createSettingRow(2010,1,15,scenarios_lables["Base_CL_CT"], "")) settings.append(createSettingRow(2025,6,15,scenarios_lables["A_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,7,15,scenarios_lables["A_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,8,15,scenarios_lables["B_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,9,15,scenarios_lables["B_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2040,10,15,scenarios_lables["C_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,11,15,scenarios_lables["C_LTL_LTT_VTO"], "")) plt_setup_smart3 = createSetup('7scenarios', (7.75/0.315) * 27.0 / 21.3, 27.0/21.3, (8, 4.5), settings) #smartplots3_setup.pltRealizedModeSplitByTrips(plt_setup_smart3, output_folder) #smartplots3_setup.pltModeSplitInPMTPerCapita(plt_setup_smart3, output_folder) #smartplots3_setup.pltAveragePersonSpeed_allModes(plt_setup_smart3, output_folder) #smartplots3_setup.pltAveragePersonSpeed_car(plt_setup_smart3, output_folder) #smartplots3_setup.pltModeSplitInVMT(plt_setup_smart3, output_folder) #smartplots3_setup.pltRHEmptyPooled(plt_setup_smart3, output_folder) #smartplots3_setup.pltRHWaitTime(plt_setup_smart3, output_folder) #smartplots3_setup.pltLdvTechnologySplitInVMT(plt_setup_smart3, output_folder) settings=[] settings.append(createSettingRow(2010,1,15,scenarios_lables["Base_CL_CT"], "")) settings.append(createSettingRow(2025,2,15,scenarios_lables["Base_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,3,15,scenarios_lables["Base_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,4,15,scenarios_lables["Base_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,5,15,scenarios_lables["Base_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2025,6,15,scenarios_lables["A_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,7,15,scenarios_lables["A_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,8,15,scenarios_lables["B_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,9,15,scenarios_lables["B_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2040,10,15,scenarios_lables["C_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,11,15,scenarios_lables["C_LTL_LTT_VTO"], "")) plt_setup_smart3_base = createSetup('11scenarios', (7.75/0.315) * 27.0 / 21.3, 27.0/21.3, (10, 4.5), settings) smartplots3_setup.pltEnergyPerCapita(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRealizedModeSplitByTrips(plt_setup_smart3_base, output_folder) smartplots3_setup.pltModeSplitInPMTPerCapita(plt_setup_smart3_base, output_folder) smartplots3_setup.pltAveragePersonSpeed_allModes(plt_setup_smart3_base, output_folder) smartplots3_setup.pltAveragePersonSpeed_car(plt_setup_smart3_base, output_folder) smartplots3_setup.pltModeSplitInVMT(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRHEmptyPooled(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRHWaitTime(plt_setup_smart3_base, output_folder) smartplots3_setup.pltLdvTechnologySplitInVMT(plt_setup_smart3_base, output_folder) #smartplots3_setup.pltMEP(plt_setup_smart3, output_folder, [15071,21151,22872,29014,27541,36325,45267]) smartplots3_setup.tableSummary(plt_setup_smart3_base, output_folder)
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 4451, 489, 1747, 18, 62, 40406, 198, 198, 1416, 268, 13010, 62, 75, 2977, 796, 1391, 198, 220, 220, 220, 366, 14881, 62, 5097, 62, 4177, 1298, 366, 14881, 15, 1600, 198, 220, 220, 220, ...
2.281327
1,628
from genrl.deep.agents.sac.sac import SAC # noqa
[ 6738, 2429, 45895, 13, 22089, 13, 49638, 13, 30584, 13, 30584, 1330, 311, 2246, 220, 1303, 645, 20402, 198 ]
2.631579
19
import os import sys if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 25064, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.48
25
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import time import schedule dir = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] sys.path.append(dir) from utilities.prompt_format import item from unosat_flood_portal_collect import collect as Collect def Wrapper(patch=False): '''Wrapper for main program.''' # # Collect data. # Collect.Main(patch=True) # # Setting-up schedule. # schedule.every(1).day.do(Wrapper) def Main(verbose=True): '''Wrapper to run all the scheduled tasks.''' if verbose: print '%s Running scheduler.' % item('prompt_bullet') try: while True: schedule.run_pending() time.sleep(1) except Exception as e: print e return False if __name__ == '__main__': Main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 7269, 198, 198, 15908, 796, 28686, 13, 6978, 13, 35312, 7, ...
2.609428
297
# python # import warnings # Third party imports import numpy as np # grAdapt from .base import Initial from grAdapt.utils.sampling import sample_corner_bounds
[ 2, 21015, 198, 2, 1330, 14601, 198, 198, 2, 10467, 2151, 17944, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 1036, 48003, 198, 6738, 764, 8692, 1330, 20768, 198, 6738, 1036, 48003, 13, 26791, 13, 37687, 11347, 1330, 6291, 62, 1021...
3.468085
47
"""Base Module.""" from abc import ABC, abstractmethod from typing import Callable, Dict, List, Optional, Union, cast from eth_account.account import LocalAccount from thirdweb_web3 import Web3 from thirdweb_web3.types import TxReceipt from zero_ex.contract_wrappers import TxParams import json from ..abi.coin import Coin from ..abi.erc165 import ERC165 from ..abi.market import Market from ..abi.nft import SignatureMint721 as NFT from ..abi.nft_collection import NFTCollection as NFTBundle from ..abi.pack import Pack from ..constants.erc_interfaces import InterfaceIdErc721, InterfaceIdErc1155 from ..errors import NoSignerException import io from ..options import SdkOptions from ..storage import IpfsStorage from ..types.role import Role ModuleTypes = Union[NFT, Market, Pack, NFTBundle, Coin]
[ 37811, 14881, 19937, 526, 15931, 198, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 4889, 540, 11, 360, 713, 11, 7343, 11, 32233, 11, 4479, 11, 3350, 198, 198, 6738, 4555, 62, 23317, 13, 23317, 1330, 10714,...
3.364017
239
# Copyright 2021 Jacob Durrant # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Contains utility code for reading packed data files. """ import os import torch from torch.utils.data import DataLoader, Dataset import numpy as np import h5py import tqdm # Atom typing # # Atom typing is the process of figuring out which layer each atom should be # written to. For ease of testing, the packed data file contains a lot of # potentially useful atomic information which can be distilled during the # data loading process. # # Atom typing is implemented by map functions of the type: # (atom descriptor) -> (layer index) # # If the layer index is -1, the atom is ignored. REC_TYPER = { # 1 channel, no hydrogen 'single': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: num not in [0,1] ]), # 1 channel, including hydrogen 'single_h': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: num != 0 ]), # (C,N,O,S,*) 'simple': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: num == 6, lambda num, aro, hdon, hacc, pcharge: num == 7, lambda num, aro, hdon, hacc, pcharge: num == 8, lambda num, aro, hdon, hacc, pcharge: num == 16, lambda num, aro, hdon, hacc, pcharge: num not in [0,1,6,7,8,16], ]), # (H,C,N,O,S,*) 'simple_h': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: num == 1, lambda num, aro, hdon, hacc, pcharge: num == 6, lambda num, aro, hdon, hacc, pcharge: num == 7, lambda num, aro, hdon, hacc, pcharge: num == 8, lambda num, aro, hdon, hacc, pcharge: num == 16, lambda num, aro, hdon, hacc, pcharge: num not in [0,1,6,7,8,16], ]), # (aro, hdon, hacc, positive, negative, occ) 'meta': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: bool(aro), # aromatic lambda num, aro, hdon, hacc, pcharge: bool(hdon), # hydrogen donor lambda num, aro, hdon, hacc, pcharge: bool(hacc), # hydrogen acceptor lambda num, aro, hdon, hacc, pcharge: pcharge >= 128, # partial positive lambda num, aro, hdon, hacc, pcharge: pcharge < 128, # partial negative lambda num, aro, hdon, hacc, pcharge: num != 0, # occupancy ]), # (aro, hdon, hacc, positive, negative, occ) 'meta_mix': CondAtomTyper([ lambda num, aro, hdon, hacc, pcharge: bool(aro), # aromatic lambda num, aro, hdon, hacc, pcharge: bool(hdon), # hydrogen donor lambda num, aro, hdon, hacc, pcharge: bool(hacc), # hydrogen acceptor lambda num, aro, hdon, hacc, pcharge: pcharge >= 128, # partial positive lambda num, aro, hdon, hacc, pcharge: pcharge < 128, # partial negative lambda num, aro, hdon, hacc, pcharge: num != 0, # occupancy lambda num, aro, hdon, hacc, pcharge: num == 1, # hydrogen lambda num, aro, hdon, hacc, pcharge: num == 6, # carbon lambda num, aro, hdon, hacc, pcharge: num == 7, # nitrogen lambda num, aro, hdon, hacc, pcharge: num == 8, # oxygen lambda num, aro, hdon, hacc, pcharge: num == 16, # sulfur ]) } LIG_TYPER = { # 1 channel, no hydrogen 'single': CondAtomTyper([ lambda num: num not in [0,1] ]), # 1 channel, including hydrogen 'single_h': CondAtomTyper([ lambda num: num != 0 ]), 'simple': CondAtomTyper([ lambda num: num == 6, # carbon lambda num: num == 7, # nitrogen lambda num: num == 8, # oxygen lambda num: num not in [0,1,6,7,8] # extra ]), 'simple_h': CondAtomTyper([ lambda num: num == 1, # hydrogen lambda num: num == 6, # carbon lambda num: num == 7, # nitrogen lambda num: num == 8, # oxygen lambda num: num not in [0,1,6,7,8] # extra ]) }
[ 2, 15069, 33448, 12806, 11164, 5250, 198, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 198, 2, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 257...
2.495662
1,729
from discord.gateway import DiscordWebSocket, utils, _log, KeepAliveHandler, ReconnectWebSocket DiscordWebSocket.received_message = received_message
[ 6738, 36446, 13, 10494, 1014, 1330, 39462, 13908, 39105, 11, 3384, 4487, 11, 4808, 6404, 11, 9175, 2348, 425, 25060, 11, 23419, 1606, 13908, 39105, 201, 198, 201, 198, 201, 198, 15642, 585, 13908, 39105, 13, 47844, 62, 20500, 796, 2722,...
3.444444
45
import numpy as np np.random.seed(123) # for reproducibility from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from dataset_pothole import pothole from keras.models import model_from_json # 4. Load pre-shuffled MNIST data into train and test sets (X_train, y_train), (X_test, y_test) = pothole.load_data() print(X_train.shape) print() print (y_train.shape) print() # 5. Preprocess input data X_train = X_train.reshape(X_train.shape[0], 200, 200, 1) X_test = X_test.reshape(X_test.shape[0], 200, 200, 1) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 3380 X_test /= 3380 # 6. Preprocess class labels Y_train = np_utils.to_categorical(y_train, 4) Y_test = np_utils.to_categorical(y_test, 4) # 7. Define model architecture nb_classes = 4 # number of epochs to train # number of convolutional filters to use nb_filters = 32 # size of pooling area for max pooling nb_pool = 2 # convolution kernel size nb_conv = 3 model = Sequential() model.add(Convolution2D(nb_filters, nb_conv, nb_conv, border_mode='valid', input_shape=(200, 200, 1))) convout1 = Activation('relu') model.add(convout1) model.add(Convolution2D(nb_filters, nb_conv, nb_conv)) convout2 = Activation('relu') model.add(convout2) model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(128)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta') # 9. Fit model on training data model.fit(X_train, Y_train, batch_size=32, nb_epoch=2, verbose=1) # 10. Evaluate model on test data score = model.evaluate(X_test, Y_test, verbose=0) # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") print('Test loss: ', score[0]) print('Test accuracy: ', score[1])
[ 11748, 299, 32152, 355, 45941, 198, 37659, 13, 25120, 13, 28826, 7, 10163, 8, 220, 1303, 329, 8186, 66, 2247, 198, 220, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, 11, 1...
2.502268
882
import hashlib import random import string import logging from django.db import models LOG = logging.getLogger(__name__)
[ 11748, 12234, 8019, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 198, 25294, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 628, 198 ]
3.368421
38
# flake8:NOQA """Python asteroid airburst calculator""" from .solver import * from .damage import * from .locator import * from .mapping import *
[ 2, 781, 539, 23, 25, 15285, 48, 32, 198, 37811, 37906, 27460, 1633, 31961, 28260, 37811, 198, 198, 6738, 764, 82, 14375, 1330, 1635, 198, 6738, 764, 28735, 1330, 1635, 198, 6738, 764, 17946, 1352, 1330, 1635, 198, 6738, 764, 76, 5912,...
3.266667
45
from django.contrib.auth import SESSION_KEY from django.core.cache import cache from django.conf import settings from django.http import HttpResponse, HttpResponseServerError from proxy_server.response import AJAX_REQUEST import httplib, json, proxy_server
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 311, 47621, 62, 20373, 198, 6738, 42625, 14208, 13, 7295, 13, 23870, 1330, 12940, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 3...
3.569444
72
# from peewee import * from playhouse.apsw_ext import TextField, IntegerField, PrimaryKeyField from py.trawl_analyzer.Settings import SensorsModel as BaseModel # database = SqliteDatabase('data\clean_sensors.db', **{})
[ 2, 422, 613, 413, 1453, 1330, 1635, 198, 6738, 711, 4803, 13, 1686, 86, 62, 2302, 1330, 8255, 15878, 11, 34142, 15878, 11, 21087, 9218, 15878, 198, 6738, 12972, 13, 83, 13132, 62, 38200, 9107, 13, 26232, 1330, 14173, 669, 17633, 355, ...
3.246377
69
import transitions from functools import partial # from transitions import transitions.Machine # TODO: whenever there is a state chage store the following # (DAY,function_called) -> Stored for every person for agent status, state and Testing state
[ 11748, 27188, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 2, 422, 27188, 1330, 27188, 13, 37573, 628, 198, 2, 16926, 46, 25, 8797, 612, 318, 257, 1181, 442, 496, 3650, 262, 1708, 198, 2, 357, 26442, 11, 8818, 62, 7174, 8, 4613, ...
4.095238
63
import os import scipy.io.wavfile as wav # install lame # install bleeding edge scipy (needs new cython) fname = 'XC135672-Red-winged\ Blackbird1301.mp3' oname = 'temp.wav' cmd = 'lame --decode {0} {1}'.format( fname,oname ) os.system(cmd) data = wav.read(oname) # your code goes here print len(data[1])
[ 11748, 28686, 198, 11748, 629, 541, 88, 13, 952, 13, 45137, 7753, 355, 266, 615, 198, 2, 2721, 30248, 198, 2, 2721, 16832, 5743, 629, 541, 88, 357, 50032, 649, 3075, 400, 261, 8, 198, 69, 3672, 796, 705, 55, 34, 17059, 43864, 12, ...
2.471545
123
"""Config flow for Eva Calor.""" from collections import OrderedDict import logging import uuid from pyevacalor import ( # pylint: disable=redefined-builtin ConnectionError, Error as EvaCalorError, UnauthorizedError, evacalor, ) import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from .const import CONF_UUID, DOMAIN _LOGGER = logging.getLogger(__name__) def conf_entries(hass): """Return the email tuples for the domain.""" return set( entry.data[CONF_EMAIL] for entry in hass.config_entries.async_entries(DOMAIN) )
[ 37811, 16934, 5202, 329, 32355, 2199, 273, 526, 15931, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 18931, 198, 11748, 334, 27112, 198, 198, 6738, 12972, 1990, 330, 282, 273, 1330, 357, 220, 1303, 279, 2645, 600, 25, 15560,...
2.780702
228
# Dataview.py # import json from .DataviewQuery import DataviewQuery from .DataviewMapping import DataviewMapping from .DataviewIndexConfig import DataviewIndexConfig from .DataviewGroupRule import DataviewGroupRule
[ 2, 16092, 615, 769, 13, 9078, 198, 2, 198, 198, 11748, 33918, 198, 6738, 764, 27354, 615, 769, 20746, 1330, 16092, 615, 769, 20746, 198, 6738, 764, 27354, 615, 769, 44, 5912, 1330, 16092, 615, 769, 44, 5912, 198, 6738, 764, 27354, 6...
3.238806
67
from tkinter import * window0 = Tk() window0.geometry('960x540') #tk.iconbitmap(default='ROBO_BEV_LOGO.ico') window0.title("BARISTO") photo = PhotoImage(file="Page1.png") widget = Label(window0, image=photo) widget.photo = photo widget = Label(window0, text="10", fg="white", font=("Source Sans Pro",50)) #widget = Label(window0, text="9", fg="white") widget.pack() window0.mainloop()
[ 6738, 256, 74, 3849, 1330, 1635, 198, 198, 17497, 15, 796, 309, 74, 3419, 198, 17497, 15, 13, 469, 15748, 10786, 39277, 87, 35005, 11537, 198, 198, 2, 30488, 13, 4749, 2545, 8899, 7, 12286, 11639, 13252, 8202, 62, 12473, 53, 62, 252...
2.613333
150
from os import path from telethon import Client from telethon.types import Message, Voice from callsmusic import callsmusic, queues import converter from downloaders import youtube from config import BOT_NAME as bn, DURATION_LIMIT from helpers.filters import command, other_filters from helpers.decorators import errors from helpers.errors import DurationLimitError from helpers.gets import get_url, get_file_name from telethon.types import InlineKeyboardButton, InlineKeyboardMarkup
[ 6738, 28686, 1330, 3108, 198, 198, 6738, 5735, 400, 261, 1330, 20985, 198, 6738, 5735, 400, 261, 13, 19199, 1330, 16000, 11, 15282, 198, 198, 6738, 3848, 28965, 1330, 3848, 28965, 11, 43359, 198, 198, 11748, 38394, 198, 6738, 4321, 364,...
3.753846
130
from __future__ import annotations from constants import DBL_EPSILON
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 38491, 1330, 360, 9148, 62, 36, 3705, 4146, 1340, 628, 628 ]
3.65
20
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Brief: Produces rand disjoint communities (clusters) for the given network with sizes similar in the ground truth. :Description: Takes number of the resulting communities and their sizes from the specified groundtruth (actually any sample of the community structure, the real ground truth is not required) and fills stubs of the clusters with randomly selected nodes from the input network with all their neighbors. Note: Produced result is a random disjoint partitioning, so if the 'ground truth' had overlapping clusters, then the number of nodes in the last cluster will be less than in the sample. :Authors: Artem Lutov <luart@ya.ru> :Organizations: eXascale lab <http://exascale.info/>, ScienceWise <http://sciencewise.info/>, Lumais <http://www.lumais.com/> :Date: 2015-07 """ from __future__ import print_function, division # Required for stderr output, must be the first import import sys import os # Pathes processing #import igraph as ig import random as rand try: # ATTENTION: Python3 newer treats imports as realtive and results in error here unlike Python2 from utils.parser_nsl import asymnet, loadNsl #pylint: disable=E0611,E0401 except ImportError: # Note: this case should be the second because explicit relative imports cause various errors # under Python2 and Python3, which complicates thier handling from .utils.parser_nsl import asymnet, loadNsl #pylint: disable=E0611,E0401 # Default number of the resulting clusterings (partitions, i.e files that contain disjoint clusters) _RESNUM = 1 def parseParams(args): """Parse user-specified parameters returns - parsed input arguments, Params() """ assert isinstance(args, (tuple, list)) and args, 'Input arguments must be specified' prm = Params() for arg in args: # Validate input format preflen = 3 if arg[0] != '-' or len(arg) <= preflen: raise ValueError('Unexpected argument: ' + arg) if arg[1] == 'g': prm.groundtruth = arg[preflen:] prm.outext = os.path.splitext(prm.groundtruth)[1] elif arg[1] == 'i': pos = arg.find('=', 2) if pos == -1 or arg[2] not in 'ud=' or len(arg) == pos + 1: raise ValueError('Unexpected argument: ' + arg) pos += 1 prm.network = arg[pos:] prm.outname, netext = os.path.splitext(os.path.split(prm.network)[1]) prm.dirnet = asymnet(netext.lower(), arg[2] == 'd') if not prm.outname: raise ValueError('Invalid network name (is a directory): ' + prm.network) elif arg[1] == 'n': prm.outnum = int(arg[preflen:]) assert prm.outnum >= 1, 'outnum must be a natural number' elif arg[1] == 'r': prm.randseed = arg[preflen:] elif arg[1] == 'o': prm.outdir = arg[preflen:] else: raise ValueError('Unexpected argument: ' + arg) if not (prm.groundtruth and prm.network): raise ValueError('Input network and groundtruth file names must be specified') if not prm.outdir: prm.outdir = os.path.split(prm.network)[0] if not prm.outdir: prm.outdir = '.' if not prm.randseed: try: prm.randseed = ''.join(str(ord(c)) for c in os.urandom(8)) except NotImplementedError: prm.randseed = str(rand.random()) prm.outpseed = True return prm def randcommuns(*args): """Generate random clusterings for the specified network""" prm = parseParams(args) print('Starting randcommuns clustering:' '\n\tgroundtruth: {}' '\n\t{} network: {}' '\n\t{} cls of {} in {} with randseed: {}' .format(prm.groundtruth, 'directed' if prm.dirnet else 'undirected', prm.network , prm.outnum, prm.outname + prm.outext, prm.outdir, prm.randseed)) # Load Data from simple real-world networks graph = loadNsl(prm.network, prm.dirnet) # ig.Graph.Read_Ncol(network, directed=dirnet) # , weights=False # Load statistics from the ground thruth groundstat = [] with open(prm.groundtruth, 'r') as fground: for line in fground: # Skip empty lines and comments (possible header) if not line or line[0] == '#': continue groundstat.append(len(line.split())) # Create outpdir if required if prm.outdir and not os.path.exists(prm.outdir): os.makedirs(prm.outdir) # Geneate rand clsuterings rand.seed(prm.randseed) while prm.outnum > 0: prm.outnum -= 1 # Active (remained) nodes indices of the input network actnodes = set(graph.vs.indices) #pylint: disable=E1101 clusters = [] # Forming clusters # Reference size of the ground truth clusters (they migh have overlaps unlike the current partitioning) for clmarg in groundstat: nodes = [] # Content of the current cluster # Check whether all nodes of the initial network are mapped if not actnodes: break # Select subsequent rand node ind = rand.sample(actnodes, 1)[0] actnodes.remove(ind) nodes.append(ind) inode = 0 # Index of the node in the current cluster # Select neighbors of the selected nodes to fill the clusters while len(nodes) < clmarg and actnodes: for nd in graph.vs[nodes[inode]].neighbors(): #pylint: disable=E1136 if nd.index not in actnodes: continue actnodes.remove(nd.index) nodes.append(nd.index) if len(nodes) >= clmarg or not actnodes: break inode += 1 if inode >= len(nodes) and len(nodes) < clmarg and actnodes: ind = rand.sample(actnodes, 1)[0] actnodes.remove(ind) nodes.append(ind) # Use original labels of the nodes clusters.append(graph.vs[ind]['name'] for ind in nodes) #pylint: disable=E1136 # Output resulting clusters with open('/'.join((prm.outdir, ''.join((prm.outname, '_', str(prm.outnum), prm.outext)))), 'w') as fout: for cl in clusters: # Note: print() unlike fout.write() appends the newline print(' '.join(cl), file=fout) # Output randseed used for the generated clusterings # Output to the dir above if possible to not mix cluster levels with rand seed if prm.outpseed: with open('/'.join((prm.outdir, (os.path.splitext(prm.outname)[0] + '.seed'))), 'w') as fout: # Note: print() unlike fout.write() appends the newline print(prm.randseed, file=fout) print('Random clusterings are successfully generated') if __name__ == '__main__': if len(sys.argv) > 2: randcommuns(*sys.argv[1:]) else: print('\n'.join(('Produces random disjoint partitioning (clusters are formed with rand nodes and their neighbors)' ' for the input network specified in the NSL format (generalizaiton of NCOL, SNAP, etc.)\n', 'Usage: {app} -g=<ground_truth> -i[{{u, d}}]=<input_network> [-n=<res_num>] [-r=<rand_seed>] [-o=<outp_dir>]', '', ' -g=<ground_truth> - ground truth clustering as a template for sizes of the resulting communities', ' -i[X]=<input_network> - file of the input network in the format: <src_id> <dst_id> [<weight>]', ' Xu - undirected input network (<src_id> <dst_id> implies also <dst_id> <src_id>). Default', ' Xd - directed input network (both <src_id> <dst_id> and <dst_id> <src_id> are specified)', ' NOTE: (un)directed flag is considered only for the networks with non-NSL file extension', ' -n=<res_num> - number of the resulting clusterings to generate. Default: {resnum}', ' -r=<rand_seed> - random seed, string. Default: value from the system rand source (otherwise current time)', ' -o=<output_communities> - . Default: ./<input_network>/' )).format(app=sys.argv[0], resnum=_RESNUM))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 25, 33, 3796, 25, 21522, 728, 43720, 595, 73, 1563, 5348, 357, 565, 13654, 8, 329, 262, 1813, 3127, 351, ...
2.70169
2,722
import numpy as np import cv2 import os import torch import os import time from torchvision import models, transforms from torch.utils.data import DataLoader from torch.optim import SGD from torch.autograd import Variable idx2catename = {'voc20': ['aeroplane','bicycle','bird','boat','bottle','bus','car','cat','chair','cow','diningtable','dog','horse', 'motorbike','person','pottedplant','sheep','sofa','train','tvmonitor'], 'coco80': ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']}
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 11748, 28034, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 28034, 10178, 1330, 4981, 11, 31408, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, ...
2.151882
744
COGNITO = "Cognito" SERVERLESS_REPO = "ServerlessRepo" MODE = "Mode" XRAY = "XRay" LAYERS = "Layers" HTTP_API = "HttpApi" IOT = "IoT" CODE_DEPLOY = "CodeDeploy" ARM = "ARM" GATEWAY_RESPONSES = "GatewayResponses" MSK = "MSK" KMS = "KMS" CWE_CWS_DLQ = "CweCwsDlq" CODE_SIGN = "CodeSign" MQ = "MQ" USAGE_PLANS = "UsagePlans" SCHEDULE_EVENT = "ScheduleEvent" DYNAMO_DB = "DynamoDB" KINESIS = "Kinesis" SNS = "SNS" SQS = "SQS" CUSTOM_DOMAIN = "CustomDomain"
[ 34, 7730, 45, 2043, 46, 796, 366, 34, 2360, 10094, 1, 198, 35009, 5959, 48481, 62, 2200, 16402, 796, 366, 10697, 1203, 6207, 78, 1, 198, 49058, 796, 366, 19076, 1, 198, 55, 30631, 796, 366, 55, 19591, 1, 198, 43, 4792, 4877, 796, ...
1.92766
235
import onnx import onnxruntime import torch import onnx.numpy_helper # added by huxi, load rpn config from pcdet.pointpillar_quantize_config import load_rpn_config_json # ======================================== config_dict = load_rpn_config_json.get_config() onnx_model_file = config_dict["vfe_onnx_file"] onnx_model = onnx.load(onnx_model_file) onnx.checker.check_model(onnx_model) #check model #[tensor_mat_weight] = [t for t in onnx_model.graph.initializer if t.name == "linear.weight"] [tensor_mat_weight] = [t for t in onnx_model.graph.initializer if t.name == "14"] [tensor_bn_gamma] = [t for t in onnx_model.graph.initializer if t.name == "norm.weight"] [tensor_bn_beta] = [t for t in onnx_model.graph.initializer if t.name == "norm.bias"] [tensor_bn_mean] = [t for t in onnx_model.graph.initializer if t.name == "norm.running_mean"] [tensor_bn_var] = [t for t in onnx_model.graph.initializer if t.name == "norm.running_var"] mat_w = onnx.numpy_helper.to_array(tensor_mat_weight) mat_w = mat_w.transpose() mat_w_list = list(mat_w.flatten()) bn_gamma_w = onnx.numpy_helper.to_array(tensor_bn_gamma) bn_gamma_w_list = list(bn_gamma_w.flatten()) bn_beta_w = onnx.numpy_helper.to_array(tensor_bn_beta) bn_beta_w_list = list(bn_beta_w.flatten()) bn_mean_w = onnx.numpy_helper.to_array(tensor_bn_mean) bn_mean_w_list = list(bn_mean_w.flatten()) bn_var_w = onnx.numpy_helper.to_array(tensor_bn_var) bn_var_w_list = list(bn_var_w.flatten()) result_line = "" exported_vfe_weight_file = config_dict["vfe_exported_weight_file"] with open(exported_vfe_weight_file, 'w') as f: for idx,val in enumerate(mat_w_list): result_line += str(val) result_line += " " result_line += "\n" for idx,val in enumerate(bn_gamma_w_list): result_line += str(val) result_line += " " result_line += "\n" for idx,val in enumerate(bn_beta_w_list): result_line += str(val) result_line += " " result_line += "\n" for idx,val in enumerate(bn_mean_w_list): result_line += str(val) result_line += " " result_line += "\n" for idx,val in enumerate(bn_var_w_list): result_line += str(val) result_line += " " f.write(result_line)
[ 11748, 319, 77, 87, 198, 11748, 319, 77, 87, 43282, 198, 11748, 28034, 198, 11748, 319, 77, 87, 13, 77, 32152, 62, 2978, 525, 198, 198, 2, 2087, 416, 289, 2821, 72, 11, 3440, 374, 21999, 4566, 198, 6738, 279, 10210, 316, 13, 4122,...
2.241071
1,008
from sklearn.cluster import KMeans from .exceptions import KMeansException from .task import Task
[ 6738, 1341, 35720, 13, 565, 5819, 1330, 509, 5308, 504, 198, 198, 6738, 764, 1069, 11755, 1330, 509, 5308, 504, 16922, 198, 6738, 764, 35943, 1330, 15941, 628 ]
3.571429
28
# # @license BSD-3-Clause # # Copyright (c) 2019 Project Jupyter Contributors. # Distributed under the terms of the 3-Clause BSD License. import IPython.display import pandas
[ 2, 198, 2, 2488, 43085, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 198, 2, 15069, 357, 66, 8, 13130, 4935, 449, 929, 88, 353, 25767, 669, 13, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 513, 12, 2601, 682, 347, 10305, 13789, ...
3.051724
58
import django.conf url_bases = { 'geonames': { 'dump': 'http://download.geonames.org/export/dump/', 'zip': 'http://download.geonames.org/export/zip/', }, } india_country_code = 'IN' files = { 'state': { 'filename': '', 'urls': [ url_bases['geonames']['dump'] + '{filename}', ], 'fields': [ ] }, 'district': { 'filename': '', 'urls': [ url_bases['geonames']['dump'] + '{filename}', ], 'fields': [ ] }, 'city': { 'filename': '', 'urls': [ url_bases['geonames']['dump'] + '{filename}', ], 'fields': [ ] } } LANGUAGE_DATA = { }
[ 11748, 42625, 14208, 13, 10414, 198, 198, 6371, 62, 65, 1386, 796, 1391, 198, 220, 220, 220, 705, 6281, 1047, 10354, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 705, 39455, 10354, 705, 4023, 1378, 15002, 13, 6281, 1047, 13, 2398, ...
1.78125
416
from decimal import Decimal from typing import List from src.dao.dao import DAO from src.dto.attempt_dto import AttemptDTO from src.entity.evaluation_entity import EvaluationEntity from src.utils.utils import Utils
[ 6738, 32465, 1330, 4280, 4402, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 12351, 13, 67, 5488, 13, 67, 5488, 1330, 17051, 46, 198, 6738, 12351, 13, 67, 1462, 13, 1078, 1791, 62, 67, 1462, 1330, 25770, 35, 10468, 198, 6738, 12351, ...
3.444444
63
#! /usr/bin/python import requests import re from bs4 import BeautifulSoup import colors
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 7007, 198, 11748, 302, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 7577, 628 ]
3.25
28
d = {"1": "a"} d[1] d["1"]
[ 67, 796, 19779, 16, 1298, 366, 64, 20662, 198, 67, 58, 16, 60, 198, 67, 14692, 16, 8973, 198 ]
1.421053
19
#!/usr/bin/python # This program revises the existing overview file. # If a keyword is found in an Abstract of an accession of a gene, the url of the abstract is added to the overview file # The revised overview.txt is created in the same directory of the old one and named overview_new.txt """ Usage: link_assignment.py -o <overview> -pub <pubhits> -h --help Please enter the files overview.txt and the pubhits. """ from docopt import docopt from sys import argv import csv import os import util def build_overview_link(pubhits_dict, gene_id, links): """ builds the pubhits link out of the gene id and the pubhits dict :param pubhits_dict: pubhits dictionary :param gene_id: gene id :param links: existsing links :return: links """ pubhits_acc = pubhits_dict[gene_id][util.PUBHITS_ACC_INDEX] pubhits_link = pubhits_dict[gene_id][util.PUBHITS_LINK_INDEX] if links.strip() == util.NO_LINK: new_links = [pubhits_acc + ":" + pubhits_link] else: new_links = [links, pubhits_acc + ":" + pubhits_link] overview_link = ','.join(new_links) if not overview_link or overview_link == util.TODO: overview_link = util.NO_KEYWORDS return overview_link def set_link_in_row(old_row, pubhits_dict): """ set link in existing overview row (dictionary) :param old_row: overview row :param pubhits_dict: pubhits dictionary :return: revised overview row """ gene_id = old_row[util.GENE_ID] if (gene_id in pubhits_dict): old_row[util.LINKS] = build_overview_link(pubhits_dict, gene_id, old_row[util.LINKS]) return old_row if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 770, 1430, 2710, 2696, 262, 4683, 16700, 2393, 13, 198, 2, 1002, 257, 21179, 318, 1043, 287, 281, 27741, 286, 281, 1895, 295, 286, 257, 9779, 11, 262, 19016, 286, 262, 12531, 318, 2087, ...
2.578462
650
from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth.decorators import login_required from .models import * import cloudinary import cloudinary.uploader import cloudinary.api from django.http import HttpResponseRedirect, JsonResponse from .forms import RegistrationForm, UpdateUserForm, UpdateUserProfileForm, ImageForm, CommentForm from django.contrib.auth import login, authenticate from .models import Image, Comment, Profile from django.contrib.auth.models import User from django.template.loader import render_to_string from django.views.generic import RedirectView from .email import send_welcome_email # Create your views here.
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 445, 1060, 11, 1136, 62, 15252, 62, 273, 62, 26429, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 764, 27530, 1330, 16...
3.733333
180
import FreeCAD, FreeCADGui from arch_texture_utils.resource_utils import iconPath import arch_texture_utils.qtutils as qtutils from arch_texture_utils.selection_utils import findSelectedTextureConfig if __name__ == "__main__": command = ExportTextureConfigCommand(); if command.IsActive(): command.Activated() else: qtutils.showInfo("No open Document", "There is no open document") else: import archtexture_toolbars archtexture_toolbars.toolbarManager.registerCommand(ExportTextureConfigCommand())
[ 11748, 3232, 34, 2885, 11, 3232, 34, 2885, 8205, 72, 198, 198, 6738, 3934, 62, 41293, 62, 26791, 13, 31092, 62, 26791, 1330, 7196, 15235, 198, 11748, 3934, 62, 41293, 62, 26791, 13, 39568, 26791, 355, 10662, 83, 26791, 198, 6738, 3934...
3.091429
175
EDGE = '101' MIDDLE = '01010' CODES = { 'A': ( '0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011' ), 'B': ( '0100111', '0110011', '0011011', '0100001', '0011101', '0111001', '0000101', '0010001', '0001001', '0010111' ), 'C': ( '1110010', '1100110', '1101100', '1000010', '1011100', '1001110', '1010000', '1000100', '1001000', '1110100' ), } LEFT_PATTERN = ( 'AAAAAA', 'AABABB', 'AABBAB', 'AABBBA', 'ABAABB', 'ABBAAB', 'ABBBAA', 'ABABAB', 'ABABBA', 'ABBABA' )
[ 1961, 8264, 796, 705, 8784, 6, 198, 44, 2389, 35, 2538, 796, 705, 486, 20943, 6, 198, 34, 3727, 1546, 796, 1391, 198, 220, 220, 220, 705, 32, 10354, 357, 198, 220, 220, 220, 220, 220, 220, 220, 705, 18005, 8784, 3256, 705, 405, ...
1.842593
324
# -------------- import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file # Code starts here df = pd.read_csv(path) df.head(5) X = df.drop(['customerID','Churn'],1) y = df['Churn'] X_train,X_test,y_train,y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) # -------------- import numpy as np from sklearn.preprocessing import LabelEncoder # Code starts here #Replacing spaces with 'NaN' in train dataset X_train['TotalCharges'].replace(' ',np.NaN, inplace=True) #Replacing spaces with 'NaN' in test dataset X_test['TotalCharges'].replace(' ',np.NaN, inplace=True) #Converting the type of column from X_train to float X_train['TotalCharges'] = X_train['TotalCharges'].astype(float) #Converting the type of column from X_test to float X_test['TotalCharges'] = X_test['TotalCharges'].astype(float) #Filling missing values X_train['TotalCharges'].fillna(X_train['TotalCharges'].mean(),inplace=True) X_test['TotalCharges'].fillna(X_train['TotalCharges'].mean(), inplace=True) #Check value counts print(X_train.isnull().sum()) cat_cols = X_train.select_dtypes(include='O').columns.tolist() #Label encoding train data for x in cat_cols: le = LabelEncoder() X_train[x] = le.fit_transform(X_train[x]) #Label encoding test data for x in cat_cols: le = LabelEncoder() X_test[x] = le.fit_transform(X_test[x]) #Encoding train data target y_train = y_train.replace({'No':0, 'Yes':1}) #Encoding test data target y_test = y_test.replace({'No':0, 'Yes':1}) # -------------- from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import accuracy_score,classification_report,confusion_matrix # Code starts here print(X_train, X_test, y_train, y_test) ada_model = AdaBoostClassifier(random_state = 0) ada_model.fit(X_train, y_train) y_pred = ada_model.predict(X_test) ada_score = accuracy_score(y_test, y_pred) ada_score ada_cm = confusion_matrix(y_test, y_pred) ada_cm # -------------- from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV #Parameter list parameters={'learning_rate':[0.1,0.15,0.2,0.25,0.3], 'max_depth':range(1,3)} # Code starts here xgb_model = XGBClassifier(random_state=0) xgb_model.fit(X_train, y_train) y_pred = xgb_model.predict(X_test) xgb_score = accuracy_score(y_test, y_pred) xgb_cm = confusion_matrix(y_test, y_pred) xgb_cr = classification_report(y_test, y_pred) clf_model = GridSearchCV(estimator=xgb_model,param_grid=parameters) clf_model.fit(X_train, y_train) y_pred = clf_model.predict(X_test) clf_score = accuracy_score(y_test, y_pred) clf_cm = confusion_matrix(y_test, y_pred) clf_cr = classification_report(y_test, y_pred) print(xgb_score, clf_score) print(xgb_cm, clf_cm) print(xgb_cr, xgb_cr)
[ 2, 220, 26171, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 2, 6978, 532, 10644, 286, 2393, 220, 198, 2, 6127, 4940, 994, 198, 198, 7568, 796, 279, 67, 1...
2.552198
1,092
import argparse, time, logging, os, math, random os.environ["MXNET_USE_OPERATOR_TUNING"] = "0" import numpy as np from scipy import stats import mxnet as mx from mxnet import gluon, nd from mxnet import autograd as ag from mxnet.gluon import nn from mxnet.gluon.data.vision import transforms from gluoncv.model_zoo import get_model from gluoncv.utils import makedirs, LRScheduler from os import listdir import os.path import argparse import pickle from mpi4py import MPI mpi_comm = MPI.COMM_WORLD mpi_size = mpi_comm.Get_size() mpi_rank = mpi_comm.Get_rank() # print('rank: %d' % (mpi_rank), flush=True) parser = argparse.ArgumentParser() parser.add_argument("-d", "--dir", type=str, help="dir of the data", required=True) parser.add_argument("--valdir", type=str, help="dir of the val data", required=True) parser.add_argument("--batchsize", type=int, help="batchsize", default=8) parser.add_argument("--epochs", type=int, help="epochs", default=100) parser.add_argument("--interval", type=int, help="log interval", default=10) parser.add_argument("--nsplit", type=int, help="number of split", default=40) parser.add_argument("--lr", type=float, help="learning rate", default=0.001) parser.add_argument("--alpha", type=float, help="moving average", default=1.0) parser.add_argument("--alpha-decay", type=float, help="decay factor of alpha", default=0.5) parser.add_argument("--alpha-decay-epoch", type=str, help="epoch of alpha decay", default='800') parser.add_argument("--log", type=str, help="dir of the log file", default='train_cifar100.log') parser.add_argument("--classes", type=int, help="number of classes", default=20) parser.add_argument("--iterations", type=int, help="number of local epochs", default=50) parser.add_argument("--aggregation", type=str, help="aggregation method", default='mean') parser.add_argument("--nbyz", type=int, help="number of Byzantine workers", default=0) parser.add_argument("--trim", type=int, help="number of trimmed workers on one side", default=0) # parser.add_argument("--lr-decay", type=float, help="lr decay rate", default=0.1) # parser.add_argument("--lr-decay-epoch", type=str, help="lr decay epoch", default='400') parser.add_argument("--iid", type=int, help="IID setting", default=0) parser.add_argument("--model", type=str, help="model", default='mobilenetv2_1.0') parser.add_argument("--save", type=int, help="save", default=0) parser.add_argument("--start-epoch", type=int, help="epoch start from", default=-1) parser.add_argument("--seed", type=int, help="random seed", default=733) args = parser.parse_args() # print(args, flush=True) filehandler = logging.FileHandler(args.log) streamhandler = logging.StreamHandler() if mpi_rank == 0: logger = logging.getLogger('') logger.setLevel(logging.INFO) logger.addHandler(filehandler) logger.addHandler(streamhandler) mx.random.seed(args.seed + mpi_rank) random.seed(args.seed + mpi_rank) np.random.seed(args.seed + mpi_rank) data_dir = os.path.join(args.dir, 'dataset_split_{}'.format(args.nsplit)) train_dir = os.path.join(data_dir, 'train') # val_dir = os.path.join(data_dir, 'val') val_train_dir = os.path.join(args.valdir, 'train') val_val_dir = os.path.join(args.valdir, 'val') training_files = [] for filename in sorted(listdir(train_dir)): absolute_filename = os.path.join(train_dir, filename) training_files.append(absolute_filename) context = mx.cpu() classes = args.classes train_data_list = [] for training_file in training_files: [train_X, train_Y] = get_train_batch(training_file) train_dataset = mx.gluon.data.dataset.ArrayDataset(train_X, train_Y) train_data = gluon.data.DataLoader(train_dataset, batch_size=args.batchsize, shuffle=True, last_batch='rollover', num_workers=1) train_data_list.append(train_data) [val_train_X, val_train_Y] = get_val_train_batch(val_train_dir) val_train_dataset = mx.gluon.data.dataset.ArrayDataset(val_train_X, val_train_Y) val_train_data = gluon.data.DataLoader(val_train_dataset, batch_size=1000, shuffle=False, last_batch='keep', num_workers=1) [val_val_X, val_val_Y] = get_val_val_batch(val_val_dir) val_val_dataset = mx.gluon.data.dataset.ArrayDataset(val_val_X, val_val_Y) val_val_data = gluon.data.DataLoader(val_val_dataset, batch_size=1000, shuffle=False, last_batch='keep', num_workers=1) model_name = args.model if model_name == 'default': net = gluon.nn.Sequential() with net.name_scope(): # First convolutional layer net.add(gluon.nn.Conv2D(channels=64, kernel_size=3, padding=(1,1), activation='relu')) net.add(gluon.nn.BatchNorm()) net.add(gluon.nn.Conv2D(channels=64, kernel_size=3, padding=(1,1), activation='relu')) net.add(gluon.nn.BatchNorm()) net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) net.add(gluon.nn.Dropout(rate=0.25)) # Second convolutional layer # net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) # Third convolutional layer net.add(gluon.nn.Conv2D(channels=128, kernel_size=3, padding=(1,1), activation='relu')) net.add(gluon.nn.BatchNorm()) net.add(gluon.nn.Conv2D(channels=128, kernel_size=3, padding=(1,1), activation='relu')) net.add(gluon.nn.BatchNorm()) net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) net.add(gluon.nn.Dropout(rate=0.25)) # net.add(gluon.nn.Conv2D(channels=64, kernel_size=3, padding=(1,1), activation='relu')) # net.add(gluon.nn.Conv2D(channels=64, kernel_size=3, padding=(1,1), activation='relu')) # net.add(gluon.nn.Conv2D(channels=64, kernel_size=3, padding=(1,1), activation='relu')) # net.add(gluon.nn.MaxPool2D(pool_size=2, strides=2)) # Flatten and apply fullly connected layers net.add(gluon.nn.Flatten()) # net.add(gluon.nn.Dense(512, activation="relu")) # net.add(gluon.nn.Dense(512, activation="relu")) net.add(gluon.nn.Dense(512, activation="relu")) net.add(gluon.nn.Dropout(rate=0.25)) net.add(gluon.nn.Dense(classes)) else: model_kwargs = {'ctx': context, 'pretrained': False, 'classes': classes} net = get_model(model_name, **model_kwargs) if model_name.startswith('cifar') or model_name == 'default': net.initialize(mx.init.Xavier(), ctx=context) else: net.initialize(mx.init.MSRAPrelu(), ctx=context) # # no weight decay # for k, v in net.collect_params('.*beta|.*gamma|.*bias').items(): # v.wd_mult = 0.0 optimizer = 'sgd' lr = args.lr # optimizer_params = {'momentum': 0.9, 'learning_rate': lr, 'wd': 0.0001} optimizer_params = {'momentum': 0.0, 'learning_rate': lr, 'wd': 0.0} # lr_decay_epoch = [int(i) for i in args.lr_decay_epoch.split(',')] alpha_decay_epoch = [int(i) for i in args.alpha_decay_epoch.split(',')] trainer = gluon.Trainer(net.collect_params(), optimizer, optimizer_params) loss_func = gluon.loss.SoftmaxCrossEntropyLoss() train_metric = mx.metric.Accuracy() acc_top1 = mx.metric.Accuracy() acc_top5 = mx.metric.TopKAccuracy(5) train_cross_entropy = mx.metric.CrossEntropy() # warmup # print('warm up', flush=True) trainer.set_learning_rate(0.01) # train_data = random.choice(train_data_list) train_data = train_data_list[90] for local_epoch in range(5): for i, (data, label) in enumerate(train_data): with ag.record(): outputs = net(data) loss = loss_func(outputs, label) loss.backward() trainer.step(args.batchsize) if args.start_epoch > 0: break if args.start_epoch > 0: break # # force initialization # train_data = random.choice(train_data_list) # for i, (data, label) in enumerate(train_data): # outputs = net(data) if mpi_rank == 0: params_prev = [param.data().copy() for param in net.collect_params().values()] else: params_prev = None nd.waitall() # broadcast params_prev = mpi_comm.bcast(params_prev, root=0) for param, param_prev in zip(net.collect_params().values(), params_prev): param.set_data(param_prev) if mpi_rank == 0: worker_list = list(range(mpi_size)) training_file_index_list = [i for i in range(len(training_files))] alpha = args.alpha randperm_choice_list = [] randperm_list = [i for i in range(args.nsplit)] for i in range(int(math.ceil(args.epochs * mpi_size / args.nsplit))): random.shuffle(randperm_list) randperm_choice_list = randperm_choice_list + randperm_list if args.start_epoch > 0: [dirname, postfix] = os.path.splitext(args.log) filename = dirname + ("_%04d.params" % (args.start_epoch)) net.load_parameters(filename, ctx=context) acc_top1.reset() acc_top5.reset() train_cross_entropy.reset() for i, (data, label) in enumerate(val_val_data): outputs = net(data) acc_top1.update(label, outputs) acc_top5.update(label, outputs) for i, (data, label) in enumerate(val_train_data): outputs = net(data) train_cross_entropy.update(label, nd.softmax(outputs)) _, top1 = acc_top1.get() _, top5 = acc_top5.get() _, crossentropy = train_cross_entropy.get() top1_list = mpi_comm.gather(top1, root=0) top5_list = mpi_comm.gather(top5, root=0) crossentropy_list = mpi_comm.gather(crossentropy, root=0) if mpi_rank == 0: top1_list = np.array(top1_list) top5_list = np.array(top5_list) crossentropy_list = np.array(crossentropy_list) logger.info('[Epoch %d] validation: acc-top1=%f acc-top5=%f, loss=%f, lr=%f, alpha=%f'%(args.start_epoch, top1_list.mean(), top5_list.mean(), crossentropy_list.mean(), trainer.learning_rate, alpha)) nd.waitall() time_0 = time.time() for epoch in range(args.start_epoch+1, args.epochs): # train_metric.reset() # if epoch in lr_decay_epoch: # lr = lr * args.lr_decay if epoch in alpha_decay_epoch: alpha = alpha * args.alpha_decay tic = time.time() if args.iid == 0: if mpi_rank == 0: training_file_index_sublist = randperm_choice_list[(mpi_size * epoch):(mpi_size * epoch + mpi_size)] # logger.info(training_file_index_sublist) else: training_file_index_sublist = None training_file_index = mpi_comm.scatter(training_file_index_sublist, root=0) train_data = train_data_list[training_file_index] trainer = gluon.Trainer(net.collect_params(), optimizer, optimizer_params) trainer.set_learning_rate(lr) if alpha < 1: for param, param_prev in zip(net.collect_params().values(), params_prev): if param.grad_req != 'null': param_prev[:] = param.data() * (1-alpha) # select byz workers if args.nbyz > 0: if mpi_rank == 0: random.shuffle(worker_list) byz_worker_list = worker_list[0:args.nbyz] else: byz_worker_list = None byz_worker_list = mpi_comm.bcast(byz_worker_list, root=0) else: byz_worker_list = [] if mpi_rank in byz_worker_list: # byz worker [byz_train_X, byz_train_Y] = get_train_batch_byz(random.choice(training_files)) byz_train_dataset = mx.gluon.data.dataset.ArrayDataset(byz_train_X, byz_train_Y) byz_train_data = gluon.data.DataLoader(byz_train_dataset, batch_size=args.batchsize, shuffle=True, last_batch='rollover', num_workers=1) net.initialize(mx.init.MSRAPrelu(), ctx=context, force_reinit=True) for local_epoch in range(args.iterations): for i, (data, label) in enumerate(byz_train_data): with ag.record(): outputs = net(data) loss = loss_func(outputs, label) loss.backward() trainer.step(args.batchsize) else: # train # local epoch for local_epoch in range(args.iterations): if args.iid == 1: train_data = random.choice(train_data_list) for i, (data, label) in enumerate(train_data): with ag.record(): outputs = net(data) loss = loss_func(outputs, label) loss.backward() trainer.step(args.batchsize) # aggregation nd.waitall() params_np = [param.data().copy().asnumpy() for param in net.collect_params().values()] params_np_list = mpi_comm.gather(params_np, root=0) if mpi_rank == 0: n_params = len(params_np) if args.aggregation == "trim" or args.trim > 0: params_np = [ ( stats.trim_mean( np.stack( [params[j] for params in params_np_list], axis=0), args.trim/mpi_size, axis=0 ) ) for j in range(n_params) ] else: params_np = [ ( np.mean( np.stack( [params[j] for params in params_np_list], axis=0), axis=0 ) ) for j in range(n_params) ] else: params_np = None params_np = mpi_comm.bcast(params_np, root=0) params_nd = [ nd.array(param_np) for param_np in params_np ] for param, param_nd in zip(net.collect_params().values(), params_nd): param.set_data(param_nd) if alpha < 1: # moving average for param, param_prev in zip(net.collect_params().values(), params_prev): if param.grad_req != 'null': weight = param.data() weight[:] = weight * alpha + param_prev # test nd.waitall() toc = time.time() if ( epoch % args.interval == 0 or epoch == args.epochs-1 ) : acc_top1.reset() acc_top5.reset() train_cross_entropy.reset() for i, (data, label) in enumerate(val_val_data): outputs = net(data) acc_top1.update(label, outputs) acc_top5.update(label, outputs) for i, (data, label) in enumerate(val_train_data): outputs = net(data) train_cross_entropy.update(label, nd.softmax(outputs)) _, top1 = acc_top1.get() _, top5 = acc_top5.get() _, crossentropy = train_cross_entropy.get() top1_list = mpi_comm.gather(top1, root=0) top5_list = mpi_comm.gather(top5, root=0) crossentropy_list = mpi_comm.gather(crossentropy, root=0) if mpi_rank == 0: top1_list = np.array(top1_list) top5_list = np.array(top5_list) crossentropy_list = np.array(crossentropy_list) logger.info('[Epoch %d] validation: acc-top1=%f acc-top5=%f, loss=%f, lr=%f, alpha=%f, time=%f, elapsed=%f'%(epoch, top1_list.mean(), top5_list.mean(), crossentropy_list.mean(), trainer.learning_rate, alpha, toc-tic, time.time()-time_0)) # logger.info('[Epoch %d] validation: acc-top1=%f acc-top5=%f'%(epoch, top1, top5)) if args.save == 1: [dirname, postfix] = os.path.splitext(args.log) filename = dirname + ("_%04d.params" % (epoch)) net.save_parameters(filename) nd.waitall()
[ 11748, 1822, 29572, 11, 640, 11, 18931, 11, 28686, 11, 10688, 11, 4738, 198, 418, 13, 268, 2268, 14692, 43243, 12884, 62, 19108, 62, 31054, 25633, 62, 51, 4944, 2751, 8973, 796, 366, 15, 1, 628, 198, 11748, 299, 32152, 355, 45941, 1...
2.183036
7,015
#!/usr/bin/env python # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import os from multiprocessing import Pool import pickle import time import numpy as np import torch from scipy.stats import norm from collections import OrderedDict import plotting as plg import utils.model_utils as mutils import utils.exp_utils as utils def apply_wbc_to_patient(inputs): """ wrapper around prediction box consolidation: weighted box clustering (wbc). processes a single patient. loops over batch elements in patient results (1 in 3D, slices in 2D) and foreground classes, aggregates and stores results in new list. :return. patient_results_list: list over batch elements. each element is a list over boxes, where each box is one dictionary: [[box_0, ...], [box_n,...]]. batch elements are slices for 2D predictions, and a dummy batch dimension of 1 for 3D predictions. :return. pid: string. patient id. """ regress_flag, in_patient_results_list, pid, class_dict, clustering_iou, n_ens = inputs out_patient_results_list = [[] for _ in range(len(in_patient_results_list))] for bix, b in enumerate(in_patient_results_list): for cl in list(class_dict.keys()): boxes = [(ix, box) for ix, box in enumerate(b) if (box['box_type'] == 'det' and box['box_pred_class_id'] == cl)] box_coords = np.array([b[1]['box_coords'] for b in boxes]) box_scores = np.array([b[1]['box_score'] for b in boxes]) box_center_factor = np.array([b[1]['box_patch_center_factor'] for b in boxes]) box_n_overlaps = np.array([b[1]['box_n_overlaps'] for b in boxes]) try: box_patch_id = np.array([b[1]['patch_id'] for b in boxes]) except KeyError: #backward compatibility for already saved pred results ... omg box_patch_id = np.array([b[1]['ens_ix'] for b in boxes]) box_regressions = np.array([b[1]['regression'] for b in boxes]) if regress_flag else None box_rg_bins = np.array([b[1]['rg_bin'] if 'rg_bin' in b[1].keys() else float('NaN') for b in boxes]) box_rg_uncs = np.array([b[1]['rg_uncertainty'] if 'rg_uncertainty' in b[1].keys() else float('NaN') for b in boxes]) if 0 not in box_scores.shape: keep_scores, keep_coords, keep_n_missing, keep_regressions, keep_rg_bins, keep_rg_uncs = \ weighted_box_clustering(box_coords, box_scores, box_center_factor, box_n_overlaps, box_rg_bins, box_rg_uncs, box_regressions, box_patch_id, clustering_iou, n_ens) for boxix in range(len(keep_scores)): clustered_box = {'box_type': 'det', 'box_coords': keep_coords[boxix], 'box_score': keep_scores[boxix], 'cluster_n_missing': keep_n_missing[boxix], 'box_pred_class_id': cl} if regress_flag: clustered_box.update({'regression': keep_regressions[boxix], 'rg_uncertainty': keep_rg_uncs[boxix], 'rg_bin': keep_rg_bins[boxix]}) out_patient_results_list[bix].append(clustered_box) # add gt boxes back to new output list. out_patient_results_list[bix].extend([box for box in b if box['box_type'] == 'gt']) return [out_patient_results_list, pid] def weighted_box_clustering(box_coords, scores, box_pc_facts, box_n_ovs, box_rg_bins, box_rg_uncs, box_regress, box_patch_id, thresh, n_ens): """Consolidates overlapping predictions resulting from patch overlaps, test data augmentations and temporal ensembling. clusters predictions together with iou > thresh (like in NMS). Output score and coordinate for one cluster are the average weighted by individual patch center factors (how trustworthy is this candidate measured by how centered its position within the patch is) and the size of the corresponding box. The number of expected predictions at a position is n_data_aug * n_temp_ens * n_overlaps_at_position (1 prediction per unique patch). Missing predictions at a cluster position are defined as the number of unique patches in the cluster, which did not contribute any predict any boxes. :param dets: (n_dets, (y1, x1, y2, x2, (z1), (z2), scores, box_pc_facts, box_n_ovs). :param box_coords: y1, x1, y2, x2, (z1), (z2). :param scores: confidence scores. :param box_pc_facts: patch-center factors from position on patch tiles. :param box_n_ovs: number of patch overlaps at box position. :param box_rg_bins: regression bin predictions. :param box_rg_uncs: (n_dets,) regression uncertainties (from model mrcnn_aleatoric). :param box_regress: (n_dets, n_regression_features). :param box_patch_id: ensemble index. :param thresh: threshold for iou_matching. :param n_ens: number of models, that are ensembled. (-> number of expected predictions per position). :return: keep_scores: (n_keep) new scores of boxes to be kept. :return: keep_coords: (n_keep, (y1, x1, y2, x2, (z1), (z2)) new coordinates of boxes to be kept. """ dim = 2 if box_coords.shape[1] == 4 else 3 y1 = box_coords[:,0] x1 = box_coords[:,1] y2 = box_coords[:,2] x2 = box_coords[:,3] areas = (y2 - y1 + 1) * (x2 - x1 + 1) if dim == 3: z1 = box_coords[:, 4] z2 = box_coords[:, 5] areas *= (z2 - z1 + 1) # order is the sorted index. maps order to index o[1] = 24 (rank1, ix 24) order = scores.argsort()[::-1] keep_scores = [] keep_coords = [] keep_n_missing = [] keep_regress = [] keep_rg_bins = [] keep_rg_uncs = [] while order.size > 0: i = order[0] # highest scoring element yy1 = np.maximum(y1[i], y1[order]) xx1 = np.maximum(x1[i], x1[order]) yy2 = np.minimum(y2[i], y2[order]) xx2 = np.minimum(x2[i], x2[order]) w = np.maximum(0, xx2 - xx1 + 1) h = np.maximum(0, yy2 - yy1 + 1) inter = w * h if dim == 3: zz1 = np.maximum(z1[i], z1[order]) zz2 = np.minimum(z2[i], z2[order]) d = np.maximum(0, zz2 - zz1 + 1) inter *= d # overlap between currently highest scoring box and all boxes. ovr = inter / (areas[i] + areas[order] - inter) ovr_fl = inter.astype('float64') / (areas[i] + areas[order] - inter.astype('float64')) assert np.all(ovr==ovr_fl), "ovr {}\n ovr_float {}".format(ovr, ovr_fl) # get all the predictions that match the current box to build one cluster. matches = np.nonzero(ovr > thresh)[0] match_n_ovs = box_n_ovs[order[matches]] match_pc_facts = box_pc_facts[order[matches]] match_patch_id = box_patch_id[order[matches]] match_ov_facts = ovr[matches] match_areas = areas[order[matches]] match_scores = scores[order[matches]] # weight all scores in cluster by patch factors, and size. match_score_weights = match_ov_facts * match_areas * match_pc_facts match_scores *= match_score_weights # for the weighted average, scores have to be divided by the number of total expected preds at the position # of the current cluster. 1 Prediction per patch is expected. therefore, the number of ensembled models is # multiplied by the mean overlaps of patches at this position (boxes of the cluster might partly be # in areas of different overlaps). n_expected_preds = n_ens * np.mean(match_n_ovs) # the number of missing predictions is obtained as the number of patches, # which did not contribute any prediction to the current cluster. n_missing_preds = np.max((0, n_expected_preds - np.unique(match_patch_id).shape[0])) # missing preds are given the mean weighting # (expected prediction is the mean over all predictions in cluster). denom = np.sum(match_score_weights) + n_missing_preds * np.mean(match_score_weights) # compute weighted average score for the cluster avg_score = np.sum(match_scores) / denom # compute weighted average of coordinates for the cluster. now only take existing # predictions into account. avg_coords = [np.sum(y1[order[matches]] * match_scores) / np.sum(match_scores), np.sum(x1[order[matches]] * match_scores) / np.sum(match_scores), np.sum(y2[order[matches]] * match_scores) / np.sum(match_scores), np.sum(x2[order[matches]] * match_scores) / np.sum(match_scores)] if dim == 3: avg_coords.append(np.sum(z1[order[matches]] * match_scores) / np.sum(match_scores)) avg_coords.append(np.sum(z2[order[matches]] * match_scores) / np.sum(match_scores)) if box_regress is not None: # compute wt. avg. of regression vectors (component-wise average) avg_regress = np.sum(box_regress[order[matches]] * match_scores[:, np.newaxis], axis=0) / np.sum( match_scores) avg_rg_bins = np.round(np.sum(box_rg_bins[order[matches]] * match_scores) / np.sum(match_scores)) avg_rg_uncs = np.sum(box_rg_uncs[order[matches]] * match_scores) / np.sum(match_scores) else: avg_regress = np.array(float('NaN')) avg_rg_bins = np.array(float('NaN')) avg_rg_uncs = np.array(float('NaN')) # some clusters might have very low scores due to high amounts of missing predictions. # filter out the with a conservative threshold, to speed up evaluation. if avg_score > 0.01: keep_scores.append(avg_score) keep_coords.append(avg_coords) keep_n_missing.append((n_missing_preds / n_expected_preds * 100)) # relative keep_regress.append(avg_regress) keep_rg_uncs.append(avg_rg_uncs) keep_rg_bins.append(avg_rg_bins) # get index of all elements that were not matched and discard all others. inds = np.nonzero(ovr <= thresh)[0] inds_where = np.where(ovr<=thresh)[0] assert np.all(inds == inds_where), "inds_nonzero {} \ninds_where {}".format(inds, inds_where) order = order[inds] return keep_scores, keep_coords, keep_n_missing, keep_regress, keep_rg_bins, keep_rg_uncs def nms_2to3D(dets, thresh): """ Merges 2D boxes to 3D cubes. For this purpose, boxes of all slices are regarded as lying in one slice. An adaptation of Non-maximum suppression is applied where clusters are found (like in NMS) with the extra constraint that suppressed boxes have to have 'connected' z coordinates w.r.t the core slice (cluster center, highest scoring box, the prevailing box). 'connected' z-coordinates are determined as the z-coordinates with predictions until the first coordinate for which no prediction is found. example: a cluster of predictions was found overlap > iou thresh in xy (like NMS). The z-coordinate of the highest scoring box is 50. Other predictions have 23, 46, 48, 49, 51, 52, 53, 56, 57. Only the coordinates connected with 50 are clustered to one cube: 48, 49, 51, 52, 53. (46 not because nothing was found in 47, so 47 is a 'hole', which interrupts the connection). Only the boxes corresponding to these coordinates are suppressed. All others are kept for building of further clusters. This algorithm works better with a certain min_confidence of predictions, because low confidence (e.g. noisy/cluttery) predictions can break the relatively strong assumption of defining cubes' z-boundaries at the first 'hole' in the cluster. :param dets: (n_detections, (y1, x1, y2, x2, scores, slice_id) :param thresh: iou matchin threshold (like in NMS). :return: keep: (n_keep,) 1D tensor of indices to be kept. :return: keep_z: (n_keep, [z1, z2]) z-coordinates to be added to boxes, which are kept in order to form cubes. """ y1 = dets[:, 0] x1 = dets[:, 1] y2 = dets[:, 2] x2 = dets[:, 3] assert np.all(y1 <= y2) and np.all(x1 <= x2), """"the definition of the coordinates is crucially important here: where maximum is taken needs to be the lower coordinate""" scores = dets[:, -2] slice_id = dets[:, -1] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] keep_z = [] while order.size > 0: # order is the sorted index. maps order to index: order[1] = 24 means (rank1, ix 24) i = order[0] # highest scoring element yy1 = np.maximum(y1[i], y1[order]) # highest scoring element still in >order<, is compared to itself: okay? xx1 = np.maximum(x1[i], x1[order]) yy2 = np.minimum(y2[i], y2[order]) xx2 = np.minimum(x2[i], x2[order]) h = np.maximum(0.0, yy2 - yy1 + 1) w = np.maximum(0.0, xx2 - xx1 + 1) inter = h * w iou = inter / (areas[i] + areas[order] - inter) matches = np.argwhere( iou > thresh) # get all the elements that match the current box and have a lower score slice_ids = slice_id[order[matches]] core_slice = slice_id[int(i)] upper_holes = [ii for ii in np.arange(core_slice, np.max(slice_ids)) if ii not in slice_ids] lower_holes = [ii for ii in np.arange(np.min(slice_ids), core_slice) if ii not in slice_ids] max_valid_slice_id = np.min(upper_holes) if len(upper_holes) > 0 else np.max(slice_ids) min_valid_slice_id = np.max(lower_holes) if len(lower_holes) > 0 else np.min(slice_ids) z_matches = matches[(slice_ids <= max_valid_slice_id) & (slice_ids >= min_valid_slice_id)] # expand by one z voxel since box content is surrounded w/o overlap, i.e., z-content computed as z2-z1 z1 = np.min(slice_id[order[z_matches]]) - 1 z2 = np.max(slice_id[order[z_matches]]) + 1 keep.append(i) keep_z.append([z1, z2]) order = np.delete(order, z_matches, axis=0) return keep, keep_z def apply_2d_3d_merging_to_patient(inputs): """ wrapper around 2Dto3D merging operation. Processes a single patient. Takes 2D patient results (slices in batch dimension) and returns 3D patient results (dummy batch dimension of 1). Applies an adaption of Non-Maximum Surpression (Detailed methodology is described in nms_2to3D). :return. results_dict_boxes: list over batch elements (1 in 3D). each element is a list over boxes, where each box is one dictionary: [[box_0, ...], [box_n,...]]. :return. pid: string. patient id. """ in_patient_results_list, pid, class_dict, merge_3D_iou = inputs out_patient_results_list = [] for cl in list(class_dict.keys()): det_boxes, slice_ids = [], [] # collect box predictions over batch dimension (slices) and store slice info as slice_ids. for batch_ix, batch in enumerate(in_patient_results_list): batch_element_det_boxes = [(ix, box) for ix, box in enumerate(batch) if (box['box_type'] == 'det' and box['box_pred_class_id'] == cl)] det_boxes += batch_element_det_boxes slice_ids += [batch_ix] * len(batch_element_det_boxes) box_coords = np.array([batch[1]['box_coords'] for batch in det_boxes]) box_scores = np.array([batch[1]['box_score'] for batch in det_boxes]) slice_ids = np.array(slice_ids) if 0 not in box_scores.shape: keep_ix, keep_z = nms_2to3D( np.concatenate((box_coords, box_scores[:, None], slice_ids[:, None]), axis=1), merge_3D_iou) else: keep_ix, keep_z = [], [] # store kept predictions in new results list and add corresponding z-dimension info to coordinates. for kix, kz in zip(keep_ix, keep_z): keep_box = det_boxes[kix][1] keep_box['box_coords'] = list(keep_box['box_coords']) + kz out_patient_results_list.append(keep_box) gt_boxes = [box for b in in_patient_results_list for box in b if box['box_type'] == 'gt'] if len(gt_boxes) > 0: assert np.all([len(box["box_coords"]) == 6 for box in gt_boxes]), "expanded preds to 3D but GT is 2D." out_patient_results_list += gt_boxes return [[out_patient_results_list], pid] # additional list wrapping is extra batch dim.
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 13130, 7458, 286, 8366, 7412, 38589, 11, 2679, 15523, 4992, 3337, 357, 48510, 37, 57, 737, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169,...
2.403801
7,209
from pupa.scrape import Jurisdiction from legistar.ext.pupa import LegistarPeopleScraper
[ 6738, 15552, 64, 13, 1416, 13484, 1330, 23383, 9409, 2867, 198, 6738, 1232, 47229, 13, 2302, 13, 79, 929, 64, 1330, 3564, 47229, 8061, 3351, 38545, 628 ]
3.333333
27
import yaml import os def parse_config(args): """ prepare configs """ file_dir = os.path.dirname(os.path.realpath('__file__')) messytable_dir = os.path.realpath(os.path.join(file_dir, '..')) config_pathname = os.path.join(messytable_dir,'models',args.config_dir,'train.yaml') config = yaml.load(open(config_pathname, 'r')) config['messytable_dir'] = messytable_dir config['config_dir'] = os.path.join(messytable_dir,'models',args.config_dir) config['data_dir'] = os.path.join(messytable_dir, 'data') if 'data_dir' not in config else config['data_dir'] # NOTE: either indicate data_dir or put the data in messytable/data config['img_dir'] = os.path.join(config['data_dir'],'images') config['train_label_pathname'] = os.path.join(config['data_dir'],'labels',config['train_json']) config['num_workers'] = config['num_workers'] if 'num_workers' in config else 16 config['milestones'] = config['milestones'] if 'milestones' in config else [60, 80] config['split_samples_in_func'] = config['split_samples_in_func'] if 'split_samples_in_func' in config else True config['loss_func'] = config['loss_func'] if 'loss_func' in config else 'ERROR_LOSS_FUNC' config['triplet_margin'] = config['triplet_margin'] if 'triplet_margin' in config else 0.3 config['data_augmentation'] = config['data_augmentation'] if 'data_augmentation' in config else False config['cropped_img_size'] = (config['cropped_height'],config['cropped_width']) config['original_img_size'] = (config['img_height'],config['img_width']) config['scene_ratio'] = config['scene_ratio'] if 'scene_ratio' in config else 1.0 config['cam_selected_num'] = config['cam_selected_num'] if 'cam_selected_num' in config else 8 config['triplet_sampling_ratio'] = config['triplet_sampling_ratio'] if 'triplet_sampling_ratio' in config else [0.5,0.3,0.2] config['image_pairs_per_batch'] = config['image_pairs_per_batch'] if 'image_pairs_per_batch' in config else 24 config['triplet_batch_size'] = config['triplet_batch_size'] if 'triplet_batch_size' in config else config['batch_size'] config['learning_rate'] = float(config['learning_rate']) config['zoomout_crop_num'] = 'single_crop' if len(config['zoomout_ratio']) == 1 else 'multi_crops' # make cam_pairs test_cam_pairs = [] for i in range(1,9): for j in range(i+1,10): test_cam_pairs.append((str(i),str(j))) reversed_cam_pairs = [] for cam_pair in test_cam_pairs: reversed_cam_pairs.append((cam_pair[1],cam_pair[0])) config['test_cam_pairs'] = test_cam_pairs config['train_cam_pairs'] = test_cam_pairs + reversed_cam_pairs config['cam_list'] = [str(i) for i in range(1,10)] return config
[ 11748, 331, 43695, 198, 11748, 28686, 198, 198, 4299, 21136, 62, 11250, 7, 22046, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 8335, 4566, 82, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 2393, 62, 15908, 796, 28686, 13, 6...
2.60452
1,062
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '!t_(11ght0&nmb&$tf4to=gdg&u$!hsm3@)c6dzp=zdc*c9zci' # nosec INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'adminlte2_templates', 'tests', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'tests.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(BASE_DIR, 'tests/templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'adminlte2_templates.context_processors.template', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
[ 11748, 28686, 198, 198, 33, 11159, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 22305, 198, 198, 23683, 26087, 62, 20373, 796, 705, 0...
1.983389
602
import argparse import numpy as np import csv if __name__ == "__main__": parser = argparse.ArgumentParser(description='fxy_gen.py generates a synthetic dataset file calling a two-variables real function on a rectangle') parser.add_argument('--dsout', type=str, dest='ds_output_filename', required=True, help='dataset output file (csv format)') parser.add_argument('--fxy', type=str, dest='func_xy_body', required=True, help='f(x, y) body (lamba format)') parser.add_argument('--rxbegin', type=float, dest='range_xbegin', required=False, default=-5.0, help='begin x range (default:-5.0)') parser.add_argument('--rxend', type=float, dest='range_xend', required=False, default=+5.0, help='end x range (default:+5.0)') parser.add_argument('--rybegin', type=float, dest='range_ybegin', required=False, default=-5.0, help='begin y range (default:-5.0)') parser.add_argument('--ryend', type=float, dest='range_yend', required=False, default=+5.0, help='end y range (default:+5.0)') parser.add_argument('--rstep', type=float, dest='range_step', required=False, default=0.01, help='step range (default: 0.01)') args = parser.parse_args() print("#### Started {} {} ####".format(__file__, args)); x_values = np.arange(args.range_xbegin, args.range_xend, args.range_step, dtype=float) y_values = np.arange(args.range_ybegin, args.range_yend, args.range_step, dtype=float) func_xy = eval('lambda x, y: ' + args.func_xy_body) csv_ds_output_file = open(args.ds_output_filename, 'w') with csv_ds_output_file: writer = csv.writer(csv_ds_output_file, delimiter=',') for i in range(0, x_values.size): for j in range(0, y_values.size): writer.writerow([x_values[i], y_values[j], func_xy(x_values[i], y_values[j])]) print("#### Terminated {} ####".format(__file__));
[ 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 21370, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 30751, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 11213, 11639, 69,...
1.76964
1,502
from corehq.apps.locations.util import location_hierarchy_config from custom.icds_reports.utils import icds_pre_release_features
[ 6738, 4755, 71, 80, 13, 18211, 13, 17946, 602, 13, 22602, 1330, 4067, 62, 71, 959, 9282, 62, 11250, 198, 6738, 2183, 13, 291, 9310, 62, 48922, 13, 26791, 1330, 14158, 9310, 62, 3866, 62, 20979, 62, 40890, 628 ]
3.333333
39
import json import string, sys from random import * # tok = Token() # tok.get_input() # print(json.dumps(tok, cls=MyEncoder))
[ 11748, 33918, 198, 11748, 4731, 11, 25064, 198, 6738, 4738, 1330, 1635, 198, 198, 2, 284, 74, 796, 29130, 3419, 198, 2, 284, 74, 13, 1136, 62, 15414, 3419, 198, 2, 3601, 7, 17752, 13, 67, 8142, 7, 83, 482, 11, 537, 82, 28, 3666,...
2.625
48
from boa_test.tests.boa_test import BoaTest from boa.compiler import Compiler from neo.Settings import settings from neo.Prompt.Commands.BuildNRun import TestBuild
[ 6738, 1489, 64, 62, 9288, 13, 41989, 13, 48614, 62, 9288, 1330, 3248, 64, 14402, 198, 6738, 1489, 64, 13, 5589, 5329, 1330, 3082, 5329, 198, 6738, 19102, 13, 26232, 1330, 6460, 198, 6738, 19102, 13, 24129, 457, 13, 6935, 1746, 13, 1...
3.367347
49
from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['tensorflow==1.8.0','pandas==0.23.1','setuptools==38.7.0','numpy==1.14.1','Keras==2.1.4','scikit_learn==0.19.1','h5py'] setup( name='classifier', version='0.1', install_requires=REQUIRED_PACKAGES, packages=find_packages(), include_package_data=True, description='My training application package.', author='Divyam Madaan', author_email='divyam3897@gmail.com', license='MIT', zip_safe=False )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 2200, 10917, 37819, 62, 47, 8120, 25552, 796, 37250, 83, 22854, 11125, 855, 16, 13, 23, 13, 15, 41707, 79, 392, 292, 855, 15, 13, 19...
2.441315
213
import sys import copy if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 4866, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.583333
24
import os from contextlib import contextmanager from tempfile import NamedTemporaryFile from typing import Optional, Sequence from pydantic import BaseModel, Field, FilePath
[ 11748, 28686, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 20218, 7753, 1330, 34441, 12966, 5551, 8979, 198, 6738, 19720, 1330, 32233, 11, 45835, 198, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 11, 7663, 11, 9220, 15235, 628, ...
4.317073
41
import os import json import argparse if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 1822, 29572, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419 ]
2.793103
29
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.6.0-bd605d07 on 2018-12-20. # 2018, SMART Health IT. import os import io import unittest import json from . import contract from .fhirdate import FHIRDate
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 2980, 515, 422, 376, 39, 4663, 513, 13, 21, 13, 15, 12, 17457, 32417, 67, 2998, 319, 2864, 12, 10...
2.478723
94
import math import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy.stats import ttest_ind from sklearn.preprocessing import LabelEncoder questionnaire, requirements, tasks = load_data() print_visual_design(index(questionnaire, slice(27, 32))) print_previous_knowledge(index(questionnaire, slice(6, 11))) calculate_sus(index(questionnaire, slice(32, 42))) plot_priority_distribution(requirements) calculate_task_success(tasks) calculate_trust_result(index(questionnaire, slice(14, 20)), index(questionnaire, slice(20, 26))) print('Correlation ML expertise and understanding of ML model') print(questionnaire.iloc[:, [6, 15]].corr())
[ 11748, 10688, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 6738, 629, 541, 88, 13, 34242, ...
3.154545
220
""" ***************** Specifying Colors ***************** Matplotlib recognizes the following formats to specify a color: * an RGB or RGBA (red, green, blue, alpha) tuple of float values in closed interval ``[0, 1]`` (e.g., ``(0.1, 0.2, 0.5)`` or ``(0.1, 0.2, 0.5, 0.3)``); * a hex RGB or RGBA string (e.g., ``'#0f0f0f'`` or ``'#0f0f0f80'``; case-insensitive); * a shorthand hex RGB or RGBA string, equivalent to the hex RGB or RGBA string obtained by duplicating each character, (e.g., ``'#abc'``, equivalent to ``'#aabbcc'``, or ``'#abcd'``, equivalent to ``'#aabbccdd'``; case-insensitive); * a string representation of a float value in ``[0, 1]`` inclusive for gray level (e.g., ``'0.5'``); * one of ``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``, they are the single character short-hand notations for blue, green, red, cyan, magenta, yellow, black, and white. * a X11/CSS4 color name (case-insensitive); * a name from the `xkcd color survey`_, prefixed with ``'xkcd:'`` (e.g., ``'xkcd:sky blue'``; case insensitive); * one of the Tableau Colors from the 'T10' categorical palette (the default color cycle): ``{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}`` (case-insensitive); * a "CN" color spec, i.e. ``'C'`` followed by a number, which is an index into the default property cycle (``matplotlib.rcParams['axes.prop_cycle']``); the indexing is intended to occur at rendering time, and defaults to black if the cycle does not include color. .. _xkcd color survey: https://xkcd.com/color/rgb/ "Red", "Green", and "Blue" are the intensities of those colors, the combination of which span the colorspace. How "Alpha" behaves depends on the ``zorder`` of the Artist. Higher ``zorder`` Artists are drawn on top of lower Artists, and "Alpha" determines whether the lower artist is covered by the higher. If the old RGB of a pixel is ``RGBold`` and the RGB of the pixel of the Artist being added is ``RGBnew`` with Alpha ``alpha``, then the RGB of the pixel is updated to: ``RGB = RGBOld * (1 - Alpha) + RGBnew * Alpha``. Alpha of 1 means the old color is completely covered by the new Artist, Alpha of 0 means that pixel of the Artist is transparent. For more information on colors in matplotlib see * the :doc:`/gallery/color/color_demo` example; * the `matplotlib.colors` API; * the :doc:`/gallery/color/named_colors` example. "CN" color selection -------------------- "CN" colors are converted to RGBA as soon as the artist is created. For example, """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl th = np.linspace(0, 2*np.pi, 128) demo('default') demo('seaborn') ############################################################################### # will use the first color for the title and then plot using the second # and third colors of each style's ``mpl.rcParams['axes.prop_cycle']``. # # # .. _xkcd-colors: # # xkcd v X11/CSS4 # --------------- # # The xkcd colors are derived from a user survey conducted by the # webcomic xkcd. `Details of the survey are available on the xkcd blog # <https://blog.xkcd.com/2010/05/03/color-survey-results/>`__. # # Out of 148 colors in the CSS color list, there are 95 name collisions # between the X11/CSS4 names and the xkcd names, all but 3 of which have # different hex values. For example ``'blue'`` maps to ``'#0000FF'`` # where as ``'xkcd:blue'`` maps to ``'#0343DF'``. Due to these name # collisions all of the xkcd colors have ``'xkcd:'`` prefixed. As noted in # the blog post, while it might be interesting to re-define the X11/CSS4 names # based on such a survey, we do not do so unilaterally. # # The name collisions are shown in the table below; the color names # where the hex values agree are shown in bold. import matplotlib._color_data as mcd import matplotlib.patches as mpatch overlap = {name for name in mcd.CSS4_COLORS if "xkcd:" + name in mcd.XKCD_COLORS} fig = plt.figure(figsize=[4.8, 16]) ax = fig.add_axes([0, 0, 1, 1]) for j, n in enumerate(sorted(overlap, reverse=True)): weight = None cn = mcd.CSS4_COLORS[n] xkcd = mcd.XKCD_COLORS["xkcd:" + n].upper() if cn == xkcd: weight = 'bold' r1 = mpatch.Rectangle((0, j), 1, 1, color=cn) r2 = mpatch.Rectangle((1, j), 1, 1, color=xkcd) txt = ax.text(2, j+.5, ' ' + n, va='center', fontsize=10, weight=weight) ax.add_patch(r1) ax.add_patch(r2) ax.axhline(j, color='k') ax.text(.5, j + 1.5, 'X11', ha='center', va='center') ax.text(1.5, j + 1.5, 'xkcd', ha='center', va='center') ax.set_xlim(0, 3) ax.set_ylim(0, j + 2) ax.axis('off')
[ 37811, 198, 8412, 9, 198, 22882, 4035, 29792, 198, 8412, 9, 198, 198, 19044, 29487, 8019, 21570, 262, 1708, 17519, 284, 11986, 257, 3124, 25, 198, 198, 9, 281, 25228, 393, 34359, 4339, 357, 445, 11, 4077, 11, 4171, 11, 17130, 8, 465...
2.760588
1,700
# List Comprehensions ######################### ### Basic List Comprehensions ######################### # allow us to circumvent constructing lists with for loops l = [] # The Old Way for n in range(12): l.append(n**2) [n ** 2 for n in range(12)] # Comprehension way # General Syntax: # [ `expr` for `var` in `iterable` ] ### Multiple iteration --- use tuples! [(i, j) for i in range(2) for j in range(3)] ### Conditionals on the Iterator [i for i in range(20) if i % 3 > 0] #S={i|0<=i<20, 3!|i, iI} l = [] # equivalent old-school construction: for val in range(20): if val % 3: l.append(val) ### Conditionals on the Value # C code :: single-line conditional operator ? # int absval = (val < 0) ? -val : val # Python code :: single-line conditional operator if-else val = -10 val if val >= 0 else -val # if 3 !| val -> val in list. # if 2 | val -> -val. [val if val % 2 else -val for val in range(20) if val % 3] ######################### ### Other comprehensions ######################### { n**2 for n in range(12) } # Set comprehension { n:n**2 for n in range(12) } # Dict comprehension { a % 3 for a in range(1000) } # a = {0, 1, 2} # GENERATOR EXPRESSION ---- see next chapter for deets ( n**2 for n in range(12) )
[ 2, 7343, 3082, 7345, 507, 198, 198, 14468, 7804, 2, 198, 21017, 14392, 7343, 3082, 7345, 507, 198, 14468, 7804, 2, 198, 2, 1249, 514, 284, 33256, 30580, 8341, 351, 329, 23607, 198, 75, 796, 17635, 220, 220, 220, 220, 220, 220, 220, ...
2.639839
497
# -*- coding: utf-8 -*- """CLI for Chemical Roles exporters.""" import os import click from ..constants import DATA directory_option = click.option('--directory', default=DATA) if __name__ == '__main__': export()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 5097, 40, 329, 24872, 371, 4316, 1033, 3816, 526, 15931, 198, 198, 11748, 28686, 198, 198, 11748, 3904, 198, 198, 6738, 11485, 9979, 1187, 1330, 42865, 628, ...
2.851852
81
"""Write DRC rule decks in klayout. TODO: - add min area - define derived layers (composed rules) """ import pathlib from dataclasses import asdict, is_dataclass from typing import List, Optional try: from typing import Literal except ImportError: from typing_extensions import Literal from gdsfactory.config import logger from gdsfactory.install import get_klayout_path from gdsfactory.types import Dict, Layer, PathType layer_name_to_min_width: Dict[str, float] RuleType = Literal[ "width", "space", "enclosing", ] def rule_width(value: float, layer: str, angle_limit: float = 90) -> str: """Min feature size""" category = "width" error = f"{layer} {category} {value}um" return ( f"{layer}.{category}({value}, angle_limit({angle_limit}))" f".output('{error}', '{error}')" ) def rule_space(value: float, layer: str, angle_limit: float = 90) -> str: """Min Space between shapes of layer""" category = "space" error = f"{layer} {category} {value}um" return ( f"{layer}.{category}({value}, angle_limit({angle_limit}))" f".output('{error}', '{error}')" ) def rule_separation(value: float, layer1: str, layer2: str): """Min space between different layers""" error = f"min {layer1} {layer2} separation {value}um" return f"{layer1}.separation({layer2}, {value})" f".output('{error}', '{error}')" def rule_enclosing( value: float, layer1: str, layer2: str, angle_limit: float = 90 ) -> str: """Layer1 must be enclosed by layer2 by value. checks if layer1 encloses (is bigger than) layer2 by value """ error = f"{layer1} enclosing {layer2} by {value}um" return ( f"{layer1}.enclosing({layer2}, angle_limit({angle_limit}), {value})" f".output('{error}', '{error}')" ) def write_layer_definition(layer_map: Dict[str, Layer]) -> str: """Returns layer_map definition script for klayout Args: layer_map: can be dict or dataclass """ layer_map = asdict(layer_map) if is_dataclass(layer_map) else layer_map return [ f"{key} = input({value[0]}, {value[1]})" for key, value in layer_map.items() ] def write_drc_deck(rules: List[str], layer_map: Dict[str, Layer]) -> str: """Returns drc_rule_deck for klayou Args: rules: list of rules layer_map: layer definitions can be dict or dataclass """ script = [] script += write_layer_definition(layer_map=layer_map) script += ["\n"] script += rules return "\n".join(script) def write_drc_deck_macro( name="generic", filepath: Optional[PathType] = None, shortcut: str = "Ctrl+Shift+D", **kwargs, ) -> str: """Write script for klayout rule deck Args: name: drc rule deck name filepath: Optional macro path (defaults to .klayout/drc/name.lydrc) Keyword Args: rules: list of rules layer_map: layer definitions can be dict or dataclass Keyword Args: rules: list of rules layer_map: layer definitions can be dict or dataclass """ script = f"""<?xml version="1.0" encoding="utf-8"?> <klayout-macro> <description>{name} DRC</description> <version/> <category>drc</category> <prolog/> <epilog/> <doc/> <autorun>false</autorun> <autorun-early>false</autorun-early> <shortcut>{shortcut}</shortcut> <show-in-menu>true</show-in-menu> <group-name>drc_scripts</group-name> <menu-path>tools_menu.drc.end</menu-path> <interpreter>dsl</interpreter> <dsl-interpreter-name>drc-dsl-xml</dsl-interpreter-name> <text># {name} DRC # Read about DRC scripts in the User Manual under "Design Rule Check (DRC)" # Based on SOEN pdk https://github.com/usnistgov/SOEN-PDK/tree/master/tech/OLMAC # http://klayout.de/doc/manual/drc_basic.html report("generic DRC") tiles(100) tile_borders(2) threads(3) """ script += write_drc_deck(**kwargs) script += """ </text> </klayout-macro> """ filepath = filepath or get_klayout_path() / "drc" / f"{name}.lydrc" filepath = pathlib.Path(filepath) filepath.write_text(script) logger.info(f"Wrote DRC deck to {filepath}") return script if __name__ == "__main__": import gdsfactory as gf rules = [ rule_width(layer="WG", value=0.2), rule_space(layer="WG", value=0.2), rule_width(layer="M1", value=1), rule_width(layer="M2", value=2), rule_space(layer="M2", value=2), rule_separation(layer1="HEATER", layer2="M1", value=1.0), rule_enclosing(layer1="M1", layer2="VIAC", value=0.2), ] drc_rule_deck = write_drc_deck_macro(rules=rules, layer_map=gf.LAYER) print(drc_rule_deck)
[ 37811, 16594, 360, 7397, 3896, 13136, 287, 479, 39786, 13, 198, 198, 51, 3727, 46, 25, 198, 198, 12, 751, 949, 1989, 198, 12, 8160, 10944, 11685, 357, 5589, 1335, 3173, 8, 198, 37811, 198, 198, 11748, 3108, 8019, 198, 6738, 4818, 33...
2.446942
1,913
# Generated by Django 2.0.4 on 2018-04-17 19:25 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 19, 319, 2864, 12, 3023, 12, 1558, 678, 25, 1495, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#! /usr/bin/env python # coding=utf-8 #================================================================ # Copyright (C) 2019 * Ltd. All rights reserved. # # Editor : VIM # File name : image_demo.py # Author : YunYang1994 # Created date: 2019-01-20 16:06:06 # Description : # #================================================================ import cv2 import numpy as np import core.utils as utils import tensorflow as tf from PIL import Image return_elements = ["input/input_rgb:0","input/input_lwir:0", "pred_sbbox/concat_2:0", "pred_mbbox/concat_2:0", "pred_lbbox/concat_2:0"] pb_file = "./yolov3_coco.pb" image_path_rgb = r"C:\Users\gary\Desktop\b09\test\JPEGImages\rgb\set06_V000_I00019.jpg" image_path_lwir = r"C:\Users\gary\Desktop\b09\test\JPEGImages\lwir\set06_V000_I00019.jpg" num_classes = 1 input_size = 416 graph = tf.Graph() original_rgb = cv2.imread(image_path_rgb) original_lwir = cv2.imread(image_path_lwir) original_image_rgb = cv2.cvtColor(original_rgb, cv2.COLOR_BGR2RGB) original_image_lwir = cv2.cvtColor(original_lwir, cv2.COLOR_BGR2RGB) original_image_size = original_image_rgb.shape[:2] image_rgb,image_lwir = utils.image_preporcess(np.copy(original_image_rgb),np.copy(original_image_lwir), [input_size, input_size]) image_rgb = image_rgb[np.newaxis, ...] image_lwir = image_lwir[np.newaxis, ...] return_tensors = utils.read_pb_return_tensors(graph, pb_file, return_elements) with tf.Session(graph=graph) as sess: pred_sbbox, pred_mbbox, pred_lbbox = sess.run( [return_tensors[2], return_tensors[3], return_tensors[4]], feed_dict={ return_tensors[0]: image_rgb,return_tensors[1]: image_lwir}) pred_bbox = np.concatenate([np.reshape(pred_sbbox, (-1, 5 + num_classes)), np.reshape(pred_mbbox, (-1, 5 + num_classes)), np.reshape(pred_lbbox, (-1, 5 + num_classes))], axis=0) bboxes = utils.postprocess_boxes(pred_bbox, original_image_size, input_size, 0.3) bboxes = utils.nms(bboxes, 0.45, method='nms') image = utils.draw_bbox(original_image_rgb, bboxes) image = Image.fromarray(image) image.show()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 2, 23926, 198, 2, 220, 220, 15069, 357, 34, 8, 13130, 1635, 12052, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 220, 12058, 220, 220, 220, ...
2.270637
957
import cv2 from datetime import * import time import logging import base64 import sys import os import shutil import paho.mqtt.client as mqtt from influxdb import InfluxDBClient import datetime import sys import re from typing import NamedTuple import json from dotenv import load_dotenv load_dotenv("sensor-variables.env") log = logging.getLogger() log.setLevel('DEBUG') handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")) log.addHandler(handler) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) print('Hello 1') def on_connect(client, userdata, flags, rc): """ The callback for when the client receives a CONNACK response from the server.""" print('Connected with result code ' + str(rc)) client.subscribe('topic') # The callback for when a PUBLISH message is received from the server. camera_id = os.getenv('CAMERA_ID') # sys.argv[1] # 123 destination_cluster_ip = os.getenv('DESTINATION_CLUSTER_IP') #sys.argv[2] # '132.207.170.59' JPGQuality = os.getenv('JPGQUALITY')#int(sys.argv[3] ) # 20 transmitdelay = os.getenv('TRANSMITDELAY') # int(sys.argv[4]) # 10 check_looping = 0 INFLUXDB_DATABASE = os.getenv('INFLUXDB_DATABASE_NAME') influx_client = InfluxDBClient(os.getenv('INFLUXDB_DATABASE_IP'), os.getenv('INFLUXDB_DATABASE_PORT'), database=INFLUXDB_DATABASE) _init_influxdb_database() #while True: camera = Camera(camera_id, destination_cluster_ip, JPGQuality, transmitdelay, './imagesout') camera.processVideoStream()
[ 198, 11748, 269, 85, 17, 198, 6738, 4818, 8079, 1330, 1635, 198, 11748, 640, 198, 11748, 18931, 198, 11748, 2779, 2414, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 11748, 279, 17108, 13, 76, 80, 926, 13, 163...
2.702658
602
# Note: # I add an underscore at the biginning of the variable name for example: "_variable" to prevent # conflicts with build-in variables from Oxide. # Use to manage the player's inventory. import ItemManager # Use to get player's information. import BasePlayer # The plug-in name should be the same as the class name and file name.
[ 2, 5740, 25, 198, 220, 220, 220, 1303, 314, 751, 281, 44810, 379, 262, 1263, 23062, 286, 262, 7885, 1438, 329, 1672, 25, 45434, 45286, 1, 284, 2948, 198, 220, 220, 220, 1303, 12333, 351, 1382, 12, 259, 9633, 422, 10736, 485, 13, 1...
3.72043
93
# encoding: utf-8 """ Parameterized decorator for catching errors and displaying them in an error popup """ from enum import Enum import npyscreen # PythonDecorators/decorator_function_with_arguments.py def error_handler(title, dialog_type=DialogType.CONFIRM): """ Decorator for functions to catch their exceptions and display them in an error popup :param title The title of the error pop-up :param dialog_type A DialogType enum """ return wrap
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 37811, 25139, 2357, 1143, 11705, 1352, 329, 16508, 8563, 290, 19407, 606, 287, 281, 4049, 46207, 37227, 198, 6738, 33829, 1330, 2039, 388, 198, 11748, 45941, 28349, 1361, 628, 198, 198, 2, 11361, 1...
3.338028
142
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Taskmaster-2 implementation for ParlAI. No official train/valid/test splits are available as of 2020-05-18, so we make our own splits. """ import os import pandas as pd import hashlib from collections import Counter from parlai.core.opt import Opt from parlai.core.teachers import DialogTeacher from parlai.core.metrics import AverageMetric, F1Metric, BleuMetric from parlai.utils.misc import warn_once import json import parlai.utils.logging as logging from typing import Optional, Tuple from parlai.core.message import Message from parlai.utils.io import PathManager import parlai.tasks.taskmaster2.build as build_ DOMAINS = [ 'flights', 'food-ordering', 'hotels', 'movies', 'restaurant-search', 'sports', 'music', ] ONTO_TOKEN = "Onto:" CALL_TOKEN = "Call:" RESP_TOKEN = "Result:"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287,...
2.959654
347
from jmeter_api.timers.constant_throughput_timer.elements import ConstantThroughputTimer, BasedOn from jmeter_api.timers.constant_timer.elements import ConstantTimer from jmeter_api.timers.uniform_random_timer.elements import UniformRandTimer
[ 6738, 474, 27231, 62, 15042, 13, 16514, 364, 13, 9979, 415, 62, 9579, 1996, 62, 45016, 13, 68, 3639, 1330, 20217, 15046, 1996, 48801, 11, 13403, 2202, 198, 6738, 474, 27231, 62, 15042, 13, 16514, 364, 13, 9979, 415, 62, 45016, 13, 6...
3.422535
71
import os import torch from torch import distributed as dist from torch import multiprocessing as mp from tensorfn import distributed as dist_fn
[ 11748, 28686, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 9387, 355, 1233, 198, 6738, 28034, 1330, 18540, 305, 919, 278, 355, 29034, 198, 198, 6738, 11192, 273, 22184, 1330, 9387, 355, 1233, 62, 22184, 628, 628 ]
4.054054
37
from enum import Enum from threading import Thread import cv2 import time
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 4704, 278, 1330, 14122, 198, 198, 11748, 269, 85, 17, 198, 11748, 640, 628, 198 ]
3.5
22
from mysql.connector.pooling import MySQLConnectionPool from ._connect import _parse_kwargs, _patch_MySQLConnection
[ 6738, 48761, 13, 8443, 273, 13, 7742, 278, 1330, 33476, 32048, 27201, 198, 198, 6738, 47540, 8443, 1330, 4808, 29572, 62, 46265, 22046, 11, 4808, 17147, 62, 3666, 17861, 32048, 628 ]
3.806452
31
# Do not manually invoke this setup.py, use catkin instead! from setuptools import setup from catkin_pkg.python_setup import generate_distutils_setup setup_args = generate_distutils_setup( packages=['vswarm'], package_dir={'': 'src'} ) setup(**setup_args)
[ 2, 2141, 407, 14500, 26342, 428, 9058, 13, 9078, 11, 779, 3797, 5116, 2427, 0, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 3797, 5116, 62, 35339, 13, 29412, 62, 40406, 1330, 7716, 62, 17080, 26791, 62, 40406, 198, 198, ...
2.934066
91
import numpy as np nparr = np.array([i for i in range(10)]) a = np.zeros(10) f = np.zeros(10,dtype=float) n = np.full((3,5),44) r = np.random.randint(0,100,size=(3,5)) r2 = np.random.random((3,5)) x = np.linspace(0,100,50) print(nparr,a,f,n,r,r2,x)
[ 198, 11748, 299, 32152, 355, 45941, 198, 77, 1845, 81, 796, 45941, 13, 18747, 26933, 72, 329, 1312, 287, 2837, 7, 940, 8, 12962, 198, 198, 64, 796, 45941, 13, 9107, 418, 7, 940, 8, 198, 69, 796, 45941, 13, 9107, 418, 7, 940, 11,...
1.908397
131
''' Function: Author: Charles : Charles ''' import re import time from DecryptLogin import login ''''''
[ 7061, 6, 198, 22203, 25, 198, 220, 220, 220, 220, 198, 13838, 25, 198, 220, 220, 220, 7516, 198, 25, 198, 220, 220, 220, 7516, 198, 7061, 6, 198, 11748, 302, 198, 11748, 640, 198, 6738, 4280, 6012, 47790, 1330, 17594, 628, 198, 39...
2.622222
45
from godot.bindings import ResourceLoader from crawlai.grid_item import GridItem from crawlai.items.food import Food from crawlai.math_utils import clamp from crawlai.turn import Turn from crawlai.position import Position _critter_resource = ResourceLoader.load("res://Game/Critter/Critter.tscn")
[ 6738, 5770, 313, 13, 21653, 654, 1330, 20857, 17401, 198, 198, 6738, 27318, 1872, 13, 25928, 62, 9186, 1330, 24846, 7449, 198, 6738, 27318, 1872, 13, 23814, 13, 19425, 1330, 7318, 198, 6738, 27318, 1872, 13, 11018, 62, 26791, 1330, 2940...
3.571429
84
# -*- coding: utf-8 -*- # Copyright: (c) 2015, Peter Sprygada <psprygada@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 25, 357, 66, 8, 1853, 11, 5613, 1338, 563, 70, 4763, 1279, 862, 79, 563, 70, 4763, 31, 504, 856, 13, 785, 29, 198, 2, 22961, 3611, 5094, 13789, 410,...
2.350649
77
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. #!/usr/bin/env python3 import abc import math from collections import defaultdict, deque from dataclasses import dataclass from enum import Enum from typing import ( Any, Callable, cast, Deque, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, ) import torch import torch.distributed as dist import torch.nn as nn from torchmetrics import Metric from torchrec.metrics.metrics_config import RecComputeMode, RecTaskInfo from torchrec.metrics.metrics_namespace import ( compose_metric_key, MetricNameBase, MetricNamespaceBase, MetricPrefix, ) RecModelOutput = Union[torch.Tensor, Dict[str, torch.Tensor]] DefaultValueT = TypeVar("DefaultValueT") ComputeIterType = Iterator[ Tuple[RecTaskInfo, MetricNameBase, torch.Tensor, MetricPrefix] ] MAX_BUFFER_COUNT = 1000 def compute(self) -> List[MetricComputationReport]: if self._my_rank == 0 or self._compute_on_all_ranks: return self._compute() else: return [] def local_compute(self) -> List[MetricComputationReport]: return self._compute() class RecMetric(nn.Module, abc.ABC): r"""The main class template to implement a recommendation metric. This class contains the recommendation tasks information (RecTaskInfo) and the actual computation object (RecMetricComputation). RecMetric processes all the information related to RecTaskInfo and models and pass the required signals to the computation object, allowing the implementation of RecMetricComputation to focus on the mathemetical meaning. A new metric that inherit RecMetric must override the following attributes in its own __init__(): `_namespace` and `_metrics_computations`. No other methods should be overridden. Args: world_size (int): the number of trainers. my_rank (int): the rank of this trainer. batch_size (int): batch size used by this trainer. tasks (List[RecTaskInfo]): the information of the model tasks. compute_mode (RecComputeMode): the computation mode. See RecComputeMode. window_size (int): the window size for the window metric. fused_update_limit (int): the maximum number of updates to be fused. compute_on_all_ranks (bool): whether to compute metrics on all ranks. This is necessary if non-leader rank want to consume global metrics result. process_group (Optional[ProcessGroup]): the process group used for the communication. Will use the default process group if not specified. Call Args: Not supported. Returns: Not supported. Example:: ne = NEMetric( world_size=4, my_rank=0, batch_size=128, tasks=DefaultTaskInfo, ) """ _computation_class: Type[RecMetricComputation] _namespace: MetricNamespaceBase _metrics_computations: nn.ModuleList _tasks: List[RecTaskInfo] _window_size: int _tasks_iter: Callable[[str], ComputeIterType] _update_buffers: Dict[str, List[RecModelOutput]] _default_weights: Dict[Tuple[int, ...], torch.Tensor] PREDICTIONS: str = "predictions" LABELS: str = "labels" WEIGHTS: str = "weights" # TODO(stellaya): Refactor the _[fused, unfused]_tasks_iter methods and replace the # compute_scope str input with an enum def _fuse_update_buffers(self) -> Dict[str, RecModelOutput]: ret: Dict[str, RecModelOutput] = {} for key, output_list in self._update_buffers.items(): if len(output_list) > 0: ret[key] = fuse(output_list) else: assert key == self.WEIGHTS output_list.clear() return ret def _check_fused_update(self, force: bool) -> None: if self._fused_update_limit <= 0: return if len(self._update_buffers[self.PREDICTIONS]) == 0: return if ( not force and len(self._update_buffers[self.PREDICTIONS]) < self._fused_update_limit ): return fused_arguments = self._fuse_update_buffers() self._update( predictions=fused_arguments[self.PREDICTIONS], labels=fused_arguments[self.LABELS], weights=fused_arguments.get(self.WEIGHTS, None), ) def _create_default_weights(self, predictions: torch.Tensor) -> torch.Tensor: weights = self._default_weights.get(predictions.size(), None) if weights is None: weights = torch.ones_like(predictions) self._default_weights[predictions.size()] = weights return weights def _check_nonempty_weights(self, weights: torch.Tensor) -> torch.Tensor: return torch.gt(torch.count_nonzero(weights, dim=-1), 0) def _update( self, *, predictions: RecModelOutput, labels: RecModelOutput, weights: Optional[RecModelOutput], ) -> None: with torch.no_grad(): if self._compute_mode == RecComputeMode.FUSED_TASKS_COMPUTATION: assert isinstance(predictions, torch.Tensor) # Reshape the predictions to size([len(self._tasks), self._batch_size]) predictions = predictions.view(-1, self._batch_size) assert isinstance(labels, torch.Tensor) labels = labels.view(-1, self._batch_size) if weights is None: weights = self._create_default_weights(predictions) else: assert isinstance(weights, torch.Tensor) weights = weights.view(-1, self._batch_size) # has_valid_weights is a tensor of bool whose length equals to the number # of tasks. Each value in it is corresponding to whether the weights # are valid, i.e. are set to non-zero values for that task in this update. # If has_valid_weights are Falses for all the tasks, we just ignore this # update. has_valid_weights = self._check_nonempty_weights(weights) if torch.any(has_valid_weights): self._metrics_computations[0].update( predictions=predictions, labels=labels, weights=weights ) self._metrics_computations[0].has_valid_update.logical_or_( has_valid_weights ).byte() else: for task, metric_ in zip(self._tasks, self._metrics_computations): if task.name not in predictions: continue if torch.numel(predictions[task.name]) == 0: assert torch.numel(labels[task.name]) == 0 assert weights is None or torch.numel(weights[task.name]) == 0 continue # Reshape the predictions to size([1, self._batch_size]) task_predictions = predictions[task.name].view(1, -1) task_labels = labels[task.name].view(1, -1) if weights is None: task_weights = self._create_default_weights(task_predictions) else: task_weights = weights[task.name].view(1, -1) # has_valid_weights is a tensor with only 1 value corresponding to # whether the weights are valid, i.e. are set to non-zero values for # the task in this update. # If has_valid_update[0] is False, we just ignore this update. has_valid_weights = self._check_nonempty_weights(task_weights) if has_valid_weights[0]: metric_.update( predictions=task_predictions, labels=task_labels, weights=task_weights, ) metric_.has_valid_update.logical_or_(has_valid_weights).byte() def update( self, *, predictions: RecModelOutput, labels: RecModelOutput, weights: Optional[RecModelOutput], ) -> None: if self._fused_update_limit > 0: self._update_buffers[self.PREDICTIONS].append(predictions) self._update_buffers[self.LABELS].append(labels) if weights is not None: self._update_buffers[self.WEIGHTS].append(weights) self._check_fused_update(force=False) else: self._update(predictions=predictions, labels=labels, weights=weights) # The implementation of compute is very similar to local_compute, but compute overwrites # the abstract method compute in torchmetrics.Metric, which is wrapped by _wrap_compute def get_memory_usage(self) -> Dict[torch.Tensor, int]: r"""Estimates the memory of the rec metric instance's underlying tensors; returns the map of tensor to size """ tensor_map = {} attributes_q = deque(self.__dict__.values()) while attributes_q: attribute = attributes_q.popleft() if isinstance(attribute, torch.Tensor): tensor_map[attribute] = ( attribute.size().numel() * attribute.element_size() ) elif isinstance(attribute, WindowBuffer): attributes_q.extend(attribute.buffers) elif isinstance(attribute, Mapping): attributes_q.extend(attribute.values()) elif isinstance(attribute, Sequence) and not isinstance(attribute, str): attributes_q.extend(attribute) elif hasattr(attribute, "__dict__") and not isinstance(attribute, Enum): attributes_q.extend(attribute.__dict__.values()) return tensor_map # pyre-fixme[14]: `state_dict` overrides method defined in `Module` inconsistently. class RecMetricList(nn.Module): """ A list module to encapulate multiple RecMetric instances and provide the same interfaces as RecMetric. Args: rec_metrics (List[RecMetric]: the list of the input RecMetrics. Call Args: Not supported. Returns: Not supported. Example:: ne = NEMetric( world_size=4, my_rank=0, batch_size=128, tasks=DefaultTaskInfo ) metrics = RecMetricList([ne]) """ rec_metrics: nn.ModuleList
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 30277, 19193, 82, 11, 3457, 13, 290, 29116, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 347, 10305, 12, 76...
2.245784
4,862
__author__ = 'JohnHiness' import sys import os import random import time import string import connection from time import strftime import ceq import json, urllib2 import thread args = sys.argv req_files = ['filegen.py', 'connection.py', 'commands.py', 'general.py', 'automatics.py'] for filename in req_files: if os.path.exists(filename) == False: print "Required file \"{}\" not found. Make sure you have acquired all files.".format(filename) sys.exit(1) import filegen if os.path.exists('config.py') == False: print 'No configuration-file found. Generating config.py' filegen.gen_config() python = sys.executable print str(python)+'||'+str(python)+'||'+ str(* sys.argv) os.execl(python, python, * sys.argv) if os.path.exists('revar.py') == False: print 'No reconfigurable file found. Generating revar.py' filegen.gen_revar() python = sys.executable print str(python)+'||'+str(python)+'||'+ str(* sys.argv) os.execl(python, python, * sys.argv) import config import revar import filegen import commands import general import automatics if not revar.channels: revar.channels = config.channel.replace(', ', ',').replace(' ', ',').split(',') if len(args) > 1: if args[1].lower() == 'reconfig' or args[1].lower() == 'config': answr = raw_input("This will have you regenerate the configuration file and all old configurations will be lost.\nAre you sure you want to do this?(y/n) ") while answr.lower() != 'y' or answr.lower() != 'n': answr = raw_input("You must use the letters Y or N to answer: ") if answr.lower() == 'y': filegen.gen_config() sys.exit(0) if answr.lower() == 'n': sys.exit(0) elif args[1].lower() == 'help': print "Usage: python alison.py <help | reconfig | >" sys.exit(0) else: print "Flag not recognized." sys.exit(1) if __name__ == '__main__': thread.start_new_thread(automatics.get_ftime, ()) connect(config.server, config.port) thread.start_new_thread(automatics.autoping, ()) thread.start_new_thread(automatics.autoweather, ()) thread.start_new_thread(automatics.checkpongs, ()) thread.start_new_thread(automatics.who_channel, ()) s = connection.s readbuffer = '' while True: readbuffer = readbuffer + s.recv(2048) temp = string.split(readbuffer, "\n") readbuffer = temp.pop() for rline in temp: rline = string.rstrip(rline) rline = string.split(rline) g = general if not server_responses(rline) and len(rline) > 3: msg = ' '.join(rline[3:])[1:] user = rline[0][1:][:rline[0].find('!')][:-1] chan = rline[2] if chan.lower() == revar.bot_nick.lower(): chan = user if config.verbose: print g.ftime + ' << ' + ' '.join(rline) else: print g.ftime + ' << ' + chan + ' <{}> '.format(user) + msg if general.check_bottriggers(msg): thread.start_new_thread(botendtriggerd, (chan, user, msg),) break thread.start_new_thread(find_imdb_link, (chan, msg), ) thread.start_new_thread(work_line, (chan, user, msg), ) msg = general.check_midsentencetrigger(msg) msg = general.check_triggers(msg) if msg: thread.start_new_thread(work_command, (chan, user, msg), )
[ 834, 9800, 834, 796, 705, 7554, 39, 1272, 6, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 640, 198, 11748, 4731, 198, 11748, 4637, 198, 6738, 640, 1330, 965, 31387, 198, 11748, 2906, 80, 198, 11748, 33918, ...
2.537157
1,238
from unittest import TestCase import numpy as np from scipy.signal import fftconvolve import pyroomacoustics as pra # fix seed for repeatability np.random.seed(0) h_len = 30 x_len = 1000 SNR = 1000. # decibels h_lp = np.fft.irfft(np.ones(5), n=h_len) h_rand = np.random.randn(h_len) h_hann = pra.hann(h_len, flag='symmetric') x = np.random.randn(x_len) noise = np.random.randn(x_len + h_len - 1) def generate_signals(SNR, x, h, noise): ''' run convolution ''' # noise standard deviation sigma_noise = 10**(-SNR / 20.) y = fftconvolve(x, h) y += sigma_noise * noise return y, sigma_noise if __name__ == '__main__': import matplotlib.pyplot as plt h = h_hann y, sigma_noise = generate_signals(SNR, x, h, noise) h_hat1 = pra.experimental.deconvolve(y, x, length=h_len) res1 = np.linalg.norm(y - fftconvolve(x, h_hat1))**2 / y.shape[0] mse1 = np.linalg.norm(h_hat1 - h)**2 / h_len h_hat2 = pra.experimental.wiener_deconvolve(y, x, length=h_len, noise_variance=sigma_noise**2, let_n_points=15) res2 = np.linalg.norm(y - fftconvolve(x, h_hat2))**2 / y.shape[0] mse2 = np.linalg.norm(h_hat2 - h)**2 / h_len print('MSE naive: rmse=', np.sqrt(mse1), ' res=', pra.dB(res1, power=True)) print('MSE Wiener: rmse=', np.sqrt(mse2), ' res=', pra.dB(res1, power=True)) plt.plot(h) plt.plot(h_hat1) plt.plot(h_hat2) plt.legend(['Original', 'Naive', 'Wiener']) plt.show()
[ 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 12683, 282, 1330, 277, 701, 42946, 6442, 198, 198, 11748, 12972, 3823, 330, 23968, 873, 355, 7201, 198, 198, 2, 4259, 9403, ...
2.090129
699
import cv2 as cv from deskew import determine_skew import numpy as np from PIL import Image, ImageFilter, ImageOps from pytesseract import image_to_string from skimage import io from skimage.color import rgb2gray from skimage.transform import rotate from spellchecker import SpellChecker import traceback # On Windows, you need to tell it where Tesseract is installed, for example: # pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe # OCR Stuff #################################################################################################### def to_text(pic): """ Read and return text from an image. Args: pic: filename string, pathlib.Path object, or file object to read. Returns: Text from the image. """ try: img = Image.open(pic) except FileNotFoundError as e: print("File " + pic + " does not exist.") quit() except PIL.UnidentifiedImageError as e: print("That file is not an image.") quit() except: print("Unanticipated error:") traceback.print_exc() quit() remove_alpha(img) text = image_to_string(img) return text def valid_text(ocr, accuracy_pct, language="en", distance=2, case_sensitive=True): # this spellchecker sucks """ Checks that the output of to_text() makes sense. To build your own dictionary, see https://pyspellchecker.readthedocs.io/en/latest/quickstart.html#how-to-build-a-new-dictionary Args: ocr: string to analyze. accuracy_pct: percentage of words in ocr that should be in the dictionary. language: language of dictionary (default English); see https://pyspellchecker.readthedocs.io/en/latest/quickstart.html#changing-language distance: Levenshtein distance (default 2 for shorter words); see https://pyspellchecker.readthedocs.io/en/latest/quickstart.html#basic-usage https://en.wikipedia.org/wiki/Levenshtein_distance Returns: Boolean indicating success of to_text(): True: to_text() makes sense. False: to_text() returned nonsense. """ if ocr == "": return False # if it returned nothing word_list = ocr.split() # get list of all words in input string spell = SpellChecker(language=language, distance=distance, case_sensitive=case_sensitive) misspelled = spell.unknown(word_list) # list of unknown words from word_list #print(misspelled) #print(word_list) if (len(word_list) - len(misspelled)) / len(word_list) < accuracy_pct / 100: return False # if it returned gibberish return True # otherwise, all good def parse(pic, accuracy_pct, language="en", distance=2, case_sensitive=True): """ Attempts OCR with image and decides if processing is needed. Args: pic: filename string, pathlib.Path object, or file object to read. accuracy_pct: percentage of words in string that should be in the dictionary. language: language of dictionary (default English); see https://pyspellchecker.readthedocs.io/en/latest/quickstart.html#changing-language distance: Levenshtein distance (default 2 for shorter words); see https://pyspellchecker.readthedocs.io/en/latest/quickstart.html#basic-usage https://en.wikipedia.org/wiki/Levenshtein_distance Returns: Text from the image if OCR was successful; otherwise a failure message. """ text = to_text(pic) if valid_text(text, accuracy_pct, language=language, distance=distance, case_sensitive=case_sensitive): return text else: return "OCR failed." # time for processing # Image Processing Stuff #################################################################################################### def remove_alpha(pic): """ Removes the alpha channel from an image, if it exists. Necessary for OCR. Args: pic: PIL.Image object to convert. Returns: The PIL.Image object in RGB format. """ return pic.convert("RGB") def invert(pic): """ Inverts the colors in an image. Useful if OCR doesn't work. Args: pic: PIL.Image object to invert. Returns: The inverted PIL.Image object. """ return ImageOps.invert(remove_alpha(pic)) # negative colors '''def resize(pic): # needs work: possible key error "dpi" """ Resizes an image that is less than 300 dpi. Useful if OCR doesn't work. Args: pic: PIL.Image object to resize. Returns: The resized PIL.Image object. """ pic = remove_alpha(pic) res = pic.info["dpi"] # fetch tuple of dpi lower = min(res) # get the lower of the two entries in the tuple factor = 300 / lower # how much should we scale? resized = pic.resize((round(pic.size[0]*factor), round(pic.size[1]*factor))) # scale it! return resized''' def threshold(pic, gaussian=True): # needs work """ Applies thresholding to the image. Doesn't work. (Tesseract already tries the Otsu algorithm.) Args: pic: filename string, pathlib.Path object, or file object to read. gaussian: boolean: True: apply adaptive Gaussian thresholding. False: apply adaptive mean thresholding. Returns: The image with thresholding. """ img = cv.imread("test2.jpg", 0) if gaussian: # adaptive Gaussian thresholding img = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2) else: # adaptive mean thresholding img = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2) return Image.fromarray(img) def denoise(pic): # needs work """ Allegedly removes noise? Useful if OCR doesn't work. Args: pic: filename string, pathlib.Path object, or file object to read. Returns: The denoised image. """ img = cv.imread(pic) img = cv.fastNlMeansDenoising(img) return Image.fromarray(img) def dilate(pic, size): """ Dilates the text (grows edges of characters) if it's against a common background. Useful if OCR doesn't work. Args: pic: PIL.Image object to dilate. size: kernel size, in pixels. Recommend starting at 1. Returns: The dilated PIL.Image object. """ pic = remove_alpha(pic) return pic.filter(ImageFilter.MaxFilter(size)) def erode(pic, size): """ Erodes the text (shrinks edges of characters) if it's against a common background. Useful if OCR doesn't work. Args: pic: PIL.Image object to erode. size: kernel size, in pixels. Recommend starting at 1. Returns: The eroded PIL.Image object. """ pic = remove_alpha(pic) return pic.filter(ImageFilter.MinFilter(size)) def deskew(pic, output): # needs work """ Deskews an image. Useful if OCR doesn't work. Args: pic: filename string, pathlib.Path object, or file object to read. output: string to save output as """ # Thanks to Stephane Brunner (https://github.com/sbrunner) for deskew and the code! img = io.imread(pic) grayscale = rgb2gray(img) angle = determine_skew(grayscale) rotated = rotate(img, angle, resize=True) * 255 io.imsave(output, rotated.astype(np.uint8))
[ 11748, 269, 85, 17, 355, 269, 85, 198, 6738, 748, 365, 86, 1330, 5004, 62, 82, 365, 86, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 22417, 11, 7412, 41472, 198, 6738, 12972, 83, 408, 263, 529, 1...
2.649179
2,802
# Params learning_rate = 0.001 k = 0.0025 x0 =2500 epochs = 4 batch_size=16 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") import torch, numpy as np from tqdm import tqdm # Get the dataloader from dataloader import get_train_test trainStays, testStays = get_train_test(train_size=0.95, batch_size=batch_size, shuffle=True, dataset='cuebiq') # Load and define the model from VAE import SentenceVAE # Model params params = dict( vocab_size = trainStays.dataset.dataset._vocab_size, max_sequence_length = trainStays.dataset.dataset._max_seq_len, embedding_size = 256, rnn_type = 'gru', hidden_size = 256, num_layers = 1, bidirectional = False, latent_size = 16, word_dropout = 0, embedding_dropout = 0.5, sos_idx=0, eos_idx=0, pad_idx=0, unk_idx=1, device=device, ) model = SentenceVAE(**params) model = model.to(device) # Device is defined in VAE # Custom loss function from paper NLL = torch.nn.NLLLoss(ignore_index=0, reduction='sum') def loss_fn(logp, target, mean, logv, step, k, x0): """The loss function used in the paper, taken from https://github.com/timbmg/Sentence-VAE""" target = target.view(-1) logp = logp.view(-1, logp.size(2)) # Negative Log Likelihood NLL_loss = NLL(logp, target) # KL Divergence KL_loss = -0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp()) KL_weight = float(1/(1+np.exp(-k*(step-x0)))) return NLL_loss, KL_loss, KL_weight optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # Logging with tensorboard from torch.utils.tensorboard import SummaryWriter LOG_DIR = "runs/cuebiq" comment = f' batch_size = {batch_size} lr = {learning_rate} dp = False' train_writer = SummaryWriter(LOG_DIR + "/train", comment=comment) val_writer = SummaryWriter(LOG_DIR + "/val", comment=comment) # Run training loop step = 0 for epoch in range(epochs): running_loss = 0.0 for i, batch in enumerate(tqdm(trainStays, miniters=500)): batch = batch.to(device) # Forward pass logp, mean, logv, z = model(batch) # loss calculation NLL_loss, KL_loss, KL_weight = loss_fn(logp, batch, mean, logv, step, k, x0) loss = (NLL_loss + KL_weight * KL_loss) / batch_size loss.to(device) # backward + optimization optimizer.zero_grad() loss.backward() optimizer.step() step += 1 running_loss += loss.item() if i % 1000 == 999: train_writer.add_scalar('loss', running_loss / 1000, epoch * len(trainStays) + i) running_loss = 0.0 # Periodic Validation and checkpointing if i % 20000 == 19999: model.eval() val_loss = 0.0 for batch in testStays: batch = batch.to(device) logp, mean, logv, z = model(batch) NLL_loss, KL_loss, KL_weight = loss_fn(logp, batch, mean, logv, step, k, x0) loss = (NLL_loss + KL_weight * KL_loss) / batch_size val_loss += loss.item() val_writer.add_scalar('loss', val_loss / 20000, epoch * len(trainStays) + i) model.train() torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': val_loss / 10000, 'params': params, }, '../models/cuebiq_vae.pt') train_writer.close() val_writer.close()
[ 2, 2547, 4105, 198, 40684, 62, 4873, 796, 657, 13, 8298, 198, 74, 796, 657, 13, 405, 1495, 198, 87, 15, 796, 44688, 198, 538, 5374, 82, 796, 604, 198, 43501, 62, 7857, 28, 1433, 198, 25202, 796, 28034, 13, 25202, 7203, 66, 15339, ...
2.206725
1,606