content
stringlengths
0
1.55M
<import_stmt>lbann<import_stmt>lbann.modules<class_stmt>FullyConnectedAutoencoder(lbann.modules.Module)<block_start>"""Multilayer perceptron autoencoder."""<line_sep>global_count=0# Static counter, used for default names <def_stmt>__init__ self data_dim latent_dim encoder_hidden_dims=[] decoder_hidden_dims=[] activation=lbann.Relu data_layout='data_parallel' name=<none> <block_start>super().__init__()<line_sep>FullyConnectedAutoencoder.global_count<augadd>1<line_sep># Module name self.name=name<if_stmt><not>self.name<block_start>self.name=f'fcautoencoder{FullyConnectedAutoencoder.global_count}'<block_end># Encoder self.encoder=[]<for_stmt>i,dim enumerate(encoder_hidden_dims)<block_start>self.encoder.append(lbann.modules.FullyConnectedModule(size=dim bias=<false> activation=activation name=f'{self.name}_encoder{i}' data_layout=data_layout ))<block_end>self.encoder.append(lbann.modules.FullyConnectedModule(size=latent_dim bias=<false> activation=activation name=f'{self.name}_encoder{len(self.encoder)}' data_layout=data_layout ))<line_sep># Decoder self.decoder=[]<for_stmt>i,dim enumerate(decoder_hidden_dims)<block_start>self.decoder.append(lbann.modules.FullyConnectedModule(size=dim bias=<false> activation=activation name=f'{self.name}_decoder{i}' data_layout=data_layout ))<block_end>self.decoder.append(lbann.modules.FullyConnectedModule(size=data_dim bias=<false> activation=activation name=f'{self.name}_decoder{len(self.decoder)}' data_layout=data_layout ))<block_end><def_stmt>forward self x<block_start><for_stmt>l self.encoder<block_start>x=l(x)<block_end><for_stmt>l self.decoder<block_start>x=l(x)<block_end><return>x<block_end><block_end>
<import_stmt>struct<import_stmt>time<import_stmt>yaml<import_stmt>yaml.resolver<import_from_stmt>collections OrderedDict<import_stmt>data_types<import_from_stmt>data_types TypeID<def_stmt>now_ns <block_start><return>int(time.time()<times>10<power>6)<block_end><class_stmt>Schema<block_start>""" The schema for the data in the atomic multilog. """<def_stmt>__init__ self columns<block_start>""" Initializes the schema to the list of columns passed in. Args: columns: The list of columns that make up the schema. """<line_sep>self.record_size_=0<line_sep>self.columns_=columns<for_stmt>c self.columns_<block_start>self.record_size_<augadd>c.data_type_.size_<block_end><block_end><def_stmt>__str__ self<block_start>""" Convert to string Returns: String representation of schema """<line_sep><return>str(self.columns_)<block_end><def_stmt>record_size self<block_start>""" Get record size in bytes Returns: Record size in bytes """<line_sep><return>self.record_size_<block_end><def_stmt>columns self<block_start>""" Get list of columns Returns: List of columns """<line_sep><return>self.columns_<block_end><def_stmt>apply self data<block_start>""" Adds data to the schema. Args: data: The data to add. Returns: The record. """<line_sep><return>Record(data self)<block_end><def_stmt>pack self rec<block_start>""" Pack data into a record. Args: rec: The record to pack Returns: Packed record """<line_sep>packed=""<if_stmt>len(rec)<eq>len(self.columns_)<block_start>off=1<line_sep>packed<augadd>struct.pack('Q' rec[0])<block_end><elif_stmt>len(rec)<eq>len(self.columns_)-1<block_start>off=0<line_sep>packed<augadd>struct.pack('Q' now_ns())<block_end><else_stmt><block_start><raise>ValueError("Record does not conform to schema: incorrect number of fields")<block_end><for_stmt>f,c zip(rec[off:] self.columns_[1:])<block_start>packed<augadd>c.data_type_.pack(f)<block_end><return>packed<block_end><block_end><class_stmt>Column<block_start>""" Container of values for a specific type in the schema. """<def_stmt>__init__ self idx offset data_type name min_value max_value<block_start>""" Initializes a column in the schema. Args: idx: The index of the column. offset: The offset of the column. data_type: The data type of values in the column. name: The name of the column. min_value: The minimum value of the column. max_value: The maximum value of the column. """<line_sep>self.idx_=idx<line_sep>self.offset_=offset<line_sep>self.data_type_=data_type<line_sep>self.name_=name.upper()<line_sep>self.value=min_value<line_sep>self.min_value_=self.value<line_sep>self.max_value=max_value<block_end><def_stmt>__str__ self<block_start>""" Convert to string Returns: String representation of the column """<line_sep><return>'{} : {}'.format(self.name_ self.data_type_)<block_end><def_stmt>apply self data<block_start>""" Adds data to the column. Args: data: The data to add. Returns: A field containing the data. """<line_sep><return>Field(self.idx_ self.data_type_ data[self.offset_:self.offset_+self.data_type_.size_])<block_end><block_end><class_stmt>Record<block_start>""" A collection of values containing different types. """<def_stmt>__init__ self data schema<block_start>""" Initializes a record to the specified values. Args: data: The data the record should hold. schema: The schema for the record. """<line_sep>self.data_=data<line_sep>self.fields_=[c.apply(self.data_)<for>c schema.columns()]<block_end><def_stmt>__str__ self<block_start>""" Converts to string Returns: String representation of record """<line_sep><return>str([str(x.unpack())<for>x self.fields_])<block_end><def_stmt>__getitem__ self idx<block_start>""" Get element at specified index Args: idx: Index into record Returns: Element at specified index """<line_sep><return>self.fields_[idx].unpack()<block_end><block_end><class_stmt>Field<block_start>""" Contains data stored as part of a record. """<def_stmt>__init__ self idx data_type data<block_start>""" Initializes the field to the data passed in. Args: idx: The index of the field. data_type: The data type the value of the field contains. data: The data that the field contains. """<line_sep>self.idx_=idx<line_sep>self.data_type_=data_type<line_sep>self.data_=data<block_end><def_stmt>unpack self<block_start>""" Unpacks the field to get the data. Returns: The data in the field. """<line_sep>tid=self.data_type_.type_id_<if_stmt>tid<eq>TypeID.STRING<block_start>format_code=str(self.data_type_.size_)+data_types.FORMAT_CODES[tid]<block_end><else_stmt><block_start>format_code=data_types.FORMAT_CODES[tid]<block_end><return>struct.unpack(format_code self.data_)[0]<block_end><block_end><class_stmt>SchemaBuilder<block_start>""" Builder of a schema for the atomic multilog. """<def_stmt>__init__ self<block_start>""" Initializes a default schema builder. """<line_sep>self.user_provided_ts_=<false><line_sep>self.offset_=0<line_sep>self.columns_=[]<line_sep>timestamp_col=Column(0 0 data_types.ULONG_TYPE "TIMESTAMP" <none> <none>)<line_sep>self.columns_.append(timestamp_col)<line_sep>self.offset_<augadd>data_types.ULONG_TYPE.size_<block_end><def_stmt>add_column self data_type name min_value=<none> max_value=<none><block_start>""" Adds a column to the schema builder. Args: data_type: The data type of the column. name: The name of the column. min_value: The minimum value of the column. max_value: The maximum value of the column. """<if_stmt>name.upper()<eq>"TIMESTAMP"<block_start>self.user_provided_ts_=<true><if_stmt>data_type<ne>data_types.ULONG_TYPE<block_start><raise>ValueError("TIMESTAMP must be of ULONG_TYPE")<block_end><return>self<block_end>col=Column(len(self.columns_) self.offset_ data_type name min_value max_value)<line_sep>self.columns_.append(col)<line_sep>self.offset_<augadd>data_type.size_<line_sep><return>self<block_end><def_stmt>build self<block_start>""" Builds a schema by returning the list of columns. Returns: A list of columns that make up the schema. """<line_sep><return>self.columns_<block_end><block_end><def_stmt>make_schema s<block_start>"""Converts a JSON-like string representation of the schema to our internal representation of the schema. Args: s: A JSON-like schema string Returns: Our internal representation of the schema. """<def_stmt>ordered_load stream<block_start><class_stmt>OrderedLoader(yaml.Loader)<block_start><pass><block_end><def_stmt>construct_mapping loader node<block_start>loader.flatten_mapping(node)<line_sep><return>OrderedDict(loader.construct_pairs(node))<block_end>OrderedLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG construct_mapping)<line_sep><return>yaml.load(stream OrderedLoader)<block_end>s_parsed=ordered_load(s)<line_sep>sb=SchemaBuilder()<for_stmt>k s_parsed<block_start>sb.add_column(data_types.make_type(s_parsed[k]) k)<block_end><return>Schema(sb.build())<block_end>
<import_stmt>torch.nn<as>nn<import_from_stmt>functools partial<import_from_stmt>experiments.util.arch_blocks *<class_stmt>network(ResNet)<block_start><def_stmt>__init__ self n_input n_output args<block_start>features=[[[32]] [[32]<times>2]<times>3 [[64]<times>2]<times>4 [[128]<times>2]<times>6 [[256]<times>2]<times>3]<line_sep>common_params={'downsample_by_pooling':args.downsample_by_pooling 'conv_dropout_p':args.p_drop_conv }<line_sep><global>OuterBlock<line_sep>OuterBlock=partial(OuterBlock res_block=partial(ResBlock **common_params))<line_sep>super().__init__(OuterBlock(n_input features[0] size=7) OuterBlock(features[0][-1][-1] features[1] size=args.kernel_size stride=1) OuterBlock(features[1][-1][-1] features[2] size=args.kernel_size stride=2) OuterBlock(features[2][-1][-1] features[3] size=args.kernel_size stride=2) OuterBlock(features[3][-1][-1] features[4] size=args.kernel_size stride=2) AvgSpacial() nn.Dropout(p=args.p_drop_fully inplace=<true>)<if>args.p_drop_fully<is><not><none><else><none> nn.Linear(features[4][-1][-1] n_output))<block_end><block_end>
<import_from_stmt>abc ABC abstractmethod<class_stmt>Base(ABC)<block_start>@abstractmethod<def_stmt>info self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>create self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>delete self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>start self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>stop self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>restart self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>update self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>move self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>clone self<block_start><raise>NotImplementedError()<block_end>@abstractmethod<def_stmt>snapshot self<block_start><raise>NotImplementedError()<block_end><block_end>
<import_stmt>tensorflow<as>tf<import_stmt>numpy<as>np<line_sep>REG_VARS='reg_vars'<def_stmt>linear X dout name bias=<true><block_start><with_stmt>tf.variable_scope(name)<block_start>dX=int(X.get_shape()[-1])<line_sep>W=tf.get_variable('W' shape=(dX dout))<line_sep>tf.add_to_collection(REG_VARS W)<if_stmt>bias<block_start>b=tf.get_variable('b' initializer=tf.constant(np.zeros(dout).astype(np.float32)))<block_end><else_stmt><block_start>b=0<block_end><block_end><return>tf.matmul(X W)+b<block_end><def_stmt>discounted_reduce_sum X discount axis=-1<block_start><if_stmt>discount<ne>1.0<block_start>disc=tf.cumprod(discount<times>tf.ones_like(X) axis=axis)<block_end><else_stmt><block_start>disc=1.0<block_end><return>tf.reduce_sum(X<times>disc axis=axis)<block_end><def_stmt>assert_shape tens shape<block_start><assert_stmt>tens.get_shape().is_compatible_with(shape)<block_end><def_stmt>relu_layer X dout name<block_start><return>tf.nn.relu(linear(X dout name))<block_end><def_stmt>softplus_layer X dout name<block_start><return>tf.nn.softplus(linear(X dout name))<block_end><def_stmt>tanh_layer X dout name<block_start><return>tf.nn.tanh(linear(X dout name))<block_end><def_stmt>get_session_config <block_start>session_config=tf.ConfigProto()<line_sep>session_config.gpu_options.allow_growth=<true><line_sep>#session_config.gpu_options.per_process_gpu_memory_fraction = 0.2 <return>session_config<block_end><def_stmt>load_prior_params pkl_fname<block_start><import_stmt>joblib<with_stmt>tf.Session(config=get_session_config())<block_start>params=joblib.load(pkl_fname)<block_end>tf.reset_default_graph()<line_sep>#joblib.dump(params, file_name, compress=3) params=params['irl_params']<line_sep>#print(params) <assert_stmt>params<is><not><none><line_sep><return>params<block_end>
<import_stmt>json<import_stmt>os<import_stmt>random<import_stmt>dash<import_from_stmt>dash.dependencies Input Output State<import_stmt>dash_core_components<as>dcc<import_stmt>dash_html_components<as>html<import_stmt>dash_cytoscape<as>cyto<line_sep>asset_path=os.path.join(os.path.dirname(os.path.abspath(__file__)) '..' 'assets')<line_sep>app=dash.Dash(__name__ assets_folder=asset_path)<line_sep>server=app.server<line_sep>random.seed(2019)<line_sep>nodes=[{'data':{'id':str(i) 'label':'Node {}'.format(i)}}<for>i range(1 21)]<line_sep>edges=[{'data':{'source':str(random.randint(1 20)) 'target':str(random.randint(1 20))}}<for>_ range(30)]<line_sep>default_elements=nodes+edges<line_sep>styles={'json-output':{'overflow-y':'scroll' 'height':'calc(50% - 25px)' 'border':'thin lightgrey solid'} 'tab':{'height':'calc(98vh - 115px)'}}<line_sep>app.layout=html.Div([html.Div(className='eight columns' children=[cyto.Cytoscape(id='cytoscape' elements=default_elements layout={'name':'grid'} style={'height':'95vh' 'width':'100%'})]) html.Div(className='four columns' children=[dcc.Tabs(id='tabs' children=[dcc.Tab(label='Actions' children=[html.Button("Remove Selected Node" id='remove-button')]) dcc.Tab(label='Tap Data' children=[html.Div(style=styles['tab'] children=[html.P('Node Data JSON:') html.Pre(id='tap-node-data-json-output' style=styles['json-output']) html.P('Edge Data JSON:') html.Pre(id='tap-edge-data-json-output' style=styles['json-output'])])]) dcc.Tab(label='Selected Data' children=[html.Div(style=styles['tab'] children=[html.P('Node Data JSON:') html.Pre(id='selected-node-data-json-output' style=styles['json-output']) html.P('Edge Data JSON:') html.Pre(id='selected-edge-data-json-output' style=styles['json-output'])])])]) ])])<line_sep>@app.callback(Output('cytoscape' 'elements') [Input('remove-button' 'n_clicks')] [State('cytoscape' 'elements') State('cytoscape' 'selectedNodeData')])<def_stmt>remove_selected_nodes _ elements data<block_start><if_stmt>elements<and>data<block_start>ids_to_remove={ele_data['id']<for>ele_data data}<line_sep>print("Before:" elements)<line_sep>new_elements=[ele<for>ele elements<if>ele['data']['id']<not><in>ids_to_remove]<line_sep>print("After:" new_elements)<line_sep><return>new_elements<block_end><return>elements<block_end>@app.callback(Output('tap-node-data-json-output' 'children') [Input('cytoscape' 'tapNodeData')])<def_stmt>displayTapNodeData data<block_start><return>json.dumps(data indent=2)<block_end>@app.callback(Output('tap-edge-data-json-output' 'children') [Input('cytoscape' 'tapEdgeData')])<def_stmt>displayTapEdgeData data<block_start><return>json.dumps(data indent=2)<block_end>@app.callback(Output('selected-node-data-json-output' 'children') [Input('cytoscape' 'selectedNodeData')])<def_stmt>displaySelectedNodeData data<block_start><return>json.dumps(data indent=2)<block_end>@app.callback(Output('selected-edge-data-json-output' 'children') [Input('cytoscape' 'selectedEdgeData')])<def_stmt>displaySelectedEdgeData data<block_start><return>json.dumps(data indent=2)<block_end><if_stmt>__name__<eq>'__main__'<block_start>app.run_server(debug=<true>)<block_end>
<import_from_stmt>sqlalchemy Column func<import_from_stmt>clickhouse_sqlalchemy types Table<import_from_stmt>tests.testcase CompilationTestCase<class_stmt>CountTestCaseBase(CompilationTestCase)<block_start>table=Table('t1' CompilationTestCase.metadata() Column('x' types.Int32 primary_key=<true>))<def_stmt>test_count self<block_start>self.assertEqual(self.compile(self.session.query(func.count(self.table.c.x))) 'SELECT count(t1.x) AS count_1 FROM t1')<block_end><def_stmt>test_count_distinct self<block_start>query=self.session.query(func.count(func.distinct(self.table.c.x)))<line_sep>self.assertEqual(self.compile(query) 'SELECT count(distinct(t1.x)) AS count_1 FROM t1')<block_end><def_stmt>test_count_no_column_specified self<block_start>query=self.session.query(func.count()).select_from(self.table)<line_sep>self.assertEqual(self.compile(query) 'SELECT count(*) AS count_1 FROM t1')<block_end><block_end>
<import_from_future_stmt> absolute_import<import_stmt>mxnet<as>mx<import_stmt>mxnet.symbol<as>sym<import_stmt>json<import_from_stmt>analysis.layers *<import_stmt>re<import_stmt>ctypes<import_from_stmt>mxnet.ndarray NDArray<import_stmt>mxnet.ndarray<as>nd<import_from_stmt>mxnet.base NDArrayHandle py_str<line_sep>blob_dict=[]<line_sep>tracked_layers=[]<def_stmt>tmpnet <block_start>x=sym.Variable('data')<line_sep>y=sym.Convolution(x kernel=(3 3) num_filter=32)<line_sep>y=sym.Activation(y 'relu')<line_sep>y=sym.Convolution(y kernel=(3 3) num_filter=64 stride=(2 2) num_group=2)<line_sep>y=sym.softmax(y)<line_sep><return>y<block_end><def_stmt>analyse data_infos module_json data_name='data'<block_start>datas={}<for_stmt>info data_infos<block_start>datas[info[1]]=info[2]<block_end>nodes=json.loads(module_json)['nodes']<line_sep>input=[]<line_sep>out=<none><for_stmt>node nodes<block_start>name=node['name']<line_sep>bottoms=[str(nodes[i[0]]['name'])<for>i node['inputs']]<for_stmt>i,bottom enumerate(bottoms)<block_start><if_stmt>bottom+'_output'<in>datas<block_start>bottoms[i]=datas[bottom+'_output']<block_end><elif_stmt>bottom+'_0'<in>datas<block_start>bottoms[i]=datas[bottom+'_0']<block_end><elif_stmt>bottom<in>datas<block_start>bottoms[i]=datas[bottom]<block_end><else_stmt><block_start>cur_node=node<while_stmt><true><block_start>bottom=[str(nodes[inp[0]]['name'])<for>inp cur_node['inputs']][0]<if_stmt>bottom+'_output'<in>datas<block_start>bottoms[i]=datas[bottom+'_output']<line_sep><break><block_end><elif_stmt>bottom+'_0'<in>datas<block_start>bottoms[i]=datas[bottom+'_0']<line_sep><break><block_end><elif_stmt>bottom<in>datas<block_start>bottoms[i]=datas[bottom]<line_sep><break><block_end><try_stmt><block_start>bottom_node=nodes[cur_node['inputs'][0][0]]<block_end><except_stmt><block_start><pass><block_end>cur_node=bottom_node<block_end><block_end><block_end><if_stmt>data_name<eq>name<block_start>input.append(Blob(datas[data_name]))<block_end><elif_stmt>node['op']<eq>'Convolution'<block_start>kernel=eval(node['attrs']['kernel'])<line_sep>num_out=eval(node['attrs']['num_filter'])<line_sep>group_size=eval(node['attrs'].get('num_group' '1'))<line_sep>pad=eval(node['attrs'].get('pad' '(0,0)'))<line_sep>stride=eval(node['attrs'].get('stride' '(1,1)'))<line_sep>x=Blob(bottoms[0])<line_sep>out=Conv(x kernel_size=kernel stride=stride pad=pad num_out=num_out group_size=group_size name=name)<line_sep>tracked_layers.append(out)<block_end><elif_stmt>node['op']<eq>'BatchNorm'<block_start>x=Blob(bottoms[0])<line_sep>out=Norm(x 'batch_norm' name=name)<line_sep>tracked_layers.append(out)<block_end><elif_stmt>node['op']<eq>'FullyConnected'<block_start>x=Blob(bottoms[0])<line_sep>num_hidden=eval(node['attrs']['num_hidden'])<line_sep>out=Fc(x num_hidden name=name)<line_sep>tracked_layers.append(out)<block_end><elif_stmt>node['op']<eq>'Activation'<block_start><pass><block_end><elif_stmt>'elemwise'<in>node['op']<block_start><pass><block_end><block_end><block_end><class_stmt>Monitor(object)<block_start><def_stmt>__init__ self interval=1 pattern='.*' sort=<false><block_start><def_stmt>stat x<block_start><return>x.shape<block_end>self.stat_func=stat<line_sep>self.interval=interval<line_sep>self.activated=<false><line_sep>self.queue=[]<line_sep>self.step=0<line_sep>self.exes=[]<line_sep>self.re_prog=re.compile(pattern)<line_sep>self.sort=sort<def_stmt>stat_helper name array<block_start>array=ctypes.cast(array NDArrayHandle)<line_sep>array=NDArray(array writable=<false>)<if_stmt><not>self.activated<or><not>self.re_prog.match(py_str(name))<block_start><return><block_end>self.queue.append((self.step py_str(name) stat(array)))<block_end>self.stat_helper=stat_helper<block_end><def_stmt>install self exe<block_start>exe.set_monitor_callback(self.stat_helper)<line_sep>self.exes.append(exe)<block_end><def_stmt>tic self<block_start><if_stmt>self.step%self.interval<eq>0<block_start><for_stmt>exe self.exes<block_start><for_stmt>array exe.arg_arrays<block_start>array.wait_to_read()<block_end><for_stmt>array exe.aux_arrays<block_start>array.wait_to_read()<block_end><block_end>self.queue=[]<line_sep>self.activated=<true><block_end>self.step<augadd>1<block_end><def_stmt>toc self<block_start><if_stmt><not>self.activated<block_start><return>[]<block_end><for_stmt>exe self.exes<block_start><for_stmt>array exe.arg_arrays<block_start>array.wait_to_read()<block_end><for_stmt>array exe.aux_arrays<block_start>array.wait_to_read()<block_end><block_end><for_stmt>exe self.exes<block_start><for_stmt>name,array zip(exe._symbol.list_arguments() exe.arg_arrays)<block_start>self.queue.append((self.step name self.stat_func(array)))<block_end><for_stmt>name,array zip(exe._symbol.list_auxiliary_states() exe.aux_arrays)# if self.re_prog.match(name): <block_start>self.queue.append((self.step name self.stat_func(array)))<block_end><block_end>self.activated=<false><line_sep>res=[]<if_stmt>self.sort<block_start>self.queue.sort(key=<lambda>x:x[1])<block_end><for_stmt>n,k,v_list self.queue<block_start>res.append((n k v_list))<block_end>self.queue=[]<line_sep><return>res<block_end><def_stmt>toc_print self<block_start><pass><block_end><block_end><def_stmt>profiling_symbol symbol data_shape data_name='data'<block_start>monitor=Monitor()<line_sep>model=mx.mod.Module(symbol)<line_sep>model.bind(data_shapes=[(data_name tuple(data_shape))])<line_sep>model.install_monitor(monitor)<line_sep>model.init_params()<line_sep>monitor.tic()<line_sep>model.forward(mx.io.DataBatch(data=(nd.ones(data_shape) )))<line_sep>data_infos=monitor.toc()<line_sep>module_json=symbol.tojson()<line_sep>analyse(data_infos module_json data_name)<block_end>
<import_stmt>re<import_from_stmt>functools reduce<import_from_stmt>operator or_<import_from_stmt>actstream.models Follow<import_from_stmt>django.contrib.contenttypes.models ContentType<import_from_stmt>django.db.models Q<import_from_stmt>django_filters CharFilter ChoiceFilter FilterSet<import_from_stmt>machina.apps.forum.models Forum<import_from_stmt>machina.apps.forum_conversation.models Topic<import_from_stmt>grandchallenge.core.filters FilterForm<import_from_stmt>grandchallenge.notifications.models Notification<line_sep>BOOLEAN_CHOICES=(("1" "Read") ("0" "Unread") )<class_stmt>NotificationFilter(FilterSet)<block_start>forum=CharFilter(method="search_filter" label="Forum")<line_sep>topic=CharFilter(method="search_filter" label="Forum post subject")<line_sep>read=ChoiceFilter(choices=BOOLEAN_CHOICES label="Status")<class_stmt>Meta<block_start>model=Notification<line_sep>form=FilterForm<line_sep>fields=("forum" "topic" "read")<block_end><def_stmt>search_filter self queryset name value<block_start><if_stmt>name<eq>"forum"<block_start>name_qs=[x.id<for>x Forum.objects.filter(name__icontains=value).all()]<block_end><elif_stmt>name<eq>"topic"<block_start>name_qs=[x.id<for>x Topic.objects.filter(subject__icontains=value).all()]<block_end>search_fields=("action__target_object_id" "action__action_object_object_id" )<line_sep><return>queryset.filter(reduce(or_ [Q(**{f"{f}__in":name_qs})<for>f search_fields] Q() ))<block_end><block_end>FOLLOW_CHOICES=(("forum_forum" "Forums") ("topic_forum_conversation" "Topics") ("readerstudy_reader_studies" "Reader studies") ("archive_archives" "Archives") ("algorithm_algorithms" "Algorithms") ("challenge_challenges" "Challenges") ("externalchallenge_challenges" "External Challenges") ("phase_evaluation" "Challenge Phase") )<class_stmt>FollowFilter(FilterSet)<block_start>forum=CharFilter(method="search_filter" label="Search for a forum")<line_sep>topic=CharFilter(method="search_filter" label="Search for a forum topic")<line_sep>forums_for_user=CharFilter(method="search_forum_topics" label="Show all topic subscriptions for a specific forum" )<line_sep>content_type=ChoiceFilter(choices=FOLLOW_CHOICES method="get_content_type" label="Filter by subscription type" )<class_stmt>Meta<block_start>model=Follow<line_sep>form=FilterForm<line_sep>fields=("forum" "topic" "forums_for_user" "content_type")<block_end><def_stmt>search_filter self queryset name value<block_start>model_name=name<if_stmt>model_name<eq>"forum"<block_start>app_label="forum"<line_sep>model=Forum<line_sep>kwargs={"name__icontains":value}<block_end><elif_stmt>model_name<eq>"topic"<block_start>app_label="forum_conversation"<line_sep>model=Topic<line_sep>kwargs={"subject__icontains":value}<block_end>name_qs=[x.id<for>x model.objects.filter(**kwargs).all()]<line_sep><return>queryset.filter(**{"object_id__in":name_qs} **{"content_type__exact":ContentType.objects.filter(model=model_name app_label=app_label).get()} )<block_end><def_stmt>search_forum_topics self queryset name value<block_start>forums=[x.id<for>x Forum.objects.filter(name__icontains=value).all()]<line_sep>name_qs=[x.id<for>x Topic.objects.filter(forum__id__in=forums).all()]<line_sep><return>queryset.filter(**{"object_id__in":name_qs} **{"content_type__exact":ContentType.objects.filter(model="topic" app_label="forum_conversation").get()} )<block_end><def_stmt>get_content_type self queryset name value<block_start>ct=ContentType.objects.filter(model=re.split(r"_" value 1)[0] app_label=re.split(r"_" value 1)[1] ).get()<line_sep><return>queryset.filter(content_type__exact=ct)<block_end><block_end>
<import_stmt>settings<import_from_stmt>.. handlers<def_stmt>test_send_welcome_email mocker ses_client<block_start>ses_send_email=mocker.patch.object(ses_client 'send_email' autospec=<true>)<line_sep>mocker.patch('emails.sender.get_ses_client' return_value=ses_client)<line_sep>event={'to':'<EMAIL>' 'name':'<NAME>' 'type':'WelcomeEmail'}<line_sep>handlers.send_email(event {})<line_sep>ses_send_email.assert_called_once()<line_sep>kwargs=ses_send_email.call_args.kwargs<assert_stmt>kwargs['Source']<eq>settings.FROM_EMAIL<assert_stmt>kwargs['Destination']['ToAddresses']<eq>[event['to']]<assert_stmt>event['name']<in>kwargs['Message']['Body']['Html']['Data']<block_end>
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 <import_from_stmt>typing Any Dict Optional <import_from_stmt>databuilder.models.graph_node GraphNode<import_from_stmt>databuilder.models.graph_relationship GraphRelationship<import_from_stmt>databuilder.models.graph_serializable NODE_KEY NODE_LABEL RELATION_END_KEY RELATION_END_LABEL RELATION_REVERSE_TYPE RELATION_START_KEY RELATION_START_LABEL RELATION_TYPE <import_from_stmt>databuilder.publisher.neo4j_csv_publisher UNQUOTED_SUFFIX<def_stmt>serialize_node node:Optional[GraphNode]<arrow>Dict[str Any]<block_start><if_stmt>node<is><none><block_start><return>{}<block_end>node_dict={NODE_LABEL:node.label NODE_KEY:node.key}<for_stmt>key,value node.attributes.items()<block_start>key_suffix=_get_neo4j_suffix_value(value)<line_sep>formatted_key=f'{key}{key_suffix}'<line_sep>node_dict[formatted_key]=value<block_end><return>node_dict<block_end><def_stmt>serialize_relationship relationship:Optional[GraphRelationship]<arrow>Dict[str Any]<block_start><if_stmt>relationship<is><none><block_start><return>{}<block_end>relationship_dict={RELATION_START_KEY:relationship.start_key RELATION_START_LABEL:relationship.start_label RELATION_END_KEY:relationship.end_key RELATION_END_LABEL:relationship.end_label RELATION_TYPE:relationship.type RELATION_REVERSE_TYPE:relationship.reverse_type }<for_stmt>key,value relationship.attributes.items()<block_start>key_suffix=_get_neo4j_suffix_value(value)<line_sep>formatted_key=f'{key}{key_suffix}'<line_sep>relationship_dict[formatted_key]=value<block_end><return>relationship_dict<block_end><def_stmt>_get_neo4j_suffix_value value:Any<arrow>str<block_start><if_stmt>isinstance(value int)<block_start><return>UNQUOTED_SUFFIX<block_end><if_stmt>isinstance(value bool)<block_start><return>UNQUOTED_SUFFIX<block_end><return>''<block_end>
"""A sheep."""<import_stmt>animal<class_stmt>Sheep(animal.Animal)<block_start><def_stmt>__init__ self<block_start>self.kind='sheep'<block_end><block_end>
# vim:fileencoding=utf-8:noet <import_from_future_stmt> unicode_literals division absolute_import print_function <import_stmt>os<import_from_stmt>powerline.bindings.vim vim_getbufoption buffer_name<def_stmt>commandt matcher_info<block_start>name=buffer_name(matcher_info)<line_sep><return>(vim_getbufoption(matcher_info 'filetype')<eq>'command-t'<or>(name<and>os.path.basename(name)<eq>b'GoToFile'))<block_end>
r""" Basic analysis of a MD simulation ================================= In this example, we will analyze a trajectory of a *Gromacs* MD simulation: The trajectory contains simulation data of lysozyme over the course of 1 ns. The data is the result of the famous *Gromacs* '`Lysozyme in Water <http://www.mdtutorials.com/gmx/lysozyme/index.html>`_' tutorial. The trajectory file can be downloaded :download:`here </examples/download/lysozyme_md.xtc>` and the template PDB can be downloaded :download:`here </examples/download/lysozyme_md.pdb>`. We begin by loading the template PDB file as :class:`AtomArray`, sanitizing it and using it to load the trajectory as :class:`AtomArrayStack`. """<line_sep># Code source: <NAME> # License: BSD 3 clause <import_stmt>biotite<import_stmt>biotite.structure<as>struc<import_stmt>biotite.structure.io<as>strucio<import_stmt>biotite.structure.io.xtc<as>xtc<import_stmt>numpy<as>np<import_stmt>matplotlib.pyplot<as>plt<line_sep># Put here the path of the downloaded files templ_file_path="../../download/lysozyme_md.pdb"<line_sep>traj_file_path="../../download/lysozyme_md.xtc"<line_sep># Gromacs does not set the element symbol in its PDB files, # but Biotite guesses the element names from the atom names, # emitting a warning template=strucio.load_structure(templ_file_path)<line_sep># The structure still has water and ions, that are not needed for our # calculations, we are only interested in the protein itself # These are removed for the sake of computational speed using a boolean # mask protein_mask=struc.filter_amino_acids(template)<line_sep>template=template[protein_mask]<line_sep># We could have loaded the trajectory also with # 'strucio.load_structure()', but in this case we only want to load # those coordinates that belong to the already selected atoms of the # template structure. # Hence, we use the 'XTCFile' class directly to load the trajectory # This gives us the additional option that allows us to select the # coordinates belonging to the amino acids. xtc_file=xtc.XTCFile.read(traj_file_path atom_i=np.where(protein_mask)[0])<line_sep>trajectory=xtc_file.get_structure(template)<line_sep># Get simulation time for plotting purposes time=xtc_file.get_time()<line_sep>######################################################################## # Since the MD simulation used periodic boundaries, the protein might be # segmented over the box boundary. # For further analysis we need to reassemble the protein chain into a # whole molecule, without periodic boundaries. # in *Gromacs* we could have used ``gmx trjconv`` for this, but this # problem can be handled in *Biotite*, too. trajectory=struc.remove_pbc(trajectory)<line_sep>######################################################################## # Now our trajectory is ready for some analysis! # At first we want to see if the simulation converged. # For this purpose we take the RMSD of a frame compared to the initial # model as measure. In order to calculate the RMSD we must # superimpose all models onto a reference, in this case we also choose # the initial structure. trajectory,transform=struc.superimpose(trajectory[0] trajectory)<line_sep>rmsd=struc.rmsd(trajectory[0] trajectory)<line_sep>figure=plt.figure(figsize=(6 3))<line_sep>ax=figure.add_subplot(111)<line_sep>ax.plot(time rmsd color=biotite.colors["dimorange"])<line_sep>ax.set_xlim(time[0] time[-1])<line_sep>ax.set_ylim(0 2)<line_sep>ax.set_xlabel("Time (ps)")<line_sep>ax.set_ylabel("RMSD (Å)")<line_sep>figure.tight_layout()<line_sep>######################################################################## # As we can see the simulation seems to converge already early in the # simulation. # After a about 200 ps the RMSD stays in a range of approx. 1 - 2 Å. # # In order to futher evaluate the unfolding of our enzyme in the # course of simulation, we calculate and plot the radius of gyration # (a measure for the protein radius). radius=struc.gyration_radius(trajectory)<line_sep>figure=plt.figure(figsize=(6 3))<line_sep>ax=figure.add_subplot(111)<line_sep>ax.plot(time radius color=biotite.colors["dimorange"])<line_sep>ax.set_xlim(time[0] time[-1])<line_sep>ax.set_ylim(14.0 14.5)<line_sep>ax.set_xlabel("Time (ps)")<line_sep>ax.set_ylabel("Radius of gyration (Å)")<line_sep>figure.tight_layout()<line_sep>######################################################################## # From this perspective, the protein seems really stable. # The radius does merely fluctuate in a range of approximately 0.3 Å # during the entire simulation. # # Let's have a look at single amino acids: # Which residues fluctuate most? # For answering this question we calculate the RMSF # (Root mean square fluctuation). # It is similar to the RMSD, but instead of averaging over the atoms # and looking at each time step, we average over the time and look at # each residue. # Usually the average model is taken as reference # (compared to the starting model for RMSD). # # Since side chain atoms fluctuate quite a lot, they are not suitable # for evaluation of the residue flexibility. Therefore, we consider only # CA atoms. # In all models, mask the CA atoms ca_trajectory=trajectory[: trajectory.atom_name<eq>"CA"]<line_sep>rmsf=struc.rmsf(struc.average(ca_trajectory) ca_trajectory)<line_sep>figure=plt.figure(figsize=(6 3))<line_sep>ax=figure.add_subplot(111)<line_sep>res_count=struc.get_residue_count(trajectory)<line_sep>ax.plot(np.arange(1 res_count+1) rmsf color=biotite.colors["dimorange"])<line_sep>ax.set_xlim(1 res_count)<line_sep>ax.set_ylim(0 1.5)<line_sep>ax.set_xlabel("Residue")<line_sep>ax.set_ylabel("RMSF (Å)")<line_sep>figure.tight_layout()<line_sep>plt.show()<line_sep>
<import_from_stmt>itertools cycle<import_from_stmt>unittest.mock patch<import_from_stmt>django.utils timezone<as>djangotime<import_from_stmt>model_bakery baker seq<import_from_stmt>tacticalrmm.test TacticalTestCase<import_from_stmt>logs.models PendingAction<class_stmt>TestAuditViews(TacticalTestCase)<block_start><def_stmt>setUp self<block_start>self.authenticate()<line_sep>self.setup_coresettings()<block_end><def_stmt>create_audit_records self# create clients for client filter <block_start>site=baker.make("clients.Site")<line_sep>agent1=baker.make_recipe("agents.agent" site=site hostname="AgentHostname1")<line_sep>agent2=baker.make_recipe("agents.agent" hostname="AgentHostname2")<line_sep>agent0=baker.make_recipe("agents.agent" hostname="AgentHostname")<line_sep># user jim agent logs baker.make_recipe("logs.agent_logs" username="jim" agent="AgentHostname1" agent_id=agent1.id _quantity=15 )<line_sep>baker.make_recipe("logs.agent_logs" username="jim" agent="AgentHostname2" agent_id=agent2.id _quantity=8 )<line_sep># user james agent logs baker.make_recipe("logs.agent_logs" username="james" agent="AgentHostname1" agent_id=agent1.id _quantity=7 )<line_sep>baker.make_recipe("logs.agent_logs" username="james" agent="AgentHostname2" agent_id=agent2.id _quantity=10 )<line_sep># generate agent logs with random usernames baker.make_recipe("logs.agent_logs" agent=seq("AgentHostname") agent_id=seq(agent1.id) _quantity=5 )<line_sep># generate random object data baker.make_recipe("logs.object_logs" username="james" _quantity=17 )<line_sep># generate login data for james baker.make_recipe("logs.login_logs" username="james" _quantity=11 )<line_sep># generate login data for jim baker.make_recipe("logs.login_logs" username="jim" _quantity=13 )<line_sep><return>{"site":site "agents":[agent0 agent1 agent2]}<block_end><def_stmt>test_get_audit_logs self<block_start>url="/logs/auditlogs/"<line_sep># create data data=self.create_audit_records()<line_sep># test data and result counts data=[{"filter":{"timeFilter":30} "count":86} {"filter":{"timeFilter":45 "agentFilter":[data["agents"][2].id] } "count":19 } {"filter":{"userFilter":["jim"] "agentFilter":[data["agents"][1].id] } "count":15 } {"filter":{"timeFilter":180 "userFilter":["james"] "agentFilter":[data["agents"][1].id] } "count":7 } {"filter":{} "count":86} {"filter":{"agentFilter":[500]} "count":0} {"filter":{"timeFilter":35 "userFilter":["james" "jim"] "agentFilter":[data["agents"][1].id data["agents"][2].id ] } "count":40 } {"filter":{"timeFilter":35 "userFilter":["james" "jim"]} "count":81} {"filter":{"objectFilter":["user"]} "count":26} {"filter":{"actionFilter":["login"]} "count":12} {"filter":{"clientFilter":[data["site"].client.id]} "count":23 } ]<line_sep>pagination={"rowsPerPage":25 "page":1 "sortBy":"entry_time" "descending":<true> }<for_stmt>req data<block_start>resp=self.client.patch(url {**req["filter"] "pagination":pagination} format="json")<line_sep>self.assertEqual(resp.status_code 200)<line_sep>self.assertEqual(len(resp.data["audit_logs"]) # type:ignore pagination["rowsPerPage"]<if>req["count"]<g>pagination["rowsPerPage"]<else>req["count"] )<line_sep>self.assertEqual(resp.data["total"] req["count"])<block_end># type:ignore self.check_not_authenticated("patch" url)<block_end><def_stmt>test_get_pending_actions self<block_start>url="/logs/pendingactions/"<line_sep>agent1=baker.make_recipe("agents.online_agent")<line_sep>agent2=baker.make_recipe("agents.online_agent")<line_sep>baker.make("logs.PendingAction" agent=agent1 action_type="chocoinstall" details={"name":"googlechrome" "output":<none> "installed":<false>} _quantity=12 )<line_sep>baker.make("logs.PendingAction" agent=agent2 action_type="chocoinstall" status="completed" details={"name":"adobereader" "output":<none> "installed":<false>} _quantity=14 )<line_sep>data={"showCompleted":<false>}<line_sep>r=self.client.patch(url data format="json")<line_sep>self.assertEqual(r.status_code 200)<line_sep>self.assertEqual(len(r.data["actions"]) 12)# type: ignore self.assertEqual(r.data["completed_count"] 14)# type: ignore self.assertEqual(r.data["total"] 26)# type: ignore PendingAction.objects.filter(action_type="chocoinstall").update(status="completed")<line_sep>data={"showCompleted":<true>}<line_sep>r=self.client.patch(url data format="json")<line_sep>self.assertEqual(r.status_code 200)<line_sep>self.assertEqual(len(r.data["actions"]) 26)# type: ignore self.assertEqual(r.data["completed_count"] 26)# type: ignore self.assertEqual(r.data["total"] 26)# type: ignore data={"showCompleted":<true> "agentPK":agent1.pk}<line_sep>r=self.client.patch(url data format="json")<line_sep>self.assertEqual(r.status_code 200)<line_sep>self.assertEqual(len(r.data["actions"]) 12)# type: ignore self.assertEqual(r.data["completed_count"] 12)# type: ignore self.assertEqual(r.data["total"] 12)# type: ignore self.check_not_authenticated("patch" url)<block_end>@patch("agents.models.Agent.nats_cmd")<def_stmt>test_cancel_pending_action self nats_cmd<block_start>nats_cmd.return_value="ok"<line_sep>url="/logs/pendingactions/"<line_sep>agent=baker.make_recipe("agents.online_agent")<line_sep>action=baker.make("logs.PendingAction" agent=agent action_type="schedreboot" details={"time":"2021-01-13 18:20:00" "taskname":"TacticalRMM_SchedReboot_wYzCCDVXlc" } )<line_sep>data={"pk":action.pk}# type: ignore r=self.client.delete(url data format="json")<line_sep>self.assertEqual(r.status_code 200)<line_sep>nats_data={"func":"delschedtask" "schedtaskpayload":{"name":"TacticalRMM_SchedReboot_wYzCCDVXlc"} }<line_sep>nats_cmd.assert_called_with(nats_data timeout=10)<line_sep># try request again and it should 404 since pending action doesn't exist r=self.client.delete(url data format="json")<line_sep>self.assertEqual(r.status_code 404)<line_sep>nats_cmd.reset_mock()<line_sep>action2=baker.make("logs.PendingAction" agent=agent action_type="schedreboot" details={"time":"2021-01-13 18:20:00" "taskname":"TacticalRMM_SchedReboot_wYzCCDVXlc" } )<line_sep>data={"pk":action2.pk}# type: ignore nats_cmd.return_value="error deleting sched task"<line_sep>r=self.client.delete(url data format="json")<line_sep>self.assertEqual(r.status_code 400)<line_sep>self.assertEqual(r.data "error deleting sched task")# type: ignore self.check_not_authenticated("delete" url)<block_end><def_stmt>test_get_debug_log self<block_start>url="/logs/debuglog/"<line_sep># create data agent=baker.make_recipe("agents.agent")<line_sep>baker.make("logs.DebugLog" log_level=cycle(["error" "info" "warning" "critical"]) log_type="agent_issues" agent=agent _quantity=4 )<line_sep>logs=baker.make("logs.DebugLog" log_type="system_issues" log_level=cycle(["error" "info" "warning" "critical"]) _quantity=15 )<line_sep># test agent filter data={"agentFilter":agent.id}<line_sep>resp=self.client.patch(url data format="json")<line_sep>self.assertEqual(resp.status_code 200)<line_sep>self.assertEqual(len(resp.data) 4)# type: ignore # test log type filter and agent data={"agentFilter":agent.id "logLevelFilter":"warning"}<line_sep>resp=self.client.patch(url data format="json")<line_sep>self.assertEqual(resp.status_code 200)<line_sep>self.assertEqual(len(resp.data) 1)# type: ignore # test time filter with other data={"logTypeFilter":"system_issues" "logLevelFilter":"error"}<line_sep>resp=self.client.patch(url data format="json")<line_sep>self.assertEqual(resp.status_code 200)<line_sep>self.assertEqual(len(resp.data) 4)# type: ignore self.check_not_authenticated("patch" url)<block_end><block_end><class_stmt>TestLogTasks(TacticalTestCase)<block_start><def_stmt>test_prune_debug_log self<block_start><import_from_stmt>.models DebugLog<import_from_stmt>.tasks prune_debug_log<line_sep># setup data debug_log=baker.make("logs.DebugLog" _quantity=50 )<line_sep>days=0<for_stmt>item debug_log# type:ignore <block_start>item.entry_time=djangotime.now()-djangotime.timedelta(days=days)<line_sep>item.save()<line_sep>days=days+5<block_end># delete AgentHistory older than 30 days prune_debug_log(30)<line_sep>self.assertEqual(DebugLog.objects.count() 6)<block_end><def_stmt>test_prune_audit_log self<block_start><import_from_stmt>.models AuditLog<import_from_stmt>.tasks prune_audit_log<line_sep># setup data audit_log=baker.make("logs.AuditLog" _quantity=50 )<line_sep>days=0<for_stmt>item audit_log# type:ignore <block_start>item.entry_time=djangotime.now()-djangotime.timedelta(days=days)<line_sep>item.save()<line_sep>days=days+5<block_end># delete AgentHistory older than 30 days prune_audit_log(30)<line_sep>self.assertEqual(AuditLog.objects.count() 6)<block_end><block_end>
""" scaffoldgraph.vis.base """<import_stmt>networkx<as>nx<import_from_stmt>abc ABC<import_from_stmt>scaffoldgraph.core ScaffoldGraph<import_from_stmt>scaffoldgraph.utils canonize_smiles<import_from_stmt>.utils remove_node_mol_images<class_stmt>Visualizer(ABC)<block_start>"""Base class for ScaffoldGraph visualizers. A Visualizer contains functions for creating visualizations of ScaffoldGraphs. See Also -------- scaffoldgraph.vis.notebook.cytoscape.CytoscapeVisualizer """<def_stmt>__init__ self graph requires_tree=<false> refresh_images=<false><block_start>"""Initialize the visualizer. Parameters ---------- graph : ScaffoldGraph ScaffoldGraph to visualize requires_tree : bool, optional Whether the visualizer requires a tree structure to create a visualization. refresh_images: bool, optional If True remove all embeded images from the input graph and regenerate when required. The default is False. """<line_sep>self._requires_tree=requires_tree<line_sep>self._refresh=refresh_images<line_sep>self._graph=self._validate_graph(graph)<block_end>@property<def_stmt>graph self<block_start>"""ScaffoldGraph: return the graph associated with the visualizer."""<line_sep><return>self._graph<block_end>@graph.setter<def_stmt>graph self graph<block_start>self._graph=self._validate_graph(graph)<block_end><def_stmt>_validate_graph self graph<block_start>"""Private: Validate a graph is suitable for visualizer."""<if_stmt><not>issubclass(type(graph) ScaffoldGraph)<block_start><raise>ValueError(f'{graph} must be a subclass of ScaffoldGraph')<block_end><if_stmt>self._requires_tree<block_start><if_stmt><not>nx.is_tree(graph)<or>nx.is_forest(graph)<block_start>msg='{} requires a tree/forest structured graph'<line_sep>msg.format(self.__class__.__name__)<line_sep><raise>ValueError(msg)<block_end><block_end><if_stmt>self._refresh<is><true><block_start>remove_node_mol_images(graph)<block_end><return>graph<block_end><def_stmt>_subgraph_from_mol self molecule<block_start>"""Private: Select a subgraph starting at a molecule node. Parameters ---------- molecule : str Molecule node identifier. Returns ------- subgraph : ScaffoldGraph A subgraph starting at `molecule`. """<line_sep>G=self._graph<if_stmt><not>G.molecule_in_graph(molecule)<block_start><raise>ValueError(f'molecule: {molecule} not in graph {G}')<block_end>scaffolds=G.get_scaffolds_for_molecule(molecule)<line_sep>subgraph=G.subgraph([molecule]+scaffolds)<line_sep><return>subgraph<block_end><def_stmt>_subgraph_from_scf self scaffold traversal<block_start>"""Private: Select a subgraph starting at a scaffold node. Parameters ---------- scaffold : str Scaffold node identifier. traversal : str {'parent', 'child', 'bidirectional'} The direction of traversal to create the subgraph. If 'bidirectional' both directions are considered. Returns ------- subgraph : ScaffoldGraph A subgraph starting at `scaffold`. """<line_sep>G=self._graph<line_sep>query=canonize_smiles(scaffold)<if_stmt><not>G.scaffold_in_graph(query)<block_start><raise>ValueError(f'scaffold: {query} not in graph {G}')<block_end><if_stmt>traversal<eq>'parent'<block_start>nodes=G.get_parent_scaffolds(query)<block_end><elif_stmt>traversal<eq>'child'<block_start>nodes=list(nx.descendants(G query))<block_end><elif_stmt>traversal<eq>'bidirectional'<block_start>nodes=G.get_parent_scaffolds(query)<line_sep>nodes<augadd>list(nx.descendants(G query))<block_end><else_stmt><block_start>msg='traversal must be one of {child, parent, bidirectional}'<line_sep><raise>ValueError(msg)<block_end>subgraph=G.subgraph([query]+nodes)<line_sep><return>subgraph<block_end><def_stmt>__repr__ self<block_start><return>'<{_cls} at {address}>'.format(_cls=self.__class__.__name__ address=hex(id(self)))<block_end><block_end>
<import_stmt>timeit<class_stmt>TimingsEntry(object)<block_start>"""A log of the runtime for an operation. """<def_stmt>__init__ self op<block_start>self.op=op<line_sep>self.evals=0<line_sep>self.total_time=0<line_sep>self.lastticstamp=<none><block_end>@property<def_stmt>avg_time self<block_start><if_stmt>self.evals<eq>0<block_start><return>0<block_end><else_stmt><block_start><return>self.total_time/self.evals<block_end><block_end><def_stmt>record_timing self elapsed<block_start>"""Updates the log with the new time. """<line_sep>self.evals<augadd>1<line_sep>self.total_time<augadd>elapsed<block_end><def_stmt>tic self<block_start>""" Default timer Example: t = tic() ... code elapsed = toc(t) print( '{0}: {1:.4f}ms'.format(message, elapsed) ) """<line_sep>t=timeit.default_timer()<line_sep>self.lastticstamp=t<line_sep><return>t<block_end><def_stmt>toc self<block_start>""" See tic f """<line_sep># Last tic <if_stmt>self.lastticstamp<is><none><block_start><raise>Exception('Error: Call to toc did never call tic before.')<block_end><else_stmt><block_start>t=self.lastticstamp<line_sep># Measure time in ms elapsed=(timeit.default_timer()-t)<times>1000.0# in ms # Update recrod. self.record_timing(elapsed)<line_sep>self.lastticstamp=<none><line_sep><return>elapsed<block_end><block_end><def_stmt>__str__ self<block_start><return>"op = %s, evals = %s, total_time (ms) = %s, avg_time (ms) = %s"%(self.op self.evals self.total_time self.avg_time)<block_end><block_end><class_stmt>TimingsLog(object)<block_start>"""A log of the runtime for a set of operations. """<def_stmt>__init__ self ops<block_start>self.ops=ops<line_sep>self.data={}<for_stmt>op self.ops<block_start>self.data[op]=TimingsEntry(op)<block_end><block_end><def_stmt>__getitem__ self item<block_start><return>self.data[item]<block_end><def_stmt>__str__ self<block_start>logs=[]<for_stmt>op self.ops<block_start><if_stmt>self[op].evals<g>0<block_start>logs<augadd>[str(self.data[op])]<block_end><block_end><return>'\n'.join(logs)<block_end><block_end>
# Copyright (c) 2019 PaddlePaddle 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. """ data preprocess for pathquery datasets """<import_stmt>os<import_stmt>sys<import_stmt>time<import_stmt>logging<import_stmt>argparse<import_from_stmt>kbc_data_preprocess write_vocab<import_from_stmt>kbc_data_preprocess load_vocab<import_from_stmt>kbc_data_preprocess generate_mask_type<import_from_stmt>collections defaultdict Counter<line_sep>logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' datefmt='%m/%d/%Y %H:%M:%S')<line_sep>logger=logging.getLogger(__name__)<line_sep>logger.setLevel(logging.DEBUG)<line_sep>inverted=<lambda>r:r[:2]<eq>'**'<line_sep>invert=<lambda>r:r[2:]<if>inverted(r)<else>'**'+r<class_stmt>EvalDataset(object)<block_start><def_stmt>__init__ self train_file test_file<block_start>self.spo_train_fp=train_file<line_sep>self.spo_test_fp=test_file<line_sep>train_triples=self._load_spo_triples(self.spo_train_fp)<line_sep>test_triples=self._load_spo_triples(self.spo_test_fp)<line_sep>#logger.debug(">>train triples cnt:%d" % len(train_triples)) #logger.debug(">>test triples cnt:%d" % len(test_triples)) _train_cnt=len(train_triples)<line_sep>all_triples=train_triples<line_sep>all_triples.update(test_triples)<line_sep>self.full_graph=Graph(all_triples)<line_sep>logger.debug(self.full_graph)<block_end><def_stmt>_load_spo_triples self spo_path<block_start>""" :param spo_path: :return: set of (s,r,t) original triples """<line_sep>logger.debug(">> Begin load base spo for %s at %s"%(spo_path time.ctime()))<line_sep>triples=set()<for_stmt>line open(spo_path)<block_start>segs=line.strip().split("\t")<assert_stmt>len(segs)<eq>3<line_sep>s,p,o=segs<line_sep>triples.add((s p o))<block_end>logger.debug(">> Loaded spo triples :%s cnt:%d"%(spo_path len(triples)))<line_sep>logger.debug(">> End load spo for %s at %s"%(spo_path time.ctime()))<line_sep><return>triples<block_end><block_end><class_stmt>Graph(object)<block_start><def_stmt>__init__ self triples<block_start>self.triples=triples<line_sep>neighbors=defaultdict(<lambda>:defaultdict(set))<line_sep>relation_args=defaultdict(<lambda>:defaultdict(set))<line_sep>logger.info(">> Begin building graph at %s"%(time.ctime()))<line_sep>self._node_set=set()<for_stmt>s,r,t triples<block_start>relation_args[r]['s'].add(s)<line_sep>relation_args[r]['t'].add(t)<line_sep>neighbors[s][r].add(t)<line_sep>neighbors[t][invert(r)].add(s)<line_sep>self._node_set.add(t)<line_sep>self._node_set.add(s)<block_end><def_stmt>freeze d<block_start>frozen={}<for_stmt>key,subdict d.iteritems()<block_start>frozen[key]={}<for_stmt>subkey,set_val subdict.iteritems()<block_start>frozen[key][subkey]=tuple(set_val)<block_end><block_end><return>frozen<block_end>self.neighbors=freeze(neighbors)<line_sep>self.relation_args=freeze(relation_args)<line_sep>logger.info(">> Done building graph at %s"%(time.ctime()))<block_end><def_stmt>__repr__ self<block_start>s=""<line_sep>s<augadd>"graph.relations_args cnt %d\t"%len(self.relation_args)<line_sep>s<augadd>"graph.neighbors cnt %d\t"%len(self.neighbors)<line_sep>s<augadd>"graph.neighbors node set cnt %d"%len(self._node_set)<line_sep><return>s<block_end><def_stmt>walk_all self start path<block_start>""" walk from start and get all the paths :param start: start entity :param path: (r1, r2, ...,rk) :return: entities set for candidates path """<line_sep>set_s=set()<line_sep>set_t=set()<line_sep>set_s.add(start)<for_stmt>_,r enumerate(path)<block_start><if_stmt>len(set_s)<eq>0<block_start><return>set()<block_end><for_stmt>_s set_s<block_start><if_stmt>_s<in>self.neighbors<and>r<in>self.neighbors[_s]<block_start>_tset=set(self.neighbors[_s][r])#tupe to set set_t.update(_tset)<block_end><block_end>set_s=set_t.copy()<line_sep>set_t.clear()<block_end><return>set_s<block_end><def_stmt>repr_walk_all_ret self start path MAX_T=20<block_start>cand_set=self.walk_all(start path)<if_stmt>len(cand_set)<eq>0<block_start><return>">>start{} path:{} end: EMPTY!".format(start "->".join(list(path)))<block_end>_len=len(cand_set)<if>len(cand_set)<l>MAX_T<else>MAX_T<line_sep>cand_node_str=", ".join(cand_set[:_len])<line_sep><return>">>start{} path:{} end: {}".format(start "->".join(list(path)) cand_node_str)<block_end><def_stmt>type_matching_entities self path position="t"<block_start><assert_stmt>(position<eq>"t")<if_stmt>position<eq>"t"<block_start>r=path[-1]<block_end><elif_stmt>position<eq>"s"<block_start>r=path[0]<block_end><else_stmt><block_start>logger.error(">>UNKNOWN position at type_matching_entities")<line_sep><raise>ValueError(position)<block_end><try_stmt><block_start><if_stmt><not>inverted(r)<block_start><return>r self.relation_args[r][position]<block_end><else_stmt><block_start>inv_pos='s'<if>position<eq>"t"<else>"t"<line_sep><return>r self.relation_args[invert(r)][inv_pos]<block_end><block_end><except_stmt>KeyError<block_start>logger.error(">>UNKNOWN path value at type_matching_entities :%s from path:%s"%(r path))<line_sep><return><none> tuple()<block_end><block_end><def_stmt>is_trival_query self start path<block_start>""" :param path: :return: Boolean if True/False, is all candidates are right answers, return True """<line_sep>#todo: check right again cand_set=self.type_matching_entities(path "t")<line_sep>ans_set=self.walk_all(start path)<line_sep>_set=cand_set-ans_set<if_stmt>len(_set)<eq>0<block_start><return><true><block_end><else_stmt><block_start><return><false><block_end><block_end><block_end><def_stmt>get_unique_entities_relations train_file dev_file test_file<block_start>entity_lst=dict()<line_sep>relation_lst=dict()<line_sep>all_files=[train_file dev_file test_file]<for_stmt>input_file all_files<block_start><with_stmt>open(input_file "r")<as>f<block_start><for_stmt>line f.readlines()<block_start>tokens=line.strip().split("\t")<assert_stmt>len(tokens)<eq>3<line_sep>entity_lst[tokens[0]]=len(entity_lst)<line_sep>entity_lst[tokens[2]]=len(entity_lst)<line_sep>relations=tokens[1].split(",")<for_stmt>relation relations<block_start>relation_lst[relation]=len(relation_lst)<block_end><block_end><block_end><block_end>print(">> Number of unique entities: %s"%len(entity_lst))<line_sep>print(">> Number of unique relations: %s"%len(relation_lst))<line_sep><return>entity_lst relation_lst<block_end><def_stmt>filter_base_data raw_train_file raw_dev_file raw_test_file train_base_file dev_base_file test_base_file<block_start><def_stmt>fil_base input_file output_file<block_start>fout=open(output_file "w")<line_sep>base_n=0<with_stmt>open(input_file "r")<as>f<block_start><for_stmt>line f.readlines()<block_start>tokens=line.strip().split("\t")<assert_stmt>len(tokens)<eq>3<line_sep>relations=tokens[1].split(",")<if_stmt>len(relations)<eq>1<block_start>fout.write(line)<line_sep>base_n<augadd>1<block_end><block_end><block_end>fout.close()<line_sep><return>base_n<block_end>train_base_n=fil_base(raw_train_file train_base_file)<line_sep>dev_base_n=fil_base(raw_dev_file dev_base_file)<line_sep>test_base_n=fil_base(raw_test_file test_base_file)<line_sep>print(">> Train base cnt:%d"%train_base_n)<line_sep>print(">> Valid base cnt:%d"%dev_base_n)<line_sep>print(">> Test base cnt:%d"%test_base_n)<block_end><def_stmt>generate_onlytail_mask_type input_file output_file<block_start><with_stmt>open(output_file "w")<as>fw<block_start><with_stmt>open(input_file "r")<as>fr<block_start><for_stmt>line fr.readlines()<block_start>fw.write(line.strip('\r \n')+"\tMASK_TAIL\n")<block_end><block_end><block_end><block_end><def_stmt>generate_eval_files vocab_path raw_test_file train_base_file dev_base_file test_base_file sen_candli_file trivial_sen_file<block_start>token2id=load_vocab(vocab_path)<line_sep>eval_data=EvalDataset(train_base_file test_base_file)<line_sep>fout_sen_cand=open(sen_candli_file "w")<line_sep>fout_q_trival=open(trivial_sen_file "w")<line_sep>sen_candli_cnt=trivial_sen_cnt=0<line_sep>j=0<for_stmt>line open(raw_test_file)<block_start>line=line.strip()<line_sep>j<augadd>1<line_sep>segs=line.split("\t")<line_sep>s=segs[0]<line_sep>t=segs[2]<line_sep>path=tuple(segs[1].split(","))<line_sep>q_set=eval_data.full_graph.walk_all(s path)<line_sep>r,cand_set=eval_data.full_graph.type_matching_entities(path "t")<line_sep>cand_set=set(cand_set)<line_sep>neg_set=cand_set-q_set<line_sep>sen_tokens=[]<line_sep>sen_tokens.append(line.split("\t")[0])<line_sep>sen_tokens.extend(line.split("\t")[1].split(","))<line_sep>sen_tokens.append(line.split("\t")[2])<line_sep>sen_id=[str(token2id[x])<for>x sen_tokens]<if_stmt>len(neg_set)<eq>0<block_start>trivial_sen_cnt<augadd>1<line_sep>#fout_q_trival.write(line + "\n") fout_q_trival.write(" ".join(sen_id)+"\n")<block_end><else_stmt><block_start>sen_candli_cnt<augadd>1<line_sep>candli_id_set=[str(token2id[x])<for>x neg_set]<line_sep>sen_canli_str="%s\t%s"%(" ".join(sen_id) " ".join(list(candli_id_set)))<line_sep>fout_sen_cand.write(sen_canli_str+"\n")<block_end><if_stmt>len(cand_set)<l>len(q_set)<block_start>logger.error("ERROR! cand_set %d < q_set %d at line[%d]:%s"%(len(cand_set) len(q_set) j line))<block_end><if_stmt>j%100<eq>0<block_start>logger.debug(" ...processing %d at %s"%(j time.ctime()))<block_end><if_stmt>-100<g>0<and>j<ge>100<block_start><break><block_end><block_end>logger.info(">> sen_canli_set count:%d "%sen_candli_cnt)<line_sep>logger.info(">> trivial sen count:%d "%trivial_sen_cnt)<line_sep>logger.info(">> Finish generate evaluation candidates for %s file at %s"%(raw_test_file time.ctime()))<block_end><def_stmt>pathquery_data_preprocess raw_train_file raw_dev_file raw_test_file vocab_path sen_candli_file trivial_sen_file new_train_file new_dev_file new_test_file train_base_file dev_base_file test_base_file<block_start>entity_lst,relation_lst=get_unique_entities_relations(raw_train_file raw_dev_file raw_test_file)<line_sep>write_vocab(vocab_path entity_lst relation_lst)<line_sep>filter_base_data(raw_train_file raw_dev_file raw_test_file train_base_file dev_base_file test_base_file)<line_sep>generate_mask_type(raw_train_file new_train_file)<line_sep>generate_onlytail_mask_type(raw_dev_file new_dev_file)<line_sep>generate_onlytail_mask_type(raw_test_file new_test_file)<line_sep>vocab=load_vocab(vocab_path)<line_sep>generate_eval_files(vocab_path raw_test_file train_base_file dev_base_file test_base_file sen_candli_file trivial_sen_file)<block_end><def_stmt>get_args <block_start>parser=argparse.ArgumentParser()<line_sep>parser.add_argument("--task" type=str required=<true> default=<none> help="task name: fb15k, fb15k237, wn18rr, wn18, pathqueryFB, pathqueryWN")<line_sep>parser.add_argument("--dir" type=str required=<true> default=<none> help="task data directory")<line_sep>parser.add_argument("--train" type=str required=<false> default="train" help="train file name, default train.txt")<line_sep>parser.add_argument("--valid" type=str required=<false> default="dev" help="valid file name, default valid.txt")<line_sep>parser.add_argument("--test" type=str required=<false> default="test" help="test file name, default test.txt")<line_sep>args=parser.parse_args()<line_sep><return>args<block_end><if_stmt>__name__<eq>"__main__"<block_start>args=get_args()<line_sep>task=args.task.lower()<assert_stmt>task<in>["pathqueryfb" "pathquerywn"]<line_sep>raw_train_file=os.path.join(args.dir args.train)<line_sep>raw_dev_file=os.path.join(args.dir args.valid)<line_sep>raw_test_file=os.path.join(args.dir args.test)<line_sep>new_train_file=os.path.join(args.dir "train.coke.txt")<line_sep>new_test_file=os.path.join(args.dir "test.coke.txt")<line_sep>new_dev_file=os.path.join(args.dir "dev.coke.txt")<line_sep>vocab_file=os.path.join(args.dir "vocab.txt")<line_sep>sen_candli_file=os.path.join(args.dir "sen_candli.txt")<line_sep>trivial_sen_file=os.path.join(args.dir "trivial_sen.txt")<line_sep>train_base_file=os.path.join(args.dir "train.base.txt")<line_sep>test_base_file=os.path.join(args.dir "test.base.txt")<line_sep>dev_base_file=os.path.join(args.dir "dev.base.txt")<line_sep>pathquery_data_preprocess(raw_train_file raw_dev_file raw_test_file vocab_file sen_candli_file trivial_sen_file new_train_file new_dev_file new_test_file train_base_file dev_base_file test_base_file)<block_end>
<import_stmt>logging<import_from_stmt>math cos pi<import_from_stmt>mxnet.lr_scheduler LRScheduler<class_stmt>WarmupMultiFactorScheduler(LRScheduler)<block_start><def_stmt>__init__ self step factor=1 warmup=<false> warmup_type='constant' warmup_lr=0 warmup_step=0<block_start>super().__init__()<assert_stmt>isinstance(step list)<for_stmt>i,_step enumerate(step)<block_start><if_stmt>i<ne>0<and>step[i]<le>step[i-1]<block_start><raise>ValueError("Schedule step must be an increasing integer list")<block_end><block_end><if_stmt>factor<g>1.0<block_start><raise>ValueError("Factor must be no more than 1 to make lr reduce")<block_end><if_stmt>warmup<block_start><if_stmt>warmup_step<ge>step[0]<block_start><raise>ValueError("Warmup step must be smaller than schedule step")<block_end><if_stmt>warmup_type<not><in>['constant' 'gradual']<block_start><raise>ValueError("Warmup scheduler only support constant or gradual")<block_end><block_end>self.step=step<line_sep>self.cur_step_ind=0<line_sep>self.factor=factor<line_sep>self.count=0<line_sep>self.warmup=warmup<line_sep>self.warmup_type=warmup_type<line_sep>self.warmup_lr=warmup_lr<line_sep>self.warmup_step=warmup_step<block_end><def_stmt>__call__ self num_update<block_start><if_stmt>self.warmup<and>num_update<le>self.warmup_step<block_start><if_stmt>self.warmup_type<eq>'constant'<block_start><return>self.warmup_lr<block_end><elif_stmt>self.warmup_type<eq>'gradual'<block_start><return>(self.base_lr-self.warmup_lr)/self.warmup_step<times>num_update+self.warmup_lr<block_end><block_end><while_stmt>self.cur_step_ind<le>len(self.step)-1<block_start><if_stmt>num_update<g>self.step[self.cur_step_ind]<block_start>self.count=self.step[self.cur_step_ind]<line_sep>self.cur_step_ind<augadd>1<line_sep>self.base_lr<augmul>self.factor<line_sep>logging.info("Update[%d]: Change learning rate to %0.5e" num_update self.base_lr)<block_end><else_stmt><block_start><return>self.base_lr<block_end><block_end><return>self.base_lr<block_end><block_end># from gluoncv <class_stmt>LRSequential(LRScheduler)<block_start>r"""Compose Learning Rate Schedulers Parameters ---------- schedulers: list list of LRScheduler objects """<def_stmt>__init__ self schedulers<block_start>super().__init__()<assert_stmt>(len(schedulers)<g>0)<line_sep>self.update_sep=[]<line_sep>self.count=0<line_sep>self.learning_rate=0<line_sep>self.schedulers=[]<for_stmt>lr schedulers<block_start>self.add(lr)<block_end><block_end><def_stmt>add self scheduler<block_start><assert_stmt>(isinstance(scheduler LRScheduler))<line_sep>scheduler.offset=self.count<line_sep>self.count<augadd>scheduler.niters<line_sep>self.update_sep.append(self.count)<line_sep>self.schedulers.append(scheduler)<block_end><def_stmt>__call__ self num_update<block_start>self.update(num_update)<line_sep><return>self.learning_rate<block_end><def_stmt>update self num_update<block_start>num_update=min(num_update self.count-1)<line_sep>ind=len(self.schedulers)-1<for_stmt>i,sep enumerate(self.update_sep)<block_start><if_stmt>sep<g>num_update<block_start>ind=i<line_sep><break><block_end><block_end>lr=self.schedulers[ind]<line_sep>lr.update(num_update)<line_sep>self.learning_rate=lr.learning_rate<block_end><block_end># from gluoncv <class_stmt>AdvancedLRScheduler(LRScheduler)<block_start>r"""Learning Rate Scheduler Parameters ---------- mode : str Modes for learning rate scheduler. Currently it supports 'constant', 'step', 'linear', 'poly' and 'cosine'. base_lr : float Base learning rate, i.e. the starting learning rate. target_lr : float Target learning rate, i.e. the ending learning rate. With constant mode target_lr is ignored. niters : int Number of iterations to be scheduled. nepochs : int Number of epochs to be scheduled. iters_per_epoch : int Number of iterations in each epoch. offset : int Number of iterations before this scheduler. power : float Power parameter of poly scheduler. step_iter : list A list of iterations to decay the learning rate. step_epoch : list A list of epochs to decay the learning rate. step_factor : float Learning rate decay factor. """<def_stmt>__init__ self mode base_lr=0.1 target_lr=0 niters=0 nepochs=0 iters_per_epoch=0 offset=0 power=2 step_iter=<none> step_epoch=<none> step_factor=0.1 baselr=<none> targetlr=<none><block_start>super().__init__()<assert_stmt>(mode<in>['constant' 'step' 'linear' 'poly' 'cosine'])<line_sep>self.mode=mode<if_stmt>mode<eq>'step'<block_start><assert_stmt>(step_iter<is><not><none><or>step_epoch<is><not><none>)<block_end><if_stmt>baselr<is><not><none><block_start>warnings.warn("baselr is deprecated. Please use base_lr.")<if_stmt>base_lr<eq>0.1<block_start>base_lr=baselr<block_end><block_end>self.base_lr=base_lr<if_stmt>targetlr<is><not><none><block_start>warnings.warn("targetlr is deprecated. Please use target_lr.")<if_stmt>target_lr<eq>0<block_start>target_lr=targetlr<block_end><block_end>self.target_lr=target_lr<if_stmt>self.mode<eq>'constant'<block_start>self.target_lr=self.base_lr<block_end>self.niters=niters<line_sep>self.step=step_iter<line_sep>epoch_iters=nepochs<times>iters_per_epoch<if_stmt>epoch_iters<g>0<block_start>self.niters=epoch_iters<if_stmt>step_epoch<is><not><none><block_start>self.step=[s<times>iters_per_epoch<for>s step_epoch]<block_end><block_end>self.offset=offset<line_sep>self.power=power<line_sep>self.step_factor=step_factor<block_end><def_stmt>__call__ self num_update<block_start>self.update(num_update)<line_sep><return>self.learning_rate<block_end><def_stmt>update self num_update<block_start>N=self.niters-1<line_sep>T=num_update-self.offset<line_sep>T=min(max(0 T) N)<if_stmt>self.mode<eq>'constant'<block_start>factor=0<block_end><elif_stmt>self.mode<eq>'linear'<block_start>factor=1-T/N<block_end><elif_stmt>self.mode<eq>'poly'<block_start>factor=pow(1-T/N self.power)<block_end><elif_stmt>self.mode<eq>'cosine'<block_start>factor=(1+cos(pi<times>T/N))/2<block_end><elif_stmt>self.mode<eq>'step'<block_start><if_stmt>self.step<is><not><none><block_start>count=sum([1<for>s self.step<if>s<le>T])<line_sep>factor=pow(self.step_factor count)<block_end><else_stmt><block_start>factor=1<block_end><block_end><else_stmt><block_start><raise>NotImplementedError<block_end><if_stmt>self.mode<eq>'step'<block_start>self.learning_rate=self.base_lr<times>factor<block_end><else_stmt><block_start>self.learning_rate=self.target_lr+(self.base_lr-self.target_lr)<times>factor<block_end><block_end><block_end>
# swift_build_support/build_graph.py ----------------------------*- python -*- # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ---------------------------------------------------------------------------- # # This is a simple implementation of an acyclic build graph. We require no # cycles, so we just perform a reverse post order traversal to get a topological # ordering. We check during the reverse post order traversal that we do not # visit any node multiple times. # # Nodes are assumed to be a product's class. # # ---------------------------------------------------------------------------- <def_stmt>_get_po_ordered_nodes root invertedDepMap# Then setup our worklist/visited node set. <block_start>worklist=[root]<line_sep>visitedNodes=set([])<line_sep># TODO: Can we unify po_ordered_nodes and visitedNodes in some way? po_ordered_nodes=[]<line_sep># Until we no longer have nodes to visit... <while_stmt><not>len(worklist)<eq>0# First grab the last element of the worklist. If we have already # visited this node, just pop it and skip it. # # DISCUSSION: Consider the following build graph: # # A -> [C, B] # B -> [C] # # In this case, we will most likely get the following worklist # before actually processing anything: # # A, C, B, C # # In this case, we want to ignore the initial C pushed onto the # worklist by visiting A since we will have visited C already due to # the edge from B -> C. <block_start>node=worklist[-1]<if_stmt>node<in>visitedNodes<block_start>worklist.pop()<line_sep><continue><block_end># Then grab the dependents of our node. deps=invertedDepMap.get(node set([]))<assert_stmt>(isinstance(deps set))<line_sep># Then visit those and see if we have not visited any of them. Push # any such nodes onto the worklist and continue. If we have already # visited all of our dependents, then we can actually process this # node. foundDep=<false><for_stmt>d deps<block_start><if_stmt>d<not><in>visitedNodes<block_start>foundDep=<true><line_sep>worklist.append(d)<block_end><block_end><if_stmt>foundDep<block_start><continue><block_end># Now process the node by popping it off the worklist, adding it to # the visited nodes set, and append it to the po_ordered_nodes in # its final position. worklist.pop()<line_sep>visitedNodes.add(node)<line_sep>po_ordered_nodes.append(node)<block_end><return>po_ordered_nodes<block_end><class_stmt>BuildDAG(object)<block_start><def_stmt>__init__ self<block_start>self.root=<none><line_sep># A map from a node to a list of nodes that depend on the given node. # # NOTE: This is an inverted dependency map implying that the root will # be a "final element" of the graph. self.invertedDepMap={}<block_end><def_stmt>add_edge self pred succ<block_start>self.invertedDepMap.setdefault(pred set([succ])).add(succ)<block_end><def_stmt>set_root self root# Assert that we always only have one root. <block_start><assert_stmt>(self.root<is><none>)<line_sep>self.root=root<block_end><def_stmt>produce_schedule self# Grab the root and make sure it is not None <block_start>root=self.root<assert_stmt>(root<is><not><none>)<line_sep># Then perform a post order traversal from root using our inverted # dependency map to compute a list of our nodes in post order. # # NOTE: The index of each node in this list is the post order number of # the node. po_ordered_nodes=_get_po_ordered_nodes(root self.invertedDepMap)<line_sep># Ok, we have our post order list. We want to provide our user a reverse # post order, so we take our array and construct a dictionary of an # enumeration of the list. This will give us a dictionary mapping our # product names to their reverse post order number. rpo_ordered_nodes=list(reversed(po_ordered_nodes))<line_sep>node_to_rpot_map=dict((y x)<for>x,y enumerate(rpo_ordered_nodes))<line_sep># Now before we return our rpo_ordered_nodes and our node_to_rpot_map, lets # verify that we didn't find any cycles. We can do this by traversing # our dependency graph in reverse post order and making sure all # dependencies of each node we visit has a later reverse post order # number than the node we are checking. <for_stmt>n,node enumerate(rpo_ordered_nodes)<block_start><for_stmt>dep self.invertedDepMap.get(node [])<block_start><if_stmt>node_to_rpot_map[dep]<l>n<block_start>print('n: {}. node: {}.'.format(n node))<line_sep>print('dep: {}.'.format(dep))<line_sep>print('inverted dependency map: {}'.format(self.invertedDepMap))<line_sep>print('rpo ordered nodes: {}'.format(rpo_ordered_nodes))<line_sep>print('rpo node to rpo number map: {}'.format(node_to_rpot_map))<line_sep><raise>RuntimeError('Found cycle in build graph!')<block_end><block_end><block_end><return>(rpo_ordered_nodes node_to_rpot_map)<block_end><block_end><def_stmt>produce_scheduled_build input_product_classes<block_start>"""For a given a subset input_input_product_classes of all_input_product_classes, compute a topological ordering of the input_input_product_classes + topological closures that respects the dependency graph. """<line_sep>dag=BuildDAG()<line_sep>worklist=list(input_product_classes)<line_sep>visited=set(input_product_classes)<line_sep># Construct the DAG. <while_stmt>len(worklist)<g>0<block_start>entry=worklist.pop()<line_sep>deps=entry.get_dependencies()<if_stmt>len(deps)<eq>0<block_start>dag.set_root(entry)<block_end><for_stmt>d deps<block_start>dag.add_edge(d entry)<if_stmt>d<not><in>visited<block_start>worklist.append(d)<block_end><block_end>visited=visited.union(deps)<block_end># Then produce the schedule. schedule=dag.produce_schedule()<line_sep># Finally check that all of our input_product_classes are in the schedule. <if_stmt>len(set(input_product_classes)-set(schedule[0]))<ne>0<block_start><raise>RuntimeError('Found disconnected graph?!')<block_end><return>schedule<block_end>
<import_from_stmt>django.contrib.auth get_user_model<import_from_stmt>django.test TestCase<import_from_stmt>wagtail.core.models Comment Page<class_stmt>CommentTestingUtils<block_start><def_stmt>setUp self<block_start>self.page=Page.objects.get(title="Welcome to the Wagtail test site!")<line_sep>self.revision_1=self.page.save_revision()<line_sep>self.revision_2=self.page.save_revision()<block_end><def_stmt>create_comment self revision_created<block_start><return>Comment.objects.create(page=self.page user=get_user_model().objects.first() text='test' contentpath='title' revision_created=revision_created )<block_end><block_end><class_stmt>TestRevisionDeletion(CommentTestingUtils TestCase)<block_start>fixtures=['test.json']<def_stmt>setUp self<block_start>super().setUp()<line_sep>self.revision_3=self.page.save_revision()<line_sep>self.old_comment=self.create_comment(self.revision_1)<line_sep>self.new_comment=self.create_comment(self.revision_3)<block_end><def_stmt>test_deleting_old_revision_moves_comment_revision_created_forwards self# test that when a revision is deleted, a comment linked to it via revision_created has its revision_created moved # to the next revision <block_start>self.revision_1.delete()<line_sep>self.old_comment.refresh_from_db()<line_sep>self.assertEqual(self.old_comment.revision_created self.revision_2)<block_end><def_stmt>test_deleting_most_recent_revision_deletes_created_comments self# test that when the most recent revision is deleted, any comments created on it are also deleted <block_start>self.revision_3.delete()<with_stmt>self.assertRaises(Comment.DoesNotExist)<block_start>self.new_comment.refresh_from_db()<block_end><block_end><block_end>
<import_stmt>numpy<as>np<import_from_stmt>sklearn svm<import_from_stmt>sklearn.datasets load_digits<import_from_stmt>sklearn.model_selection KFold cross_val_score<import_from_stmt>opytimizer Opytimizer<import_from_stmt>opytimizer.core Function<import_from_stmt>opytimizer.optimizers.swarm PSO<import_from_stmt>opytimizer.spaces SearchSpace<line_sep># Loads digits dataset digits=load_digits()<line_sep># Gathers samples and targets X=digits.data<line_sep>Y=digits.target<def_stmt>_svm opytimizer# Gathers params <block_start>C=opytimizer[0][0]<line_sep># Instanciating an SVC class svc=svm.SVC(C=C kernel='linear')<line_sep># Creates a cross-validation holder k_fold=KFold(n_splits=5)<line_sep># Fitting model using cross-validation scores=cross_val_score(svc X Y cv=k_fold n_jobs=-1)<line_sep># Calculates scores mean mean_score=np.mean(scores)<line_sep><return>1-mean_score<block_end># Number of agents and decision variables n_agents=10<line_sep>n_variables=1<line_sep># Lower and upper bounds (has to be the same size as `n_variables`) lower_bound=[0.000001]<line_sep>upper_bound=[10]<line_sep># Creates the space, optimizer and function space=SearchSpace(n_agents n_variables lower_bound upper_bound)<line_sep>optimizer=PSO()<line_sep>function=Function(_svm)<line_sep># Bundles every piece into Opytimizer class opt=Opytimizer(space optimizer function)<line_sep># Runs the optimization task opt.start(n_iterations=100)<line_sep>
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. <import_stmt>unittest<import_from_stmt>telemetry.internal.platform.tracing_agent chrome_tracing_agent<class_stmt>FakePlatformBackend(object)<block_start><pass><block_end><class_stmt>FakeDevtoolsClient(object)<block_start><def_stmt>__init__ self remote_port<block_start>self.is_alive=<true><line_sep>self.tracing_started=<false><line_sep>self.remote_port=remote_port<line_sep>self.will_raise_exception_in_stop_tracing=<false><block_end><def_stmt>IsAlive self<block_start><return>self.is_alive<block_end><def_stmt>StartChromeTracing self _trace_options _filter_string _timeout=10<block_start>self.tracing_started=<true><block_end><def_stmt>StopChromeTracing self _trace_data_builder<block_start>self.tracing_started=<false><if_stmt>self.will_raise_exception_in_stop_tracing<block_start><raise>Exception<block_end><block_end><def_stmt>IsChromeTracingSupported self<block_start><return><true><block_end><block_end><class_stmt>FakeTraceOptions(object)<block_start><def_stmt>__init__ self<block_start>self.enable_chrome_trace=<true><block_end><block_end><class_stmt>FakeCategoryFilter(object)<block_start><def_stmt>__init__ self<block_start>self.filter_string='foo'<block_end><block_end><class_stmt>ChromeTracingAgentUnittest(unittest.TestCase)<block_start><def_stmt>setUp self<block_start>self.platform1=FakePlatformBackend()<line_sep>self.platform2=FakePlatformBackend()<line_sep>self.platform3=FakePlatformBackend()<block_end><def_stmt>StartTracing self platform_backend enable_chrome_trace=<true><block_start><assert_stmt>chrome_tracing_agent.ChromeTracingAgent.IsSupported(platform_backend)<line_sep>agent=chrome_tracing_agent.ChromeTracingAgent(platform_backend)<line_sep>trace_options=FakeTraceOptions()<line_sep>trace_options.enable_chrome_trace=enable_chrome_trace<line_sep>agent.Start(trace_options FakeCategoryFilter() 10)<line_sep><return>agent<block_end><def_stmt>StopTracing self tracing_agent<block_start>tracing_agent.Stop(<none>)<block_end><def_stmt>testRegisterDevtoolsClient self<block_start>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(1) self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(2) self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(3) self.platform1)<line_sep>tracing_agent_of_platform1=self.StartTracing(self.platform1)<with_stmt>self.assertRaises(chrome_tracing_agent.ChromeTracingStartedError)<block_start>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(4) self.platform1)<block_end>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(5) self.platform2)<line_sep>self.StopTracing(tracing_agent_of_platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(FakeDevtoolsClient(6) self.platform1)<block_end><def_stmt>testIsSupport self<block_start>self.assertFalse(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform1))<line_sep>self.assertFalse(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform2))<line_sep>self.assertFalse(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform3))<line_sep>devtool1=FakeDevtoolsClient(1)<line_sep>devtool2=FakeDevtoolsClient(2)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool1 self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool2 self.platform2)<line_sep>devtool2.is_alive=<false><line_sep># Chrome tracing is only supported on platform 1 since only platform 1 has # an alive devtool. self.assertTrue(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform1))<line_sep>self.assertFalse(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform2))<line_sep>self.assertFalse(chrome_tracing_agent.ChromeTracingAgent.IsSupported(self.platform3))<block_end><def_stmt>testStartAndStopTracing self<block_start>devtool1=FakeDevtoolsClient(1)<line_sep>devtool2=FakeDevtoolsClient(2)<line_sep>devtool3=FakeDevtoolsClient(3)<line_sep>devtool4=FakeDevtoolsClient(2)<line_sep># Register devtools 1, 2, 3 on platform1 and devtool 4 on platform 2 chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool1 self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool2 self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool3 self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool4 self.platform2)<line_sep>devtool2.is_alive=<false><line_sep>tracing_agent1=self.StartTracing(self.platform1)<with_stmt>self.assertRaises(chrome_tracing_agent.ChromeTracingStartedError)<block_start>self.StartTracing(self.platform1)<block_end>self.assertTrue(devtool1.tracing_started)<line_sep>self.assertFalse(devtool2.tracing_started)<line_sep>self.assertTrue(devtool3.tracing_started)<line_sep># Devtool 4 shouldn't have tracing started although it has the same remote # port as devtool 2 self.assertFalse(devtool4.tracing_started)<line_sep>self.StopTracing(tracing_agent1)<line_sep>self.assertFalse(devtool1.tracing_started)<line_sep>self.assertFalse(devtool2.tracing_started)<line_sep>self.assertFalse(devtool3.tracing_started)<line_sep>self.assertFalse(devtool4.tracing_started)<line_sep># Test that it should be ok to start & stop tracing on platform1 again. tracing_agent1=self.StartTracing(self.platform1)<line_sep>self.StopTracing(tracing_agent1)<line_sep>tracing_agent2=self.StartTracing(self.platform2)<line_sep>self.assertTrue(devtool4.tracing_started)<line_sep>self.StopTracing(tracing_agent2)<line_sep>self.assertFalse(devtool4.tracing_started)<block_end><def_stmt>testExceptionRaisedInStopTracing self<block_start>devtool1=FakeDevtoolsClient(1)<line_sep>devtool2=FakeDevtoolsClient(2)<line_sep># Register devtools 1, 2 on platform 1 chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool1 self.platform1)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool2 self.platform1)<line_sep>tracing_agent1=self.StartTracing(self.platform1)<line_sep>self.assertTrue(devtool1.tracing_started)<line_sep>self.assertTrue(devtool2.tracing_started)<line_sep>devtool2.will_raise_exception_in_stop_tracing=<true><with_stmt>self.assertRaises(chrome_tracing_agent.ChromeTracingStoppedError)<block_start>self.StopTracing(tracing_agent1)<block_end>devtool1.is_alive=<false><line_sep>devtool2.is_alive=<false><line_sep># Register devtools 3 on platform 1 should not raise any exception. devtool3=FakeDevtoolsClient(3)<line_sep>chrome_tracing_agent.ChromeTracingAgent.RegisterDevToolsClient(devtool3 self.platform1)<line_sep># Start & Stop tracing on platform 1 should work just fine. tracing_agent2=self.StartTracing(self.platform1)<line_sep>self.StopTracing(tracing_agent2)<block_end><block_end>
# -*- coding: utf-8 -*- <import_from_stmt>south.utils datetime_utils<as>datetime<import_from_stmt>south.db db<import_from_stmt>south.v2 SchemaMigration<import_from_stmt>django.db models<class_stmt>Migration(SchemaMigration)<block_start>depends_on=(("authenz" "0002_auto__add_cluser") )<def_stmt>forwards self orm# Adding model 'Queue' <block_start>db.create_table(u'queues_queue' ((u'id' self.gf('django.db.models.fields.AutoField')(primary_key=<true>)) ('name' self.gf('django.db.models.fields.CharField')(max_length=64)) ('vhost' self.gf('django.db.models.fields.CharField')(unique=<true> max_length=36 blank=<true>)) ('is_public' self.gf('django.db.models.fields.BooleanField')(default=<false>)) ('owner' self.gf('django.db.models.fields.related.ForeignKey')(to=orm['authenz.ClUser'])) ))<line_sep>db.send_create_signal(u'queues' ['Queue'])<line_sep># Adding M2M table for field organizers on 'Queue' m2m_table_name=db.shorten_name(u'queues_queue_organizers')<line_sep>db.create_table(m2m_table_name (('id' models.AutoField(verbose_name='ID' primary_key=<true> auto_created=<true>)) ('queue' models.ForeignKey(orm[u'queues.queue'] null=<false>)) ('cluser' models.ForeignKey(orm[u'authenz.cluser'] null=<false>))))<line_sep>db.create_unique(m2m_table_name ['queue_id' 'cluser_id'])<block_end><def_stmt>backwards self orm# Deleting model 'Queue' <block_start>db.delete_table(u'queues_queue')<line_sep># Removing M2M table for field organizers on 'Queue' db.delete_table(db.shorten_name(u'queues_queue_organizers'))<block_end>models={u'auth.group':{'Meta':{'object_name':'Group'} u'id':('django.db.models.fields.AutoField' [] {'primary_key':'True'}) 'name':('django.db.models.fields.CharField' [] {'unique':'True' 'max_length':'80'}) 'permissions':('django.db.models.fields.related.ManyToManyField' [] {'to':u"orm['auth.Permission']" 'symmetrical':'False' 'blank':'True'})} u'auth.permission':{'Meta':{'ordering':"(u'content_type__app_label', u'content_type__model', u'codename')" 'unique_together':"((u'content_type', u'codename'),)" 'object_name':'Permission'} 'codename':('django.db.models.fields.CharField' [] {'max_length':'100'}) 'content_type':('django.db.models.fields.related.ForeignKey' [] {'to':u"orm['contenttypes.ContentType']"}) u'id':('django.db.models.fields.AutoField' [] {'primary_key':'True'}) 'name':('django.db.models.fields.CharField' [] {'max_length':'50'})} u'authenz.cluser':{'Meta':{'object_name':'ClUser'} 'bibtex':('django.db.models.fields.TextField' [] {'null':'True' 'blank':'True'}) 'contact_email':('django.db.models.fields.EmailField' [] {'max_length':'75' 'null':'True' 'blank':'True'}) 'date_joined':('django.db.models.fields.DateTimeField' [] {'default':'datetime.datetime.now'}) 'email':('django.db.models.fields.EmailField' [] {'max_length':'75' 'blank':'True'}) 'email_on_submission_finished_successfully':('django.db.models.fields.BooleanField' [] {'default':'False'}) 'first_name':('django.db.models.fields.CharField' [] {'max_length':'30' 'blank':'True'}) 'groups':('django.db.models.fields.related.ManyToManyField' [] {'symmetrical':'False' 'related_name':"u'user_set'" 'blank':'True' 'to':u"orm['auth.Group']"}) u'id':('django.db.models.fields.AutoField' [] {'primary_key':'True'}) 'is_active':('django.db.models.fields.BooleanField' [] {'default':'True'}) 'is_staff':('django.db.models.fields.BooleanField' [] {'default':'False'}) 'is_superuser':('django.db.models.fields.BooleanField' [] {'default':'False'}) 'last_login':('django.db.models.fields.DateTimeField' [] {'default':'datetime.datetime.now'}) 'last_name':('django.db.models.fields.CharField' [] {'max_length':'30' 'blank':'True'}) 'method_description':('django.db.models.fields.TextField' [] {'null':'True' 'blank':'True'}) 'method_name':('django.db.models.fields.CharField' [] {'max_length':'20' 'null':'True' 'blank':'True'}) 'organization_or_affiliation':('django.db.models.fields.CharField' [] {'max_length':'255' 'null':'True' 'blank':'True'}) 'organizer_direct_message_updates':('django.db.models.fields.BooleanField' [] {'default':'True'}) 'organizer_status_updates':('django.db.models.fields.BooleanField' [] {'default':'True'}) 'participation_status_updates':('django.db.models.fields.BooleanField' [] {'default':'True'}) 'password':('<PASSWORD>' [] {'max_length':'128'}) 'project_url':('django.db.models.fields.URLField' [] {'max_length':'200' 'null':'True' 'blank':'True'}) 'publication_url':('django.db.models.fields.URLField' [] {'max_length':'200' 'null':'True' 'blank':'True'}) 'team_members':('django.db.models.fields.TextField' [] {'null':'True' 'blank':'True'}) 'team_name':('django.db.models.fields.CharField' [] {'max_length':'64' 'null':'True' 'blank':'True'}) 'user_permissions':('django.db.models.fields.related.ManyToManyField' [] {'symmetrical':'False' 'related_name':"u'user_set'" 'blank':'True' 'to':u"orm['auth.Permission']"}) 'username':('django.db.models.fields.CharField' [] {'unique':'True' 'max_length':'30'})} u'contenttypes.contenttype':{'Meta':{'ordering':"('name',)" 'unique_together':"(('app_label', 'model'),)" 'object_name':'ContentType' 'db_table':"'django_content_type'"} 'app_label':('django.db.models.fields.CharField' [] {'max_length':'100'}) u'id':('django.db.models.fields.AutoField' [] {'primary_key':'True'}) 'model':('django.db.models.fields.CharField' [] {'max_length':'100'}) 'name':('django.db.models.fields.CharField' [] {'max_length':'100'})} u'queues.queue':{'Meta':{'object_name':'Queue'} u'id':('django.db.models.fields.AutoField' [] {'primary_key':'True'}) 'is_public':('django.db.models.fields.BooleanField' [] {'default':'False'}) 'name':('django.db.models.fields.CharField' [] {'max_length':'64'}) 'organizers':('django.db.models.fields.related.ManyToManyField' [] {'blank':'True' 'related_name':"'organizers'" 'null':'True' 'symmetrical':'False' 'to':u"orm['authenz.ClUser']"}) 'owner':('django.db.models.fields.related.ForeignKey' [] {'to':u"orm['authenz.ClUser']"}) 'vhost':('django.db.models.fields.CharField' [] {'unique':'True' 'max_length':'36' 'blank':'True'})}}<line_sep>complete_apps=['queues']<block_end>
<import_from_stmt>RecoTauTag.RecoTau.pfRecoTauProducerDef_cfi pfRecoTauProducerDef<line_sep>pfRecoTauProducer=pfRecoTauProducerDef.clone()<line_sep>
"""Tests of C language support."""<import_stmt>logging<import_stmt>unittest<import_stmt>timing<import_stmt>typed_astunparse<import_from_stmt>transpyle.general.code_reader CodeReader<import_from_stmt>transpyle.c.parser C99Parser<import_from_stmt>transpyle.c.ast_generalizer CAstGeneralizer<import_from_stmt>.common basic_check_c_ast basic_check_python_ast execute_on_language_examples<line_sep>_LOG=logging.getLogger(__name__)<line_sep>_TIME=timing.get_timing_group(__name__)<class_stmt>ParserTests(unittest.TestCase)<block_start>@execute_on_language_examples('c11')<def_stmt>test_parse_examples self input_path<block_start>code_reader=CodeReader()<line_sep>code=code_reader.read_file(input_path)<line_sep>parser=C99Parser()<with_stmt>_TIME.measure('parse.{}'.format(input_path.name.replace('.' '_')))<as>timer<block_start>c_ast=parser.parse(code input_path)<block_end>basic_check_c_ast(self input_path c_ast)<line_sep>_LOG.info('parsed "%s" in %fs' input_path timer.elapsed)<block_end><block_end><class_stmt>AstGeneralizerTests(unittest.TestCase)<block_start>@execute_on_language_examples('c11')<def_stmt>test_generalize_examples self input_path<block_start>code_reader=CodeReader()<line_sep>code=code_reader.read_file(input_path)<line_sep>parser=C99Parser()<line_sep>c_ast=parser.parse(code input_path)<line_sep>basic_check_c_ast(self input_path c_ast)<line_sep>ast_generalizer=CAstGeneralizer()<with_stmt>_TIME.measure('generalize.{}'.format(input_path.name.replace('.' '_')))<as>timer<block_start>syntax=ast_generalizer.generalize(c_ast)<block_end>basic_check_python_ast(self input_path syntax)<line_sep>_LOG.info('generalized "%s" in %fs' input_path timer.elapsed)<line_sep>_LOG.debug('%s' typed_astunparse.dump(syntax))<line_sep>_LOG.debug('%s' typed_astunparse.unparse(syntax))<block_end><block_end>
<import_stmt>asyncio<import_stmt>logging<import_stmt>signal<import_from_stmt>concurrent.futures CancelledError ThreadPoolExecutor<import_from_stmt>contextlib suppress<line_sep>logger=logging.getLogger(__name__)<class_stmt>LoaferRunner<block_start><def_stmt>__init__ self max_workers=<none> on_stop_callback=<none><block_start>self._on_stop_callback=on_stop_callback<line_sep># XXX: See https://github.com/python/asyncio/issues/258 # The minimum value depends on the number of cores in the machine # See https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor self._executor=ThreadPoolExecutor(max_workers)<line_sep>self.loop.set_default_executor(self._executor)<block_end>@property<def_stmt>loop self<block_start><return>asyncio.get_event_loop()<block_end><def_stmt>start self debug=<false><block_start><if_stmt>debug<block_start>self.loop.set_debug(enabled=debug)<block_end>self.loop.add_signal_handler(signal.SIGINT self.prepare_stop)<line_sep>self.loop.add_signal_handler(signal.SIGTERM self.prepare_stop)<try_stmt><block_start>self.loop.run_forever()<block_end><finally_stmt><block_start>self.stop()<line_sep>self.loop.close()<line_sep>logger.debug('loop.is_running={}'.format(self.loop.is_running()))<line_sep>logger.debug('loop.is_closed={}'.format(self.loop.is_closed()))<block_end><block_end><def_stmt>prepare_stop self *args<block_start><if_stmt>self.loop.is_running()# signals loop.run_forever to exit in the next iteration <block_start>self.loop.stop()<block_end><block_end><def_stmt>stop self *args **kwargs<block_start>logger.info('stopping Loafer ...')<if_stmt>callable(self._on_stop_callback)<block_start>self._on_stop_callback()<block_end>logger.info('cancel schedulled operations ...')<for_stmt>task asyncio.Task.all_tasks(self.loop)<block_start>task.cancel()<if_stmt>task.cancelled()<or>task.done()<block_start><continue><block_end><with_stmt>suppress(CancelledError)<block_start>self.loop.run_until_complete(task)<block_end><block_end>self._executor.shutdown(wait=<true>)<block_end><block_end>
# Copyright (c) 2020 vesoft inc. All rights reserved. # # This source code is licensed under Apache 2.0 License, # attached with Common Clause Condition 1.0, found in the LICENSES directory. <def_stmt>__bytes2ul b<block_start><return>int.from_bytes(b byteorder='little' signed=<false>)<block_end><def_stmt>mmh2 bstr seed=0xc70f6907 signed=<true><block_start>MASK=2<power>64-1<line_sep>size=len(bstr)<line_sep>m=0xc6a4a7935bd1e995<line_sep>r=47<line_sep>h=seed^(size<times>m&MASK)<line_sep>end=size&(0xfffffff8)<for_stmt>pos range(0 end 8)<block_start>k=__bytes2ul(bstr[pos:pos+8])<line_sep>k=k<times>m&MASK<line_sep>k=k^(k<rshift>r)<line_sep>k=k<times>m&MASK<line_sep>h=h^k<line_sep>h=h<times>m&MASK<block_end>left=size&0x7<if_stmt>left<ge>7<block_start>h=h^(bstr[end+6]<lshift>48)<block_end><if_stmt>left<ge>6<block_start>h=h^(bstr[end+5]<lshift>40)<block_end><if_stmt>left<ge>5<block_start>h=h^(bstr[end+4]<lshift>32)<block_end><if_stmt>left<ge>4<block_start>h=h^(bstr[end+3]<lshift>24)<block_end><if_stmt>left<ge>3<block_start>h=h^(bstr[end+2]<lshift>16)<block_end><if_stmt>left<ge>2<block_start>h=h^(bstr[end+1]<lshift>8)<block_end><if_stmt>left<ge>1<block_start>h=h^bstr[end+0]<line_sep>h=h<times>m&MASK<block_end>h=h^(h<rshift>r)<line_sep>h=h<times>m&MASK<line_sep>h=h^(h<rshift>r)<if_stmt>signed<block_start>h=h|(-(h&0x8000000000000000))<block_end><return>h<block_end><if_stmt>__name__<eq>'__main__'<block_start><assert_stmt>mmh2(b'hello')<eq>2762169579135187400<assert_stmt>mmh2(b'World')<eq>-295471233978816215<assert_stmt>mmh2(b'Hello World')<eq>2146989006636459346<assert_stmt>mmh2(b'Hello Wo')<eq>-821961639117166431<block_end>
""" categories: Modules,struct description: Struct pack with too few args, not checked by uPy cause: Unknown workaround: Unknown """<import_stmt>struct<try_stmt><block_start>print(struct.pack("bb" 1))<line_sep>print("Should not get here")<block_end><except_stmt><block_start>print("struct.error")<block_end>
<import_from_stmt>.hparams *<import_from_stmt>.logger Logger<line_sep>
<import_from_stmt>time sleep<import_stmt>pandas<as>pd<import_from_stmt>collections OrderedDict<try_stmt><block_start><import_from_stmt>WindPy *<block_end><except_stmt>ImportError<block_start><pass><block_end><import_from_stmt>DyCommon.DyCommon *<import_from_stmt>...Common.DyStockCommon *<class_stmt>DyStockDataWind(object)<block_start>""" Wind数据接口 """<line_sep>sectorCodeWindMap={DyStockCommon.sz50Index:'a00103010b000000' DyStockCommon.hs300Index:'a001030201000000' DyStockCommon.zz500Index:'a001030208000000'}<def_stmt>__init__ self info<block_start>self._info=info<line_sep>self._gateway=w<block_end><def_stmt>getDays self code startDate endDate fields name=<none><block_start>""" @return: df['datetime', indicators] None - errors [] - no data """<if_stmt><not>fields<block_start>self._info.print('没有指定获取的指标' DyLogData.error)<line_sep><return><none><block_end># 添加'volume',由此判断停牌是否 fields_=','.join(fields)<if>'volume'<in>fields<else>','.join(fields+['volume'])<for_stmt>_ range(3)<block_start>windData=self._gateway.wsd(code fields_ startDate endDate)<if_stmt>windData.ErrorCode<ne>0<block_start>errorStr="从Wind获取{0}:{1}, [{2}, {3}]WSD错误: {4}".format(code name startDate endDate windData.Data[0][0])<if_stmt>'Timeout'<in>errorStr<block_start>sleep(1)<line_sep><continue><block_end><block_end><break><block_end><if_stmt>windData.ErrorCode<ne>0<block_start>self._info.print(errorStr DyLogData.error)<line_sep><return><none><block_end><try_stmt><block_start>df=pd.DataFrame(windData.Data index=[x.lower()<for>x windData.Fields] columns=windData.Times)<line_sep>df=df.T<line_sep>df=df.dropna(axis=1 how='all')# 去除全为NaN的列,比如指数数据,没有'mf_vol' df=df.ix[df['volume']<g>0 :]# 去除停牌的数据 <if_stmt>'volume'<not><in>fields<block_start><del_stmt>df['volume']<block_end>df.reset_index(inplace=<true>)# 把时间索引转成列 df.rename(columns={'index':'datetime'} inplace=<true>)<line_sep># 把日期的HH:MM:SS转成 00:00:00 df['datetime']=df['datetime'].map(<lambda>x:x.strftime('%Y-%m-%d'))<line_sep>df['datetime']=pd.to_datetime(df['datetime'] format='%Y-%m-%d')<line_sep>df=df[['datetime']+fields]<block_end><except_stmt><block_start>df=pd.DataFrame(columns=['datetime']+fields)<block_end><return>df<block_end><def_stmt>_login self<block_start><if_stmt><not>self._gateway.isconnected()<block_start>self._info.print("登录Wind...")<line_sep>data=self._gateway.start()<if_stmt>data.ErrorCode<ne>0<block_start>self._info.print("登录Wind失败" DyLogData.error)<line_sep><return><false><block_end>self._info.print("登录Wind成功")<block_end><return><true><block_end><def_stmt>getTradeDays self startDate endDate<block_start><if_stmt><not>self._login()<block_start><return><none><block_end>self._info.print("开始从Wind获取交易日数据[{}, {}]...".format(startDate endDate))<line_sep>data=w.tdayscount(startDate endDate)<if_stmt>data.ErrorCode<eq>0<block_start><if_stmt>data.Data[0][0]<eq>0<block_start><return>[]<block_end># no trade days between startDate and endDate data=self._gateway.tdays(startDate endDate)<if_stmt>data.ErrorCode<eq>0<block_start><return>[x.strftime('%Y-%m-%d')<for>x data.Data[0]]<block_end><block_end>self._info.print("从Wind获取交易日数据失败[{0}, {1}]: {2}".format(startDate endDate data.Data[0][0]) DyLogData.error)<line_sep><return><none><block_end><def_stmt>getStockCodes self<block_start><if_stmt><not>self._login()<block_start><return><none><block_end>self._info.print("开始从Wind获取股票代码表...")<line_sep>date=datetime.today()<line_sep>date=date.strftime("%Y%m%d")<line_sep>data=w.wset("SectorConstituent" "date={0};sectorId=a001010100000000".format(date))<if_stmt>data.ErrorCode<ne>0<block_start>self._info.print("从Wind获取股票代码表失败: {0}!".format(data.Data[0][0]) DyLogData.error)<line_sep><return><none><block_end>codes={}<for_stmt>code,name zip(data.Data[1] data.Data[2])<block_start>codes[code]=name<block_end><return>codes<block_end><def_stmt>getSectorStockCodes self sectorCode startDate endDate<block_start><if_stmt><not>self._login()<block_start><return><none><block_end>self._info.print("开始从Wind获取[{0}]股票代码表[{1}, {2}]...".format(DyStockCommon.sectors[sectorCode] startDate endDate))<line_sep>dates=DyTime.getDates(startDate endDate)<line_sep>progress=DyProgress(self._info)<line_sep>progress.init(len(dates))<line_sep>codesDict=OrderedDict()# {date: {code: name}} <for_stmt>date_ dates<block_start>date=date_.strftime("%Y%m%d")<line_sep>date_=date_.strftime("%Y-%m-%d")<line_sep>data=w.wset("SectorConstituent" "date={0};sectorId={1}".format(date self.sectorCodeWindMap[sectorCode]))<if_stmt>data.ErrorCode<ne>0<block_start>self._info.print("从Wind获取[{0}]股票代码表[{1}]失败: {2}!".format(DyStockCommon.sectors[sectorCode] date_ data.Data[0][0]) DyLogData.error)<line_sep><return><none><block_end>codes={}<if_stmt>data.Data<block_start><for_stmt>code,name zip(data.Data[1] data.Data[2])<block_start>codes[code]=name<block_end><block_end>codesDict[date_]=codes<line_sep>progress.update()<block_end>self._info.print("从Wind获取[{0}]股票代码表[{1}, {2}]完成".format(DyStockCommon.sectors[sectorCode] startDate endDate))<line_sep><return>codesDict<block_end><block_end>
""" This module helps out with generating text using templates """<import_stmt>json<import_stmt>random<import_stmt>re<import_from_stmt>functools lru_cache<import_stmt>tracery<import_from_stmt>tracery.modifiers base_english<import_from_stmt>talkgenerator.sources conceptnet<import_from_stmt>talkgenerator.sources phrasefinder<import_from_stmt>talkgenerator.sources wikihow<import_from_stmt>talkgenerator.util language_util<import_from_stmt>talkgenerator.util os_util<import_from_stmt>talkgenerator.util random_util<line_sep>known_functions={"title":str.title "lower":str.lower "upper":str.upper "dashes":<lambda>words:words.replace(" " "-") "first_letter":<lambda>words:words[0] "last_letter_is_vowel":<lambda>word:word<if>language_util.is_vowel(word[-1])<else><none> "last_letter_is_consonant":<lambda>word:word<if>language_util.is_consonant(word[-1])<else><none> "a":<lambda>word:language_util.add_article(word) "ing":language_util.to_present_participle "plural":language_util.to_plural "singular":language_util.to_singular # "synonym": generator_util.FromListGenerator(language_util.get_synonyms), "2_to_1_pronouns":language_util.second_to_first_pronouns "wikihow_action":<lambda>seed:random_util.choice_optional(wikihow.get_related_wikihow_actions(seed)) "get_last_noun_and_article":language_util.get_last_noun_and_article # Conceptnet "conceptnet_location":conceptnet.weighted_location_generator "conceptnet_related":conceptnet.weighted_related_word_generator "conceptnet_related_single_word":<lambda>word:phrasefinder.get_rarest_word(conceptnet.weighted_related_word_generator(word)) # Checkers "is_noun":<lambda>word:word<if>language_util.is_noun(word)<else><none> "is_verb":<lambda>word:word<if>language_util.is_verb(word)<else><none> # Unique: To make a variable not be the same as something else with the same parameters "unique":<lambda>x:x }<class_stmt>AbstractTextGenerator(object)<block_start><def_stmt>generate self variables_dictionary<block_start><raise>NotImplementedError()<block_end><def_stmt>generate_with_seed self seed<block_start><return>self.generate({"seed":seed})<block_end><block_end><class_stmt>TemplatedTextGenerator(AbstractTextGenerator)<block_start><def_stmt>__init__ self template_file=<none> templates_list=<none><block_start>templates=[]<if_stmt>template_file<block_start>templates.extend(read_lines(template_file))<block_end><if_stmt>templates_list<block_start>templates.extend(templates_list)<block_end># Create a tuple so no templates can accidentally be deleted from the generator self._templates=tuple(templates)<block_end><def_stmt>generate self variables_dictionary=<none><block_start>""" Generates a text from the templates using the given variables dictionary"""<line_sep># Set empty dictionary if none is given <if_stmt><not>bool(variables_dictionary)<block_start>variables_dictionary={}<block_end># Create a mutable copy of the templates list possible_templates=list(self._templates)<for_stmt>i range(len(possible_templates))<block_start>template=random.choice(possible_templates)<if_stmt>can_format_with(template variables_dictionary)<block_start>result=apply_variables_to_template(template variables_dictionary)<if_stmt>result<block_start><return>result<block_end><block_end># Remove the template from the possible templates list, such that it won possible_templates.remove(template)<block_end><block_end><block_end><class_stmt>TraceryTextGenerator(AbstractTextGenerator)<block_start><def_stmt>__init__ self tracery_json variable="origin"<block_start><with_stmt>open(os_util.to_actual_file(tracery_json))<as>grammar_file<block_start>grammar=get_tracery_grammar(grammar_file)<line_sep>grammar.add_modifiers(base_english)<line_sep>self._grammar=grammar<line_sep>self._variable=variable<block_end><block_end><def_stmt>generate self variables_dictionary=<none><block_start>""" Generates a text from internal tracery grammar using the given variables dictionary"""<line_sep># Set empty dictionary if none is given <if_stmt><not>bool(variables_dictionary)<block_start>variables_dictionary={}<block_end># Generate <for_stmt>i range(100)# TODO prune the grammar instead of retrying <block_start>template=self._grammar.flatten("#"+self._variable+"#")<if_stmt>can_format_with(template variables_dictionary)<block_start>result=apply_variables_to_template(template variables_dictionary)<if_stmt>result<block_start><return>result<block_end><block_end><block_end><block_end><block_end>@lru_cache(maxsize=20)<def_stmt>get_tracery_grammar grammar_file<block_start><return>tracery.Grammar(json.load(grammar_file))<block_end><def_stmt>can_format_with template variables_dictionary<block_start>""" Checks if the template can be fully formatted by the given variable dictionary without errors"""<line_sep>format_variables=get_format_variables(template)<line_sep><return>(len(format_variables)<eq>0<and>len(variables_dictionary)<eq>0)<or>set(format_variables)<le>set(variables_dictionary.keys())<block_end><def_stmt>get_format_variables template<block_start>""" Finds all the names of the variables used in the template """<line_sep><return>{x[0]<for>x get_format_variables_and_functions(template)}<block_end><def_stmt>get_format_variables_and_functions template<block_start>""" Finds all the names of the variables used in the template with their functions in a large tuple"""<line_sep>matches=re.findall(r"{(\w+)((?:[.]\w+)*)}" template)<line_sep><return>set(matches)<block_end><def_stmt>apply_variables_to_template template variables_dictionary<block_start>variables_and_functions=get_format_variables_and_functions(template)<line_sep>applied=apply_functions_to_variables(template variables_dictionary variables_and_functions)<if_stmt>applied<block_start>(template variables_dictionary)=applied<line_sep><return>template.format(**variables_dictionary)<block_end><block_end><def_stmt>apply_functions variable functions<block_start>""" Applies a list of functions to a variable """<line_sep>result=variable<for_stmt>func functions# Check if it transformed the result into None <block_start><if_stmt>result<is><none><block_start><return><none><block_end><if_stmt>func<in>known_functions<block_start>result=known_functions[func](result)<block_end># Check if it is a dictionary, as is allowed in real str.format <elif_stmt>isinstance(result dict)<and>func<in>result<block_start>result=result[func]<block_end># Unique identifier to make similar functions on a variable have different effects <elif_stmt>func.isdigit()<block_start>result=result<block_end><else_stmt><block_start><raise>ValueError("Unknown function:" func)<block_end><block_end><return>result<block_end><def_stmt>apply_functions_to_variables template variables_dictionary variables_and_functions<block_start>""" Applies the functions of the variables_and_functions tuple and stores them in the variable dictionary and updates the template """<line_sep>variables_and_functions=list(variables_and_functions)<line_sep>variables_and_functions.sort(key=<lambda>a:len(a) reverse=<true>)<for_stmt>var_func variables_and_functions# Check if it has functions to apply <block_start><if_stmt>len(var_func)<g>1<and>len(var_func[1])<g>0<block_start>old_var_name=var_func[0]+var_func[1]<line_sep>functions=var_func[1][1:].split(".")<line_sep>variable_name=var_func[0]<line_sep>variable=variables_dictionary[variable_name]<line_sep>applied_functions=apply_functions(variable functions)<if_stmt>applied_functions<is><not><none><block_start>applied_var_name=old_var_name.replace("." "_")<line_sep># Replace all occurrences with the dot to the underscore notation template=template.replace(old_var_name applied_var_name)<line_sep># Store in dictionary variables_dictionary[applied_var_name]=applied_functions<block_end><else_stmt><block_start><return><none><block_end><block_end><block_end><return>template variables_dictionary<block_end><def_stmt>read_lines filename<block_start>""" Reads all the string lines from a file """<line_sep><return>os_util.read_lines(filename)<block_end>
<import_from_stmt>enum Enum<class_stmt>NotificationEnum(Enum)<block_start>config_refresh=1<line_sep>config_refresh_finished=2<line_sep>config_refresh_failed=3<line_sep>process_stop=4<line_sep>process_pause=5<line_sep>process_continue=6<block_end>
# Copyright 2018 Google Inc. # # 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_stmt>io<import_stmt>logging<import_stmt>os<import_stmt>time<import_from_stmt>mobly logger<as>mobly_logger<import_from_stmt>mobly utils<import_from_stmt>mobly.controllers.android_device_lib adb<import_from_stmt>mobly.controllers.android_device_lib errors<import_from_stmt>mobly.controllers.android_device_lib.services base_service<line_sep>CREATE_LOGCAT_FILE_TIMEOUT_SEC=5<class_stmt>Error(errors.ServiceError)<block_start>"""Root error type for logcat service."""<line_sep>SERVICE_TYPE='Logcat'<block_end><class_stmt>Config<block_start>"""Config object for logcat service. Attributes: clear_log: bool, clears the logcat before collection if True. logcat_params: string, extra params to be added to logcat command. output_file_path: string, the path on the host to write the log file to, including the actual filename. The service will automatically generate one if not specified. """<def_stmt>__init__ self logcat_params=<none> clear_log=<true> output_file_path=<none><block_start>self.clear_log=clear_log<line_sep>self.logcat_params=logcat_params<if>logcat_params<else>''<line_sep>self.output_file_path=output_file_path<block_end><block_end><class_stmt>Logcat(base_service.BaseService)<block_start>"""Android logcat service for Mobly's AndroidDevice controller. Attributes: adb_logcat_file_path: string, path to the file that the service writes adb logcat to by default. """<line_sep>OUTPUT_FILE_TYPE='logcat'<def_stmt>__init__ self android_device configs=<none><block_start>super().__init__(android_device configs)<line_sep>self._ad=android_device<line_sep>self._adb_logcat_process=<none><line_sep>self._adb_logcat_file_obj=<none><line_sep>self.adb_logcat_file_path=<none><line_sep># Logcat service uses a single config obj, using singular internal # name: `_config`. self._config=configs<if>configs<else>Config()<block_end><def_stmt>_enable_logpersist self<block_start>"""Attempts to enable logpersist daemon to persist logs."""<line_sep># Logpersist is only allowed on rootable devices because of excessive # reads/writes for persisting logs. <if_stmt><not>self._ad.is_rootable<block_start><return><block_end>logpersist_warning=('%s encountered an error enabling persistent'<concat>' logs, logs may not get saved.')<line_sep># Android L and older versions do not have logpersist installed, # so check that the logpersist scripts exists before trying to use # them. <if_stmt><not>self._ad.adb.has_shell_command('logpersist.start')<block_start>logging.warning(logpersist_warning self)<line_sep><return><block_end><try_stmt># Disable adb log spam filter for rootable devices. Have to stop # and clear settings first because 'start' doesn't support --clear # option before Android N. <block_start>self._ad.adb.shell('logpersist.stop --clear')<line_sep>self._ad.adb.shell('logpersist.start')<block_end><except_stmt>adb.AdbError<block_start>logging.warning(logpersist_warning self)<block_end><block_end><def_stmt>_is_timestamp_in_range self target begin_time end_time<block_start>low=mobly_logger.logline_timestamp_comparator(begin_time target)<le>0<line_sep>high=mobly_logger.logline_timestamp_comparator(end_time target)<ge>0<line_sep><return>low<and>high<block_end><def_stmt>create_output_excerpts self test_info<block_start>"""Convenient method for creating excerpts of adb logcat. This copies logcat lines from self.adb_logcat_file_path to an excerpt file, starting from the location where the previous excerpt ended. Call this method at the end of: `setup_class`, `teardown_test`, and `teardown_class`. Args: test_info: `self.current_test_info` in a Mobly test. Returns: List of strings, the absolute paths to excerpt files. """<line_sep>dest_path=test_info.output_path<line_sep>utils.create_dir(dest_path)<line_sep>filename=self._ad.generate_filename(self.OUTPUT_FILE_TYPE test_info 'txt')<line_sep>excerpt_file_path=os.path.join(dest_path filename)<with_stmt>io.open(excerpt_file_path 'w' encoding='utf-8' errors='replace')<as>out# Devices may accidentally go offline during test, # check not None before readline(). <block_start><while_stmt>self._adb_logcat_file_obj<block_start>line=self._adb_logcat_file_obj.readline()<if_stmt><not>line<block_start><break><block_end>out.write(line)<block_end><block_end>self._ad.log.debug('logcat excerpt created at: %s' excerpt_file_path)<line_sep><return>[excerpt_file_path]<block_end>@property<def_stmt>is_alive self<block_start><return><true><if>self._adb_logcat_process<else><false><block_end><def_stmt>clear_adb_log self<block_start>"""Clears cached adb content."""<try_stmt><block_start>self._ad.adb.logcat('-c')<block_end><except_stmt>adb.AdbError<as>e# On Android O, the clear command fails due to a known bug. # Catching this so we don't crash from this Android issue. <block_start><if_stmt>b'failed to clear'<in>e.stderr<block_start>self._ad.log.warning('Encountered known Android error to clear logcat.')<block_end><else_stmt><block_start><raise><block_end><block_end><block_end><def_stmt>_assert_not_running self<block_start>"""Asserts the logcat service is not running. Raises: Error, if the logcat service is running. """<if_stmt>self.is_alive<block_start><raise>Error(self._ad 'Logcat thread is already running, cannot start another one.')<block_end><block_end><def_stmt>update_config self new_config<block_start>"""Updates the configuration for the service. The service needs to be stopped before updating, and explicitly started after the update. This will reset the service. Previous output files may be orphaned if output path is changed. Args: new_config: Config, the new config to use. """<line_sep>self._assert_not_running()<line_sep>self._ad.log.info('[LogcatService] Changing config from %s to %s' self._config new_config)<line_sep>self._config=new_config<block_end><def_stmt>_open_logcat_file self<block_start>"""Create a file object that points to the beginning of the logcat file. Wait for the logcat file to be created by the subprocess if it doesn't exist. """<if_stmt><not>self._adb_logcat_file_obj<block_start>deadline=time.perf_counter()+CREATE_LOGCAT_FILE_TIMEOUT_SEC<while_stmt><not>os.path.exists(self.adb_logcat_file_path)<block_start><if_stmt>time.perf_counter()<g>deadline<block_start><raise>Error(self._ad 'Timeout while waiting for logcat file to be created.')<block_end>time.sleep(1)<block_end>self._adb_logcat_file_obj=io.open(self.adb_logcat_file_path 'r' encoding='utf-8' errors='replace')<line_sep>self._adb_logcat_file_obj.seek(0 os.SEEK_END)<block_end><block_end><def_stmt>_close_logcat_file self<block_start>"""Closes and resets the logcat file object, if it exists."""<if_stmt>self._adb_logcat_file_obj<block_start>self._adb_logcat_file_obj.close()<line_sep>self._adb_logcat_file_obj=<none><block_end><block_end><def_stmt>start self<block_start>"""Starts a standing adb logcat collection. The collection runs in a separate subprocess and saves logs in a file. """<line_sep>self._assert_not_running()<if_stmt>self._config.clear_log<block_start>self.clear_adb_log()<block_end>self._start()<line_sep>self._open_logcat_file()<block_end><def_stmt>_start self<block_start>"""The actual logic of starting logcat."""<line_sep>self._enable_logpersist()<if_stmt>self._config.output_file_path<block_start>self._close_logcat_file()<line_sep>self.adb_logcat_file_path=self._config.output_file_path<block_end><if_stmt><not>self.adb_logcat_file_path<block_start>f_name=self._ad.generate_filename(self.OUTPUT_FILE_TYPE extension_name='txt')<line_sep>logcat_file_path=os.path.join(self._ad.log_path f_name)<line_sep>self.adb_logcat_file_path=logcat_file_path<block_end>utils.create_dir(os.path.dirname(self.adb_logcat_file_path))<line_sep># In debugging mode of IntelijIDEA, "patch_args" remove # double quotes in args if starting and ending with it. # Add spaces at beginning and at last to fix this issue. cmd=' "%s" -s %s logcat -v threadtime -T 1 %s >> "%s" '%(adb.ADB self._ad.serial self._config.logcat_params self.adb_logcat_file_path)<line_sep>process=utils.start_standing_subprocess(cmd shell=<true>)<line_sep>self._adb_logcat_process=process<block_end><def_stmt>stop self<block_start>"""Stops the adb logcat service."""<line_sep>self._close_logcat_file()<line_sep>self._stop()<block_end><def_stmt>_stop self<block_start>"""Stops the background process for logcat."""<if_stmt><not>self._adb_logcat_process<block_start><return><block_end><try_stmt><block_start>utils.stop_standing_subprocess(self._adb_logcat_process)<block_end><except_stmt>Exception<block_start>self._ad.log.exception('Failed to stop adb logcat.')<block_end>self._adb_logcat_process=<none><block_end><def_stmt>pause self<block_start>"""Pauses logcat. Note: the service is unable to collect the logs when paused, if more logs are generated on the device than the device's log buffer can hold, some logs would be lost. """<line_sep>self._stop()<block_end><def_stmt>resume self<block_start>"""Resumes a paused logcat service."""<line_sep>self._assert_not_running()<line_sep># Not clearing the log regardless of the config when resuming. # Otherwise the logs during the paused time will be lost. self._start()<block_end><block_end>
<class_stmt>HandledEventArgs(EventArgs)<block_start>""" Provides data for events that can be handled completely in an event handler. HandledEventArgs() HandledEventArgs(defaultHandledValue: bool) """<line_sep>@staticmethod<def_stmt>__new__ self defaultHandledValue=<none><block_start>""" __new__(cls: type) __new__(cls: type,defaultHandledValue: bool) """<line_sep><pass><block_end>Handled=property(<lambda>self:object() <lambda>self v:<none> <lambda>self:<none>)<line_sep>"""Gets or sets a value that indicates whether the event handler has completely handled the event or whether the system should continue its own processing. Get: Handled(self: HandledEventArgs) -> bool Set: Handled(self: HandledEventArgs)=value """<block_end>
<import_stmt>copy<import_stmt>errno<import_stmt>os<import_stmt>logging<import_stmt>math<import_stmt>torch<import_from_stmt>torch nn<import_stmt>torch.nn.functional<as>F<import_from_stmt>torch.nn.parallel DistributedDataParallel<import_from_stmt>.helper TensorBoardWriter<import_from_stmt>.linear_eval iter_eval_epoch linear_eval_online linear_eval_offline<import_from_stmt>data get_loaders_for_trainer<import_from_stmt>models Backbone<import_from_stmt>models.heads SingleLayerLinearHead TwoLayerLinearHead<import_from_stmt>optim get_optimizer_and_scheduler<import_stmt>utils<line_sep>log=logging.getLogger('main')<line_sep>C=utils.Colorer.instance()<def_stmt>_unwrap wrapped_module<block_start><if_stmt>isinstance(wrapped_module DistributedDataParallel)<block_start>module=wrapped_module.module<block_end><else_stmt><block_start>module=wrapped_module<block_end><return>module<block_end><def_stmt>_regression_loss x y# eps = 1e-6 if torch.is_autocast_enabled() else 1e-12 <block_start>x=F.normalize(x p=2 dim=1)#, eps=eps) y=F.normalize(y p=2 dim=1)#, eps=eps) <return>(2-2<times>(x<times>y).sum(dim=1)).view(-1)<block_end><class_stmt>BYOLBasedTrainer<block_start>"""This trainer supports BYOL-like training framework that can be subclassed by other task-specific trainer classes. To specify a detailed algorithm, the user should implement Traniner.run(). """<def_stmt>__init__ self cfg online_network target_network predictor=<none> evaluator=<none> train_loader=<none> eval_loader=<none><block_start><if_stmt>cfg.train.enabled<block_start><assert_stmt>train_loader<is><not><none><assert_stmt>predictor<is><not><none><block_end><if_stmt>cfg.train.enabled<and>cfg.train.online_eval<block_start><assert_stmt>eval_loader<is><not><none><assert_stmt>evaluator<is><not><none><block_end>self._modules={}<line_sep>self._saving_targets={}<line_sep>self.cfg=cfg<line_sep>self.device=cfg.device<line_sep>self.online_network=online_network<line_sep>self.target_network=target_network<line_sep>self.predictor=predictor<line_sep>self.evaluator=evaluator<line_sep>self.xent_loss=nn.CrossEntropyLoss()<line_sep>self.train_loader=train_loader<line_sep>self.eval_loader=eval_loader<line_sep>self._setup_device_and_distributed_parallel(cfg.device)<line_sep>self.cur_epoch=0<line_sep>self.max_epochs=0<line_sep>self.max_eval_score=0.<line_sep>self.max_eval_epoch=0<if_stmt>self.cfg.train.enabled<block_start>self.m_base=self.m=cfg.train.m<line_sep>self.max_epochs=cfg.train.max_epochs<line_sep>self.total_global_step=len(train_loader)<times>cfg.train.max_epochs<line_sep>self.optimizer,self.scheduler=get_optimizer_and_scheduler(cfg=self.cfg mode='train' modules=self._modules loader=train_loader exclude_from_lars=<true> module_black_list=['target_network'])<line_sep>self.scaler=torch.cuda.amp.GradScaler()#init_scale=2**14) # default init_scale 2**16 will yield invalid gradient in the first interation self.tb_writer=TensorBoardWriter.init_for_train_from_config(cfg)<block_end><else_stmt><block_start>self.optimizer,self.scheduler,self.scaler=<none> <none> <none><block_end><block_end><def_stmt>__setattr__ self name value<block_start><if_stmt>hasattr(value 'state_dict')<and>callable(value.state_dict)<block_start>self._saving_targets[name]=value# including optimzers & schedulers <block_end><if_stmt>isinstance(value nn.Module)<block_start>self._modules[name]=value<block_end>object.__setattr__(self name value)<block_end><def_stmt>run self<block_start>"""Main training algorithm should be implemented in this method."""<line_sep><raise>NotImplementedError()<block_end>@classmethod<def_stmt>init_from_config cls cfg<block_start>train_loader,eval_loader,num_classes=get_loaders_for_trainer(cfg)<line_sep>online_network=Backbone.init_from_config(cfg)<line_sep>target_network,predictor,evaluator=<none> <none> <none><if_stmt>cfg.train.enabled<block_start>target_network=Backbone.init_from_config(cfg)<line_sep>predictor=TwoLayerLinearHead.init_predictor_from_config(cfg)<line_sep>evaluator=SingleLayerLinearHead.init_evaluator_from_config(cfg num_classes)<block_end><return>cls(cfg=cfg train_loader=train_loader eval_loader=eval_loader online_network=online_network target_network=target_network predictor=predictor evaluator=evaluator )<block_end><def_stmt>_setup_device_and_distributed_parallel self device<block_start><for_stmt>name,module self._modules.items()<block_start>module=module.to(device)<line_sep>module=utils.wrap_if_distributed(module device)<line_sep>self._modules[name]=module<line_sep>object.__setattr__(self name module)<block_end><block_end>@torch.no_grad()<def_stmt>_update_target_network_parameters self<block_start>""" Momentum update of the key encoder """<for_stmt>param_q,param_k zip(self.online_network.parameters() self.target_network.parameters())<block_start>param_k.data=param_k.data<times>self.m+param_q.data<times>(1.-self.m)<block_end><block_end><def_stmt>_decay_ema_momentum self step<block_start>self.m=(1-(1-self.m_base)<times>(math.cos(math.pi<times>step/self.total_global_step)+1)/2)<block_end>@staticmethod<def_stmt>_criterion p_online p_target<block_start>"""Regression loss used in BYOL."""<line_sep>p_online_v1,p_online_v2=p_online.chunk(2)<line_sep>p_target_v1,p_target_v2=p_target.chunk(2)<assert_stmt>p_online_v1.size(0)<eq>p_online_v2.size(0)<assert_stmt>p_target_v1.size(0)<eq>p_target_v2.size(0)<assert_stmt>p_online_v1.size(0)<eq>p_target_v1.size(0)<line_sep># symmetric loss loss=_regression_loss(p_online_v1 p_target_v2)<line_sep>loss<augadd>_regression_loss(p_online_v2 p_target_v1)<line_sep><return>loss.mean()<block_end><def_stmt>_initialize_target_network self from_online# init momentum network as encoder net <block_start><for_stmt>param_q,param_k zip(self.online_network.parameters() self.target_network.parameters())<block_start><if_stmt>from_online<block_start>param_k.data.copy_(param_q.data)# initialize <block_end>param_k.requires_grad=<false><block_end><block_end># not update by gradient <def_stmt>_save_checkpoint self tag<block_start>save_path=f"{self.cfg.save_dir}/checkpoint_"+str(tag)+".pth"<line_sep>state_dict={'tag':str(tag) 'epoch':self.cur_epoch 'max_eval_score':self.max_eval_score 'max_eval_epoch':self.max_eval_epoch }<for_stmt>key,target self._saving_targets.items()<block_start><if_stmt>self.cfg.fake_checkpoint<block_start>target="fake_state_dict"<block_end><else_stmt><block_start>target=utils.unwrap_if_distributed(target)<line_sep>target=target.state_dict()<block_end>state_dict[f"{key}_state_dict"]=target<block_end>torch.save(state_dict save_path)<line_sep>suffix=(C.debug(" (fake_checkpoint)")<if>self.cfg.fake_checkpoint<else>"")<line_sep><return>save_path+suffix<block_end><def_stmt>save_checkpoint self epoch<block_start>save_path=self._save_checkpoint(str(epoch))<line_sep>log.info(f"[Save] restore the model's checkpoint: {save_path}")<line_sep><return>save_path<block_end><def_stmt>save_best_checkpoint self<block_start>save_path=self._save_checkpoint('best')<line_sep>log.info(f"[Save] restore the best model's checkpoint: {save_path}")<line_sep><return>save_path<block_end><def_stmt>symlink_checkpoint_with_tag self epoch tag<block_start>save_path=f"{self.cfg.save_dir}/checkpoint_{epoch}.pth"<line_sep>symlink_path=f"{self.cfg.save_dir}/checkpoint_{tag}.pth"<if_stmt><not>os.path.exists(save_path)<block_start>self._save_checkpoint(epoch)<block_end><try_stmt><block_start>os.symlink(os.path.abspath(save_path) symlink_path)<block_end><except_stmt>OSError<as>e<block_start><if_stmt>e.errno<eq>errno.EEXIST<block_start>os.remove(symlink_path)<line_sep>os.symlink(os.path.abspath(save_path) symlink_path)<block_end><else_stmt><block_start><raise>e<block_end><block_end><finally_stmt><block_start>log.info(f"[Save] make a symlink of the current model: "<concat>f"{symlink_path}")<block_end><return>symlink_path<block_end><def_stmt>load_checkpoint_if_available self tag='last'<block_start><if_stmt>self.cfg.overwrite<block_start><assert_stmt><not>self.cfg.load_dir "Mutually exclusive aruguements: overwrite, load_dir."<line_sep>log.warning("Overwrite checkpoints in save_dir.")<line_sep><return><false><block_end><try_stmt><block_start>load_dir=self.cfg.load_dir<or>self.cfg.save_dir<line_sep>load_path=f"{load_dir}/checkpoint_{tag}.pth"<line_sep>state_dict=torch.load(load_path)<block_end><except_stmt>FileNotFoundError<block_start><if_stmt>self.cfg.load_dir<block_start><raise>FileNotFoundError(f"Can't find checkpoint at {load_dir}")<block_end><else_stmt><block_start>log.warning(f'No checkpoint to resume from {load_dir}.')<block_end><return><false><block_end>self.cur_epoch=state_dict['epoch']<line_sep>self.max_eval_score=state_dict['max_eval_score']<line_sep>self.max_eval_epoch=state_dict['max_eval_epoch']<line_sep>state_dict={k[:-len('_state_dict')]:v<for>k,v state_dict.items()<if>k.endswith('_state_dict')}<line_sep>log.info(f"[Resume] Loaded chekpoint (epoch: {self.cur_epoch}) "<concat>f"from: {load_path}")<line_sep>missing_keys=set(self._saving_targets.keys())-set(state_dict.keys())<line_sep>unexpected_keys=set(state_dict.keys())-set(self._saving_targets.keys())<assert_stmt>len(missing_keys)<eq>0 "Missing keys!"<line_sep>log.info("[Resume] Redundant keys: "<concat>f"{list(unexpected_keys)<if>unexpected_keys<else>'None'}")<for_stmt>key,target self._saving_targets.items()<block_start><if_stmt>state_dict[key]<eq>'fake_state_dict'<block_start>log.info(f"[Resume] Loaded {key}: {C.debug('(fake_chekpoint)')}")<block_end><else_stmt><block_start>kwargs={'strict':<false>}<if>isinstance(target nn.Module)<else>{}<line_sep>loaded=_unwrap(target).load_state_dict(state_dict[key] **kwargs)<if_stmt>isinstance(target nn.Module)<block_start><assert_stmt>len(loaded.missing_keys)<eq>0<block_end><if_stmt>isinstance(target Backbone)# the projector is be ignored in evaluation-only cases <block_start><assert_stmt>all([key.startswith('projector.')<for>key loaded.unexpected_keys])<block_end>log.info(f"[Resume] Loaded {key}")<block_end><block_end><return><true><block_end><block_end>
# coding=utf-8 # Copyright 2019 The SEED Authors # 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. """Parametric distributions over action spaces."""<import_stmt>abc<import_from_stmt>typing Callable<import_stmt>dataclasses<import_stmt>gym<import_stmt>tensorflow<as>tf<import_stmt>tensorflow_probability<as>tfp<import_from_stmt>tensorflow_probability.python.distributions kullback_leibler<line_sep>tfb=tfp.bijectors<line_sep>tfd=tfp.distributions<class_stmt>ParametricDistribution(abc.ABC)<block_start>"""Abstract class for parametric (action) distribution."""<def_stmt>__init__ self param_size create_dist<block_start>"""Abstract class for parametric (action) distribution. Specifies how to transform distribution parameters (i.e. actor output) into a distribution over actions. Args: param_size: Size of the parameters for the distribution create_dist: Function from parameters to tf Distribution. """<line_sep>self._param_size=param_size<line_sep>self._create_dist=create_dist<block_end>@property<def_stmt>create_dist self<block_start><return>self._create_dist<block_end><def_stmt>__call__ self params<block_start><return>self.create_dist(params)<block_end>@property<def_stmt>param_size self<block_start><return>self._param_size<block_end>@property<def_stmt>reparametrizable self<block_start><return>self._create_dist(tf.zeros((self._param_size ))).reparameterization_type<eq>tfd.FULLY_REPARAMETERIZED<block_end><def_stmt>sample self parameters<block_start><return>self._create_dist(parameters).sample()<block_end><def_stmt>log_prob self parameters actions<block_start><return>self._create_dist(parameters).log_prob(actions)<block_end><def_stmt>entropy self parameters<block_start>"""Return the entropy of the given distribution."""<line_sep><return>self._create_dist(parameters).entropy()<block_end><def_stmt>kl_divergence self parameters_a parameters_b<block_start>"""Return KL divergence between the two distributions."""<line_sep>dist_a=self._create_dist(parameters_a)<line_sep>dist_b=self._create_dist(parameters_b)<line_sep><return>tfd.kl_divergence(dist_a dist_b)<block_end><block_end><def_stmt>categorical_distribution n_actions dtype<block_start>"""Initialize the categorical distribution. Args: n_actions: the number of actions available. dtype: dtype of actions, usually int32 or int64. Returns: A tuple (param size, fn(params) -> distribution) """<def_stmt>create_dist parameters<block_start><return>tfd.Categorical(logits=parameters dtype=dtype)<block_end><return>ParametricDistribution(n_actions create_dist)<block_end><def_stmt>multi_categorical_distribution n_dimensions n_actions_per_dim dtype<block_start>"""Initialize the categorical distribution. Args: n_dimensions: the dimensionality of actions. n_actions_per_dim: number of actions available per dimension. dtype: dtype of actions, usually int32 or int64. Returns: A tuple (param size, fn(params) -> distribution) """<def_stmt>create_dist parameters<block_start>batch_shape=parameters.shape[:-1]<line_sep>logits_shape=[n_dimensions n_actions_per_dim]<line_sep>logits=tf.reshape(parameters batch_shape+logits_shape)<line_sep><return>tfd.Independent(tfd.Categorical(logits=logits dtype=dtype) reinterpreted_batch_ndims=1)<block_end><return>ParametricDistribution(n_dimensions<times>n_actions_per_dim create_dist)<block_end># NB: This distribution has no gradient w.r.t the action close to boundaries. <class_stmt>TanhTransformedDistribution(tfd.TransformedDistribution)<block_start>"""Distribution followed by tanh."""<def_stmt>__init__ self distribution threshold=.999 validate_args=<false><block_start>"""Initialize the distribution. Args: distribution: The distribution to transform. threshold: Clipping value of the action when computing the logprob. validate_args: Passed to super class. """<line_sep>super().__init__(distribution=distribution bijector=tfp.bijectors.Tanh() validate_args=validate_args)<line_sep># Computes the log of the average probability distribution outside the # clipping range, i.e. on the interval [-inf, -atanh(threshold)] for # log_prob_left and [atanh(threshold), inf] for log_prob_right. self._threshold=threshold<line_sep>inverse_threshold=self.bijector.inverse(threshold)<line_sep># Let epsilon = 1 - threshold # average(pdf) on [threshold, 1] = probability([threshold, 1])/epsilon # So log(average(pdf)) = log(probability) - log(epsilon) log_epsilon=tf.math.log(1.-threshold)<line_sep># Those 2 values are differentiable w.r.t. model parameters, such that the # gradient is defined everywhere. # There won't be any gradient w.r.t the action though. self._log_prob_left=self.distribution.log_cdf(-inverse_threshold)-log_epsilon<line_sep>self._log_prob_right=self.distribution.log_survival_function(inverse_threshold)-log_epsilon<block_end><def_stmt>log_prob self event# Without this clip there would be NaNs in the inner tf.where and that # causes issues for some reasons. <block_start>event=tf.clip_by_value(event -self._threshold self._threshold)<line_sep># The inverse image of {threshold} is the interval [atanh(threshold), inf] # which has a probability of "log_prob_right" under the given distribution. <return>tf.where(event<le>-self._threshold self._log_prob_left tf.where(event<ge>self._threshold self._log_prob_right super().log_prob(event)))<block_end><def_stmt>mode self<block_start><return>self.bijector.forward(self.distribution.mode())<block_end><def_stmt>mean self<block_start><return>self.bijector.forward(self.distribution.mean())<block_end><def_stmt>entropy self seed=<none># We return an estimation using a single sample of the log_det_jacobian. # We can still do some backpropagation with this estimate. <block_start><return>self.distribution.entropy()+self.bijector.forward_log_det_jacobian(self.distribution.sample(seed=seed) event_ndims=0)<block_end><block_end>@kullback_leibler.RegisterKL(TanhTransformedDistribution TanhTransformedDistribution)<def_stmt>_kl_transformed a b name='kl_transformed'<block_start><return>kullback_leibler.kl_divergence(a.distribution b.distribution name=name)<block_end><def_stmt>softplus_default_std_fn scale<block_start><return>tf.nn.softplus(scale)+1e-3<block_end><def_stmt>normal_tanh_distribution num_actions gaussian_std_fn=softplus_default_std_fn<block_start>"""Normal distribution postprocessed by a tanh."""<def_stmt>create_dist parameters<block_start>loc,scale=tf.split(parameters 2 axis=-1)<line_sep>scale=gaussian_std_fn(scale)<line_sep>normal_dist=tfd.Normal(loc=loc scale=scale)<line_sep><return>tfd.Independent(TanhTransformedDistribution(normal_dist) reinterpreted_batch_ndims=1)<block_end><return>ParametricDistribution(2<times>num_actions create_dist)<block_end><class_stmt>ClippedIdentity(tfb.identity.Identity)<block_start>"""Compute Y = clip_by_value(X, -1, 1). Note that we do not override `is_injective` despite this bijector not being injective, to not disable Identity's `forward_log_det_jacobian`. See also tensorflow_probability.bijectors.identity.Identity. """<def_stmt>__init__ self validate_args=<false> name='clipped_identity'<block_start><with_stmt>tf.name_scope(name)<as>name<block_start>super(ClippedIdentity self).__init__(validate_args=validate_args name=name)<block_end><block_end>@classmethod<def_stmt>_is_increasing cls<block_start><return><false><block_end><def_stmt>_forward self x<block_start><return>tf.clip_by_value(x -1. 1.)<block_end><block_end>CLIPPED_IDENTITY=ClippedIdentity()<def_stmt>normal_clipped_distribution num_actions gaussian_std_fn=softplus_default_std_fn<block_start>"""Normal distribution postprocessed by a clipped identity."""<def_stmt>create_dist parameters<block_start>loc,scale=tf.split(parameters 2 axis=-1)<line_sep>scale=gaussian_std_fn(scale)<line_sep>normal_dist=tfd.Normal(loc=loc scale=scale)<line_sep><return>tfd.Independent(CLIPPED_IDENTITY(normal_dist) reinterpreted_batch_ndims=1)<block_end><return>ParametricDistribution(2<times>num_actions create_dist)<block_end><def_stmt>deterministic_tanh_distribution num_actions<block_start><def_stmt>create_dist parameters<block_start><return>tfd.Independent(TanhTransformedDistribution(tfd.Deterministic(loc=parameters)) reinterpreted_batch_ndims=1)<block_end><return>ParametricDistribution(num_actions create_dist)<block_end><def_stmt>joint_distribution parametric_distributions dtype_override=tf.float32<block_start>"""Initialize the distribution. Args: parametric_distributions: A list of ParametricDistributions. dtype_override: The type to output the actions in. Returns: A tuple (param size, fn(params) -> distribution) """<line_sep>param_sizes=[dist.param_size<for>dist parametric_distributions]<def_stmt>create_dist parameters<block_start>split_params=tf.split(parameters param_sizes axis=-1)<line_sep>dists=[dist(param)<for>(dist param) zip(parametric_distributions split_params)]<line_sep><return>tfd.Blockwise(dists dtype_override=dtype_override)<block_end><return>ParametricDistribution(sum(param_sizes) create_dist)<block_end><def_stmt>check_multi_discrete_space space<block_start><if_stmt>min(space.nvec)<ne>max(space.nvec)<block_start><raise>ValueError('space nvec must be constant: {}'.format(space.nvec))<block_end><block_end><def_stmt>check_box_space space<block_start><assert_stmt>len(space.shape)<eq>1 space.shape<if_stmt>any(l<ne>-1<for>l space.low)<block_start><raise>ValueError(f'Learner only supports actions bounded to [-1,1]: {space.low}')<block_end><if_stmt>any(h<ne>1<for>h space.high)<block_start><raise>ValueError(f'Learner only supports actions bounded to [-1,1]: {space.high}')<block_end><block_end><def_stmt>get_parametric_distribution_for_action_space action_space continuous_config=<none><block_start>"""Returns an action distribution parametrization based on the action space. Args: action_space: action space of the environment continuous_config: Configuration for the continuous action distribution (used when needed by the action space).. """<if_stmt>isinstance(action_space gym.spaces.Discrete)<block_start><return>categorical_distribution(action_space.n dtype=action_space.dtype)<block_end><elif_stmt>isinstance(action_space gym.spaces.MultiDiscrete)<block_start>check_multi_discrete_space(action_space)<line_sep><return>multi_categorical_distribution(n_dimensions=len(action_space.nvec) n_actions_per_dim=action_space.nvec[0] dtype=action_space.dtype)<block_end><elif_stmt>isinstance(action_space gym.spaces.Box)# continuous actions <block_start>check_box_space(action_space)<if_stmt>continuous_config<is><none><block_start>continuous_config=ContinuousDistributionConfig()<block_end><if_stmt>continuous_config.postprocessor<eq>'Tanh'<block_start><return>normal_tanh_distribution(num_actions=action_space.shape[0] gaussian_std_fn=continuous_config.gaussian_std_fn)<block_end><elif_stmt>continuous_config.postprocessor<eq>'ClippedIdentity'<block_start><return>normal_clipped_distribution(num_actions=action_space.shape[0] gaussian_std_fn=continuous_config.gaussian_std_fn)<block_end><else_stmt><block_start><raise>ValueError(f'Postprocessor {continuous_config.postprocessor} not supported.')<block_end><block_end><elif_stmt>isinstance(action_space gym.spaces.Tuple)# mixed actions <block_start><return>joint_distribution([get_parametric_distribution_for_action_space(subspace continuous_config)<for>subspace action_space])<block_end><else_stmt><block_start><raise>ValueError(f'Unsupported action space {action_space}')<block_end><block_end>@tf.custom_gradient<def_stmt>safe_exp x<block_start>e=tf.exp(tf.clip_by_value(x -15 15))<def_stmt>grad dy<block_start><return>dy<times>e<block_end><return>e grad<block_end><def_stmt>safe_exp_std_fn std_for_zero_param:float min_std<block_start>std_shift=tf.math.log(std_for_zero_param-min_std)<line_sep>fn=<lambda>scale:safe_exp(scale+std_shift)+min_std<assert_stmt>abs(fn(0)-std_for_zero_param)<l>1e-3<line_sep><return>fn<block_end><def_stmt>softplus_std_fn std_for_zero_param:float min_std:float<block_start>std_shift=tfp.math.softplus_inverse(std_for_zero_param-min_std)<line_sep>fn=<lambda>scale:tf.nn.softplus(scale+std_shift)+min_std<assert_stmt>abs(fn(0)-std_for_zero_param)<l>1e-3<line_sep><return>fn<block_end>@dataclasses.dataclass<class_stmt>ContinuousDistributionConfig(object)<block_start>"""Configuration for continuous distributions. Currently, only NormalSquashedDistribution is supported. The default configuration corresponds to a normal distribution (with standard deviation computed from params using an unshifted softplus offset by 1e-3), followed by tanh. """<line_sep># Transforms parameters into non-negative values for standard deviation of the # gaussian. gaussian_std_fn:Callable[[tf.Tensor] tf.Tensor]=softplus_default_std_fn<line_sep># The squashing postprocessor. # Accepted values are Tanh and ClippedIdentity. postprocessor:str='Tanh'<block_end><def_stmt>continuous_action_config action_min_gaussian_std:float=1e-3 action_gaussian_std_fn:str='softplus' action_std_for_zero_param:float=1 action_postprocessor:str='Tanh'<arrow>ContinuousDistributionConfig<block_start>"""Configures continuous distributions from numerical and string inputs. Currently, only NormalSquashedDistribution is supported. The default configuration corresponds to a normal distribution with standard deviation computed from params using an unshifted softplus, followed by tanh. Args: action_min_gaussian_std: minimal standard deviation. action_gaussian_std_fn: transform for standard deviation parameters. action_std_for_zero_param: shifts the transform to get this std when parameters are zero. action_postprocessor: the non-linearity applied to the sample from the gaussian. Returns: A continuous distribution setup, with the parameters transform to get the standard deviation applied with a shift, as configured. """<line_sep>config=ContinuousDistributionConfig()<line_sep>config.min_gaussian_std=float(action_min_gaussian_std)<if_stmt>action_gaussian_std_fn<eq>'safe_exp'<block_start>config.gaussian_std_fn=safe_exp_std_fn(action_std_for_zero_param config.min_gaussian_std)<block_end><elif_stmt>action_gaussian_std_fn<eq>'softplus'<block_start>config.gaussian_std_fn=softplus_std_fn(action_std_for_zero_param config.min_gaussian_std)<block_end><else_stmt><block_start><raise>ValueError('Flag `action_gaussian_std_fn` only supports safe_exp and'<concat>f' softplus, got: {action_gaussian_std_fn}')<block_end>config.postprocessor=action_postprocessor<line_sep><return>config<block_end>
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.2' # jupytext_version: 1.2.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% <import_from_stmt>mpl_toolkits mplot3d<import_from_stmt>matplotlib.pylab *<line_sep># %% style.use(['dark_background' 'bmh'])<line_sep>rc('axes' facecolor='k')<line_sep>rc('figure' facecolor='k')<line_sep>rc('figure' figsize=(10 5))<line_sep># %% # Lanes from -1 to 3 --> 0 is target lane y=r_[-1:3.1:.1]<line_sep># 2 lane widths in front and in back x=r_[-2:2.1:.1]<line_sep># %% # Target lane cost # target_lane_cost = y ** 2 / 4 target_lane_cost=abs(y)<times>.5<line_sep># %% # Color shorthands r,g,b,p='C1' 'C3' 'C0' 'C2'<line_sep>set_color=<lambda>c:dict(linefmt=c basefmt=" " markerfmt='o'+c)<line_sep># %% # Target Lane 0, Ego Car Lane 2, Other Car Lane 1 figure()<line_sep>y_proximity=maximum(1-abs(1-y) 0)<line_sep>stem(y target_lane_cost+y_proximity **set_color(p) label='Total Cost')<line_sep>stem(y target_lane_cost **set_color(b) label='Target Lane Cost')<line_sep>stem(y y_proximity **set_color(g) label='Y Proximity Cost')<line_sep>arrow_props=dict(width=1.5 facecolor='white')<line_sep># annotate('Ego Car', (2.0, 0.0), (2, -0.25), arrowprops=arrow_props) annotate('Other Car' (1.0 0.0) (1 -0.25) arrowprops=arrow_props)<line_sep>annotate('Target Lane' (0.0 0.0) (0 -0.25) arrowprops=arrow_props)<line_sep>axis('equal')<line_sep>title('Target Lane Cost + Proximity Cost')<line_sep>legend()<line_sep>savefig('car_1_left.png')<line_sep># Target Lane 0, Ego Car Lane 2, Other Car Lane 0 figure()<line_sep>y_proximity=maximum(1-abs(0-y) 0)<line_sep>stem(y target_lane_cost+y_proximity **set_color(p) label='Total Cost')<line_sep>stem(y target_lane_cost **set_color(b) label='Target Lane Cost')<line_sep>stem(y y_proximity **set_color(g) label='Y Proximity Cost')<line_sep># annotate('Ego Car', (2.0, 0.0), (2, -0.25), arrowprops=arrow_props) annotate('Other Car' (0.0 0.0) (0.8 -0.25) arrowprops=arrow_props)<line_sep>annotate('Target Lane' (0.0 0.0) (0 -0.25) arrowprops=arrow_props)<line_sep>axis('equal')<line_sep>title('Target Lane Cost + Proximity Cost')<line_sep>legend()<line_sep>savefig('car_2_left.png')<line_sep># Target Lane 0, Ego Car Lane 1, Lane Cost accounted for figure()<line_sep>lane_cost=(maximum(0.5-abs(0.5-y) 0)+maximum(0.5-abs(1.5-y) 0))<times>0.4<line_sep>stem(y target_lane_cost+lane_cost **set_color(p) label='Total Cost')<line_sep>stem(y target_lane_cost **set_color(b) label='Target Lane Cost')<line_sep>stem(y lane_cost **set_color(r) label='Lane Cost')<line_sep>annotate('Ego Car' (1.0 0.0) (1 -0.25) arrowprops=arrow_props)<line_sep>annotate('Target Lane' (0.0 0.0) (0 -0.25) arrowprops=arrow_props)<line_sep>axis('equal')<line_sep>title('Target Lane Cost + Lane Cost')<line_sep>legend()<line_sep>savefig('lane_change.png')<line_sep># %% figure()<line_sep>plot(y lane_cost)<line_sep>ylim(-0.05 0.2)<line_sep>annotate('Ego Car' (1.0 0.0) (1 -0.04) arrowprops=arrow_props)<line_sep>title('Lane Cost')<line_sep># %% set_color_3d=<lambda>c:dict(color=c marker='o' markeredgecolor=c markevery=(0.1 0.1))<line_sep>x_proximity=maximum(0 1-abs(x))<line_sep>figure()<line_sep>ax=axes(projection='3d')<line_sep>ax.set_xlabel('x-direction')<line_sep>ax.set_ylabel('y-direction')<line_sep>ax.set_zlabel('Cost')<for_stmt>i range(len(y))# Target lane cost <block_start>line=mplot3d.art3d.Line3D(*zip((0 y[i] 0) (0 y[i] target_lane_cost[i])) **set_color_3d(b))<line_sep>ax.add_line(line)<line_sep># Lane cost line=mplot3d.art3d.Line3D(*zip((0 y[i] 0) (0 y[i] lane_cost[i])) **set_color_3d(r))<line_sep>ax.add_line(line)<line_sep># X-Proximity cost line=mplot3d.art3d.Line3D(*zip((x[i] 1 0) (x[i] 1 x_proximity[i])) **set_color_3d(g))<line_sep>ax.add_line(line)<block_end>ax.set_xlim3d(-2 2)<line_sep>ax.set_ylim3d(-1 3)<line_sep>ax.set_zlim3d(-0.25 2)<line_sep># %%
<import_from_future_stmt> absolute_import<import_stmt>json<import_stmt>urlparse<import_stmt>requests<import_from_stmt>requests.exceptions RequestException<import_from_stmt>django.conf settings<import_from_stmt>rest_client.decorators json_format<import_from_stmt>rest_client.utils ConfigDict get_logger Guardor<import_from_stmt>rest_client.exceptions ServerResponseException InvalidRestMethodException ConfigMissing <line_sep>logger=get_logger()<line_sep>ALLOWED_HTTP_METHODS=frozenset(('GET' 'POST' 'PUT' 'DELETE' 'PATCH'))<class_stmt>Client(object)<block_start>_timeout=3<line_sep>_env='default'<line_sep>_default_env='default'<line_sep>_use_default=<false><line_sep>_parser=staticmethod(json.loads)<line_sep>_error_parser=staticmethod(<lambda>x:x)<def_stmt>__new__ cls<block_start><raise>AssertionError<block_end># Client can't have instances @classmethod<def_stmt>config cls name=<none> key=<none><block_start>name=name<or>cls.__name__.upper()<line_sep>configs=settings.REST_CLIENT_SETTINGS.get(name {})<try_stmt><block_start><if_stmt>cls._use_default<and>cls._env<not><in>configs<block_start>profile=cls._default_env<block_end><else_stmt><block_start>profile=cls._env<block_end>config=configs[profile]<block_end><except_stmt>KeyError<block_start><raise>ConfigMissing('Configuration for {} is not found'.format(cls.__name__))<block_end>config=ConfigDict(config)<line_sep>config.host=cls.__name__<line_sep><return>config<if>key<is><none><else>config.get(key)<block_end>@classmethod<def_stmt>build_url_base cls<block_start>cfg=cls.config()<line_sep>url=urlparse.urlparse('http://'+cfg['HOSTNAME'])<line_sep>port=cfg.get('PORT')<or>'80'<line_sep>hostname=url.hostname<line_sep>url_str=url.geturl()<line_sep>cls._url_base=url_str.replace(hostname '{}:{}'.format(hostname port) 1)<block_end>@classmethod<def_stmt>_get_sanitized_url cls url<block_start><if_stmt>cls._url_base<is><none><block_start>cls.build_url_base()<block_end><return>urlparse.urljoin(cls._url_base url)<block_end>@classmethod<def_stmt>_rest_call cls url method='GET' **kwargs<block_start>url=cls._get_sanitized_url(url)<if_stmt>method<in>ALLOWED_HTTP_METHODS<block_start><try_stmt><block_start>kwargs.setdefault('timeout' cls._timeout)<line_sep>response=requests.request(method.lower() url verify=<true> **kwargs)<block_end><except_stmt>RequestException<as>e<block_start><raise>ServerResponseException('Connection error {}'.format(e.message))<block_end><block_end><else_stmt><block_start><raise>InvalidRestMethodException('Invalid method "{}" is used for the HTTP request. Can only'<concat>'use the following: {!s}'.format(method ALLOWED_HTTP_METHODS))<block_end><if_stmt>200<le>response.status_code<l>300<block_start>response_data=response.text<line_sep>data=cls._parser(response_data)<if>response_data<else><none><line_sep><return>data<block_end><else_stmt><block_start>cleansed_kwargs=Guardor.cleanse_content(kwargs)<line_sep>msg='%s returned HTTP %d: %s\nResponse\nHeaders: %s\nBody: %s'%(url response.status_code cleansed_kwargs response.headers cls._error_parser(response.text))<line_sep>logger.error(msg)<line_sep>cls._error_handler(response)<line_sep><raise>ServerResponseException('Server response not OK. Verbose: {0}'.format(msg))<block_end><block_end>@classmethod<def_stmt>_error_handler cls response<block_start><pass><block_end><block_end><class_stmt>JsonClient(Client)<block_start>@classmethod@json_format<def_stmt>_rest_call cls url method **kwargs<block_start><return>super(JsonClient cls)._rest_call(url method **kwargs)<block_end><block_end>
<import_stmt>unittest<import_stmt>netCDF4<import_stmt>numpy<as>np<import_from_stmt>numpy.testing assert_array_equal<class_stmt>TestCreateMem(unittest.TestCase)<block_start><def_stmt>test_mem_create self<block_start><def_stmt>check_inmemory format# memory is 'advisory size' - not needed for NETCDF4/HDF5 # but is used for NETCDF3. <block_start>nc=netCDF4.Dataset('test.nc' 'w' memory=1028 format=format)<line_sep>d=nc.createDimension('x' <none>)<line_sep>v=nc.createVariable('v' np.int32 'x')<line_sep>data=np.arange(5)<line_sep>v[0:5]=data<line_sep># retrieve memory buffer b=nc.close()<line_sep># open a new file using this memory buffer nc2=netCDF4.Dataset('test2.nc' 'r' memory=b)<line_sep>assert_array_equal(nc2['v'][:] data)<line_sep>nc2.close()<block_end>check_inmemory('NETCDF3_CLASSIC')<line_sep>check_inmemory('NETCDF4_CLASSIC')<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>unittest.main()<block_end>
<import_from_stmt>collections defaultdict<import_stmt>numpy<as>np<import_stmt>torch<import_stmt>torch.nn<as>nn<import_from_stmt>metal.utils move_to_device recursive_merge_dicts set_seed<line_sep>model_defaults={"seed":<none> "device":0 # gpu id (int) or -1 for cpu "verbose":<true> "fp16":<false> "model_weights":<none> # the path to a saved checkpoint to initialize with }<class_stmt>MetalModel(nn.Module)<block_start>"""A dynamically constructed discriminative classifier Args: tasks: a list of Task objects which bring their own (named) modules We currently support up to N input modules -> middle layers -> up to N heads TODO: Accept specifications for more exotic structure (e.g., via user-defined graph) """<def_stmt>__init__ self tasks **kwargs<block_start>self.config=recursive_merge_dicts(model_defaults kwargs misses="insert")<line_sep># Set random seed before initializing module weights <if_stmt>self.config["seed"]<is><none><block_start>self.config["seed"]=np.random.randint(1e6)<block_end>set_seed(self.config["seed"])<line_sep>super().__init__()<line_sep># Build network self._build(tasks)<line_sep>self.task_map={task.name:task<for>task tasks}<line_sep># Load weights <if_stmt>self.config["model_weights"]<block_start>self.load_weights(self.config["model_weights"])<block_end># Half precision <if_stmt>self.config["fp16"]<block_start>print("metal_model.py: Using fp16")<line_sep>self.half()<block_end># Move model to device now, then move data to device in forward() or calculate_loss() <if_stmt>self.config["device"]<ge>0<block_start><if_stmt>torch.cuda.is_available()<block_start><if_stmt>self.config["verbose"]<block_start>print("Using GPU...")<block_end>self.to(torch.device(f"cuda:{self.config['device']}"))<block_end><else_stmt><block_start><if_stmt>self.config["verbose"]<block_start>print("No cuda device available. Using cpu instead.")<block_end><block_end><block_end># Show network <if_stmt>self.config["verbose"]<block_start>print("\nNetwork architecture:")<line_sep>print(self)<line_sep>print()<line_sep>num_params=sum(p.numel()<for>p self.parameters()<if>p.requires_grad)<line_sep>print(f"Total number of parameters: {num_params}")<block_end><block_end><def_stmt>_build self tasks<block_start>"""Iterates over tasks, adding their input_modules and head_modules"""<line_sep># TODO: Allow more flexible specification of network structure self.input_modules=nn.ModuleDict({task.name:nn.DataParallel(task.input_module)<for>task tasks})<line_sep>self.middle_modules=nn.ModuleDict({task.name:nn.DataParallel(task.middle_module)<for>task tasks})<line_sep>self.head_modules=nn.ModuleDict({task.name:nn.DataParallel(task.head_module)<for>task tasks})<line_sep>self.loss_hat_funcs={task.name:task.loss_hat_func<for>task tasks}<line_sep>self.output_hat_funcs={task.name:task.output_hat_func<for>task tasks}<block_end><def_stmt>forward self X task_names<block_start>"""Returns the outputs of the requested task heads in a dictionary The output of each task is the result of passing the input through the input_module, middle_module, and head_module for that task, in that order. Before calculating any intermediate values, we first check whether a previously evaluated task has produced that intermediate result. If so, we use that. Args: X: a [batch_size, ...] batch from a DataLoader Returns: output_dict: {task_name (str): output (Tensor)} """<line_sep>input=move_to_device(X self.config["device"])<line_sep>outputs={}<line_sep># TODO: Replace this naive caching scheme with a more intelligent and feature- # complete approach where arbitrary DAGs of modules are specified and we only # cache things that will be reused by another task <for_stmt>task_name task_names# Extra .module call is to get past DataParallel wrapper <block_start>input_module=self.input_modules[task_name].module<if_stmt>input_module<not><in>outputs<block_start>output=input_module(input)<line_sep>outputs[input_module]=output<block_end>middle_module=self.middle_modules[task_name].module<if_stmt>middle_module<not><in>outputs<block_start>output=middle_module(outputs[input_module])<line_sep>outputs[middle_module]=output<block_end>head_module=self.head_modules[task_name].module<if_stmt>head_module<not><in>outputs<block_start>output=head_module(outputs[middle_module])<line_sep>outputs[head_module]=output<block_end><block_end><return>{t:outputs[self.head_modules[t].module]<for>t task_names}<block_end><def_stmt>calculate_loss self X Ys payload_name labels_to_tasks<block_start>"""Returns a dict of {task_name: loss (a FloatTensor scalar)}. Args: X: an appropriate input for forward(), either a Tensor or tuple Ys: a dict of {task_name: labels} where labels is [n, ?] labels_to_tasks: a dict of {label_name: task_name} indicating which task head to use to calculate the loss for each labelset. """<line_sep>task_names=set(labels_to_tasks.values())<line_sep>outputs=self.forward(X task_names)<line_sep>loss_dict={}# Stores the loss by task count_dict={}# Stores the number of active examples by task <for_stmt>label_name,task_name labels_to_tasks.items()<block_start>loss_name=f"{task_name}/{payload_name}/{label_name}/loss"<line_sep>Y=Ys[label_name]<assert_stmt>isinstance(Y torch.Tensor)<line_sep>out=outputs[task_name]<line_sep># Identify which instances have at least one non-zero target labels active=torch.any(Y.detach()<ne>0 dim=1)<line_sep>count_dict[loss_name]=active.sum().item()<line_sep># If there are inactive instances, slice them out to save computation # and ignore their contribution to the loss <if_stmt>0<in>active<block_start>Y=Y[active]<if_stmt>isinstance(out torch.Tensor)<block_start>out=out[active]<block_end># If the output of the head has multiple fields, slice them all <elif_stmt>isinstance(out dict)<block_start>out=move_to_device({k:v[active]<for>k,v out.items()})<block_end><block_end># Convert to half precision last thing if applicable <if_stmt>self.config["fp16"]<and>Y.dtype<eq>torch.float32<block_start>out["data"]=out["data"].half()<line_sep>Y=Y.half()<block_end># If no examples in this batch have labels for this task, skip loss calc # Active has type torch.uint8; avoid overflow with long() <if_stmt>active.long().sum()<block_start>label_loss=self.loss_hat_funcs[task_name](out move_to_device(Y self.config["device"]))<assert_stmt>isinstance(label_loss.item() float)<line_sep>loss_dict[loss_name]=(label_loss<times>self.task_map[task_name].loss_multiplier)<block_end><block_end><return>loss_dict count_dict<block_end>@torch.no_grad()<def_stmt>calculate_probs self X task_names<block_start>"""Returns a dict of {task_name: probs} Args: X: instances to feed through the network task_names: the names of the tasks for which to calculate outputs Returns: {task_name: probs}: probs is the output of the output_hat for the given task_head The type of each entry in probs depends on the task type: instance-based tasks: each entry in probs is a [k]-len array token-based tasks: each entry is a [seq_len, k] array """<assert_stmt>self.eval()<line_sep><return>{t:[probs.cpu().numpy()<for>probs self.output_hat_funcs[t](out)]<for>t,out self.forward(X task_names).items()}<block_end><def_stmt>update_config self update_dict<block_start>"""Updates self.config with the values in a given update dictionary."""<line_sep>self.config=recursive_merge_dicts(self.config update_dict)<block_end><def_stmt>load_weights self model_path<block_start>"""Load model weights from checkpoint."""<if_stmt>self.config["device"]<ge>0<block_start>device=torch.device(f"cuda:{self.config['device']}")<block_end><else_stmt><block_start>device=torch.device("cpu")<block_end><try_stmt><block_start>self.load_state_dict(torch.load(model_path map_location=device)["model"])<block_end><except_stmt>RuntimeError<block_start>print("Your destination state dict has different keys for the update key.")<line_sep>self.load_state_dict(torch.load(model_path map_location=device)["model"] strict=<false>)<block_end><block_end><def_stmt>save_weights self model_path<block_start>"""Saves weight in checkpoint directory"""<line_sep><raise>NotImplementedError<block_end>@torch.no_grad()<def_stmt>score self payload metrics=[] verbose=<true> **kwargs<block_start>"""Calculate the requested metrics for the given payload Args: payload: a Payload to score metrics: a list of full metric names, a single full metric name, or []: list: a list of full metric names supported by the tasks' Scorers. (full metric names are of the form task/payload/labelset/metric) Only these metrics will be calculated and returned. []: defaults to all supported metrics for the given payload's Tasks str: a single full metric name A single score will be returned instead of a dictionary Returns: scores: a dict of the form {metric_name: score} corresponding to the requested metrics (optionally a single score if metrics is a string instead of a list) """<line_sep>self.eval()<line_sep>return_unwrapped=isinstance(metrics str)<line_sep># If no specific metrics were requested, calculate all available metrics <if_stmt>metrics<block_start>metrics_list=metrics<if>isinstance(metrics list)<else>[metrics]<assert_stmt>all(len(metric.split("/"))<eq>4<for>metric metrics_list)<line_sep>target_metrics=defaultdict(list)<line_sep>target_tasks=[]<line_sep>target_labels=[]<for_stmt>full_metric_name metrics<block_start>task_name,payload_name,label_name,metric_name=full_metric_name.split("/")<line_sep>target_tasks.append(task_name)<line_sep>target_labels.append(label_name)<line_sep>target_metrics[label_name].append(metric_name)<block_end><block_end><else_stmt><block_start>target_tasks=set(payload.labels_to_tasks.values())<line_sep>target_labels=set(payload.labels_to_tasks.keys())<line_sep>target_metrics={label_name:<none><for>label_name payload.labels_to_tasks}<block_end>Ys,Ys_probs,Ys_preds=self.predict_with_gold(payload target_tasks target_labels return_preds=<true> **kwargs)<line_sep>metrics_dict={}<for_stmt>label_name,task_name payload.labels_to_tasks.items()<block_start>scorer=self.task_map[task_name].scorer<line_sep>task_metrics_dict=scorer.score(Ys[label_name] Ys_probs[task_name] Ys_preds[task_name] target_metrics=target_metrics[label_name] )<line_sep># Expand short metric names into full metric names <for_stmt>metric_name,score task_metrics_dict.items()<block_start>full_metric_name=(f"{task_name}/{payload.name}/{label_name}/{metric_name}")<line_sep>metrics_dict[full_metric_name]=score<block_end><block_end># If a single metric was given as a string (not list), return a float <if_stmt>return_unwrapped<block_start>metric,score=metrics_dict.popitem()<line_sep><return>score<block_end><else_stmt><block_start><return>metrics_dict<block_end><block_end>@torch.no_grad()<def_stmt>predict_with_gold self payload target_tasks=<none> target_labels=<none> return_preds=<false> max_examples=0 **kwargs <block_start>"""Extracts Y and calculates Y_prods, Y_preds for the given payload and tasks To get just the probabilities or predictions for a single task, consider using predict() or predict_probs(). Args: payload: the Payload to make predictions for target_tasks: if not None, predict probs only for the specified tasks; otherwise, predict probs for all tasks with corresponding labelsets in the payload target_labels: if not None, return labels for only the specified labelsets; otherwise, return all labelsets return_preds: if True, also include preds in return values max_examples: if > 0, predict for a maximum of this many examples # TODO: consider returning Ys as tensors instead of lists (padded if necessary) Returns: Ys: a {label_name: Y} dict where Y is an [n] list of labels (often ints) Ys_probs: a {task_name: Y_probs} dict where Y_probs is a [n] list of probabilities Ys_preds: a {task_name: Y_preds} dict where Y_preds is a [n] list of predictions """<line_sep>validate_targets(payload target_tasks target_labels)<if_stmt>target_tasks<is><none><block_start>target_tasks=set(payload.labels_to_tasks.values())<block_end><elif_stmt>isinstance(target_tasks str)<block_start>target_tasks=[target_tasks]<block_end>Ys=defaultdict(list)<line_sep>Ys_probs=defaultdict(list)<line_sep>total=0<for_stmt>batch_num,(Xb Yb) enumerate(payload.data_loader)<block_start>Yb_probs=self.calculate_probs(Xb target_tasks)<for_stmt>task_name,yb_probs Yb_probs.items()<block_start>Ys_probs[task_name].extend(yb_probs)<block_end><for_stmt>label_name,yb Yb.items()<block_start><if_stmt>target_labels<is><none><or>label_name<in>target_labels<block_start>Ys[label_name].extend(yb.cpu().numpy())<block_end><block_end>total<augadd>len(Xb)<if_stmt>max_examples<g>0<and>total<ge>max_examples<block_start><break><block_end><block_end><if_stmt>max_examples<block_start>Ys={label_name:Y[:max_examples]<for>label_name,Y Ys.items()}<line_sep>Ys_probs={task_name:Y_probs[:max_examples]<for>task_name,Y_probs Ys_probs.items()}<block_end><if_stmt>return_preds<block_start>Ys_preds={task_name:[probs_to_preds(y_probs)<for>y_probs Y_probs]<for>task_name,Y_probs Ys_probs.items()}<line_sep><return>Ys Ys_probs Ys_preds<block_end><else_stmt><block_start><return>Ys Ys_probs<block_end><block_end># Single-task prediction helpers (for convenience) @torch.no_grad()<def_stmt>predict_probs self payload task_name=<none> **kwargs<block_start>"""Return probabilistic labels for a single task of a payload Args: payload: a Payload task_name: the task to calculate probabilities for If task_name is None and the payload includes labels for only one task, return predictions for that task. If task_name is None and the payload includes labels for more than one task, raise an exception. Returns: Y_probs: an [n] list of probabilities """<line_sep>self.eval()<if_stmt>task_name<is><none><block_start><if_stmt>len(payload.labels_to_tasks)<g>1<block_start>msg=("The payload you provided contains labels for more than one "<concat>"task, so task_name cannot be None.")<line_sep><raise>Exception(msg)<block_end><else_stmt><block_start>task_name=next(iter(payload.labels_to_tasks.values()))<block_end><block_end>target_tasks=[task_name]<line_sep>_,Ys_probs=self.predict_with_gold(payload target_tasks **kwargs)<line_sep><return>Ys_probs[task_name]<block_end>@torch.no_grad()<def_stmt>predict self payload task_name=<none> return_probs=<false> **kwargs<block_start>"""Return predicted labels for a single task of a payload Args: payload: a Payload task_name: the task to calculate predictions for If task_name is None and the payload includes labels for only one task, return predictions for that task. If task_name is None and the payload includes labels for more than one task, raise an exception. Returns: Y_probs: an [n] list of probabilities Y_preds: an [n] list of predictions """<line_sep>self.eval()<if_stmt>task_name<is><none><block_start><if_stmt>len(payload.labels_to_tasks)<g>1<block_start>msg=("The payload you provided contains labels for more than one "<concat>"task, so task_name cannot be None.")<line_sep><raise>Exception(msg)<block_end><else_stmt><block_start>task_name=next(iter(payload.labels_to_tasks.values()))<block_end><block_end>target_tasks=[task_name]<line_sep>_,Ys_probs,Ys_preds=self.predict_with_gold(payload target_tasks return_preds=<true> **kwargs)<line_sep>Y_probs=Ys_probs[task_name]<line_sep>Y_preds=Ys_preds[task_name]<if_stmt>return_probs<block_start><return>Y_preds Y_probs<block_end><else_stmt><block_start><return>Y_preds<block_end><block_end><block_end><def_stmt>validate_targets payload target_tasks target_labels<block_start><if_stmt>target_tasks<block_start><for_stmt>task_name target_tasks<block_start><if_stmt>task_name<not><in>set(payload.labels_to_tasks.values())<block_start>msg=(f"Could not find the specified task_name {task_name} in "<concat>f"payload {payload}.")<line_sep><raise>Exception(msg)<block_end><block_end><block_end><if_stmt>target_labels<block_start><for_stmt>label_name target_labels<block_start><if_stmt>label_name<not><in>payload.labels_to_tasks<block_start>msg=(f"Could not find the specified labelset {label_name} in "<concat>f"payload {payload}.")<line_sep><raise>Exception(msg)<block_end><block_end><block_end><block_end><def_stmt>probs_to_preds probs<block_start>"""Identifies the largest probability in each column on the last axis We add 1 to the argmax to account for the fact that all labels in MeTaL are categorical and the 0 label is reserved for abstaining weak labels. """<line_sep># TODO: Consider replacing argmax with a version of the rargmax utility to randomly # break ties instead of accepting the first one, or allowing other tie-breaking # strategies <return>np.argmax(probs axis=-1)+1<block_end>
<import_from_stmt>torchtext.data.datasets_utils _RawTextIterableDataset _wrap_split_argument _add_docstring_header _download_extract_validate _create_dataset_directory _create_data_from_iob <import_stmt>os<import_stmt>logging<line_sep>URL={'train':"https://www.clips.uantwerpen.be/conll2000/chunking/train.txt.gz" 'test':"https://www.clips.uantwerpen.be/conll2000/chunking/test.txt.gz" }<line_sep>MD5={'train':"6969c2903a1f19a83569db643e43dcc8" 'test':"a916e1c2d83eb3004b38fc6fcd628939" }<line_sep>NUM_LINES={'train':8936 'test':2012 }<line_sep>_EXTRACTED_FILES={'train':'train.txt' 'test':'test.txt'}<line_sep>_EXTRACTED_FILES_MD5={'train':"2e2f24e90e20fcb910ab2251b5ed8cd0" 'test':"56944df34be553b72a2a634e539a0951"}<line_sep>DATASET_NAME="CoNLL2000Chunking"<line_sep>@_add_docstring_header(num_lines=NUM_LINES)@_create_dataset_directory(dataset_name=DATASET_NAME)@_wrap_split_argument(('train' 'test'))<def_stmt>CoNLL2000Chunking root split# Create a dataset specific subfolder to deal with generic download filenames <block_start>root=os.path.join(root 'conll2000chunking')<line_sep>path=os.path.join(root split+".txt.gz")<line_sep>data_filename=_download_extract_validate(root URL[split] MD5[split] path os.path.join(root _EXTRACTED_FILES[split]) _EXTRACTED_FILES_MD5[split] hash_type="md5")<line_sep>logging.info('Creating {} data'.format(split))<line_sep><return>_RawTextIterableDataset(DATASET_NAME NUM_LINES[split] _create_data_from_iob(data_filename " "))<block_end>
<class_stmt>Solution<block_start><def_stmt>minSteps self n:int<arrow>int<block_start>res,m=0 2<while_stmt>n<g>1<block_start><while_stmt>n%m<eq>0<block_start>res<augadd>m<line_sep>n<augfloordiv>m<block_end>m<augadd>1<block_end><return>res<block_end><block_end>
"""Traversing core logic."""<line_sep># Pyramid <import_from_stmt>pyramid.interfaces ILocation<import_from_stmt>zope.interface implementer<line_sep>@implementer(ILocation)<class_stmt>Resource<block_start>"""Traversable resource in a nested tree hierarchy with basic breadcrumbs support. All traverable context classes should inherit from this class. Note that this is not a strict requirement, as often anything implementing :py:class:`pyramid.interfaces.ILocation` and ``get_title()`` will work. For more information see :ref:`Traversal <traversal>`. .. _traversal: """<line_sep># TODO: Cannot annotate request as it breaks sphinx-autodoc-typehints, sphinx-autodoc-typehints==1.1.0, when doing make html <def_stmt>__init__ self request#: Pointer to the parent object in traverse hierarchy. This is none until make_lineage is called. <block_start>self.__parent__=<none><line_sep>#: The id of this resource as its appear in URL and traversing path self.__name__=<none><line_sep>self.request=request<block_end><def_stmt>get_title self<arrow>str<block_start>"""Return human-readable title of this resource. This is viewed in admin breadcrumbs path, etc. """<line_sep>title=getattr(self "title" <none>)<if_stmt>title<block_start><return>title<block_end><raise>NotImplementedError("get_title() implementation missing for {}".format(self))<block_end>@classmethod<def_stmt>make_lineage self parent child name allow_new_parent=<false><arrow>"Resource"<block_start>"""Set traversing pointers between the child and the parent resources. Builds __parent__ and __name__ pointer and sets it on the child resource. * If lineage relationship is not lazy and the referenced children is stored in the parent, the lineage must be set when the child is put into parent container. * If lineage relationship is lazy and child resource is constructed upon lookup in ``__item__``, the lineage is constructed before the child is returned. :param parent: Parent resource who children is become part to :param child: Child resource mutated in place :param name: Id of the child resource as it will appear in the URL traversing path :param allow_new_parent: If the child has alraedy a parent assigned, allow override the parent... or basically move an existing resource. You don't usually want this for in-memory resource and this is for catching bugs. :return: The mutated child resource """<assert_stmt>child<assert_stmt>parent<assert_stmt>name<if_stmt><not>allow_new_parent# Catch bugs when you try to double lineage a persistnet parent -> child relationship <block_start><assert_stmt><not>getattr(child "__parent__" <none>) "Tried to double init lineage for {} -> {}, previous parent was {}".format(parent child child.__parent__)<block_end>child.__parent__=parent<line_sep>child.__name__=name<line_sep><return>child<block_end><block_end>
"""Event filtering by hash, for partitioned databases. Parameters: key=COLUMN: column name to use for hashing hash_key=COLUMN: column name to use for hashing (overrides 'key' parameter) hashfunc=NAME: function to use for hashing (default: partconf.get_hash_raw) hashexpr=EXPR: full expression to use for hashing (deprecated) encoding=ENC: validate and fix incoming data (only utf8 supported atm) ignore_truncate=BOOL: ignore truncate event, default: 0, values: 0,1 On root node: * Hash of key field will be added to ev_extra3. This is implemented by adding additional trigger argument: ev_extra3='hash='||partconf.get_hash_raw(key_column) On branch/leaf node: * On COPY time, the SELECT on provider side gets filtered by hash. * On replay time, the events gets filtered by looking at hash in ev_extra3. Local config: * Local hash value and mask are loaded from partconf.conf table. """<import_stmt>skytools<import_from_stmt>londiste.handler TableHandler<line_sep>__all__=['ShardHandler' 'PartHandler']<class_stmt>ShardHandler(TableHandler)<block_start>__doc__=__doc__<line_sep>handler_name='shard'<line_sep>DEFAULT_HASHFUNC="partconf.get_hash_raw"<line_sep>DEFAULT_HASHEXPR="%s(%s)"<def_stmt>__init__ self table_name args dest_table<block_start>TableHandler.__init__(self table_name args dest_table)<line_sep>self.hash_mask=<none># aka max part number (atm) self.shard_nr=<none># part number of local node # primary key columns self.hash_key=args.get('hash_key' args.get('key'))<line_sep>self._validate_hash_key()<line_sep># hash function & full expression hashfunc=args.get('hashfunc' self.DEFAULT_HASHFUNC)<line_sep>self.hashexpr=self.DEFAULT_HASHEXPR%(skytools.quote_fqident(hashfunc) skytools.quote_ident(self.hash_key<or>''))<line_sep>self.hashexpr=args.get('hashexpr' self.hashexpr)<block_end><def_stmt>_validate_hash_key self<block_start><if_stmt>self.hash_key<is><none><block_start><raise>Exception('Specify hash key field as hash_key argument')<block_end><block_end><def_stmt>reset self<block_start>"""Forget config info."""<line_sep>self.hash_mask=<none><line_sep>self.shard_nr=<none><line_sep>TableHandler.reset(self)<block_end><def_stmt>add self trigger_arg_list<block_start>"""Let trigger put hash into extra3"""<line_sep>arg="ev_extra3='hash='||%s"%self.hashexpr<line_sep>trigger_arg_list.append(arg)<line_sep>TableHandler.add(self trigger_arg_list)<block_end><def_stmt>prepare_batch self batch_info dst_curs<block_start>"""Called on first event for this table in current batch."""<if_stmt>self.hash_key<is><not><none><block_start><if_stmt><not>self.hash_mask<block_start>self.load_shard_info(dst_curs)<block_end><block_end>TableHandler.prepare_batch(self batch_info dst_curs)<block_end><def_stmt>process_event self ev sql_queue_func arg<block_start>"""Filter event by hash in extra3, apply only if for local shard."""<if_stmt>ev.extra3<and>self.hash_key<is><not><none><block_start>meta=skytools.db_urldecode(ev.extra3)<line_sep>self.log.debug('shard.process_event: hash=%i, hash_mask=%i, shard_nr=%i' int(meta['hash']) self.hash_mask self.shard_nr)<if_stmt>(int(meta['hash'])&self.hash_mask)<ne>self.shard_nr<block_start>self.log.debug('shard.process_event: not my event')<line_sep><return><block_end><block_end>self._process_event(ev sql_queue_func arg)<block_end><def_stmt>_process_event self ev sql_queue_func arg<block_start>self.log.debug('shard.process_event: my event, processing')<line_sep>TableHandler.process_event(self ev sql_queue_func arg)<block_end><def_stmt>get_copy_condition self src_curs dst_curs<block_start>"""Prepare the where condition for copy and replay filtering"""<if_stmt>self.hash_key<is><none><block_start><return>TableHandler.get_copy_condition(self src_curs dst_curs)<block_end>self.load_shard_info(dst_curs)<line_sep>w="(%s & %d) = %d"%(self.hashexpr self.hash_mask self.shard_nr)<line_sep>self.log.debug('shard: copy_condition=%r' w)<line_sep><return>w<block_end><def_stmt>load_shard_info self curs<block_start>"""Load part/slot info from database."""<line_sep>q="select part_nr, max_part from partconf.conf"<line_sep>curs.execute(q)<line_sep>self.shard_nr,self.hash_mask=curs.fetchone()<if_stmt>self.shard_nr<is><none><or>self.hash_mask<is><none><block_start><raise>Exception('Error loading shard info')<block_end><block_end><block_end><class_stmt>PartHandler(ShardHandler)<block_start>__doc__="Deprecated compat name for shard handler.\n"+__doc__.split('\n' 1)[1]<line_sep>handler_name='part'<block_end># register handler class __londiste_handlers__=[ShardHandler PartHandler]<line_sep>
<import_stmt>concise<line_sep># all the custom objects are already loaded through importing concise OBJECTS=<none><line_sep># new concise version # OBJECTS = concise.custom_objects
""" Short Plotting Routine to Plot Pandas Dataframes by Column Label 1. Takes list of dateframes to compare multiple trials 2. Takes list of y-variables to combine on 1 plot 3. Legend location and y-axis limits can be customized Written by <NAME> (pat-coady.github.io) """<import_stmt>matplotlib.pyplot<as>plt<def_stmt>df_plot dfs x ys ylim=<none> xlim=<none> legend_loc='best'<block_start>""" Plot y vs. x curves from pandas dataframe(s) Args: dfs: list of pandas dataframes x: str column label for x variable ys: list of str column labels for y variable(s) ylim: tuple to override automatic y-axis limits xlim: tuple to override automatic x-axis limits legend_loc: str to override automatic legend placement: 'upper left', 'lower left', 'lower right' , 'right' , 'center left', 'center right', 'lower center', 'upper center', and 'center' """<if_stmt>ylim<is><not><none><block_start>plt.ylim(ylim)<block_end><if_stmt>xlim<is><not><none><block_start>plt.xlim(xlim)<block_end><for_stmt>df,name dfs<block_start><if_stmt>'_'<in>name<block_start>name=name.split('_')[1]<block_end><for_stmt>y ys<block_start>plt.plot(df[x] df[y] linewidth=1 label=name+' '+y.replace('_' ''))<block_end><block_end>plt.xlabel(x.replace('_' ''))<line_sep>plt.legend(loc=legend_loc)<line_sep>plt.show()<block_end>
# Copyright 2017 <NAME> # # 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_from_stmt>gpflow.param DataHolder AutoFlow<import_from_stmt>gpflow settings<import_stmt>numpy<as>np<import_from_stmt>.transforms LinearTransform DataTransform<import_from_stmt>.domain UnitCube<import_from_stmt>.models ModelWrapper<line_sep>float_type=settings.dtypes.float_type<class_stmt>DataScaler(ModelWrapper)<block_start>""" Model-wrapping class, primarily intended to assure the data in GPflow models is scaled. One DataScaler wraps one GPflow model, and can scale the input as well as the output data. By default, if any kind of object attribute is not found in the datascaler object, it is searched on the wrapped model. The datascaler supports both input as well as output scaling, although both scalings are set up differently: - For input, the transform is not automatically generated. By default, the input transform is the identity transform. The input transform can be set through the setter property, or by specifying a domain in the constructor. For the latter, the input transform will be initialized as the transform from the specified domain to a unit cube. When X is updated, the transform does not change. - If enabled: for output the data is always scaled to zero mean and unit variance. This means that if the Y property is set, the output transform is first calculated, then the data is scaled. By default, :class:`~.acquisition.Acquisition` objects will always wrap each model received. However, the input and output transforms will be the identity transforms, and output normalization is switched off. It is up to the user (or specialized classes such as the BayesianOptimizer) to correctly configure the datascalers involved. By carrying out the scaling at such a deep level in the framework, it is possible to keep the scaling hidden throughout the rest of GPflowOpt. This means that, during implementation of acquisition functions it is safe to assume the data is not scaled, and is within the configured optimization domain. There is only one exception: the hyperparameters are determined on the scaled data, and are NOT automatically unscaled by this class because the datascaler does not know what model is wrapped and what kernels are used. Should hyperparameters of the model be required, it is the responsibility of the implementation to rescale the hyperparameters. Additionally, applying hyperpriors should anticipate for the scaled data. """<def_stmt>__init__ self model domain=<none> normalize_Y=<false><block_start>""" :param model: model to be wrapped :param domain: (default: None) if supplied, the input transform is configured from the supplied domain to :class:`.UnitCube`. If None, the input transform defaults to the identity transform. :param normalize_Y: (default: False) enable automatic scaling of output values to zero mean and unit variance. """<line_sep># model sanity checks, slightly stronger conditions than the wrapper super(DataScaler self).__init__(model)<line_sep># Initial configuration of the datascaler n_inputs=model.X.shape[1]<line_sep>n_outputs=model.Y.shape[1]<line_sep>self._input_transform=(domain<or>UnitCube(n_inputs))<rshift>UnitCube(n_inputs)<line_sep>self._normalize_Y=normalize_Y<line_sep>self._output_transform=LinearTransform(np.ones(n_outputs) np.zeros(n_outputs))<line_sep>self.X=model.X.value<line_sep>self.Y=model.Y.value<block_end>@property<def_stmt>input_transform self<block_start>""" Get the current input transform :return: :class:`.DataTransform` input transform object """<line_sep><return>self._input_transform<block_end>@input_transform.setter<def_stmt>input_transform self t<block_start>""" Configure a new input transform. Data in the wrapped model is automatically updated with the new transform. :param t: :class:`.DataTransform` object: the new input transform. """<assert_stmt>isinstance(t DataTransform)<line_sep>X=self.X.value# unscales the data self._input_transform.assign(t)<line_sep>self.X=X<block_end># scales the back using the new input transform @property<def_stmt>output_transform self<block_start>""" Get the current output transform :return: :class:`.DataTransform` output transform object """<line_sep><return>self._output_transform<block_end>@output_transform.setter<def_stmt>output_transform self t<block_start>""" Configure a new output transform. Data in the model is automatically updated with the new transform. :param t: :class:`.DataTransform` object: the new output transform. """<assert_stmt>isinstance(t DataTransform)<line_sep>Y=self.Y.value<line_sep>self._output_transform.assign(t)<line_sep>self.Y=Y<block_end>@property<def_stmt>normalize_output self<block_start>""" :return: boolean, indicating if output is automatically scaled to zero mean and unit variance. """<line_sep><return>self._normalize_Y<block_end>@normalize_output.setter<def_stmt>normalize_output self flag<block_start>""" Enable/disable automated output scaling. If switched off, the output transform becomes the identity transform. If enabled, data will be automatically scaled to zero mean and unit variance. When the output normalization is switched on or off, the data in the model is automatically adapted. :param flag: boolean, turn output scaling on or off """<line_sep>self._normalize_Y=flag<if_stmt><not>flag# Output normalization turned off. Reset transform to identity <block_start>self.output_transform=LinearTransform(np.ones(self.Y.value.shape[1]) np.zeros(self.Y.value.shape[1]))<block_end><else_stmt># Output normalization enabled. Trigger scaling. <block_start>self.Y=self.Y.value<block_end><block_end># Methods overwriting methods of the wrapped model. @property<def_stmt>X self<block_start>""" Returns the input data of the model, unscaled. :return: :class:`.DataHolder`: unscaled input data """<line_sep><return>DataHolder(self.input_transform.backward(self.wrapped.X.value))<block_end>@property<def_stmt>Y self<block_start>""" Returns the output data of the wrapped model, unscaled. :return: :class:`.DataHolder`: unscaled output data """<line_sep><return>DataHolder(self.output_transform.backward(self.wrapped.Y.value))<block_end>@X.setter<def_stmt>X self x<block_start>""" Set the input data. Applies the input transform before setting the data of the wrapped model. """<line_sep>self.wrapped.X=self.input_transform.forward(x.value<if>isinstance(x DataHolder)<else>x)<block_end>@Y.setter<def_stmt>Y self y<block_start>""" Set the output data. In case normalize_Y=True, the appropriate output transform is updated. It is then applied on the data before setting the data of the wrapped model. """<line_sep>value=y.value<if>isinstance(y DataHolder)<else>y<if_stmt>self.normalize_output<block_start>self.output_transform.assign(~LinearTransform(value.std(axis=0) value.mean(axis=0)))<block_end>self.wrapped.Y=self.output_transform.forward(value)<block_end><def_stmt>build_predict self Xnew full_cov=<false><block_start>""" build_predict builds the TensorFlow graph for prediction. Similar to the method in the wrapped model, however the input points are transformed using the input transform. The returned mean and variance are transformed backward using the output transform. """<line_sep>f,var=self.wrapped.build_predict(self.input_transform.build_forward(Xnew) full_cov=full_cov)<line_sep><return>self.output_transform.build_backward(f) self.output_transform.build_backward_variance(var)<block_end>@AutoFlow((float_type [<none> <none>]))<def_stmt>predict_f self Xnew<block_start>""" Compute the mean and variance of held-out data at the points Xnew """<line_sep><return>self.build_predict(Xnew)<block_end>@AutoFlow((float_type [<none> <none>]))<def_stmt>predict_f_full_cov self Xnew<block_start>""" Compute the mean and variance of held-out data at the points Xnew """<line_sep><return>self.build_predict(Xnew full_cov=<true>)<block_end>@AutoFlow((float_type [<none> <none>]))<def_stmt>predict_y self Xnew<block_start>""" Compute the mean and variance of held-out data at the points Xnew """<line_sep>f,var=self.wrapped.build_predict(self.input_transform.build_forward(Xnew))<line_sep>f,var=self.likelihood.predict_mean_and_var(f var)<line_sep><return>self.output_transform.build_backward(f) self.output_transform.build_backward_variance(var)<block_end>@AutoFlow((float_type [<none> <none>]) (float_type [<none> <none>]))<def_stmt>predict_density self Xnew Ynew<block_start>""" Compute the (log) density of the data Ynew at the points Xnew """<line_sep>mu,var=self.wrapped.build_predict(self.input_transform.build_forward(Xnew))<line_sep>Ys=self.output_transform.build_forward(Ynew)<line_sep><return>self.likelihood.predict_density(mu var Ys)<block_end><block_end>
<import_stmt>torch<import_stmt>unittest<import_from_stmt>qtorch.quant *<import_from_stmt>qtorch FixedPoint BlockFloatingPoint FloatingPoint<line_sep>DEBUG=<false><line_sep>log=<lambda>m:print(m)<if>DEBUG<else><false><class_stmt>TestStochastic(unittest.TestCase)<block_start>""" invariant: quantized numbers cannot be greater than the maximum representable number or lower than the maximum representable number """<def_stmt>test_fixed self<block_start>"""test fixed point clamping"""<for_stmt>d ["cpu" "cuda"]<block_start><for_stmt>r ["stochastic" "nearest"]<block_start>wl=5<line_sep>fl=4<line_sep>t_min=-(2<power>(wl-fl-1))<line_sep>t_max=2<power>(wl-fl-1)-2<power>(-fl)<line_sep>a=torch.linspace(-2 2 steps=100 device=d)<line_sep>clamp_a=fixed_point_quantize(a wl=wl fl=fl clamp=<true> rounding=r)<line_sep>self.assertEqual(t_max clamp_a.max().item())<line_sep>self.assertEqual(t_min clamp_a.min().item())<line_sep>a=torch.linspace(-2 2 steps=100 device=d)<line_sep>no_clamp_a=fixed_point_quantize(a wl=wl fl=fl clamp=<false> rounding=r)<line_sep>self.assertLess(t_max no_clamp_a.max().item())<line_sep>self.assertGreater(t_min no_clamp_a.min().item())<block_end><block_end><block_end><def_stmt>test_float self<block_start>"""test floating point quantization"""<line_sep>formats=[(2 2) (2 3) (3 2)]<for_stmt>exp,man formats<block_start><for_stmt>d ["cpu" "cuda"]<block_start><for_stmt>r ["stochastic" "nearest"]<block_start>a_max=2<power>(2<power>(exp-1))<times>(1-2<power>(-man-1))<line_sep>a_min=2<power>(-(2<power>(exp-1))+1)<line_sep>max_exp=int((2<power>exp)/2)<line_sep>min_exp=-(max_exp-2)<line_sep>mantissa_step=2<power>(-man)<line_sep>min_mantissa=mantissa_step# When denormalized max_mantissa=2-mantissa_step# When normalized, mantissa goes from 1 to 2-mantissa_step a_min=2<power>min_exp<times>min_mantissa<line_sep>a_max=2<power>max_exp<times>max_mantissa<line_sep>expected_vals=[]<line_sep>log(f"With {exp} exponent bits, our exponent goes from {min_exp} to {max_exp}")<line_sep>log(f"With {man} mantissa bits, our mantissa goes from {min_mantissa} (denormalized) to {max_mantissa}")<line_sep>log(f"With {man} mantissa bits and {exp} exponent bits, we can go from {a_min} to {a_max}")<line_sep>representable_normalized=[]<for_stmt>sign [1 -1]<block_start><for_stmt>e range(0 2<power>exp)<block_start><for_stmt>m range(0 2<power>man)<block_start><if_stmt>e<eq>0<block_start>val=sign<times>(2<power>(e+min_exp)<times>m<times>2<power>(-man))<line_sep>log(f"{0<if>sign<eq>1<else>1} {e:0{exp}b} {m:0{man}b} = {sign} * 2^{e+min_exp} * {m<times>2<power>(-man)} \t= {val} (denormalized)")<block_end><else_stmt><block_start>val=sign<times>(2<power>(e+min_exp-1)<times>(1+(m<times>2<power>(-man))))<line_sep>log(f"{0<if>sign<eq>1<else>1} {e:0{exp}b} {m:0{man}b} = {sign} * 2^{e+min_exp-1} * {1+(m<times>2<power>(-man))} \t= {val}")<block_end><if_stmt>val<not><in>expected_vals<block_start>expected_vals.append(val)<block_end><block_end><block_end><block_end>expected_vals.sort()<line_sep># Block box test to get representable numbers <import_stmt>numpy<as>np<line_sep>quant_vals=[]<for_stmt>i np.arange(-30 30 .01)<block_start>a=torch.Tensor([i]).to(device=d)<line_sep>quant_a=float_quantize(a exp=exp man=man rounding=r)<if_stmt>quant_a[0]<not><in>quant_vals<block_start>quant_vals.append(quant_a[0].item())<block_end><block_end>log("Values representable in QPytorch")<line_sep>log(quant_vals)<line_sep>self.assertEqual(quant_vals expected_vals)<block_end><block_end><block_end><block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>unittest.main()<block_end>
<import_stmt>maya.OpenMaya<as>OpenMaya<import_stmt>maya.OpenMayaRender<as>OpenMayaRender<line_sep>
"""Ally Model"""<line_sep>__docformat__="numpy"<import_stmt>ally<import_stmt>pandas<as>pd<def_stmt>get_holdings <arrow>pd.DataFrame<block_start>"""Get holdings from Ally account in pandas df Returns ------- pd.DataFrame Dataframe of positions """<line_sep>a=ally.Ally()<line_sep><return>ally_positions_to_df(a.holdings(dataframe=<true>))<block_end><def_stmt>ally_positions_to_df df:pd.DataFrame<arrow>pd.DataFrame<block_start>"""Clean up ally holdings dataframe Parameters ---------- df : pd.DataFrame Input dataframe of holdings Returns ------- pd.DataFrame Processed holdings """<line_sep>names={"costbasis":"CostBasis" "marketvalue":"MarketValue" "sym":"Symbol" "qty":"Quantity" }<line_sep>df=df.loc[: ["qty" "costbasis" "marketvalue" "sym"]]<line_sep>df[["qty" "costbasis" "marketvalue"]]=df[["qty" "costbasis" "marketvalue"]].astype(float)<line_sep>df=df.rename(columns=names)<line_sep>df["PnL"]=df["MarketValue"]-df["CostBasis"]<line_sep><return>df<block_end><def_stmt>get_history <arrow>pd.DataFrame<block_start>"""Gets transaction history for the account." Returns ------- pd.DataFrame Dataframe of transaction history """<line_sep>a=ally.Ally()<line_sep><return>a.history(dataframe=<true>)<block_end><def_stmt>get_balances <arrow>pd.DataFrame<block_start>"""Gets balance details for the account." Returns ------- pd.DataFrame Dataframe of transaction history """<line_sep>a=ally.Ally()<line_sep><return>a.balances(dataframe=<true>)<block_end><def_stmt>get_stock_quote ticker:str<arrow>pd.DataFrame<block_start>"""Gets quote for stock ticker Parameters ---------- ticker : str Ticker to get. Can be in form of 'tick1,tick2...' Returns ------- pd.DataFrame Dataframe of ticker quote """<line_sep>a=ally.Ally()<line_sep><return>a.quote(ticker fields=["last" "bid" "ask" "opn" "dollar_value" "chg" "vl"] dataframe=<true> )<block_end><def_stmt>get_top_movers list_type:str exchange:str<arrow>pd.DataFrame<block_start>""" Gets top lists from ally Invest API. Documentation for parameters below: https://www.ally.com/api/invest/documentation/market-toplists-get/ Parameters ---------- list_type : str Which list to get data for exchange : str Which exchange to look at Returns ------- pd.DataFrame DataFrame of top movers """<line_sep>a=ally.Ally()<line_sep><return>a.toplists(list_type exchange dataframe=<true>)<block_end>
<import_stmt>pytest<line_sep>pytestmark=[pytest.mark.django_db]<line_sep>@pytest.fixture<def_stmt>answer answers<block_start><return>answers[0]<block_end>@pytest.fixture<def_stmt>crosscheck mixer answer another_user<block_start><return>mixer.blend('homework.AnswerCrossCheck' answer=answer checker=another_user)<block_end><def_stmt>test_not_by_default crosscheck<block_start><assert_stmt>crosscheck.is_checked()<is><false><block_end><def_stmt>test_checked_if_there_are_comments_from_checker crosscheck mixer another_user answer<block_start>mixer.blend('homework.Answer' parent=answer author=another_user)<assert_stmt>crosscheck.is_checked()<is><true><block_end><def_stmt>test_not_checked_if_answers_are_not_children_of_the_checked_answer crosscheck mixer another_user answer<block_start>mixer.blend('homework.Answer' author=another_user)<assert_stmt>crosscheck.is_checked()<is><false><block_end>
"""! @brief Colors used by pyclustering library for visualization. @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause """<class_stmt>color<block_start>"""! @brief Consists titles of colors that are used by pyclustering for visualization. """<line_sep>@staticmethod<def_stmt>get_color sequential_index<block_start>"""! @brief Returns color using round robin to avoid out of range exception. @param[in] sequential_index (uint): Index that should be converted to valid color index. @return (uint) Color from list color.TITLES. """<line_sep><return>color.TITLES[sequential_index%len(color.TITLES)]<block_end>## List of color titles that are used by pyclustering for visualization. TITLES=['red' 'blue' 'darkgreen' 'gold' 'violet' 'deepskyblue' 'darkgrey' 'lightsalmon' 'deeppink' 'yellow' 'black' 'mediumspringgreen' 'orange' 'darkviolet' 'darkblue' 'silver' 'lime' 'pink' 'brown' 'bisque' 'dimgray' 'firebrick' 'darksalmon' 'chartreuse' 'skyblue' 'purple' 'fuchsia' 'palegoldenrod' 'coral' 'hotpink' 'gray' 'tan' 'crimson' 'teal' 'olive']<block_end>
"""add reported post count column to account Revision ID: 0983f1227366 Revises: <PASSWORD> Create Date: 2017-08-03 19:16:55.883575 """<import_from_stmt>alembic op<import_stmt>sqlalchemy<as>sa<line_sep># revision identifiers, used by Alembic. revision='0983f1227366'<line_sep>down_revision='7<PASSWORD>'<line_sep>branch_labels=<none><line_sep>depends_on=<none><def_stmt>upgrade <block_start>op.add_column('accounts' sa.Column('reported_post_count' sa.Integer() nullable=<true>))<block_end><def_stmt>downgrade <block_start>op.drop_column('accounts' 'reported_post_count')<block_end>
<import_stmt>datetime<import_stmt>pytest<import_from_stmt>sqlalchemy create_engine<import_from_stmt>sqlalchemy.orm sessionmaker<import_stmt>Pegasus.db.schema<as>schema<import_from_stmt>Pegasus.db.ensembles EMError Triggers TriggerType<line_sep>@pytest.fixture(scope="function")<def_stmt>session <block_start>""" Create in-memory sqlite database with tables setup and return a db session object. """<line_sep>engine=create_engine("sqlite://")<line_sep># create all tables in the schema schema.Base.metadata.create_all(engine)<line_sep>session=sessionmaker(bind=engine)()<line_sep># create an ensemble entry session.add(schema.Ensemble(name="test-ensemble" created=datetime.datetime.now() updated=datetime.datetime.now() state="ACTIVE" max_running=1 max_planning=1 username="test-user" ))<line_sep>session.commit()<line_sep><yield>session<line_sep># close session, db will be released session.close()<block_end><class_stmt>TestTriggers<block_start><def_stmt>test_get_trigger self session# insert trigger <block_start>t=schema.Trigger(_id=1 ensemble_id=1 name="test-trigger" state="STOPPED" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t)<line_sep>triggers=Triggers(session)<line_sep>expected={"id":1 "ensemble_id":1 "name":"test-trigger" "state":"STOPPED" "workflow":{"script":"/wf.py" "args":["arg1"]} "args":{"timeout":100 "interval":20} "type":"CRON" }<line_sep># get trigger and convert to dict for comparison result=Triggers.get_object(triggers.get_trigger(1 "test-trigger"))<assert_stmt>expected<eq>result<block_end><def_stmt>test_get_trigger_not_found self session<block_start><with_stmt>pytest.raises(EMError)<as>e<block_start>Triggers(session).get_trigger(1 "test-trigger")<block_end><assert_stmt>"No such trigger: test-trigger"<in>str(e)<assert_stmt>e.value.status_code<eq>404<block_end><def_stmt>test_list_triggers self session<block_start>t1=schema.Trigger(_id=1 ensemble_id=1 name="test-trigger1" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t1)<line_sep>t2=schema.Trigger(_id=2 ensemble_id=1 name="test-trigger2" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t2)<line_sep>session.commit()<line_sep>triggers=Triggers(session)<line_sep>result=triggers.list_triggers()<assert_stmt>len(result)<eq>2<block_end><def_stmt>test_list_triggers_by_ensemble self session# add another ensemble to the ensemble table <block_start>session.add(schema.Ensemble(id=2 name="test-ensemble2" created=datetime.datetime.now() updated=datetime.datetime.now() state="ACTIVE" max_running=1 max_planning=1 username="test-user" ))<line_sep>session.commit()<line_sep># add a trigger assigned to test-ensemble2 t=schema.Trigger(_id=1 ensemble_id=2 name="test-trigger1" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t)<line_sep>session.commit()<line_sep>triggers=Triggers(session)<line_sep>result=triggers.list_triggers_by_ensemble(username="test-user" ensemble="test-ensemble2")<assert_stmt>len(result)<eq>1<assert_stmt>Triggers.get_object(result[0])<eq>{"id":1 "ensemble_id":2 "name":"test-trigger1" "state":"READY" "workflow":{"script":"/wf.py" "args":["arg1"]} "args":{"timeout":100 "interval":20} "type":"CRON" }<line_sep>result=triggers.list_triggers_by_ensemble(username="test-user" ensemble="doesntexist")<assert_stmt>len(result)<eq>0<block_end><def_stmt>test_insert_trigger self session<block_start>print(session.query(schema.Ensemble).all())<line_sep>triggers=Triggers(session)<line_sep>triggers.insert_trigger(ensemble_id=1 trigger="test-trigger" trigger_type=TriggerType.CRON.value workflow_script="/wf.py" workflow_args=["arg1"] interval=10 timeout=20 )<line_sep>expected={"id":1 "ensemble_id":1 "name":"test-trigger" "state":"READY" "workflow":{"script":"/wf.py" "args":["arg1"]} "args":{"timeout":20 "interval":10} "type":"CRON" }<line_sep>result=Triggers.get_object(session.query(schema.Trigger).filter_by(ensemble_id=1 name="test-trigger").one())<assert_stmt>expected<eq>result<block_end><def_stmt>test_update_state self session# insert trigger <block_start>t=schema.Trigger(_id=1 ensemble_id=1 name="test-trigger" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t)<line_sep>triggers=Triggers(session)<line_sep>triggers.update_state(ensemble_id=1 trigger_id=1 new_state="RUNNING")<line_sep>expected_state="RUNNING"<line_sep>result=session.query(schema.Trigger).filter_by(_id=1).one().state<assert_stmt>expected_state<eq>result<block_end><def_stmt>test_delete_trigger self session# insert trigger <block_start>t=schema.Trigger(_id=1 ensemble_id=1 name="test-trigger" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>session.add(t)<assert_stmt>len(session.query(schema.Trigger).all())<eq>1<line_sep>triggers=Triggers(session)<line_sep># delete trigger triggers.delete_trigger(ensemble_id=1 trigger="test-trigger")<assert_stmt>len(session.query(schema.Trigger).all())<eq>0<block_end><def_stmt>test_get_object self session<block_start>t=schema.Trigger(_id=1 ensemble_id=1 name="test-trigger" state="READY" workflow=r'{"script":"/wf.py", "args":["arg1"]}' args=r'{"timeout":100, "interval":20}' _type=TriggerType.CRON.value )<line_sep>expected={"id":1 "ensemble_id":1 "name":"test-trigger" "state":"READY" "workflow":{"script":"/wf.py" "args":["arg1"]} "args":{"timeout":100 "interval":20} "type":"CRON" }<line_sep>result=Triggers.get_object(t)<assert_stmt>expected<eq>result<block_end><block_end>
<import_stmt>posixpath<import_stmt>pkg_resources<def_stmt>pkg_walk package top<block_start>""" Walk the package resources. Implementation from os.walk. """<line_sep>names=pkg_resources.resource_listdir(package top)<line_sep>dirs,nondirs=[] []<for_stmt>name names# Forward slashes with pkg_resources <block_start><if_stmt>pkg_resources.resource_isdir(package posixpath.join(top name))<block_start>dirs.append(name)<block_end><else_stmt><block_start>nondirs.append(name)<block_end><block_end><yield>top dirs nondirs<for_stmt>name dirs<block_start>new_path=posixpath.join(top name)<for_stmt>out pkg_walk(package new_path)<block_start><yield>out<block_end><block_end><block_end>
<import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep># # Geometry master configuration # forStandalone APD # # Ideal geometry, needed for simulation <import_from_stmt>Geometry.EcalTestBeam.APDXML_cfi *<line_sep># Calorimeters <import_from_stmt>Geometry.CaloEventSetup.CaloTopology_cfi *<import_from_stmt>Geometry.CaloEventSetup.CaloGeometry_cff *<import_from_stmt>Geometry.CaloEventSetup.EcalTrigTowerConstituents_cfi *<import_from_stmt>Geometry.EcalMapping.EcalMapping_cfi *<import_from_stmt>Geometry.EcalMapping.EcalMappingRecord_cfi *<line_sep>
<import_from_stmt>gazette.spiders.base.instar BaseInstarSpider<class_stmt>SpSaoRoqueSpider(BaseInstarSpider)<block_start>TERRITORY_ID="3550605"<line_sep>name="sp_sao_roque"<line_sep>allowed_domains=["saoroque.sp.gov.br"]<line_sep>start_urls=["https://www.saoroque.sp.gov.br/portal/diario-oficial"]<block_end>
<import_from_stmt>fbrp life_cycle<import_from_stmt>fbrp registrar<import_stmt>argparse<line_sep>@registrar.register_command("down")<class_stmt>down_cmd<block_start>@classmethod<def_stmt>define_argparse cls parser:argparse.ArgumentParser<block_start>parser.add_argument("proc" action="append" nargs="*")<block_end>@staticmethod<def_stmt>exec args:argparse.Namespace<block_start>procs=life_cycle.system_state().procs.keys()<line_sep>given_proc_names=args.proc[0]<if_stmt>given_proc_names<block_start>procs=set(procs)&set(given_proc_names)<block_end><for_stmt>proc_name procs<block_start>life_cycle.set_ask(proc_name life_cycle.Ask.DOWN)<block_end><block_end><block_end>
""" DABNet for image segmentation, implemented in Gluon. Original paper: 'DABNet: Depth-wise Asymmetric Bottleneck for Real-time Semantic Segmentation,' https://arxiv.org/abs/1907.11357. """<line_sep>__all__=['DABNet' 'dabnet_cityscapes']<import_stmt>os<import_from_stmt>mxnet cpu<import_from_stmt>mxnet.gluon nn HybridBlock<import_from_stmt>.common conv1x1 conv3x3 conv3x3_block ConvBlock NormActivation Concurrent InterpolationBlock DualPathSequential PReLU2<class_stmt>DwaConvBlock(HybridBlock)<block_start>""" Depthwise asymmetric separable convolution block. Parameters: ---------- channels : int Number of input/output channels. kernel_size : int Convolution window size. strides : int or tuple/list of 2 int Strides of the convolution. padding : int Padding value for convolution layer. dilation : int, default 1 Dilation value for convolution layer. use_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. bn_epsilon : float, default 1e-5 Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. activation : function or str or None, default nn.Activation('relu') Activation function or name of activation function. """<def_stmt>__init__ self channels kernel_size strides padding dilation=1 use_bias=<false> use_bn=<true> bn_epsilon=1e-5 bn_use_global_stats=<false> bn_cudnn_off=<false> activation=(<lambda>:nn.Activation("relu")) **kwargs<block_start>super(DwaConvBlock self).__init__(**kwargs)<with_stmt>self.name_scope()<block_start>self.conv1=ConvBlock(in_channels=channels out_channels=channels kernel_size=(kernel_size 1) strides=strides padding=(padding 0) dilation=(dilation 1) groups=channels use_bias=use_bias use_bn=use_bn bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=activation)<line_sep>self.conv2=ConvBlock(in_channels=channels out_channels=channels kernel_size=(1 kernel_size) strides=strides padding=(0 padding) dilation=(1 dilation) groups=channels use_bias=use_bias use_bn=use_bn bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=activation)<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>x=self.conv1(x)<line_sep>x=self.conv2(x)<line_sep><return>x<block_end><block_end><def_stmt>dwa_conv3x3_block channels strides=1 padding=1 dilation=1 use_bias=<false> use_bn=<true> bn_epsilon=1e-5 bn_use_global_stats=<false> bn_cudnn_off=<false> activation=(<lambda>:nn.Activation("relu")) **kwargs<block_start>""" 3x3 version of the depthwise asymmetric separable convolution block. Parameters: ---------- channels : int Number of input/output channels. strides : int, default 1 Strides of the convolution. padding : int, default 1 Padding value for convolution layer. dilation : int, default 1 Dilation value for convolution layer. use_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. bn_epsilon : float, default 1e-5 Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. activation : function or str or None, default nn.Activation('relu') Activation function or name of activation function. """<line_sep><return>DwaConvBlock(channels=channels kernel_size=3 strides=strides padding=padding dilation=dilation use_bias=use_bias use_bn=use_bn bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=activation **kwargs)<block_end><class_stmt>DABBlock(HybridBlock)<block_start>""" DABNet specific base block. Parameters: ---------- channels : int Number of input/output channels. dilation : int Dilation value for a dilated branch in the unit. bn_epsilon : float Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. """<def_stmt>__init__ self channels dilation bn_epsilon bn_use_global_stats=<false> bn_cudnn_off=<false> **kwargs<block_start>super(DABBlock self).__init__(**kwargs)<line_sep>mid_channels=channels<floordiv>2<with_stmt>self.name_scope()<block_start>self.norm_activ1=NormActivation(in_channels=channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(channels)))<line_sep>self.conv1=conv3x3_block(in_channels=channels out_channels=mid_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(mid_channels)))<line_sep>self.branches=Concurrent(stack=<true>)<line_sep>self.branches.add(dwa_conv3x3_block(channels=mid_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(mid_channels))))<line_sep>self.branches.add(dwa_conv3x3_block(channels=mid_channels padding=dilation dilation=dilation bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(mid_channels))))<line_sep>self.norm_activ2=NormActivation(in_channels=mid_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(mid_channels)))<line_sep>self.conv2=conv1x1(in_channels=mid_channels out_channels=channels)<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>identity=x<line_sep>x=self.norm_activ1(x)<line_sep>x=self.conv1(x)<line_sep>x=self.branches(x)<line_sep>x=x.sum(axis=1)<line_sep>x=self.norm_activ2(x)<line_sep>x=self.conv2(x)<line_sep>x=x+identity<line_sep><return>x<block_end><block_end><class_stmt>DownBlock(HybridBlock)<block_start>""" DABNet specific downsample block for the main branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_epsilon : float Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. """<def_stmt>__init__ self in_channels out_channels bn_epsilon bn_use_global_stats=<false> bn_cudnn_off=<false> **kwargs<block_start>super(DownBlock self).__init__(**kwargs)<line_sep>self.expand=(in_channels<l>out_channels)<line_sep>mid_channels=out_channels-in_channels<if>self.expand<else>out_channels<with_stmt>self.name_scope()<block_start>self.conv=conv3x3(in_channels=in_channels out_channels=mid_channels strides=2)<if_stmt>self.expand<block_start>self.pool=nn.MaxPool2D(pool_size=2 strides=2)<block_end>self.norm_activ=NormActivation(in_channels=out_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(out_channels)))<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>y=self.conv(x)<if_stmt>self.expand<block_start>z=self.pool(x)<line_sep>y=F.concat(y z dim=1)<block_end>y=self.norm_activ(y)<line_sep><return>y<block_end><block_end><class_stmt>DABUnit(HybridBlock)<block_start>""" DABNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. dilations : list of int Dilations for blocks. bn_epsilon : float Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. """<def_stmt>__init__ self in_channels out_channels dilations bn_epsilon bn_use_global_stats=<false> bn_cudnn_off=<false> **kwargs<block_start>super(DABUnit self).__init__(**kwargs)<line_sep>mid_channels=out_channels<floordiv>2<with_stmt>self.name_scope()<block_start>self.down=DownBlock(in_channels=in_channels out_channels=mid_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off)<line_sep>self.blocks=nn.HybridSequential(prefix="")<for_stmt>i,dilation enumerate(dilations)<block_start>self.blocks.add(DABBlock(channels=mid_channels dilation=dilation bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off))<block_end><block_end><block_end><def_stmt>hybrid_forward self F x<block_start>x=self.down(x)<line_sep>y=self.blocks(x)<line_sep>x=F.concat(y x dim=1)<line_sep><return>x<block_end><block_end><class_stmt>DABStage(HybridBlock)<block_start>""" DABNet stage. Parameters: ---------- x_channels : int Number of input/output channels for x. y_in_channels : int Number of input channels for y. y_out_channels : int Number of output channels for y. dilations : list of int Dilations for blocks. bn_epsilon : float Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. """<def_stmt>__init__ self x_channels y_in_channels y_out_channels dilations bn_epsilon bn_use_global_stats=<false> bn_cudnn_off=<false> **kwargs<block_start>super(DABStage self).__init__(**kwargs)<line_sep>self.use_unit=(len(dilations)<g>0)<with_stmt>self.name_scope()<block_start>self.x_down=nn.AvgPool2D(pool_size=3 strides=2 padding=1)<if_stmt>self.use_unit<block_start>self.unit=DABUnit(in_channels=y_in_channels out_channels=(y_out_channels-x_channels) dilations=dilations bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off)<block_end>self.norm_activ=NormActivation(in_channels=y_out_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(y_out_channels)))<block_end><block_end><def_stmt>hybrid_forward self F y x<block_start>x=self.x_down(x)<if_stmt>self.use_unit<block_start>y=self.unit(y)<block_end>y=F.concat(y x dim=1)<line_sep>y=self.norm_activ(y)<line_sep><return>y x<block_end><block_end><class_stmt>DABInitBlock(HybridBlock)<block_start>""" DABNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_epsilon : float Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. """<def_stmt>__init__ self in_channels out_channels bn_epsilon bn_use_global_stats=<false> bn_cudnn_off=<false> **kwargs<block_start>super(DABInitBlock self).__init__(**kwargs)<with_stmt>self.name_scope()<block_start>self.conv1=conv3x3_block(in_channels=in_channels out_channels=out_channels strides=2 bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(out_channels)))<line_sep>self.conv2=conv3x3_block(in_channels=out_channels out_channels=out_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(out_channels)))<line_sep>self.conv3=conv3x3_block(in_channels=out_channels out_channels=out_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off activation=(<lambda>:PReLU2(out_channels)))<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>x=self.conv1(x)<line_sep>x=self.conv2(x)<line_sep>x=self.conv3(x)<line_sep><return>x<block_end><block_end><class_stmt>DABNet(HybridBlock)<block_start>""" DABNet model from 'DABNet: Depth-wise Asymmetric Bottleneck for Real-time Semantic Segmentation,' https://arxiv.org/abs/1907.11357. Parameters: ---------- channels : list of int Number of output channels for each unit (for y-branch). init_block_channels : int Number of output channels for the initial unit. dilations : list of list of int Dilations for blocks. bn_epsilon : float, default 1e-5 Small float added to variance in Batch norm. bn_use_global_stats : bool, default False Whether global moving statistics is used instead of local batch-norm for BatchNorm layers. bn_cudnn_off : bool, default False Whether to disable CUDNN batch normalization operator. aux : bool, default False Whether to output an auxiliary result. fixed_size : bool, default False Whether to expect fixed spatial size of input image. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (1024, 2048) Spatial size of the expected input image. classes : int, default 19 Number of segmentation classes. """<def_stmt>__init__ self channels init_block_channels dilations bn_epsilon=1e-5 bn_use_global_stats=<false> bn_cudnn_off=<false> aux=<false> fixed_size=<false> in_channels=3 in_size=(1024 2048) classes=19 **kwargs<block_start>super(DABNet self).__init__(**kwargs)<assert_stmt>(aux<is><not><none>)<assert_stmt>(fixed_size<is><not><none>)<assert_stmt>((in_size[0]%8<eq>0)<and>(in_size[1]%8<eq>0))<line_sep>self.in_size=in_size<line_sep>self.classes=classes<line_sep>self.fixed_size=fixed_size<with_stmt>self.name_scope()<block_start>self.features=DualPathSequential(return_two=<false> first_ordinals=1 last_ordinals=0)<line_sep>self.features.add(DABInitBlock(in_channels=in_channels out_channels=init_block_channels bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off))<line_sep>y_in_channels=init_block_channels<for_stmt>i,(y_out_channels dilations_i) enumerate(zip(channels dilations))<block_start>self.features.add(DABStage(x_channels=in_channels y_in_channels=y_in_channels y_out_channels=y_out_channels dilations=dilations_i bn_epsilon=bn_epsilon bn_use_global_stats=bn_use_global_stats bn_cudnn_off=bn_cudnn_off))<line_sep>y_in_channels=y_out_channels<block_end>self.classifier=conv1x1(in_channels=y_in_channels out_channels=classes)<line_sep>self.up=InterpolationBlock(scale_factor=8)<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>in_size=self.in_size<if>self.fixed_size<else>x.shape[2:]<line_sep>y=self.features(x x)<line_sep>y=self.classifier(y)<line_sep>y=self.up(y in_size)<line_sep><return>y<block_end><block_end><def_stmt>get_dabnet model_name=<none> pretrained=<false> ctx=cpu() root=os.path.join("~" ".mxnet" "models") **kwargs<block_start>""" Create DABNet model with specific parameters. Parameters: ---------- model_name : str or None, default None Model name for loading pretrained model. pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. """<line_sep>init_block_channels=32<line_sep>channels=[35 131 259]<line_sep>dilations=[[] [2 2 2] [4 4 8 8 16 16]]<line_sep>bn_epsilon=1e-3<line_sep>net=DABNet(channels=channels init_block_channels=init_block_channels dilations=dilations bn_epsilon=bn_epsilon **kwargs)<if_stmt>pretrained<block_start><if_stmt>(model_name<is><none>)<or>(<not>model_name)<block_start><raise>ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")<block_end><import_from_stmt>.model_store get_model_file<line_sep>net.load_parameters(filename=get_model_file(model_name=model_name local_model_store_dir_path=root) ctx=ctx ignore_extra=<true>)<block_end><return>net<block_end><def_stmt>dabnet_cityscapes classes=19 **kwargs<block_start>""" DABNet model for Cityscapes from 'DABNet: Depth-wise Asymmetric Bottleneck for Real-time Semantic Segmentation,' https://arxiv.org/abs/1907.11357. Parameters: ---------- classes : int, default 19 Number of segmentation classes. pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. """<line_sep><return>get_dabnet(classes=classes model_name="dabnet_cityscapes" **kwargs)<block_end><def_stmt>_calc_width net<block_start><import_stmt>numpy<as>np<line_sep>net_params=net.collect_params()<line_sep>weight_count=0<for_stmt>param net_params.values()<block_start><if_stmt>(param.shape<is><none>)<or>(<not>param._differentiable)<block_start><continue><block_end>weight_count<augadd>np.prod(param.shape)<block_end><return>weight_count<block_end><def_stmt>_test <block_start><import_stmt>mxnet<as>mx<line_sep>pretrained=<false><line_sep>fixed_size=<true><line_sep>in_size=(1024 2048)<line_sep>classes=19<line_sep>models=[dabnet_cityscapes ]<for_stmt>model models<block_start>net=model(pretrained=pretrained in_size=in_size fixed_size=fixed_size)<line_sep>ctx=mx.cpu()<if_stmt><not>pretrained<block_start>net.initialize(ctx=ctx)<block_end># net.hybridize() weight_count=_calc_width(net)<line_sep>print("m={}, {}".format(model.__name__ weight_count))<assert_stmt>(model<ne>dabnet_cityscapes<or>weight_count<eq>756643)<line_sep>batch=4<line_sep>x=mx.nd.random.normal(shape=(batch 3 in_size[0] in_size[1]) ctx=ctx)<line_sep>y=net(x)<assert_stmt>(y.shape<eq>(batch classes in_size[0] in_size[1]))<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>_test()<block_end>
<import_stmt>sys<import_stmt>re<import_stmt>os<import_stmt>fnmatch<import_from_stmt>os walk<as>py_walk<def_stmt>walk top callback args<block_start><for_stmt>root,dirs,files py_walk(top)<block_start>callback(args root files)<block_end><block_end><def_stmt>find_data_files srcdir destdir *wildcards **kw<block_start>""" get a list of all files under the srcdir matching wildcards, returned in a format to be used for install_data """<def_stmt>walk_helper arg dirname files<block_start><if_stmt>'.svn'<in>dirname<block_start><return><block_end>names=[]<line_sep>lst,wildcards,dirnameconverter,destdir=arg<for_stmt>wc wildcards<block_start>wc_name=os.path.normpath(os.path.join(dirname wc))<for_stmt>f files<block_start>filename=os.path.normpath(os.path.join(dirname f))<if_stmt>fnmatch.fnmatch(filename wc_name)<and><not>os.path.isdir(filename)<block_start>names.append(filename)<block_end><block_end><block_end><if_stmt>names<block_start>destdirname=dirnameconverter.sub(destdir dirname)<line_sep>lst.append((destdirname names))<block_end><block_end>file_list=[]<line_sep>recursive=kw.get('recursive' <true>)<line_sep>converter=re.compile('^({0})'.format(srcdir))<if_stmt>recursive<block_start>walk(srcdir walk_helper (file_list wildcards converter destdir))<block_end><else_stmt><block_start>walk_helper((file_list wildcards converter destdir) srcdir [os.path.basename(f)<for>f glob.glob(os.path.join(srcdir '*'))])<block_end><return>file_list<block_end>
<import_stmt>os<import_stmt>sys<line_sep>BASE_DIR=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))<line_sep>sys.path.append(BASE_DIR)<import_from_stmt>tools.path ILSVRC2012_path<import_from_stmt>simpleAICV.classification backbones<import_from_stmt>simpleAICV.classification losses<import_stmt>torchvision.transforms<as>transforms<import_stmt>torchvision.datasets<as>datasets<class_stmt>config<block_start>val_dataset_path=os.path.join(ILSVRC2012_path 'val')<line_sep>network='resnet18'<line_sep>pretrained=<true><line_sep>num_classes=1000<line_sep>input_image_size=224<line_sep>scale=256/224<line_sep>model=backbones.__dict__[network](**{'pretrained':pretrained 'num_classes':num_classes })<line_sep>criterion=losses.__dict__['CELoss']()<line_sep>val_dataset=datasets.ImageFolder(val_dataset_path transforms.Compose([transforms.Resize(int(input_image_size<times>scale)) transforms.CenterCrop(input_image_size) transforms.ToTensor() transforms.Normalize(mean=[0.485 0.456 0.406] std=[0.229 0.224 0.225]) ]))<line_sep>distributed=<true><line_sep>seed=0<line_sep>batch_size=256<line_sep>num_workers=16<line_sep>trained_model_path=''<block_end>
# Copyright 2021, The TensorFlow Federated Authors. # # 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_from_stmt>absl.testing absltest<import_from_stmt>tensorflow_federated.python.core.impl.executors data_conversions<import_from_stmt>tensorflow_federated.python.core.impl.types placements<class_stmt>DataConversionsTest(absltest.TestCase)<block_start><def_stmt>test_converts_placement_keyed_to_string_keyed self<block_start>num_clients=10<line_sep>placement_keyed_mapping={placements.SERVER:1 placements.CLIENTS:num_clients}<line_sep>expected_string_keyed_mapping={placements.SERVER.uri:1 placements.CLIENTS.uri:num_clients}<line_sep>string_keyed_mapping=data_conversions.convert_cardinalities_dict_to_string_keyed(placement_keyed_mapping)<line_sep>self.assertEqual(string_keyed_mapping expected_string_keyed_mapping)<block_end><def_stmt>test_raises_string_keyed_mapping self<block_start>string_keyed_mapping={placements.SERVER.uri:1 placements.CLIENTS.uri:5}<with_stmt>self.assertRaises(TypeError)<block_start>data_conversions.convert_cardinalities_dict_to_string_keyed(string_keyed_mapping)<block_end><block_end><def_stmt>test_raises_non_integer_values self<block_start>placement_keyed_non_integer_valued_mapping={placements.SERVER:1. placements.CLIENTS:10.}<with_stmt>self.assertRaises(TypeError)<block_start>data_conversions.convert_cardinalities_dict_to_string_keyed(placement_keyed_non_integer_valued_mapping)<block_end><block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>absltest.main()<block_end>
<import_from_stmt>collections namedtuple<import_from_stmt>django.conf settings<import_from_stmt>corehq.apps.domain.dbaccessors get_doc_ids_in_domain_by_class get_docs_in_domain_by_class <def_stmt>group_by_domain domain<block_start><import_from_stmt>corehq.apps.groups.models Group<line_sep><return>get_docs_in_domain_by_class(domain Group)<block_end><def_stmt>_group_by_name domain name **kwargs<block_start><import_from_stmt>corehq.apps.groups.models Group<line_sep><return>list(Group.view('groups/by_name' key=[domain name] **kwargs))<block_end><def_stmt>group_by_name domain name include_docs=<true><block_start><return>_group_by_name(domain name include_docs=include_docs )<block_end><def_stmt>stale_group_by_name domain name include_docs=<true><block_start><return>_group_by_name(domain name include_docs=include_docs stale=settings.COUCH_STALE_QUERY )<block_end><def_stmt>refresh_group_views <block_start><import_from_stmt>corehq.apps.groups.models Group<for_stmt>view_name ['groups/by_name' ]<block_start>Group.view(view_name include_docs=<false> limit=1 ).fetch()<block_end><block_end><def_stmt>get_group_ids_by_domain domain<block_start><import_from_stmt>corehq.apps.groups.models Group<line_sep><return>get_doc_ids_in_domain_by_class(domain Group)<block_end>GroupIdName=namedtuple('GroupIdName' 'id name')<def_stmt>get_group_id_name_map_by_user user_id limit=<none><block_start><import_from_stmt>corehq.apps.groups.models Group<line_sep>view_results=Group.view('groups/by_user' key=user_id include_docs=<false> limit=limit)<line_sep><return>[GroupIdName(r['id'] r['value'][1])<for>r view_results]<block_end>
<import_from_stmt>changes.testutils APITestCase<class_stmt>JenkinsMasterBlacklist(APITestCase)<block_start><def_stmt>test_add_remove_blacklist self<block_start>path='/api/0/jenkins_master_blacklist/'<line_sep># Add to blacklist data=dict(master_url='https://jenkins-master-a')<line_sep>resp=self.client.post(path data=data)<assert_stmt>resp.status_code<eq>200<line_sep>data=dict(master_url='https://jenkins-master-b')<line_sep>resp=self.client.post(path data=data)<assert_stmt>resp.status_code<eq>200<line_sep>resp=self.client.get(path)<line_sep>resp.status_code<eq>200<line_sep>result=self.unserialize(resp)<assert_stmt>'https://jenkins-master-a'<in>result['blacklist']<assert_stmt>'https://jenkins-master-b'<in>result['blacklist']<line_sep># Delete from blacklist data=dict(master_url='https://jenkins-master-a' remove=1)<line_sep>resp=self.client.post(path data=data)<line_sep>resp.status_code<eq>200<assert_stmt>['https://jenkins-master-b']<eq>self.unserialize(resp)['blacklist']<block_end><def_stmt>test_re_add self<block_start>path='/api/0/jenkins_master_blacklist/'<line_sep>data=dict(master_url='https://jenkins-master-a')<line_sep>resp=self.client.post(path data=data)<assert_stmt>resp.status_code<eq>200<line_sep>data=dict(master_url='https://jenkins-master-a')<line_sep>resp=self.client.post(path data=data)<assert_stmt>resp.status_code<eq>200<line_sep>result=self.unserialize(resp)<assert_stmt>'warning'<in>result<block_end><def_stmt>test_remove_missing self<block_start>path='/api/0/jenkins_master_blacklist/'<line_sep>data=dict(master_url='https://jenkins-master-a' remove=1)<line_sep>resp=self.client.post(path data=data)<assert_stmt>resp.status_code<eq>200<line_sep>result=self.unserialize(resp)<assert_stmt>'warning'<in>result<block_end><block_end>
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. <import_stmt>os<import_stmt>sys<import_stmt>torch<import_from_stmt>torchvision.utils save_image<import_from_stmt>options.train_options TrainOptions<import_stmt>data<import_from_stmt>util.iter_counter IterationCounter<import_from_stmt>util.util print_current_errors<import_from_stmt>util.util mkdir<import_from_stmt>trainers.pix2pix_trainer Pix2PixTrainer<if_stmt>__name__<eq>'__main__'# parse options <block_start>opt=TrainOptions().parse()<line_sep># print options to help debugging print(' '.join(sys.argv))<line_sep>dataloader=data.create_dataloader(opt)<line_sep>len_dataloader=len(dataloader)<line_sep># create tool for counting iterations iter_counter=IterationCounter(opt len(dataloader))<line_sep># create trainer for our model trainer=Pix2PixTrainer(opt resume_epoch=iter_counter.first_epoch)<line_sep>save_root=os.path.join('checkpoints' opt.name 'train')<line_sep>mkdir(save_root)<for_stmt>epoch iter_counter.training_epochs()<block_start>opt.epoch=epoch<line_sep>iter_counter.record_epoch_start(epoch)<for_stmt>i,data_i enumerate(dataloader start=iter_counter.epoch_iter)<block_start>iter_counter.record_one_iteration()<line_sep># Training # train generator <if_stmt>i%opt.D_steps_per_G<eq>0<block_start>trainer.run_generator_one_step(data_i)<block_end># train discriminator trainer.run_discriminator_one_step(data_i)<if_stmt>iter_counter.needs_printing()<block_start>losses=trainer.get_latest_losses()<try_stmt><block_start>print_current_errors(opt epoch iter_counter.epoch_iter iter_counter.epoch_iter_num losses iter_counter.time_per_iter)<block_end><except_stmt>OSError<as>err<block_start>print(err)<block_end><block_end><if_stmt>iter_counter.needs_displaying()<block_start>imgs_num=data_i['label'].shape[0]<if_stmt>opt.dataset_mode<eq>'deepfashionHD'<block_start>label=data_i['label'][: :3 : :]<block_end>show_size=opt.display_winsize<line_sep>imgs=torch.cat((label.cpu() data_i['ref'].cpu() trainer.get_latest_generated().data.cpu() data_i['image'].cpu()) 0)<try_stmt><block_start>save_name='%08d_%08d.png'%(epoch iter_counter.total_steps_so_far)<line_sep>save_name=os.path.join(save_root save_name)<line_sep>save_image(imgs save_name nrow=imgs_num padding=0 normalize=<true>)<block_end><except_stmt>OSError<as>err<block_start>print(err)<block_end><block_end><if_stmt>iter_counter.needs_saving()<block_start>print('saving the latest model (epoch %d, total_steps %d)'%(epoch iter_counter.total_steps_so_far))<try_stmt><block_start>trainer.save('latest')<line_sep>iter_counter.record_current_iter()<block_end><except_stmt>OSError<as>err<block_start><import_stmt>pdb<line_sep>pdb.set_trace()<line_sep>print(err)<block_end><block_end><block_end>trainer.update_learning_rate(epoch)<line_sep>iter_counter.record_epoch_end()<if_stmt>epoch%opt.save_epoch_freq<eq>0<or>epoch<eq>iter_counter.total_epochs<block_start>print('saving the model at the end of epoch %d, iters %d'%(epoch iter_counter.total_steps_so_far))<try_stmt><block_start>trainer.save('latest')<line_sep>trainer.save(epoch)<block_end><except_stmt>OSError<as>err<block_start>print(err)<block_end><block_end><block_end>print('Training was successfully finished.')<block_end>
<import_from_future_stmt> absolute_import division unicode_literals<import_from_stmt>flask_restful.reqparse RequestParser<import_from_stmt>sqlalchemy or_<import_from_stmt>sqlalchemy.orm contains_eager joinedload<import_from_stmt>changes.api.auth get_current_user<import_from_stmt>changes.api.base APIView<import_from_stmt>changes.constants Cause Result<import_from_stmt>changes.models.author Author<import_from_stmt>changes.models.build Build<import_from_stmt>changes.models.project Project<import_from_stmt>changes.models.source Source<import_from_stmt>changes.utils.phabricator_utils might_be_diffusion_iden get_hash_from_diffusion_iden <def_stmt>validate_author author_id<block_start>current_user=get_current_user()<if_stmt>author_id<eq>'me'<and><not>current_user<block_start><raise>ValueError('You are not signed in.')<block_end><return>Author.find(author_id current_user)<block_end><class_stmt>ProjectBuildIndexAPIView(APIView)<block_start>get_parser=RequestParser()<line_sep>get_parser.add_argument('include_patches' type=<lambda>x:bool(int(x)) location='args' default=<true>)<line_sep>get_parser.add_argument('author' type=validate_author location='args' dest='authors')<line_sep>get_parser.add_argument('query' type=unicode location='args')<line_sep>get_parser.add_argument('source' type=unicode location='args')<line_sep>get_parser.add_argument('result' type=unicode location='args' choices=('failed' 'passed' 'aborted' 'unknown' ''))<line_sep>get_parser.add_argument('patches_only' type=<lambda>x:bool(int(x)) location='args' default=<false>)<line_sep>get_parser.add_argument('cause' type=unicode location='args' choices=('unknown' 'manual' 'push' 'retry' 'snapshot' ''))<line_sep>get_parser.add_argument('tag' type=unicode action='append' location='args')<def_stmt>get self project_id<block_start>project=Project.get(project_id)<if_stmt><not>project<block_start><return>'' 404<block_end>args=self.get_parser.parse_args()<line_sep>filters=[]<if_stmt>args.authors<block_start>filters.append(Build.author_id.in_([a.id<for>a args.authors]))<block_end><elif_stmt>args.authors<is><not><none><block_start><return>[]<block_end><if_stmt>args.source<block_start>filters.append(Build.target.startswith(args.source))<block_end># is this from the search bar <if_stmt>args.query<block_start>clauses=[]<line_sep># search by revision title clauses.append(Build.label.contains(args.query))<line_sep># search by prefix clauses.append(Build.target.startswith(args.query))<line_sep># allows users to paste a full commit hash and still # find the relevant build(s). Should be fine for mercurial/git, # and svn will never have long enough strings <if_stmt>len(args.query)<g>12<block_start>clauses.append(Build.target.startswith(args.query[0:12]))<block_end># if they searched for something that looks like a phabricator # identifier, try to find it <if_stmt>might_be_diffusion_iden(args.query)<block_start>possible_hash=get_hash_from_diffusion_iden(args.query)<if_stmt>possible_hash# the query should always be at least as long or longer than # our commit identifiers <block_start>clauses.append(Build.target.startswith(possible_hash[0:12]))<block_end><block_end>filters.append(or_(*clauses))<block_end><if_stmt>args.result<block_start>filters.append(Build.result<eq>Result[args.result])<block_end><if_stmt>args.cause<block_start>filters.append(Build.cause<eq>Cause[args.cause])<block_end><if_stmt>args.tag<block_start>tags=filter(bool args.tag)<line_sep># Avoid empty tags, which historically are meant to mean "no tag" restriction. <if_stmt>tags<block_start>filters.append(or_(*[Build.tags.any(t)<for>t tags]))<block_end><block_end><if_stmt>args.patches_only<block_start>filters.append(Source.patch_id<ne><none>)# NOQA <block_end><elif_stmt><not>args.include_patches<block_start>filters.append(Source.patch_id<eq><none>)<block_end># NOQA queryset=Build.query.options(joinedload('project' innerjoin=<true>) joinedload('author') contains_eager('source').joinedload('revision') ).join(Source Source.id<eq>Build.source_id ).filter(Build.project_id<eq>project.id Source.repository_id<eq>project.repository_id *filters).order_by(Build.date_created.desc())<line_sep><return>self.paginate(queryset)<block_end><block_end>
#----------------------------------------------------------------------------- # Copyright (c) 2005-2021, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- name='pyi_testmod_relimp.relimp1'<import_from_stmt>. relimp2<as>upper# noqa: E402 <import_from_stmt>.pyi_testmod_relimp relimp2<as>lower# noqa: E402 <assert_stmt>upper.name<eq>'pyi_testmod_relimp.relimp2'<assert_stmt>lower.name<eq>'pyi_testmod_relimp.pyi_testmod_relimp.relimp2'<if_stmt>upper.__name__<eq>lower.__name__<block_start><raise>SystemExit("Imported the same module")<block_end><if_stmt>upper.__file__<eq>lower.__file__<block_start><raise>SystemExit("Imported the same file")<block_end>
<import_from_stmt>os makedirs<import_from_stmt>os.path exists join<import_from_stmt>fedot.core.composer.gp_composer.gp_composer GPComposerBuilder GPComposerRequirements<import_from_stmt>fedot.core.data.data InputData<import_from_stmt>fedot.core.data.data_split train_test_data_setup<import_from_stmt>fedot.core.optimisers.gp_comp.gp_optimiser GPGraphOptimiserParameters<import_from_stmt>fedot.core.optimisers.gp_comp.operators.inheritance GeneticSchemeTypesEnum<import_from_stmt>fedot.core.pipelines.node PrimaryNode SecondaryNode<import_from_stmt>fedot.core.pipelines.pipeline Pipeline<import_from_stmt>fedot.core.repository.operation_types_repository get_operations_for_task<import_from_stmt>fedot.core.repository.quality_metrics_repository ClassificationMetricsEnum MetricsRepository RegressionMetricsEnum<import_from_stmt>fedot.core.repository.tasks Task TaskTypesEnum<import_from_stmt>fedot.core.utils default_fedot_data_dir fedot_project_root<import_from_stmt>fedot.sensitivity.node_sa_approaches NodeDeletionAnalyze NodeReplaceOperationAnalyze<import_from_stmt>fedot.sensitivity.nodes_sensitivity NodesAnalysis<def_stmt>get_three_depth_manual_class_pipeline <block_start>logit_node_primary=PrimaryNode('logit')<line_sep>xgb_node_primary=PrimaryNode('xgboost')<line_sep>xgb_node_primary_second=PrimaryNode('xgboost')<line_sep>qda_node_third=SecondaryNode('qda' nodes_from=[xgb_node_primary_second])<line_sep>knn_node_third=SecondaryNode('knn' nodes_from=[logit_node_primary xgb_node_primary])<line_sep>knn_root=SecondaryNode('knn' nodes_from=[qda_node_third knn_node_third])<line_sep>pipeline=Pipeline(knn_root)<line_sep><return>pipeline<block_end><def_stmt>get_three_depth_manual_regr_pipeline <block_start>xgb_primary=PrimaryNode('xgbreg')<line_sep>knn_primary=PrimaryNode('knnreg')<line_sep>dtreg_secondary=SecondaryNode('dtreg' nodes_from=[xgb_primary])<line_sep>rfr_secondary=SecondaryNode('rfr' nodes_from=[knn_primary])<line_sep>knnreg_root=SecondaryNode('knnreg' nodes_from=[dtreg_secondary rfr_secondary])<line_sep>pipeline=Pipeline(knnreg_root)<line_sep><return>pipeline<block_end><def_stmt>get_composed_pipeline dataset_to_compose task metric_function# the search of the models provided by the framework that can be used as nodes in a pipeline for the selected task <block_start>available_model_types=get_operations_for_task(task=task mode='model')<line_sep># the choice and initialisation of the GP search composer_requirements=GPComposerRequirements(primary=available_model_types secondary=available_model_types max_arity=3 max_depth=3 pop_size=20 num_of_generations=20 crossover_prob=0.8 mutation_prob=0.8)<line_sep># GP optimiser parameters choice scheme_type=GeneticSchemeTypesEnum.steady_state<line_sep>optimiser_parameters=GPGraphOptimiserParameters(genetic_scheme_type=scheme_type)<line_sep># Create builder for composer and set composer params builder=GPComposerBuilder(task=task).with_requirements(composer_requirements).with_metrics(metric_function).with_optimiser_parameters(optimiser_parameters)<line_sep># Create GP-based composer composer=builder.build()<line_sep># the optimal pipeline generation by composition - the most time-consuming task pipeline_evo_composed=composer.compose_pipeline(data=dataset_to_compose is_visualise=<true>)<line_sep><return>pipeline_evo_composed<block_end><def_stmt>get_scoring_data <block_start>file_path_train='cases/data/scoring/scoring_train.csv'<line_sep>full_path_train=join(str(fedot_project_root()) file_path_train)<line_sep># a dataset for a final validation of the composed model file_path_test='cases/data/scoring/scoring_test.csv'<line_sep>full_path_test=join(str(fedot_project_root()) file_path_test)<line_sep>task=Task(TaskTypesEnum.classification)<line_sep>train=InputData.from_csv(full_path_train task=task)<line_sep>test=InputData.from_csv(full_path_test task=task)<line_sep><return>train test<block_end><def_stmt>get_kc2_data <block_start>file_path='cases/data/kc2/kc2.csv'<line_sep>full_path=join(str(fedot_project_root()) file_path)<line_sep>task=Task(TaskTypesEnum.classification)<line_sep>data=InputData.from_csv(full_path task=task)<line_sep>train,test=train_test_data_setup(data)<line_sep><return>train test<block_end><def_stmt>get_cholesterol_data <block_start>file_path='cases/data/cholesterol/cholesterol.csv'<line_sep>full_path=join(str(fedot_project_root()) file_path)<line_sep>task=Task(TaskTypesEnum.regression)<line_sep>data=InputData.from_csv(full_path task=task)<line_sep>train,test=train_test_data_setup(data)<line_sep><return>train test<block_end><def_stmt>pipeline_by_task task metric data is_composed<block_start><if_stmt>is_composed<block_start>pipeline=get_composed_pipeline(data task metric_function=metric)<block_end><else_stmt><block_start><if_stmt>task.task_type.name<eq>'classification'<block_start>pipeline=get_three_depth_manual_class_pipeline()<block_end><else_stmt><block_start>pipeline=get_three_depth_manual_regr_pipeline()<block_end><block_end><return>pipeline<block_end><def_stmt>run_analysis_case train_data:InputData test_data:InputData case_name:str task metric is_composed=<false> result_path=<none><block_start>pipeline=pipeline_by_task(task=task metric=metric data=train_data is_composed=is_composed)<line_sep>pipeline.fit(train_data)<if_stmt><not>result_path<block_start>result_path=join(default_fedot_data_dir() 'sensitivity' f'{case_name}')<if_stmt><not>exists(result_path)<block_start>makedirs(result_path)<block_end><block_end>pipeline.show(path=result_path)<line_sep>pipeline_analysis_result=NodesAnalysis(pipeline=pipeline train_data=train_data test_data=test_data path_to_save=result_path approaches=[NodeDeletionAnalyze NodeReplaceOperationAnalyze]).analyze()<line_sep>print(f'pipeline analysis result {pipeline_analysis_result}')<block_end><def_stmt>run_class_scoring_case is_composed:bool path_to_save=<none><block_start>train_data,test_data=get_scoring_data()<line_sep>task=Task(TaskTypesEnum.classification)<line_sep># the choice of the metric for the pipeline quality assessment during composition metric_function=MetricsRepository().metric_by_id(ClassificationMetricsEnum.ROCAUC_penalty)<if_stmt>is_composed<block_start>case='scoring_composed'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<true> result_path=path_to_save)<block_end><else_stmt><block_start>case='scoring'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<false> result_path=path_to_save)<block_end><block_end><def_stmt>run_class_kc2_case is_composed:bool=<false> path_to_save=<none><block_start>train_data,test_data=get_kc2_data()<line_sep>task=Task(TaskTypesEnum.classification)<line_sep># the choice of the metric for the pipeline quality assessment during composition metric_function=MetricsRepository().metric_by_id(ClassificationMetricsEnum.ROCAUC_penalty)<if_stmt>is_composed<block_start>case='kc2_composed'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<true> result_path=path_to_save)<block_end><else_stmt><block_start>case='kc2'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<false> result_path=path_to_save)<block_end><block_end><def_stmt>run_regr_case is_composed:bool=<false> path_to_save=<none><block_start>train_data,test_data=get_cholesterol_data()<line_sep>task=Task(TaskTypesEnum.regression)<line_sep># the choice of the metric for the pipeline quality assessment during composition metric_function=MetricsRepository().metric_by_id(RegressionMetricsEnum.RMSE)<if_stmt>is_composed<block_start>case='cholesterol_composed'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<true> result_path=path_to_save)<block_end><else_stmt><block_start>case='cholesterol'<line_sep>run_analysis_case(train_data test_data case task metric=metric_function is_composed=<false> result_path=path_to_save)<block_end><block_end><if_stmt>__name__<eq>'__main__'# scoring case manual <block_start>run_class_scoring_case(is_composed=<false>)<line_sep># kc2 case manual run_class_kc2_case(is_composed=<false>)<line_sep># cholesterol regr case run_regr_case(is_composed=<false>)<block_end>
<class_stmt>Car(object)<block_start>"""A car class"""<def_stmt>__init__ self model make color<block_start>self.model=model<line_sep>self.make=make<line_sep>self.color=color<line_sep>self.price=<none><block_end><def_stmt>get_price self<block_start><return>self.price<block_end><def_stmt>set_price self value<block_start>self.price=value<block_end><block_end>availableCars=[]<def_stmt>main <block_start><global>availableCars<line_sep>#Create a new car obj carObj=Car("<NAME>" "2011" "Black")<line_sep>carObj.set_price(950000)# Set price # Add this to available cars availableCars.append(carObj)<line_sep>print('TEST SUCEEDED')<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end>
<import_stmt>logging<import_stmt>sys<import_from_stmt>dbnd PipelineTask PythonTask output parameter<line_sep>logger=logging.getLogger(__name__)<class_stmt>T1(PythonTask)<block_start>p1=parameter.value("somep")<line_sep>o_1=output[str]<def_stmt>run self<block_start>self.o_1=self.p1<block_end><block_end><class_stmt>T2(PythonTask)<block_start>p1=parameter.value("somep")<line_sep>o_1=output[str]<def_stmt>run self<block_start><raise>Exception()<line_sep># self.o_1 = self.p1 <block_end><block_end><class_stmt>TPipe(PipelineTask)<block_start>o_1=output[str]<line_sep>o_2=output[str]<def_stmt>band self<block_start>self.o_1=T1().o_1<line_sep>self.o_2=T2(p1=self.o_1)<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>TPipe(override={T1.task_version:"now"}).dbnd_run()<block_end>
# -*- coding: utf-8; py-indent-offset: 2 -*- """ This module provides tools for examining a set of vectors and find the geometry that best fits from a set of built in shapes. """<import_from_future_stmt> absolute_import division print_function<import_from_stmt>scitbx.matrix col<import_from_stmt>collections OrderedDict<try_stmt><block_start><import_from_stmt>collections.abc Iterable<block_end><except_stmt>ImportError<block_start><import_from_stmt>collections Iterable<block_end><import_from_stmt>math sqrt<import_from_stmt>six.moves zip<def_stmt>_bond_angles vectors<block_start>""" Creates a list of angles (In degrees) between all two-element combinations in vectors. Parameters ---------- vectors : scitbx.matrix.col Returns ------- list of float """<line_sep><return>[(v1 v2 v1.angle(v2 deg=<true>))<for>index,v1 enumerate(vectors)<for>v2 vectors[index+1:]]<block_end><def_stmt>_is_tetrahedron vectors dev_cutoff=20<block_start>""" Tetrahedrons have four vertices, with angles between all pairs of vertices uniformly about 104.5 degrees. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<g>4<or>len(vectors)<l>3<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>deviation=sqrt(sum(abs(i[2]-104.5)<power>2<for>i angles)/len(vectors))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 4-len(vectors)<block_end><block_end><def_stmt>_is_trigonal_plane vectors dev_cutoff=20<block_start>""" Triangular planar geometry has three vertices (By definition all on the same equatorial plane). The expected angles are 120 degrees between neighboring vertices. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>3<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>a_120s=[]<for_stmt>angle angles<block_start>a_120s.append(angle[2]-120)<block_end>deviation=sqrt(sum(i<power>2<for>i a_120s)/len(angles))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 3-len(vectors)<block_end><block_end><def_stmt>_is_square_plane vectors dev_cutoff=20<block_start>""" Square planar geometry has four vertices, all on the same equatorial plane. The expected angles are 90 degrees between neighboring vertices and 180 degrees between vertices across from one another. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>4<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep># Expect 2x 180 degrees and 4x 90 degrees a_90s=[]<line_sep>a_180s=[]<for_stmt>angle angles<block_start><if_stmt>abs(angle[2]-90)<l>abs(angle[2]-180)<block_start>a_90s.append(angle[2]-90)<block_end><else_stmt><block_start>a_180s.append(angle[2]-180)<block_end><block_end># With up to one atom missing, we must have 2 to 4 90 degree angles and 1 to 2 # 180 degree angles <if_stmt>len(a_90s)<l>2<or>len(a_90s)<g>4<or>len(a_180s)<l>1<or>len(a_180s)<g>2<block_start><return><block_end>deviation=sqrt(sum(i<power>2<for>i a_90s+a_180s)/len(angles))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 4-len(vectors)<block_end><block_end><def_stmt>_is_square_pyramid vectors dev_cutoff=20<block_start>""" Square bipyramids have five vertices, four on the same equatorial plane with one above. The expected angles are all either 90 degrees or 180 degrees. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>5<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>a_90s,a_180s=[] []<for_stmt>angle angles<block_start><if_stmt>abs(angle[2]-90)<l>abs(angle[2]-180)<block_start>a_90s.append(angle[2]-90)<block_end><else_stmt><block_start>a_180s.append(angle[2]-180)<block_end><block_end><if_stmt>len(a_90s)<ne>8<or>len(a_180s)<ne>2<block_start><return><block_end>deviation=sqrt(sum(i<power>2<for>i a_90s+a_180s)/len(angles))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 5-len(vectors)<block_end><block_end><def_stmt>_is_octahedron vectors dev_cutoff=20<block_start>""" Octahedrons have six vertices (Their name comes from their eight faces). The expected angles are all either 90 degrees (Next to each other), or 180 degrees (Across from each other). Another name for this shape is square bipyramidal. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>6<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>a_90s,a_180s=[] []<for_stmt>angle angles<block_start><if_stmt>abs(angle[-1]-90)<l>abs(angle[-1]-180)<block_start>a_90s.append(angle[-1]-90)<block_end><else_stmt><block_start>a_180s.append(angle[-1]-180)<block_end><block_end><if_stmt>len(a_180s)<g>3<or>len(a_180s)<l>2<or>len(a_90s)<l>8<or>len(a_90s)<g>12<block_start><return><block_end>deviation=sqrt(sum(i<power>2<for>i a_90s+a_180s)/len(angles))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 6-len(vectors)<block_end><block_end><def_stmt>_is_trigonal_pyramid vectors dev_cutoff=15<block_start>""" Trigional pyramids have four vertices. Three vertices form a plane with angles of 120 degrees between each pair. The last vertex resides axial to the plane, at 90 degrees from all of the equatorial vertices. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>4<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>a_90s,a_120s=[] []<for_stmt>angle angles<block_start><if_stmt>abs(angle[2]-90)<l>abs(angle[2]-120)<block_start>a_90s.append(angle[2]-90)<block_end><else_stmt><block_start>a_120s.append(angle[2]-120)<block_end><block_end><if_stmt>len(a_90s)<l>2<or>len(a_90s)<g>4<or>len(a_120s)<l>2<or>len(a_120s)<g>4<block_start><return><block_end>deviation=sqrt(sum(i<power>2<for>i a_90s+a_120s)/len(angles))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 4-len(vectors)<block_end><block_end><def_stmt>_is_trigonal_bipyramid vectors dev_cutoff=15<block_start>""" Trigonal bipyramids have five vertices. Three vertices form a plane in the middle and the angles between all three are 120 degrees. The two other vertices reside axial to the plane, at 90 degrees from all the equatorial vertices. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<g>5<or>len(vectors)<l>4<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep># Grab the two axial vectors ax1,ax2,axial_angle=max(angles key=<lambda>x:abs(x[-1]))<if_stmt>axial_angle<l>150# Missing one of the two axial vectors, just quit <block_start><return><block_end>base_to_axials=[]<line_sep>equatorial_angles=[]<for_stmt>v1,v2,angle angles# Python has no boolean xor! # Grab the angles between the two endpoints of the bipyramid and the base <block_start><if_stmt>(v1<in>[ax1 ax2])<ne>(v2<in>[ax1 ax2])<block_start>base_to_axials<augadd>angle <block_end><elif_stmt>(v1<not><in>[ax1 ax2])<and>(v2<not><in>[ax1 ax2])<block_start>equatorial_angles<augadd>angle <block_end><block_end>deviants=[axial_angle-180]<line_sep>deviants<augadd>[i-90<for>i base_to_axials]<line_sep>deviants<augadd>[i-120<for>i equatorial_angles]<line_sep>deviation=sqrt(sum(i<power>2<for>i deviants)/len(deviants))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 5-len(vectors)<block_end><block_end><def_stmt>_is_pentagonal_bipyramid vectors dev_cutoff=15<block_start>""" Pentagonal bipyramids have seven vertices. Five vertices form a plane in the middle and the angles between all five are 72 degrees. The two other vertices reside axial to the plane, at 90 degrees from all the equatorial vertices. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<g>7<or>len(vectors)<l>6<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep># Determine which two vectors define the axial angles axials=[]<for_stmt>v1 vectors<block_start>v_angles=[]<for_stmt>v2 vectors<block_start><if_stmt>v2<ne>v1<block_start>v_angles.append(v1.angle(v2 deg=<true>))<block_end><block_end>a_180s=len([i<for>i v_angles<if>abs(i-180)<l>20])<line_sep>a_90s=len([i<for>i v_angles<if>abs(i-90)<l>20])<if_stmt>a_180s<g>0<and>a_90s<g>4<block_start>axials.append(v1)<block_end><block_end><if_stmt>len(axials)<ne>2# Couldn't determine axial angles <block_start><return><block_end>ax1,ax2=axials<line_sep>axial_angle=ax1.angle(ax2 deg=<true>)<line_sep>base_to_axials=[]<line_sep>equatorial_angles=[]<for_stmt>v1,v2,angle angles# Python has no boolean xor! # Grab the angles between the two endpoints of the bipyramid and the base <block_start><if_stmt>(v1<in>[ax1 ax2])<ne>(v2<in>[ax1 ax2])<block_start>base_to_axials<augadd>angle <block_end><elif_stmt>(v1<not><in>[ax1 ax2])<and>(v2<not><in>[ax1 ax2])<block_start>equatorial_angles<augadd>angle <block_end><block_end>deviants=[axial_angle-180]<line_sep>deviants<augadd>[i-90<for>i base_to_axials]<line_sep>deviants<augadd>[min(abs(i-72) abs(i-144))<for>i equatorial_angles]<line_sep>deviation=sqrt(sum(i<power>2<for>i deviants)/len(deviants))<if_stmt>deviation<le>dev_cutoff<block_start><return>deviation 7-len(vectors)<block_end><block_end><def_stmt>_is_trigonal_prism vectors dev_cutoff=15<block_start>""" Triangular prisms are defined by 3 vertices in a triangular pattern on two aligned planes. Unfortunately, the angles are dependent on the length and width of the prism. Need more examples to come up with a better way of detecting this shape. For now, this code is experimental. Parameters ---------- vectors : list scitbx.matrix.col dev_cutoff : float, optional Returns ------- bool """<if_stmt>len(vectors)<ne>6<block_start><return><block_end>angles=_bond_angles(vectors)<line_sep>a_85s,a_135s=[] []<for_stmt>angle angles<block_start><if_stmt>abs(angle[-1]-85)<l>abs(angle[-1]-135)<block_start>a_85s.append(angle[-1]-85)<block_end><else_stmt><block_start>a_135s.append(angle[-1]-135)<block_end><block_end><if_stmt>len(a_85s)<ne>9<and>len(a_135s)<ne>6<block_start><return><block_end>deviation=sqrt(sum(i<power>2<for>i a_85s+a_135s)/len(angles))<if_stmt>deviation<l>dev_cutoff<block_start><return>deviation 6-len(vectors)<block_end><block_end>SUPPORTED_GEOMETRIES_OLD=OrderedDict([("tetrahedral" _is_tetrahedron) ("trigonal_planar" _is_trigonal_plane) ("square_planar" _is_square_plane) ("square_pyramidal" _is_square_pyramid) ("octahedral" _is_octahedron) ("trigonal_pyramidal" _is_trigonal_pyramid) ("trigonal_bipyramidal" _is_trigonal_bipyramid) ("pentagonal_bipyramidal" _is_pentagonal_bipyramid) ("trigonal_prism" _is_trigonal_prism) ])<def_stmt>_concatenate *args<block_start>""" Reduces a list of a mixture of elements and lists down to a single list. Parameters ---------- args : tuple of (object or list of object) Returns ------- list """<line_sep>lst=[]<for_stmt>arg args<block_start><if_stmt>isinstance(arg list)<block_start><for_stmt>elem arg<block_start>lst.append(elem)<block_end><block_end><else_stmt><block_start>lst.append(arg)<block_end><block_end><return>lst<block_end><def_stmt>_tetrahedron <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([1 1 1]) col([-1 -1 1]) col([-1 1 -1]) col([1 -1 -1]) ]<block_end><def_stmt>_octahedron <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_bipyramid(_square_plane())<block_end><def_stmt>_trigonal_plane <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([0 1 0]) col([-sqrt(3)/2 -1/2 0]) col([sqrt(3)/2 -1/2 0]) ]<block_end><def_stmt>_square_plane <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([0 1 0]) col([0 -1 0]) col([1 0 0]) col([-1 0 0]) ]<block_end><def_stmt>_pyramid base<block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(base col([0 0 1]))<block_end><def_stmt>_bipyramid base<block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(base col([0 0 1]) col([0 0 -1]))<block_end><def_stmt>_square_pyramid <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_pyramid(_square_plane())<block_end><def_stmt>_square_bipyramid <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_bipyramid(_square_plane())<block_end><def_stmt>_trigonal_pyramid <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_pyramid(_trigonal_plane())<block_end><def_stmt>_trigonal_bipyramid <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_bipyramid(_trigonal_plane())<block_end><def_stmt>_trigonal_prism <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate([i+col([0 0 1])<for>i _trigonal_plane()] [i+col([0 0 -1])<for>i _trigonal_plane()] )<block_end><def_stmt>_pentagon <block_start>""" Create a list of vectors in the shape of a planar pentagon. Returns ------- list of scitbx.matrix.col See Also -------- http://mathworld.wolfram.com/Pentagon.html """<line_sep>c_1=(sqrt(5)-1)/4<line_sep>c_2=(sqrt(5)+1)/4<line_sep>s_1=sqrt(10+2<times>sqrt(5))/4<line_sep>s_2=sqrt(10-2<times>sqrt(5))/4<line_sep><return>[col([1 0 0]) col([c_1 s_1 0]) col([-c_2 s_2 0]) col([-c_2 -s_2 0]) col([c_1 -s_1 0]) ]<block_end><def_stmt>_pentagonal_pyramid <block_start>""" Returns ------- list of scitbx.matrix.col """<line_sep><return>_pyramid(_pentagon())<block_end><def_stmt>_pentagonal_bipyramid <block_start>""" Creates a square bipyramid shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_bipyramid(_pentagon())<block_end><def_stmt>_square_pyramid_bidentate_miss_1 <block_start>""" Creates a square pyramid shape with one vertex replaced with a bidentate coordination group. One vertex is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_square_plane() col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) )<block_end><def_stmt>_square_pyramid_bidentate_miss_2 <block_start>""" Creates a square pyramid shape with one vertex replaced with a bidentate coordination group. One vertex is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([0 1 0]) col([0 -1 0]) col([-1 0 0]) col([0 0 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) ]<block_end><def_stmt>_square_pyramid_bidentate_miss_3 <block_start>""" Creates a square pyramid shape with one vertex replaced with a bidentate coordination group. One vertex is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([0 1 0]) col([0 -1 0]) col([-1 0 0]) col([1 0 0]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) ]<block_end><def_stmt>_square_pyramid_bidentate <block_start>""" Creates a square pyramid shape with one vertex replaced with a bidentate coordination group. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_square_pyramid() col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]))<block_end><def_stmt>_pentagonal_pyramid_bidentate <block_start>""" Creates a pentagonal pyramid shape with one vertex replaced with a bidentate coordination group. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_pentagonal_pyramid() col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) )<block_end><def_stmt>_pentagonal_bibidentate_miss_1 <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. One vertex from the plane is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) *_pentagon()[:-1])<block_end><def_stmt>_pentagonal_bibidentate_miss_2 <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. One vertex from the plane is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) *_pentagon()[1:])<block_end><def_stmt>_pentagonal_bibidentate_miss_3 <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. One vertex from the plane is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep>pentagon=_pentagon()<line_sep><return>_concatenate(col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) pentagon[0] pentagon[1] pentagon[3] pentagon[4] )<block_end><def_stmt>_pentagonal_bibidentate_miss_4 <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. One vertex from a bidentate coordinator is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_pentagon() col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) )<block_end><def_stmt>_pentagonal_bibidentate_miss_5 <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. One vertex from a bidentate coordinator is missing in this shape. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_pentagon() col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) )<block_end><def_stmt>_pentagonal_bibidentate <block_start>""" A planar pentagon with bidentate atoms coordinating directly above and below. Returns ------- list of scitbx.matrix.col """<line_sep><return>_concatenate(_pentagon() col([sqrt(2)/2 sqrt(2)/2 1]) col([-sqrt(2)/2 -sqrt(2)/2 1]) col([sqrt(2)/2 sqrt(2)/2 -1]) col([-sqrt(2)/2 -sqrt(2)/2 -1]) )<block_end><def_stmt>_see_saw <block_start>""" An octahedron missing two adjacent points. Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([1 0 0]) col([-1 0 0]) col([0 1 0]) col([0 0 1]) ]<block_end><def_stmt>_three_legs <block_start>""" Better name? Imagine 3 orthogonal vectors pointed in the x, y, and z directions. Returns ------- list of scitbx.matrix.col """<line_sep><return>[col([1 0 0]) col([0 1 0]) col([0 0 1]) ]<block_end>SUPPORTED_GEOMETRIES=OrderedDict([(3 [("three_legs" _three_legs 15) ("trigonal_plane" _trigonal_plane 15) ]) (4 [("tetrahedron" _tetrahedron 15) ("square_plane" _square_plane 20) ("trigonal_pyramid" _trigonal_pyramid 15) ("see_saw" _see_saw 15) ]) (5 [("square_pyramid" _square_pyramid 15) ("trigonal_bipyramid" _trigonal_bipyramid 15) ("pentagon" _pentagon 15)]) (6 [("octahedron" _octahedron 15) ("trigonal_prism" _trigonal_prism 15) ("pentagonal_pyramid" _pentagonal_pyramid 15) ("square_pyramid_bidentate_miss" [_square_pyramid_bidentate_miss_1 _square_pyramid_bidentate_miss_2 _square_pyramid_bidentate_miss_3] 15) ]) (7 [("pentagonal_bipyramid" _pentagonal_bipyramid 15) ("square_pyramid_bidentate" _square_pyramid_bidentate 15) ]) (8 [("pentagonal_pyramid_bidentate" _pentagonal_pyramid_bidentate 15) ("pentagonal_bibidentate_miss" [_pentagonal_bibidentate_miss_1 _pentagonal_bibidentate_miss_2 _pentagonal_bibidentate_miss_3] 15) ]) (9 [("pentagonal_bibidentate" _pentagonal_bibidentate 15) ]) ])<line_sep>SUPPORTED_GEOMETRY_NAMES=[lst_i[0]<for>vals SUPPORTED_GEOMETRIES.values()<for>lst_i vals]<def_stmt>_angles_deviation vectors_a vectors_b<block_start>""" Calculates the root mean square of the angle deviation (in degrees) between two lists of vectors. Parameters ---------- vectors_a : list of scitbx.matrix.col vectors_b : list of scitbx.matrix.col Returns ------- float """<assert_stmt>len(vectors_a)<eq>len(vectors_b)<line_sep>angles_a=[vec.angle(vec_o deg=<true>)<for>index,vec enumerate(vectors_a)<for>vec_o vectors_a[index+1:]]<line_sep>angles_b=[vec.angle(vec_o deg=<true>)<for>index,vec enumerate(vectors_b)<for>vec_o vectors_b[index+1:]]<line_sep>angles_a.sort()<line_sep>angles_b.sort()<line_sep>angle_deviation=sqrt(sum((i-j)<power>2<for>i,j zip(angles_a angles_b))/len(angles_a))<line_sep><return>angle_deviation<block_end><def_stmt>find_coordination_geometry nearby_atoms minimizer_method=<false> cutoff=2.9<block_start>""" Searches through a list of geometries to find those that fit nearby_atom. Geometries are recognized by generating a list of all combinations of angles between the vectors and comparing them against the angles among the vectors of the ideal geometry. Parameters ---------- nearby_atoms: list of mmtbx.ions.environment.atom_contact A list of atom contacts, indicating the vertices of the shape to be recognized. minimizer_method: bool, optional Optional parameter to use the new, more efficient version of geometry recognition. The old method will be depreciated in later versions of cctbx. cutoff: float, optional A cutoff distance, past which vectors are not included in geometry calculations. Returns ------- list of tuples of str, float A list of found geometries. Each tuple contains the name of the geometry in string form followed by the deviation from ideal angles. See Also -------- mmtbx.ions.geometry.SUPPORTED_GEOMETRY_NAMES, mmtbx.ions.geometry.SUPPORTED_GEOMETRIES_OLD """<line_sep># Filter out overlapping atoms, we just want an idea of the coordinating # geometry, even if it is two different atoms are occupying the same spot. non_overlapping=[]<for_stmt>index,contact enumerate(nearby_atoms)<block_start><if_stmt>all(contact.distance_from(other)<g>0.5<for>other nearby_atoms[index+1:])<block_start>non_overlapping.append(contact)<block_end><block_end># Filter out contacts > cutoff away filtered=[]<for_stmt>contact non_overlapping<block_start><if_stmt>contact.distance()<l>cutoff<block_start>filtered.append(contact.vector)<block_end><block_end>geometries=[]<if_stmt>minimizer_method<block_start>n_vectors=len(filtered)<if_stmt>n_vectors<not><in>SUPPORTED_GEOMETRIES<block_start><return>geometries<block_end><for_stmt>name,func,rmsa_cutoff SUPPORTED_GEOMETRIES[n_vectors]<block_start><if_stmt>isinstance(func Iterable)<block_start>rmsa=min(_angles_deviation(filtered i())<for>i func)<block_end><else_stmt><block_start>rmsa=_angles_deviation(filtered func())<block_end><if_stmt>rmsa<l>rmsa_cutoff<block_start>geometries.append((name rmsa))<block_end><block_end><if_stmt>geometries<block_start>geometries.sort(key=<lambda>x:x[-1])<line_sep>geometries=[geometries[0]]<block_end><block_end><else_stmt><block_start><for_stmt>name,func SUPPORTED_GEOMETRIES_OLD.items()<block_start>val=func(filtered)<if_stmt>val<block_start>deviation=val[0]<line_sep>geometries.append((name deviation))<block_end><block_end><block_end><return>geometries<block_end>
# type: ignore # ^ that's necessary to prevent a false linting error of some kind <import_stmt>asyncio<import_stmt>urllib.parse<import_from_stmt>time perf_counter<import_stmt>typer<import_from_stmt>mcsniperpy.util.logs_manager Color<as>color<import_from_stmt>mcsniperpy.util.logs_manager Logger<as>log<async_keyword><def_stmt>check url:str iterations:int<block_start><async_keyword><def_stmt>ping <block_start><try_stmt><block_start>uri=urllib.parse.urlparse(url)<line_sep>reader,writer=<await>asyncio.open_connection(uri.hostname 443 ssl=<false>)<line_sep>writer.write(f"GET {uri.path<or>'/'} HTTP/1.1\r\nHost:{uri.hostname}\r\n\r\n".encode())<line_sep>start=perf_counter()<line_sep><await>writer.drain()<line_sep>_=<await>reader.read(100)<line_sep>end=perf_counter()<line_sep><return>round((end-start)<times>1000)<block_end># pylint: disable=invalid-name, broad-except <except_stmt>Exception<as>e<block_start>log.error("Failed to connect to URL. error code: "+str(e))<block_end><block_end>pings=[]<with_stmt>typer.progressbar(range(iterations) fill_char="█" empty_char=" " color=10 show_eta=<false> bar_template="%(label)s %(bar)s %(info)s" )<as>progress<block_start><for_stmt>_ progress<block_start>pings.append(<await>ping())<line_sep><await>asyncio.sleep(0.01)<block_end><block_end>print()<line_sep>log.info(f"Host {color.l_cyan}» {color.blue}{urllib.parse.urlparse(url).hostname}")<line_sep>log.info(f"Ping {color.l_cyan}» {color.blue}{sum(pings)/5}ms")<block_end><async_keyword><def_stmt>ping_test iterations<block_start>print()<line_sep><await>check("https://api.minecraftservices.com/minecraft" iterations)<block_end>
# Ideas """ server = dkeras.DataServer() model1.link(model3) model1.postprocess = lambda z: np.float16(z) server = model1 + model2 + model3 server.add(camera1, dest=('m1', 'm2')) server.add_address('192.168.1.42') """<line_sep>
__test__=<false><if_stmt>__name__<eq>'__main__'<block_start><import_stmt>eventlet<line_sep>eventlet.monkey_patch()<try_stmt><block_start>eventlet.wrap_ssl(eventlet.listen(('localhost' 0)) certfile='does-not-exist' keyfile='does-not-exist' server_side=<true>)<block_end><except_stmt>IOError<as>ex<block_start><assert_stmt>ex.errno<eq>2<line_sep>print('pass')<block_end><block_end>
version='2.2.2'<line_sep>
<import_stmt>logging<import_stmt>random<import_stmt>numpy<as>np<import_stmt>math<import_stmt>torch<import_stmt>torch.nn<as>nn<class_stmt>PosEmbedding(nn.Module)<block_start><def_stmt>__init__ self max_logscale N_freqs logscale=<true> multi_pi=<false> <block_start>""" Defines a function that embeds x to (x, sin(2^k x), cos(2^k x), ...) """<line_sep>super().__init__()<line_sep>self.N_freqs=N_freqs<line_sep>self.funcs=[torch.sin torch.cos]<if_stmt>logscale<block_start>self.freqs=2<power>torch.linspace(0 max_logscale N_freqs)<block_end><else_stmt><block_start>self.freqs=torch.linspace(1 2<power>max_logscale N_freqs)<block_end><if_stmt>multi_pi<block_start>self.freqs=self.freqs<times>math.pi<block_end><pass><block_end><def_stmt>get_out_dim self<block_start>outdim=3+3<times>2<times>self.N_freqs<line_sep><return>outdim<block_end><def_stmt>forward self x<block_start>""" Inputs: x: (B, 3) Outputs: out: (B, 6*N_freqs+3) """<line_sep>out=[x]<for_stmt>freq self.freqs<block_start><for_stmt>func self.funcs<block_start>out<augadd>[func(freq<times>x)]<block_end><block_end><return>torch.cat(out -1)<block_end><block_end><class_stmt>EMA(object)<block_start><def_stmt>__init__ self source target decay=0.9999 start_itr=0<block_start>""" # Simple wrapper that applies EMA to a model. Could be better done in 1.0 using # the parameters() and buffers() module functions, but for now this works # with state_dicts using .copy_ :param source: model :param target: ema model :param decay: :param start_itr: """<line_sep>self.source=source<line_sep>self.target=target<line_sep>self.decay=decay<line_sep># Optional parameter indicating what iteration to start the decay at self.start_itr=start_itr<line_sep>logger=logging.getLogger('tl')<line_sep># Initialize target's params to be source's self.source_dict=self.source.state_dict()<line_sep>self.target_dict=self.target.state_dict()<line_sep>logger.info(f'Initializing EMA [{decay}] parameters to be source parameters...')<line_sep>self.update_target_dict(source_state_dict=self.source_dict)<line_sep><pass><block_end><def_stmt>update_target_dict self source_state_dict<block_start>""" Reset the ema model weights. :param source_state_dict: :return: """<with_stmt>torch.no_grad()<block_start><for_stmt>key source_state_dict<block_start>self.target_dict[key].data.copy_(source_state_dict[key].data)<line_sep># target_dict[key].data = source_dict[key].data # Doesn't work! <block_end><block_end><pass><block_end><def_stmt>update self itr=<none> source_dict=<none><block_start>""" # If an iteration counter is provided and itr is less than the start itr, # peg the ema weights to the underlying weights. :param itr: :return: """<if_stmt>itr<is><not><none><and>itr<l>self.start_itr# decay = 0.0 <block_start><return><block_end><else_stmt><block_start>decay=self.decay<block_end><with_stmt>torch.no_grad()<block_start><if_stmt>source_dict<is><none><block_start>source_dict=self.source_dict<block_end><for_stmt>key source_dict<block_start>self.target_dict[key].data.copy_(self.target_dict[key].data<times>decay+source_dict[key].data<times>(1-decay))<block_end><block_end><pass><block_end><block_end>
""" Testlldb Python SBFrame APIs IsInlined() and GetFunctionName(). """<import_from_future_stmt> print_function<import_stmt>lldb<import_from_stmt>lldbsuite.test.decorators *<import_from_stmt>lldbsuite.test.lldbtest *<import_from_stmt>lldbsuite.test lldbutil<class_stmt>InlinedFrameAPITestCase(TestBase)<block_start>mydir=TestBase.compute_mydir(__file__)<def_stmt>setUp self# Call super's setUp(). <block_start>TestBase.setUp(self)<line_sep># Find the line number to of function 'c'. self.source='inlines.c'<line_sep>self.first_stop=line_number(self.source '// This should correspond to the first break stop.')<line_sep>self.second_stop=line_number(self.source '// This should correspond to the second break stop.')<block_end><def_stmt>test_stop_at_outer_inline self<block_start>"""Exercise SBFrame.IsInlined() and SBFrame.GetFunctionName()."""<line_sep>self.build()<line_sep>exe=self.getBuildArtifact("a.out")<line_sep># Create a target by the debugger. target=self.dbg.CreateTarget(exe)<line_sep>self.assertTrue(target VALID_TARGET)<line_sep># Now create a breakpoint on main.c by the name of 'inner_inline'. breakpoint=target.BreakpointCreateByName('inner_inline' 'a.out')<line_sep>self.trace("breakpoint:" breakpoint)<line_sep>self.assertTrue(breakpoint<and>breakpoint.GetNumLocations()<g>1 VALID_BREAKPOINT)<line_sep># Now launch the process, and do not stop at the entry point. process=target.LaunchSimple(<none> <none> self.get_process_working_directory())<line_sep>process=target.GetProcess()<line_sep>self.assertEqual(process.GetState() lldb.eStateStopped PROCESS_STOPPED)<import_stmt>lldbsuite.test.lldbutil<as>lldbutil<line_sep>stack_traces1=lldbutil.print_stacktraces(process string_buffer=<true>)<if_stmt>self.TraceOn()<block_start>print("Full stack traces when first stopped on the breakpoint 'inner_inline':")<line_sep>print(stack_traces1)<block_end># The first breakpoint should correspond to an inlined call frame. # If it's an inlined call frame, expect to find, in the stack trace, # that there is a frame which corresponds to the following call site: # # outer_inline (argc); # thread=lldbutil.get_stopped_thread(process lldb.eStopReasonBreakpoint)<line_sep>self.assertIsNotNone(thread)<line_sep>frame0=thread.GetFrameAtIndex(0)<if_stmt>frame0.IsInlined()<block_start>filename=frame0.GetLineEntry().GetFileSpec().GetFilename()<line_sep>self.assertEqual(filename self.source)<line_sep>self.expect(stack_traces1 "First stop at %s:%d"%(self.source self.first_stop) exe=<false> substrs=['%s:%d'%(self.source self.first_stop)])<line_sep># Expect to break again for the second time. process.Continue()<line_sep>self.assertEqual(process.GetState() lldb.eStateStopped PROCESS_STOPPED)<line_sep>stack_traces2=lldbutil.print_stacktraces(process string_buffer=<true>)<if_stmt>self.TraceOn()<block_start>print("Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:")<line_sep>print(stack_traces2)<line_sep>self.expect(stack_traces2 "Second stop at %s:%d"%(self.source self.second_stop) exe=<false> substrs=['%s:%d'%(self.source self.second_stop)])<block_end><block_end><block_end><block_end>
<import_from_stmt>datetime date timedelta datetime time<import_from_stmt>django.contrib.contenttypes.models ContentType<import_from_stmt>django.conf settings<import_from_stmt>django.db models<import_from_stmt>django.db connections<import_from_stmt>django.utils timezone<import_from_stmt>.models Period StatisticByDate StatisticByDateAndObject<class_stmt>ObjectsByDateTracker(object)<block_start>date_field='date'<line_sep>aggr_op=<none><line_sep>metric=<none><line_sep>period=<none><line_sep>statistic_model=StatisticByDate<def_stmt>__init__ self **kwargs<block_start><for_stmt>prop,val kwargs.items()<block_start>setattr(self prop val)<block_end><block_end><def_stmt>get_most_recent_kwargs self<block_start>most_recent_kwargs={'metric':self.metric 'period':self.period}<line_sep><return>most_recent_kwargs<block_end><def_stmt>get_start_date self qs<block_start>most_recent_kwargs=self.get_most_recent_kwargs()<line_sep>last_stat=self.statistic_model.objects.most_recent(**most_recent_kwargs)<if_stmt>last_stat<block_start>start_date=last_stat.date<block_end><else_stmt><block_start>first_instance=qs.order_by(self.date_field).first()<if_stmt>first_instance<is><none># No data <block_start><return><block_end>start_date=getattr(first_instance self.date_field)<block_end><if_stmt>start_date<and>isinstance(start_date datetime)<block_start><if_stmt>timezone.is_aware(start_date)<block_start>start_date=timezone.make_naive(start_date).date()<block_end><else_stmt><block_start>start_date=start_date.date()<block_end><block_end><return>start_date<block_end><def_stmt>track_lifetime_upto self qs upto_date<block_start>filter_kwargs={self.date_field+'__date__lte':upto_date}<line_sep>n=qs.filter(**filter_kwargs).count()<line_sep>self.statistic_model.objects.record(metric=self.metric value=n period=self.period date=upto_date)<block_end><def_stmt>get_track_values self<block_start><return>[]<block_end><def_stmt>get_record_kwargs self val<block_start><return>{}<block_end><def_stmt>track self qs<block_start>to_date=date.today()<line_sep>start_date=self.get_start_date(qs)<if_stmt><not>start_date<block_start><return><block_end><if_stmt>self.period<eq>Period.LIFETIME# Intentionally recompute last stat, as we may have computed # that the last time when the day was not over yet. <block_start>upto_date=start_date<while_stmt>upto_date<le>to_date<block_start>self.track_lifetime_upto(qs upto_date)<line_sep>upto_date<augadd>timedelta(days=1)<block_end><block_end><elif_stmt>self.period<eq>Period.DAY<block_start>values_fields=['ts_date']+self.get_track_values()<line_sep>connection=connections[qs.db]<line_sep>tzname=(timezone.get_current_timezone_name()<if>settings.USE_TZ<else><none>)<line_sep>is_datetime=isinstance(qs.model._meta.get_field(self.date_field) models.DateTimeField)<if_stmt>is_datetime<block_start>date_sql=connection.ops.datetime_cast_date_sql(self.date_field tzname)<line_sep># before django 2.0 it returns a tuple <if_stmt>isinstance(date_sql tuple)<block_start>vals=qs.extra(select={"ts_date":date_sql[0]} select_params=date_sql[1])<block_end><else_stmt><block_start>vals=qs.extra(select={"ts_date":date_sql})<block_end>start_dt=datetime.combine(start_date time())-timedelta(days=1)<if_stmt>tzname<block_start>start_dt=timezone.make_aware(start_dt timezone.get_current_timezone())<block_end><block_end><else_stmt><block_start>vals=qs.extra(select={"ts_date":self.date_field})<line_sep>start_dt=start_date<block_end>vals=vals.filter(**{self.date_field+'__gte':start_dt}).values(*values_fields).order_by().annotate(ts_n=self.aggr_op)<line_sep># TODO: Bulk create <for_stmt>val vals<block_start>self.statistic_model.objects.record(metric=self.metric value=val['ts_n'] date=val['ts_date'] period=self.period **self.get_record_kwargs(val))<block_end><block_end><else_stmt><block_start><raise>NotImplementedError<block_end><block_end><block_end><class_stmt>ObjectsByDateAndObjectTracker(ObjectsByDateTracker)<block_start>object=<none><line_sep>object_model=<none><line_sep>object_field=<none><line_sep>statistic_model=StatisticByDateAndObject<def_stmt>__init__ self **kwargs<block_start>super(ObjectsByDateAndObjectTracker self).__init__(**kwargs)<assert_stmt>self.object<is><none><or>self.object_field<is><none><assert_stmt>self.object<or>self.object_field<block_end><def_stmt>get_most_recent_kwargs self<block_start>kwargs=super(ObjectsByDateAndObjectTracker self).get_most_recent_kwargs()<if_stmt>self.object_model<block_start>kwargs['object_type']=ContentType.objects.get_for_model(self.object_model)<block_end><else_stmt><block_start>kwargs['object']=self.object<block_end><return>kwargs<block_end><def_stmt>track_lifetime_upto self qs upto_date<block_start>filter_kwargs={self.date_field+'__date__lte':upto_date}<if_stmt>self.object_model<block_start>vals=qs.filter(**filter_kwargs).values(self.object_field).annotate(ts_n=self.aggr_op)<for_stmt>val vals<block_start>object=self.object_model(pk=val[self.object_field])<line_sep># TODO: Bulk create StatisticByDateAndObject.objects.record(metric=self.metric value=val['ts_n'] date=upto_date object=object period=self.period)<block_end><block_end><else_stmt><block_start>n=qs.filter(**filter_kwargs).count()<line_sep>StatisticByDateAndObject.objects.record(metric=self.metric value=n object=self.object period=self.period date=upto_date)<block_end><block_end><def_stmt>get_track_values self<block_start>ret=super(ObjectsByDateAndObjectTracker self).get_track_values()<if_stmt>self.object_model<block_start>ret.append(self.object_field)<block_end><return>ret<block_end><def_stmt>get_record_kwargs self val<block_start><if_stmt>self.object_model<block_start>object=self.object_model(pk=val[self.object_field])<block_end><else_stmt><block_start>object=self.object<block_end><return>{'object':object}<block_end><block_end><class_stmt>CountObjectsByDateTracker(ObjectsByDateTracker)<block_start>aggr_op=models.Count('pk' distinct=<true>)<block_end><class_stmt>CountObjectsByDateAndObjectTracker(ObjectsByDateAndObjectTracker)<block_start>aggr_op=models.Count('pk' distinct=<true>)<block_end>
<import_stmt>argparse<import_stmt>json<import_from_stmt>pathlib Path<import_from_stmt>typing Dict Iterable List Tuple<import_stmt>boto3<import_stmt>yaml<def_stmt>_fetch_vcpu_mapping <arrow>Iterable[Tuple[str Dict]]# Price List api is only available in us-east-1 and ap-southeast-1. <block_start>client=boto3.client("pricing" region_name="us-east-1")<for_stmt>page client.get_paginator("get_products").paginate(ServiceCode="AmazonEC2")<block_start><for_stmt>sku_str page["PriceList"]<block_start>sku_data=json.loads(sku_str)<try_stmt><block_start>attributes=sku_data["product"]["attributes"]<line_sep>data={"instanceType":attributes["instanceType"] "vcpu":int(attributes["vcpu"]) }<if_stmt>"gpu"<in>attributes<block_start>data["gpu"]=int(attributes["gpu"])<block_end><yield>(attributes["instanceType"] data)<block_end><except_stmt>KeyError<block_start><pass><block_end><block_end><block_end><block_end><def_stmt>fetch_vcpu_mapping <arrow>List[Dict]<block_start><return>[v<for>(_ v) sorted(dict(_fetch_vcpu_mapping()).items())]<block_end><def_stmt>main args:argparse.Namespace<arrow><none><block_start>data=fetch_vcpu_mapping()<with_stmt>args.output_fn.open("w")<as>fout<block_start>yaml.safe_dump(data fout)<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>parser=argparse.ArgumentParser()<line_sep>parser.add_argument("output_fn" type=Path help="output filename")<line_sep>args=parser.parse_args()<line_sep>main(args)<block_end>
<import_from_stmt>.upernet UPerHead<import_from_stmt>.segformer SegFormerHead<import_from_stmt>.sfnet SFHead<import_from_stmt>.fpn FPNHead<import_from_stmt>.fapn FaPNHead<import_from_stmt>.fcn FCNHead<import_from_stmt>.condnet CondHead<line_sep>__all__=['UPerHead' 'SegFormerHead' 'SFHead' 'FPNHead' 'FaPNHead' 'FCNHead' 'CondHead']<line_sep>
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 10:07 <import_from_future_stmt> unicode_literals<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[("account" "0008_auto_20161115_1011")]<line_sep>replaces=[("userprofile" "0009_auto_20170206_0407")]<line_sep>operations=[migrations.AlterModelOptions(name="address" options={"verbose_name":"address" "verbose_name_plural":"addresses"} ) migrations.AlterModelOptions(name="user" options={"verbose_name":"user" "verbose_name_plural":"users"} ) migrations.AlterField(model_name="user" name="addresses" field=models.ManyToManyField(blank=<true> to="account.Address" verbose_name="addresses") ) migrations.AlterField(model_name="user" name="email" field=models.EmailField(max_length=254 unique=<true> verbose_name="email") ) ]<block_end>
# Load in our dependencies <import_from_future_stmt> absolute_import<import_from_stmt>restructuredtext_lint.lint lint lint_file<line_sep># Export lint functions lint=lint<line_sep>lint_file=lint_file<line_sep>
# Wrapper class to make dealing with logs easier <class_stmt>ChannelLog()<block_start>__channel=""<line_sep>__logs=[]<line_sep>unread=<false><line_sep>mentioned_in=<false><line_sep># the index of where to start printing the messages __index=0<def_stmt>__init__ self channel logs<block_start>self.__channel=channel<line_sep>self.__logs=list(logs)<block_end><def_stmt>get_server self<block_start><return>self.__channel.server<block_end><def_stmt>get_channel self<block_start><return>self.__channel<block_end><def_stmt>get_logs self<block_start><return>self.__logs<block_end><def_stmt>get_name self<block_start><return>self.__channel.name<block_end><def_stmt>get_server_name self<block_start><return>self.__channel.server.name<block_end><def_stmt>append self message<block_start>self.__logs.append(message)<block_end><def_stmt>index self message<block_start><return>self.__logs.index(message)<block_end><def_stmt>insert self i message<block_start>self.__logs.insert(i message)<block_end><def_stmt>len self<block_start><return>len(self.__logs)<block_end><def_stmt>get_index self<block_start><return>self.__index<block_end><def_stmt>set_index self int<block_start>self.__index=int<block_end><def_stmt>inc_index self int<block_start>self.__index<augadd>int<block_end><def_stmt>dec_index self int<block_start>self.__index<augsub>int<block_end><block_end>
# This script removes the input reference numbers from html pages. # They play a useful role in scientific notebooks, but they are really # just visual clutter in this project. # Could be an nbconvert setting, but it's an easy enough scripting job. <import_stmt>os<import_stmt>sys<line_sep>print("\nStripping input reference numbers from code cells...")<line_sep># Find all files to work with. path_to_notebooks='/srv/projects/intro_programming/intro_programming/notebooks/'<line_sep>filenames=[]<for_stmt>filename os.listdir(path_to_notebooks)<block_start><if_stmt>'.html'<in>filename<and>filename<ne>'index.html'<block_start>filenames.append(filename)<block_end><block_end># one file for testing: #filenames = ['hello_world.html'] <for_stmt>filename filenames<block_start>f=open(path_to_notebooks+filename 'r')<line_sep>lines=f.readlines()<line_sep>f.close()<line_sep>f=open(path_to_notebooks+filename 'wb')<for_stmt>line lines# Unwanted lines have opening and closing div on same line, # with input reference number between them. <block_start><if_stmt>('<div class="prompt input_prompt">'<in>line<and>'</div>'<in>line)# Don't write this line. <block_start><continue><block_end><else_stmt># Regular line, write it. <block_start>f.write(line.encode('utf-8'))<block_end><block_end>f.close()<block_end>print(" Stripped input reference numbers.\n")<line_sep>
<import_from_stmt>common *<def_stmt>test_virtual_columns_spherical <block_start>df=vaex.from_scalars(alpha=0 delta=0 distance=1)<line_sep>df.add_virtual_columns_spherical_to_cartesian("alpha" "delta" "distance" "x" "y" "z" radians=<false>)<line_sep>x,y,z=df['x'].values[0] df['y'].values[0] df['z'].values[0]<line_sep>np.testing.assert_array_almost_equal(x 1)<line_sep>np.testing.assert_array_almost_equal(y 0)<line_sep>np.testing.assert_array_almost_equal(z 0)<for_stmt>radians [<true> <false>]<block_start><def_stmt>dfs alpha delta distance radians=radians<block_start>ds_1=vaex.from_scalars(alpha=alpha delta=delta distance=distance alpha_e=0.1 delta_e=0.2 distance_e=0.3)<line_sep>ds_1.add_virtual_columns_spherical_to_cartesian("alpha" "delta" "distance" propagate_uncertainties=<true> radians=radians)<line_sep>N=1000000<line_sep># distance alpha=np.random.normal(0 0.1 N)+alpha<line_sep>delta=np.random.normal(0 0.2 N)+delta<line_sep>distance=np.random.normal(0 0.3 N)+distance<line_sep>ds_many=vaex.from_arrays(alpha=alpha delta=delta distance=distance)<line_sep>ds_many.add_virtual_columns_spherical_to_cartesian("alpha" "delta" "distance" radians=radians)<line_sep><return>ds_1 ds_many<block_end>ds_1,ds_many=dfs(0 0 1.)<line_sep>x_e=ds_1.evaluate("x_uncertainty")[0]<line_sep>y_e=ds_1.evaluate("y_uncertainty")[0]<line_sep>z_e=ds_1.evaluate("z_uncertainty")[0]<line_sep>np.testing.assert_array_almost_equal(x_e ds_many.std("x").item() decimal=2)<line_sep>np.testing.assert_array_almost_equal(y_e ds_many.std("y").item() decimal=2)<line_sep>np.testing.assert_array_almost_equal(z_e ds_many.std("z").item() decimal=2)<line_sep>np.testing.assert_array_almost_equal(x_e 0.3)<block_end># TODO: from cartesian tot spherical errors df.add_virtual_columns_cartesian_to_spherical("x" "y" "z" "theta" "phi" "r" radians=<false>)<line_sep>theta,phi,r=df("theta" "phi" "r").row(0)<line_sep>np.testing.assert_array_almost_equal(theta 0)<line_sep>np.testing.assert_array_almost_equal(phi 0)<line_sep>np.testing.assert_array_almost_equal(r 1)<line_sep>df.add_virtual_columns_celestial("alpha" "delta" "l" "b" _matrix='eq2gal')<line_sep># TODO: properly test, with and without radians df.evaluate("l")<line_sep>df.evaluate("b")<line_sep>ds=vaex.from_scalars(x=1 y=0 z=0)<line_sep>ds.add_virtual_columns_cartesian_to_spherical()<assert_stmt>ds.evaluate('b')[0]<eq>0<block_end><def_stmt>test_inside_polygon_single df_factory<block_start>df=df_factory(x=[1 2 3] y=[2 3 4])<line_sep>px=np.array([1.5 2.5 2.5 1.5])<line_sep>py=np.array([2.5 2.5 3.5 3.5])<line_sep>df['inside']=df.geo.inside_polygon(df.x df.y px py)<assert_stmt>df.inside.values.tolist()<eq>[<false> <true> <false>]<block_end><def_stmt>test_inside_polygons df_factory<block_start>df=df_factory(x=[1 2 3] y=[2 3 4])<line_sep>px=np.array([1.5 2.5 2.5 1.5])<line_sep>py=np.array([2.5 2.5 3.5 3.5])<line_sep>df['inside']=df.geo.inside_polygons(df.x df.y [px px+1] [py py+1] any=<true>)<assert_stmt>df.inside.values.tolist()<eq>[<false> <true> <true>]<block_end><def_stmt>test_which_polygon_single df_factory<block_start>df=df_factory(x=[1 2 3] y=[2 3 4])<line_sep>px=np.array([1.5 2.5 2.5 1.5])<line_sep>py=np.array([2.5 2.5 3.5 3.5])<line_sep>df['polygon_index']=df.geo.inside_which_polygon(df.x df.y [px px+1] [py py+1])<assert_stmt>df.polygon_index.values.tolist()<eq>[<none> 0 1]<block_end><def_stmt>test_which_polygons df_factory<block_start>df=df_factory(x=[1 2 3] y=[2 3 4])<line_sep># polygon1a = np.array( [(1.5, 2.5, 2.5, 1.5), (2.5, 2.5, 3.5, 3.5)] ) # polygon1b = (polygon1a.T + [1, 1]).T px=np.array([1.5 2.5 2.5 1.5])<line_sep>py=np.array([2.5 2.5 3.5 3.5])<line_sep>polygon1a=[px py]# matches #1 polygon1b=[px+1 py+1]# matches #2 polygon_nothing=[px+10 py+10]# matches nothing pxw=np.array([1.5 3.5 3.5 1.5])<line_sep>pyw=np.array([2.5 2.5 4.5 4.5])<line_sep>polygon1c=[pxw pyw]# matches #1 and 2 pxs=[[polygon1a polygon1b] [polygon1b polygon1c] [polygon1c]]<line_sep>df['polygon_index']=df.geo.inside_which_polygons(df.x df.y pxs any=<true>)<assert_stmt>df.polygon_index.values.tolist()<eq>[<none> 0 0]<line_sep>df['polygon_index']=df.geo.inside_which_polygons(df.x df.y pxs any=<false>)<assert_stmt>df.polygon_index.values.tolist()<eq>[<none> 2 1]<line_sep>pxs=[[polygon_nothing polygon1a polygon_nothing]]<line_sep>df['polygon_index']=df.geo.inside_which_polygons(df.x df.y pxs any=<true>)<assert_stmt>df.polygon_index.values.tolist()<eq>[<none> 0 <none>]<line_sep>pxs=[[polygon1a polygon_nothing polygon1a]]<line_sep>df['polygon_index']=df.geo.inside_which_polygons(df.x df.y pxs any=<false>)<assert_stmt>df.polygon_index.values.tolist()<eq>[<none> <none> <none>]<block_end>
# coding=utf-8 <import_stmt>argparse<import_stmt>os<import_stmt>time<import_from_stmt>math ceil<import_stmt>caffe<import_stmt>cv2<import_stmt>numpy<as>np<line_sep>parser=argparse.ArgumentParser()<line_sep>parser.add_argument('--caffe_prototxt_path' default="model/RFB-320/RFB-320.prototxt" type=str help='caffe_prototxt_path')<line_sep>parser.add_argument('--caffe_model_path' default="model/RFB-320/RFB-320.caffemodel" type=str help='caffe_model_path')<line_sep>parser.add_argument('--input_size' default="320,240" type=str help='define network input size,format: width,height')<line_sep>parser.add_argument('--threshold' default=0.7 type=float help='score threshold')<line_sep>parser.add_argument('--imgs_path' default="../MNN/imgs" type=str help='imgs dir')<line_sep>parser.add_argument('--results_path' default="results" type=str help='results dir')<line_sep>parser.add_argument('--mode' default="cpu" type=str help='cpu or gpu')<line_sep>args=parser.parse_args()<if_stmt>args.mode<eq>"cpu"<block_start>caffe.set_mode_cpu()<block_end><elif_stmt>args.mode<eq>"gpu"<block_start>caffe.set_mode_gpu()<block_end>image_mean=np.array([127 127 127])<line_sep>image_std=128.0<line_sep>iou_threshold=0.3<line_sep>center_variance=0.1<line_sep>size_variance=0.2<line_sep>min_boxes=[[10.0 16.0 24.0] [32.0 48.0] [64.0 96.0] [128.0 192.0 256.0]]<line_sep>strides=[8.0 16.0 32.0 64.0]<def_stmt>define_img_size image_size<block_start>shrinkage_list=[]<line_sep>feature_map_w_h_list=[]<for_stmt>size image_size<block_start>feature_map=[int(ceil(size/stride))<for>stride strides]<line_sep>feature_map_w_h_list.append(feature_map)<block_end><for_stmt>i range(0 len(image_size))<block_start>shrinkage_list.append(strides)<block_end>priors=generate_priors(feature_map_w_h_list shrinkage_list image_size min_boxes)<line_sep><return>priors<block_end><def_stmt>generate_priors feature_map_list shrinkage_list image_size min_boxes<block_start>priors=[]<for_stmt>index range(0 len(feature_map_list[0]))<block_start>scale_w=image_size[0]/shrinkage_list[0][index]<line_sep>scale_h=image_size[1]/shrinkage_list[1][index]<for_stmt>j range(0 feature_map_list[1][index])<block_start><for_stmt>i range(0 feature_map_list[0][index])<block_start>x_center=(i+0.5)/scale_w<line_sep>y_center=(j+0.5)/scale_h<for_stmt>min_box min_boxes[index]<block_start>w=min_box/image_size[0]<line_sep>h=min_box/image_size[1]<line_sep>priors.append([x_center y_center w h])<block_end><block_end><block_end><block_end>print("priors nums:{}".format(len(priors)))<line_sep><return>np.clip(priors 0.0 1.0)<block_end><def_stmt>hard_nms box_scores iou_threshold top_k=-1 candidate_size=200<block_start>scores=box_scores[: -1]<line_sep>boxes=box_scores[: :-1]<line_sep>picked=[]<line_sep>indexes=np.argsort(scores)<line_sep>indexes=indexes[-candidate_size:]<while_stmt>len(indexes)<g>0<block_start>current=indexes[-1]<line_sep>picked.append(current)<if_stmt>0<l>top_k<eq>len(picked)<or>len(indexes)<eq>1<block_start><break><block_end>current_box=boxes[current :]<line_sep>indexes=indexes[:-1]<line_sep>rest_boxes=boxes[indexes :]<line_sep>iou=iou_of(rest_boxes np.expand_dims(current_box axis=0) )<line_sep>indexes=indexes[iou<le>iou_threshold]<block_end><return>box_scores[picked :]<block_end><def_stmt>area_of left_top right_bottom<block_start>hw=np.clip(right_bottom-left_top 0.0 <none>)<line_sep><return>hw[<ellipsis> 0]<times>hw[<ellipsis> 1]<block_end><def_stmt>iou_of boxes0 boxes1 eps=1e-5<block_start>overlap_left_top=np.maximum(boxes0[<ellipsis> :2] boxes1[<ellipsis> :2])<line_sep>overlap_right_bottom=np.minimum(boxes0[<ellipsis> 2:] boxes1[<ellipsis> 2:])<line_sep>overlap_area=area_of(overlap_left_top overlap_right_bottom)<line_sep>area0=area_of(boxes0[<ellipsis> :2] boxes0[<ellipsis> 2:])<line_sep>area1=area_of(boxes1[<ellipsis> :2] boxes1[<ellipsis> 2:])<line_sep><return>overlap_area/(area0+area1-overlap_area+eps)<block_end><def_stmt>predict width height confidences boxes prob_threshold iou_threshold=0.3 top_k=-1<block_start>boxes=boxes[0]<line_sep>confidences=confidences[0]<line_sep>picked_box_probs=[]<line_sep>picked_labels=[]<for_stmt>class_index range(1 confidences.shape[1])<block_start>probs=confidences[: class_index]<line_sep>mask=probs<g>prob_threshold<line_sep>probs=probs[mask]<if_stmt>probs.shape[0]<eq>0<block_start><continue><block_end>subset_boxes=boxes[mask :]<line_sep>box_probs=np.concatenate([subset_boxes probs.reshape(-1 1)] axis=1)<line_sep>box_probs=hard_nms(box_probs iou_threshold=iou_threshold top_k=top_k )<line_sep>picked_box_probs.append(box_probs)<line_sep>picked_labels.extend([class_index]<times>box_probs.shape[0])<block_end><if_stmt><not>picked_box_probs<block_start><return>np.array([]) np.array([]) np.array([])<block_end>picked_box_probs=np.concatenate(picked_box_probs)<line_sep>picked_box_probs[: 0]<augmul>width<line_sep>picked_box_probs[: 1]<augmul>height<line_sep>picked_box_probs[: 2]<augmul>width<line_sep>picked_box_probs[: 3]<augmul>height<line_sep><return>picked_box_probs[: :4].astype(np.int32) np.array(picked_labels) picked_box_probs[: 4]<block_end><def_stmt>convert_locations_to_boxes locations priors center_variance size_variance<block_start><if_stmt>len(priors.shape)+1<eq>len(locations.shape)<block_start>priors=np.expand_dims(priors 0)<block_end><return>np.concatenate([locations[<ellipsis> :2]<times>center_variance<times>priors[<ellipsis> 2:]+priors[<ellipsis> :2] np.exp(locations[<ellipsis> 2:]<times>size_variance)<times>priors[<ellipsis> 2:]] axis=len(locations.shape)-1)<block_end><def_stmt>center_form_to_corner_form locations<block_start><return>np.concatenate([locations[<ellipsis> :2]-locations[<ellipsis> 2:]/2 locations[<ellipsis> :2]+locations[<ellipsis> 2:]/2] len(locations.shape)-1)<block_end><def_stmt>inference <block_start>net=caffe.Net(args.caffe_prototxt_path args.caffe_model_path caffe.TEST)<line_sep>input_size=[int(v.strip())<for>v args.input_size.split(",")]<line_sep>witdh=input_size[0]<line_sep>height=input_size[1]<line_sep>priors=define_img_size(input_size)<line_sep>net.blobs['input'].reshape(1 3 height witdh)<line_sep>result_path=args.results_path<line_sep>imgs_path=args.imgs_path<if_stmt><not>os.path.exists(result_path)<block_start>os.makedirs(result_path)<block_end>listdir=os.listdir(imgs_path)<for_stmt>file_path listdir<block_start>img_path=os.path.join(imgs_path file_path)<line_sep>img_ori=cv2.imread(img_path)<line_sep>tmp_batch=np.zeros([1 3 height witdh] dtype=np.float32)<line_sep>rect=cv2.resize(img_ori (witdh height))<line_sep>rect=cv2.cvtColor(rect cv2.COLOR_BGR2RGB)<line_sep>image=(rect-image_mean)/image_std<line_sep>tmp_batch[0 : : :]=image.transpose(2 0 1)<line_sep>net.blobs['input'].data[<ellipsis>]=tmp_batch<line_sep>time_time=time.time()<line_sep>scores=net.forward()['scores'][0]<line_sep>boxes=net.forward()['boxes'][0]<line_sep>print("inference time: {} s".format(round(time.time()-time_time 4)))<line_sep>boxes=np.expand_dims(np.reshape(boxes (-1 4)) axis=0)<line_sep>scores=np.expand_dims(np.reshape(scores (-1 2)) axis=0)<line_sep>boxes=convert_locations_to_boxes(boxes priors center_variance size_variance)<line_sep>boxes=center_form_to_corner_form(boxes)<line_sep>boxes,labels,probs=predict(img_ori.shape[1] img_ori.shape[0] scores boxes args.threshold)<for_stmt>i range(boxes.shape[0])<block_start>box=boxes[i :]<line_sep>cv2.rectangle(img_ori (box[0] box[1]) (box[2] box[3]) (0 255 0) 2)<block_end>cv2.imwrite(os.path.join(result_path file_path) img_ori)<line_sep>print("result_pic is written to {}".format(os.path.join(result_path file_path)))<line_sep>cv2.imshow("ultraFace_caffe_py" img_ori)<line_sep>cv2.waitKey(-1)<block_end>cv2.destroyAllWindows()<block_end><if_stmt>__name__<eq>'__main__'<block_start>inference()<block_end>
<import_stmt>sys<import_stmt>logging<import_stmt>re<class_stmt>LogFormatter(logging.Formatter)<block_start>@staticmethod<def_stmt>_filter s<block_start>no_access_key_id=re.sub(r'(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])' 'SECRET' s)<line_sep>no_secret_access_key=re.sub(r'(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])' 'SECRET' no_access_key_id)<line_sep><return>no_secret_access_key<block_end><def_stmt>format self record<block_start>original=logging.Formatter.format(self record)<line_sep><return>self._filter(original)<block_end><block_end>logger=logging.getLogger('awsume')# type: logging.Logger LOG_HANDLER=logging.StreamHandler()<line_sep>LOG_HANDLER.setFormatter(LogFormatter('[%(asctime)s] %(filename)s:%(funcName)s : [%(levelname)s] %(message)s'))<line_sep>logger.addHandler(LOG_HANDLER)<line_sep>
<import_from_stmt>django.http JsonResponse Http404<import_from_stmt>django.shortcuts redirect<def_stmt>parse_ip_address request<block_start>ipaddress=request.META.get("HTTP_X_REAL_IP")<or>request.META.get("HTTP_X_FORWARDED_FOR")<or>request.environ.get("REMOTE_ADDR")<or>""<if_stmt>","<in>ipaddress# multiple ips in the header <block_start>ipaddress=ipaddress.split("," 1)[0]<block_end><return>ipaddress<block_end><def_stmt>parse_useragent request<block_start><return>(request.META.get("HTTP_USER_AGENT")<or>"")[:512]<block_end><def_stmt>is_ajax request<block_start><return>bool(request.GET.get("is_ajax"))<block_end><def_stmt>ajax_request view<block_start><def_stmt>wrapper request *args **kwargs<block_start>status_code=200<try_stmt><block_start>results=view(request *args **kwargs)<block_end><except_stmt>Http404<block_start>status_code=404<line_sep>results={"error":"Not Found"}<block_end><if_stmt>is_ajax(request)<block_start><return>JsonResponse(data=results status=status_code)<block_end><else_stmt><block_start><return>redirect(request.META.get("HTTP_REFERER")<or>"/")<block_end><block_end><return>wrapper<block_end>
""" NetBet odds scraper """<import_stmt>datetime<import_stmt>http.client<import_stmt>re<import_stmt>urllib<import_stmt>urllib.error<import_stmt>urllib.request<import_stmt>fake_useragent<import_from_stmt>bs4 BeautifulSoup<import_stmt>sportsbetting<as>sb<import_from_stmt>sportsbetting.auxiliary_functions truncate_datetime<def_stmt>parse_netbet url<block_start>""" Retourne les cotes disponibles sur netbet """<line_sep>sport=<none><if_stmt>url<in>["football" "tennis" "basketball" "hockey-glace" "rugby" "handball"]<block_start>sport=url<line_sep>url="https://www.netbet.fr/top-paris"<block_end>headers={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4)"<concat>"AppleWebKit/537.36 (KHTML, like Gecko)"<concat>"Chrome/83.0.4103.97"<concat>"Safari/537.36"}<for_stmt>_ range(3)<block_start><try_stmt><block_start>request=urllib.request.Request(url <none> headers)<line_sep>response=urllib.request.urlopen(request timeout=5)<line_sep>soup=BeautifulSoup(response features="lxml")<line_sep><break><block_end><except_stmt>http.client.IncompleteRead<block_start>headers={"User-Agent":fake_useragent.UserAgent().random}<line_sep>print("User agent change")<block_end><except_stmt>urllib.error.HTTPError<block_start>headers={"User-Agent":fake_useragent.UserAgent().random}<line_sep>print("User agent change (403)")<block_end><except_stmt>urllib.error.URLError<block_start>headers={"User-Agent":fake_useragent.UserAgent().random}<line_sep>print("User agent change (Timeout)")<block_end><block_end><else_stmt><block_start><raise>sb.UnavailableSiteException<block_end><if_stmt>soup.find(attrs={"class":"none"})<block_start><raise>sb.UnavailableCompetitionException<block_end><if_stmt>response.geturl()<eq>"https://www.netbet.fr/"<block_start><raise>sb.UnavailableCompetitionException<block_end>match_odds_hash={}<line_sep>today=datetime.datetime.today()<line_sep>today=datetime.datetime(today.year today.month today.day)<line_sep>date=""<line_sep>year=" "+str(today.year)<line_sep>match=""<line_sep>competition=""<line_sep>date_time=<none><line_sep>valid_match=<true><for_stmt>line soup.find_all()<block_start><if_stmt>"class"<in>line.attrs<and>"nb-link-event"<in>line["class"]<and>"href"<in>line.attrs<block_start><if_stmt>sport<block_start>valid_match=sport+"/"<in>line["href"]<block_end>link=line["href"]<line_sep>competition=" - ".join(map(<lambda>x:x.replace("-" " ").title() link.split("/")[2:4]))<block_end><elif_stmt>"class"<in>line.attrs<and>"nb-event_datestart"<in>line["class"]<block_start>date=list(line.stripped_strings)[0]+year<if_stmt>"Auj."<in>date<block_start>date=datetime.datetime.today().strftime("%d/%m %Y")<block_end><block_end><elif_stmt>"class"<in>line.attrs<and>"nb-event_timestart"<in>line["class"]<block_start>hour=line.text<if_stmt>" min"<in>hour<block_start>date_time=datetime.datetime.today()+datetime.timedelta(minutes=int(hour.strip(" min")))<line_sep>date_time=truncate_datetime(date_time)<line_sep><continue><block_end><try_stmt><block_start>date_time=datetime.datetime.strptime(date+" "+hour "%d/%m %Y %H:%M")<if_stmt>date_time<l>today<block_start>date_time=date_time.replace(year=date_time.year+1)<block_end><block_end><except_stmt>ValueError<block_start>date_time="undefined"<block_end><block_end><elif_stmt>"class"<in>line.attrs<and>"nb-event_actors"<in>line["class"]<block_start>match=" - ".join(list(map(<lambda>x:x.replace(" - " "-") line.stripped_strings)))<line_sep>reg_exp=r'\[[0-7]\/[0-7]\s?([0-7]\/[0-7]\s?)*\]|\[[0-7]\-[0-7]\s?([0-7]\-[0-7]\s?)*\]'<if_stmt>list(re.finditer(reg_exp match))# match tennis live <block_start>match=match.split("[")[0].strip()<block_end><block_end><elif_stmt>"class"<in>line.attrs<and>"nb-event_odds_wrapper"<in>line["class"]<block_start><try_stmt><block_start>odds=list(map(<lambda>x:float(x.replace("," ".")) list(line.stripped_strings)[1::2]))<if_stmt>valid_match<and>match<and>match<not><in>match_odds_hash<and>date_time<block_start>match_odds_hash[match]={}<line_sep>match_odds_hash[match]['odds']={"netbet":odds}<line_sep>match_odds_hash[match]['date']=date_time<line_sep>match_odds_hash[match]['id']={"netbet":link}<line_sep>match_odds_hash[match]['competition']=competition<block_end><block_end><except_stmt>ValueError# match live (cotes non disponibles) <block_start><pass><block_end><block_end><block_end><return>match_odds_hash<block_end>
<import_stmt>time<def_stmt>test_sleep_400ms <block_start>time.sleep(0.4)<block_end>
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 <NAME>. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- """ A framebuffer is a collection of buffers that can be used as the destination for rendering. OpenGL has two kinds of framebuffers: the default framebuffer, which is provided by the OpenGL Context; and user-created framebuffers called framebuffer objects (FBOs). The buffers for default framebuffers are part of the context and usually represent a window or display device. The buffers for FBOs reference images from either textures or render buffers; they are never directly visible. Read more on framebuffers on `OpenGL Wiki <https://www.opengl.org/wiki/Framebuffer>`_ **Example usage** .. code:: python ... texture = np.zeros((512,512,4),np.float32).view(gloo.TextureFloat2D) framebuffer = gloo.FrameBuffer(color=[texture]) ... @window.event def on_draw(dt): framebuffer.activate() window.clear() quad.draw(gl.GL_TRIANGLE_STRIP) framebuffer.deactivate() """<import_stmt>numpy<as>np<import_from_stmt>glumpy gl<import_from_stmt>glumpy.log log<import_from_stmt>glumpy.gloo.globject GLObject<import_from_stmt>glumpy.gloo.texture Texture2D<class_stmt>RenderBuffer(GLObject)<block_start>""" Base class for render buffer object. :param GLEnum format: Buffer format :param int width: Buffer width (pixels) :param int height: Buffer height (pixel) """<def_stmt>__init__ self width height format<block_start>GLObject.__init__(self)<line_sep>self._width=width<line_sep>self._height=height<line_sep>self._target=gl.GL_RENDERBUFFER<line_sep>self._format=format<line_sep>self._need_resize=<true><block_end>@property<def_stmt>width self<block_start>""" Buffer width (read-only). """<line_sep><return>self._width<block_end>@property<def_stmt>height self<block_start>""" Buffer height (read-only). """<line_sep><return>self._height<block_end><def_stmt>resize self width height<block_start>""" Resize the buffer (deferred operation). :param int width: New buffer width (pixels) :param int height: New buffer height (pixels) """<if_stmt>width<ne>self._width<or>height<ne>self._height<block_start>self._need_resize=<true><line_sep>self._width=width<line_sep>self._height=height<block_end><block_end><def_stmt>_create self<block_start>""" Create buffer on GPU """<line_sep>log.debug("GPU: Create render buffer")<line_sep>self._handle=gl.glGenRenderbuffers(1)<block_end><def_stmt>_delete self<block_start>""" Delete buffer from GPU """<line_sep>log.debug("GPU: Deleting render buffer")<line_sep>gl.glDeleteRenderbuffer(self._handle)<block_end><def_stmt>_activate self<block_start>""" Activate buffer on GPU """<line_sep>log.debug("GPU: Activate render buffer")<line_sep>gl.glBindRenderbuffer(gl.GL_RENDERBUFFER self._handle)<if_stmt>self._need_resize<block_start>self._resize()<line_sep>self._need_resize=<false><block_end><block_end><def_stmt>_deactivate self<block_start>""" Deactivate buffer on GPU """<line_sep>log.debug("GPU: Deactivate render buffer")<line_sep>gl.glBindRenderbuffer(gl.GL_RENDERBUFFER 0)<block_end><def_stmt>_resize self<block_start>""" Buffer resize on GPU """<line_sep># WARNING: width/height should be checked against maximum size # maxsize = gl.glGetParameter(gl.GL_MAX_RENDERBUFFER_SIZE) log.debug("GPU: Resize render buffer")<line_sep>gl.glRenderbufferStorage(self._target self._format self._width self._height)<block_end><block_end><class_stmt>ColorBuffer(RenderBuffer)<block_start>""" Color buffer object. :param int width: Buffer width (pixels) :param int height: Buffer height (pixel) :param GLEnum format: Buffer format (default is gl.GL_RGBA) """<def_stmt>__init__ self width height format=gl.GL_RGBA# if format not in (gl.GL_RGB565, gl.GL_RGBA4, gl.GL_RGB5_A1): # raise ValueError("Format not allowed for color buffer") <block_start>RenderBuffer.__init__(self width height format)<block_end><block_end><class_stmt>DepthBuffer(RenderBuffer)<block_start>""" Depth buffer object. :param int width: Buffer width (pixels) :param int height: Buffer height (pixel) :param GLEnum format: Buffer format (default is gl.GL_DEPTH_COMPONENT) """<def_stmt>__init__ self width height format=gl.GL_DEPTH_COMPONENT#if format not in (gl.GL_DEPTH_COMPONENT16,): # raise ValueError("Format not allowed for depth buffer") <block_start>RenderBuffer.__init__(self width height format)<block_end><block_end><class_stmt>StencilBuffer(RenderBuffer)<block_start>""" Stencil buffer object :param int width: Buffer width (pixels) :param int height: Buffer height (pixel) :param GLEnum format: Buffer format (default is gl.GL_STENCIL_INDEX8) """<def_stmt>__init__ self width height format=gl.GL_STENCIL_INDEX8# if format not in (gl.GL_STENCIL_INDEX,): # raise ValueError("Format not allowed for color buffer") <block_start>RenderBuffer.__init__(self width height format)<block_end><block_end><class_stmt>FrameBuffer(GLObject)<block_start>""" Framebuffer object. :param ColorBuffer color: One or several color buffers or None :param DepthBuffer depth: A depth buffer or None :param StencilBuffer stencil: A stencil buffer or None """<def_stmt>__init__ self color=<none> depth=<none> stencil=<none><block_start>""" """<line_sep>GLObject.__init__(self)<line_sep>self._width=<none><line_sep>self._height=<none><line_sep>self._color=<none><line_sep>self._depth=<none><line_sep>self._stencil=<none><line_sep>self._need_attach=<true><line_sep>self._pending_attachments=[]<if_stmt>color<is><not><none><block_start>self.color=color<block_end><if_stmt>depth<is><not><none><block_start>self.depth=depth<block_end><if_stmt>stencil<is><not><none><block_start>self.stencil=stencil<block_end><block_end>@property<def_stmt>color self<block_start>""" Color buffer attachment(s) (read/write) """<line_sep><return>self._color<block_end>@color.setter<def_stmt>color self buffers<block_start>""" Color buffer attachment(s) (read/write) """<if_stmt><not>isinstance(buffers list)<block_start>buffers=[buffers]<block_end>self._color=[]<for_stmt>i,buffer enumerate(buffers)<block_start><if_stmt>self.width<is><not><none><and>self.width<ne>buffer.width<block_start><raise>ValueError("Buffer width does not match")<block_end><elif_stmt>self.height<is><not><none><and>self.height<ne>buffer.height<block_start><raise>ValueError("Buffer height does not match")<block_end>self._width=buffer.width<line_sep>self._height=buffer.height<line_sep>target=gl.GL_COLOR_ATTACHMENT0+i<line_sep>self._color.append(buffer)<if_stmt>isinstance(buffer (ColorBuffer Texture2D))<or>buffer<is><none><block_start>self._pending_attachments.append((target buffer))<block_end><else_stmt><block_start><raise>ValueError("Buffer must be a ColorBuffer, Texture2D or None")<block_end><block_end>self._need_attach=<true><block_end>@property<def_stmt>depth self<block_start>""" Depth buffer attachment (read/write) """<line_sep><return>self._depth<block_end>@depth.setter<def_stmt>depth self buffer<block_start>""" Depth buffer attachment (read/write) """<if_stmt>self.width<is><not><none><and>self.width<ne>buffer.width<block_start><raise>ValueError("Buffer width does not match")<block_end><elif_stmt>self.height<is><not><none><and>self.height<ne>buffer.height<block_start><raise>ValueError("Buffer height does not match")<block_end>self._width=buffer.width<line_sep>self._height=buffer.height<line_sep>target=gl.GL_DEPTH_ATTACHMENT<line_sep>self._depth=buffer<if_stmt>isinstance(buffer (DepthBuffer Texture2D))<or>buffer<is><none><block_start>self._pending_attachments.append((target buffer))<block_end><else_stmt><block_start><raise>ValueError("Buffer must be a DepthBuffer, Texture2D or None")<block_end>self._need_attach=<true><block_end>@property<def_stmt>stencil self<block_start>""" Stencil buffer attachment (read/write) """<line_sep><return>self._stencil<block_end>@stencil.setter<def_stmt>stencil self buffer<block_start>""" Stencil buffer attachment (read/write) """<if_stmt>self.width<is><not><none><and>self.width<ne>buffer.width<block_start><raise>ValueError("Buffer width does not match")<block_end><elif_stmt>self.height<is><not><none><and>self.height<ne>buffer.height<block_start><raise>ValueError("Buffer height does not match")<block_end>self._width=buffer.width<line_sep>self._height=buffer.height<line_sep>target=gl.GL_STENCIL_ATTACHMENT<line_sep>self._stencil=buffer<if_stmt>isinstance(buffer StencilBuffer)<or>buffer<is><none><block_start>self._pending_attachments.append((target buffer))<block_end><else_stmt><block_start><raise>ValueError("Buffer must be a StencilBuffer, Texture2D or None")<block_end>self._need_attach=<true><block_end>@property<def_stmt>width self<block_start>""" Buffer width (read only, pixels) """<line_sep><return>self._width<block_end>@property<def_stmt>height self<block_start>""" Buffer height (read only, pixels) """<line_sep><return>self._height<block_end><def_stmt>resize self width height<block_start>""" Resize the buffer (deferred operation). This method will also resize any attached buffers. :param int width: New buffer width (pixels) :param int height: New buffer height (pixels) """<line_sep>self._width=width<line_sep>self._height=height<for_stmt>i,buffer enumerate(self.color)<block_start><if_stmt>isinstance(buffer ColorBuffer)<block_start>buffer.resize(width height)<block_end><elif_stmt>isinstance(buffer Texture2D)<block_start>newbuffer=np.resize(buffer (height width buffer.shape[2]))<line_sep>newbuffer=newbuffer.view(buffer.__class__)<line_sep>self.color[i]=newbuffer<line_sep>buffer.delete()<line_sep>target=gl.GL_COLOR_ATTACHMENT0+i<line_sep>self._pending_attachments.append((target self.color[i]))<line_sep>self._need_attach=<true><block_end><block_end><if_stmt>isinstance(self.depth DepthBuffer)<block_start>self.depth.resize(width height)<block_end><elif_stmt>isinstance(self.depth Texture2D)<block_start>depth=np.resize(self.depth (height width self.depth.shape[2]))<line_sep>depth=depth.view(self.depth.__class__)<line_sep>self.depth.delete()<line_sep>self.depth=depth<line_sep>target=gl.GL_DEPTH_ATTACHMENT<line_sep>self._pending_attachments.append((target self.depth))<line_sep>self._need_attach=<true><block_end><if_stmt>isinstance(self.stencil StencilBuffer)<block_start>self.stencil.resize(width height)<block_end><elif_stmt>isinstance(self.stencil Texture2D)<block_start>stencil=np.resize(self.stencil (height width self.stencil.shape[2]))<line_sep>stencil=stencil.view(self.stencil.__class__)<line_sep>self.stencil.delete()<line_sep>self.stencil=stencil<line_sep>target=gl.GL_STENCIL_ATTACHMENT<line_sep>self._pending_attachments.append((target self.stencil))<line_sep>self._need_attach=<true><block_end><block_end><def_stmt>_create self<block_start>""" Create framebuffer on GPU """<line_sep>log.debug("GPU: Create framebuffer")<line_sep>self._handle=gl.glGenFramebuffers(1)<block_end><def_stmt>_delete self<block_start>""" Delete buffer from GPU """<line_sep>log.debug("GPU: Delete framebuffer")<line_sep>gl.glDeleteFramebuffers(1 np.array([self._handle]))<block_end><def_stmt>_activate self<block_start>""" Activate framebuffer on GPU """<line_sep>log.debug("GPU: Activate render framebuffer")<line_sep>gl.glBindFramebuffer(gl.GL_FRAMEBUFFER self._handle)<if_stmt>self._need_attach<block_start>self._attach()<line_sep>self._need_attach=<false><block_end>attachments=[gl.GL_COLOR_ATTACHMENT0+i<for>i range(len(self.color))]<line_sep>gl.glDrawBuffers(np.array(attachments dtype=np.uint32))<block_end><def_stmt>_deactivate self<block_start>""" Deactivate framebuffer on GPU """<line_sep>log.debug("GPU: Deactivate render framebuffer")<line_sep>gl.glBindFramebuffer(gl.GL_FRAMEBUFFER 0)<line_sep># gl.glDrawBuffers([gl.GL_COLOR_ATTACHMENT0]) <block_end><def_stmt>_attach self<block_start>""" Attach render buffers to framebuffer """<line_sep>log.debug("GPU: Attach render buffers")<while_stmt>self._pending_attachments<block_start>attachment,buffer=self._pending_attachments.pop(0)<if_stmt>buffer<is><none><block_start>gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER attachment gl.GL_RENDERBUFFER 0)<block_end><elif_stmt>isinstance(buffer RenderBuffer)<block_start>buffer.activate()<line_sep>gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER attachment gl.GL_RENDERBUFFER buffer.handle)<line_sep>buffer.deactivate()<block_end><elif_stmt>isinstance(buffer Texture2D)<block_start>buffer.activate()<line_sep># INFO: 0 is for mipmap level 0 (default) of the texture gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER attachment buffer.target buffer.handle 0)<line_sep>buffer.deactivate()<block_end><else_stmt><block_start><raise>ValueError("Invalid attachment")<block_end><block_end>res=gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)<if_stmt>res<eq>gl.GL_FRAMEBUFFER_COMPLETE<block_start><pass><block_end><elif_stmt>res<eq>0<block_start><raise>RuntimeError('Target not equal to GL_FRAMEBUFFER')<block_end><elif_stmt>res<eq>gl.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT<block_start><raise>RuntimeError('FrameBuffer attachments are incomplete.')<block_end><elif_stmt>res<eq>gl.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT<block_start><raise>RuntimeError('No valid attachments in the FrameBuffer.')<block_end><elif_stmt>res<eq>gl.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS<block_start><raise>RuntimeError('attachments do not have the same width and height.')<block_end><elif_stmt>res<eq>gl.GL_FRAMEBUFFER_INCOMPLETE_FORMATS<block_start><raise>RuntimeError('Internal format of attachment '<concat>'is not renderable.')<block_end><elif_stmt>res<eq>gl.GL_FRAMEBUFFER_UNSUPPORTED<block_start><raise>RuntimeError('Combination of internal formats used '<concat>'by attachments is not supported.')<block_end><block_end><block_end>
<import_from_future_stmt> print_function<def_stmt>josephus list_of_players step#skipdeadguy <block_start>step<augsub>1<line_sep>index=step<while_stmt>len(list_of_players)<g>1<block_start>print("Player Died : " list_of_players.pop(index))<line_sep>index=(index+step)%len(list_of_players)<block_end>print('Player Survived : ' list_of_players[0])<block_end><def_stmt>main <block_start>print("[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 5")<line_sep>josephus([1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] 5)<block_end><if_stmt>__name__<eq>"__main__"<block_start>main()<block_end>
<import_from_future_stmt> absolute_import division print_function<import_from_stmt>mmtbx.geometry topology<import_stmt>unittest<class_stmt>TestAtom(unittest.TestCase)<block_start><def_stmt>test_1 self<block_start>foo=object()<line_sep>bar=object()<line_sep>a=topology.Atom(foo=foo bar=bar)<line_sep>self.assertEqual(a.foo foo)<line_sep>self.assertEqual(a.bar bar)<block_end><block_end><class_stmt>TestMolecule(unittest.TestCase)<block_start><def_stmt>test_0 self<block_start>m=topology.Molecule()<line_sep>self.assertEqual(m.size() 0)<line_sep>self.assertEqual(m.atoms [])<line_sep>self.assertEqual(m.atom_for {})<line_sep>self.assertEqual(m.descriptor_for {})<line_sep>self.assertEqual(list(m.graph.vertices()) [])<line_sep>self.assertEqual(list(m.graph.edges()) [])<block_end><def_stmt>test_1 self<block_start>m=topology.Molecule()<line_sep>a=topology.Atom()<line_sep>m.add(atom=a xyz=(0 0 0))<line_sep>self.assertEqual(m.size() 1)<line_sep>self.assertEqual(m.atoms [a])<line_sep>self.assertEqual(len(m.atom_for) 1)<line_sep>self.assertTrue(a<in>m.atom_for.values())<line_sep>self.assertEqual(len(m.descriptor_for) 1)<line_sep>self.assertTrue(a<in>m.descriptor_for)<line_sep>self.assertEqual(len(list(m.graph.vertices())) 1)<line_sep>self.assertEqual(list(m.graph.edges()) [])<block_end><def_stmt>test_2 self<block_start>m=topology.Molecule()<line_sep>a1=topology.Atom()<line_sep>a2=topology.Atom()<line_sep>m.add(atom=a1 xyz=(0 0 0))<line_sep>m.add(atom=a2 xyz=(1 1 1))<line_sep>self.assertEqual(m.size() 2)<line_sep>self.assertEqual(set(m.atoms) set([a1 a2]))<line_sep>self.assertEqual(len(m.atom_for) 2)<line_sep>self.assertTrue(a1<in>m.atom_for.values())<line_sep>self.assertTrue(a2<in>m.atom_for.values())<line_sep>self.assertEqual(len(m.descriptor_for) 2)<line_sep>self.assertTrue(a1<in>m.descriptor_for)<line_sep>self.assertTrue(a2<in>m.descriptor_for)<line_sep>self.assertEqual(len(list(m.graph.vertices())) 2)<line_sep>self.assertEqual(len(list(m.graph.edges())) 1)<line_sep>edge=next(m.graph.edges())<line_sep>self.assertAlmostEqual(m.graph.edge_weight(edge=edge) 1.73205 5)<block_end><block_end><class_stmt>TestCompound(unittest.TestCase)<block_start><def_stmt>test_0 self<block_start>m=topology.Compound.create()<line_sep>self.assertEqual(m.atoms [])<line_sep>self.assertEqual(m.atom_for {})<line_sep>self.assertEqual(m.descriptor_for {})<line_sep>self.assertEqual(list(m.graph.vertices()) [])<line_sep>self.assertEqual(list(m.graph.edges()) [])<block_end><def_stmt>test_1 self<block_start>m=topology.Compound.create()<line_sep>a=topology.Atom()<line_sep>m.add_atom(atom=a)<line_sep>self.assertEqual(m.atoms [a])<line_sep>self.assertEqual(len(m.atom_for) 1)<line_sep>self.assertTrue(a<in>m.atom_for.values())<line_sep>self.assertEqual(len(m.descriptor_for) 1)<line_sep>self.assertTrue(a<in>m.descriptor_for)<line_sep>self.assertEqual(len(list(m.graph.vertices())) 1)<line_sep>self.assertEqual(list(m.graph.edges()) [])<line_sep>self.assertEqual(m.distances_from(atom=a) {a:0})<line_sep>self.assertEqual(m.connected_segments() [[a]])<block_end><def_stmt>test_2 self<block_start>m=topology.Compound.create()<line_sep>a1=topology.Atom()<line_sep>a2=topology.Atom()<line_sep>m.add_atom(atom=a1)<line_sep>m.add_atom(atom=a2)<line_sep>self.assertEqual(set(m.atoms) set([a1 a2]))<line_sep>self.assertEqual(len(m.atom_for) 2)<line_sep>self.assertTrue(a1<in>m.atom_for.values())<line_sep>self.assertTrue(a2<in>m.atom_for.values())<line_sep>self.assertEqual(len(m.descriptor_for) 2)<line_sep>self.assertTrue(a1<in>m.descriptor_for)<line_sep>self.assertTrue(a2<in>m.descriptor_for)<line_sep>self.assertEqual(len(list(m.graph.vertices())) 2)<line_sep>self.assertEqual(len(list(m.graph.edges())) 0)<line_sep>self.assertEqual(m.distances_from(atom=a1) {a1:0 a2:<none>})<line_sep>self.assertEqual(m.distances_from(atom=a2) {a2:0 a1:<none>})<line_sep>self.assertEqual(set(frozenset(s)<for>s m.connected_segments()) set([frozenset([a1]) frozenset([a2])]) )<line_sep>m.add_bond(left=a1 right=a2)<line_sep>self.assertEqual(len(list(m.graph.vertices())) 2)<line_sep>self.assertEqual(len(list(m.graph.edges())) 1)<line_sep>self.assertEqual(m.distances_from(atom=a1) {a1:0 a2:1})<line_sep>self.assertEqual(m.distances_from(atom=a2) {a2:0 a1:1})<line_sep>self.assertEqual(set(frozenset(s)<for>s m.connected_segments()) set([frozenset([a1 a2])]) )<line_sep>ss1=m.subset(atoms=[a1])<line_sep>self.assertEqual(len(ss1.atom_for) 1)<line_sep>self.assertTrue(a1<in>ss1.atom_for.values())<line_sep>self.assertEqual(len(ss1.descriptor_for) 1)<line_sep>self.assertTrue(a1<in>ss1.descriptor_for)<line_sep>self.assertEqual(len(list(ss1.graph.vertices())) 1)<line_sep>self.assertEqual(len(list(ss1.graph.edges())) 0)<line_sep>ss2=m.subset(atoms=[a2])<line_sep>self.assertEqual(len(ss2.atom_for) 1)<line_sep>self.assertTrue(a2<in>ss2.atom_for.values())<line_sep>self.assertEqual(len(ss2.descriptor_for) 1)<line_sep>self.assertTrue(a2<in>ss2.descriptor_for)<line_sep>self.assertEqual(len(list(ss2.graph.vertices())) 1)<line_sep>self.assertEqual(len(list(ss2.graph.edges())) 0)<block_end><def_stmt>test_3 self<block_start>atoms=[topology.Atom(name="N" element="N" xyz=(11.498 10.510 10.231)) topology.Atom(name="CA" element="C" xyz=(12.730 11.073 10.769)) topology.Atom(name="C" element="C" xyz=(13.674 9.966 11.221)) topology.Atom(name="O" element="O" xyz=(13.739 8.902 10.605)) topology.Atom(name="CB" element="C" xyz=(12.421 12.004 11.944)) topology.Atom(name="CG" element="C" xyz=(11.478 13.179 11.661)) topology.Atom(name="CD1" element="C" xyz=(11.043 13.834 12.963)) topology.Atom(name="CD2" element="C" xyz=(12.126 14.201 10.736)) ]<line_sep>compound=topology.Compound.from_structure(atoms=atoms tolerance=0.1)<line_sep>self.assertEqual(set(frozenset([l.name r.name])<for>(l r) compound.bonds) set([frozenset(["N" "CA"]) frozenset(["CA" "C"]) frozenset(["C" "O"]) frozenset(["CA" "CB"]) frozenset(["CB" "CG"]) frozenset(["CG" "CD1"]) frozenset(["CG" "CD2"]) ]))<block_end><block_end><class_stmt>TestMcGregorMatch(unittest.TestCase)<block_start><def_stmt>test_asn_leu self<block_start>l_ca=topology.Atom(label="CA")<line_sep>l_cb=topology.Atom(label="C")<line_sep>l_cg=topology.Atom(label="C")<line_sep>l_cd1=topology.Atom(label="C")<line_sep>l_cd2=topology.Atom(label="C")<line_sep>leu=topology.Molecule()<line_sep>leu.add(atom=l_ca xyz=(-1.0085 -0.590773 0.814318))<line_sep>leu.add(atom=l_cb xyz=(0.0275 -0.557773 -0.314682))<line_sep>leu.add(atom=l_cg xyz=(1.2335 0.374227 -0.138682))<line_sep>leu.add(atom=l_cd1 xyz=(2.3065 0.046227 -1.16768))<line_sep>leu.add(atom=l_cd2 xyz=(0.8395 1.84323 -0.230682))<line_sep>a_ca=topology.Atom(label="CA")<line_sep>a_cb=topology.Atom(label="C")<line_sep>a_cg=topology.Atom(label="C")<line_sep>a_od1=topology.Atom(label="C")<line_sep>a_nd2=topology.Atom(label="C")<line_sep>asn=topology.Molecule()<line_sep>asn.add(atom=a_ca xyz=(-1.03327 -0.544348 0.860946))<line_sep>asn.add(atom=a_cb xyz=(0.10486 -0.548357 -0.164901))<line_sep>asn.add(atom=a_cg xyz=(0.990984 0.682823 -0.070521))<line_sep>asn.add(atom=a_od1 xyz=(1.39496 1.24684 -1.08724))<line_sep>asn.add(atom=a_nd2 xyz=(1.29745 1.10599 1.15228))<line_sep>res=topology.McGregorMatch(molecule1=leu molecule2=asn is_valid=<lambda>match:any(m.label<eq>"CA"<for>m match) vertex_equality=<lambda>l r:l.label<eq>r.label edge_equality=<lambda>l r:abs(l-r)<l>0.1)<line_sep>self.assertEqual(res.length() 3)<line_sep>mapping=res.remapped()<line_sep>self.assertTrue((l_ca a_ca)<in>mapping)<line_sep>self.assertTrue((l_cb a_cb)<in>mapping)<line_sep>self.assertTrue((l_cg a_cg)<in>mapping)<line_sep>self.assertTrue((l_cd1 a_od1)<not><in>mapping)<block_end><block_end><class_stmt>TestRascalMatch(unittest.TestCase)<block_start><def_stmt>test_asn_leu self<block_start>l_ca=topology.Atom(label="CA")<line_sep>l_cb=topology.Atom(label="C")<line_sep>l_cg=topology.Atom(label="C")<line_sep>l_cd1=topology.Atom(label="C")<line_sep>l_cd2=topology.Atom(label="C")<line_sep>leu=topology.Molecule()<line_sep>leu.add(atom=l_ca xyz=(-1.0085 -0.590773 0.814318))<line_sep>leu.add(atom=l_cb xyz=(0.0275 -0.557773 -0.314682))<line_sep>leu.add(atom=l_cg xyz=(1.2335 0.374227 -0.138682))<line_sep>leu.add(atom=l_cd1 xyz=(2.3065 0.046227 -1.16768))<line_sep>leu.add(atom=l_cd2 xyz=(0.8395 1.84323 -0.230682))<line_sep>a_ca=topology.Atom(label="CA")<line_sep>a_cb=topology.Atom(label="C")<line_sep>a_cg=topology.Atom(label="C")<line_sep>a_od1=topology.Atom(label="C")<line_sep>a_nd2=topology.Atom(label="C")<line_sep>asn=topology.Molecule()<line_sep>asn.add(atom=a_ca xyz=(-1.03327 -0.544348 0.860946))<line_sep>asn.add(atom=a_cb xyz=(0.10486 -0.548357 -0.164901))<line_sep>asn.add(atom=a_cg xyz=(0.990984 0.682823 -0.070521))<line_sep>asn.add(atom=a_od1 xyz=(1.39496 1.24684 -1.08724))<line_sep>asn.add(atom=a_nd2 xyz=(1.29745 1.10599 1.15228))<line_sep>m=topology.RascalMatch(molecule1=leu molecule2=asn vertex_equality=<lambda>l r:l.label<eq>r.label edge_equality=<lambda>l r:abs(l-r)<le>0.1 )<line_sep>self.assertEqual(m.count() 1)<line_sep>self.assertEqual(m.length() 3)<line_sep>mapping=m.remapped()[0]<line_sep>self.assertEqual(len(mapping) 3)<line_sep>self.assertTrue((l_ca a_ca)<in>mapping)<line_sep>self.assertTrue((l_cb a_cb)<in>mapping)<line_sep>self.assertTrue((l_cg a_cg)<in>mapping)<line_sep>self.assertTrue((l_cd1 a_od1)<not><in>mapping)<block_end><block_end><class_stmt>TestGreedyMatch(unittest.TestCase)<block_start><def_stmt>test_asn_leu self<block_start>l_ca=topology.Atom(label="CA")<line_sep>l_cb=topology.Atom(label="C")<line_sep>l_cg=topology.Atom(label="C")<line_sep>l_cd1=topology.Atom(label="C")<line_sep>l_cd2=topology.Atom(label="C")<line_sep>leu=topology.Molecule()<line_sep>leu.add(atom=l_ca xyz=(-1.0085 -0.590773 0.814318))<line_sep>leu.add(atom=l_cb xyz=(0.0275 -0.557773 -0.314682))<line_sep>leu.add(atom=l_cg xyz=(1.2335 0.374227 -0.138682))<line_sep>leu.add(atom=l_cd1 xyz=(2.3065 0.046227 -1.16768))<line_sep>leu.add(atom=l_cd2 xyz=(0.8395 1.84323 -0.230682))<line_sep>a_ca=topology.Atom(label="CA")<line_sep>a_cb=topology.Atom(label="C")<line_sep>a_cg=topology.Atom(label="C")<line_sep>a_od1=topology.Atom(label="C")<line_sep>a_nd2=topology.Atom(label="C")<line_sep>asn=topology.Molecule()<line_sep>asn.add(atom=a_ca xyz=(-1.03327 -0.544348 0.860946))<line_sep>asn.add(atom=a_cb xyz=(0.10486 -0.548357 -0.164901))<line_sep>asn.add(atom=a_cg xyz=(0.990984 0.682823 -0.070521))<line_sep>asn.add(atom=a_od1 xyz=(1.39496 1.24684 -1.08724))<line_sep>asn.add(atom=a_nd2 xyz=(1.29745 1.10599 1.15228))<line_sep>m=topology.GreedyMatch(molecule1=leu molecule2=asn vertex_equality=<lambda>l r:l.label<eq>r.label edge_equality=<lambda>l r:abs(l-r)<le>0.1 )<line_sep>self.assertEqual(m.count() 1)<line_sep>self.assertEqual(m.length() 3)<line_sep>mapping=m.remapped()[0]<line_sep>self.assertEqual(len(mapping) 3)<line_sep>self.assertTrue((l_ca a_ca)<in>mapping)<line_sep>self.assertTrue((l_cb a_cb)<in>mapping)<line_sep>self.assertTrue((l_cg a_cg)<in>mapping)<line_sep>self.assertTrue((l_cd1 a_od1)<not><in>mapping)<block_end><block_end>suite_atom=unittest.TestLoader().loadTestsFromTestCase(TestAtom)<line_sep>suite_molecule=unittest.TestLoader().loadTestsFromTestCase(TestMolecule)<line_sep>suite_compound=unittest.TestLoader().loadTestsFromTestCase(TestCompound)<line_sep>suite_mcgregor_match=unittest.TestLoader().loadTestsFromTestCase(TestMcGregorMatch)<line_sep>suite_rascal_match=unittest.TestLoader().loadTestsFromTestCase(TestRascalMatch)<line_sep>suite_greedy_match=unittest.TestLoader().loadTestsFromTestCase(TestGreedyMatch)<line_sep>alltests=unittest.TestSuite([suite_atom suite_molecule suite_compound suite_mcgregor_match suite_rascal_match suite_greedy_match ])<def_stmt>load_tests loader tests pattern<block_start><return>alltests<block_end><if_stmt>__name__<eq>"__main__"<block_start>unittest.TextTestRunner(verbosity=2).run(alltests)<block_end>
# -*- coding: utf-8 -*- <import_stmt>pytest<import_from_stmt>bravado_core.exception SwaggerMappingError<import_from_stmt>bravado_core.schema get_spec_for_prop<import_from_stmt>bravado_core.spec Spec<line_sep>@pytest.fixture<def_stmt>address_spec <block_start><return>{'type':'object' 'properties':{'number':{'type':'number' } 'street_name':{'type':'string' } 'street_type':{'type':'string' 'enum':['Street' 'Avenue' 'Boulevard' ] } } }<block_end>@pytest.fixture<def_stmt>business_address_spec <block_start><return>{'allOf':[{'$ref':'#/definitions/Address' } {'type':'object' 'properties':{'company':{'type':'string' } } } ] }<block_end>@pytest.fixture<def_stmt>address <block_start><return>{'number':1600 'street_name':'Pennsylvania' 'street_type':'Avenue' }<block_end>@pytest.fixture<def_stmt>business_address <block_start><return>{'company':'White House' 'number':1600 'street_name':'Pennsylvania' 'street_type':'Avenue' }<block_end><def_stmt>test_declared_property minimal_swagger_spec address_spec address<block_start>expected_spec=address_spec['properties']['street_name']<line_sep>result=get_spec_for_prop(minimal_swagger_spec address_spec address 'street_name' )<assert_stmt>expected_spec<eq>result<block_end><def_stmt>test_properties_and_additionalProperties_not_present minimal_swagger_spec address<block_start>object_spec={'type':'object'}<line_sep>result=get_spec_for_prop(minimal_swagger_spec object_spec address 'street_name' )<assert_stmt>result<is><none><block_end><def_stmt>test_properties_not_present_and_additionalProperties_True minimal_swagger_spec address<block_start>object_spec={'type':'object' 'additionalProperties':<true> }<line_sep>result=get_spec_for_prop(minimal_swagger_spec object_spec address 'street_name' )<assert_stmt>result<is><none><block_end><def_stmt>test_properties_not_present_and_additionalProperties_False minimal_swagger_spec address<block_start>object_spec={'type':'object' 'additionalProperties':<false> }<line_sep>result=get_spec_for_prop(minimal_swagger_spec object_spec address 'street_name' )<assert_stmt>result<is><none><block_end><def_stmt>test_additionalProperties_with_spec minimal_swagger_spec address_spec address<block_start>address_spec['additionalProperties']={'type':'string'}<line_sep>expected_spec={'type':'string'}<line_sep># 'city' is not a declared property so it gets classified under # additionalProperties result=get_spec_for_prop(minimal_swagger_spec address_spec address 'city' )<assert_stmt>expected_spec<eq>result<block_end><def_stmt>test_additionalProperties_not_dict_like minimal_swagger_spec address_spec address<block_start>address_spec['additionalProperties']='i am not a dict'<with_stmt>pytest.raises(SwaggerMappingError)<as>excinfo<block_start>get_spec_for_prop(minimal_swagger_spec address_spec address 'city')<block_end><assert_stmt>"Don't know what to do"<in>str(excinfo.value)<block_end>@pytest.mark.filterwarnings("ignore:.*with siblings that will be overwritten")<def_stmt>test_get_spec_for_prop_with_x_nullable_and_reference minimal_swagger_dict# TODO: remove is_nullable support once https://github.com/Yelp/bravado-core/issues/335 is addressed <block_start>minimal_swagger_dict['definitions']={'referenced':{'type':'string' } 'model':{'type':'object' 'properties':{'property':{'x-nullable':<true> '$ref':'#/definitions/referenced' } } } }<line_sep>swagger_spec=Spec.from_dict(minimal_swagger_dict)<assert_stmt>{'x-nullable':<true> 'type':'string'}<eq>get_spec_for_prop(swagger_spec minimal_swagger_dict['definitions']['model'] <none> 'property' )<block_end><def_stmt>test_composition minimal_swagger_dict address_spec address business_address_spec business_address<block_start>minimal_swagger_dict['definitions']['Address']=address_spec<line_sep>minimal_swagger_dict['definitions']['BusinessAddress']=business_address_spec<line_sep>swagger_spec=Spec.from_dict(minimal_swagger_dict)<line_sep>expected_spec_1=address_spec['properties']['street_name']<line_sep>result_1=get_spec_for_prop(swagger_spec address_spec address 'street_name' )<assert_stmt>expected_spec_1<eq>result_1<line_sep>expected_spec_2=business_address_spec['allOf'][1]['properties']['company']<line_sep>result_2=get_spec_for_prop(swagger_spec business_address_spec business_address 'company' )<assert_stmt>expected_spec_2<eq>result_2<block_end><def_stmt>test_object_is_ref minimal_swagger_dict address_spec address<block_start>minimal_swagger_dict['definitions']['Address']=address_spec<line_sep>address_ref_spec={'$ref':'#/definitions/Address'}<line_sep>swagger_spec=Spec.from_dict(minimal_swagger_dict)<line_sep>result=get_spec_for_prop(swagger_spec address_ref_spec address 'street_type' )<assert_stmt>address_spec['properties']['street_type']<eq>result<block_end><def_stmt>test_property_is_ref minimal_swagger_dict address<block_start>street_type_spec={'type':'string' 'enum':['Street' 'Avenue' 'Boulevard'] }<line_sep>address_spec={'type':'object' 'properties':{'street_type':{'$ref':'#/definitions/StreetType' } } }<line_sep>minimal_swagger_dict['definitions']['StreetType']=street_type_spec<line_sep>swagger_spec=Spec.from_dict(minimal_swagger_dict)<line_sep>result=get_spec_for_prop(swagger_spec address_spec address 'street_type' )<assert_stmt>street_type_spec<eq>result<block_end>
""" Classes from the 'CryptoTokenKit' framework. """<try_stmt><block_start><import_from_stmt>rubicon.objc ObjCClass<block_end><except_stmt>ValueError<block_start><def_stmt>ObjCClass name<block_start><return><none><block_end><block_end><def_stmt>_Class name<block_start><try_stmt><block_start><return>ObjCClass(name)<block_end><except_stmt>NameError<block_start><return><none><block_end><block_end>TKTokenWatcher=_Class("TKTokenWatcher")<line_sep>TKTokenWatcherTokenInfo=_Class("TKTokenWatcherTokenInfo")<line_sep>TKTokenWatcherProxy=_Class("TKTokenWatcherProxy")<line_sep>TKTokenKeyAlgorithm=_Class("TKTokenKeyAlgorithm")<line_sep>TKTokenKeyExchangeParameters=_Class("TKTokenKeyExchangeParameters")<line_sep>TKApplicationProxy=_Class("TKApplicationProxy")<line_sep>TKTokenConnection=_Class("TKTokenConnection")<line_sep>TKTokenSessionConnection=_Class("TKTokenSessionConnection")<line_sep>TKTokenAccessUserPromptInfo=_Class("TKTokenAccessUserPromptInfo")<line_sep>TKSharedResource=_Class("TKSharedResource")<line_sep>TKSharedResourceSlot=_Class("TKSharedResourceSlot")<line_sep>TKTokenAccessRegistry=_Class("TKTokenAccessRegistry")<line_sep>TKSmartCardATR=_Class("TKSmartCardATR")<line_sep>TKSmartCardATRInterfaceGroup=_Class("TKSmartCardATRInterfaceGroup")<line_sep>TKTokenAccessUserPromptNoop=_Class("TKTokenAccessUserPromptNoop")<line_sep>TKTokenAccessUserPromptRemoteAlert=_Class("TKTokenAccessUserPromptRemoteAlert")<line_sep>TKTokenKeychainContents=_Class("TKTokenKeychainContents")<line_sep>TKTokenKeychainItem=_Class("TKTokenKeychainItem")<line_sep>TKTokenKeychainKey=_Class("TKTokenKeychainKey")<line_sep>TKTokenKeychainCertificate=_Class("TKTokenKeychainCertificate")<line_sep>TKTokenAccessRequest=_Class("TKTokenAccessRequest")<line_sep>TKClientTokenAdvertisedItem=_Class("TKClientTokenAdvertisedItem")<line_sep>TKClientTokenSession=_Class("TKClientTokenSession")<line_sep>TKClientTokenObject=_Class("TKClientTokenObject")<line_sep>TKClientToken=_Class("TKClientToken")<line_sep>TKTokenSession=_Class("TKTokenSession")<line_sep>TKSmartCardTokenSession=_Class("TKSmartCardTokenSession")<line_sep>TKTokenAuthOperation=_Class("TKTokenAuthOperation")<line_sep>TKTokenPasswordAuthOperation=_Class("TKTokenPasswordAuthOperation")<line_sep>TKTokenSmartCardPINAuthOperation=_Class("TKTokenSmartCardPINAuthOperation")<line_sep>TKSmartCardSessionEngine=_Class("TKSmartCardSessionEngine")<line_sep>TKSmartCardSlotEngine=_Class("TKSmartCardSlotEngine")<line_sep>_TKSmartCardSlotReservation=_Class("_TKSmartCardSlotReservation")<line_sep>TKPowerMonitor=_Class("TKPowerMonitor")<line_sep>TKSmartCardSessionRequest=_Class("TKSmartCardSessionRequest")<line_sep>TKTokenDriverConfiguration=_Class("TKTokenDriverConfiguration")<line_sep>TKTokenConfiguration=_Class("TKTokenConfiguration")<line_sep>TKTokenConfigurationTransaction=_Class("TKTokenConfigurationTransaction")<line_sep>TKTokenConfigurationConnection=_Class("TKTokenConfigurationConnection")<line_sep>TKTokenID=_Class("TKTokenID")<line_sep>TKSmartCardUserInteraction=_Class("TKSmartCardUserInteraction")<line_sep>TKSmartCardUserInteractionForStringEntry=_Class("TKSmartCardUserInteractionForStringEntry")<line_sep>TKSmartCardUserInteractionForConfirmation=_Class("TKSmartCardUserInteractionForConfirmation")<line_sep>TKSmartCardUserInteractionForPINOperation=_Class("TKSmartCardUserInteractionForPINOperation")<line_sep>TKSmartCardUserInteractionForSecurePINChange=_Class("TKSmartCardUserInteractionForSecurePINChange")<line_sep>TKSmartCardUserInteractionForSecurePINVerification=_Class("TKSmartCardUserInteractionForSecurePINVerification")<line_sep>TKSmartCardSlotScreen=_Class("TKSmartCardSlotScreen")<line_sep>TKSmartCardPINFormat=_Class("TKSmartCardPINFormat")<line_sep>TKSmartCard=_Class("TKSmartCard")<line_sep>TKSmartCardWithError=_Class("TKSmartCardWithError")<line_sep>TKSmartCardSlot=_Class("TKSmartCardSlot")<line_sep>TKSmartCardSlotProxy=_Class("TKSmartCardSlotProxy")<line_sep>TKSmartCardSlotManager=_Class("TKSmartCardSlotManager")<line_sep>TKTokenAccessDBBackedByUserDefaults=_Class("TKTokenAccessDBBackedByUserDefaults")<line_sep>TKTLVRecord=_Class("TKTLVRecord")<line_sep>TKCompactTLVRecord=_Class("TKCompactTLVRecord")<line_sep>TKSimpleTLVRecord=_Class("TKSimpleTLVRecord")<line_sep>TKBERTLVRecord=_Class("TKBERTLVRecord")<line_sep>TKDataSource=_Class("TKDataSource")<line_sep>TKTokenDriverRequest=_Class("TKTokenDriverRequest")<line_sep>TKTokenService_Subsystem=_Class("TKTokenService_Subsystem")<line_sep>TKTokenDriver=_Class("TKTokenDriver")<line_sep>TKSmartCardTokenDriver=_Class("TKSmartCardTokenDriver")<line_sep>TKToken=_Class("TKToken")<line_sep>TKSmartCardToken=_Class("TKSmartCardToken")<line_sep>TKTokenBaseContext=_Class("TKTokenBaseContext")<line_sep>TKTokenDriverContext=_Class("TKTokenDriverContext")<line_sep>
#!python3 <import_stmt>os<import_stmt>sys<line_sep>sys.path.insert(1 os.path.dirname(os.path.dirname(os.path.abspath(__file__))))<import_stmt>util<import_stmt>re<import_stmt>shutil<import_stmt>subprocess<import_stmt>dllversion<import_from_stmt>os.path abspath<import_from_stmt>subprocess check_call<import_from_stmt>util glob_paths rmpath mkdirs buildTimeStamp projectDir getGppVer<line_sep>sys.platform<eq>'win32'<or>sys.exit('error: script only runs on Windows (no Cygwin/MSYS)')<line_sep>shutil.which('7z')<or>sys.exit('error: 7z missing')<line_sep>shutil.which('curl')<or>sys.exit('error: curl missing')<line_sep>buildDir=os.path.join(projectDir 'out\\build-cygwin')<line_sep>artifactDir=os.path.join(projectDir 'out\\artifact')<line_sep>rmpath(buildDir)<line_sep>mkdirs(buildDir)<line_sep>mkdirs(artifactDir)<line_sep>os.chdir(buildDir)<for_stmt>setup,cygwin (('setup-x86_64' 'cygwin64') ('setup-x86' 'cygwin32'))<block_start>check_call(['curl' '-fL' '-O' 'https://cygwin.com/{}.exe'.format(setup)])<line_sep>check_call([abspath('{}.exe'.format(setup)) '-l' abspath('{}-packages'.format(cygwin)) '-P' 'gcc-g++,make' '-s' 'http://mirrors.kernel.org/sourceware/cygwin' '-R' abspath(cygwin) '--no-admin' '--no-desktop' '--no-shortcuts' '--no-startmenu' '--quiet-mode' ])<line_sep>check_call(['{}/bin/ash.exe'.format(cygwin) '/bin/rebaseall' '-v'])<line_sep>cygVer=dllversion.fileVersion('{}/bin/cygwin1.dll'.format(cygwin))<line_sep>gppVer=getGppVer('{}/bin/g++.exe'.format(cygwin))<line_sep>filename='{}\\{}-{}-dll{}-gcc{}.7z'.format(artifactDir cygwin buildTimeStamp cygVer gppVer)<line_sep>rmpath(filename)<line_sep>open(cygwin+'/tmp/.keep' 'wb').close()<line_sep>check_call(['7z' 'a' '-mx=9' filename]+glob_paths([cygwin+'/dev' cygwin+'/etc/setup' cygwin+'/tmp/.keep' cygwin+'/bin' cygwin+'/lib' cygwin+'/usr/include' cygwin+'/usr/*-pc-cygwin' ]))<block_end>
# Testing datetime module <import_stmt>sys<import_stmt>UnitTest<import_stmt>datetime<class_stmt>DatetimeModuleTest(UnitTest.UnitTest)<block_start><def_stmt>testDate self<block_start>d=datetime.date(2010 4 9)<line_sep>self.assertEqual(d.year 2010)<line_sep>self.assertEqual(d.month 4)<line_sep>self.assertEqual(d.day 9)<line_sep>self.assertEqual(d.weekday() 4)<block_end><def_stmt>testTime self<block_start>t=datetime.time(9 45 11 95000)<line_sep>self.assertEqual(t.hour 9)<line_sep>self.assertEqual(t.minute 45)<line_sep>self.assertEqual(t.second 11)<line_sep>self.assertEqual(t.microsecond 95000)<block_end><def_stmt>testTimestamp self<block_start>d=datetime.date.fromtimestamp(1270804609)<line_sep>self.assertEqual(str(d) '2010-04-09')<line_sep>dt=str(datetime.datetime.fromtimestamp(1270804609.95))<line_sep># CET: 2010-04-09 11:16:49.950000 self.assertEqual((dt[:11] dt[16:]) ("2010-04-09 " ":49.950000") )<block_end><def_stmt>testCtime self<block_start>d=datetime.date(2010 4 9)<line_sep>self.assertEqual(d.ctime() "Fri Apr 9 00:00:00 2010")<line_sep>dt=datetime.datetime(2010 4 9 10 57 32)<line_sep>self.assertEqual(dt.ctime() "Fri Apr 9 10:57:32 2010")<block_end><def_stmt>testIsoCalendar self<block_start>d=datetime.date(2010 4 9)<line_sep>self.assertEqual(d.isocalendar() (2010 14 5))<line_sep>d1=datetime.date(2007 12 31)<line_sep>self.assertEqual(d1.isocalendar() (2008 1 1))<block_end><def_stmt>testIsoFormat self<block_start>d=datetime.date(2010 4 9)<line_sep>self.assertEqual(d.isoformat() '2010-04-09')<line_sep>dt=datetime.datetime(2010 4 9 10 57 32)<line_sep>self.assertEqual(dt.isoformat() '2010-04-09T10:57:32')<line_sep>dt2=datetime.datetime(2010 4 9 10 57 32 95000)<line_sep>self.assertEqual(dt2.isoformat() '2010-04-09T10:57:32.095000')<block_end><def_stmt>testOrdinal self<block_start>d=datetime.date.fromordinal(1)<line_sep>self.assertEqual(str(d) '0001-01-01')<line_sep>d1=datetime.date.fromordinal(733871)<line_sep>self.assertEqual(str(d1) '2010-04-09')<line_sep>self.assertEqual(d1.toordinal() 733871)<block_end><def_stmt>testReplace self<block_start>d=datetime.date(2010 4 9).replace(month=6 day=13)<line_sep>self.assertEqual(str(d) '2010-06-13')<line_sep>t=datetime.time(23 59 59).replace(minute=45 microsecond=95000)<line_sep>self.assertEqual(str(t) '23:45:59.095000')<line_sep>dt=datetime.datetime(2010 4 9 10 57 32).replace(month=6 day=13 hour=12 minute=0 second=0)<line_sep>self.assertEqual(str(dt) '2010-06-13 12:00:00')<block_end><def_stmt>testTimetuple self<block_start>tm=datetime.date(2010 4 9).timetuple()<line_sep>self.assertEqual(tm.tm_year 2010)<line_sep>self.assertEqual(tm.tm_mon 4)<line_sep>self.assertEqual(tm.tm_mday 9)<line_sep>self.assertEqual(tm.tm_hour 0)<line_sep>self.assertEqual(tm.tm_min 0)<line_sep>self.assertEqual(tm.tm_sec 0)<line_sep>self.assertEqual(tm.tm_wday 4)<line_sep>self.assertEqual(tm.tm_yday 99)<block_end><def_stmt>testStrftime self<block_start>d=datetime.date(2010 4 9)<line_sep>self.assertEqual(d.strftime("%d/%m/%y") "09/04/10")<block_end><def_stmt>testStrptime self<block_start>d=datetime.datetime.strptime("010100 1234" "%d%m%y %H%M")<line_sep>self.assertEqual(str(d) '2000-01-01 12:34:00')<block_end><def_stmt>testComparision self<block_start>d1=datetime.date(2010 6 8)<line_sep>d2=datetime.date(2010 6 8)<line_sep>d3=datetime.date(2010 4 9)<line_sep>self.assertTrue(d1<eq>d2 "d1 and d2 differ")<line_sep>self.assertTrue(d1<g>d3 "d1 is not later than d3")<line_sep>self.assertTrue(d3<l>d1 "d3 is not earlier than d1")<block_end><def_stmt>testOperations self<block_start>d1=datetime.date(2010 4 9)<line_sep>d2=datetime.date(2010 6 13)<line_sep>diff=d2-d1<line_sep>self.assertEqual(diff.days 65)<line_sep>self.assertEqual(str(d1+diff) "2010-06-13")<line_sep>self.assertEqual(str(d1-diff) "2010-02-03")<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start><import_from_stmt>RunTests RunTests<line_sep>t=RunTests()<line_sep>t.add(DatetimeModuleTest)<line_sep>t.start_test()<block_end>
<import_stmt>os<import_stmt>re<import_stmt>json<import_stmt>time<import_stmt>numpy<as>np<import_stmt>pandas<as>pd<import_from_stmt>plotnine *<line_sep># Config PATH=os.getcwd()<line_sep>path_n=re.split(pattern=r"/|\\" string=PATH)[1:]<if_stmt>os.name<eq>"posix"<block_start>path_n="/"+os.path.join(*path_n)<block_end><else_stmt><block_start>drive=PATH[0:3]<line_sep>path_n=drive+os.path.join(*path_n)<block_end>RUNS=100<def_stmt>infer_column_cats dir:"Path to working directoty."<arrow>tuple<block_start>"""Helper function to identify dataset sizes based on file names."""<line_sep>files=os.listdir(os.path.join(dir "data"))<line_sep>cats=set([re.match(pattern=".*_(.*).csv$" string=file).group(1)<for>file files])<line_sep>cols=set([re.match(pattern=".*_(.*)_.*.csv$" string=file).group(1)<for>file files])<line_sep><return>cats cols<block_end><def_stmt>time_function func:"Function call to be evaluted as str."<arrow>float<block_start>"""Helper function to time data access."""<line_sep>start=time.time()<line_sep>exec(func)<line_sep><return>time.time()-start<block_end><def_stmt>create_stats measures:"List of function timings." col:"Current Column." row:"Current Row" scenario:"Current Scenario."<arrow>dict<block_start>"""Helper function to create result dataset."""<line_sep><return>{"scenario":scenario "no_column":col "data_length":row "min":np.min(measures) "max":np.max(measures) "avg":np.mean(measures) "q50":np.median(measures)}<block_end>scenarios=json.load(open(os.path.join(path_n "output" "mutate.JSON")))<line_sep>nrows,ncols=infer_column_cats(path_n)<line_sep>timings,results=[] []<for_stmt>col ncols<block_start>print(f"-Column: {col}--")<for_stmt>row nrows<block_start>print(f"--Row: {row}")<line_sep>data=pd.read_csv(os.path.join(path_n "data" f"sim_data_{col}_{row}.csv"))<for_stmt>i,scenario enumerate(scenarios[col]["mutate"])<block_start>print(f"---Scenario {i+1}: {scenario}---")<line_sep>sel=re.search(pattern=r'([A-Z]{3})' string=scenario).group(1)<line_sep>print(sel)<if_stmt>sel<eq>"INT"<block_start>func=f"temp['result'] = temp['{scenario}'] + 1"<block_end><elif_stmt>sel<eq>"DBL"<block_start>func=f"temp['result'] = temp['{scenario}'] * 2"<block_end><elif_stmt>sel<eq>"STR"<block_start>func=f"temp['result'] = temp['{scenario}'] + 'a'"<block_end><elif_stmt>sel<eq>"LGL"<block_start>func=f"temp['result'] = ~temp['{scenario}']"<block_end><for_stmt>j range(RUNS)<block_start>temp=data<line_sep>timings.append(time_function(func=func))<line_sep>temp=<none><block_end>results.append(create_stats(measures=timings col=col row=row scenario=sel))<line_sep>print(results[-1])<line_sep>timings=[]<block_end><block_end><block_end>results_df=pd.DataFrame(results)<line_sep>results_df[["data_length" "no_column"]]=results_df[["data_length" "no_column"]].apply(pd.to_numeric axis=1 downcast="integer")<line_sep>results_df.sort_values(["data_length" "no_column"])<line_sep>results_df[["min" "max" "q50" "avg"]]=round(results_df[["min" "max" "q50" "avg"]]<times>1000 2)<line_sep># results_df["sel_col"] = results_df["scenario"].apply(lambda x: re.search(pattern="([13])", string=x).group(1)) # results_df["pos_col"] = results_df["scenario"].apply(lambda x: re.search(pattern="[13](.*)$", string=x).group(1)) results_df.to_csv(os.path.join(path_n "output" "mutate_results_pandas.csv") index=<false>)<line_sep>
<import_stmt>sys<import_stmt>os<import_stmt>os.path<import_stmt>hashlib<import_stmt>struct<import_stmt>tempfile<import_stmt>shutil<import_stmt>pickle<line_sep>#from twisted.trial import unittest <import_stmt>unittest<line_sep>this_dir=os.path.dirname(os.path.abspath(__file__))<line_sep>sys.path.append(os.path.dirname(this_dir))<import_from_stmt>paxos durable<class_stmt>DObj(object)<block_start><def_stmt>__init__ self<block_start>self.state='initial'<block_end><block_end><class_stmt>DurableReadTester(unittest.TestCase)<block_start><def_stmt>setUp self<block_start>tmpfs_dir='/dev/shm'<if>os.path.exists('/dev/shm')<else><none><line_sep>self.tdir=tempfile.mkdtemp(dir=tmpfs_dir)<line_sep>self.fds=list()<block_end><def_stmt>tearDown self<block_start>shutil.rmtree(self.tdir)<for_stmt>fd self.fds<block_start>os.close(fd)<block_end><block_end><def_stmt>newfd self data=<none><block_start>bin_flag=0<if><not>hasattr(os 'O_BINARY')<else>os.O_BINARY<line_sep>fd=os.open(os.path.join(self.tdir str(len(self.fds))) os.O_CREAT|os.O_RDWR|bin_flag)<line_sep>self.fds.append(fd)<if_stmt>data<is><not><none><block_start>os.write(fd data)<block_end><return>fd<block_end><def_stmt>test_read_zero_length self<block_start>self.assertRaises(durable.FileTruncated durable.read self.newfd())<block_end><def_stmt>test_read_header_too_small self<block_start>self.assertRaises(durable.FileTruncated durable.read self.newfd('\0'<times>31))<block_end><def_stmt>test_read_no_pickle_data self<block_start>data='\0'<times>24+struct.pack('>Q' 5)<line_sep>self.assertRaises(durable.FileTruncated durable.read self.newfd(data))<block_end><def_stmt>test_read_bad_hash_mismatch self<block_start>data='\0'<times>24+struct.pack('>Q' 5)+'x'<times>5<line_sep>self.assertRaises(durable.HashMismatch durable.read self.newfd(data))<block_end><def_stmt>test_read_ok self<block_start>pdata='x'<times>5<line_sep>p=pickle.dumps(pdata pickle.HIGHEST_PROTOCOL)<line_sep>data='\0'<times>8+struct.pack('>Q' len(p))+p<line_sep>data=hashlib.md5(data).digest()+data<line_sep>self.assertEqual(durable.read(self.newfd(data)) (0 pdata))<block_end><block_end><class_stmt>DurableObjectHandlerTester(unittest.TestCase)<block_start><def_stmt>setUp self<block_start>tmpfs_dir='/dev/shm'<if>os.path.exists('/dev/shm')<else><none><line_sep>self.o=DObj()<line_sep>self.tdir=tempfile.mkdtemp(dir=tmpfs_dir)<line_sep>self.doh=durable.DurableObjectHandler(self.tdir 'id1')<line_sep>self.dohs=[self.doh ]<block_end><def_stmt>tearDown self<block_start><for_stmt>doh self.dohs<block_start>doh.close()<block_end>shutil.rmtree(self.tdir)<block_end><def_stmt>newdoh self obj_id=<none><block_start><if_stmt>obj_id<is><none><block_start>obj_id='id'+str(len(self.dohs))<block_end>doh=durable.DurableObjectHandler(self.tdir obj_id)<line_sep>self.dohs.append(doh)<line_sep><return>doh<block_end><def_stmt>test_bad_directory self<block_start>self.assertRaises(Exception durable.DurableObjectHandler '/@#$!$^FOOBARBAZ' 'blah')<block_end><def_stmt>test_no_save self<block_start>self.doh.close()<line_sep>d=self.newdoh('id1')<line_sep>self.assertEquals(d.recovered <none>)<line_sep>self.assertEquals(d.serial 1)<block_end><def_stmt>test_one_save self<block_start>self.doh.save(self.o)<line_sep>self.doh.close()<line_sep>d=self.newdoh('id1')<line_sep>self.assertTrue(os.stat(self.doh.fn_a).st_size<g>0)<line_sep>self.assertTrue(os.stat(self.doh.fn_b).st_size<eq>0)<line_sep>self.assertTrue(isinstance(d.recovered DObj))<line_sep>self.assertEquals(d.recovered.state 'initial')<block_end><def_stmt>test_two_save self<block_start>self.doh.save(self.o)<line_sep>self.o.state='second'<line_sep>self.doh.save(self.o)<line_sep>self.doh.close()<line_sep>d=self.newdoh('id1')<line_sep>self.assertTrue(os.stat(self.doh.fn_a).st_size<g>0)<line_sep>self.assertTrue(os.stat(self.doh.fn_b).st_size<g>0)<line_sep>self.assertTrue(isinstance(d.recovered DObj))<line_sep>self.assertEquals(d.recovered.state 'second')<block_end><def_stmt>test_three_save self<block_start>self.doh.save(self.o)<line_sep>self.o.state='second'<line_sep>self.doh.save(self.o)<line_sep>self.o.state='third'<line_sep>self.doh.save(self.o)<line_sep>self.doh.close()<line_sep>d=self.newdoh('id1')<line_sep>self.assertTrue(isinstance(d.recovered DObj))<line_sep>self.assertEquals(d.recovered.state 'third')<block_end><def_stmt>test_new_object_corrupted self<block_start>self.test_two_save()<with_stmt>open(self.doh.fn_b 'wb')<as>f<block_start>f.write('\0')<line_sep>f.flush()<block_end>d=self.newdoh('id1')<line_sep>self.assertTrue(isinstance(d.recovered DObj))<line_sep>self.assertEquals(d.recovered.state 'initial')<block_end><def_stmt>test_old_object_corrupted self<block_start>self.test_two_save()<with_stmt>open(self.doh.fn_a 'wb')<as>f<block_start>f.write('\0')<line_sep>f.flush()<block_end>d=self.newdoh('id1')<line_sep>self.assertTrue(isinstance(d.recovered DObj))<line_sep>self.assertEquals(d.recovered.state 'second')<block_end><def_stmt>test_unrecoverable_corruption self<block_start>self.test_two_save()<with_stmt>open(self.doh.fn_a 'wb')<as>f<block_start>f.write('\0')<line_sep>f.flush()<block_end><with_stmt>open(self.doh.fn_b 'wb')<as>f<block_start>f.write('\0')<line_sep>f.flush()<block_end><def_stmt>diehorribly <block_start>self.newdoh('id1')<block_end>self.assertRaises(durable.UnrecoverableFailure diehorribly)<block_end><block_end>