content
stringlengths 0
1.55M
|
---|
"""Operators associated with SeqMotif searching using RCSB Search API."""<import_from_stmt>dataclasses dataclass<import_from_stmt>enum Enum<import_from_stmt>typing Any Dict<class_stmt>SequenceType(Enum)<block_start>"""Type of sequence being searched for motifs."""<line_sep>DNA="pdb_dna_sequence"<line_sep>RNA="pdb_rna_sequence"<line_sep>PROTEIN="pdb_protein_sequence"<block_end><class_stmt>PatternType(Enum)<block_start>"""Type of pattern being used for SeqMotif search."""<line_sep>SIMPLE="simple"<line_sep>PROSITE="prosite"<line_sep>REGEX="regex"<block_end>@dataclass<class_stmt>SeqMotifOperator# Pattern to search with
<block_start>pattern:str<line_sep>sequence_type:SequenceType<line_sep>pattern_type:PatternType<def_stmt>_to_dict self<arrow>Dict[str Any]<block_start><return>{"value":self.pattern "pattern_type":self.pattern_type.value "target":self.sequence_type.value}<block_end><block_end># DO NOT APPROVE: DO NOT APPROVE THIS CL UNTIL ADDED TO VALIDATION
|
#
# Copyright 2019 The FATE 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.
#
<import_from_stmt>.components ComponentMeta<line_sep>secure_add_example_cpn_meta=ComponentMeta("SecureAddExample")<line_sep>@secure_add_example_cpn_meta.bind_param<def_stmt>secure_add_example_param <block_start><import_from_stmt>federatedml.param.secure_add_example_param SecureAddExampleParam<line_sep><return>SecureAddExampleParam<block_end>@secure_add_example_cpn_meta.bind_runner.on_guest<def_stmt>secure_add_example_guest_runner <block_start><import_from_stmt>federatedml.toy_example.secure_add_guest SecureAddGuest<line_sep><return>SecureAddGuest<block_end>@secure_add_example_cpn_meta.bind_runner.on_host<def_stmt>secure_add_example_host_runner <block_start><import_from_stmt>federatedml.toy_example.secure_add_host SecureAddHost<line_sep><return>SecureAddHost<block_end> |
<def_stmt>extractXiakeluojiao侠客落脚 item<block_start>"""
Xiakeluojiao 侠客落脚
"""<line_sep>badwords=['korean drama' 'badword' ]<if_stmt>any([bad<in>item['tags']<for>bad badwords])<block_start><return><none><block_end>vol,chp,frag,postfix=extractVolChapterFragmentPostfix(item['title'])<if_stmt><not>(chp<or>vol<or>frag)<or>'preview'<in>item['title'].lower()<block_start><return><none><block_end>tagmap=[('Pr<NAME>iyang' 'The <NAME>' 'translated') ]<for_stmt>tagname,name,tl_type tagmap<block_start><if_stmt>tagname<in>item['tags']<block_start><return>buildReleaseMessageWithType(item name vol chp frag=frag postfix=postfix tl_type=tl_type)<block_end><block_end><if_stmt>item['title'].startswith("Chapter ")<and>item['tags']<eq>[]<block_start><return>buildReleaseMessageWithType(item 'Zhu Xian' vol chp frag=frag postfix=postfix)<block_end><return><false><block_end> |
<import_from_stmt>collections OrderedDict<import_stmt>torch<import_stmt>torch.nn<as>nn<line_sep>__all__=['googlenet']<class_stmt>Inception_v1_GoogLeNet(nn.Module)<block_start>input_side=227<line_sep>rescale=255.0<line_sep>rgb_mean=[122.7717 115.9465 102.9801]<line_sep>rgb_std=[1 1 1]<def_stmt>__init__ self num_classes=1000<block_start>super(Inception_v1_GoogLeNet self).__init__()<line_sep>self.num_classes=num_classes<line_sep>self.features=nn.Sequential(OrderedDict([('conv1' nn.Sequential(OrderedDict([('7x7_s2' nn.Conv2d(3 64 (7 7) (2 2) (3 3) bias=<false>)) ('7x7_s2_bn' nn.BatchNorm2d(64 affine=<true>)) ('relu1' nn.ReLU(<true>)) ('pool1' nn.MaxPool2d((3 3) (2 2) padding=(1 1)))]))) ('conv2' nn.Sequential(OrderedDict([('3x3_reduce' nn.Conv2d(64 64 (1 1) (1 1) (0 0) bias=<false>)) ('3x3_reduce_bn' nn.BatchNorm2d(64 affine=<true>)) ('relu1' nn.ReLU(<true>)) ('3x3' nn.Conv2d(64 192 (3 3) (1 1) (1 1) bias=<false>)) ('3x3_bn' nn.BatchNorm2d(192 affine=<true>)) ('relu2' nn.ReLU(<true>)) ('pool2' nn.MaxPool2d((3 3) (2 2) padding=(1 1)))]))) ('inception_3a' InceptionModule(192 64 96 128 16 32 32)) ('inception_3b' InceptionModule(256 128 128 192 32 96 64)) ('pool3' nn.MaxPool2d((3 3) (2 2) padding=(1 1))) ('inception_4a' InceptionModule(480 192 96 208 16 48 64)) ('inception_4b' InceptionModule(512 160 112 224 24 64 64)) ('inception_4c' InceptionModule(512 128 128 256 24 64 64)) ('inception_4d' InceptionModule(512 112 144 288 32 64 64)) ('inception_4e' InceptionModule(528 256 160 320 32 128 128)) ('pool4' nn.MaxPool2d((3 3) (2 2) padding=(1 1))) ('inception_5a' InceptionModule(832 256 160 320 32 128 128)) ('inception_5b' InceptionModule(832 384 192 384 48 128 128)) ('pool5' nn.AvgPool2d((7 7) (1 1))) ('drop5' nn.Dropout(0.2))]))<line_sep>self.classifier=nn.Linear(1024 self.num_classes)<line_sep>self.regime=[{'epoch':0 'optimizer':'SGD' 'lr':1e-1 'weight_decay':1e-4 'momentum':0.9} {'epoch':30 'lr':1e-2} {'epoch':60 'lr':1e-3 'weight_decay':0} {'epoch':90 'lr':1e-3 'optimizer':'Adam'}]<block_end><def_stmt>forward self x<block_start>x=self.features(x)<line_sep>x=x.view(x.size(0) -1)<line_sep>x=self.classifier(x)<line_sep><return>x<block_end><block_end><class_stmt>InceptionModule(nn.Module)<block_start><def_stmt>__init__ self inplane outplane_a1x1 outplane_b3x3_reduce outplane_b3x3 outplane_c5x5_reduce outplane_c5x5 outplane_pool_proj<block_start>super(InceptionModule self).__init__()<line_sep>a=nn.Sequential(OrderedDict([('1x1' nn.Conv2d(inplane outplane_a1x1 (1 1) (1 1) (0 0) bias=<false>)) ('1x1_bn' nn.BatchNorm2d(outplane_a1x1 affine=<true>)) ('1x1_relu' nn.ReLU(<true>))]))<line_sep>b=nn.Sequential(OrderedDict([('3x3_reduce' nn.Conv2d(inplane outplane_b3x3_reduce (1 1) (1 1) (0 0) bias=<false>)) ('3x3_reduce_bn' nn.BatchNorm2d(outplane_b3x3_reduce affine=<true>)) ('3x3_relu1' nn.ReLU(<true>)) ('3x3' nn.Conv2d(outplane_b3x3_reduce outplane_b3x3 (3 3) (1 1) (1 1) bias=<false>)) ('3x3_bn' nn.BatchNorm2d(outplane_b3x3 affine=<true>)) ('3x3_relu2' nn.ReLU(<true>))]))<line_sep>c=nn.Sequential(OrderedDict([('5x5_reduce' nn.Conv2d(inplane outplane_c5x5_reduce (1 1) (1 1) (0 0) bias=<false>)) ('5x5_reduce_bn' nn.BatchNorm2d(outplane_c5x5_reduce affine=<true>)) ('5x5_relu1' nn.ReLU(<true>)) ('5x5' nn.Conv2d(outplane_c5x5_reduce outplane_c5x5 (5 5) (1 1) (2 2) bias=<false>)) ('5x5_bn' nn.BatchNorm2d(outplane_c5x5 affine=<true>)) ('5x5_relu2' nn.ReLU(<true>))]))<line_sep>d=nn.Sequential(OrderedDict([('pool_pool' nn.MaxPool2d((3 3) (1 1) (1 1))) ('pool_proj' nn.Conv2d(inplane outplane_pool_proj (1 1) (1 1) (0 0))) ('pool_proj_bn' nn.BatchNorm2d(outplane_pool_proj affine=<true>)) ('pool_relu' nn.ReLU(<true>))]))<for_stmt>container [a b c d]<block_start><for_stmt>name,module container.named_children()<block_start>self.add_module(name module)<block_end><block_end>self.branches=[a b c d]<block_end><def_stmt>forward self input<block_start><return>torch.cat([branch(input)<for>branch self.branches] 1)<block_end><block_end><def_stmt>googlenet **kwargs<block_start>num_classes=getattr(kwargs 'num_classes' 1000)<line_sep><return>Inception_v1_GoogLeNet(num_classes)<block_end> |
"""Support for tracking MQTT enabled devices."""<import_from_stmt>.schema_discovery async_setup_entry_from_discovery<import_from_stmt>.schema_yaml PLATFORM_SCHEMA_YAML async_setup_scanner_from_yaml<line_sep>PLATFORM_SCHEMA=PLATFORM_SCHEMA_YAML<line_sep>async_setup_scanner=async_setup_scanner_from_yaml<line_sep>async_setup_entry=async_setup_entry_from_discovery<line_sep> |
<import_from_stmt>abc ABCMeta abstractmethod<class_stmt>Format<block_start>"""Format encapsulates a format for presenting minimum versions and related information during
processing."""<line_sep># Can't use `class Format(metaclass=ABCMeta)` in py2.
__metaclass__=ABCMeta<def_stmt>__init__ self name<block_start>self.__name=name<line_sep>self.__config=<none><block_end><def_stmt>name self<block_start><return>self.__name<block_end><def_stmt>config self<block_start><return>self.__config<block_end><def_stmt>set_config self config<block_start>self.__config=config<block_end>@staticmethod<def_stmt>require_config funcobj<block_start>"""Decorator that checks config is not None."""<def_stmt>_require_config self *args **kwargs<block_start><assert_stmt>(self.config()<is><not><none>)<line_sep><return>funcobj(self *args **kwargs)<block_end><return>_require_config<block_end>@abstractmethod<def_stmt>skip_output_line self<block_start>"""Whether or not to skip outputting a line."""<block_end>@abstractmethod<def_stmt>format_output_line self msg path=<none> line=<none> col=<none> versions=<none><block_start>"""Yield formatted output line given file name, line, column, text, minimum versions."""<block_end>@abstractmethod<def_stmt>output_result self proc_res<block_start>"""Output processed result."""<block_end>@abstractmethod<def_stmt>sort_output_lines self lines<block_start>"""Sort and return output lines."""<block_end><block_end> |
"""
ViP Architecture in PyTorch
Copyright 2021 <NAME>
"""<import_stmt>math<import_stmt>torch.nn.init<as>init<import_from_stmt>timm.models.registry register_model<import_from_stmt>timm.models.layers DropPath<import_from_stmt>.vip_layers *<class_stmt>PatchEmbed(nn.Module)<block_start><def_stmt>__init__ self stride has_mask=<false> in_ch=0 out_ch=0<block_start>super(PatchEmbed self).__init__()<line_sep>self.to_token=nn.Conv2d(in_ch in_ch kernel_size=3 padding=1 stride=stride groups=in_ch)<line_sep>self.proj=nn.Linear(in_ch out_ch bias=<false>)<line_sep>self.has_mask=has_mask<block_end><def_stmt>process_mask self x mask H W<block_start><if_stmt>mask<is><none><and>self.has_mask<block_start>mask=x.new_zeros((1 1 H W))<block_end><if_stmt>mask<is><not><none><block_start>H_mask,W_mask=mask.shape[-2:]<if_stmt>H_mask<ne>H<or>W_mask<ne>W<block_start>mask=F.interpolate(mask (H W) mode='nearest')<block_end><block_end><return>mask<block_end><def_stmt>forward self x mask<block_start>"""
Args:
x: [B, C, H, W]
mask: [B, 1, H, W] if exists, else None
Returns:
out: [B, out_H * out_W, out_C]
H, W: output height & width
mask: [B, 1, out_H, out_W] if exists, else None
"""<line_sep>out=self.to_token(x)<line_sep>B,C,H,W=out.shape<line_sep>mask=self.process_mask(out mask H W)<line_sep>out=rearrange(out "b c h w -> b (h w) c").contiguous()<line_sep>out=self.proj(out)<line_sep><return>out H W mask<block_end><block_end><class_stmt>Encoder(nn.Module)<block_start><def_stmt>__init__ self dim num_parts=64 num_enc_heads=1 drop_path=0.1 act=nn.GELU has_ffn=<true><block_start>super(Encoder self).__init__()<line_sep>self.num_heads=num_enc_heads<line_sep>self.enc_attn=AnyAttention(dim num_enc_heads)<line_sep>self.drop_path=DropPath(drop_prob=drop_path)<if>drop_path<else>nn.Identity()<line_sep>self.reason=SimpleReasoning(num_parts dim)<line_sep>self.enc_ffn=Mlp(dim hidden_features=dim act_layer=act)<if>has_ffn<else><none><block_end><def_stmt>forward self feats parts=<none> qpos=<none> kpos=<none> mask=<none><block_start>"""
Args:
feats: [B, patch_num * patch_size, C]
parts: [B, N, C]
qpos: [B, N, 1, C]
kpos: [B, patch_num * patch_size, C]
mask: [B, 1, patch_num, patch_size] if exists, else None
Returns:
parts: [B, N, C]
"""<line_sep>attn_out=self.enc_attn(q=parts k=feats v=feats qpos=qpos kpos=kpos mask=mask)<line_sep>parts=parts+self.drop_path(attn_out)<line_sep>parts=self.reason(parts)<if_stmt>self.enc_ffn<is><not><none><block_start>parts=parts+self.drop_path(self.enc_ffn(parts))<block_end><return>parts<block_end><block_end><class_stmt>Decoder(nn.Module)<block_start><def_stmt>__init__ self dim num_heads=8 patch_size=7 ffn_exp=3 act=nn.GELU drop_path=0.1<block_start>super().__init__()<assert_stmt>dim%num_heads<eq>0 f"dim {dim} should be divided by num_heads {num_heads}."<line_sep>self.dim=dim<line_sep>self.num_heads=num_heads<line_sep>self.attn1=AnyAttention(dim num_heads)<line_sep>self.attn2=AnyAttention(dim num_heads)<line_sep>self.rel_pos=FullRelPos(patch_size patch_size dim<floordiv>num_heads)<line_sep>self.ffn1=Mlp(dim hidden_features=dim<times>ffn_exp act_layer=act norm_layer=Norm)<line_sep>self.ffn2=Mlp(dim hidden_features=dim<times>ffn_exp act_layer=act norm_layer=Norm)<line_sep>self.drop_path=DropPath(drop_path)<block_end><def_stmt>forward self x parts=<none> part_kpos=<none> mask=<none> P=0<block_start>"""
Args:
x: [B, patch_num * patch_size, C]
parts: [B, N, C]
part_kpos: [B, N, 1, C]
mask: [B, 1, patch_num, patch_size] if exists, else None
P: patch_num
Returns:
feat: [B, patch_num, patch_size, C]
"""<line_sep>dec_mask=<none><if>mask<is><none><else>rearrange(mask.squeeze(1) "b h w -> b (h w) 1 1")<line_sep>out=self.attn1(q=x k=parts v=parts kpos=part_kpos mask=dec_mask)<line_sep>out=x+self.drop_path(out)<line_sep>out=out+self.drop_path(self.ffn1(out))<line_sep>out=rearrange(out "b (p k) c -> (b p) k c" p=P)<line_sep>local_out=self.attn2(q=out k=out v=out mask=mask rel_pos=self.rel_pos)<line_sep>out=out+self.drop_path(local_out)<line_sep>out=out+self.drop_path(self.ffn2(out))<line_sep><return>rearrange(out "(b p) k c -> b p k c" p=P)<block_end><block_end><class_stmt>ViPBlock(nn.Module)<block_start><def_stmt>__init__ self dim ffn_exp=4 drop_path=0.1 patch_size=7 num_heads=1 num_enc_heads=1 num_parts=0<block_start>super(ViPBlock self).__init__()<line_sep>self.encoder=Encoder(dim num_parts=num_parts num_enc_heads=num_enc_heads drop_path=drop_path)<line_sep>self.decoder=Decoder(dim num_heads=num_heads patch_size=patch_size ffn_exp=ffn_exp drop_path=drop_path)<block_end><def_stmt>forward self x parts=<none> part_qpos=<none> part_kpos=<none> mask=<none><block_start>"""
Args:
x: [B, patch_num, patch_size, C]
parts: [B, N, C]
part_qpos: [B, N, 1, C]
part_kpos: [B, N, 1, C]
mask: [B, 1, patch_num, patch_size] if exists, else None
Returns:
feats: [B, patch_num, patch_size, C]
parts: [B, N, C]
part_qpos: [B, N, 1, C]
mask: [B, 1, patch_num, patch_size] if exists, else None
"""<line_sep>P=x.shape[1]<line_sep>x=rearrange(x "b p k c -> b (p k) c")<line_sep>parts=self.encoder(x parts=parts qpos=part_qpos mask=mask)<line_sep>feats=self.decoder(x parts=parts part_kpos=part_kpos mask=mask P=P)<line_sep><return>feats parts part_qpos mask<block_end><block_end><class_stmt>Stage(nn.Module)<block_start><def_stmt>__init__ self in_ch out_ch num_blocks patch_size=7 num_heads=1 num_enc_heads=1 stride=1 num_parts=0 last_np=0 last_enc=<false> drop_path=0.1 has_mask=<none> ffn_exp=3<block_start>super(Stage self).__init__()<if_stmt>isinstance(drop_path float)<block_start>drop_path=[drop_path<for>_ range(num_blocks)]<block_end>self.patch_size=patch_size<line_sep>self.rpn_qpos=nn.Parameter(torch.Tensor(1 num_parts 1 out_ch<floordiv>num_enc_heads))<line_sep>self.rpn_kpos=nn.Parameter(torch.Tensor(1 num_parts 1 out_ch<floordiv>num_heads))<line_sep>self.proj=PatchEmbed(stride has_mask=has_mask in_ch=in_ch out_ch=out_ch)<line_sep>self.proj_token=nn.Sequential(nn.Conv1d(last_np num_parts 1 bias=<false>)<if>last_np<ne>num_parts<else>nn.Identity() nn.Linear(in_ch out_ch) Norm(out_ch))<line_sep>self.proj_norm=Norm(out_ch)<line_sep>blocks=[ViPBlock(out_ch patch_size=patch_size num_heads=num_heads num_enc_heads=num_enc_heads num_parts=num_parts ffn_exp=ffn_exp drop_path=drop_path[i])<for>i range(num_blocks)]<line_sep>self.blocks=nn.ModuleList(blocks)<line_sep>self.last_enc=Encoder(dim=out_ch num_enc_heads=num_enc_heads num_parts=num_parts drop_path=drop_path[-1] has_ffn=<false>)<if>last_enc<else><none><line_sep>self._init_weights()<block_end><def_stmt>_init_weights self<block_start>init.kaiming_uniform_(self.rpn_qpos a=math.sqrt(5))<line_sep>trunc_normal_(self.rpn_qpos std=.02)<line_sep>init.kaiming_uniform_(self.rpn_kpos a=math.sqrt(5))<line_sep>trunc_normal_(self.rpn_kpos std=.02)<block_end><def_stmt>to_patch self x patch_size H W mask=<none><block_start>x=rearrange(x "b (h w) c -> b h w c" h=H)<line_sep>pad_l=pad_t=0<line_sep>pad_r=int(math.ceil(W/patch_size))<times>patch_size-W<line_sep>pad_b=int(math.ceil(H/patch_size))<times>patch_size-H<line_sep>x=F.pad(x (0 0 pad_l pad_r pad_t pad_b))<if_stmt>mask<is><not><none><block_start>mask=F.pad(mask (pad_l pad_r pad_t pad_b) value=1)<block_end>x=rearrange(x "b (sh kh) (sw kw) c -> b (sh sw) (kh kw) c" kh=patch_size kw=patch_size)<if_stmt>mask<is><not><none><block_start>mask=rearrange(mask "b c (sh kh) (sw kw) -> b c (kh kw) (sh sw)" kh=patch_size kw=patch_size)<block_end><return>x mask H+pad_b W+pad_r<block_end><def_stmt>forward self x parts=<none> mask=<none><block_start>"""
Args:
x: [B, C, H, W]
parts: [B, N, C]
mask: [B, 1, H, W] if exists, else None
Returns:
x: [B, out_C, out_H, out_W]
parts: [B, out_N, out_C]
mask: [B, 1, out_H, out_W] if exists else None
"""<line_sep>x,H,W,mask=self.proj(x mask=mask)<line_sep>x=self.proj_norm(x)<if_stmt>self.proj_token<is><not><none><block_start>parts=self.proj_token(parts)<block_end>rpn_qpos,rpn_kpos=self.rpn_qpos self.rpn_kpos<line_sep>rpn_qpos=rpn_qpos.expand(x.shape[0] -1 -1 -1)<line_sep>rpn_kpos=rpn_kpos.expand(x.shape[0] -1 -1 -1)<line_sep>ori_H,ori_W=H W<line_sep>x,mask,H,W=self.to_patch(x self.patch_size H W mask)<for_stmt>blk self.blocks# x: [B, K, P, C]
<block_start>x,parts,rpn_qpos,mask=blk(x parts=parts part_qpos=rpn_qpos part_kpos=rpn_kpos mask=mask)<block_end>dec_mask=<none><if>mask<is><none><else>rearrange(mask.squeeze(1) "b h w -> b 1 1 (h w)")<if_stmt>self.last_enc<is><not><none><block_start>x=rearrange(x "b p k c -> b (p k) c")<line_sep>rpn_out=self.last_enc(x parts=parts qpos=rpn_qpos mask=dec_mask)<line_sep><return>rpn_out parts mask<block_end><else_stmt><block_start>x=rearrange(x "b (sh sw) (kh kw) c -> b c (sh kh) (sw kw)" kh=self.patch_size sh=H<floordiv>self.patch_size)<line_sep>x=x[: : :ori_H :ori_W]<line_sep><return>x parts mask<block_end><block_end><block_end><class_stmt>ViP(nn.Module)<block_start><def_stmt>__init__ self in_chans=3 inplanes=64 num_layers=(3 4 6 3) num_chs=(256 512 1024 2048) num_strides=(1 2 2 2) num_classes=1000 num_heads=(1 1 1 1) num_parts=(1 1 1 1) patch_sizes=(1 1 1 1) drop_path=0.1 num_enc_heads=(1 1 1 1) act=nn.GELU ffn_exp=3 no_pos_wd=<false> has_last_encoder=<false> pretrained=<false> **ret_args<block_start>super(ViP self).__init__()<line_sep>self.depth=len(num_layers)<line_sep>self.no_pos_wd=no_pos_wd<line_sep>self.conv1=nn.Conv2d(in_chans inplanes kernel_size=7 padding=3 stride=2 bias=<false>)<line_sep>self.norm1=nn.BatchNorm2d(inplanes)<line_sep>self.act=act()<line_sep>self.pool1=nn.MaxPool2d(kernel_size=3 stride=2 padding=1)<line_sep>self.rpn_tokens=nn.Parameter(torch.Tensor(1 num_parts[0] inplanes))<line_sep>drop_path_ratios=torch.linspace(0 drop_path sum(num_layers))<line_sep>last_chs=[inplanes *num_chs[:-1]]<line_sep>last_nps=[num_parts[0] *num_parts[:-1]]<for_stmt>i,n_l enumerate(num_layers)<block_start>stage_ratios=[drop_path_ratios[sum(num_layers[:i])+did]<for>did range(n_l)]<line_sep>setattr(self "layer_{}".format(i) Stage(last_chs[i] num_chs[i] n_l stride=num_strides[i] num_heads=num_heads[i] num_enc_heads=num_enc_heads[i] patch_size=patch_sizes[i] drop_path=stage_ratios ffn_exp=ffn_exp num_parts=num_parts[i] last_np=last_nps[i] last_enc=has_last_encoder<and>i<eq>len(num_layers)-1))<block_end><if_stmt>has_last_encoder<block_start>self.last_fc=nn.Linear(num_chs[-1] num_classes)<block_end><else_stmt><block_start>self.last_linear=nn.Conv2d(num_chs[-1] num_chs[-1] kernel_size=1 bias=<false>)<line_sep>self.last_norm=nn.BatchNorm2d(num_chs[-1])<line_sep>self.pool2=nn.AdaptiveAvgPool2d(1)<line_sep>self.last_fc=nn.Linear(num_chs[-1] num_classes)<block_end>self.has_last_encoder=has_last_encoder<line_sep>self._init_weights(pretrained=pretrained)<block_end>@torch.jit.ignore<def_stmt>no_weight_decay self<block_start>skip_pattern=['rel_pos']<if>self.no_pos_wd<else>[]<line_sep>no_wd_layers=set()<for_stmt>name,param self.named_parameters()<block_start><for_stmt>skip_name skip_pattern<block_start><if_stmt>skip_name<in>name<block_start>no_wd_layers.add(name)<block_end><block_end><block_end><return>no_wd_layers<block_end><def_stmt>_init_weights self pretrained=<none><block_start><if_stmt>isinstance(pretrained str)<block_start>state_dict=torch.load(pretrained map_location=torch.device("cpu"))<if_stmt>"state_dict"<in>state_dict.keys()<block_start>state_dict=state_dict["state_dict"]<block_end>self.load_state_dict(state_dict strict=<true>)<line_sep><return><block_end>init.kaiming_uniform_(self.rpn_tokens a=math.sqrt(5))<line_sep>trunc_normal_(self.rpn_tokens std=.02)<for_stmt>m self.modules()<block_start><if_stmt>isinstance(m nn.Conv2d)<block_start>n=m.kernel_size[0]<times>m.kernel_size[1]<times>m.out_channels<line_sep>m.weight.data.normal_(0 math.sqrt(2./n))<line_sep>trunc_normal_(m.weight std=.02)<if_stmt>m.bias<is><not><none><block_start>nn.init.constant_(m.bias 0)<block_end><block_end><elif_stmt>isinstance(m nn.Conv1d)<block_start>n=m.kernel_size[0]<times>m.out_channels<line_sep>m.weight.data.normal_(0 math.sqrt(2./n))<line_sep>trunc_normal_(m.weight std=.02)<if_stmt>m.bias<is><not><none><block_start>nn.init.constant_(m.bias 0)<block_end><block_end><elif_stmt>isinstance(m (nn.BatchNorm2d nn.BatchNorm1d))<block_start><if_stmt><not>torch.sum(m.weight.data<eq>0).item()<eq>m.num_features# zero gamma
<block_start>m.weight.data.fill_(1)<block_end>m.bias.data.zero_()<block_end><elif_stmt>isinstance(m nn.Linear)<block_start>trunc_normal_(m.weight std=.02)<if_stmt>m.bias<is><not><none><block_start>nn.init.constant_(m.bias 0)<block_end><block_end><elif_stmt>isinstance(m nn.LayerNorm)<block_start>nn.init.constant_(m.bias 0)<line_sep>nn.init.constant_(m.weight 1.0)<block_end><block_end><block_end><def_stmt>forward self x<block_start>out=self.conv1(x)<line_sep>out=self.norm1(out)<line_sep>out=self.act(out)<line_sep>out=self.pool1(out)<line_sep>B,_,H,W=out.shape<line_sep>rpn_tokens,mask=self.rpn_tokens.expand(x.shape[0] -1 -1) <none><for_stmt>i range(self.depth)<block_start>layer=getattr(self "layer_{}".format(i))<line_sep>out,rpn_tokens,mask=layer(out rpn_tokens mask=mask)<block_end><if_stmt>self.has_last_encoder<block_start>out=self.act(out)<line_sep>out=out.mean(1)<block_end><else_stmt><block_start>out=self.last_linear(out)<line_sep>out=self.last_norm(out)<line_sep>out=self.act(out)<line_sep>out=self.pool2(out)<line_sep>out=out.squeeze()<block_end>out=self.last_fc(out).squeeze()<line_sep><return>out.view(out.size(0) -1)<block_end><block_end>@register_model<def_stmt>vip_mobile pretrained=<false> **cfg<block_start>model_cfg=dict(inplanes=64 num_chs=(48 96 192 384) patch_sizes=[8 7 7 7] num_heads=[1 2 4 8] num_enc_heads=[1 2 4 8] num_parts=[16 16 16 32] num_layers=[1 1 1 1] ffn_exp=3 has_last_encoder=<true> drop_path=0. **cfg)<line_sep><return>ViP(pretrained=pretrained **model_cfg)<block_end>@register_model<def_stmt>vip_tiny pretrained=<false> **cfg<block_start>model_cfg=dict(inplanes=64 num_chs=(64 128 256 512) patch_sizes=[8 7 7 7] num_heads=[1 2 4 8] num_enc_heads=[1 2 4 8] num_parts=[32 32 32 32] num_layers=[1 1 2 1] ffn_exp=3 has_last_encoder=<true> drop_path=0.1 **cfg)<line_sep><return>ViP(pretrained=pretrained **model_cfg)<block_end>@register_model<def_stmt>vip_small pretrained=<false> **cfg<block_start>model_cfg=dict(inplanes=64 num_chs=(96 192 384 768) patch_sizes=[8 7 7 7] num_heads=[3 6 12 24] num_enc_heads=[1 3 6 12] num_parts=[64 64 64 64] num_layers=[1 1 3 1] ffn_exp=3 has_last_encoder=<true> drop_path=0.1 **cfg)<line_sep><return>ViP(pretrained=pretrained **model_cfg)<block_end>@register_model<def_stmt>vip_medium pretrained=<false> **cfg<block_start>model_cfg=dict(inplanes=64 num_chs=(96 192 384 768) patch_sizes=[8 7 7 7] num_heads=[3 6 12 24] num_enc_heads=[1 3 6 12] num_parts=[64 64 64 128] num_layers=[1 1 8 1] ffn_exp=3 has_last_encoder=<false> drop_path=0.2 **cfg)<line_sep><return>ViP(pretrained=pretrained **model_cfg)<block_end>@register_model<def_stmt>vip_base pretrained=<false> **cfg<block_start>model_cfg=dict(inplanes=64 num_chs=(128 256 512 1024) patch_sizes=[8 7 7 7] num_heads=[4 8 16 32] num_enc_heads=[1 4 8 16] num_parts=[64 64 128 128] num_layers=[1 1 8 1] ffn_exp=3 has_last_encoder=<false> drop_path=0.3 **cfg)<line_sep><return>ViP(pretrained=pretrained **model_cfg)<block_end> |
# Leo colorizer control file for factor mode.
# This file is in the public domain.
# Properties for factor mode.
properties={"commentEnd":")" "commentStart":"(" "doubleBracketIndent":"true" "indentCloseBrackets":"]" "indentNextLines":"^(\\*<<|:).*" "indentOpenBrackets":"[" "lineComment":"!" "lineUpClosingBracket":"true" "noWordSep":"+-*=><;.?/'" }<line_sep># Attributes dict for factor_main ruleset.
factor_main_attributes_dict={"default":"null" "digit_re":"-?\\d+([./]\\d+)?" "escape":"\\" "highlight_digits":"true" "ignore_case":"false" "no_word_sep":"+-*=><;.?/'" }<line_sep># Attributes dict for factor_stack_effect ruleset.
factor_stack_effect_attributes_dict={"default":"COMMENT4" "digit_re":"-?\\d+([./]\\d+)?" "escape":"\\" "highlight_digits":"true" "ignore_case":"false" "no_word_sep":"+-*=><;.?/'" }<line_sep># Dictionary of attributes dictionaries for factor mode.
attributesDictDict={"factor_main":factor_main_attributes_dict "factor_stack_effect":factor_stack_effect_attributes_dict }<line_sep># Keywords dict for factor_main ruleset.
factor_main_keywords_dict={"#{":"operator" "--":"label" ";":"markup" "<":"label" ">":"label" "[":"operator" "]":"operator" "f":"literal4" "r":"keyword1" "t":"literal3" "{":"operator" "|":"operator" "}":"operator" "~":"label" }<line_sep># Keywords dict for factor_stack_effect ruleset.
factor_stack_effect_keywords_dict={}<line_sep># Dictionary of keywords dictionaries for factor mode.
keywordsDictDict={"factor_main":factor_main_keywords_dict "factor_stack_effect":factor_stack_effect_keywords_dict }<line_sep># Rules for factor_main ruleset.
<def_stmt>factor_rule0 colorer s i<block_start><return>colorer.match_eol_span(s i kind="comment2" seq="#!" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false>)<block_end><def_stmt>factor_rule1 colorer s i<block_start><return>colorer.match_eol_span(s i kind="comment1" seq="!" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false>)<block_end><def_stmt>factor_rule2 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="markup" regexp=":\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule3 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="markup" regexp="IN:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule4 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="markup" regexp="USE:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule5 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="markup" regexp="DEFER:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule6 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="markup" regexp="POSTPONE:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule7 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="literal2" regexp="CHAR:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule8 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="literal2" regexp="BIN:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule9 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="literal2" regexp="OCT:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule10 colorer s i<block_start><return>colorer.match_seq_regexp(s i kind="literal2" regexp="HEX:\\s+(\\S+)" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end><def_stmt>factor_rule11 colorer s i<block_start><return>colorer.match_span(s i kind="comment3" begin="(" end=")" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="factor::stack_effect" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>factor_rule12 colorer s i<block_start><return>colorer.match_span(s i kind="literal1" begin="\"" end="\"" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false> no_escape=<false> no_line_break=<true> no_word_break=<false>)<block_end><def_stmt>factor_rule13 colorer s i<block_start><return>colorer.match_keywords(s i)<block_end># Rules dict for factor_main ruleset.
rulesDict1={"!":[factor_rule1 ] "\"":[factor_rule12 ] "#":[factor_rule0 factor_rule13 ] "(":[factor_rule11 ] "-":[factor_rule13 ] "0":[factor_rule13 ] "1":[factor_rule13 ] "2":[factor_rule13 ] "3":[factor_rule13 ] "4":[factor_rule13 ] "5":[factor_rule13 ] "6":[factor_rule13 ] "7":[factor_rule13 ] "8":[factor_rule13 ] "9":[factor_rule13 ] ":":[factor_rule2 ] ";":[factor_rule13 ] "<":[factor_rule13 ] ">":[factor_rule13 ] "@":[factor_rule13 ] "A":[factor_rule13 ] "B":[factor_rule8 factor_rule13 ] "C":[factor_rule7 factor_rule13 ] "D":[factor_rule5 factor_rule13 ] "E":[factor_rule13 ] "F":[factor_rule13 ] "G":[factor_rule13 ] "H":[factor_rule10 factor_rule13 ] "I":[factor_rule3 factor_rule13 ] "J":[factor_rule13 ] "K":[factor_rule13 ] "L":[factor_rule13 ] "M":[factor_rule13 ] "N":[factor_rule13 ] "O":[factor_rule9 factor_rule13 ] "P":[factor_rule6 factor_rule13 ] "Q":[factor_rule13 ] "R":[factor_rule13 ] "S":[factor_rule13 ] "T":[factor_rule13 ] "U":[factor_rule4 factor_rule13 ] "V":[factor_rule13 ] "W":[factor_rule13 ] "X":[factor_rule13 ] "Y":[factor_rule13 ] "Z":[factor_rule13 ] "[":[factor_rule13 ] "]":[factor_rule13 ] "a":[factor_rule13 ] "b":[factor_rule13 ] "c":[factor_rule13 ] "d":[factor_rule13 ] "e":[factor_rule13 ] "f":[factor_rule13 ] "g":[factor_rule13 ] "h":[factor_rule13 ] "i":[factor_rule13 ] "j":[factor_rule13 ] "k":[factor_rule13 ] "l":[factor_rule13 ] "m":[factor_rule13 ] "n":[factor_rule13 ] "o":[factor_rule13 ] "p":[factor_rule13 ] "q":[factor_rule13 ] "r":[factor_rule13 ] "s":[factor_rule13 ] "t":[factor_rule13 ] "u":[factor_rule13 ] "v":[factor_rule13 ] "w":[factor_rule13 ] "x":[factor_rule13 ] "y":[factor_rule13 ] "z":[factor_rule13 ] "{":[factor_rule13 ] "|":[factor_rule13 ] "}":[factor_rule13 ] "~":[factor_rule13 ] }<line_sep># Rules for factor_stack_effect ruleset.
<def_stmt>factor_rule14 colorer s i<block_start><return>colorer.match_seq(s i kind="comment3" seq="--" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="")<block_end># Rules dict for factor_stack_effect ruleset.
rulesDict2={"-":[factor_rule14 ] }<line_sep># x.rulesDictDict for factor mode.
rulesDictDict={"factor_main":rulesDict1 "factor_stack_effect":rulesDict2 }<line_sep># Import dict for factor mode.
importDict={}<line_sep> |
<import_from_stmt>time sleep<import_stmt>pytest<import_from_stmt>pyvirtualdisplay Display<import_from_stmt>pyvirtualdisplay.abstractdisplay XStartError<import_from_stmt>pyvirtualdisplay.xephyr XephyrDisplay<import_from_stmt>pyvirtualdisplay.xvfb XvfbDisplay<import_from_stmt>pyvirtualdisplay.xvnc XvncDisplay<import_from_stmt>tutil has_xvnc rfbport<def_stmt>test_virt <block_start>vd=Display()<assert_stmt>vd.return_code<is><none><assert_stmt><not>vd.is_alive()<line_sep>vd.start()<assert_stmt>vd.return_code<is><none><assert_stmt>vd.is_alive()<line_sep>vd.stop()<assert_stmt>vd.return_code<eq>0<assert_stmt><not>vd.is_alive()<line_sep>vd=Display().start().stop()<assert_stmt>vd.return_code<eq>0<assert_stmt><not>vd.is_alive()<block_end><def_stmt>test_nest <block_start>vd=Display().start()<assert_stmt>vd.is_alive()<line_sep>nd=Display(visible=<true>).start().stop()<assert_stmt>nd.return_code<eq>0<line_sep>vd.stop()<assert_stmt><not>vd.is_alive()<block_end><def_stmt>test_disp <block_start>vd=Display().start()<assert_stmt>vd.is_alive()<line_sep># d = Display(visible=True).start().sleep(2).stop()
# .assertEquals(d.return_code, 0)
d=Display(visible=<false>).start().stop()<assert_stmt>d.return_code<eq>0<line_sep>vd.stop()<assert_stmt><not>vd.is_alive()<block_end><def_stmt>test_repr_xvfb <block_start>display=Display()<line_sep>print(repr(display))<line_sep>display=Display(visible=<false>)<line_sep>print(repr(display))<line_sep>display=Display(backend="xvfb")<line_sep>print(repr(display))<line_sep>display=XvfbDisplay()<line_sep>print(repr(display))<block_end><if_stmt>has_xvnc()<block_start><def_stmt>test_repr_xvnc <block_start>display=Display(backend="xvnc" rfbport=rfbport())<line_sep>print(repr(display))<line_sep>display=XvncDisplay()<line_sep>print(repr(display))<block_end><block_end><def_stmt>test_repr_xephyr <block_start>display=Display(visible=<true>)<line_sep>print(repr(display))<line_sep>display=Display(backend="xephyr")<line_sep>print(repr(display))<line_sep>display=XephyrDisplay()<line_sep>print(repr(display))<block_end><def_stmt>test_stop_nostart <block_start><with_stmt>pytest.raises(XStartError)<block_start>Display().stop()<block_end><block_end><def_stmt>test_double_start <block_start>vd=Display()<try_stmt><block_start>vd.start()<with_stmt>pytest.raises(XStartError)<block_start>vd.start()<block_end><block_end><finally_stmt><block_start>vd.stop()<block_end><block_end><def_stmt>test_double_stop <block_start>vd=Display().start().stop()<assert_stmt>vd.return_code<eq>0<assert_stmt><not>vd.is_alive()<line_sep>vd.stop()<assert_stmt>vd.return_code<eq>0<assert_stmt><not>vd.is_alive()<block_end><def_stmt>test_stop_terminated <block_start>vd=Display().start()<assert_stmt>vd.is_alive()<line_sep>vd._obj._subproc.terminate()<line_sep>sleep(0.2)<assert_stmt><not>vd.is_alive()<line_sep>vd.stop()<assert_stmt>vd.return_code<eq>0<assert_stmt><not>vd.is_alive()<block_end><def_stmt>test_no_backend <block_start><with_stmt>pytest.raises(ValueError)<block_start>Display(backend="unknown")<block_end><block_end><def_stmt>test_color_xvfb <block_start><with_stmt>pytest.raises(XStartError)<block_start>Display(color_depth=99).start().stop()<block_end>Display(color_depth=16).start().stop()<line_sep>Display(color_depth=24).start().stop()<line_sep>Display(color_depth=8).start().stop()<block_end><def_stmt>test_color_xephyr <block_start><with_stmt>Display()# requested screen depth not supported, setting to match hosts
<block_start>Display(backend="xephyr" color_depth=99).start().stop()<line_sep>Display(backend="xephyr" color_depth=16).start().stop()<line_sep>Display(backend="xephyr" color_depth=24).start().stop()<line_sep>Display(backend="xephyr" color_depth=8).start().stop()<block_end><block_end><if_stmt>has_xvnc()<block_start><def_stmt>test_color_xvnc <block_start><with_stmt>pytest.raises(XStartError)<block_start><with_stmt>Display(backend="xvnc" color_depth=99 rfbport=rfbport())<block_start><pass><block_end><block_end><with_stmt>Display(backend="xvnc" color_depth=16 rfbport=rfbport())<block_start><pass><block_end><with_stmt>Display(backend="xvnc" color_depth=24 rfbport=rfbport())<block_start><pass><block_end># tigervnc no longer works 8-bit pseudocolors, 18.04 is OK
# with Display(backend="xvnc", color_depth=8, rfbport=rfbport()):
# pass
<block_end><block_end><def_stmt>test_pid <block_start><with_stmt>Display()<as>d<block_start><assert_stmt>d.pid<g>0<block_end><with_stmt>XvfbDisplay()<as>d<block_start><assert_stmt>d.pid<g>0<block_end><block_end><def_stmt>test_bgcolor <block_start>Display(bgcolor="black").start().stop()<line_sep>Display(bgcolor="white").start().stop()<with_stmt>pytest.raises(KeyError)<block_start>Display(bgcolor="green").start().stop()<block_end><block_end><def_stmt>test_is_started # d = Display()
# assert not d._is_started
# d.start()
# assert d._is_started
# d.stop()
# assert d._is_started
# with Display() as d:
# assert d._is_started
# assert d._is_started
<block_start><with_stmt>XvfbDisplay()<as>d<block_start><assert_stmt>d._is_started<block_end><assert_stmt>d._is_started<with_stmt>Display()<block_start><with_stmt>XephyrDisplay()<as>d<block_start><assert_stmt>d._is_started<block_end><assert_stmt>d._is_started<line_sep># with XvncDisplay() as d:
# assert d._is_started
# assert d._is_started
<block_end><block_end><def_stmt>test_extra_args # Unrecognized option
<block_start>d=Display(extra_args=["willcrash"])<with_stmt>pytest.raises(XStartError)<block_start>d.start()<block_end><with_stmt>Display()# -c turns off key-click
<block_start><with_stmt>Display(visible=<true> extra_args=["-c"])<as>d<block_start><assert_stmt>d.is_alive()<block_end><assert_stmt><not>d.is_alive()<with_stmt>XephyrDisplay(extra_args=["-c"])<as>d<block_start><assert_stmt>d.is_alive()<block_end><assert_stmt><not>d.is_alive()<block_end><block_end><def_stmt>test_display <block_start>d=Display()<assert_stmt>d.display<is><none><line_sep>d.start()<assert_stmt>d.display<ge>0<line_sep>d=XvfbDisplay()<assert_stmt>d.display<is><none><line_sep>d.start()<assert_stmt>d.display<ge>0<block_end> |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-04 13:43
<import_from_future_stmt> unicode_literals<import_stmt>django.contrib.postgres.fields<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('probes' '0004_auto_20161103_1728') ]<line_sep>operations=[migrations.AddField(model_name='probesource' name='apps' field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255) blank=<true> default=[] editable=<false> size=<none>) preserve_default=<false> ) migrations.AddField(model_name='probesource' name='event_types' field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255) blank=<true> default=[] editable=<false> size=<none>) preserve_default=<false> ) migrations.AddField(model_name='probesource' name='model' field=models.CharField(blank=<true> editable=<false> max_length=255 null=<true>) ) migrations.AlterField(model_name='probesource' name='body' field=models.TextField(editable=<false>) ) migrations.AlterField(model_name='probesource' name='slug' field=models.SlugField(editable=<false> max_length=255 unique=<true>) ) ]<block_end> |
"""Extra functionality (not necessary for the EnKF or the particle filter)."""<import_stmt>numpy<as>np<import_stmt>dapper.mods.Lorenz63<as>core<import_stmt>dapper.tools.liveplotting<as>LP<import_from_stmt>dapper.mods.integration integrate_TLM<def_stmt>d2x_dtdx x<block_start>"""Tangent linear model (TLM). I.e. the Jacobian of dxdt(x)."""<line_sep>x,y,z=x<line_sep>sig,rho,beta=core.sig core.rho core.beta<line_sep>A=np.array([[-sig sig 0] [rho-z -1 -x] [y x -beta]])<line_sep><return>A<block_end><def_stmt>dstep_dx x t dt<block_start>"""Compute resolvent (propagator) of the TLM. I.e. the Jacobian of `step(x)`."""<line_sep><return>integrate_TLM(d2x_dtdx(x) dt method='approx')<block_end># Add some non-default liveplotters
params=dict(labels='xyz' Tplot=1)<def_stmt>LPs jj=<none> params=params<block_start><return>[(1 LP.correlations) (1 LP.sliding_marginals(jj zoomy=0.8 **params)) (1 LP.phase_particles(is_3d=<true> obs_inds=jj **params)) ]<block_end> |
# -*- coding: utf-8 -*-
<import_from_future_stmt> unicode_literals<import_from_stmt>django.urls reverse<import_from_stmt>django.utils.safestring mark_safe<import_from_stmt>django.utils.translation ugettext_lazy<as>_<import_from_stmt>six.moves reduce<import_from_stmt>six.moves.urllib.parse parse_qsl<def_stmt>anchor text href **kwargs<block_start>"""转化为a标签"""<line_sep>@mark_safe<def_stmt>wrapper modeladmin obj<block_start>kwargs.update(href=href text=text)<for_stmt>key,value kwargs.items()<block_start><if_stmt>callable(value)<block_start>kwargs[key]=value(modeladmin obj)<block_end><block_end><return>kwargs["text"]<and>'<a href="{href}">{text}</a>'.format(**kwargs)<block_end><return>wrapper<block_end><def_stmt>foreignkey field_name<block_start>"""
Converts a foreign key value into clickable links.
If field_name is 'parent', link text will be str(obj.parent)
Link will be admin url for the admin url for obj.parent.id:change
"""<line_sep>@mark_safe<def_stmt>_linkify obj<block_start>app_label=obj._meta.app_label<line_sep>linked_obj=getattr(obj field_name)<line_sep>model_name=linked_obj._meta.model_name<line_sep>view_name="admin:{app_label}_{model_name}_change".format(app_label=app_label model_name=model_name)<line_sep>link_url=reverse(view_name kwargs=dict(object_id=linked_obj.id wechat_app_id=obj.app_id))<line_sep><return>'<a href="{0}">{1}</a>'.format(link_url linked_obj)<block_end>_linkify.short_description=_(field_name)<line_sep>_linkify.admin_order_field=field_name<line_sep><return>_linkify<block_end><def_stmt>list_property field_name **kwargs<block_start><def_stmt>_from_property obj<block_start>rv=reduce(getattr field_name.split(".") obj)<line_sep><return>rv()<if>callable(rv)<else>rv<block_end><for_stmt>key,value kwargs.items()<block_start>setattr(_from_property key value)<block_end><return>_from_property<block_end><def_stmt>field_property field_name **kwargs<block_start><def_stmt>_from_property admin obj=<none><block_start><if_stmt><not>obj<block_start><return><none><block_end>rv=reduce(getattr field_name.split(".") obj)<line_sep><return>rv()<if>callable(rv)<else>rv<block_end><for_stmt>key,value kwargs.items()<block_start>setattr(_from_property key value)<block_end><return>_from_property<block_end><def_stmt>get_request_params request param<block_start>"""从请求信息中获取想要的信息"""<if_stmt><not>hasattr(request param)<block_start>preserved_filters_str=request.GET.get('_changelist_filters')<if_stmt>preserved_filters_str<block_start>preserved_filters=dict(parse_qsl(preserved_filters_str))<block_end><else_stmt><block_start>preserved_filters=dict()<block_end>value=(request.GET.get(param)<or>preserved_filters.get(param))<line_sep>setattr(request param value)<block_end><return>getattr(request param)<block_end> |
"""Integration tests for lit_nlp.examples.models.glue_models."""<import_from_stmt>absl.testing absltest<import_from_stmt>lit_nlp.examples.models glue_models<import_stmt>transformers<class_stmt>GlueModelsIntTest(absltest.TestCase)<block_start><def_stmt>test_sst2_model_predict self# Create model.
<block_start>model_path="https://storage.googleapis.com/what-if-tool-resources/lit-models/sst2_tiny.tar.gz"# pylint: disable=line-too-long
<if_stmt>model_path.endswith(".tar.gz")<block_start>model_path=transformers.file_utils.cached_path(model_path extract_compressed_file=<true>)<block_end>model=glue_models.SST2Model(model_path)<line_sep># Run prediction to ensure no failure.
model_in=[{"sentence":"test sentence"}]<line_sep>model_out=list(model.predict(model_in))<line_sep># Sanity-check output vs output spec.
self.assertLen(model_out 1)<for_stmt>key model.output_spec().keys()<block_start>self.assertIn(key model_out[0].keys())<block_end><block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>absltest.main()<block_end> |
# Generated by Django 2.2 on 2019-05-12 18:20
<import_stmt>uuid<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[("boltstream" "0003_streamsession")]<line_sep>operations=[migrations.AddField(model_name="user" name="uuid" field=models.UUIDField(default=uuid.uuid4 editable=<false> unique=<true> verbose_name="UUID") )]<block_end> |
<import_stmt>numpy<as>np<line_sep>ROWS=6<line_sep>COLS=9<line_sep>S=(2 0)<line_sep>G=(0 8)<line_sep>BLOCKS=[(1 2) (2 2) (3 2) (0 7) (1 7) (2 7) (4 5)]<line_sep>ACTIONS=["left" "up" "right" "down"]<class_stmt>Maze<block_start><def_stmt>__init__ self<block_start>self.rows=ROWS<line_sep>self.cols=COLS<line_sep>self.start=S<line_sep>self.goal=G<line_sep>self.blocks=BLOCKS<line_sep>self.state=S<line_sep>self.end=<false><line_sep># init maze
self.maze=np.zeros((self.rows self.cols))<for_stmt>b self.blocks<block_start>self.maze[b]=-1<block_end><block_end><def_stmt>nxtPosition self action<block_start>r,c=self.state<if_stmt>action<eq>"left"<block_start>c<augsub>1<block_end><elif_stmt>action<eq>"right"<block_start>c<augadd>1<block_end><elif_stmt>action<eq>"up"<block_start>r<augsub>1<block_end><else_stmt><block_start>r<augadd>1<block_end><if_stmt>(r<ge>0<and>r<le>self.rows-1)<and>(c<ge>0<and>c<le>self.cols-1)<block_start><if_stmt>(r c)<not><in>self.blocks<block_start>self.state=(r c)<block_end><block_end><return>self.state<block_end><def_stmt>giveReward self<block_start><if_stmt>self.state<eq>self.goal<block_start>self.end=<true><line_sep><return>1<block_end><else_stmt><block_start><return>0<block_end><block_end><def_stmt>showMaze self<block_start>self.maze[self.state]=1<for_stmt>i range(0 self.rows)<block_start>print('-------------------------------------')<line_sep>out='| '<for_stmt>j range(0 self.cols)<block_start><if_stmt>self.maze[i j]<eq>1<block_start>token='*'<block_end><if_stmt>self.maze[i j]<eq>-1<block_start>token='z'<block_end><if_stmt>self.maze[i j]<eq>0<block_start>token='0'<block_end>out<augadd>token+' | '<block_end>print(out)<block_end>print('-------------------------------------')<block_end><block_end><class_stmt>DynaAgentPlus<block_start><def_stmt>__init__ self exp_rate=0.3 lr=0.1 n_steps=5 episodes=1 timeWeight=1e-4<block_start>self.time=0# keep track of the total time
self.timeWeight=timeWeight<line_sep>self.maze=Maze()<line_sep>self.state=S<line_sep>self.actions=ACTIONS<line_sep>self.state_actions=[]# state & action track
self.exp_rate=exp_rate<line_sep>self.lr=lr<line_sep>self.steps=n_steps<line_sep>self.episodes=episodes# number of episodes going to play
self.steps_per_episode=[]<line_sep>self.Q_values={}<line_sep># model function
self.model={}<for_stmt>row range(ROWS)<block_start><for_stmt>col range(COLS)<block_start>self.Q_values[(row col)]={}<for_stmt>a self.actions<block_start>self.Q_values[(row col)][a]=0<block_end><block_end><block_end><block_end><def_stmt>chooseAction self# epsilon-greedy
<block_start>mx_nxt_reward=-999<line_sep>action=""<if_stmt>np.random.uniform(0 1)<le>self.exp_rate<block_start>action=np.random.choice(self.actions)<block_end><else_stmt># greedy action
<block_start>current_position=self.state<line_sep># if all actions have same value, then select randomly
<if_stmt>len(set(self.Q_values[current_position].values()))<eq>1<block_start>action=np.random.choice(self.actions)<block_end><else_stmt><block_start><for_stmt>a self.actions<block_start>nxt_reward=self.Q_values[current_position][a]<if_stmt>nxt_reward<ge>mx_nxt_reward<block_start>action=a<line_sep>mx_nxt_reward=nxt_reward<block_end><block_end><block_end><block_end><return>action<block_end><def_stmt>reset self<block_start>self.maze=Maze()<line_sep>self.state=S<line_sep>self.state_actions=[]<line_sep>self.time=0<block_end><def_stmt>updateModel self state nxtState action reward<block_start><if_stmt>state<not><in>self.model.keys()<block_start>self.model[state]={}<block_end><for_stmt>a self.actions# the initial model for such actions was that they would
# lead back to the same state with a reward of 0.
<block_start><if_stmt>a<ne>action<block_start>self.model[state][a]=(0 state 1)<block_end><block_end>self.model[state][action]=(reward nxtState self.time)<block_end><def_stmt>play self<block_start>self.steps_per_episode=[]<for_stmt>ep range(self.episodes)<block_start><while_stmt><not>self.maze.end<block_start>action=self.chooseAction()<line_sep>self.state_actions.append((self.state action))<line_sep>nxtState=self.maze.nxtPosition(action)<line_sep>reward=self.maze.giveReward()<line_sep># update Q-value
self.Q_values[self.state][action]<augadd>self.lr<times>(reward+np.max(list(self.Q_values[nxtState].values()))-self.Q_values[self.state][action])<line_sep># update model
self.updateModel(self.state nxtState action reward)<line_sep>self.state=nxtState<line_sep>self.time<augadd>1<line_sep># loop n times to randomly update Q-value
<for_stmt>_ range(self.steps)# randomly choose an state
<block_start>rand_idx=np.random.choice(range(len(self.model.keys())))<line_sep>_state=list(self.model)[rand_idx]<line_sep># randomly choose an action
rand_idx=np.random.choice(range(len(self.model[_state].keys())))<line_sep>_action=list(self.model[_state])[rand_idx]<line_sep>_reward,_nxtState,_time=self.model[_state][_action]<line_sep># update _reward
_reward<augadd>self.timeWeight<times>np.sqrt(self.time-_time)<line_sep>self.Q_values[_state][_action]<augadd>self.lr<times>(_reward+np.max(list(self.Q_values[_nxtState].values()))-self.Q_values[_state][_action])<block_end><block_end># end of game
<if_stmt>ep%10<eq>0<block_start>print("episode" ep)<block_end>self.steps_per_episode.append(len(self.state_actions))<line_sep>self.reset()<block_end><block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>dap=DynaAgentPlus()<line_sep>dap.play()<block_end> |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2021.10.04
#
# title: Scrapy returning None on querying by xpath
# url: https://stackoverflow.com/questions/69442962/scrapy-returning-none-on-querying-by-xpath/69443343#69443343
# [Scrapy returning None on querying by xpath](https://stackoverflow.com/questions/69442962/scrapy-returning-none-on-querying-by-xpath/69443343#69443343)
<import_stmt>scrapy<class_stmt>MySpider(scrapy.Spider)<block_start>start_urls=[# f"https://www.centralbankofindia.co.in/en/branch-locator?field_state_target_id=All&combine=&page={i}"
# for i in range(0, 5)
# only first page - links to other pages it will find in HTML
"https://www.centralbankofindia.co.in/en/branch-locator?field_state_target_id=All&combine=&page=0"]<line_sep>name="Central Bank of India"<def_stmt>parse self response<block_start>print(f'url: {response.url}')<line_sep>all_items=response.xpath('//*[@id="block-cbi-content"]//td[2]//span[2]/text()').extract()<for_stmt>address all_items<block_start>print(address)<line_sep><yield>{'address':address}<block_end># get link to next page
next_page=response.xpath('//a[@rel="next"]/@href').extract_first()<if_stmt>next_page<block_start>print(f'Next Page: {next_page}')<line_sep><yield>response.follow(next_page)<block_end><block_end><block_end># --- run without project and save in `output.csv` ---
<import_from_stmt>scrapy.crawler CrawlerProcess<line_sep>c=CrawlerProcess({'USER_AGENT':'Mozilla/5.0' # save in file CSV, JSON or XML
'FEEDS':{'output.csv':{'format':'csv'}} # new in 2.1
})<line_sep>c.crawl(MySpider)<line_sep>c.start()<line_sep> |
<import_stmt>json<import_stmt>os<import_stmt>warnings<import_stmt>requests<try_stmt><block_start>_CODESPEED_USER=os.environ["CODESPEED_USER"]<line_sep>_CODESPEED_PASSWORD=os.environ["CODESPEED_PASSWORD"]<line_sep>_BENCHMARK_HOST=os.environ["BENCHMARK_HOST"]<block_end><except_stmt>KeyError<block_start>warnings.warn("Codespeed environment variables not available, posting results would fail." RuntimeWarning )<block_end><def_stmt>post_result codespeed_url commit_id branch bench_name value<block_start>data=[{"commitid":commit_id "project":"raiden" "branch":branch "executable":"raiden" "benchmark":bench_name "environment":_BENCHMARK_HOST "result_value":value }]<line_sep>data_={"json":json.dumps(data)}<line_sep>url=codespeed_url+"/result/add/json/"<line_sep>resp=requests.post(url data=data_ auth=(_CODESPEED_USER _CODESPEED_PASSWORD))<line_sep>resp.raise_for_status()<block_end> |
c=get_config()<line_sep>c.NotebookApp.ip='{{IPYTHON_NB_LISTEN_ADDR}}'<line_sep>c.NotebookApp.port={{IPYTHON_NB_LISTEN_PORT}}<line_sep>c.NotebookApp.open_browser=<false><line_sep>c.NotebookApp.notebook_dir=u'{{IPYTHON_NB_DIR}}'<line_sep>c.NotebookApp.base_url='{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}'<line_sep>c.NotebookApp.tornado_settings={'static_url_prefix':'{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}/static/'}<line_sep># Disable token auth for now
c.NotebookApp.token=''<line_sep>c.NotebookApp.password=''<line_sep> |
<import_stmt>torch<import_stmt>mmcv<import_stmt>argparse<import_stmt>os.path<as>osp<line_sep>parser=argparse.ArgumentParser(description='Hyperparams')<line_sep>parser.add_argument('checkpoint' nargs='?' type=str default=<none>)<line_sep>args=parser.parse_args()<line_sep>dir_name=args.checkpoint.split("/")[-2]<line_sep>checkpoint=torch.load(args.checkpoint map_location='cpu')<line_sep>state_dict=checkpoint['state_dict']<for_stmt>k,v state_dict.items()<block_start>print(k)<block_end>checkpoint={'state_dict':state_dict}<line_sep>mmcv.mkdir_or_exist("converted/")<try_stmt><block_start>torch.save(checkpoint osp.join("converted" dir_name+".pth.tar") _use_new_zipfile_serialization=<false>)<block_end><except_stmt><block_start>torch.save(checkpoint osp.join("converted" dir_name+".pth.tar"))<block_end> |
<import_from_future_stmt> absolute_import division print_function unicode_literals <import_stmt>numpy<as>np<import_from_stmt>slicerator pipeline Pipeline<import_stmt>six<line_sep>@pipeline<def_stmt>as_grey frame<block_start>"""Convert a 2D image or PIMS reader to greyscale.
This weights the color channels according to their typical
response to white light.
It does nothing if the input is already greyscale.
"""<if_stmt>len(frame.shape)<eq>2<block_start><return>frame<block_end><else_stmt><block_start>red=frame[: : 0]<line_sep>green=frame[: : 1]<line_sep>blue=frame[: : 2]<line_sep><return>0.2125<times>red+0.7154<times>green+0.0721<times>blue<block_end><block_end># "Gray" is the more common spelling
as_gray=as_grey<line_sep># Source of this patch: https://github.com/scikit-image/scikit-image/pull/3556
# See also: https://github.com/numpy/numpy/pull/11966
<import_from_stmt>distutils.version LooseVersion<if_stmt>LooseVersion(np.__version__)<l>LooseVersion('1.16')<block_start><import_from_stmt>numpy.lib.arraypad _validate_lengths<as>validate_lengths<block_end><else_stmt><block_start><import_from_stmt>numpy.lib.arraypad _as_pairs<def_stmt>validate_lengths ar crop_width<block_start><return>_as_pairs(crop_width ar.ndim as_index=<true>)<block_end><block_end><def_stmt>_crop frame bbox<block_start><return>frame[bbox[0]:bbox[2] bbox[1]:bbox[3]]<block_end>@pipeline<class_stmt>crop(Pipeline)<block_start>"""Crop image or image-reader`reader` by `crop_width` along each dimension.
Parameters
----------
ar : array-like of rank N
Input array.
crop_width : {sequence, int}
Number of values to remove from the edges of each axis.
``((before_1, after_1),`` ... ``(before_N, after_N))`` specifies
unique crop widths at the start and end of each axis.
``((before, after),)`` specifies a fixed start and end crop
for every axis.
``(n,)`` or ``n`` for integer ``n`` is a shortcut for
before = after = ``n`` for all axes.
order : {'C', 'F', 'A', 'K'}, optional
control the memory layout of the copy. See ``np.copy``.
Returns
-------
cropped : array
The cropped array.
See Also
--------
Source: ``skimage.util.crop`` (v0.12.3)
"""<def_stmt>__init__ self reader crop_width order='K'# We have to know the frame shape that is returned by the reader.
<block_start><try_stmt># In case the reader is a FramesSequence, there is an attribute
<block_start>shape=reader.frame_shape<line_sep>first_frame=np.empty(shape dtype=bool)<block_end><except_stmt>AttributeError<block_start>first_frame=reader[0]<line_sep>shape=first_frame.shape<block_end># Validate the crop widths on the first frame
crops=validate_lengths(first_frame crop_width)<line_sep>self._crop_slices=tuple([slice(a shape[i]-b)<for>i,(a b) enumerate(crops)])<line_sep>self._crop_shape=tuple([shape[i]-b-a<for>i,(a b) enumerate(crops)])<line_sep>self._crop_order=order<line_sep># We could pass _crop to proc_func. However this adds an extra copy
# operation. Therefore we define our own here.
super(self.__class__ self).__init__(<none> reader)<block_end><def_stmt>_get self key<block_start>ar=self._ancestors[0][key]<line_sep><return>np.array(ar[self._crop_slices] order=self._crop_order copy=<true>)<block_end>@property<def_stmt>frame_shape self<block_start><return>self._crop_shape<block_end><block_end> |
<import_from_stmt>django.db models<class_stmt>A(models.Model)<block_start>null_field=models.IntegerField(null=<true>)<line_sep>new_null_field=models.IntegerField(null=<true>)<block_end> |
"""
Copyright 2022 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
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>argparse<import_stmt>subprocess# noqa: S404
<import_stmt>sys<def_stmt>main <arrow><none><block_start>"""Provide command-line options to flatten MAGMA-MME OAI image"""<line_sep>args=_parse_args()<line_sep>status=perform_flattening(args.tag)<line_sep>sys.exit(status)<block_end><def_stmt>_parse_args <arrow>argparse.Namespace<block_start>"""Parse the command line args
Returns:
argparse.Namespace: the created parser
"""<line_sep>parser=argparse.ArgumentParser(description='Flattening Image')<line_sep>parser.add_argument('--tag' '-t' action='store' required=<true> help='Image Tag in image-name:image tag format' )<line_sep><return>parser.parse_args()<block_end><def_stmt>perform_flattening tag<block_start>"""Parse the command line args
Args:
tag: Image Tag in image-name:image tag format
Returns:
int: pass / fail status
"""<line_sep># First detect which docker/podman command to use
cli=''<line_sep>image_prefix=''<line_sep>cmd='which podman || true'<line_sep>podman_check=subprocess.check_output(cmd shell=<true> universal_newlines=<true>)# noqa: S602
<if_stmt>podman_check.strip()<block_start>cli='sudo podman'<line_sep>image_prefix='localhost/'<block_end><else_stmt><block_start>cmd='which docker || true'<line_sep>docker_check=subprocess.check_output(cmd shell=<true> universal_newlines=<true>)# noqa: S602
<if_stmt>docker_check.strip()<block_start>cli='docker'<line_sep>image_prefix=''<block_end><else_stmt><block_start>print('No docker / podman installed: quitting')<line_sep><return>-1<block_end><block_end>print(f'Flattening {tag}')<line_sep># Creating a container
cmd=cli+' run --name test-flatten --entrypoint /bin/true -d '+tag<line_sep>print(cmd)<line_sep>subprocess.check_call(cmd shell=<true> universal_newlines=<true>)# noqa: S602
# Export / Import trick
cmd=cli+' export test-flatten | '+cli+' import '<line_sep># Bizarro syntax issue with podman
<if_stmt>cli<eq>'docker'<block_start>cmd<augadd>' --change "ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" '<block_end><else_stmt><block_start>cmd<augadd>' --change "ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" '<block_end>cmd<augadd>' --change "WORKDIR /magma-mme" '<line_sep>cmd<augadd>' --change "EXPOSE 3870/tcp" '<line_sep>cmd<augadd>' --change "EXPOSE 5870/tcp" '<line_sep>cmd<augadd>' --change "EXPOSE 2123/udp" '<line_sep>cmd<augadd>' --change "CMD [\\"sleep\\", \\"infinity\\"]" '# noqa: WPS342
cmd<augadd>' - '+image_prefix+tag<line_sep>print(cmd)<line_sep>subprocess.check_call(cmd shell=<true> universal_newlines=<true>)# noqa: S602
# Remove container
cmd=cli+' rm -f test-flatten'<line_sep>print(cmd)<line_sep>subprocess.check_call(cmd shell=<true> universal_newlines=<true>)# noqa: S602
# At this point the original image is a dangling image.
# CI pipeline will clean up (`image prune --force`)
<return>0<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_from_future_stmt> absolute_import division print_function<line_sep># LIBTBX_SET_DISPATCHER_NAME boost_adaptbx.inexact
<import_stmt>boost_adaptbx.boost.python<as>bp<import_stmt>sys<def_stmt>run args<block_start><assert_stmt>len(args)<eq>0<line_sep>print("Now creating a NaN in C++ as 0/0 ...")<line_sep>sys.stdout.flush()<line_sep>result=bp.ext.divide_doubles(0 0)<line_sep>print("Result:" result)<block_end><if_stmt>(__name__<eq>"__main__")<block_start>run(sys.argv[1:])<block_end> |
<import_stmt>unittest<import_stmt>torch<import_from_stmt>fastNLP Vocabulary<import_from_stmt>fastNLP.embeddings StaticEmbedding<import_from_stmt>fastNLP.modules TransformerSeq2SeqDecoder<import_from_stmt>fastNLP.modules LSTMSeq2SeqDecoder<import_from_stmt>fastNLP seq_len_to_mask<class_stmt>TestTransformerSeq2SeqDecoder(unittest.TestCase)<block_start><def_stmt>test_case self<block_start>vocab=Vocabulary().add_word_lst("This is a test .".split())<line_sep>vocab.add_word_lst("Another test !".split())<line_sep>embed=StaticEmbedding(vocab embedding_dim=10)<line_sep>encoder_output=torch.randn(2 3 10)<line_sep>src_seq_len=torch.LongTensor([3 2])<line_sep>encoder_mask=seq_len_to_mask(src_seq_len)<for_stmt>flag [<true> <false>]<block_start><with_stmt>self.subTest(bind_decoder_input_output_embed=flag)<block_start>decoder=TransformerSeq2SeqDecoder(embed=embed pos_embed=<none> d_model=10 num_layers=2 n_head=5 dim_ff=20 dropout=0.1 bind_decoder_input_output_embed=<true>)<line_sep>state=decoder.init_state(encoder_output encoder_mask)<line_sep>output=decoder(tokens=torch.randint(0 len(vocab) size=(2 4)) state=state)<line_sep>self.assertEqual(output.size() (2 4 len(vocab)))<block_end><block_end><block_end><block_end><class_stmt>TestLSTMDecoder(unittest.TestCase)<block_start><def_stmt>test_case self<block_start>vocab=Vocabulary().add_word_lst("This is a test .".split())<line_sep>vocab.add_word_lst("Another test !".split())<line_sep>embed=StaticEmbedding(vocab model_dir_or_name=<none> embedding_dim=10)<line_sep>encoder_output=torch.randn(2 3 10)<line_sep>tgt_words_idx=torch.LongTensor([[1 2 3 4] [2 3 0 0]])<line_sep>src_seq_len=torch.LongTensor([3 2])<line_sep>encoder_mask=seq_len_to_mask(src_seq_len)<for_stmt>flag [<true> <false>]<block_start><for_stmt>attention [<true> <false>]<block_start><with_stmt>self.subTest(bind_decoder_input_output_embed=flag attention=attention)<block_start>decoder=LSTMSeq2SeqDecoder(embed=embed num_layers=2 hidden_size=10 dropout=0.3 bind_decoder_input_output_embed=flag attention=attention)<line_sep>state=decoder.init_state(encoder_output encoder_mask)<line_sep>output=decoder(tgt_words_idx state)<line_sep>self.assertEqual(tuple(output.size()) (2 4 len(vocab)))<block_end><block_end><block_end><block_end><block_end> |
#
# Copyright 2019 The FATE 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.
#
<import_from_stmt>pipeline.backend.config VERSION<class_stmt>Data(object)<block_start><def_stmt>__init__ self data=<none> train_data=<none> validate_data=<none> test_data=<none> predict_input=<none><block_start>self._data=data<line_sep>self._train_data=train_data<line_sep>self._validate_data=validate_data<line_sep>self._test_data=test_data<line_sep>self._predict_input=predict_input<block_end><def_stmt>__getattr__ self data_key<block_start><if_stmt>data_key<eq>"train_data"<block_start><return>self._train_data<block_end><elif_stmt>data_key<eq>"validate_data"<block_start><return>self._validate_data<block_end><elif_stmt>data_key<eq>"test_data"<block_start><return>self._test_data<block_end><elif_stmt>data_key<eq>"data"<block_start><return>self._data<block_end><elif_stmt>data_key<eq>"predict_input"<block_start><return>self._predict_input<block_end><else_stmt><block_start><raise>ValueError("data key {} not support".format(data_key))<block_end><block_end><block_end> |
<import_stmt>os<import_stmt>numpy<as>np<import_stmt>json<import_stmt>cv2<import_from_stmt>tqdm tqdm<import_from_stmt>collections defaultdict<def_stmt>convert img_dir split label_dir save_label_dir filter_crowd=<false> filter_ignore=<false><block_start>cat2id={'train':6 'car':3 'bus':5 'other person':1 'rider':2 'pedestrian':1 'other vehicle':3 'motorcycle':7 'bicycle':8 'trailer':4 'truck':4}<line_sep>coco=defaultdict(list)<line_sep>coco["categories"]=[{"supercategory":"human" "id":1 "name":"pedestrian"} {"supercategory":"human" "id":2 "name":"rider"} {"supercategory":"vehicle" "id":3 "name":"car"} {"supercategory":"vehicle" "id":4 "name":"truck"} {"supercategory":"vehicle" "id":5 "name":"bus"} {"supercategory":"vehicle" "id":6 "name":"train"} {"supercategory":"bike" "id":7 "name":"motorcycle"} {"supercategory":"bike" "id":8 "name":"bicycle"} ]<line_sep>attr_id_dict={frame["name"]:frame["id"]<for>frame coco["categories"]}<line_sep>all_categories=set()<line_sep>img_dir=os.path.join(img_dir split)<line_sep>label_dir=os.path.join(label_dir split)<line_sep>vids=os.listdir(img_dir)<for_stmt>vid tqdm(vids)<block_start>txt_label_dir=os.path.join(save_label_dir split vid)<line_sep>os.makedirs(txt_label_dir exist_ok=<true>)<line_sep>annos=json.load(open(os.path.join(label_dir vid+'.json') 'r'))<for_stmt>anno annos<block_start>name=anno['name']<line_sep>labels=anno['labels']<line_sep>videoName=anno['videoName']<line_sep>frameIndex=anno['frameIndex']<line_sep>img=cv2.imread(os.path.join(img_dir vid name))<line_sep>seq_height,seq_width,_=img.shape<if_stmt>len(labels)<l>1<block_start><continue><block_end># for label in labels:
# category = label['category']
# all_categories.add(category)
<with_stmt>open(os.path.join(txt_label_dir name.replace('jpg' 'txt')) 'w')<as>f<block_start><for_stmt>label labels<block_start>obj_id=label['id']<line_sep>category=label['category']<line_sep>attributes=label['attributes']<line_sep>is_crowd=attributes['crowd']<if_stmt>filter_crowd<and>is_crowd<block_start><continue><block_end><if_stmt>filter_ignore<and>(category<not><in>attr_id_dict.keys())<block_start><continue><block_end>box2d=label['box2d']<line_sep>x1=box2d['x1']<line_sep>x2=box2d['x2']<line_sep>y1=box2d['y1']<line_sep>y2=box2d['y2']<line_sep>w=x2-x1<line_sep>h=y2-y1<line_sep>cx=(x1+x2)/2<line_sep>cy=(y1+y2)/2<line_sep>label_str='{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}\n'.format(cat2id[category] int(obj_id) cx/seq_width cy/seq_height w/seq_width h/seq_height)<line_sep>f.write(label_str)<block_end><block_end><block_end><block_end># print(f'all categories are {all_categories}.')
<block_end><def_stmt>generate_txt img_dir label_dir txt_path='bdd100k.train' split='train'<block_start>img_dir=os.path.join(img_dir split)<line_sep>label_dir=os.path.join(label_dir split)<line_sep>all_vids=os.listdir(img_dir)<line_sep>all_frames=[]<for_stmt>vid tqdm(all_vids)<block_start>fids=os.listdir(os.path.join(img_dir vid))<line_sep>fids.sort()<for_stmt>fid fids<block_start><if_stmt>os.path.exists(os.path.join(label_dir vid fid.replace('jpg' 'txt')))<block_start>all_frames.append(f'images/track/{split}/{vid}/{fid}')<block_end><block_end><block_end><with_stmt>open(txt_path 'w')<as>f<block_start><for_stmt>frame all_frames<block_start>f.write(frame+'\n')<block_end><block_end><block_end>'''no filter'''<line_sep># img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/labels/track'
# split = 'train'
# convert(img_dir, split, label_dir, save_label_dir)
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/labels/track'
# split = 'val'
# convert(img_dir, split, label_dir, save_label_dir)
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/labels/track'
# split = 'train'
# generate_txt(img_dir,save_label_dir,txt_path='bdd100k.train',split='train')
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/labels/track'
# split = 'val'
# generate_txt(img_dir,save_label_dir,txt_path='bdd100k.val',split='val')
'''for filter'''<line_sep># img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/filter_labels/track'
# split = 'train'
# convert(img_dir, split, label_dir, save_label_dir, filter_crowd=True, filter_ignore=True)
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/filter_labels/track'
# split = 'val'
# convert(img_dir, split, label_dir, save_label_dir, filter_crowd=True, filter_ignore=True)
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/filter_labels/track'
# split = 'train'
# generate_txt(img_dir,save_label_dir,txt_path='filter.bdd100k.train',split='train')
# img_dir = '/data/Dataset/bdd100k/bdd100k/images/track'
# label_dir = '/data/Dataset/bdd100k/bdd100k/labels/box_track_20'
# save_label_dir = '/data/Dataset/bdd100k/bdd100k/filter_labels/track'
# split = 'val'
# generate_txt(img_dir,save_label_dir,txt_path='filter.bdd100k.val',split='val')
|
<import_from_stmt>chalice Chalice Rate<import_stmt>logging<line_sep>app=Chalice(app_name='chalice-lambdas')<line_sep>app.log.setLevel(logging.DEBUG)<line_sep>@app.route('/')<def_stmt>index <block_start><return>{'message':'Olar Chalice!'}<block_end>@app.route('/batatinhas')<def_stmt>batatinhas <block_start><return>{'message':'Olar batatinhas!'}<block_end>@app.route('/query')<def_stmt>query <block_start><return>{'message':'Olar Query!' 'params':app.current_request.query_params}<block_end>@app.route('/meu-post' methods=['POST'])<def_stmt>post_func <block_start><return>{'message':'Olar Query!' 'params':app.current_request.json_body}<block_end>@app.lambda_function(name='batata-function')<def_stmt>my_lambda request context<block_start><return>{}<block_end>@app.schedule(Rate(1 unit=Rate.MINUTES))<def_stmt>scheduler event<block_start>app.log.info('Executei o scheeeeedddddddd!!!!')<block_end>@app.on_s3_event(bucket='live-de-bucket')<def_stmt>s3_event event<block_start>app.log.info(f'{event.bucket}, {event.key}')<block_end> |
<import_from_stmt>typing Union Optional<import_from_stmt>_stubs *<class_stmt>StrParamT(Par Union[Par str])<block_start><def_stmt>eval self<arrow>str<block_start><pass><block_end><block_end><class_stmt>IntParamT(Par Union[Par str int])<block_start><def_stmt>eval self<arrow>int<block_start><pass><block_end><block_end><class_stmt>FloatParamT(Par Union[Par str float int])<block_start><def_stmt>eval self<arrow>float<block_start><pass><block_end><block_end><class_stmt>DatParamT(Par Union[Par str DAT])<block_start><def_stmt>eval self<arrow>Optional[DAT]<block_start><pass><block_end><block_end><class_stmt>CompParamT(Par Union[Par str COMP])<block_start><def_stmt>eval self<arrow>Optional[COMP]<block_start><pass><block_end><block_end><class_stmt>OPParamT(Par Union[Par str OP COMP DAT SOP TOP CHOP MAT])<block_start><def_stmt>eval self<arrow>Optional[Union[OP COMP DAT SOP TOP CHOP MAT]]<block_start><pass><block_end><block_end><class_stmt>BoolParamT(Par Union[Par bool int])<block_start><def_stmt>eval self<arrow>bool<block_start><pass><block_end><block_end> |
"""
Script for translating the KITTI 3D bounding box annotation format into the BB3TXT data format.
A BB3TXT file is formatted like this:
filename label confidence xmin ymin xmax ymax fblx fbly fbrx fbry rblx rbly ftly
filename label confidence xmin ymin xmax ymax fblx fbly fbrx fbry rblx rbly ftly
filename label confidence xmin ymin xmax ymax fblx fbly fbrx fbry rblx rbly ftly
...
----------------------------------------------------------------------------------------------------
python kitti2bb3txt.py path_labels path_images outfile.bb3txt
----------------------------------------------------------------------------------------------------
"""<line_sep>__date__='03/17/2017'<line_sep>__author__='<NAME>'<line_sep>__email__='<EMAIL>'<import_stmt>argparse<import_stmt>os<import_stmt>numpy<as>np<import_stmt>cv2<import_from_stmt>mappings.utils LabelMappingManager<import_from_stmt>mappings.utils available_categories<import_from_stmt>shared.geometry R3x3_y t3x1 Rt4x4<line_sep>####################################################################################################
# DEFINITIONS #
####################################################################################################
# IMPORTANT !!
# The labels must translate precisely into the numbers in the kitti.yaml mapping file!
LABELS={'Car':1 'Van':2 'Truck':3 'Pedestrian':4 'Person_sitting':5 'Cyclist':6 'Tram':7 # Throw away 'Misc' and 'DontCare'
}<line_sep># Initialize the LabelMappingManager
LMM=LabelMappingManager()<line_sep>MAPPING=LMM.get_mapping('kitti')<line_sep>####################################################################################################
# FUNCTIONS #
####################################################################################################
<def_stmt>read_camera_matrix line<block_start>"""
Reads a camera matrix P (3x4) stored in the row-major scheme.
Input:
line: Row-major stored matrix separated by spaces, first element is the matrix name
Returns:
camera matrix P 4x4
"""<line_sep>data=line.split(' ')<if_stmt>data[0]<ne>'P2:'<block_start>print('ERROR: We need left camera matrix (P2)!')<line_sep>exit(1)<block_end>P=np.asmatrix([[float(data[1]) float(data[2]) float(data[3]) float(data[4])] [float(data[5]) float(data[6]) float(data[7]) float(data[8])] [float(data[9]) float(data[10]) float(data[11]) float(data[12])]])<line_sep><return>P<block_end><def_stmt>extract_3D_bb data P<block_start>"""
Extract 3D bounding box coordinates in the image from the KITTI labels.
Input:
data: One split line of the label file (line.split(' '))
P: 3x4 camera projection matrix
Returns:
matrix of corners: fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl
"""<line_sep># Object dimensions
h=float(data[8])<line_sep>w=float(data[9])<line_sep>l=float(data[10])<line_sep># Position of the center point on the ground plane (xz plane)
cx=float(data[11])<line_sep>cy=float(data[12])<line_sep>cz=float(data[13])<line_sep># Rotation of the object around y
ry=float(data[14])<line_sep># 3D box corners - careful, the coordinate system of the car is that x points
# forward, not z! (It is rotated by 90deg with respect to the camera one)
# fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl
X=np.asmatrix([[l/2 -l/2 l/2 -l/2 l/2 -l/2 l/2 -l/2] [0 0 0 0 -h -h -h -h] [-w/2 -w/2 w/2 w/2 -w/2 -w/2 w/2 w/2] [1 1 1 1 1 1 1 1]])<line_sep># Rotate the 3D box around y axis and translate it to the correct position in the camera frame
X=Rt4x4(R3x3_y(ry) t3x1(cx cy cz))<times>X<line_sep>x=P<times>X<line_sep># x is in homogeneous coordinates -> get u, v
x=x/x[2 :]<line_sep>x=x[0:2 :]<line_sep># image = cv2.imread(path_image)
# # Front
# cv2.line(image, (int(x[0,0]), int(x[1,0])), (int(x[0,2]), int(x[1,2])), (0,255,0), 3)
# cv2.line(image, (int(x[0,4]), int(x[1,4])), (int(x[0,6]), int(x[1,6])), (0,255,0))
# cv2.line(image, (int(x[0,0]), int(x[1,0])), (int(x[0,4]), int(x[1,4])), (0,255,0))
# cv2.line(image, (int(x[0,2]), int(x[1,2])), (int(x[0,6]), int(x[1,6])), (0,255,0), 3)
# # Rear
# cv2.line(image, (int(x[0,1]), int(x[1,1])), (int(x[0,3]), int(x[1,3])), (0,0,255))
# cv2.line(image, (int(x[0,5]), int(x[1,5])), (int(x[0,7]), int(x[1,7])), (0,0,255))
# cv2.line(image, (int(x[0,1]), int(x[1,1])), (int(x[0,5]), int(x[1,5])), (0,0,255))
# cv2.line(image, (int(x[0,3]), int(x[1,3])), (int(x[0,7]), int(x[1,7])), (0,0,255))
# # Connections
# cv2.line(image, (int(x[0,0]), int(x[1,0])), (int(x[0,1]), int(x[1,1])), (255,0,0))
# cv2.line(image, (int(x[0,2]), int(x[1,2])), (int(x[0,3]), int(x[1,3])), (255,0,0), 3)
# cv2.line(image, (int(x[0,4]), int(x[1,4])), (int(x[0,5]), int(x[1,5])), (255,0,0))
# cv2.line(image, (int(x[0,6]), int(x[1,6])), (int(x[0,7]), int(x[1,7])), (255,0,0))
# # Show image
# cv2.imshow('img', image)
# cv2.waitKey()
<return>x<block_end><def_stmt>flip_3D_bb x image_width<block_start>"""
Flips the annotation of the image around y axis.
Input:
x: coordinates of points fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl
image_width: width of the flipped image
Return:
x - flipped coordinates
"""<line_sep># First flip the x coordinates of the points
x[0 :]=image_width-x[0 :]<line_sep># Now switch left and right points
x_out=np.matrix(np.copy(x))<line_sep>x_out[: 0]=x[: 2]<line_sep>x_out[: 1]=x[: 3]<line_sep>x_out[: 2]=x[: 0]<line_sep>x_out[: 3]=x[: 1]<line_sep>x_out[: 4]=x[: 6]<line_sep>x_out[: 5]=x[: 7]<line_sep>x_out[: 6]=x[: 4]<line_sep>x_out[: 7]=x[: 5]<line_sep><return>x_out<block_end><def_stmt>process_image path_image path_label_file path_calib_file label flip filter outfile<block_start>"""
Processes one image from the dataset and writes it out to the outfile.
Input:
path_image: Path to the image file
path_label_file: Path to the label file with KITTI labels
path_calib_file: Path to the calibration file for this image
label: Which class label should be extracted from the dataset (default None)
flip: True/False whether the images should also be flipped by this script
filter: True/False whether we should filter out very occluded and truncated boxes
outfile: File handle of the open output BBTXT file
"""<if_stmt>flip# We have to flip the image and save it
<block_start>image=cv2.imread(path_image)<line_sep>image_width=image.shape[1]<line_sep>filename=os.path.basename(path_image)<line_sep>directory=os.path.dirname(path_image).rstrip('/')+'_flip'<line_sep>path_image=os.path.join(directory filename)<if_stmt><not>os.path.exists(directory)<block_start>os.makedirs(directory)<block_end><if_stmt><not>os.path.exists(path_image)<block_start>image=cv2.flip(image 1)<line_sep>cv2.imwrite(path_image image)<block_end><block_end><with_stmt>open(path_label_file 'r')<as>infile_label open(path_calib_file 'r')<as>infile_calib# Read camera calibration matrices
<block_start><for_stmt>line infile_calib<block_start><if_stmt>line[:2]<eq>'P2'<block_start>P=read_camera_matrix(line.rstrip('\n'))<block_end><block_end># Read the objects
<for_stmt>line infile_label<block_start>line=line.rstrip('\n')<line_sep>data=line.split(' ')<line_sep># First element of the data is the label. We don't want to process 'Misc' and
# 'DontCare' labels
<if_stmt>data[0]<eq>'Misc'<or>data[0]<eq>'DontCare'<block_start><continue><block_end># Check label, if required
<if_stmt>label<is><not><none><and>MAPPING[LABELS[data[0]]]<ne>label<block_start><continue><block_end># We do not want to include objects, which are occluded or truncated too much
<if_stmt>filter<and>(int(data[2])<ge>2<or>float(data[1])<g>0.75)<block_start><continue><block_end># Extract image coordinates (positions) of 3D bounding box corners, the corners are
# in the following order: fbr, rbr, fbl, rbl, ftr, rtr, ftl, rtl
x=extract_3D_bb(data P)<if_stmt>flip<block_start>x=flip_3D_bb(x image_width)<block_end>min_uv=np.min(x axis=1)# xmin, ymin
max_uv=np.max(x axis=1)# xmax, ymax
# The size of an image in KITTI is 1250x375. If the bounding box is significantly
# larger, discard it - probably just some large distortion from camera
<if_stmt>max_uv[1 0]-min_uv[1 0]<g>700<or>max_uv[0 0]-min_uv[0 0]<g>1500<block_start><continue><block_end>line_out=path_image+' '<line_sep>line_out<augadd>str(LABELS[data[0]])+' '<line_sep># For confidence we put one - just to have something
line_out<augadd>'1 '<line_sep># 3D bounding box is specified by the image coordinates of the front bottom left and
# right corners, rear bottom left corner and y coordinate of the front top left
# corner
line_out<augadd>str(min_uv[0 0])+' '+str(min_uv[1 0])+' '+str(max_uv[0 0])+' '+str(max_uv[1 0])+' '+str(x[0 2])+' '+str(x[1 2])+' '+str(x[0 0])+' '+str(x[1 0])+' '+str(x[0 3])+' '+str(x[1 3])+' '+str(x[1 6])+'\n'<line_sep>outfile.write(line_out)<block_end><block_end><block_end><def_stmt>translate_file path_labels path_images outfile label flip filter<block_start>"""
Runs the translation of the KITTI 3d bounding box label format into the BB3TXT format.
Input:
path_labels: Path to the "label_2" folder of the KITTI dataset
path_images: Path to the "image_2" folder with images from the KITTI dataset
outfile: File handle of the open output BBTXT file
label: Which class label should be extracted from the dataset (default None)
flip: True/False whether the images should also be flipped by this script
filter: True/False whether we should filter out very occluded and truncated boxes
"""<line_sep>print('-- TRANSLATING KITTI TO BB3TXT')<line_sep># Get the list of all label files in the directory
filenames=[f<for>f os.listdir(path_labels)<if>os.path.isfile(os.path.join(path_labels f))]<if_stmt>len(filenames)<ne>7481<block_start>print('Wrong number (%d) of files in the KITTI dataset! Should be 7481.'%(len(filenames)))<line_sep><return><block_end># Read each file and write the labels from it
<for_stmt>f filenames<block_start>path_label_file=os.path.join(path_labels f)<line_sep>path_calib_file=os.path.join(path_labels.rstrip('/').rstrip('label_2') 'calib' f)<if_stmt><not>os.path.exists(path_calib_file)<block_start>print('ERROR: We need camera calibration matrices "%s"'%(path_calib_file))<line_sep>exit(1)<block_end>path_image=os.path.join(path_images os.path.splitext(f)[0])+'.png'<if_stmt><not>os.path.isfile(path_image)<block_start>print('WARNING: Image "%s" does not exist!'%(path_image))<block_end>process_image(path_image path_label_file path_calib_file label <false> filter outfile)<if_stmt>flip# Add also the flipped image
<block_start>process_image(path_image path_label_file path_calib_file label <true> filter outfile)<block_end><block_end>print('-- TRANSLATION DONE')<block_end>####################################################################################################
# MAIN #
####################################################################################################
<def_stmt>parse_arguments <block_start>"""
Parse input options of the script.
"""<line_sep>parser=argparse.ArgumentParser(description='Convert KITTI label files into BBTXT.')<line_sep>parser.add_argument('path_labels' metavar='path_labels' type=str help='Path to the "label_2" folder of the KITTI dataset')<line_sep>parser.add_argument('path_images' metavar='path_images' type=str help='Path to the "image_2" folder of the KITTI dataset')<line_sep>parser.add_argument('outfile' metavar='path_outfile' type=argparse.FileType('w') help='Path to the output BBTXT file (including the extension)')<line_sep>parser.add_argument('--label' metavar='label' type=str default=<none> help='Single class of objects that should be separated from the dataset. '<concat>'One from '+str(available_categories(MAPPING)))<line_sep>parser.add_argument('--flip' dest='flip' action='store_true' default=<false> help='If provided, the images will also be flipped')<line_sep>parser.add_argument('--filter' dest='filter' action='store_true' default=<false> help='If provided, very occluded and truncated bounding boxes will be '<concat>'filtered out')<line_sep>args=parser.parse_args()<if_stmt><not>os.path.exists(args.path_labels)<block_start>print('Input path "%s" does not exist!'%(args.path_labels))<line_sep>parser.print_help()<line_sep>exit(1)<block_end><if_stmt><not>os.path.exists(args.path_images)<block_start>print('Input path "%s" does not exist!'%(args.path_images))<line_sep>parser.print_help()<line_sep>exit(1)<block_end><if_stmt>args.label<is><not><none><and>args.label<not><in>available_categories(MAPPING)<block_start>print('Unknown class label "%s"!'%(args.label))<line_sep>exit(1)<block_end><return>args<block_end><def_stmt>main <block_start>args=parse_arguments()<line_sep>translate_file(args.path_labels args.path_images args.outfile args.label args.flip args.filter)<line_sep>args.outfile.close()<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_from_stmt>roboticstoolbox.models.ETS.Panda Panda<import_from_stmt>roboticstoolbox.models.ETS.Frankie Frankie<import_from_stmt>roboticstoolbox.models.ETS.Puma560 Puma560<import_from_stmt>roboticstoolbox.models.ETS.Planar_Y Planar_Y<import_from_stmt>roboticstoolbox.models.ETS.Planar2 Planar2<import_from_stmt>roboticstoolbox.models.ETS.GenericSeven GenericSeven<import_from_stmt>roboticstoolbox.models.ETS.Omni Omni<line_sep>__all__=["Panda" "Frankie" "Puma560" "Planar_Y" "Planar2" "GenericSeven" "Omni"]<line_sep> |
<import_stmt>tkinter<as>Tk<import_from_stmt>functools partial<import_stmt>datetime<import_stmt>tkinter.messagebox<import_stmt>locale<import_from_stmt>.base_words BaseWordsNode center_window<import_from_stmt>.const NUMBER_LIST DATE_FORMATS SPECIAL_CHARACTERS<import_from_stmt>.. model<class_stmt>AdderNode(BaseWordsNode)<block_start>'''Append and Prepend nodes. Inherits the file menu from BaseWordsNode.
'''<def_stmt>__init__ self controller master=<none> main=<none> type_='Append' allow_remove=<true> **kwargs<block_start>BaseWordsNode.__init__(self controller master=master main=main title=type_ allow_remove=allow_remove **kwargs)<line_sep>self.sp_from=<none><line_sep>self.sp_to=<none><line_sep>self.custom_num_window=<none><line_sep>self.entry_string=<none><line_sep>self.date_format=Tk.StringVar()<line_sep>self.special_dlg=<none><line_sep>self.chk_special=[]<block_end><def_stmt>add_upper_button self<block_start>mb=Tk.Menubutton(self.upper_frame text=" + " relief="raised" font=("Helvetica" "14"))<line_sep>mb.menu=Tk.Menu(mb tearoff=0)<line_sep>mb["menu"]=mb.menu<line_sep>label='No %s'%self.title<line_sep>mb.menu.add_command(label=label command=partial(self.controller.add_attr label=label node_view=self attr_class=model.NothingAdderAttr))<line_sep># The first few attributes are the same as BaseFile
m_words=Tk.Menu(mb tearoff=0)<line_sep>mb.menu.add_cascade(label='Words' menu=m_words underline=0)<line_sep>m_words.add_command(label='Custom File...' command=partial(self.open_file_dlg partial(self.controller.add_attr label='File:' right_label_text='Calculating...' node_view=self attr_class=model.FileAttr controller=self.controller)))<line_sep>m_words.add_command(label='Custom String...' command=partial(self.open_string_popup 'String'))<line_sep>self.add_file_menu(m_words m_words)<line_sep># In addition to BaseFile's attributes, we have numbers, dates,
# and special characters
m_numbers=Tk.Menu(mb tearoff=0)<line_sep>mb.menu.add_cascade(label='Numbers' menu=m_numbers underline=0)<line_sep>m_numbers.add_command(label='User Defined...' command=self.open_custom_number_dlg)<for_stmt>type_,range_str NUMBER_LIST<block_start>range_=list(map(int range_str.split('-')))<if_stmt>type_<ne>'years'<block_start>range_str='-'.join(['0' locale.format('%d' range_[1] grouping=<true>)])<block_end>range_[1]<augadd>1<line_sep>m_numbers.add_command(label='{}: {}'.format(type_.capitalize() range_str) command=partial(self.controller.add_attr label='Numbers: {} {}'.format(type_.capitalize() range_str) node_view=self attr_class=model.RangeAttr start=range_[0] end=range_[1]))<block_end>m_numbers.add_command(label='Dates...' command=self.open_date_dlg)<line_sep>mb.menu.add_command(label="Special Characters..." command=self.open_special_dlg)<line_sep># Area and zip codes from lookup tables
<for_stmt>code_type ['Area' 'Zip']<block_start>m_area_zip=Tk.Menu(mb tearoff=0)<line_sep>mb.menu.add_cascade(label='{} Codes (US)'.format(code_type) menu=m_area_zip underline=0)<for_stmt>location_type ['State' 'City']<block_start>m_sub=Tk.Menu(m_area_zip tearoff=0)<line_sep>m_area_zip.add_cascade(label='By {}'.format(location_type) menu=m_sub underline=0)<line_sep>target_list=sorted(model.location_codes[location_type][code_type].keys())<for_stmt>st target_list<block_start>label='{} Codes: {} {}'.format(code_type st location_type<if>location_type<eq>'State'<else>'')<line_sep>m_sub.add_command(label=st command=partial(self.controller.add_attr label=label node_view=self attr_class=model.LocationCodeAttr code_type=code_type location=st location_type=location_type))<block_end><block_end><block_end>mb.pack(side="left" fill="x" padx=10 pady=5)<block_end><def_stmt>open_custom_number_dlg self<block_start>'''Opens a popup for defining a custom number range
'''<line_sep>self.custom_num_window=Tk.Toplevel()<line_sep>self.custom_num_window.withdraw()<line_sep>self.custom_num_window.title('{}: Number Selection'.format(self.title))<line_sep>self.custom_num_window.resizable(width=<false> height=<false>)<line_sep>frame=Tk.Frame(self.custom_num_window)<line_sep>lb=Tk.Label(frame text='Select Numbers to {}'.format(self.title))<line_sep>lb.pack(fill='both' side='top')<line_sep># Boxes for inputting the start and endpoints
sp_box=Tk.Frame(frame)<line_sep>lb1=Tk.Label(sp_box text='From')<line_sep>lb1.grid(column=0 row=0 padx=5 sticky='E')<line_sep>self.sp_from=Tk.Spinbox(sp_box width=12 from_=0 to=10000)<line_sep>self.sp_from.grid(column=1 row=0)<line_sep>lb2=Tk.Label(sp_box text='To')<line_sep>lb2.grid(column=0 row=1 padx=5 sticky='E')<line_sep>self.sp_to=Tk.Spinbox(sp_box width=12 from_=0 to=10000)<line_sep>self.sp_to.grid(column=1 row=1)<line_sep># Optional zero padding
lb_zeros=Tk.Label(sp_box text='Pad with zeros to width:')<line_sep>lb_zeros.grid(column=0 row=2 sticky='E')<line_sep>self.sp_zfill=Tk.Spinbox(sp_box width=12 from_=0 to=10)<line_sep>self.sp_zfill.grid(column=1 row=2)<line_sep>sp_box.pack(fill='both' side='top' padx=30 pady=20)<line_sep># Cancel and Ok buttons
btn_box=Tk.Frame(frame)<line_sep>btn_cancel=Tk.Button(btn_box text='Cancel' command=self.cancel_custom_num_window)<line_sep>btn_cancel.pack(side='right' padx=10 pady=20)<line_sep>btn_ok=Tk.Button(btn_box text='Ok' command=self.on_ok_custom_num_window)<line_sep>btn_ok.pack(side='left' padx=10 pady=20)<line_sep>btn_box.pack()<line_sep>frame.pack(fill='both' padx=10 pady=10)<line_sep>center_window(self.custom_num_window self.main.master)<line_sep>self.custom_num_window.focus_set()<block_end><def_stmt>cancel_custom_num_window self *args<block_start>'''Cancel was pressed
'''<if_stmt>self.custom_num_window<block_start>self.custom_num_window.destroy()<line_sep>self.custom_num_window=<none><block_end><block_end><def_stmt>on_ok_custom_num_window self *args<block_start>'''Ok was pressed, create the attribute
'''<try_stmt><block_start>val_from=int(self.sp_from.get())<line_sep>val_to=int(self.sp_to.get())<line_sep>zfill=int(self.sp_zfill.get())<block_end><except_stmt>ValueError<block_start>tkinter.messagebox.showerror('Invalid Number' '"From", "To", and "Pad with zeros to width" must all be integers' parent=self.main)<line_sep><return><block_end><if_stmt>val_from<g>val_to<block_start>tkinter.messagebox.showerror('Invalid Range' '"From" value must be less than or equal to "To"' parent=self.main)<block_end><elif_stmt>val_to-val_from<g>3000000<block_start>tkinter.messagebox.showerror('Invalid Range' 'The range must be smaller than 3 million' parent=self.main)<block_end><else_stmt><block_start><if_stmt>zfill<eq>0<block_start>label='Numbers: {} - {}'.format(val_from val_to)<block_end><else_stmt><block_start>label='Numbers: {} - {}, zero padding width: {}'.format(val_from val_to zfill)<block_end>self.controller.add_attr(label=label node_view=self attr_class=model.RangeAttr start=val_from end=val_to+1 zfill=zfill)<line_sep>self.cancel_custom_num_window()<block_end><block_end><def_stmt>open_date_dlg self<block_start>'''Open a popup for defining a range of dates
'''<line_sep>self.custom_num_window=Tk.Toplevel()<line_sep>self.custom_num_window.withdraw()<line_sep>self.custom_num_window.title('{}: Date Selection'.format(self.title))<line_sep>self.custom_num_window.resizable(width=<false> height=<false>)<line_sep>frame=Tk.Frame(self.custom_num_window)<line_sep>lb=Tk.Label(frame text='Select Dates to {}'.format(self.title))<line_sep>lb.pack(fill='both' side='top')<line_sep># Boxes for inputting the start and endpoints
sp_box=Tk.Frame(frame)<line_sep>lb1=Tk.Label(sp_box text='From')<line_sep>lb1.pack(side='left' padx=5)<line_sep>cur_year=datetime.date.today().year<line_sep>self.sp_from=Tk.Spinbox(sp_box width=12 from_=1950 to=cur_year)<line_sep>self.sp_from.pack(side='left')<line_sep>lb2=Tk.Label(sp_box text='To')<line_sep>lb2.pack(side='left' padx=(50 5))<line_sep>var=Tk.IntVar()<line_sep>var.set(str(cur_year))<line_sep>self.sp_to=Tk.Spinbox(sp_box width=12 from_=1950 to=cur_year textvariable=var)<line_sep>self.sp_to.pack(side='right')<line_sep>sp_box.pack(fill='both' side='top' padx=30 pady=20)<line_sep># Choose how the dates are formatted (mmddyyyy etc.)
drop_down=Tk.OptionMenu(frame self.date_format *DATE_FORMATS)<line_sep>drop_down.configure(width=max(map(len DATE_FORMATS))+4)<line_sep>self.date_format.set('mmddyy')<line_sep>drop_down.pack(side='top')<line_sep>self.date_zero_padding=Tk.IntVar()<line_sep>checkbutton=Tk.Checkbutton(frame text='Leading zero on single-digit d or m' relief=Tk.FLAT variable=self.date_zero_padding)<line_sep>checkbutton.pack()<line_sep># Ok and cancel buttons
btn_box=Tk.Frame(frame)<line_sep>btn_cancel=Tk.Button(btn_box text='Cancel' command=self.cancel_custom_num_window)<line_sep>btn_cancel.pack(side='right' padx=10 pady=20)<line_sep>btn_ok=Tk.Button(btn_box text='Ok' command=self.on_ok_date_window)<line_sep>btn_ok.pack(side='left' padx=10 pady=20)<line_sep>btn_box.pack()<line_sep>frame.pack(fill='both' padx=10 pady=10)<line_sep>center_window(self.custom_num_window self.main.master)<line_sep>self.custom_num_window.focus_set()<block_end><def_stmt>on_ok_date_window self<block_start>'''Ok was pressed, add the date range attribute
'''<line_sep>year_limits=[1 3000]<try_stmt><block_start>val_from=int(self.sp_from.get())<line_sep>val_to=int(self.sp_to.get())<block_end><except_stmt>ValueError<block_start>tkinter.messagebox.showerror('Invalid Value' '"From" year and "To" year must both be integers' parent=self.main)<line_sep><return><block_end><if_stmt>val_from<g>val_to<block_start>tkinter.messagebox.showerror('Invalid Value' '"From" year must be less than or equal to "To" year' parent=self.main)<block_end><elif_stmt>val_to-val_from<g>200<block_start>tkinter.messagebox.showerror('Invalid Value' 'Distance between "From" year and "To" year must be 200 or less' parent=self.main)<block_end><elif_stmt>val_from<l>year_limits[0]<or>val_to<g>year_limits[1]<block_start>tkinter.messagebox.showerror('Invalid Range' 'The year must be between {} and {}'.format(*year_limits) parent=self.main)<block_end><else_stmt><block_start>label='Date: {} - {}, format: {}, {}'.format(val_from val_to self.date_format.get() ['no leading zero' 'with leading zero'][self.date_zero_padding.get()<eq>1])<line_sep>self.controller.add_attr(label=label node_view=self attr_class=model.DateRangeAttr start_year=val_from end_year=val_to+1 format=self.date_format.get() zero_padding=self.date_zero_padding.get()<eq>1 controller=self.controller)<line_sep>self.cancel_custom_num_window()<block_end><block_end><def_stmt>open_special_dlg self<block_start>'''Open a popup for selecting special characters
'''<line_sep>self.special_dlg=Tk.Toplevel()<line_sep>self.special_dlg.withdraw()<line_sep>self.special_dlg.title('Select Special Characters')<line_sep>self.special_dlg.resizable(width=<false> height=<false>)<line_sep>frame=Tk.Frame(self.special_dlg)<line_sep>lb=Tk.Label(frame text='Select Special Characters'.format(self.title))<line_sep>lb.pack(fill='both' side='top')<line_sep>box=Tk.Frame(frame)<line_sep>self.chk_special=[]<line_sep>max_column_checks=15<for_stmt>v,val enumerate(SPECIAL_CHARACTERS)<block_start>var=Tk.IntVar()<line_sep>tmp=Tk.Checkbutton(box text=val relief=Tk.FLAT variable=var)<line_sep>self.chk_special.append(var)<line_sep>tmp.grid(row=v%max_column_checks column=v<floordiv>max_column_checks sticky='W' padx=10)<block_end>box.pack(fill='both' side='top' padx=30 pady=20)<line_sep># Ok and Cancel buttons
btn_box=Tk.Frame(frame)<line_sep>btn_cancel=Tk.Button(btn_box text='Cancel' command=self.cancel_special)<line_sep>btn_cancel.pack(side='right' padx=10 pady=20)<line_sep>btn_ok=Tk.Button(btn_box text='Ok' command=self.on_ok_special_dlg)<line_sep>btn_ok.pack(side='left' padx=10 pady=20)<line_sep>btn_box.pack()<line_sep>frame.pack(fill='both' padx=60 pady=10)<line_sep>center_window(self.special_dlg self.main.master)<line_sep>self.special_dlg.focus_set()<block_end><def_stmt>cancel_special self *args<block_start><if_stmt>self.special_dlg<block_start>self.special_dlg.destroy()<line_sep>self.special_dlg=<none><block_end><block_end><def_stmt>on_ok_special_dlg self *args<block_start>'''Ok was pressed, add the special character attribute
'''<line_sep>checked_vals=[SPECIAL_CHARACTERS[i]<for>i range(len(SPECIAL_CHARACTERS))<if>self.chk_special[i].get()<eq>1]<if_stmt>len(checked_vals)<g>0<block_start>label='Special Characters: {}'.format(' '.join(checked_vals))<line_sep>self.controller.add_attr(label=label node_view=self attr_class=model.StringListAttr strings=checked_vals)<block_end>self.cancel_special()<block_end><block_end> |
# -*- coding: utf-8 -*-
<import_stmt>re<import_stmt>unittest<import_from_stmt>xml.etree ElementTree<import_from_stmt>macropy.case_classes macros case<import_from_stmt>macropy.experimental.pyxl_strings macros p# noqa: F811
<import_from_stmt>macropy.tracing macros require# noqa: F811, F401
<import_from_stmt>pyxl html# noqa: F401
<def_stmt>normalize string<block_start><return>ElementTree.tostring(ElementTree.fromstring(re.sub("\n *" "" string)) encoding='utf8' method='xml')<block_end><class_stmt>Tests(unittest.TestCase)<block_start><def_stmt>test_inline_python self<block_start>image_name="bolton.png"<line_sep>image=p['<img src="/static/images/{image_name}" />']<line_sep>text="<NAME>"<line_sep>block=p['<div>{image}{text}</div>']<line_sep>element_list=[image text]<line_sep>block2=p['<div>{element_list}</div>']<with_stmt>require<block_start>block2.to_string()<eq>'<div><img src="/static/images/bolton.png" /><NAME></div>'<block_end><block_end><def_stmt>test_dynamic self<block_start>items=['Puppies' 'Dragons']<line_sep>nav=p['<ul />']<for_stmt>text items<block_start>nav.append(p['<li>{text}</li>'])<block_end><with_stmt>require<block_start>str(nav)<eq>"<ul><li>Puppies</li><li>Dragons</li></ul>"<block_end><block_end><def_stmt>test_attributes self<block_start>fruit=p['<div data-text="tangerine" />']<with_stmt>require<block_start>fruit.data_text<eq>"tangerine"<block_end>fruit.set_attr('data-text' 'clementine')<with_stmt>require<block_start>fruit.attr('data-text')<eq>"clementine"<block_end><block_end><def_stmt>test_interpreter self<block_start>safe_value="<b>Puppies!</b>"<line_sep>unsafe_value="<script>bad();</script>"<line_sep>unsafe_attr='">'<line_sep>pyxl_blob=p["""<div class="{unsafe_attr}">
{unsafe_value}
{rawhtml(safe_value)}
</div>"""]<line_sep>target_blob='<div class="">"><script>bad();</script> <b>Puppies!</b></div>'<with_stmt>require<block_start>normalize(pyxl_blob.to_string())<eq>normalize(target_blob)<block_end><block_end><def_stmt>test_modules self<block_start><import_from_stmt>pyxl.element x_element<line_sep>@case<class_stmt>User(name profile_picture)<block_start><pass><block_end><class_stmt>x_user_badge(x_element)<block_start>__attrs__={'user':object }<def_stmt>render self<block_start><return>p["""
<div>
<img src="{self.user.profile_picture}" style="float: left; margin-right: 10px;"/>
<div style="display: table-cell;">
<div>{self.user.name}</div>
{self.children()}
</div>
</div>"""]<block_end><block_end>user=User("cowman" "http:/www.google.com")<line_sep>content=p['<div>Any arbitrary content...</div>']<line_sep>pyxl_blob=p['<user_badge user="{user}">{content}</user_badge>']<line_sep>target_blob="""
<div>
<img src="http:/www.google.com" style="float: left; margin-right: 10px;" />
<div style="display: table-cell;"><div>cowman</div>
<div>Any arbitrary content...</div></div>
</div>"""<with_stmt>require<block_start>normalize(pyxl_blob.to_string())<eq>normalize(target_blob)<block_end><block_end><block_end> |
<import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep>process=cms.Process("CastorProducts")<line_sep>process.load("FWCore.MessageLogger.MessageLogger_cfi")<line_sep># specify the correct database tags which contain the updated gains and channelquality flags
process.load("CondCore.DBCommon.CondDBSetup_cfi")<line_sep>process.CastorDbProducer=cms.ESProducer("CastorDbProducer")<line_sep>process.es_pool=cms.ESSource("PoolDBESSource" process.CondDBSetup timetype=cms.string('runnumber') connect=cms.string('frontier://cmsfrontier.cern.ch:8000/FrontierProd/CMS_COND_31X_HCAL') authenticationMethod=cms.untracked.uint32(0) toGet=cms.VPSet(cms.PSet(record=cms.string('CastorPedestalsRcd') tag=cms.string('CastorPedestals_v2.0_offline')) cms.PSet(record=cms.string('CastorPedestalWidthsRcd') tag=cms.string('CastorPedestalWidths_v2.0_offline')) cms.PSet(record=cms.string('CastorGainsRcd') tag=cms.string('CastorGains_v2.0_offline')) cms.PSet(record=cms.string('CastorGainWidthsRcd') tag=cms.string('CastorGainWidths_v2.0_offline')) cms.PSet(record=cms.string('CastorQIEDataRcd') tag=cms.string('CastorQIEData_v2.0_offline')) cms.PSet(record=cms.string('CastorChannelQualityRcd') tag=cms.string('CastorChannelQuality_v2.0_offline')) cms.PSet(record=cms.string('CastorElectronicsMapRcd') tag=cms.string('CastorElectronicsMap_v2.0_offline'))))<line_sep># end of Db configuration
process.maxEvents=cms.untracked.PSet(input=cms.untracked.int32(-1))<line_sep>process.source=cms.Source("PoolSource" duplicateCheckMode=cms.untracked.string("noDuplicateCheck") fileNames=cms.untracked.vstring('file:data_RAW2DIGI_L1Reco_RECO.root'# choose your input file here
))<line_sep># load CASTOR default reco chain (from towers on)
process.load('RecoLocalCalo.Castor.Castor_cff')<line_sep># construct the module which executes the RechitCorrector for data reconstructed in releases < 4.2.X
process.rechitcorrector=cms.EDProducer("RecHitCorrector" rechitLabel=cms.InputTag("castorreco" "" "RECO") # choose the original RecHit collection
revertFactor=cms.double(62.5) # this is the factor to go back to the original fC: 1/0.016
doInterCalib=cms.bool(<true>)# do intercalibration
)<line_sep># construct the module which executes the RechitCorrector for data reconstructed in releases >= 4.2.X
process.rechitcorrector42=cms.EDProducer("RecHitCorrector" rechitLabel=cms.InputTag("castorreco" "" "RECO") # choose the original RecHit collection
revertFactor=cms.double(1) # this is the factor to go back to the original fC - not needed when data is already intercalibrated
doInterCalib=cms.bool(<false>)# don't do intercalibration, RecHitCorrector will only correct the EM response and remove BAD channels
)<line_sep># tell to the CastorCell reconstruction that he should use the new corrected rechits for releases < 4.2.X
#process.CastorCellReco.inputprocess = "rechitcorrector"
# tell to the CastorTower reconstruction that he should use the new corrected rechits for releases >= 4.2.X
process.CastorTowerReco.inputprocess="rechitcorrector"<line_sep>process.MyOutputModule=cms.OutputModule("PoolOutputModule" fileName=cms.untracked.string('rechitcorrector_output.root')# choose your output file
)<line_sep># execute the rechitcorrector and afterwards do the reco chain again (towers -> jets)
process.producer=cms.Path(process.rechitcorrector<times>process.CastorFullReco)<line_sep>process.end=cms.EndPath(process.MyOutputModule)<line_sep> |
<import_from_stmt>river metrics utils<import_from_stmt>river.metrics.multioutput.base MultiOutputMetric<line_sep>__all__=["MicroAverage"]<class_stmt>MicroAverage(MultiOutputMetric metrics.base.WrapperMetric)<block_start>"""Micro-average wrapper.
The provided metric is updated with the value of each output.
Parameters
----------
metric
A classification or a regression metric.
"""<def_stmt>__init__ self metric<block_start>self._metric=metric<block_end>@property<def_stmt>metric self<block_start><return>self._metric<block_end><def_stmt>works_with self model<arrow>bool<block_start><if_stmt>isinstance(self.metric metrics.base.ClassificationMetric)<block_start><return>utils.inspect.ismoclassifier(model)<block_end><return>utils.inspect.ismoregressor(model)<block_end><def_stmt>update self y_true y_pred sample_weight=1.0<block_start><for_stmt>i y_pred<block_start>self.metric.update(y_true[i] y_pred[i] sample_weight)<block_end><return>self<block_end><def_stmt>revert self y_true y_pred sample_weight=1.0<block_start><for_stmt>i y_pred<block_start>self.metric.revert(y_true[i] y_pred[i] sample_weight)<block_end><return>self<block_end><def_stmt>get self<block_start><return>self.metric.get()<block_end><block_end> |
<import_from_stmt>functools reduce wraps<import_stmt>re<import_from_stmt>tasklib TaskWarrior<import_from_stmt>taskwiki constants<import_from_stmt>taskwiki regexp<def_stmt>complete_last_word f<block_start>@wraps(f)<def_stmt>wrapper self arglead<block_start>before,sep,after=arglead.rpartition(' ')<line_sep>comps=f(self after)<if_stmt>comps<block_start><return>[before+sep+comp<for>comp comps]<block_end><else_stmt><block_start><return>[]<block_end><block_end><return>wrapper<block_end># TODO(2023-06-27): use functools once python 3.7 is EOL
<def_stmt>cached_property f<block_start>@wraps(f)<def_stmt>wrapper self<block_start>k='_cache_'+f.__name__<if_stmt>k<in>self.__dict__<block_start><return>self.__dict__[k]<block_end><else_stmt><block_start>v=f(self)<line_sep>self.__dict__[k]=v<line_sep><return>v<block_end><block_end><return>wrapper<block_end># "must*opt" -> "must(o(p(t)?)?)?"
<def_stmt>prefix_regex s<block_start>must,_,opt=s.partition('*')<line_sep><return>must+reduce(<lambda>y x:f"({x}{y})?" reversed(opt) '')<block_end>RE_PROJECT=re.compile(prefix_regex('pro*ject'))<line_sep>RE_DATE=re.compile('|'.join([prefix_regex(r)<for>r "du*e un*til wa*it ent*ry end st*art sc*heduled".split()]))<line_sep>RE_RECUR=re.compile(prefix_regex('re*cur'))<class_stmt>Completion()<block_start><def_stmt>__init__ self tw<block_start>self.tw=tw<block_end>@cached_property<def_stmt>_attributes self<block_start><return>sorted(self.tw.execute_command(['_columns']))<block_end>@cached_property<def_stmt>_tags self<block_start><if_stmt>self.tw.version<l>TaskWarrior.VERSION_2_4_5<block_start><return>sorted(self.tw.execute_command(['_tags']))<block_end><else_stmt><block_start><return>sorted(set(tag<for>tags self.tw.execute_command(['_unique' 'tag'])<for>tag tags.split(',')))<block_end><block_end>@cached_property<def_stmt>_projects self<block_start><if_stmt>self.tw.version<l>TaskWarrior.VERSION_2_4_5<block_start><return>sorted(self.tw.execute_command(['_projects']))<block_end><else_stmt><block_start><return>sorted(self.tw.execute_command(['_unique' 'project']))<block_end><block_end><def_stmt>_complete_any self w<block_start><if_stmt>w<block_start><return>[]<block_end><return>['+' '-']+[attr+':'<for>attr self._attributes()]<block_end><def_stmt>_complete_attributes self w<block_start><if_stmt><not>w.isalpha()<block_start><return>[]<block_end><return>[attr+':'<for>attr self._attributes()<if>attr.startswith(w)]<block_end><def_stmt>_complete_tags self w<block_start><if_stmt><not>w<or>w[0]<not><in>['+' '-']<block_start><return>[]<block_end>t=w[1:]<line_sep><return>[w[0]+tag<for>tag self._tags()<if>tag.startswith(t)]<block_end><def_stmt>_comp_words self w pattern words<block_start>before,sep,after=w.partition(':')<if_stmt><not>sep<or><not>re.fullmatch(pattern before)<block_start><return>[]<block_end><return>[before+sep+word<for>word words()<if>word.startswith(after)]<block_end><def_stmt>_complete_projects self w<block_start><return>self._comp_words(w RE_PROJECT self._projects)<block_end><def_stmt>_complete_dates self w<block_start><return>self._comp_words(w RE_DATE <lambda>:constants.COMPLETION_DATE)<block_end><def_stmt>_complete_recur self w<block_start><return>self._comp_words(w RE_RECUR <lambda>:constants.COMPLETION_RECUR)<block_end>@complete_last_word<def_stmt>modify self w<block_start><return>self._complete_any(w)<or>self._complete_attributes(w)<or>self._complete_projects(w)<or>self._complete_tags(w)<or>self._complete_dates(w)<or>self._complete_recur(w)<or>[]<block_end><def_stmt>omni_modstring_findstart self line<block_start>m=re.search(regexp.GENERIC_TASK line)<line_sep>bline=line.encode("utf-8")# omni findstart needs byte offset
<if_stmt>m<and><not>m.group('uuid')<and>b' -- '<in>bline<block_start><return>bline.rfind(b' ')+1<block_end><else_stmt><block_start><return>-1<block_end><block_end><def_stmt>omni_modstring self w<block_start><return>self._complete_any(w)<or>self._complete_attributes(w)<or>self._complete_projects(w)<or>self._complete_tags(w)<or>self._complete_dates(w)<or>self._complete_recur(w)<or>[]<block_end><block_end> |
# Import installed packages
# Import app code
<import_from_stmt>app.main app<import_from_stmt>app.core config<import_from_stmt>app.db.flask_session db_session<import_from_stmt>.api_docs docs<import_from_stmt>.endpoints role<import_from_stmt>.endpoints token<import_from_stmt>.endpoints user<import_from_stmt>.endpoints utils<line_sep> |
"""
警察vs土匪
"""<class_stmt>Gun(object)<block_start><def_stmt>__init__ self model damage# 型号
<block_start>self.model=model<line_sep># 杀伤力
self.damage=damage<line_sep># 子弹数量,默认为0
self.bullet_count=0<block_end># 重写str
<def_stmt>__str__ self<block_start><return>"型号:%s, 杀伤力:%s, 子弹数量:%s"%(self.model self.damage self.bullet_count)<block_end># 填充子弹
<def_stmt>add_bullets self bullet_count<block_start>self.bullet_count<augadd>bullet_count<line_sep>print("填充子弹完成,当前数量为:%s"%bullet_count)<block_end># gun发射子弹打击土匪
<def_stmt>shoot self enemy# 判断当前枪是否有子弹
<block_start><if_stmt>self.bullet_count<le>0<block_start>print("%s 没有子弹, 请填充子弹"%self.model)<block_end><else_stmt># 如果有子弹,更新子弹数量
<block_start>self.bullet_count<augsub>1<line_sep># 判断是否击中土匪
<if_stmt>enemy<is><not><none><block_start>enemy.hurt(self)<block_end>print("发射了一颗子弹 %s 剩余子弹:%d"%(self.model self.bullet_count))<block_end><block_end><block_end><class_stmt>Player(object)<block_start><def_stmt>__init__ self name hp=100# 玩家名字
<block_start>self.name=name<line_sep># 血量
self.hp=hp<line_sep># 使用的枪械
self.gun=<none><block_end><def_stmt>__str__ self# 如果土匪的学量小于0
<block_start><if_stmt>self.hp<le>0<block_start><return>"%s 已经挂掉了..."%self.name<block_end><else_stmt># 没枪是土匪,只有警察有枪
<block_start><if_stmt>self.gun<is><none><block_start><return>"%s [%d]没有佩戴枪"%(self.name self.hp)<block_end><else_stmt><block_start><return>"%s [%d] 枪:%s"%(self.name self.hp self.gun)<block_end><block_end><block_end># 土匪受伤的方法
<def_stmt>hurt self enemy_gun# 击中更新血量
<block_start>self.hp<augsub>enemy_gun.damage<line_sep># 判断剩余血量
<if_stmt>self.hp<le>0<block_start>print("%s 已经挂掉了..."%self.name)<block_end><else_stmt><block_start>print("%s 被 %s 击中,剩余血量: %d"%(self.name enemy_gun.model self.hp))<block_end><block_end># 警察开火
<def_stmt>fire self enemy# 警察判断自己有无武器
<block_start><if_stmt>self.gun<is><none><block_start>print("%s 没有佩戴枪, 请佩戴枪"%self.name)<line_sep><return><block_end># 判断有无子弹
<if_stmt>self.gun.bullet_count<le>0# 自动填充子弹
<block_start>self.gun.add_bullets(10)<block_end># 射击土匪
self.gun.shoot(enemy)<line_sep>print("%s 正在向 %s 开火..."%(self.name enemy.name))<block_end><block_end># 测试main()函数
<def_stmt>main # 创建一个警察
<block_start>police_man=Player("警察")<line_sep># 创建一个土匪
bad_man=Player("土匪" 70)<line_sep># 枪打土匪(无枪)
police_man.fire(bad_man)<line_sep># 使用枪类创建一把AK47
ak47=Gun("AK47" 50)<line_sep># 给警察配枪
police_man.gun=ak47<line_sep># 枪打土匪(有枪)
police_man.fire(bad_man)<line_sep>police_man.fire(bad_man)<line_sep># # 填充子弹
# ak47.add_bullets(50)
<block_end>main()<line_sep> |
<import_from_stmt>PIL ImageOps Image<import_stmt>os<line_sep>image_dict={"Satyr":{"base_path":"../images/satyr/PNG/" "Attacking":"/reference/Attacking/attack.png" "Taunt":"/reference/Taunt/taunt.png" "Walking":"/reference/Walking/walking.png" "Dying":"/reference/Dying/dying.png" "Hurt":"/reference/Hurt/hurt.png" "Idle":"/reference/Idle/idle.png"} "Golem":{"base_path":"../images/golem/PNG/" "Attacking":"/reference/Attacking/attack.png" "Taunt":"/reference/Taunt/taunt.png" "Walking":"/reference/Walking/walking.png" "Dying":"/reference/Dying/dying.png" "Hurt":"/reference/Hurt/hurt.png" "Idle":"/reference/Idle/idle.png"}}<def_stmt>get_concat_h im1 im2<block_start>dst=Image.new('RGB' (im1.width+im2.width im1.height))<line_sep>dst.paste(im1 (0 0))<line_sep>dst.paste(im2 (im1.width 0))<line_sep><return>dst<block_end><def_stmt>draw_duel actor reactor<block_start>'''
Loading variables.
'''<line_sep>act_name=actor["name"]<line_sep>rct_name=reactor["name"]<line_sep>action=actor["action"]<line_sep>reaction=reactor["reaction"]<line_sep>act_type=actor["type"]<line_sep>rct_type=reactor["type"]<line_sep>img1=Image.open(image_dict[act_name]["base_path"]+act_type+image_dict[act_name][action])<line_sep>img2=Image.open(image_dict[rct_name]["base_path"]+rct_type+image_dict[rct_name][reaction])<line_sep>#Flipping the reactor to give the feel of a duel.
img2=ImageOps.mirror(img2)<line_sep><return>get_concat_h(img1 img2) img1 img2<block_end> |
<import_from_stmt>..models db<class_stmt>OAuth2Token(db.Model)<block_start>id=db.Column(db.Integer() primary_key=<true>)<line_sep>name=db.Column(db.String(40))<line_sep>token_type=db.Column(db.String(40))<line_sep>access_token=db.Column(db.String(200))<line_sep>refresh_token=db.Column(db.String(200))<line_sep>expires_at=db.Column(db.Integer())<line_sep>user_id=db.Column(db.Integer() db.ForeignKey("user.id"))<line_sep>user=db.relationship("User" backref=db.backref("tokens" lazy="dynamic"))<def_stmt>to_token self<block_start><return>dict(access_token=self.access_token token_type=self.token_type refresh_token=self.refresh_token expires_at=self.expires_at )<block_end><block_end> |
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing the unit tests for handle_changes_stages."""<import_from_future_stmt> print_function<import_stmt>itertools<import_stmt>mock<import_from_stmt>chromite.cbuildbot relevant_changes<import_from_stmt>chromite.cbuildbot.stages handle_changes_stages<import_from_stmt>chromite.cbuildbot.stages generic_stages<import_from_stmt>chromite.cbuildbot.stages generic_stages_unittest<import_from_stmt>chromite.cbuildbot.stages sync_stages<import_from_stmt>chromite.lib builder_status_lib<import_from_stmt>chromite.lib cidb<import_from_stmt>chromite.lib clactions<import_from_stmt>chromite.lib config_lib<import_from_stmt>chromite.lib constants<import_from_stmt>chromite.lib fake_cidb<import_from_stmt>chromite.lib hwtest_results<import_from_stmt>chromite.lib timeout_util<import_from_stmt>chromite.lib tree_status<import_from_stmt>chromite.lib.const waterfall<line_sep># pylint: disable=protected-access
<class_stmt>CommitQueueHandleChangesStageTests(generic_stages_unittest.AbstractStageTestCase)<block_start>"""Tests for CommitQueueHandleChangesStag."""<line_sep>BOT_ID='master-paladin'<def_stmt>setUp self<block_start>self._Prepare()<line_sep>self.partial_submit_changes=['A' 'B']<line_sep>self.other_changes=['C' 'D']<line_sep>self.changes=self.other_changes+self.partial_submit_changes<line_sep>self.PatchObject(builder_status_lib 'GetFailedMessages')<line_sep>self.PatchObject(relevant_changes.RelevantChanges '_GetSlaveMappingAndCLActions' return_value=(dict() []))<line_sep>self.PatchObject(clactions 'GetRelevantChangesForBuilds')<line_sep>self.PatchObject(tree_status 'WaitForTreeStatus' return_value=constants.TREE_OPEN)<line_sep>self.PatchObject(relevant_changes.RelevantChanges 'GetPreviouslyPassedSlavesForChanges')<line_sep>self.mock_record_metrics=self.PatchObject(handle_changes_stages.CommitQueueHandleChangesStage '_RecordSubmissionMetrics')<line_sep>self.sync_stage=self._MockSyncStage()<line_sep>self.completion_stage=mock.Mock()<block_end><def_stmt>tearDown self<block_start>cidb.CIDBConnectionFactory.ClearMock()<block_end><def_stmt>_MockSyncStage self tree_was_open=<true><block_start>sync_stage=sync_stages.CommitQueueSyncStage(self._run)<line_sep>sync_stage.pool=mock.MagicMock()<line_sep>sync_stage.pool.applied=self.changes<line_sep>sync_stage.pool.tree_was_open=tree_was_open<line_sep>sync_stage.pool.handle_failure_mock=self.PatchObject(sync_stage.pool 'HandleValidationFailure')<line_sep>sync_stage.pool.handle_timeout_mock=self.PatchObject(sync_stage.pool 'HandleValidationTimeout')<line_sep>sync_stage.pool.submit_pool_mock=self.PatchObject(sync_stage.pool 'SubmitPool')<line_sep><return>sync_stage<block_end># pylint: disable=W0221
<def_stmt>ConstructStage self sync_stage=<none> completion_stage=<none><block_start>sync_stage=sync_stage<or>self.sync_stage<line_sep>completion_stage=completion_stage<or>self.completion_stage<line_sep><return>handle_changes_stages.CommitQueueHandleChangesStage(self._run sync_stage completion_stage)<block_end><def_stmt>test_GetBuildsPassedSyncStage self<block_start>"""Test _GetBuildsPassedSyncStage."""<line_sep>stage=self.ConstructStage()<line_sep>mock_cidb=mock.Mock()<line_sep>mock_cidb.GetSlaveStages.return_value=[{'build_config':'s_1' 'status':'pass' 'name':'CommitQueueSync'} {'build_config':'s_2' 'status':'pass' 'name':'CommitQueueSync'} {'build_config':'s_3' 'status':'fail' 'name':'CommitQueueSync'}]<line_sep>mock_cidb.GetBuildStages.return_value=[{'status':'pass' 'name':'CommitQueueSync'}]<line_sep>builds=stage._GetBuildsPassedSyncStage('build_id' mock_cidb ['id_1' 'id_2'])<line_sep>self.assertItemsEqual(builds ['s_1' 's_2' 'master-paladin'])<block_end><def_stmt>_MockPartialSubmit self stage<block_start>self.PatchObject(relevant_changes.RelevantChanges 'GetRelevantChangesForSlaves' return_value={'master-paladin':{mock.Mock()}})<line_sep>self.PatchObject(relevant_changes.RelevantChanges 'GetSubsysResultForSlaves')<line_sep>self.PatchObject(handle_changes_stages.CommitQueueHandleChangesStage '_GetBuildsPassedSyncStage')<line_sep>stage.sync_stage.pool.SubmitPartialPool.return_value=self.changes<block_end><def_stmt>testHandleCommitQueueFailureWithOpenTree self<block_start>"""Test _HandleCommitQueueFailure with open tree."""<line_sep>stage=self.ConstructStage()<line_sep>self._MockPartialSubmit(stage)<line_sep>self.PatchObject(tree_status 'WaitForTreeStatus' return_value=constants.TREE_OPEN)<line_sep>self.PatchObject(generic_stages.BuilderStage 'GetScheduledSlaveBuildbucketIds' return_value=[])<line_sep>stage._HandleCommitQueueFailure(set(['test1']) set() set() <false>)<line_sep>stage.sync_stage.pool.handle_failure_mock.assert_called_once_with(mock.ANY sanity=<true> no_stat=set() changes=self.changes failed_hwtests=<none>)<block_end><def_stmt>testHandleCommitQueueFailureWithThrottledTree self<block_start>"""Test _HandleCommitQueueFailure with throttled tree."""<line_sep>stage=self.ConstructStage()<line_sep>self._MockPartialSubmit(stage)<line_sep>self.PatchObject(tree_status 'WaitForTreeStatus' return_value=constants.TREE_THROTTLED)<line_sep>self.PatchObject(generic_stages.BuilderStage 'GetScheduledSlaveBuildbucketIds' return_value=[])<line_sep>stage._HandleCommitQueueFailure(set(['test1']) set() set() <false>)<line_sep>stage.sync_stage.pool.handle_failure_mock.assert_called_once_with(mock.ANY sanity=<false> no_stat=set() changes=self.changes failed_hwtests=<none>)<block_end><def_stmt>testHandleCommitQueueFailureWithClosedTree self<block_start>"""Test _HandleCommitQueueFailure with closed tree."""<line_sep>stage=self.ConstructStage()<line_sep>self._MockPartialSubmit(stage)<line_sep>self.PatchObject(tree_status 'WaitForTreeStatus' side_effect=timeout_util.TimeoutError())<line_sep>self.PatchObject(generic_stages.BuilderStage 'GetScheduledSlaveBuildbucketIds' return_value=[])<line_sep>stage._HandleCommitQueueFailure(set(['test1']) set() set() <false>)<line_sep>stage.sync_stage.pool.handle_failure_mock.assert_called_once_with(mock.ANY sanity=<false> no_stat=set() changes=self.changes failed_hwtests=<none>)<block_end><def_stmt>testHandleCommitQueueFailureWithFailedHWtests self<block_start>"""Test _HandleCommitQueueFailure with failed HWtests."""<line_sep>stage=self.ConstructStage()<line_sep>self._MockPartialSubmit(stage)<line_sep>master_build_id=stage._run.attrs.metadata.GetValue('build_id')<line_sep>db=fake_cidb.FakeCIDBConnection()<line_sep>slave_build_id=db.InsertBuild('slave_1' waterfall.WATERFALL_INTERNAL 1 'slave_1' 'bot_hostname' master_build_id=master_build_id buildbucket_id='123')<line_sep>cidb.CIDBConnectionFactory.SetupMockCidb(db)<line_sep>mock_failed_hwtests=mock.Mock()<line_sep>mock_get_hwtests=self.PatchObject(hwtest_results.HWTestResultManager 'GetFailedHWTestsFromCIDB' return_value=mock_failed_hwtests)<line_sep>self.PatchObject(tree_status 'WaitForTreeStatus' return_value=constants.TREE_OPEN)<line_sep>self.PatchObject(generic_stages.BuilderStage 'GetScheduledSlaveBuildbucketIds' return_value=['123'])<line_sep>stage._HandleCommitQueueFailure(set(['test1']) set() set() <false>)<line_sep>stage.sync_stage.pool.handle_failure_mock.assert_called_once_with(mock.ANY sanity=<true> no_stat=set() changes=self.changes failed_hwtests=mock_failed_hwtests)<line_sep>mock_get_hwtests.assert_called_once_with(db [slave_build_id])<block_end><def_stmt>VerifyStage self failing inflight no_stat handle_failure=<false> handle_timeout=<false> sane_tot=<true> stage=<none> all_slaves=<none> slave_stages=<none> fatal=<true> self_destructed=<false><block_start>"""Runs and Verifies PerformStage.
Args:
failing: The names of the builders that failed.
inflight: The names of the buiders that timed out.
no_stat: The names of the builders that had no status.
handle_failure: If True, calls HandleValidationFailure.
handle_timeout: If True, calls HandleValidationTimeout.
sane_tot: If not true, assumes TOT is not sane.
stage: If set, use this constructed stage, otherwise create own.
all_slaves: Optional set of all slave configs.
slave_stages: Optional list of slave stages.
fatal: Optional boolean indicating whether the completion_stage failed
with fatal. Default to True.
self_destructed: Optional boolean indicating whether the completion_stage
self_destructed. Default to False.
"""<if_stmt><not>stage<block_start>stage=self.ConstructStage()<block_end>stage._run.attrs.metadata.UpdateWithDict({constants.SELF_DESTRUCTED_BUILD:self_destructed})<line_sep># Setup the stage to look at the specified configs.
all_slaves=list(all_slaves<or>set(failing+inflight+no_stat))<line_sep>all_started_slaves=list(all_slaves<or>set(failing+inflight))<line_sep>configs=[config_lib.BuildConfig(name=x)<for>x all_slaves]<line_sep>self.PatchObject(stage '_GetSlaveConfigs' return_value=configs)<line_sep>statuses={}<for_stmt>x failing<block_start>statuses[x]=builder_status_lib.BuilderStatus(constants.BUILDER_STATUS_FAILED message=<none>)<block_end><for_stmt>x inflight<block_start>statuses[x]=builder_status_lib.BuilderStatus(constants.BUILDER_STATUS_INFLIGHT message=<none>)<block_end><for_stmt>x no_stat<block_start>statuses[x]=builder_status_lib.BuilderStatus(constants.BUILDER_STATUS_MISSING message=<none>)<block_end>self.completion_stage.GetSlaveStatuses.return_value=statuses<line_sep>self.completion_stage.GetFatal.return_value=fatal<line_sep># Setup DB and provide list of slave stages.
mock_cidb=mock.MagicMock()<line_sep>cidb.CIDBConnectionFactory.SetupMockCidb(mock_cidb)<if_stmt>slave_stages<is><none><block_start>slave_stages=[]<line_sep>critical_stages=(relevant_changes.TriageRelevantChanges.STAGE_SYNC)<for_stmt>stage_name,slave itertools.product(critical_stages all_started_slaves)<block_start>slave_stages.append({'name':stage_name 'build_config':slave 'status':constants.BUILDER_STATUS_PASSED})<block_end><block_end>self.PatchObject(mock_cidb 'GetSlaveStages' return_value=slave_stages)<line_sep># Set up SubmitPartialPool to provide a list of changes to look at.
self.PatchObject(stage.sync_stage.pool 'SubmitPartialPool' return_value=self.other_changes)<line_sep># Actually run the stage.
stage.PerformStage()<if_stmt>fatal<block_start>stage.sync_stage.pool.submit_pool_mock.assert_not_called()<line_sep>self.mock_record_metrics.assert_called_once_with(<false>)<block_end><else_stmt><block_start>stage.sync_stage.pool.submit_pool_mock.assert_called_once_with(reason=constants.STRATEGY_CQ_SUCCESS)<line_sep>self.mock_record_metrics.assert_called_once_with(<true>)<block_end><if_stmt>handle_failure<block_start>stage.sync_stage.pool.handle_failure_mock.assert_called_once_with(mock.ANY no_stat=set(no_stat) sanity=sane_tot changes=self.other_changes failed_hwtests=mock.ANY)<block_end><if_stmt>handle_timeout<block_start>stage.sync_stage.pool.handle_timeout_mock.assert_called_once_with(sanity=mock.ANY changes=self.other_changes)<block_end><block_end><def_stmt>testCompletionSuccess self<block_start>"""Verify stage when the completion_stage succeeded."""<line_sep>self.VerifyStage([] [] [] fatal=<false>)<block_end><def_stmt>testCompletionWithInflightSlaves self<block_start>"""Verify stage when the completion_stage failed with inflight slaves."""<line_sep>self.VerifyStage([] ['foo'] [] handle_timeout=<true>)<block_end><def_stmt>testCompletionSelfDestructedWithInflightSlaves self<block_start>"""Verify stage when the completion_stage self_destructed with inflight."""<line_sep>self.VerifyStage([] ['foo'] [] self_destructed=<true> handle_failure=<true>)<block_end><def_stmt>testCompletionSelfDestructedWithFailingSlaves self<block_start>"""Verify stage when the completion_stage self_destructed with failing."""<line_sep>self.VerifyStage(['foo'] [] [] self_destructed=<true> handle_failure=<true>)<block_end><def_stmt>testCompletionSelfDestructedWithdNoStatSlaves self<block_start>"""Verify stage when the completion_stage self_destructed with no_stat."""<line_sep>self.VerifyStage([] [] ['foo'] self_destructed=<true> handle_failure=<true>)<block_end><block_end> |
# Generated by Django 2.2.7 on 2020-01-15 14:39
<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('web' '0013_auto_20200108_2257') ]<line_sep>operations=[migrations.AlterField(model_name='article' name='src_url' field=models.CharField(max_length=1024 unique=<true> verbose_name='原始链接') ) migrations.AlterField(model_name='article' name='title' field=models.CharField(max_length=200 verbose_name='标题') ) migrations.AlterField(model_name='site' name='creator' field=models.CharField(blank=<true> choices=[('system' '系统录入') ('user' '用户提交') ('wemp' '微信公众号')] db_index=<true> default='system' max_length=20 null=<true> verbose_name='创建人') ) migrations.AlterField(model_name='site' name='link' field=models.CharField(max_length=1024 verbose_name='主页') ) migrations.AlterField(model_name='site' name='rss' field=models.CharField(blank=<true> max_length=1024 null=<true> verbose_name='RSS地址') ) ]<block_end> |
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
<class_stmt>Solution(object)<block_start><def_stmt>copyRandomList self head<block_start>"""
:type head: RandomListNode
:rtype: RandomListNode
"""<if_stmt>head<is><none><block_start><return><none><block_end># append copy node behind its orignal one
# 1 -> 1' -> 2 -> 2' -> .... -> n -> n' -> None
current=head<while_stmt>(current<is><not><none>)<block_start>node=RandomListNode(current.label)<line_sep>node.next=current.next<line_sep>current.next=node<line_sep>current=current.next.next<block_end># copy random pointers
current=head<while_stmt>(current<is><not><none>)<block_start><if_stmt>current.random<is><not><none><block_start>current.next.random=current.random.next<block_end>current=current.next.next<block_end># construct new linked list
new_head=head.next<line_sep>new_cur=new_head<line_sep>old_cur=head<while_stmt>(new_cur<is><not><none>)<block_start>old_cur.next=new_cur.next<if_stmt>new_cur.next<is><not><none><block_start>new_cur.next=new_cur.next.next<block_end>new_cur=new_cur.next<line_sep>old_cur=old_cur.next<block_end><return>new_head<block_end><block_end> |
<import_stmt>unittest<import_stmt>unreal_engine<as>ue<import_from_stmt>unreal_engine.structs ColorMaterialInput Key<import_from_stmt>unreal_engine.structs StaticMeshSourceModel MeshBuildSettings<class_stmt>TestStructs(unittest.TestCase)<block_start><def_stmt>test_new_struct self<block_start>material_input=ColorMaterialInput()<line_sep>self.assertTrue('MaskR'<in>material_input.fields())<block_end><def_stmt>test_new_struct_with_kwargs self<block_start>material_input=ColorMaterialInput(Mask=1 MaskR=1 MaskG=1 MaskB=0 MaskA=1)<line_sep>self.assertEqual(material_input.Mask 1)<line_sep>self.assertEqual(material_input.MaskR 1)<line_sep>self.assertEqual(material_input.MaskG 1)<line_sep>self.assertEqual(material_input.MaskB 0)<line_sep>self.assertEqual(material_input.MaskA 1)<block_end><def_stmt>test_struct_set self<block_start>material_input=ColorMaterialInput()<line_sep>material_input.MaskG=1<line_sep>self.assertEqual(material_input.MaskG 1)<block_end><def_stmt>test_struct_clone self<block_start>material_input=ColorMaterialInput(Mask=1 MaskR=0 MaskG=1 MaskB=0 MaskA=1)<line_sep>material_input2=material_input.clone()<line_sep>self.assertEqual(material_input2.Mask 1)<line_sep>self.assertEqual(material_input2.MaskR 0)<line_sep>self.assertEqual(material_input2.MaskG 1)<line_sep>self.assertEqual(material_input2.MaskB 0)<line_sep>self.assertEqual(material_input2.MaskA 1)<block_end><def_stmt>test_cmp self<block_start>key1=Key(KeyName='SpaceBar')<line_sep>key2=Key(KeyName='SpaceBar')<line_sep>self.assertEqual(key1 key2)<block_end><def_stmt>test_ptr self<block_start>source_model=StaticMeshSourceModel()<line_sep>source_model.BuildSettings.bRecomputeNormals=<false><line_sep>source_model.BuildSettings.bRecomputeTangents=<true><line_sep>source_model.BuildSettings.bUseMikkTSpace=<true><line_sep>source_model.BuildSettings.bBuildAdjacencyBuffer=<true><line_sep>source_model.BuildSettings.bRemoveDegenerates=<true><line_sep>source_model2=source_model.clone()<line_sep>self.assertEqual(source_model2.BuildSettings.bRecomputeNormals <false>)<line_sep>self.assertEqual(source_model2.BuildSettings.bRecomputeTangents <true>)<line_sep>self.assertEqual(source_model2.BuildSettings.bUseMikkTSpace <true>)<line_sep>self.assertEqual(source_model2.BuildSettings.bBuildAdjacencyBuffer <true>)<line_sep>self.assertEqual(source_model2.BuildSettings.bRemoveDegenerates <true>)<block_end><block_end> |
<import_from_future_stmt> absolute_import<import_stmt>numpy<as>np<import_from_stmt>numpy.testing assert_allclose<import_from_stmt>pycircstat utils<line_sep> |
eggs="eggs"<line_sep> |
# Copyright 2012 Viewfinder Inc. All Rights Reserved.
"""Async version of Amazon S3 access library.
The "boto" open source library supports synchronous operations against
S3, but does not have asynchronous support. In a high-scale server
environment, this is a real problem, because it is not permissible to
block threads waiting on network I/O. This module layers support for non-
blocking async operations over the boto library. It re-uses boto
functionality whenever possible.
"""<line_sep>__author__='<EMAIL> (<NAME>)'<import_stmt>logging<import_stmt>socket<import_stmt>urllib<import_from_stmt>tornado.httpclient AsyncHTTPClient HTTPRequest HTTPError<import_from_stmt>boto.connection AWSAuthConnection<import_from_stmt>boto.s3.connection SubdomainCallingFormat<import_from_stmt>viewfinder.backend.base.retry RetryPolicy CallWithRetryAsync<class_stmt>S3RetryPolicy(RetryPolicy)<block_start>"""Define a retry policy that is adapted to the Amazon S3 service.
Retries will only be attempted for HTTP 500-level errors, or if there
was a basic network failure of some kind. By default, a request
against S3 will be retried three times, with retries starting after
at least 1/2 second, and exponentially backing off from there to a
maximum of 10 seconds.
"""<def_stmt>__init__ self max_tries=3 timeout=30 min_delay=.5 max_delay=10<block_start>RetryPolicy.__init__(self max_tries=max_tries timeout=timeout min_delay=min_delay max_delay=max_delay check_result=self._ShouldRetry)<block_end><def_stmt>_ShouldRetry self response<block_start>"""Retry on:
1. HTTP error codes 500 (Internal Server Error) and 503 (Service
Unavailable).
2. Tornado HTTP error code 599, which typically indicates some kind
of general network failure of some kind.
3. Socket-related errors.
"""<if_stmt>response.error# Check for socket errors.
<block_start><if_stmt>type(response.error)<eq>socket.error<or>type(response.error)<eq>socket.gaierror<block_start><return><true><block_end># Check for HTTP errors.
<if_stmt>isinstance(response.error HTTPError)<block_start>code=response.error.code<if_stmt>code<in>(500 503 599)<block_start><return><true><block_end><block_end><block_end><return><false><block_end><block_end><class_stmt>AsyncS3Connection(AWSAuthConnection)<block_start>"""Sub-class that adds support for asynchronous S3 access. Callers provide
their Amazon AWS access key and secret key when an instance of the class
is created. Then, callers can repeatedly call 'make_request' in order to
make asynchronous HTTP calls against the S3 service. Using this API
rather than the standard boto API avoids blocking the calling thread
until the operation is complete.
"""<line_sep>DefaultHost='s3.amazonaws.com'<line_sep>"""By default, connect to this S3 endpoint."""<line_sep>DefaultCallingFormat=SubdomainCallingFormat()<line_sep>"""By default, use the S3 sub-domain format for providing bucket name."""<def_stmt>__init__ self host=DefaultHost aws_access_key_id=<none> aws_secret_access_key=<none> retry_policy=S3RetryPolicy()<block_start>AWSAuthConnection.__init__(self host aws_access_key_id aws_secret_access_key)<line_sep>self.retry_policy=retry_policy<block_end><def_stmt>make_request self method bucket='' key='' headers=<none> params=<none> body=<none> request_timeout=20.0 callback=<none><block_start>"""Start an asynchronous HTTP operation against the S3 service. When
the operation is complete, the 'callback' function will be invoked,
with the HTTP response object as its only parameter. If a failure
occurs during execution of the operation, it may be retried, according
to the retry policy with which this instance was initialized.
"""<line_sep>CallWithRetryAsync(self.retry_policy self._make_request method bucket key headers params body request_timeout callback=callback)<block_end><def_stmt>_make_request self method bucket key headers params body request_timeout callback<block_start>"""Wrapped by CallWithRetryAsync in order to support retry."""<line_sep># Build the boto HTTP request in order to create the authorization header.
path=AsyncS3Connection.DefaultCallingFormat.build_path_base(bucket key)<line_sep>auth_path=AsyncS3Connection.DefaultCallingFormat.build_auth_path(bucket key)<line_sep>host=AsyncS3Connection.DefaultCallingFormat.build_host(self.server_name() bucket)<line_sep># Only support byte strings for now.
<assert_stmt><not>body<or>type(body)<is>str "Only support byte strings (type=%s)."%type(body)<line_sep>boto_request=self.build_base_http_request(method path auth_path {} headers body<or>'' host)<line_sep>boto_request.authorize(connection=self)<line_sep># Log request for debugging.
debug_body=boto_request.body[:256].decode(errors='ignore')<if>boto_request.body<else><none><line_sep>logging.debug('%s "%s://%s%s" headers: %s body: %s' boto_request.method self.protocol boto_request.host boto_request.path boto_request.headers debug_body)<line_sep>request_url='%s://%s%s'%(self.protocol host path)<if_stmt>params<block_start>request_url<augadd>'?'+urllib.urlencode(params)<block_end># Build the tornado http client request (different version of HTTPRequest class).
tornado_request=HTTPRequest(request_url method=method headers=boto_request.headers body=body request_timeout=request_timeout)<line_sep># Start the asynchronous request. When it's complete, invoke 'callback', passing the HTTP response object.
http_client=AsyncHTTPClient()<line_sep>http_client.fetch(tornado_request callback=callback)<block_end><def_stmt>_required_auth_capability self<block_start>"""Called by AWSAuthConnection.__init__ in order to determine which
auth handler to construct. In this case, S3 HMAC signing should be used.
"""<line_sep><return>['s3']<block_end><block_end> |
"""Example web view for application factory."""<import_from_stmt>flask Blueprint<import_from_stmt>.extensions scheduler<import_from_stmt>.tasks task2<line_sep>web_bp=Blueprint("web_bp" __name__)<line_sep>@web_bp.route("/")<def_stmt>index <block_start>"""Say hi!.
:url: /
:returns: hi!
"""<line_sep><return>"hi!"<block_end>@web_bp.route("/add")<def_stmt>add <block_start>"""Add a task.
:url: /add/
:returns: job
"""<line_sep>job=scheduler.add_job(func=task2 trigger="interval" seconds=10 id="test job 2" name="test job 2" replace_existing=<true> )<line_sep><return>"%s added!"%job.name<block_end> |
<import_from_stmt>testing_helpers wrap<line_sep>@wrap<def_stmt>nested x<block_start><def_stmt>f y<block_start><return>y+y<block_end><return>f(x)<block_end><def_stmt>test_nested <block_start>nested(3)<line_sep>nested(3.0)<line_sep>nested([1])<block_end>@wrap<def_stmt>nested_closure x<block_start><def_stmt>f y<block_start><return>x+y<block_end><return>f(x)<block_end><def_stmt>test_nested_closure <block_start>nested_closure(3)<line_sep>nested_closure(3.0)<line_sep>nested_closure([1])<block_end>@wrap<def_stmt>nested_closure_repeat <block_start><for_stmt>i xrange(50)<block_start>temp=nested_closure(i)<block_end><return>temp<block_end><def_stmt>test_nested_closure_repeat <block_start>nested_closure_repeat()<block_end><if_stmt>__name__<eq>'__main__'<block_start><import_stmt>nose<line_sep>nose.main()<block_end> |
# Input Cases
t=int(input("\nTotal Test Cases : "))<for_stmt>i range(1 t+1)<block_start>print(f"\n------------ CASE #{i} -------------")<line_sep>n=int(input("\nTotal Items : "))<line_sep>m=int(input("Max Capacity : "))<line_sep>v=[int(i)<for>i input("\nValues : ").split(" ")]<line_sep>w=[int(i)<for>i input("Weights : ").split(" ")]<line_sep># Tabulation (DP)
dp=[[0<for>x range(m+1)]<for>x range(n+1)]<for_stmt>i range(n+1)<block_start><for_stmt>j range(m+1)<block_start><if_stmt>i<eq>0<or>j<eq>0<block_start>dp[i][j]=0<block_end><elif_stmt>w[i-1]<le>j<block_start>dp[i][j]=max(dp[i-1][j] dp[i-1][j-w[i-1]]+v[i-1])<block_end><else_stmt><block_start>dp[i][j]=dp[i-1][j]<block_end><block_end><block_end>print(f"\nMax Value Picked : {dp[n][m]}")<block_end> |
<import_from_future_stmt> absolute_import<import_stmt>os<import_from_stmt>celery shared_task<import_from_stmt>django.core management<import_from_stmt>leonardo.decorators catch_result<import_from_stmt>django.conf settings<line_sep>@shared_task@catch_result<def_stmt>sync_search_indexes <block_start>management.call_command('rebuild_index' interactive=<false>)<line_sep># patch whoosh backend
haystack=getattr(settings 'HAYSTACK_CONNECTIONS' <none>)<if_stmt>'default'<in>haystack<and>'whoosh'<in>haystack['default']['ENGINE']<block_start><try_stmt><block_start>os.remove(os.path.join(haystack['default']['PATH'] 'MAIN_WRITELOCK'))<block_end><except_stmt><block_start><pass><block_end><block_end><return>{'result':'Rebuild index OK'}<block_end> |
<class_stmt>HttpStyleUriParser(UriParser)<block_start>"""
A customizable parser based on the HTTP scheme.
HttpStyleUriParser()
"""<block_end> |
<import_from_stmt>spacy.lang.de German<line_sep>nlp=German()<line_sep>people=["<NAME>" "<NAME>" "<NAME>"]<line_sep># Erstelle eine Liste von Patterns für den PhraseMatcher
patterns=list(nlp.pipe(people))<line_sep> |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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>os<import_from_stmt>os.path join abspath dirname<import_from_stmt>typing List<import_from_stmt>weasyprint HTML CSS<import_from_stmt>qf_lib.common.utils.logging.qf_parent_logger qf_logger<import_from_stmt>qf_lib.documents_utils.document_exporting.document Document<import_from_stmt>qf_lib.documents_utils.document_exporting.document_exporter DocumentExporter<import_from_stmt>qf_lib.settings Settings<import_from_stmt>qf_lib.starting_dir get_starting_dir_abs_path<class_stmt>PDFExporter(DocumentExporter)<block_start>"""
Stores elements such as the ParagraphElement and ChartElement in order to build a PDF based on them once they
have all been added. If there is a "document_css_directory" attribute set in the Settings, then CSS files from that
directory will be applied for styling the output page. Otherwise the default styling will be applied.
"""<line_sep>DEFAULT_CSS_DIR_NAME='default_css'<def_stmt>__init__ self settings:Settings<block_start>super().__init__(settings)<if_stmt>hasattr(settings 'document_css_directory')<block_start>self._document_css_dir=join(get_starting_dir_abs_path() settings.document_css_directory)<block_end><else_stmt><block_start>this_dir_abs_path=abspath(dirname(__file__))<line_sep>self._document_css_dir=join(this_dir_abs_path self.DEFAULT_CSS_DIR_NAME)<block_end>self.logger=qf_logger.getChild(self.__class__.__name__)<block_end><def_stmt>set_default_directory_level_up self<block_start>"""
Sets the document_css_dir one level above 'default css', to enable applying css classes in other folders.
Using the generate function demands inputting css_file_names as paths from newly set level.
e.g: 'default_css\main"
"""<line_sep>self._document_css_dir=abspath(dirname(__file__))<block_end><def_stmt>generate self documents:List[Document] export_dir:str filename:str include_table_of_contents=<false> css_file_names:List[str]=<none><arrow>str<block_start>"""
Merged all documents into one and then exports the merged document to a PDF file in the given directory.
Allows defining of multiple css files. The base css file will be applied first, followed sequentially
by files defined in css_file_names.
The CSS files must be placed in the Settings.document_css_directory directory.
CSS files placed in Settings.document_css_directory/base will be applied for all exported PDF documents.
Parameters
----------
documents
list of documents for which files should be generated
export_dir
relative path to the directory (relative to the output root directory) in which the PDF should be saved
filename
filename under which the merged document should be saved
include_table_of_contents
if True then table of contents will be generated at the beginning of the file
css_file_names
names of css files which should be applied for generating the PDF
Returns
-------
the absolute path to the output PDF file that was saved
"""<line_sep>css_file_paths=[]<line_sep>documents=[self._merge_documents(documents filename)]<line_sep># Find the output directory
output_dir=self.get_output_dir(export_dir)<line_sep>output_filename=os.path.join(output_dir filename)<for_stmt>document documents<block_start><if_stmt>include_table_of_contents<block_start>self._add_table_of_contents(document)<block_end># Generate the full document HTML
self.logger.info("Generating HTML for PDF...")<line_sep>html=document.generate_html()<line_sep># Automatically include all the css files in the `document_css/base` directory
base_css=os.listdir(self._document_css_dir)<for_stmt>name base_css<block_start>path=os.path.join(self._document_css_dir name)<if_stmt>os.path.isfile(path)<block_start>css_file_paths.append(CSS(path))<block_end><block_end># If we've set custom css files, add them to the pdf
<if_stmt>css_file_names<is><not><none><block_start><for_stmt>name css_file_names<block_start>css_file_paths.append(CSS(os.path.join(self._document_css_dir name+".css")))<block_end><block_end># Parse the HTML.
html=HTML(string=html)<line_sep># Write out the PDF.
self.logger.info("Rendering PDF in {}...".format(output_filename))<line_sep>html.write_pdf(output_filename css_file_paths)<block_end><return>output_filename<block_end><block_end> |
__________________________________________________________________________________________________<line_sep>36ms<class_stmt>Solution<block_start><def_stmt>generateParenthesis self n:'int'<arrow>'List[str]'<block_start><if_stmt>n<eq>0<block_start><return>['']<block_end>ans=[]<def_stmt>backtrack S='' left=0 right=0<block_start><if_stmt>len(S)<eq>2<times>n<block_start>ans.append(S)<line_sep><return><block_end><if_stmt>left<l>n<block_start>backtrack(S+'(' left+1 right)<block_end><if_stmt>right<l>left<block_start>backtrack(S+')' left right+1)<block_end><block_end>backtrack()<line_sep><return>ans<block_end><block_end>__________________________________________________________________________________________________<line_sep>40ms<class_stmt>Solution<block_start><def_stmt>generateParenthesis self n<block_start>"""
:type n: int
:rtype: List[str]
"""<line_sep>res=[]<def_stmt>helper l_num=0 r_num=0 s=''<block_start><if_stmt>len(s)<eq>2<times>n<block_start>res.append(s)<line_sep><return><block_end><if_stmt>l_num<l>n<block_start>helper(l_num+1 r_num s+'(')<block_end><if_stmt>l_num<g>r_num<block_start>helper(l_num r_num+1 s+')')<block_end><block_end>helper()<line_sep><return>res<block_end><block_end>__________________________________________________________________________________________________<line_sep>44ms<class_stmt>Solution<block_start><def_stmt>generateParenthesis self n:int<arrow>List[str]<block_start>result=[]<if_stmt>n<eq>0<block_start><return>[""]<block_end><def_stmt>gene_par index present_sum strs<block_start><if_stmt>index<eq>2<times>n<block_start><if_stmt>present_sum<eq>1<block_start>result.append(strs+")")<block_end><return><block_end><if_stmt>present_sum<g>0<block_start>gene_par(index+1 present_sum+1 strs+"(")<line_sep>gene_par(index+1 present_sum-1 strs+")")<block_end><else_stmt><block_start>gene_par(index+1 present_sum+1 strs+"(")<block_end><block_end>gene_par(1 0 "")<line_sep><return>result<block_end><block_end>__________________________________________________________________________________________________<line_sep>12396 kb<class_stmt>Solution<block_start><def_stmt>generateParenthesis self n:'int'<arrow>'List[str]'<block_start><if_stmt>n<le>0<block_start><return>[]<block_end><if_stmt>n<eq>1<block_start><return>["()"]<block_end><else_stmt><block_start>prev=self.generateParenthesis(n-1)<line_sep>fresh=set()<for_stmt>line prev<block_start>fresh.add("()"+line)<line_sep>fresh.add(line+"()")<line_sep>fresh.add("("+line+")")<for_stmt>i range(1 len(line))<block_start>fresh.add(line[:i]+"()"+line[i:])<block_end><block_end><return>list(fresh)<block_end><block_end><block_end>__________________________________________________________________________________________________<line_sep>12424 kb<class_stmt>Solution<block_start><def_stmt>generateParenthesis self n:'int'<arrow>'List[str]'<block_start>res=[]<def_stmt>rec str iter<block_start><if_stmt>iter<eq>0#print(str)
<block_start><if_stmt>str<not><in>res<block_start>res.append(str)<block_end><return><block_end>rec(str+'()' iter-1)<line_sep>rec('()'+str iter-1)<line_sep>rec('('+str+')' iter-1)<block_end>#rec('', n)
#return res
<def_stmt>BT str left right#print(str,left,right)
<block_start><if_stmt>(left<l>0)<block_start><return><block_end><if_stmt>(right<l>0)<block_start><return><block_end><if_stmt>(left<g>right)<block_start><return><block_end><if_stmt>(left<eq>0<and>right<eq>0)<block_start>print(str)<line_sep>res.append(str)<line_sep><return><block_end>BT(str+'(' left-1 right)<line_sep>BT(str+')' left right-1)<block_end>BT('' n n)<line_sep><return>res<block_end><block_end>__________________________________________________________________________________________________<line_sep> |
# -*- coding: utf-8 -*-
<import_stmt>numpy<as>np<import_from_stmt>PIL Image<import_stmt>pickle<import_stmt>os<import_from_stmt>abc abstractmethod<import_from_stmt>...utils ModuleBase<import_from_stmt>typing Dict List<class_stmt>FolderBase(ModuleBase)<block_start>"""
The base class of folder function.
"""<line_sep>default_hyper_params=dict()<def_stmt>__init__ self data_json_path:str transformer:callable<or><none>=<none> hps:Dict<or><none>=<none><block_start>"""
Args:
data_json_path (str): the path for data json file.
transformer (callable): a list of data augmentation operations.
hps (dict): default hyper parameters in a dict (keys, values).
"""<line_sep>super(FolderBase self).__init__(hps)<with_stmt>open(data_json_path "rb")<as>f<block_start>self.data_info=pickle.load(f)<block_end>self.data_json_path=data_json_path<line_sep>self.transformer=transformer<block_end><def_stmt>__len__ self<arrow>int<block_start><pass><block_end>@abstractmethod<def_stmt>__getitem__ self idx:int<arrow>Dict<block_start><pass><block_end><def_stmt>find_classes self info_dicts:Dict<arrow>(List Dict)<block_start><pass><block_end><def_stmt>read_img self path:str<arrow>Image<block_start>"""
Load image.
Args:
path (str): the path of the image.
Returns:
image (Image): shape (H, W, C).
"""<try_stmt><block_start>img=Image.open(path)<line_sep>img=img.convert("RGB")<line_sep><return>img<block_end><except_stmt>Exception<as>e<block_start>print('[DataSet]: WARNING image can not be loaded: {}'.format(str(e)))<line_sep><return><none><block_end><block_end><block_end> |
<import_stmt>math<def_stmt>sum_circle data x y r<block_start>"""Sum array values that fall within the given circle.
Parameters
----------
data : numpy.ndarray
The array to sum.
x, y, r : float
The center and radius of circle, in array coordinates.
"""<line_sep>imin=math.floor((x-r)+0.5)<line_sep>imax=math.floor((x+r)+0.5)<line_sep>jmin=math.floor((y-r)+0.5)<line_sep>jmax=math.floor((y+r)+0.5)<line_sep>r2=r<times>r<line_sep>sum=0.0<for_stmt>j range(jmin jmax+1)<block_start><for_stmt>i range(imin imax+1)<block_start><if_stmt>(i-x)<power>2+(j-y)<power>2<l>r2<block_start>sum<augadd>data[j i]<block_end><block_end><block_end><return>sum<block_end> |
<import_from_stmt>picotui.context Context<import_from_stmt>picotui.dialogs *<with_stmt>Context()# Feel free to comment out extra dialogs to play with a particular
# in detail
<block_start>d=DTextEntry(25 "Hello World" title="Wazzup?")<line_sep>res=d.result()<line_sep>d=DMultiEntry(25 5 "Hello\nWorld".split("\n") title="Comment:")<line_sep>res=d.result()<block_end>print(res)<line_sep> |
"""
DenseNet for CIFAR dataset proposed in Gao et al. 2016
https://github.com/liuzhuang13/DenseNet
"""<import_stmt>torch<import_from_stmt>torch nn<import_from_stmt>torch.nn functional<as>F<import_from_stmt>homura.vision.models MODEL_REGISTRY<line_sep>__all__=["densenet40" "densenet100" "CIFARDenseNet"]<line_sep>_padding={"reflect":nn.ReflectionPad2d "zero":nn.ZeroPad2d}<class_stmt>_DenseLayer(nn.Module)<block_start><def_stmt>__init__ self in_channels bn_size growth_rate dropout_rate padding<block_start>super(_DenseLayer self).__init__()<assert_stmt>padding<in>_padding.keys()<line_sep>self.dropout_rate=dropout_rate<line_sep>self.layers=nn.Sequential(nn.BatchNorm2d(in_channels) nn.ReLU(inplace=<true>) nn.Conv2d(in_channels bn_size<times>growth_rate kernel_size=1 stride=1 bias=<false>) nn.BatchNorm2d(bn_size<times>growth_rate) nn.ReLU(inplace=<true>) _padding[padding](1) nn.Conv2d(bn_size<times>growth_rate growth_rate kernel_size=3 stride=1 bias=<false>))<block_end><def_stmt>forward self input<block_start>x=self.layers(input)<if_stmt>self.dropout_rate<g>0<block_start>x=F.dropout(x p=self.dropout_rate training=self.training)<block_end><return>torch.cat([input x] dim=1)<block_end><block_end><class_stmt>_DenseBlock(nn.Module)<block_start><def_stmt>__init__ self num_layers in_channels bn_size growth_rate dropout_rate padding<block_start>super(_DenseBlock self).__init__()<line_sep>layers=[_DenseLayer(in_channels+i<times>growth_rate bn_size growth_rate dropout_rate padding)<for>i range(num_layers)]<line_sep>self.layers=nn.Sequential(*layers)<block_end><def_stmt>forward self input<block_start><return>self.layers(input)<block_end><block_end><class_stmt>_Transition(nn.Module)<block_start><def_stmt>__init__ self in_channels out_channels<block_start>super(_Transition self).__init__()<line_sep>self.layers=nn.Sequential(nn.BatchNorm2d(in_channels) nn.ReLU(inplace=<true>) nn.Conv2d(in_channels out_channels kernel_size=1 stride=1 bias=<false>) nn.AvgPool2d(kernel_size=2 stride=2))<block_end><def_stmt>forward self input<block_start><return>self.layers(input)<block_end><block_end>@MODEL_REGISTRY.register<class_stmt>CIFARDenseNet(nn.Module)<block_start>"""
DenseNet-BC (bottleneck and compactness) for CIFAR dataset. For ImageNet classification, use `torchvision`'s.
:param num_classes: (int) number of output classes
:param init_channels: (int) output channels which is performed on the input. 16 or 2 * growth_rate
:param num_layers: (int) number of layers of each dense block
:param growth_rate: (int) growth rate, which is referred as k in the paper
:param dropout_rate: (float=0) dropout rate
:param bn_size: (int=4) multiplicative factor in bottleneck
:param reduction: (int=2) divisional factor in transition
"""<def_stmt>__init__ self num_classes init_channels num_layers growth_rate dropout_rate=0 bn_size=4 reduction=2 padding="reflect"<block_start>super(CIFARDenseNet self).__init__()<line_sep># initial conv.
num_channels=init_channels<line_sep>layers=[_padding[padding](1) nn.Conv2d(3 num_channels kernel_size=3 bias=<false>)]<line_sep># first and second dense-block+transition
<for_stmt>_ range(2)<block_start>layers.append(_DenseBlock(num_layers in_channels=num_channels bn_size=bn_size growth_rate=growth_rate dropout_rate=dropout_rate padding=padding))<line_sep>num_channels=num_channels+num_layers<times>growth_rate<line_sep>layers.append(_Transition(num_channels num_channels<floordiv>reduction))<line_sep>num_channels=num_channels<floordiv>reduction<block_end># third denseblock
layers.append(_DenseBlock(num_layers in_channels=num_channels bn_size=bn_size growth_rate=growth_rate dropout_rate=dropout_rate padding="reflect"))<line_sep>self.features=nn.Sequential(*layers)<line_sep>self.bn1=nn.BatchNorm2d(num_channels+num_layers<times>growth_rate)<line_sep>self.linear=nn.Linear(num_channels+num_layers<times>growth_rate num_classes)<line_sep># initialize parameters
self.initialize()<block_end><def_stmt>forward self input<block_start>x=self.features(input)<line_sep>x=F.relu(self.bn1(x) inplace=<true>)<line_sep>x=F.adaptive_avg_pool2d(x 1)<line_sep>x=x.view(x.size(0) -1)<line_sep><return>self.linear(x)<block_end><def_stmt>initialize self<block_start><for_stmt>m self.modules()<block_start><if_stmt>isinstance(m nn.Conv2d)<block_start>nn.init.kaiming_normal_(m.weight.data)<block_end><elif_stmt>isinstance(m nn.BatchNorm2d)<block_start>m.weight.data.fill_(1)<line_sep>m.bias.data.zero_()<block_end><elif_stmt>isinstance(m nn.Linear)<block_start>m.bias.data.zero_()<block_end><block_end><block_end><block_end><def_stmt>_cifar_densenet depth num_classes growth_rate=12 **kwargs<block_start>n=(depth-4)<floordiv>6<line_sep>model=CIFARDenseNet(num_classes init_channels=2<times>growth_rate num_layers=n growth_rate=growth_rate padding="reflect" **kwargs)<line_sep><return>model<block_end>@MODEL_REGISTRY.register<def_stmt>densenet100 num_classes **kwargs<block_start><return>_cifar_densenet(100 num_classes **kwargs)<block_end>@MODEL_REGISTRY.register<def_stmt>densenet40 num_classes **kwargs<block_start><return>_cifar_densenet(40 num_classes **kwargs)<block_end> |
<import_stmt>tensorflow<as>tf<import_from_stmt>tensorflow.contrib.seq2seq.python.ops.helper CustomHelper<import_from_stmt>tensorflow.contrib.rnn *<class_stmt>InferenceHelper(CustomHelper)<block_start><def_stmt>_initialize_fn self# we always reconstruct the whole output
<block_start>finished=tf.tile([<false>] [self._batch_size])<line_sep>next_inputs=tf.zeros([self._batch_size self._out_size] dtype=tf.float32)<line_sep><return>(finished next_inputs)<block_end><def_stmt>_sample_fn self time outputs state# we're not sampling from a vocab so we don't care about this function
<block_start><return>tf.zeros(32 dtype=tf.int32)<block_end><def_stmt>_next_inputs_fn self time outputs state sample_ids<block_start><del_stmt>time sample_ids<line_sep>finished=tf.tile([<false>] [self._batch_size])<line_sep>next_inputs=outputs<line_sep><return>(finished next_inputs state)<block_end><def_stmt>__init__ self batch_size out_size<block_start>self._batch_size=batch_size<line_sep>self._out_size=out_size<block_end><block_end><def_stmt>highway inputs units=128# correct input shape
<block_start><if_stmt>inputs.shape[-1]<ne>units<block_start>inputs=tf.layers.dense(inputs units=units)<block_end>T=tf.layers.dense(inputs units=units activation=tf.nn.sigmoid )<line_sep># TODO update bias initial value
H=tf.layers.dense(inputs units=units activation=tf.nn.relu)<line_sep>C=H<times>T+inputs<times>(1-T)<line_sep><return>C<block_end><def_stmt>CBHG inputs speaker_embed=<none> K=16 c=[128 128 128] gru_units=128 num_highway_layers=4 num_conv_proj=2<block_start><with_stmt>tf.variable_scope('cbhg')# 1D convolution bank
<block_start>conv_bank=[tf.layers.conv1d(inputs filters=c[0] kernel_size=k padding='same' activation=tf.nn.relu)<for>k range(1 K+1)]<line_sep>conv_bank=tf.concat(conv_bank -1)<line_sep>conv_bank=tf.layers.batch_normalization(conv_bank)<line_sep>conv_bank=tf.layers.max_pooling1d(conv_bank pool_size=2 strides=1 padding='same')<line_sep>tf.summary.histogram('conv_bank' conv_bank)<assert_stmt>num_conv_proj<eq>len(c)-1<line_sep>conv_proj=conv_bank<for_stmt>layer range(num_conv_proj)<block_start>activation=<none><if>layer<eq>num_conv_proj-1<else>tf.nn.relu<line_sep># conv projections
conv_proj=tf.layers.conv1d(conv_proj filters=c[layer+1] kernel_size=3 padding='same' activation=activation)<line_sep>conv_proj=tf.layers.batch_normalization(conv_proj)<block_end>tf.summary.histogram('conv_proj' conv_proj)<line_sep># residual connection
conv_res=conv_proj+inputs<line_sep>tf.summary.histogram('conv_res' conv_res)<line_sep># highway feature extraction
h=conv_res<for_stmt>layer range(num_highway_layers)<block_start><with_stmt>tf.variable_scope('highway_'+str(layer))# site specific speaker embedding
<block_start><if_stmt>speaker_embed<is><not><none><block_start>s=tf.layers.dense(speaker_embed h.shape[-1] activation=tf.nn.relu)<line_sep>s=tf.tile(tf.expand_dims(s 1) [1 tf.shape(h)[1] 1])<line_sep>h=tf.concat([h s] 2)<block_end>h=highway(h)<block_end><block_end>tf.summary.histogram('highway_out' h)<line_sep># site specfic speaker embedding
<if_stmt>speaker_embed<is><not><none><block_start>s=tf.layers.dense(speaker_embed gru_units activation=tf.nn.relu)<block_end><else_stmt><block_start>s=<none><block_end># bi-GRU
forward_gru_cell=GRUCell(gru_units)<line_sep>backward_gru_cell=GRUCell(gru_units)<line_sep>out,_=tf.nn.bidirectional_dynamic_rnn(forward_gru_cell backward_gru_cell h initial_state_fw=s initial_state_bw=s dtype=tf.float32)<line_sep>out=tf.concat(out 2)<line_sep>tf.summary.histogram('encoded' out)<line_sep><return>out<block_end><block_end> |
"""
Plotting data from the SARS database
====================================
"""<import_stmt>sharppy.sharptab<as>tab<import_stmt>sharppy.databases.sars<as>sars<import_stmt>numpy<as>np<import_stmt>os<import_stmt>matplotlib.pyplot<as>plt<line_sep>database_fn=os.path.join(os.path.dirname(sars.__file__) 'sars_supercell.txt')<line_sep>supercell_database=np.loadtxt(database_fn skiprows=1 dtype=bytes comments="%%%%")<line_sep>magnitude=[]<line_sep>mlcape=[]<line_sep>srh01=[]<for_stmt>record supercell_database<block_start>magnitude.append(int(record[1]))<line_sep>mlcape.append(float(record[3]))<line_sep>srh01.append(float(record[6]))<block_end>plt.grid()<line_sep>plt.scatter(mlcape srh01 c=magnitude marker='.')<line_sep>plt.colorbar()<line_sep>plt.xlabel("MLCAPE [J/kg]")<line_sep>plt.ylabel(r'0-1 km Storm Relative Helicity [$m^{2}/s^{2}$]')<line_sep>plt.savefig('plot_sars.png' bbox_inches='tight')<line_sep>plt.show()<line_sep> |
<import_from_stmt>gcc.models.emb FromNumpy FromNumpyAlign FromNumpyGraph GraphWave ProNE Zero <def_stmt>build_model name hidden_size **model_args<block_start><return>{"zero":Zero "from_numpy":FromNumpy "from_numpy_align":FromNumpyAlign "from_numpy_graph":FromNumpyGraph "prone":ProNE "graphwave":GraphWave }[name](hidden_size **model_args)<block_end> |
<def_stmt>func1 <block_start><pass><block_end><def_stmt>func2 <block_start><pass><block_end>a=b=func1<line_sep>b()<line_sep>a=b=func2<line_sep>a()<line_sep> |
<import_stmt>pandas<as>pd<line_sep>df=pd.read_csv('data/src/aapl_2015_2019.csv' index_col=0 parse_dates=<true>)['2017']<line_sep>print(df)<line_sep># open high low close volume
# 2017-01-03 115.80 116.3300 114.760 116.15 28781865
# 2017-01-04 115.85 116.5100 115.750 116.02 21118116
# 2017-01-05 115.92 116.8642 115.810 116.61 22193587
# 2017-01-06 116.78 118.1600 116.470 117.91 31751900
# 2017-01-09 117.95 119.4300 117.940 118.99 33561948
# ... ... ... ... ... ...
# 2017-12-22 174.68 175.4240 174.500 175.01 16052615
# 2017-12-26 170.80 171.4700 169.679 170.57 32968167
# 2017-12-27 170.10 170.7800 169.710 170.60 21672062
# 2017-12-28 171.00 171.8500 170.480 171.08 15997739
# 2017-12-29 170.52 170.5900 169.220 169.23 25643711
#
# [251 rows x 5 columns]
d_ohlc={'open':'first' 'high':'max' 'low':'min' 'close':'last'}<line_sep>print(df.resample('MS').agg(d_ohlc))<line_sep># open high low close
# 2017-01-01 115.80 122.4400 114.76 121.35
# 2017-02-01 127.03 137.4800 127.01 136.99
# 2017-03-01 137.89 144.5000 137.05 143.66
# 2017-04-01 143.71 145.4600 140.06 143.65
# 2017-05-01 145.10 156.6500 144.27 152.76
# 2017-06-01 153.17 155.9800 142.20 144.02
# 2017-07-01 144.88 153.9900 142.41 148.73
# 2017-08-01 149.10 164.5200 148.41 164.00
# 2017-09-01 164.80 164.9400 149.16 154.12
# 2017-10-01 154.26 169.6499 152.46 169.04
# 2017-11-01 169.87 176.2400 165.28 171.85
# 2017-12-01 169.95 177.2000 166.46 169.23
print(df.resample('QS').agg(d_ohlc))<line_sep># open high low close
# 2017-01-01 115.80 144.50 114.76 143.66
# 2017-04-01 143.71 156.65 140.06 144.02
# 2017-07-01 144.88 164.94 142.41 154.12
# 2017-10-01 154.26 177.20 152.46 169.23
print(df.resample('2W-MON' closed='left' label='left').agg(d_ohlc))<line_sep># open high low close
# 2017-01-02 115.800 119.9300 114.7600 119.04
# 2017-01-16 118.340 122.4400 118.2200 121.95
# 2017-01-30 120.930 132.9400 120.6200 132.12
# 2017-02-13 133.080 137.4800 132.7500 136.66
# 2017-02-27 137.140 140.2786 136.2800 139.14
# 2017-03-13 138.850 142.8000 138.8200 140.64
# 2017-03-27 139.390 145.4600 138.6200 143.34
# 2017-04-10 143.600 143.8792 140.0600 142.27
# 2017-04-24 143.500 148.9800 143.1800 148.96
# 2017-05-08 149.030 156.6500 149.0300 153.06
# 2017-05-22 154.000 155.4500 152.2200 155.45
# 2017-06-05 154.340 155.9800 142.2000 142.27
# 2017-06-19 143.660 148.2800 142.2800 144.02
# 2017-07-03 144.880 149.3300 142.4100 149.04
# 2017-07-17 148.820 153.9900 147.3000 149.50
# 2017-07-31 149.900 161.8300 148.1300 157.48
# 2017-08-14 159.320 162.5100 155.1101 159.86
# 2017-08-28 160.140 164.9400 158.5300 158.63
# 2017-09-11 160.500 163.9600 150.5600 151.89
# 2017-09-25 149.990 155.4900 149.1600 155.30
# 2017-10-09 155.810 160.8700 155.0200 156.25
# 2017-10-23 156.890 174.2600 155.2700 172.50
# 2017-11-06 172.365 176.2400 168.3800 170.15
# 2017-11-20 170.290 175.5000 167.1600 171.05
# 2017-12-04 172.480 174.1700 166.4600 173.97
# 2017-12-18 174.880 177.2000 169.2200 169.23
d_ohlcv={'open':'first' 'high':'max' 'low':'min' 'close':'last' 'volume':'sum'}<line_sep>print(df.resample('MS').agg(d_ohlcv))<line_sep># open high low close volume
# 2017-01-01 115.80 122.4400 114.76 121.35 563331160
# 2017-02-01 127.03 137.4800 127.01 136.99 574968547
# 2017-03-01 137.89 144.5000 137.05 143.66 562091214
# 2017-04-01 143.71 145.4600 140.06 143.65 371280180
# 2017-05-01 145.10 156.6500 144.27 152.76 635292989
# 2017-06-01 153.17 155.9800 142.20 144.02 664986406
# 2017-07-01 144.88 153.9900 142.41 148.73 411377229
# 2017-08-01 149.10 164.5200 148.41 164.00 638221161
# 2017-09-01 164.80 164.9400 149.16 154.12 669594016
# 2017-10-01 154.26 169.6499 152.46 169.04 496135305
# 2017-11-01 169.87 176.2400 165.28 171.85 581876496
# 2017-12-01 169.95 177.2000 166.46 169.23 518560008
|
<import_stmt>pytest<import_stmt>os.path<import_stmt>logging<import_from_stmt>cryptography x509<import_from_stmt>cryptography.hazmat.primitives.asymmetric rsa<import_from_stmt>commandment.pki.models RSAPrivateKey CACertificate<line_sep>logger=logging.getLogger(__name__)<class_stmt>TestModels<block_start><def_stmt>test_rsa_privatekey_from_crypto self private_key:rsa.RSAPrivateKeyWithSerialization session<block_start>m=RSAPrivateKey.from_crypto(private_key)<line_sep>session.add(m)<line_sep>session.commit()<assert_stmt>m.id<is><not><none><assert_stmt>m.pem_data<is><not><none><block_end><def_stmt>test_ca_certificate_from_crypto self ca_certificate:x509.Certificate session<block_start>m=CACertificate.from_crypto(ca_certificate)<line_sep>session.add(m)<line_sep>session.commit()<assert_stmt>m.id<is><not><none><assert_stmt>m.pem_data<is><not><none><assert_stmt>m.fingerprint<is><not><none><assert_stmt>m.x509_cn<is><not><none><block_end><block_end> |
'''
Script to manage datasets for multiple tasks
'''<import_from_stmt>torch.utils.data Dataset DataLoader BatchSampler<import_from_stmt>utils.data_utils TaskType ModelType<import_stmt>torch<import_stmt>random<import_stmt>logging<import_stmt>json<line_sep>logger=logging.getLogger("multi_task")<class_stmt>allTasksDataset(Dataset)<block_start>'''
class to make pytorch dataset of the processed data for a specific task
taskDict :- list of dictionaries. Each dictioanry belong to the details of a
dataset to be created for a task
[ {"data_task_id" : "", "data_path" : "", "data_task_type" : ""},
...]
'''<def_stmt>__init__ self taskDict pipeline=<false><block_start>self.taskDict=taskDict<line_sep>self.pipeline=pipeline<line_sep>self.allTasksData,self.taskIdTypeMap=self.make_all_datasets()<block_end><def_stmt>read_data self readPath<block_start><with_stmt>open(readPath 'r' encoding='utf-8')<as>file<block_start>logger.info('Reading data from file {}'.format(readPath))<line_sep>taskData=[]<for_stmt>i,line enumerate(file)#if i >=1000:
#continue
<block_start>sample=json.loads(line)<line_sep>taskData.append(sample)<block_end><block_end><return>taskData<block_end><def_stmt>make_all_datasets self<block_start>'''
For each dataset entry in the taskDict, this function makes them into corresponding dataset
and returns a dictionary mapping like {<task_id> : <dataset>,}
'''<line_sep>allTasksData={}<line_sep>taskIdTypeMap={}# mapping from task id to task type
<for_stmt>task self.taskDict<block_start><if_stmt>self.pipeline<block_start>logger.info('Reading data for pipeline')<line_sep>data=task["data_"]<block_end><else_stmt><block_start>data=self.read_data(task["data_path"])<block_end>allTasksData[task["data_task_id"]]=data<line_sep>taskIdTypeMap[task["data_task_id"]]=task["data_task_type"]<line_sep>logger.info('Read Data for Task Id: {} Task Name: {}. Samples {}'.format(task["data_task_id"] task["data_task_name"] len(data)))<block_end><return>allTasksData taskIdTypeMap<block_end># some standard functions which need to be overridden from Dataset
#class for item, len etc..
<def_stmt>__len__ self<block_start><return>sum(len(v)<for>k,v self.allTasksData.items())<block_end># get item will be used to fetch a sample when required for the corresponding task id.
<def_stmt>__getitem__ self idx<block_start>taskId,sampleId=idx<line_sep>out={"task":{"task_id":taskId "task_type":self.taskIdTypeMap[taskId]} "sample":self.allTasksData[taskId][sampleId]}<line_sep><return>out<block_end><block_end><class_stmt>Batcher(BatchSampler)<block_start><def_stmt>__init__ self dataObj batchSize shuffleTask=<true> shuffleBatch=<true> seed=42<block_start>'''
dataObj :- An instance of allTasksDataset containing data for all tasks
'''<line_sep>self.dataObj=dataObj<line_sep>self.allTasksData=dataObj.allTasksData<line_sep>self.batchSize=batchSize<line_sep># to shuffle the indices in a batch
self.shuffleBatch=shuffleBatch<line_sep># to shuffle the samples picked up among all the tasks
self.shuffleTask=shuffleTask<line_sep>self.seed=seed<line_sep>self.allTasksDataBatchIdxs=[]<line_sep>self.taskIdxId=[]<for_stmt>taskId,data self.allTasksData.items()<block_start>self.allTasksDataBatchIdxs.append(self.make_batches(len(data)))<line_sep>self.taskIdxId.append(taskId)<block_end><block_end><def_stmt>make_batches self dataSize<block_start>batchIdxs=[list(range(i min(i+self.batchSize dataSize)))<for>i range(0 dataSize self.batchSize)]<if_stmt>self.shuffleBatch<block_start>random.seed(self.seed)<line_sep>random.shuffle(batchIdxs)<block_end><return>batchIdxs<block_end><def_stmt>make_task_idxs self<block_start>'''
This fn makes task indices for which a corresponding batch is created
eg. [0, 0, 1, 3, 0, 2, 3, 1, 1, ..] if task ids are 0,1,2,3
'''<line_sep>taskIdxs=[]<for_stmt>i range(len(self.allTasksDataBatchIdxs))<block_start>taskIdxs<augadd>[i]<times>len(self.allTasksDataBatchIdxs[i])<block_end><if_stmt>self.shuffleTask<block_start>random.seed(self.seed)<line_sep>random.shuffle(taskIdxs)<block_end><return>taskIdxs<block_end>#over riding BatchSampler functions to generate iterators for all tasks
# and iterate
<def_stmt>__len__ self<block_start><return>sum(len(data)<for>taskId,data self.allTasksData.items())<block_end><def_stmt>__iter__ self<block_start>allTasksIters=[iter(item)<for>item self.allTasksDataBatchIdxs]<line_sep>#all_iters = [iter(item) for item in self._train_data_list]
allIdxs=self.make_task_idxs()<for_stmt>taskIdx allIdxs# this batch belongs to a specific task id
<block_start>batchTaskId=self.taskIdxId[taskIdx]<line_sep>batch=next(allTasksIters[taskIdx])<line_sep><yield>[(batchTaskId sampleIdx)<for>sampleIdx batch]<block_end><block_end><def_stmt>patch_data self batch_info batch_data gpu=<none><block_start><if_stmt>gpu<block_start><for_stmt>i,part enumerate(batch_data)<block_start><if_stmt>part<is><not><none><block_start><if_stmt>isinstance(part torch.Tensor)<block_start>batch_data[i]=part.pin_memory().cuda(non_blocking=<true>)<block_end><elif_stmt>isinstance(part tuple)<block_start>batch_data[i]=tuple(sub_part.pin_memory().cuda(non_blocking=<true>)<for>sub_part part)<block_end><elif_stmt>isinstance(part list)<block_start>batch_data[i]=[sub_part.pin_memory().cuda(non_blocking=<true>)<for>sub_part part]<block_end><else_stmt><block_start><raise>TypeError("unknown batch data type at %s: %s"%(i part))<block_end><block_end><block_end><block_end><return>batch_info batch_data<block_end><block_end><class_stmt>batchUtils<block_start>'''
This class is supposed to perform function which will help complete the batch data
when DataLoader creates batch using allTasksDataset and Batcher.
Main function would be
1. A function to make get the various components of input in batch samples and make them into
Pytorch Tensors like token_id, type_ids, masks.
2. Collater function :- This function will use the above function to convert the batch into
pytorch tensor inputs. As converting all the data into pytorch tensors before might not be a good
idea due to space, hence this custom function will be used to convert the batches into tensors on the fly
by acting as custom collater function to DataLoader
'''<def_stmt>__init__ self isTrain modelType maxSeqLen dropout=0.005<block_start>self.isTrain=isTrain<line_sep>self.modelType=modelType<line_sep>self.maxSeqLen=maxSeqLen<line_sep>#self.dropout = dropout
<block_end><def_stmt>check_samples_len self batch#function to check whether all samples are having the maxSeqLen mentioned
<block_start><for_stmt>samp batch<block_start><assert_stmt>len(samp['token_id'])<eq>self.maxSeqLen "token_id len doesn't match max seq len"<line_sep># for multiple encoders
<if_stmt>samp['type_id']<is><not><none><block_start><assert_stmt>len(samp['type_id'])<eq>self.maxSeqLen "type_id len doesn't match max seq len"<block_end><if_stmt>samp['mask']<is><not><none><block_start><assert_stmt>len(samp['mask'])<eq>self.maxSeqLen "mask len doesn't match max seq len"<block_end><block_end><block_end><def_stmt>make_batch_to_input_tensor self batch#check len in batch data
<block_start>self.check_samples_len(batch)<line_sep>batchSize=len(batch)<line_sep>hasTypeIds=<true><line_sep>hasAttnMasks=<true><if_stmt>batch[0]['type_id']<is><none><block_start>hasTypeIds=<false><block_end><if_stmt>batch[0]['mask']<is><none><block_start>hasAttnMasks=<false><block_end>#initializing token id, type id, attention mask tensors for this batch
tokenIdsBatchTensor=torch.LongTensor(batchSize self.maxSeqLen).fill_(0)<line_sep>typeIdsBatchTensor=torch.LongTensor(batchSize self.maxSeqLen).fill_(0)<line_sep>masksBatchTensor=torch.LongTensor(batchSize self.maxSeqLen).fill_(0)<line_sep>#fillling in data from sample
<for_stmt>i,sample enumerate(batch)<block_start>tokenIdsBatchTensor[i]=torch.LongTensor(sample['token_id'])<if_stmt>hasTypeIds<block_start>typeIdsBatchTensor[i]=torch.LongTensor(sample['type_id'])<block_end><if_stmt>hasAttnMasks<block_start>masksBatchTensor[i]=torch.LongTensor(sample['mask'])<block_end><block_end># meta deta will store more things like task id, task type etc.
batchMetaData={"token_id_pos":0 "type_id_pos":1 "mask_pos":2}<line_sep>batchData=[tokenIdsBatchTensor <none> <none>]#None, None in case type ids, attnMasks not required by model
<if_stmt>hasTypeIds<block_start>batchData[1]=typeIdsBatchTensor<block_end><if_stmt>hasAttnMasks<block_start>batchData[2]=masksBatchTensor<block_end><return>batchMetaData batchData<block_end><def_stmt>collate_fn self batch<block_start>'''
This function will be used by DataLoader to return batches
'''<line_sep>taskId=batch[0]["task"]["task_id"]<line_sep>taskType=batch[0]["task"]["task_type"]<line_sep>orgBatch=[]<line_sep>labels=[]<for_stmt>sample batch<block_start><assert_stmt>sample["task"]["task_id"]<eq>taskId<assert_stmt>sample["task"]["task_type"]<eq>taskType<line_sep>orgBatch.append(sample["sample"])<line_sep>labels.append(sample["sample"]["label"])<block_end>batch=orgBatch<line_sep>#making tensor batch data
batchMetaData,batchData=self.make_batch_to_input_tensor(batch)<line_sep>batchMetaData['task_id']=taskId<line_sep>batchMetaData['task_type']=taskType<line_sep>#adding label tensor when training (as they'll used for loss calculatoion and update)
# and in evaluation, it won't go with batch data, rather will keep it with meta data for metrics
<if_stmt>self.isTrain<block_start><if_stmt>taskType<in>(TaskType.SingleSenClassification TaskType.SentencePairClassification TaskType.NER)<block_start>batchData.append(torch.LongTensor(labels))<block_end>#position for label
batchMetaData['label_pos']=len(batchData)-1<block_end><else_stmt># for test/eval labels won't be added into batch, but kept in meta data
# so metric evaluation can be done
#batchData :- [tokenIdsBatchTensor, typeIdsBatchTensor, MasksBatchTensor]
<block_start>batchMetaData['label']=labels<block_end>batchMetaData['uids']=[sample['uid']<for>sample batch]# used in scoring
<return>batchMetaData batchData<block_end><block_end> |
#
# Copyright 2021 Espressif Systems (Shanghai) CO., LTD
#
# 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>construct Int16ul Int32ul Padding Struct<import_from_stmt>corefile BaseArchMethodsMixin BaseTargetMethods ESPCoreDumpLoaderError<try_stmt><block_start><import_from_stmt>typing Any Optional Tuple<block_end><except_stmt>ImportError<block_start><pass><block_end>RISCV_GP_REGS_COUNT=32<line_sep>PRSTATUS_SIZE=204<line_sep>PRSTATUS_OFFSET_PR_CURSIG=12<line_sep>PRSTATUS_OFFSET_PR_PID=24<line_sep>PRSTATUS_OFFSET_PR_REG=72<line_sep>ELF_GREGSET_T_SIZE=128<line_sep>PrStruct=Struct(Padding(PRSTATUS_OFFSET_PR_CURSIG) 'pr_cursig'/Int16ul Padding(PRSTATUS_OFFSET_PR_PID-PRSTATUS_OFFSET_PR_CURSIG-Int16ul.sizeof()) 'pr_pid'/Int32ul Padding(PRSTATUS_OFFSET_PR_REG-PRSTATUS_OFFSET_PR_PID-Int32ul.sizeof()) 'regs'/Int32ul[RISCV_GP_REGS_COUNT] Padding(PRSTATUS_SIZE-PRSTATUS_OFFSET_PR_REG-ELF_GREGSET_T_SIZE))<class_stmt>RiscvMethodsMixin(BaseArchMethodsMixin)<block_start>@staticmethod<def_stmt>get_registers_from_stack data grows_down# type: (bytes, bool) -> Tuple[list[int], Optional[dict[int, int]]]
<block_start>regs=Int32ul[RISCV_GP_REGS_COUNT].parse(data)<if_stmt><not>grows_down<block_start><raise>ESPCoreDumpLoaderError('Growing up stacks are not supported for now!')<block_end><return>regs <none><block_end>@staticmethod<def_stmt>build_prstatus_data tcb_addr task_regs# type: (int, list[int]) -> Any
<block_start><return>PrStruct.build({'pr_cursig':0 'pr_pid':tcb_addr 'regs':task_regs })<block_end><block_end><class_stmt>Esp32c3Methods(BaseTargetMethods RiscvMethodsMixin)<block_start>TARGET='esp32c3'<block_end> |
# Python Standard Library Imports
<import_stmt>re<line_sep># Third Party (PyPI) Imports
<import_stmt>requests<import_stmt>rollbar<import_stmt>six.moves.urllib<as>urllib<line_sep># HTK Imports
<import_from_stmt>htk.lib.oembed.cachekeys OembedResponseCache<import_from_stmt>htk.lib.oembed.constants *<import_from_stmt>htk.utils.request get_current_request<def_stmt>get_oembed_html url autoplay=<false><block_start>"""Gets the oEmbed HTML for a URL, if it is an oEmbed type
"""<line_sep>oembed_type=get_oembed_type(url)<if_stmt>oembed_type<block_start><if_stmt>oembed_type<eq>'youtube'<block_start>html=youtube_oembed(url autoplay=autoplay)<block_end><else_stmt><block_start>html=get_oembed_html_for_service(url oembed_type)<block_end><block_end><else_stmt><block_start>html=<none><block_end><return>html<block_end><def_stmt>get_oembed_html_for_service url service<block_start>"""Returns the oEmbed HTML for `service` (YouTube, Vimeo, etc)
Makes an HTTP request, so we should probably cache its response
"""<line_sep>c=OembedResponseCache(prekey=url)<line_sep>html=c.get()<if_stmt>html<is><none><block_start>request=<none><line_sep>success=<false><try_stmt><block_start>oembed_base_url=OEMBED_BASE_URLS[service]<line_sep>oembed_url=oembed_base_url%{'url':urllib.parse.quote(url) }<line_sep>response=requests.get(oembed_url)<if_stmt>response.status_code<ge>400<block_start><pass><block_end><else_stmt><block_start>data=response.json()<line_sep>html=data['html']<line_sep>c.cache_store(html)<line_sep>success=<true><block_end><block_end><except_stmt><block_start>request=get_current_request()<line_sep>extra_data={'message':'Bad oembed URL' 'oembed_url':oembed_url 'url':url 'response':{'status_code':response.status_code 'content':response.content }}<line_sep>rollbar.report_exc_info(level='warning' request=request extra_data=extra_data)<block_end><if_stmt>success<block_start><pass><block_end><else_stmt><block_start>html='<a href="%(url)s" target="_blank">%(url)s</a>'%{'url':url }<block_end><block_end><else_stmt><block_start><pass><block_end><return>html<block_end><def_stmt>get_oembed_type url<block_start>"""Determines the type of oEmbed this URL is, if it exists
"""<line_sep>oembed_type=<none><for_stmt>service,pattern OEMBED_URL_SCHEME_REGEXPS.items()<block_start><if_stmt>re.match(pattern url flags=re.I)<block_start>oembed_type=service<line_sep><break><block_end><block_end><return>oembed_type<block_end><def_stmt>youtube_oembed url autoplay=<false><block_start>html=get_oembed_html_for_service(url 'youtube')<if_stmt>autoplay<block_start>replacement='?feature=oembed&autoplay=1&rel=0&modestbranding=1'<block_end><else_stmt><block_start>replacement='?feature=oembed&rel=0&modestbranding=1'<block_end>html=re.sub(r'\?feature=oembed' replacement html)<line_sep><return>html<block_end><def_stmt>youtube_oembed_autoplay url<block_start>html=youtube_oembed(url autoplay=<true>)<line_sep><return>html<block_end> |
"""
Copyright (c) 2021 TU Darmstadt
Author: <NAME> <<EMAIL>>
License: Apache License 2.0
"""<import_from_future_stmt> print_function<import_stmt>os<import_stmt>torch<import_stmt>argparse<import_from_stmt>core.config cfg<def_stmt>add_global_arguments parser#
# Model details
#
<block_start>parser.add_argument("--snapshot-dir" type=str default='./snapshots' help="Where to save snapshots of the model.")<line_sep>parser.add_argument("--logdir" type=str default='./logs' help="Where to save log files of the model.")<line_sep>parser.add_argument("--exp" type=str default="main" help="ID of the experiment (multiple runs)")<line_sep>parser.add_argument("--run" type=str help="ID of the run")<line_sep>parser.add_argument('--workers' type=int default=8 metavar='N' help='dataloader threads')<line_sep>parser.add_argument('--seed' default=64 type=int help='seed for initializing training. ')<line_sep>#
# Inference only
#
parser.add_argument("--infer-list" default="voc12/val.txt" type=str)<line_sep>parser.add_argument('--mask-output-dir' type=str default=<none> help='path where to save masks')<line_sep>parser.add_argument("--resume" type=str default=<none> help="Snapshot \"ID,iter\" to load")<line_sep>#
# Configuration
#
parser.add_argument('--cfg' dest='cfg_file' required=<true> help='Config file for training (and optionally testing)')<line_sep>parser.add_argument('--set' dest='set_cfgs' help='Set config keys. Key value sequence seperate by whitespace.'<concat>'e.g. [key] [value] [key] [value]' default=[] nargs='+')<block_end><def_stmt>maybe_create_dir path<block_start><if_stmt><not>os.path.exists(path)<block_start>os.makedirs(path)<block_end><block_end><def_stmt>check_global_arguments args<block_start>args.cuda=torch.cuda.is_available()<line_sep>print("Available threads: " torch.get_num_threads())<line_sep>args.logdir=os.path.join(args.logdir args.exp args.run)<line_sep>maybe_create_dir(args.logdir)<line_sep>#
# Model directories
#
args.snapshot_dir=os.path.join(args.snapshot_dir args.exp args.run)<line_sep>maybe_create_dir(args.snapshot_dir)<block_end><def_stmt>get_arguments args_in<block_start>"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""<line_sep>parser=argparse.ArgumentParser(description="Dense Unsupervised Learning for Video Segmentation")<line_sep>add_global_arguments(parser)<line_sep>args=parser.parse_args(args_in)<line_sep>check_global_arguments(args)<line_sep><return>args<block_end> |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
<import_stmt>argparse<import_from_stmt>maro.cli.inspector.cim_dashboard start_cim_dashboard<import_from_stmt>maro.cli.inspector.citi_bike_dashboard start_citi_bike_dashboard<import_from_stmt>maro.cli.inspector.params GlobalScenarios<if_stmt>__name__<eq>'__main__'<block_start>parser=argparse.ArgumentParser()<line_sep>parser.add_argument("--source_path" type=str)<line_sep>parser.add_argument("--scenario" type=str)<line_sep>parser.add_argument("--epoch_num" type=int)<line_sep>parser.add_argument("--prefix" type=str)<line_sep>args=parser.parse_args()<line_sep>source_path=args.source_path<line_sep>scenario=GlobalScenarios(args.scenario)<line_sep>epoch_num=args.epoch_num<line_sep>prefix=args.prefix<if_stmt>scenario<eq>GlobalScenarios.CIM<block_start>start_cim_dashboard(source_path epoch_num prefix)<block_end><elif_stmt>scenario<eq>GlobalScenarios.CITI_BIKE<block_start>start_citi_bike_dashboard(source_path epoch_num prefix)<block_end><block_end> |
<import_from_stmt>jadi service<import_stmt>aj<line_sep>@service<class_stmt>ClientCertificateVerificator()<block_start><def_stmt>__init__ self context<block_start>self.context=context<block_end><def_stmt>verify self x509<block_start>serial=x509.get_serial_number()<line_sep>digest=x509.digest('sha1')<line_sep># logging.debug('SSL verify: %s / %s' % (x509.get_subject(), digest))
<for_stmt>c aj.config.data['ssl']['client_auth']['certificates']<block_start><if_stmt>int(c['serial'])<eq>serial<and>c['digest'].encode('utf-8')<eq>digest<block_start><return>c['user']<block_end><block_end><block_end><block_end> |
<import_stmt>numpy<as>np<def_stmt>get_PF_Results <block_start>results={10:{0:{'delta':{'Yyn':np.array([#10,0,deltaYyn
#BusTr_HV,Tr_LV,Load
1.0000001787261197 0.9990664471050634 0.9408623912831601 0.9999997973033823 0.9989329879720452 0.9398981202882926 1.000000023970535 0.9990124767159095 0.9422153531204793 ]) 'YNyn':np.array([#10,0,deltaYNyn
#BusTr_HV,Tr_LV,Load
1.0000001786899793 0.9990638105447855 0.9408586320432043 0.9999997971517767 0.9989338020819162 0.9398997093459485 1.000000024158281 0.9990142941344189 0.9422174830541402 ]) 'Dyn':np.array([#10,0,deltaDyn
#BusTr_HV,Tr_LV,Load
1.000000178603741 0.9990638106892 0.9408586322473715 0.9999997971832201 0.9989338020666364 0.9398997093074486 1.000000024213076 0.9990142940055439 0.9422174828921106 ]) 'Yzn':np.array([#10,0,deltaYzn
#BusTr_HV,Tr_LV,Load
1.000000178603741 0.9990638106892 0.9408586322473715 0.9999997971832201 0.9989338020666364 0.9398997093074486 1.000000024213076 0.9990142940055439 0.9422174828921106 ]) } 'wye':{'Yyn':np.array([#10,0,wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999998021362442 0.9915031010358111 0.9206318374527404 0.9999997791045989 1.0143417780460269 0.9616365638634155 1.000000418759289 0.9913387390190033 0.9408558778822637 ]) 'YNyn':np.array([#10,0,wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999997083766274 0.9988968962217385 0.9287452455114519 1.0000001672319114 0.999061839981782 0.9452915718541725 1.0000001243918462 0.9990504923797096 0.9488965582258678 ]) 'Dyn':np.array([#10,0,wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999599731432 0.9988963012384348 0.9287445940341739 0.999999734429128 0.9990625733649781 0.9452923634430362 1.000000305597812 0.9990503538577492 0.9488964199625295 ]) 'Yzn':np.array([#10,0,wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999599731432 0.9988963012384348 0.9287445940341739 0.999999734429128 0.9990625733649781 0.9452923634430362 1.000000305597812 0.9990503538577492 0.9488964199625295 ]) } 'delta_wye':{'Yyn':np.array([#10,0,delta_wyeYyn
#BusTr_HV,Tr_LV,Load
1.000000289039923 0.9945259444558469 0.9241479442057374 0.9999996598061066 1.0028660964609941 0.9332827547884484 1.0000000511540714 0.9989227003917809 0.9366758414321353 ]) 'YNyn':np.array([#10,0,delta_wyeYNyn
#BusTr_HV,Tr_LV,Load
1.0000001633660651 0.9988186334488024 0.9284513283443013 0.9999997731436624 0.9986857571039884 0.9290168825920521 1.0000000634904662 0.9987917974558278 0.9366076053493121 ]) 'Dyn':np.array([#10,0,delta_wyeDyn
#BusTr_HV,Tr_LV,Load
1.0000002947774138 0.9988183812973129 0.928451074375663 0.9999996601592913 0.9986859152711799 0.9290170457925304 1.0000000450633972 0.9987918914643369 0.936607696605823 ]) 'Yzn':np.array([#10,0,delta_wyeYzn
#BusTr_HV,Tr_LV,Load
1.0000002947774138 0.9988183812973129 0.928451074375663 0.9999996601592913 0.9986859152711799 0.9290170457925304 1.0000000450633972 0.9987918914643369 0.936607696605823 ]) } 'bal_wye':{'Yyn':np.array([#10,0,bal_wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999999999999879 0.9990668908275987 0.9446728357045939 0.9999999999999739 0.9990668910254652 0.9446728363197381 1.0000000000000384 0.9990668908667012 0.9446728362625954 ]) 'YNyn':np.array([#10,0,bal_wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999999999999863 0.9990668909016067 0.9446728357836535 0.9999999999999772 0.9990668908990621 0.9446728361848189 1.0000000000000362 0.9990668909190944 0.9446728363184529 ]) 'Dyn':np.array([#10,0,bal_wyeDyn
#BusTr_HV,Tr_LV,Load
0.999999999999989 0.999066890901618 0.9446728357836652 0.9999999999999737 0.999066890899081 0.9446728361848393 1.0000000000000375 0.999066890919066 0.9446728363184226 ]) 'Yzn':np.array([#10,0,bal_wyeYzn
#BusTr_HV,Tr_LV,Load
0.999999999999989 0.999066890901618 0.9446728357836652 0.9999999999999737 0.999066890899081 0.9446728361848393 1.0000000000000375 0.999066890919066 0.9446728363184226 ]) } } 1:{'delta':{'Yyn':np.array([#10,1,deltaYyn
#BusTr_HV,Tr_LV,Load
1.0000001795040512 1.0240495841864894 0.9674397511496959 0.9999997971910463 1.0239111614639989 0.9664923222986317 1.0000000233049395 1.0239935208058917 0.9687543048259518 ]) 'YNyn':np.array([#10,1,deltaYNyn
#BusTr_HV,Tr_LV,Load
1.0000001782704175 1.0240459468337655 0.9674352916726019 0.9999997977852046 1.0239130527637306 0.9664952324047731 1.0000000239444145 1.023995255504894 0.9687558295327158 ]) 'Dyn':np.array([#10,1,deltaDyn
#BusTr_HV,Tr_LV,Load
1.0000001782214243 1.024045946940332 0.967435291834159 0.9999997978066542 1.0239130527420286 0.9664952323430777 1.0000000239719584 1.023995255420507 0.9687558294364838 ]) 'Yzn':np.array([#10,1,deltaYzn
#BusTr_HV,Tr_LV,Load
1.0000001782214243 1.024045946940332 0.967435291834159 0.9999997978066542 1.0239130527420286 0.9664952323430777 1.0000000239719584 1.023995255420507 0.9687558294364838 ]) } 'wye':{'Yyn':np.array([#10,1,wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999998049723338 1.0163471727161444 0.9474851372085454 0.9999997835047069 1.0396033478524176 0.9883119194148919 1.0000004115230865 1.016177862041642 0.9670415224711911 ]) 'YNyn':np.array([#10,1,wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999997111904564 1.023876123903735 0.9557104532156954 1.000000169840967 1.024045000904823 0.97172789408756 1.0000001189689527 1.024030547850082 0.9752090807560196 ]) 'Dyn':np.array([#10,1,wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999610844935 1.0238755180281829 0.9557097928361534 0.9999997396431541 1.0240457481759326 0.9717286975282872 1.0000002992724317 1.0240304063318828 0.975208939465858 ]) 'Yzn':np.array([#10,1,wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999610844935 1.0238755180281829 0.9557097928361534 0.9999997396431541 1.0240457481759326 0.9717286975282872 1.0000002992724317 1.0240304063318828 0.975208939465858 ]) } 'delta_wye':{'Yyn':np.array([#10,1,delta_wyeYyn
#BusTr_HV,Tr_LV,Load
1.0000002896605282 1.0194026014413138 0.9509830141499932 0.9999996606572187 1.0279455302463374 0.9603073239465667 1.0000000496823542 1.0238970684816717 0.9633884768515291 ]) 'YNyn':np.array([#10,1,delta_wyeYNyn
#BusTr_HV,Tr_LV,Load
1.0000001631049464 1.0237965435008547 0.9553922424619002 0.9999997741736003 1.0236607923322103 0.9559358029296258 1.000000062721646 1.0237688359303385 0.9633200580357987 ]) 'Dyn':np.array([#10,1,delta_wyeDyn
#BusTr_HV,Tr_LV,Load
1.0000002940160242 1.023796285978077 0.9553919829548445 0.9999996614657936 1.0236609541452617 0.9559359697011912 1.000000044518284 1.0237689316654306 0.9633201512377196 ]) 'Yzn':np.array([#10,1,delta_wyeYzn
#BusTr_HV,Tr_LV,Load
1.0000002940160242 1.023796285978077 0.9553919829548445 0.9999996614657936 1.0236609541452617 0.9559359697011912 1.000000044518284 1.0237689316654306 0.9633201512377196 ]) } 'bal_wye':{'Yyn':np.array([#10,1,bal_wyeYyn
#BusTr_HV,Tr_LV,Load
0.99999999999999 1.02404859308445 0.971134029249497 0.9999999999999845 1.0240485931685195 0.9711340295967834 1.0000000000000258 1.0240485931044616 0.9711340295607079 ]) 'YNyn':np.array([#10,1,bal_wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999999999999892 1.0240485931151249 0.9711340292823146 0.9999999999999865 1.024048593114567 0.9711340295398108 1.0000000000000244 1.0240485931277552 0.9711340295848808 ]) 'Dyn':np.array([#10,1,bal_wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999999999902 1.024048593115119 0.9711340292823075 0.9999999999999848 1.0240485931145844 0.9711340295398292 1.0000000000000249 1.024048593127728 0.9711340295848522 ]) 'Yzn':np.array([#10,1,bal_wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999999999902 1.024048593115119 0.9711340292823075 0.9999999999999848 1.0240485931145844 0.9711340295398292 1.0000000000000249 1.024048593127728 0.9711340295848522 ]) } } } 11:{0:{'delta':{'Yyn':np.array([#11,0,deltaYyn
#BusTr_HV,Tr_LV,Load
1.0000001770832512 1.0991666419999009 1.046863039382953 0.9999997998271506 1.0990478952608114 1.0459974904307656 1.0000000230896342 1.0991196058562567 1.0480820977965253 ]) 'YNyn':np.array([#11,0,deltaYNyn
#BusTr_HV,Tr_LV,Load
1.000000177064337 1.0991653032170863 1.0468611006390927 0.9999997997417357 1.0990483460592901 1.0459983357170173 1.0000000231939636 1.0991204912844936 1.0480831713683516 ]) 'Dyn':np.array([#11,0,deltaDyn
#BusTr_HV,Tr_LV,Load
1.0000001770170086 1.099165303280019 1.046861100729514 0.9999997997589116 1.0990483460550085 1.0459983357036897 1.0000000232241157 1.0991204912259542 1.0480831712929268 ]) 'Yzn':np.array([#11,0,deltaYzn
#BusTr_HV,Tr_LV,Load
1.0000001770170086 1.099165303280019 1.046861100729514 0.9999997997589116 1.0990483460550085 1.0459983357036897 1.0000000232241157 1.0991204912259542 1.0480831712929268 ]) } 'wye':{'Yyn':np.array([#11,0,wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999998409135958 1.0924753274233265 1.0291805067306592 0.9999997887228856 1.112638254093763 1.0649872145063082 1.0000003703636224 1.0923417509837368 1.0468846408299153 ]) 'YNyn':np.array([#11,0,wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999997198861459 1.0990179190476412 1.0362148303868974 1.0000001764446427 1.0991669773561135 1.0507765134998273 1.0000001036695618 1.0991473807202723 1.0539233691792418 ]) 'Dyn':np.array([#11,0,wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999645965844 1.0990174387140366 1.036214314982853 0.9999997540341666 1.0991675482923782 1.0507771199594842 1.0000002813693196 1.0991472900387962 1.0539232794875342 ]) 'Yzn':np.array([#11,0,wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999645965844 1.0990174387140366 1.036214314982853 0.9999997540341666 1.0991675482923782 1.0507771199594842 1.0000002813693196 1.0991472900387962 1.0539232794875342 ]) } 'delta_wye':{'Yyn':np.array([#11,0,delta_wyeYyn
#BusTr_HV,Tr_LV,Load
1.0000002867915057 1.09511471406464 1.0320045668742739 0.9999996655448716 1.102582851029247 1.0401766570762196 1.0000000476637207 1.0990187740288424 1.0431968194073924 ]) 'YNyn':np.array([#11,0,delta_wyeYNyn
#BusTr_HV,Tr_LV,Load
1.0000001623852481 1.0989490480618516 1.0358488170212126 0.9999997776678232 1.098829878782537 1.0363599386677118 1.0000000599471168 1.0989238972185933 1.0431472226133363 ]) 'Dyn':np.array([#11,0,delta_wyeDyn
#BusTr_HV,Tr_LV,Load
1.000000291479138 1.0989488469146447 1.0358486145520418 0.9999996659434413 1.0988300000349813 1.0363600632236267 1.0000000425775202 1.098923977128452 1.0431473008280179 ]) 'Yzn':np.array([#11,0,delta_wyeYzn
#BusTr_HV,Tr_LV,Load
1.000000291479138 1.0989488469146447 1.0358486145520418 0.9999996659434413 1.0988300000349813 1.0363600632236267 1.0000000425775202 1.098923977128452 1.0431473008280179 ]) } 'bal_wye':{'Yyn':np.array([#11,0,bal_wyeYyn
#BusTr_HV,Tr_LV,Load
0.999999999999994 1.0991663222840553 1.0502483483014522 0.999999999999986 1.0991663223629755 1.0502483485683893 1.00000000000002 1.0991663223022374 1.0502483485566558 ]) 'YNyn':np.array([#11,0,bal_wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999999999999934 1.0991663223142185 1.050248348333234 0.9999999999999878 1.0991663223125718 1.0502483485153113 1.000000000000019 1.0991663223224817 1.0502483485779557 ]) 'Dyn':np.array([#11,0,bal_wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999999999944 1.099166322314217 1.0502483483332314 0.999999999999986 1.0991663223125883 1.050248348515329 1.0000000000000195 1.099166322322463 1.0502483485779364 ]) 'Yzn':np.array([#11,0,bal_wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999999999944 1.099166322314217 1.0502483483332314 0.999999999999986 1.0991663223125883 1.050248348515329 1.0000000000000195 1.099166322322463 1.0502483485779364 ]) } } 1:{'delta':{'Yyn':np.array([#11,1,deltaYyn
#BusTr_HV,Tr_LV,Load
1.000000177759738 1.1266508599188314 1.075749945733859 0.9999997996753168 1.1265276819882335 1.0748995015125222 1.0000000225649812 1.1266018378562361 1.076934372664356 ]) 'YNyn':np.array([#11,1,deltaYNyn
#BusTr_HV,Tr_LV,Load
1.000000176730594 1.1266486259211201 1.0757473443700512 0.9999998002521623 1.1265290107226675 1.0749013345769867 1.0000000230172796 1.1266027366684568 1.0769351304583261 ]) 'Dyn':np.array([#11,1,deltaDyn
#BusTr_HV,Tr_LV,Load
1.0000001767039686 1.1266486259729462 1.0757473444450258 0.9999998002646232 1.1265290107113315 1.0749013345478544 1.0000000230314439 1.126602736628164 1.0769351304141572 ]) 'Yzn':np.array([#11,1,deltaYzn
#BusTr_HV,Tr_LV,Load
1.0000001767039686 1.1266486259729462 1.0757473444450258 0.9999998002646232 1.1265290107113315 1.0749013345478544 1.0000000230314439 1.126602736628164 1.0769351304141572 ]) } 'wye':{'Yyn':np.array([#11,1,wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999998425139852 1.1198215550651343 1.0582701679876008 0.999999792808548 1.1404037383383383 1.0940119347447643 1.000000364677568 1.119678656475928 1.0754147798091545 ]) 'YNyn':np.array([#11,1,wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999997220234313 1.1264984365036237 1.065423794124721 1.0000001785338588 1.126651120595415 1.0795452055229118 1.0000000994430542 1.126629015453866 1.0825891788506536 ]) 'Dyn':np.array([#11,1,wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999654333293 1.1264979466596041 1.0654232703853377 0.9999997580954444 1.1266517031402583 1.079545822405393 1.0000002764712945 1.1266289226736226 1.0825890870214312 ]) 'Yzn':np.array([#11,1,wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999654333293 1.1264979466596041 1.0654232703853377 0.9999997580954444 1.1266517031402583 1.079545822405393 1.0000002764712945 1.1266289226736226 1.0825890870214312 ]) } 'delta_wye':{'Yyn':np.array([#11,1,delta_wyeYyn
#BusTr_HV,Tr_LV,Load
1.0000002872593454 1.122503013135439 1.061107915739188 0.9999996662661563 1.1301536319129346 1.069448792307849 1.0000000464745962 1.1264944198323028 1.0721922685731713 ]) 'YNyn':np.array([#11,1,delta_wyeYNyn
#BusTr_HV,Tr_LV,Load
1.0000001621739123 1.126428316031026 1.0650458103409908 0.9999997785161929 1.1263065012425137 1.0655375147447366 1.0000000593100822 1.12640238251751 1.0721435619381965 ]) 'Dyn':np.array([#11,1,delta_wyeDyn
#BusTr_HV,Tr_LV,Load
1.0000002908474748 1.1264281104824707 1.0650456033928053 0.9999996670234566 1.1263066253385652 1.065537642082384 1.0000000421291677 1.126402463985756 1.0721436418376473 ]) 'Yzn':np.array([#11,1,delta_wyeYzn
#BusTr_HV,Tr_LV,Load
1.0000002908474748 1.1264281104824707 1.0650456033928053 0.9999996670234566 1.1263066253385652 1.065537642082384 1.0000000421291677 1.126402463985756 1.0721436418376473 ]) } 'bal_wye':{'Yyn':np.array([#11,1,bal_wyeYyn
#BusTr_HV,Tr_LV,Load
0.9999999999999946 1.126649305937712 1.0790357881145098 0.9999999999999919 1.1266493059651883 1.0790357882640247 1.0000000000000135 1.1266493059449603 1.0790357882526134 ]) 'YNyn':np.array([#11,1,bal_wyeYNyn
#BusTr_HV,Tr_LV,Load
0.9999999999999944 1.126649305947411 1.079035788124742 0.9999999999999928 1.126649305946962 1.0790357882450081 1.000000000000013 1.1266493059535365 1.079035788261449 ]) 'Dyn':np.array([#11,1,bal_wyeDyn
#BusTr_HV,Tr_LV,Load
0.9999999999999944 1.1266493059473897 1.0790357881247188 0.9999999999999922 1.1266493059469642 1.079035788245011 1.0000000000000133 1.1266493059535063 1.0790357882614174 ]) 'Yzn':np.array([#11,1,bal_wyeYzn
#BusTr_HV,Tr_LV,Load
0.9999999999999944 1.1266493059473897 1.0790357881247188 0.9999999999999922 1.1266493059469642 1.079035788245011 1.0000000000000133 1.1266493059535063 1.0790357882614174 ]) } } } }<line_sep><return>results<block_end> |
"""
Modified from https://colab.research.google.com/github/PytorchLightning/pytorch-lightning/blob/master/notebooks/01-mnist-hello-world.ipynb
Added labml logger
"""<import_stmt>pytorch_lightning<as>pl<import_stmt>torch<import_from_stmt>pytorch_lightning.metrics.functional accuracy<import_from_stmt>torch nn<import_from_stmt>torch.nn functional<as>F<import_from_stmt>torch.utils.data DataLoader random_split<import_from_stmt>torchvision transforms<import_from_stmt>torchvision.datasets MNIST<import_from_stmt>labml lab experiment<import_from_stmt>labml.utils.lightning LabMLLightningLogger<class_stmt>LitMNIST(pl.LightningModule)<block_start><def_stmt>__init__ self hidden_size=64 learning_rate=2e-4<block_start>super().__init__()<line_sep># Set our init args as class attributes
self.hidden_size=hidden_size<line_sep>self.learning_rate=learning_rate<line_sep># Hardcode some dataset specific attributes
self.num_classes=10<line_sep>self.dims=(1 28 28)<line_sep>channels,width,height=self.dims<line_sep>self.transform=transforms.Compose([transforms.ToTensor() transforms.Normalize((0.1307 ) (0.3081 ))])<line_sep># Define PyTorch model
self.model=nn.Sequential(nn.Flatten() nn.Linear(channels<times>width<times>height hidden_size) nn.ReLU() nn.Dropout(0.1) nn.Linear(hidden_size hidden_size) nn.ReLU() nn.Dropout(0.1) nn.Linear(hidden_size self.num_classes))<block_end><def_stmt>forward self x<block_start>x=self.model(x)<line_sep><return>F.log_softmax(x dim=1)<block_end><def_stmt>training_step self batch batch_idx<block_start>x,y=batch<line_sep>logits=self(x)<line_sep>loss=F.nll_loss(logits y)<line_sep>preds=torch.argmax(logits dim=1)<line_sep>acc=accuracy(preds y)<line_sep>self.log('loss.train' loss)<line_sep>self.log('accuracy.train' acc)<line_sep><return>loss<block_end><def_stmt>validation_step self batch batch_idx<block_start>x,y=batch<line_sep>logits=self(x)<line_sep>loss=F.nll_loss(logits y)<line_sep>preds=torch.argmax(logits dim=1)<line_sep>acc=accuracy(preds y)<line_sep># Calling self.log will surface up scalars for you in TensorBoard
self.log('loss.valid' loss)<line_sep>self.log('accuracy.valid' acc)<line_sep><return>loss<block_end><def_stmt>test_step self batch batch_idx# Here we just reuse the validation_step for testing
<block_start><return>self.validation_step(batch batch_idx)<block_end><def_stmt>configure_optimizers self<block_start>optimizer=torch.optim.Adam(self.parameters() lr=self.learning_rate)<line_sep><return>optimizer<block_end>####################
# DATA RELATED HOOKS
####################
<def_stmt>prepare_data self# download
<block_start>MNIST(str(lab.get_data_path()) train=<true> download=<true>)<line_sep>MNIST(str(lab.get_data_path()) train=<false> download=<true>)<block_end><def_stmt>setup self stage=<none># Assign train/val datasets for use in dataloaders
<block_start><if_stmt>stage<eq>'fit'<or>stage<is><none><block_start>mnist_full=MNIST(str(lab.get_data_path()) train=<true> transform=self.transform)<line_sep>self.mnist_train,self.mnist_val=random_split(mnist_full [55000 5000])<block_end># Assign test dataset for use in dataloader(s)
<if_stmt>stage<eq>'test'<or>stage<is><none><block_start>self.mnist_test=MNIST(str(lab.get_data_path()) train=<false> transform=self.transform)<block_end><block_end><def_stmt>train_dataloader self<block_start><return>DataLoader(self.mnist_train batch_size=32)<block_end><def_stmt>val_dataloader self<block_start><return>DataLoader(self.mnist_val batch_size=32)<block_end><def_stmt>test_dataloader self<block_start><return>DataLoader(self.mnist_test batch_size=32)<block_end><block_end><def_stmt>main <block_start>experiment.create(name='mnist_lit_lightening' disable_screen=<true>)<line_sep>model=LitMNIST()<line_sep>trainer=pl.Trainer(gpus=1 max_epochs=3 progress_bar_refresh_rate=20 logger=LabMLLightningLogger())<with_stmt>experiment.start()<block_start>trainer.fit(model)<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_stmt>numpy<import_stmt>torch<import_from_stmt>allennlp.modules.span_extractors SpanExtractor SelfAttentiveSpanExtractor<import_from_stmt>allennlp.common.params Params<class_stmt>TestSelfAttentiveSpanExtractor<block_start><def_stmt>test_locally_normalised_span_extractor_can_build_from_params self<block_start>params=Params({"type":"self_attentive" "input_dim":7 "num_width_embeddings":5 "span_width_embedding_dim":3 })<line_sep>extractor=SpanExtractor.from_params(params)<assert_stmt>isinstance(extractor SelfAttentiveSpanExtractor)<assert_stmt>extractor.get_output_dim()<eq>10<block_end># input_dim + span_width_embedding_dim
<def_stmt>test_attention_is_normalised_correctly self<block_start>input_dim=7<line_sep>sequence_tensor=torch.randn([2 5 input_dim])<line_sep>extractor=SelfAttentiveSpanExtractor(input_dim=input_dim)<assert_stmt>extractor.get_output_dim()<eq>input_dim<assert_stmt>extractor.get_input_dim()<eq>input_dim<line_sep># In order to test the attention, we'll make the weight which computes the logits
# zero, so the attention distribution is uniform over the sentence. This lets
# us check that the computed spans are just the averages of their representations.
extractor._global_attention._module.weight.data.fill_(0.0)<line_sep>extractor._global_attention._module.bias.data.fill_(0.0)<line_sep>indices=torch.LongTensor([[[1 3] [2 4]] [[0 2] [3 4]]])<line_sep># smaller span tests masking.
span_representations=extractor(sequence_tensor indices)<assert_stmt>list(span_representations.size())<eq>[2 2 input_dim]<line_sep># First element in the batch.
batch_element=0<line_sep>spans=span_representations[batch_element]<line_sep># First span.
mean_embeddings=sequence_tensor[batch_element 1:4 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[0].data.numpy() mean_embeddings.data.numpy())<line_sep># Second span.
mean_embeddings=sequence_tensor[batch_element 2:5 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[1].data.numpy() mean_embeddings.data.numpy())<line_sep># Now the second element in the batch.
batch_element=1<line_sep>spans=span_representations[batch_element]<line_sep># First span.
mean_embeddings=sequence_tensor[batch_element 0:3 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[0].data.numpy() mean_embeddings.data.numpy())<line_sep># Second span.
mean_embeddings=sequence_tensor[batch_element 3:5 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[1].data.numpy() mean_embeddings.data.numpy())<line_sep># Now test the case in which we have some masked spans in our indices.
indices_mask=torch.tensor([[<true> <true>] [<true> <false>]])<line_sep>span_representations=extractor(sequence_tensor indices span_indices_mask=indices_mask)<line_sep># First element in the batch.
batch_element=0<line_sep>spans=span_representations[batch_element]<line_sep># First span.
mean_embeddings=sequence_tensor[batch_element 1:4 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[0].data.numpy() mean_embeddings.data.numpy())<line_sep># Second span.
mean_embeddings=sequence_tensor[batch_element 2:5 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[1].data.numpy() mean_embeddings.data.numpy())<line_sep># Now the second element in the batch.
batch_element=1<line_sep>spans=span_representations[batch_element]<line_sep># First span.
mean_embeddings=sequence_tensor[batch_element 0:3 :].mean(0)<line_sep>numpy.testing.assert_array_almost_equal(spans[0].data.numpy() mean_embeddings.data.numpy())<line_sep># Second span was masked, so should be completely zero.
numpy.testing.assert_array_almost_equal(spans[1].data.numpy() numpy.zeros([input_dim]))<block_end><def_stmt>test_widths_are_embedded_correctly self<block_start>input_dim=7<line_sep>max_span_width=5<line_sep>span_width_embedding_dim=3<line_sep>output_dim=input_dim+span_width_embedding_dim<line_sep>extractor=SelfAttentiveSpanExtractor(input_dim=input_dim num_width_embeddings=max_span_width span_width_embedding_dim=span_width_embedding_dim )<assert_stmt>extractor.get_output_dim()<eq>output_dim<assert_stmt>extractor.get_input_dim()<eq>input_dim<line_sep>sequence_tensor=torch.randn([2 max_span_width input_dim])<line_sep>indices=torch.LongTensor([[[1 3] [0 4] [0 0]] [[0 2] [1 4] [2 2]]])<line_sep># smaller span tests masking.
span_representations=extractor(sequence_tensor indices)<assert_stmt>list(span_representations.size())<eq>[2 3 output_dim]<line_sep>width_embeddings=extractor._span_width_embedding.weight.data.numpy()<line_sep>widths_minus_one=indices[<ellipsis> 1]-indices[<ellipsis> 0]<for_stmt>element range(indices.size(0))<block_start><for_stmt>span range(indices.size(1))<block_start>width=widths_minus_one[element span].item()<line_sep>width_embedding=span_representations[element span input_dim:]<line_sep>numpy.testing.assert_array_almost_equal(width_embedding.data.numpy() width_embeddings[width])<block_end><block_end><block_end><block_end> |
<import_from_stmt>hypothesis given<import_from_stmt>hypothesis.strategies binary<import_from_stmt>mitmproxy options<import_from_stmt>mitmproxy.connection Client<import_from_stmt>mitmproxy.proxy.context Context<import_from_stmt>mitmproxy.proxy.events DataReceived<import_from_stmt>mitmproxy.proxy.layers.modes Socks5Proxy<line_sep>opts=options.Options()<line_sep>tctx=Context(Client(("client" 1234) ("127.0.0.1" 8080) 1605699329) opts)<line_sep>@given(binary())<def_stmt>test_socks5_fuzz data<block_start>layer=Socks5Proxy(tctx)<line_sep>list(layer.handle_event(DataReceived(tctx.client data)))<block_end> |
"""Tests for Nikola."""<line_sep> |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2012 California Institute of Technology. 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.
#
# United States Government Sponsorship acknowledged. This software is subject to
# U.S. export control laws and regulations and has been classified as 'EAR99 NLR'
# (No [Export] License Required except when exporting to an embargoed country,
# end user, or in support of a prohibited end use). By downloading this software,
# the user agrees to comply with all applicable U.S. export laws and regulations.
# The user has the responsibility to obtain export licenses, or other export
# authority as may be required before exporting this software to any 'EAR99'
# embargoed foreign country or citizen of those countries.
#
# Author: <NAME>
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""Some specialized arithmetic exceptions for
Vector and Affine Spaces.
"""<line_sep>## \namespace geo::exceptions
## <a href="http://docs.python.org/2/library/exceptions.html">Exceptions</a>
## for Vector and Affines spaces.
## Base class for geometric errors
<class_stmt>GeometricException(ArithmeticError)<block_start>"""A base class- not to be raised"""<line_sep><pass><block_end>## A reminder to treat geometric objects properly.
<class_stmt>NonCovariantOperation(GeometricException)<block_start>"""Raise when you do something that is silly[1], like adding
a Scalar to a Vector\.
[1]Silly: (adj.) syn: non-covariant"""<line_sep><pass><block_end>## A reminder that Affine space are affine, and vector spaces are not.
<class_stmt>AffineSpaceError(GeometricException)<block_start>"""Raised when you forget the points in an affine space are
not vector in a vector space, and visa versa"""<line_sep><pass><block_end>## A catch-all for overlaoded operations getting non-sense.
<class_stmt>UndefinedGeometricOperation(GeometricException)<block_start>"""This will raised if you get do an opeation that has been defined for
a Tensor/Affine/Coordinate argument, but you just have a non-sense
combinabtion, like vector**vector.
"""<line_sep><pass><block_end>## This function should make a generic error message
<def_stmt>error_message op left right<block_start>"""message = error_message(op, left, right)
op is a method or a function
left is a geo object
right is probably a geo object.
message is what did not work
"""<line_sep><return>"%s(%s, %s)"%(op.__name__ left.__class__.__name__ right.__class__.__name__)<block_end> |
<import_stmt>time<import_stmt>datetime<import_stmt>os<import_stmt>sys<import_stmt>numpy<as>np<line_sep>use_cntk=<true><if_stmt>use_cntk<block_start><try_stmt><block_start>base_directory=os.path.split(sys.executable)[0]<line_sep>os.environ['PATH']<augadd>';'+base_directory<import_stmt>cntk<line_sep>os.environ['KERAS_BACKEND']='cntk'<block_end><except_stmt>ImportError<block_start>print('CNTK not installed')<block_end><block_end><else_stmt><block_start>os.environ['KERAS_BACKEND']='tensorflow'<line_sep>os.environ['CUDA_VISIBLE_DEVICES']='0'<block_end><import_stmt>keras<def_stmt>learning_word_embeddings_with_the_embedding_layer # Number of words to consider as features
<block_start>max_features=10000<line_sep># Cut texts after this number of words
# (among top max_features most common words)
maxlen=20<line_sep># Load the data as lists of integers.
(x_train y_train),(x_test y_test)=keras.datasets.imdb.load_data(num_words=max_features)<line_sep># This turns our lists of integers
# into a 2D integer tensor of shape `(samples, maxlen)`
x_train=keras.preprocessing.sequence.pad_sequences(x_train maxlen=maxlen)<line_sep>x_test=keras.preprocessing.sequence.pad_sequences(x_test maxlen=maxlen)<line_sep>model=keras.models.Sequential()<line_sep># We specify the maximum input length to our Embedding layer
# so we can later flatten the embedded inputs
model.add(keras.layers.Embedding(max_features 8 input_length=maxlen))<line_sep># After the Embedding layer,
# our activations have shape `(samples, maxlen, 8)`.
# We flatten the 3D tensor of embeddings
# into a 2D tensor of shape `(samples, maxlen * 8)`
model.add(keras.layers.Flatten())<line_sep># We add the classifier on top
model.add(keras.layers.Dense(1 activation='sigmoid'))<line_sep>model.compile(optimizer='rmsprop' loss='binary_crossentropy' metrics=['acc'])<line_sep>model.summary()<line_sep>history=model.fit(x_train y_train epochs=10 batch_size=32 validation_split=0.2)<block_end><def_stmt>learning_word_embeddings_with_the_embedding_layer_cntk <block_start>x_train,y_train,x_test,y_test=load_from_files()<line_sep>max_features=10000<line_sep>maxlen=20<line_sep>embedding_dim=8<line_sep>x=cntk.input_variable(shape=(maxlen ) dtype=np.float32)<line_sep>y=cntk.input_variable(shape=(1 ) dtype=np.float32)<line_sep>model=cntk.one_hot(x num_classes=max_features sparse_output=<true>)<line_sep>model=cntk.layers.Embedding(embedding_dim)(model)<line_sep>model=cntk.layers.Dense(1 activation=cntk.sigmoid)(model)<line_sep>loss_function=cntk.binary_cross_entropy(model.output y)<line_sep>round_predictions=cntk.round(model.output)<line_sep>equal_elements=cntk.equal(round_predictions y)<line_sep>accuracy_function=cntk.reduce_mean(equal_elements axis=0)<line_sep>max_epochs=30<line_sep>batch_size=32<line_sep>learner=cntk.adam(model.parameters cntk.learning_parameter_schedule_per_sample(0.0001) cntk.learning_parameter_schedule_per_sample(0.99))<line_sep>progress_printer=cntk.logging.ProgressPrinter(tag='Training' num_epochs=max_epochs)<line_sep>trainer=cntk.Trainer(model (loss_function accuracy_function) [learner] progress_printer)<line_sep>evaluator=cntk.Evaluator(accuracy_function)<line_sep>cntk_train(x y x_train y_train max_epochs batch_size trainer evaluator)<block_end><def_stmt>cntk_train x y x_train y_train max_epochs batch_size trainer evaluator<block_start>N=len(x_train)<line_sep>y_train=np.expand_dims(y_train axis=1)<line_sep>train_features=x_train[:int(N<times>0.8)]<line_sep>train_labels=y_train[:int(N<times>0.8)]<line_sep>validation_features=x_train[int(N<times>0.8):]<line_sep>validation_labels=y_train[int(N<times>0.8):]<for_stmt>current_epoch range(max_epochs)<block_start>epoch_start_time=time.time()<line_sep>train_indices=np.random.permutation(train_features.shape[0])<line_sep>pos=0<line_sep>epoch_training_error=0<line_sep>num_batches=0<while_stmt>pos<l>len(train_indices)<block_start>pos_end=min(pos+batch_size len(train_indices))<line_sep>x_train_minibatch=train_features[train_indices[pos:pos_end]]<line_sep>y_train_minibatch=train_labels[train_indices[pos:pos_end]]<line_sep>trainer.train_minibatch({x:x_train_minibatch y:y_train_minibatch})<line_sep>epoch_training_error<augadd>trainer.previous_minibatch_evaluation_average<line_sep>num_batches<augadd>1<line_sep>pos=pos_end<block_end>epoch_training_error<augdiv>num_batches<line_sep>epoch_validation_error=0<line_sep>num_batches=0<line_sep>pos=0<while_stmt>pos<l>len(validation_features)<block_start>pos_end=min(pos+batch_size len(validation_features))<line_sep>x_train_minibatch=validation_features[pos:pos_end]<line_sep>y_train_minibatch=validation_labels[pos:pos_end]<line_sep>previous_minibatch_evaluation_average=evaluator.test_minibatch({x:x_train_minibatch y:y_train_minibatch})<line_sep>epoch_validation_error<augadd>previous_minibatch_evaluation_average<line_sep>num_batches<augadd>1<line_sep>pos=pos_end<block_end>epoch_validation_error<augdiv>num_batches<line_sep>print('Epoch Elapsed Time: {0}, training_accuracy={1:.3f}, evaluation_accuracy={2:.3f}'.format(datetime.timedelta(seconds=time.time()-epoch_start_time) epoch_training_error epoch_validation_error))<block_end><block_end><def_stmt>save_to_files x_train y_train x_test y_test<block_start>x_train=np.ascontiguousarray(x_train.astype(np.float32))<line_sep>y_train=np.ascontiguousarray(y_train.astype(np.float32))<line_sep>x_test=np.ascontiguousarray(x_test.astype(np.float32))<line_sep>y_test=np.ascontiguousarray(y_test.astype(np.float32))<line_sep>print(x_train.shape y_train.shape x_test.shape y_test.shape)<line_sep>x_train.tofile('x_train_imdb.bin')<line_sep>y_train.tofile('y_train_imdb.bin')<line_sep>x_test.tofile('x_test_imdb.bin')<line_sep>y_test.tofile('y_test_imdb.bin')<block_end><def_stmt>load_from_files x_shape=(25000 20) y_shape=(25000 )<block_start>print('Loading .bin files')<line_sep>x_train=np.fromfile('x_train_imdb.bin' dtype=np.float32)<line_sep>y_train=np.fromfile('y_train_imdb.bin' dtype=np.float32)<line_sep>x_test=np.fromfile('x_test_imdb.bin' dtype=np.float32)<line_sep>y_test=np.fromfile('y_test_imdb.bin' dtype=np.float32)<line_sep>x_train=np.reshape(x_train newshape=x_shape)<line_sep>y_train=np.reshape(y_train newshape=y_shape)<line_sep>x_test=np.reshape(x_test newshape=x_shape)<line_sep>y_test=np.reshape(y_test newshape=y_shape)<line_sep><return>x_train y_train x_test y_test<block_end><class_stmt>Constants<block_start>maxlen=100# We will cut reviews after 100 words
training_samples=200# We will be training on 200 samples
validation_samples=10000# We will be validating on 10000 samples
max_words=10000# We will only consider the top 10,000 words in the dataset
embedding_dim=100<line_sep>imdb_dir='C:\\Users\\anastasios\\Downloads\\aclImdb'<block_end><def_stmt>load_texts_labels path<block_start><import_stmt>tqdm<line_sep>labels=[]<line_sep>texts=[]<for_stmt>label_type ['neg' 'pos']<block_start>dir_name=os.path.join(path label_type)<line_sep>print('\nLoading ' dir_name '\n' flush=<true>)<for_stmt>fname tqdm.tqdm(os.listdir(dir_name))<block_start><if_stmt>fname[-4:]<eq>'.txt'<block_start>f=open(os.path.join(dir_name fname) encoding='utf8')<line_sep>texts.append(f.read())<line_sep>f.close()<if_stmt>label_type<eq>'neg'<block_start>labels.append(0)<block_end><else_stmt><block_start>labels.append(1)<block_end><block_end><block_end><block_end><return>texts labels<block_end><def_stmt>tokenize_alImdb <block_start><import_stmt>keras.preprocessing.text<line_sep>train_dir=os.path.join(Constants.imdb_dir 'train')<line_sep>texts,labels=load_texts_labels(train_dir)<line_sep>tokenizer=keras.preprocessing.text.Tokenizer(num_words=Constants.max_words)<line_sep>print('\n\nRunning tokenizer...' end='' flush=<true>)<line_sep>tokenizer.fit_on_texts(texts)<line_sep><return>tokenizer texts labels<block_end><def_stmt>from_raw_text_to_word_embeddings <block_start><import_stmt>numpy<as>np<import_stmt>keras.preprocessing.sequence<line_sep>tokenizer,texts,labels=tokenize_alImdb()<line_sep>sequences=tokenizer.texts_to_sequences(texts)<line_sep>word_index=tokenizer.word_index<line_sep>print('Found %s unique tokens.'%len(word_index))<line_sep>data=keras.preprocessing.sequence.pad_sequences(sequences maxlen=Constants.maxlen)<line_sep>data=np.asarray(data dtype=np.float32)<line_sep>labels=np.asarray(labels dtype=np.float32)<line_sep>print('Shape of data tensor:' data.shape)<line_sep>print('Shape of label tensor:' labels.shape)<line_sep># Split the data into a training set and a validation set
# But first, shuffle the data, since we started from data
# where sample are ordered (all negative first, then all positive).
indices=np.arange(data.shape[0])<line_sep>np.random.shuffle(indices)<line_sep>data=data[indices]<line_sep>labels=labels[indices]<line_sep>x_train=data[:Constants.training_samples]<line_sep>y_train=labels[:Constants.training_samples]<line_sep>x_val=data[Constants.training_samples:Constants.training_samples+Constants.validation_samples]<line_sep>y_val=labels[Constants.training_samples:Constants.training_samples+Constants.validation_samples]<line_sep><return>tokenizer x_train y_train x_val y_val<block_end><def_stmt>preprocess_embeddings <block_start><import_stmt>numpy<as>np<import_stmt>tqdm<line_sep>glove_dir='C:\\Users\\anastasios\\Downloads\\glove.6B'<line_sep>embeddings_index={}<line_sep>glove_path=os.path.join(glove_dir 'glove.6B.100d.txt')<line_sep>f=open(glove_path encoding='utf8')<line_sep>print('Processing ' glove_path)<for_stmt>line f<block_start>values=line.split()<line_sep>word=values[0]<line_sep>coefs=np.asarray(values[1:] dtype='float32')<line_sep>embeddings_index[word]=coefs<block_end>f.close()<line_sep>print('Found %s word vectors.'%len(embeddings_index))<line_sep><return>embeddings_index<block_end><def_stmt>build_model <block_start>model=keras.models.Sequential()<line_sep>model.add(keras.layers.Embedding(Constants.max_words Constants.embedding_dim input_length=Constants.maxlen))<line_sep>model.add(keras.layers.Flatten())<line_sep>model.add(keras.layers.Dense(32 activation='relu'))<line_sep>model.add(keras.layers.Dense(1 activation='sigmoid'))<line_sep>model.summary()<line_sep><return>model<block_end><def_stmt>use_glove_word_embeddings_cntk preload_weights=<false><block_start>tokenizer,x_train,y_train,x_val,y_val=from_raw_text_to_word_embeddings()<line_sep>x=cntk.input_variable(shape=(Constants.maxlen ) dtype=np.float32)<line_sep>y=cntk.input_variable(shape=(1 ) dtype=np.float32)<line_sep>model=cntk.one_hot(x num_classes=Constants.max_words sparse_output=<true>)<if_stmt>preload_weights<is><true><block_start>embedding_matrix=compute_embedding_matrix(tokenizer)<assert_stmt>(Constants.embedding_dim<eq>embedding_matrix.shape[0])<or>(Constants.embedding_dim<eq>embedding_matrix.shape[1])<line_sep>model=cntk.layers.Embedding(weights=embedding_matrix)(model)<block_end><else_stmt><block_start>model=cntk.layers.Embedding(Constants.embedding_dim)(model)<block_end>model=cntk.layers.Dense(32 activation=cntk.relu)(model)<line_sep>model=cntk.layers.Dense(1 activation=cntk.sigmoid)(model)<line_sep>loss_function=cntk.binary_cross_entropy(model.output y)<line_sep>round_predictions=cntk.round(model.output)<line_sep>equal_elements=cntk.equal(round_predictions y)<line_sep>accuracy_function=cntk.reduce_mean(equal_elements axis=0)<line_sep>max_epochs=10<line_sep>batch_size=32<line_sep>learner=cntk.adam(model.parameters cntk.learning_parameter_schedule_per_sample(0.0001) cntk.learning_parameter_schedule_per_sample(0.99))<line_sep>progress_printer=cntk.logging.ProgressPrinter(tag='Training' num_epochs=max_epochs)<line_sep>trainer=cntk.Trainer(model (loss_function accuracy_function) [learner] progress_printer)<line_sep>evaluator=cntk.Evaluator(accuracy_function)<line_sep>cntk_train(x y x_train y_train max_epochs batch_size trainer evaluator)<block_end><def_stmt>compute_embedding_matrix tokenizer<block_start>embeddings_index=preprocess_embeddings()<line_sep>embedding_matrix=np.zeros((Constants.max_words Constants.embedding_dim))<for_stmt>word,i tokenizer.word_index.items()<block_start>embedding_vector=embeddings_index.get(word)<if_stmt>i<l>Constants.max_words<block_start><if_stmt>embedding_vector<is><not><none># Words not found in embedding index will be all-zeros.
<block_start>embedding_matrix[i]=embedding_vector<block_end><block_end><block_end><return>embedding_matrix<block_end><def_stmt>use_glove_word_embeddings preload_weights=<true><block_start>tokenizer,x_train,y_train,x_val,y_val=from_raw_text_to_word_embeddings()<line_sep>model=build_model()<if_stmt>preload_weights<block_start>embedding_matrix=compute_embedding_matrix(tokenizer)<line_sep>model.layers[0].set_weights([embedding_matrix])<line_sep>model.layers[0].trainable=<false><block_end>model.compile(optimizer='rmsprop' loss='binary_crossentropy' metrics=['acc'])<line_sep>history=model.fit(x_train y_train epochs=10 batch_size=32 validation_data=(x_val y_val))<line_sep>model.save_weights('pre_trained_glove_model.h5')<line_sep>plot_results(history)<block_end><def_stmt>plot_results history<block_start><import_stmt>matplotlib.pyplot<as>plt<line_sep>acc=history.history['acc']<line_sep>val_acc=history.history['val_acc']<line_sep>loss=history.history['loss']<line_sep>val_loss=history.history['val_loss']<line_sep>epochs=range(1 len(acc)+1)<line_sep>plt.plot(epochs acc 'bo' label='Training acc')<line_sep>plt.plot(epochs val_acc 'b' label='Validation acc')<line_sep>plt.title('Training and validation accuracy')<line_sep>plt.legend()<line_sep>plt.figure()<line_sep>plt.plot(epochs loss 'bo' label='Training loss')<line_sep>plt.plot(epochs val_loss 'b' label='Validation loss')<line_sep>plt.title('Training and validation loss')<line_sep>plt.legend()<line_sep>plt.show()<block_end><def_stmt>evaluate_on_test_data <block_start><import_stmt>numpy<as>np<line_sep>test_dir=os.path.join(Constants.imdb_dir 'test')<line_sep>tokenizer,_,_=tokenize_alImdb()<line_sep>texts,labels=load_texts_labels(test_dir)<line_sep>sequences=tokenizer.texts_to_sequences(texts)<line_sep>x_test=keras.preprocessing.sequence.pad_sequences(sequences maxlen=Constants.maxlen)<line_sep>y_test=np.asarray(labels)<line_sep>model=build_model()<line_sep>model.load_weights('pre_trained_glove_model.h5')<line_sep>model.compile(optimizer='rmsprop' loss='binary_crossentropy' metrics=['acc'])<line_sep>print(model.evaluate(x_test y_test))<block_end><if_stmt>__name__<eq>'__main__'<block_start>learning_word_embeddings_with_the_embedding_layer()<line_sep># learning_word_embeddings_with_the_embedding_layer_cntk()
use_glove_word_embeddings(preload_weights=<true>)<line_sep># use_glove_word_embeddings_cntk(preload_weights=True)
<block_end> |
# Expression evaluation routines
<import_stmt>claripy<def_stmt>get_signed_range se expr<block_start>"""
Calculate the range of the expression with signed boundaries
"""<line_sep>size=expr.size()<line_sep>umin=umax=smin=smax=<none><if_stmt><not>sat_zero(se expr)<block_start><try_stmt><block_start>umin=se.min(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>0])<line_sep>umax=se.max(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>0])<line_sep><return>(umin umax)<block_end><except_stmt><block_start><pass><block_end><try_stmt><block_start>smin=-(1<lshift>size)+se.min(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>1])<line_sep>smax=-(1<lshift>size)+se.max(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>1])<line_sep><return>(smin smax)<block_end><except_stmt><block_start><pass><block_end><return><none><block_end><else_stmt><block_start><try_stmt><block_start>umax=se.max(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>0])<line_sep>smin=0<try_stmt><block_start>smin=-(1<lshift>size)+se.min(expr extra_constraints=[claripy.Extract(size-1 size-1 expr)<eq>1])<block_end><except_stmt><block_start><pass><block_end><return>(smin umax)<block_end><except_stmt><block_start><pass><block_end><return><none><block_end><block_end><def_stmt>sat_zero se expr<block_start><return>se.satisfiable(extra_constraints=([expr<eq>0]))<block_end><def_stmt>sat_negative se expr<block_start>size=expr.size()<line_sep><return>se.satisfiable(extra_constraints=([claripy.Extract(size-1 size-1 expr)<eq>1]))<block_end><def_stmt>sat_positive se expr<block_start><return>se.satisfiable(extra_constraints=([claripy.Extract(size-1 size-1 expr)<eq>0]))<block_end> |
<import_from_stmt>setuptools setup<line_sep>setup(name='Cortx S3-Label Studio Integration' version='1.0.0' packages=[''] url='' license='MIT ' author='sumit' author_email='<EMAIL>' description='Cortx S3 integration with Label Studio, one of the best open-source data annotation tool used by companies like Nvidia, IBM, Cloudflare. Using Cortx Ecosystem to store world\'s growing unstructured data and making AI/ML tasks faster. Cortx provides scalability, efficiency and security anytime.')<line_sep> |
<import_stmt>torch<import_stmt>torch.nn<as>nn<import_stmt>torch.nn.functional<as>F<import_from_stmt>torch.utils.checkpoint checkpoint<def_stmt>identity x *args **kwargs<block_start><return>x<block_end><def_stmt>get_act activation<block_start><if_stmt>activation<eq>"gelu"<block_start><return>F.gelu<block_end><if_stmt>activation<eq>"relu"<block_start><return>F.relu<block_end><return><none><block_end><def_stmt>gen_causal_mask input_size dim_k full_attention=<false><block_start>"""
Generates a causal mask of size (input_size, dim_k) for linformer
Else, it generates (input_size, input_size) for full attention
"""<if_stmt>full_attention<block_start><return>(torch.triu(torch.ones(input_size input_size))<eq>1).transpose(0 1)<block_end><return>(torch.triu(torch.ones(dim_k input_size))<eq>1).transpose(0 1)<block_end><def_stmt>get_EF input_size dim method="learnable" head_dim=<none> bias=<true><block_start>"""
Retuns the E or F matrix, initialized via xavier initialization.
This is the recommended way to do it according to the authors of the paper.
Includes a method for convolution, as well as a method for no additional params.
"""<assert_stmt>method<eq>"learnable"<or>method<eq>"convolution"<or>method<eq>"no_params" "The method flag needs to be either 'learnable', 'convolution', or 'no_params'!"<if_stmt>method<eq>"convolution"<block_start>conv=nn.Conv1d(head_dim head_dim kernel_size=int(input_size/dim) stride=int(input_size/dim))<line_sep><return>conv<block_end><if_stmt>method<eq>"no_params"<block_start>mat=torch.zeros((input_size dim))<line_sep>torch.nn.init.normal_(mat mean=0.0 std=1/dim)<line_sep><return>mat<block_end>lin=nn.Linear(input_size dim bias)<line_sep>torch.nn.init.xavier_normal_(lin.weight)<line_sep><return>lin<block_end><class_stmt>Residual(nn.Module)<block_start>"""
Implemenation taken from
https://github.com/lucidrains/sinkhorn-transformer/blob/master/sinkhorn_transformer/sinkhorn_transformer.py
However, I do postnorm instead of prenorm.
"""<def_stmt>__init__ self fn input_channels=0 output_channels=0<block_start>super(Residual self).__init__()<line_sep>self.fn=fn<line_sep>self.resample=nn.Linear(input_channels output_channels)<if>input_channels<ne>output_channels<else><none><line_sep>self.norm=nn.LayerNorm(output_channels)<block_end><def_stmt>forward self tensor **kwargs<block_start><if_stmt>self.resample<is><not><none><block_start>tensor=self.resample(tensor)+self.fn(tensor **kwargs)<line_sep>tensor=self.norm(tensor)<line_sep><return>tensor<block_end>tensor=tensor+self.fn(tensor **kwargs)<line_sep>tensor=self.norm(tensor)<line_sep><return>tensor<block_end><block_end><class_stmt>PositionalEmbedding(nn.Module)<block_start>"""
Standard positional embedding.
From the paper "Attention is all you need".
Changed the constant from 10k to 100k, since this may be better for longer sequence lengths.
"""<def_stmt>__init__ self channels<block_start>super(PositionalEmbedding self).__init__()<line_sep>inv_freq=1./(100000<power>(torch.arange(0 channels 2).float()/channels))<line_sep>self.register_buffer('inv_freq' inv_freq)<block_end><def_stmt>forward self tensor<block_start>pos=torch.arange(tensor.shape[1] device=tensor.device).type(self.inv_freq.type())<line_sep>sin_inp=torch.einsum("i,j->ij" pos self.inv_freq)<line_sep>emb=torch.cat((sin_inp.sin() sin_inp.cos()) dim=-1)<line_sep><return>emb[<none> : :]<block_end><block_end><class_stmt>ProjectInOut(nn.Module)<block_start>"""
Impelemenation taken from https://github.com/lucidrains/sinkhorn-transformer/blob/73da02958965e1a690cb301292c0a3c549687d44/sinkhorn_transformer/sinkhorn_transformer.py#L218
"""<def_stmt>__init__ self fn dim_in dim_out project_out=<true><block_start>super(ProjectInOut self).__init__()<line_sep>self.fn=fn<line_sep>self.project_in=nn.Linear(dim_in dim_out)<line_sep>self.project_out=nn.Linear(dim_out dim_in)<if>project_out<else>identity<block_end><def_stmt>forward self tensor **kwargs<block_start>tensor=self.project_in(tensor)<line_sep>tensor=self.fn(tensor **kwargs)<line_sep>tensor=self.project_out(tensor)<line_sep><return>tensor<block_end><block_end><class_stmt>FeedForward(nn.Module)<block_start>"""
Standard Feed Forward Layer
"""<def_stmt>__init__ self input_channels output_channels ff_dim dropout activation="gelu"<block_start>super(FeedForward self).__init__()<line_sep>self.w_1=nn.Linear(input_channels ff_dim)<line_sep>self.w_2=nn.Linear(ff_dim output_channels)<line_sep>self.activation=get_act(activation)<line_sep>self.dropout=nn.Dropout(dropout)<line_sep>self.dropout2=nn.Dropout(dropout)<block_end><def_stmt>forward self tensor **kwargs<block_start>tensor=self.w_1(tensor)<if_stmt>self.activation<is><not><none><block_start>tensor=self.activation(tensor)<block_end>tensor=self.dropout(tensor)<line_sep>tensor=self.w_2(tensor)<line_sep>tensor=self.dropout2(tensor)<line_sep><return>tensor<block_end><block_end><class_stmt>LinearAttentionHead(nn.Module)<block_start>"""
Linear attention, as proposed by the linformer paper
"""<def_stmt>__init__ self dim dropout E_proj F_proj causal_mask full_attention=<false><block_start>super(LinearAttentionHead self).__init__()<line_sep>self.E=E_proj<line_sep>self.F=F_proj<line_sep>self.dim=dim<line_sep>self.dropout=nn.Dropout(dropout)<line_sep>self.P_bar=<none><line_sep>self.full_attention=full_attention<line_sep>self.causal_mask=causal_mask<line_sep>self.is_proj_tensor=isinstance(E_proj torch.Tensor)<block_end><def_stmt>forward self Q K V **kwargs<block_start>"""
Assume Q, K, V have same dtype
E, F are `nn.Linear` modules
"""<line_sep>input_mask=kwargs["input_mask"]<if>"input_mask"<in>kwargs<else><none><line_sep>embeddings_mask=kwargs["embeddings_mask"]<if>"embeddings_mask"<in>kwargs<else><none><line_sep># Instead of classic masking, we have to do this, because the classic mask is of size nxn
<if_stmt>input_mask<is><not><none># This is for k, v
<block_start>mask=input_mask[: : <none>]<line_sep>K=K.masked_fill_(~mask 0.0)<line_sep>V=V.masked_fill_(~mask 0.0)<del_stmt>mask<block_end><if_stmt>embeddings_mask<is><not><none><block_start>mask=embeddings_mask[: : <none>]<line_sep>Q=Q.masked_fill_(~mask 0.0)<del_stmt>mask<block_end>K=K.transpose(1 2)<if_stmt><not>self.full_attention<block_start><if_stmt>self.is_proj_tensor<block_start>self.E=self.E.to(K.device)<line_sep>K=torch.matmul(K self.E)<block_end><else_stmt><block_start>K=self.E(K)<block_end><block_end>Q=torch.matmul(Q K)<line_sep>P_bar=Q/torch.sqrt(torch.tensor(self.dim).type(Q.type())).to(Q.device)<if_stmt>self.causal_mask<is><not><none><block_start>self.causal_mask=self.causal_mask.to(Q.device)<line_sep>P_bar=P_bar.masked_fill_(~self.causal_mask float('-inf'))<block_end>P_bar=P_bar.softmax(dim=-1)<line_sep># Only save this when visualizing
<if_stmt>"visualize"<in>kwargs<and>kwargs["visualize"]<eq><true><block_start>self.P_bar=P_bar<block_end>P_bar=self.dropout(P_bar)<if_stmt><not>self.full_attention<block_start>V=V.transpose(1 2)<if_stmt>self.is_proj_tensor<block_start>self.F=self.F.to(V.device)<line_sep>V=torch.matmul(V self.F)<block_end><else_stmt><block_start>V=self.F(V)<block_end>V=V.transpose(1 2)<block_end>out_tensor=torch.matmul(P_bar V)<line_sep><return>out_tensor<block_end><block_end><class_stmt>MHAttention(nn.Module)<block_start>"""
Multihead attention, with each head being a Linformer Head
This feeds directly into a feed forward head
"""<def_stmt>__init__ self input_size dim channels dim_k nhead dropout checkpoint_level parameter_sharing E_proj F_proj full_attention causal_mask w_o_intermediate_dim=<none> decoder_mode=<false> method="learnable"<block_start>super(MHAttention self).__init__()<line_sep>self.heads=nn.ModuleList()<line_sep>self.input_size=input_size<line_sep>self.dim_k=dim_k<line_sep>self.channels=channels<line_sep>self.causal_mask=causal_mask<line_sep>self.checkpoint_level=checkpoint_level<line_sep>self.w_o_intermediate_dim=w_o_intermediate_dim<if_stmt>parameter_sharing<ne>"layerwise"<block_start>E_proj=get_EF(input_size dim_k method dim)<line_sep>F_proj=get_EF(input_size dim_k method dim)<if>parameter_sharing<eq>"none"<or>parameter_sharing<eq>"headwise"<else>E_proj<block_end>self.decoder_mode=decoder_mode<line_sep>self.to_q=nn.ModuleList()<line_sep>self.to_k=nn.ModuleList()<line_sep>self.to_v=nn.ModuleList()<for_stmt>_ range(nhead)<block_start><if_stmt>parameter_sharing<eq>"none"<block_start>E_proj=get_EF(input_size dim_k method dim)<line_sep>F_proj=get_EF(input_size dim_k method dim)<block_end>attn=LinearAttentionHead(dim dropout E_proj F_proj causal_mask full_attention)<line_sep>self.heads.append(attn)<line_sep>self.to_q.append(nn.Linear(channels dim bias=<false>))<line_sep>self.to_k.append(nn.Linear(channels dim bias=<false>))<line_sep>self.to_v.append(nn.Linear(channels dim bias=<false>))<block_end><if_stmt>w_o_intermediate_dim<is><none><block_start>self.w_o=nn.Linear(dim<times>nhead channels)<block_end><else_stmt><block_start>self.w_o_1=nn.Linear(dim<times>nhead w_o_intermediate_dim)<line_sep>self.w_o_2=nn.Linear(w_o_intermediate_dim channels)<block_end>self.mh_dropout=nn.Dropout(dropout)<block_end><def_stmt>forward self tensor **kwargs<block_start>batch_size,input_len,channels=tensor.shape<assert_stmt><not>(self.decoder_mode<and>"embeddings"<not><in>kwargs) "Embeddings must be supplied if decoding"<assert_stmt><not>("embeddings"<in>kwargs<and>(kwargs["embeddings"].shape[0] kwargs["embeddings"].shape[1] kwargs["embeddings"].shape[2])<ne>(batch_size input_len channels)) "Embeddings size must be the same as the input tensor"<line_sep>head_outputs=[]<for_stmt>index,head enumerate(self.heads)<block_start>Q=self.to_q[index](tensor)<line_sep>K=self.to_k[index](tensor)<if><not>self.decoder_mode<else>self.to_k[index](kwargs["embeddings"])<line_sep>V=self.to_v[index](tensor)<if><not>self.decoder_mode<else>self.to_v[index](kwargs["embeddings"])<if_stmt>self.checkpoint_level<eq>"C2"<block_start>head_outputs.append(checkpoint(head Q K V))<block_end><else_stmt><block_start>head_outputs.append(head(Q K V **kwargs))<block_end><block_end>out=torch.cat(head_outputs dim=-1)<if_stmt>self.w_o_intermediate_dim<is><none><block_start>out=self.w_o(out)<block_end><else_stmt><block_start>out=self.w_o_1(out)<line_sep>out=self.w_o_2(out)<block_end>out=self.mh_dropout(out)<line_sep><return>out<block_end><block_end><class_stmt>Linformer(nn.Module)<block_start>"""
My attempt at reproducing the Linformer Paper
https://arxiv.org/pdf/2006.04768.pdf
"""<def_stmt>__init__ self input_size channels dim_k dim_ff=256 dim_d=<none> dropout_ff=0.15 nhead=4 depth=1 dropout=0.1 activation="gelu" checkpoint_level="C0" parameter_sharing="layerwise" k_reduce_by_layer=0 full_attention=<false> include_ff=<true> w_o_intermediate_dim=<none> decoder_mode=<false> causal=<false> method="learnable" ff_intermediate=<none><block_start>super(Linformer self).__init__()<assert_stmt>activation<eq>"gelu"<or>activation<eq>"relu" "Only gelu and relu activations supported for now"<assert_stmt>checkpoint_level<eq>"C0"<or>checkpoint_level<eq>"C1"<or>checkpoint_level<eq>"C2" "Checkpoint level has to be either C0, C1, or C2."<assert_stmt>parameter_sharing<eq>"none"<or>parameter_sharing<eq>"headwise"<or>parameter_sharing<eq>"kv"<or>parameter_sharing<eq>"layerwise" "The `parameter_sharing` flag has to be either 'none', 'headwise', 'kv', or 'layerwise'."<assert_stmt>channels%nhead<eq>0<if>dim_d<is><none><else><true> "If `dim_d` is not set to a custom value, `channels` must be divisible by `nhead`!"<assert_stmt><not>(ff_intermediate<and>parameter_sharing<eq>"layerwise") "Parameter sharing must not be layerwise if ff_intermediate is enabled!"<assert_stmt><not>(ff_intermediate<and>decoder_mode) "Raising the dimension in the middle cannot be done in the decoder!"<line_sep>layers=nn.ModuleList()<line_sep>self.decoder_mode=decoder_mode<line_sep>self.input_size=input_size<line_sep>self.channels=channels<line_sep>self.checkpoint_level=checkpoint_level<line_sep>self.depth=depth<line_sep>self.nhead=nhead<line_sep>head_dim=channels<floordiv>nhead<if>dim_d<is><none><else>dim_d<line_sep>E_proj=get_EF(input_size dim_k method head_dim)<line_sep>causal_mask=gen_causal_mask(input_size dim_k full_attention)<if>causal<else><none><line_sep># If we want causal but only with the encoder
causal_enc=gen_causal_mask(input_size dim_k full_attention)<if>(causal<and><not>decoder_mode)<else><none><line_sep>get_attn=<lambda>attn_channels curr_dim_k:MHAttention(input_size head_dim attn_channels curr_dim_k nhead dropout checkpoint_level parameter_sharing E_proj E_proj full_attention causal_enc w_o_intermediate_dim decoder_mode=<false> method=method)<line_sep>get_attn_context=<lambda>attn_channels curr_dim_k:MHAttention(input_size head_dim attn_channels curr_dim_k nhead dropout checkpoint_level parameter_sharing E_proj E_proj full_attention causal_mask w_o_intermediate_dim decoder_mode=<true> method=method)<line_sep>get_ff=<lambda>input_channels output_channels:FeedForward(input_channels output_channels dim_ff dropout_ff activation)<for_stmt>index range(depth)<block_start>input_channels=ff_intermediate<if>(index<ne>0<and>ff_intermediate<is><not><none>)<and><not>decoder_mode<else>channels<line_sep>output_channels=ff_intermediate<if>(index<ne>depth-1<and>ff_intermediate<is><not><none>)<and><not>decoder_mode<else>channels<line_sep># TODO: Change the input and output channels here
attn_layer=get_attn(input_channels max(1 dim_k-index<times>k_reduce_by_layer))<line_sep>ff_layer=get_ff(input_channels output_channels)<line_sep>attn_layer,ff_layer=map(<lambda>res_ch_in res_ch_out fn:Residual(fn res_ch_in res_ch_out) (input_channels input_channels) (input_channels output_channels) (attn_layer ff_layer))<if_stmt>include_ff<block_start>layers.extend([attn_layer ff_layer])<block_end><else_stmt><block_start>layers.extend([attn_layer])<block_end><if_stmt><not>self.decoder_mode<block_start><continue><block_end>attn_context=get_attn_context(channels max(1 dim_k-index<times>k_reduce_by_layer))<line_sep>ff_context=get_ff(channels channels)<line_sep>attn_context,ff_context=map(<lambda>fn:Residual(fn channels channels) (attn_context ff_context))<if_stmt>include_ff<block_start>layers.extend([attn_context ff_context])<block_end><else_stmt><block_start>layers.extend([attn_context])<block_end><block_end>self.seq=layers<block_end><def_stmt>forward self tensor **kwargs<block_start>"""
Input is (batch_size, seq_len, channels)
"""<line_sep>bt,n,c=tensor.shape<assert_stmt>n<eq>self.input_size "This tensor is of the wrong size. Dimension 1 has to match the `input_size` flag"<assert_stmt>c<eq>self.channels "This tensor is of the wrong size. Dimension 2 has to match the `channels` flag"<assert_stmt>self.checkpoint_level<eq>"C0"<if>kwargs<else><true> "Cannot run checkpointing when using kwargs. Please set the checkpoint level to `C0`"<assert_stmt>"embeddings"<not><in>kwargs<or>self.decoder_mode "If decoding, needs to be initialized with `decoder_mode=True`"<for_stmt>layer self.seq<block_start><if_stmt>self.checkpoint_level<ne>"C0"<block_start>tensor=checkpoint(layer tensor)<block_end><else_stmt><block_start>tensor=layer(tensor **kwargs)<block_end><block_end><return>tensor<block_end><block_end><class_stmt>LinformerLM(nn.Module)<block_start>"""
A wrapper function to accept LM tasks, inspired by https://github.com/lucidrains/sinkhorn-transformer
"""<def_stmt>__init__ self num_tokens input_size channels dim_k=64 dim_ff=1024 dim_d=<none> dropout_ff=0.1 dropout_tokens=0.1 nhead=4 depth=2 ff_intermediate=<none> dropout=0.05 activation="gelu" checkpoint_level="C0" parameter_sharing="layerwise" k_reduce_by_layer=0 full_attention=<false> include_ff=<true> w_o_intermediate_dim=<none> emb_dim=<none> return_emb=<false> decoder_mode=<false> causal=<false> method="learnable"<block_start>super(LinformerLM self).__init__()<line_sep>emb_dim=channels<if>emb_dim<is><none><else>emb_dim<line_sep>self.input_size=input_size<line_sep>self.to_token_emb=nn.Embedding(num_tokens emb_dim)<line_sep>self.pos_emb=PositionalEmbedding(emb_dim)<line_sep>self.linformer=Linformer(input_size channels dim_k=dim_k dim_ff=dim_ff dim_d=dim_d dropout_ff=dropout_ff nhead=nhead depth=depth dropout=dropout ff_intermediate=ff_intermediate activation=activation checkpoint_level=checkpoint_level parameter_sharing=parameter_sharing k_reduce_by_layer=k_reduce_by_layer full_attention=full_attention include_ff=include_ff w_o_intermediate_dim=w_o_intermediate_dim decoder_mode=decoder_mode causal=causal method=method)<if_stmt>emb_dim<ne>channels<block_start>self.linformer=ProjectInOut(self.linformer emb_dim channels)<block_end>self.to_logits=identity<if>return_emb<else>nn.Linear(emb_dim num_tokens)<line_sep>self.dropout_tokens=nn.Dropout(dropout_tokens)<block_end><def_stmt>forward self tensor **kwargs<block_start>"""
Input is (batch_size, seq_len), and all items are ints from [0, num_tokens-1]
"""<line_sep>tensor=self.to_token_emb(tensor)<line_sep>tensor=self.pos_emb(tensor).type(tensor.type())+tensor<line_sep>tensor=self.dropout_tokens(tensor)<line_sep>tensor=self.linformer(tensor **kwargs)<line_sep>tensor=self.to_logits(tensor)<line_sep><return>tensor<block_end><block_end><class_stmt>LinformerEncDec(nn.Module)<block_start>"""
A complete seq -> seq translation task. Complete with an encoder and a decoder module.
"""<def_stmt>__init__ self enc_num_tokens enc_input_size enc_channels dec_num_tokens dec_input_size dec_channels enc_dim_k=64 enc_dim_ff=1024 enc_dim_d=<none> enc_ff_intermediate=<none> dec_ff_intermediate=<none> enc_dropout_ff=0.1 enc_nhead=4 enc_depth=2 enc_dropout=0.05 enc_parameter_sharing="layerwise" enc_k_reduce_by_layer=0 enc_full_attention=<false> enc_include_ff=<true> enc_w_o_intermediate_dim=<none> enc_emb_dim=<none> enc_method="learnable" dec_dim_k=64 dec_dim_ff=1024 dec_dim_d=<none> dec_dropout_ff=0.1 dec_nhead=4 dec_depth=2 dec_dropout=0.05 dec_parameter_sharing="layerwise" dec_k_reduce_by_layer=0 dec_full_attention=<false> dec_include_ff=<true> dec_w_o_intermediate_dim=<none> dec_emb_dim=<none> dec_method="learnable" activation="gelu" checkpoint_level="C0"<block_start>super(LinformerEncDec self).__init__()<line_sep>self.encoder=LinformerLM(num_tokens=enc_num_tokens input_size=enc_input_size channels=enc_channels dim_d=enc_dim_d dim_ff=enc_dim_ff dim_k=enc_dim_k dropout_ff=enc_dropout_ff nhead=enc_nhead depth=enc_depth dropout=enc_dropout parameter_sharing=enc_parameter_sharing k_reduce_by_layer=enc_k_reduce_by_layer ff_intermediate=enc_ff_intermediate full_attention=enc_full_attention include_ff=enc_include_ff w_o_intermediate_dim=enc_w_o_intermediate_dim emb_dim=enc_emb_dim return_emb=<true> activation=activation checkpoint_level=checkpoint_level method=enc_method)<line_sep>self.decoder=LinformerLM(num_tokens=dec_num_tokens input_size=dec_input_size channels=dec_channels dim_d=dec_dim_d dim_ff=dec_dim_ff dim_k=dec_dim_k dropout_ff=dec_dropout_ff nhead=dec_nhead depth=dec_depth dropout=dec_dropout ff_intermediate=dec_ff_intermediate parameter_sharing=dec_parameter_sharing k_reduce_by_layer=dec_k_reduce_by_layer method=dec_method full_attention=dec_full_attention include_ff=dec_include_ff w_o_intermediate_dim=dec_w_o_intermediate_dim emb_dim=dec_emb_dim decoder_mode=<true> causal=<true> activation=activation checkpoint_level=checkpoint_level)<block_end><def_stmt>forward self x y=<none> **kwargs<block_start>"""
Input is (batch_size, seq_len), and all items are ints from [0, num_tokens-1]
"""<line_sep>encoder_output=self.encoder(x **kwargs)<line_sep>y=y<if>y<is><not><none><else>x<line_sep><return>self.decoder(y embeddings=encoder_output)<block_end><block_end> |
expected_output={"cdp":{"index":{1:{"capability":"R S C" "device_id":"Device_With_A_Particularly_Long_Name" "hold_time":134 "local_interface":"GigabitEthernet1" "platform":"N9K-9000v" "port_id":"Ethernet0/0" } 2:{"capability":"S I" "device_id":"another_device_with_a_long_name" "hold_time":141 "local_interface":"TwentyFiveGigE1/0/3" "platform":"WS-C3850-" "port_id":"TenGigabitEthernet1/1/4" } }}}<line_sep> |
<class_stmt>Solution<block_start><def_stmt>decodeString self s:str<arrow>str<block_start>stack=[]<line_sep>stack.append([1 ""])<line_sep>num=0<for_stmt>l s<block_start><if_stmt>l.isdigit()<block_start>num=num<times>10+ord(l)-ord('0')<block_end><elif_stmt>l<eq>'['<block_start>stack.append([num ""])<line_sep>num=0<block_end><elif_stmt>l<eq>']'<block_start>stack[-2][1]<augadd>stack[-1][0]<times>stack[-1][1]<line_sep>stack.pop()<block_end><else_stmt><block_start>stack[-1][1]<augadd>l<block_end><block_end><return>stack[0][1]<block_end><block_end> |
# Time: O(n)
# Space: O(1)
<class_stmt>Solution(object)<block_start><def_stmt>countGoodRectangles self rectangles<block_start>"""
:type rectangles: List[List[int]]
:rtype: int
"""<line_sep>result=mx=0<for_stmt>l,w rectangles<block_start>side=min(l w)<if_stmt>side<g>mx<block_start>result,mx=1 side<block_end><elif_stmt>side<eq>mx<block_start>result<augadd>1<block_end><block_end><return>result<block_end><block_end> |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
"""<import_stmt>logging<import_from_stmt>.base_node_info BaseNodeInfo<import_from_stmt>....config_manager.ui.ui_manager UIType<import_from_stmt>....config_manager.ui.ui_action ROI<import_from_stmt>..project_data_manager ProjectDataManager<import_from_stmt>...utils get_value<import_from_stmt>....common.define DEFAULT_TEMPLATE_THRESHOLD<line_sep>logger=logging.getLogger("sdktool")<class_stmt>OverNodeInfo(BaseNodeInfo)<block_start><def_stmt>__init__ self<block_start>super(OverNodeInfo self).__init__(UIType.OVER_UI.value)<block_end><def_stmt>init self config_value<block_start>self._node_cfg.clear()<line_sep>self._node_cfg["name"]=config_value.get("name")<line_sep>self._node_cfg["id"]=config_value.get("id")<or>-1<line_sep>self._node_cfg["actionType"]=config_value.get("actionType")<or>"click"<line_sep>self._node_cfg["desc"]=config_value.get("desc")<or>""<line_sep>self._node_cfg["imgPath"]=config_value.get("imgPath")<or>""<if_stmt>len(self._node_cfg["imgPath"])<g>0<block_start>self._node_cfg["imgPath"]=ProjectDataManager().change_to_tool_path(self._node_cfg["imgPath"])<block_end>self._node_cfg["ROI"]=self.int_roi(config_value)<if_stmt>self._node_cfg["actionType"]<eq>'click'<block_start>self._node_cfg["action"]=self.init_click_action(config_value)<block_end><elif_stmt>self._node_cfg["actionType"]<eq>'drag'<block_start>self._node_cfg["action"]=self.init_drag_action(config_value)<block_end><return>self._node_cfg<block_end><def_stmt>change_to_data_cfg self<block_start>data_cfg=dict()<line_sep>rois=self._node_cfg.get('ROI')<if_stmt>rois<is><none><block_start>logger.error("not have over item")<line_sep><return>data_cfg<block_end>data_cfg["element_id"]=int(self._node_cfg.get("id")<or>-1)<line_sep>data_cfg["element_name"]=self._node_cfg.get('name')<line_sep>data_cfg['description']=self._node_cfg.get('desc')<line_sep>data_cfg["action_type"]=self._node_cfg.get('actionType')<line_sep>data_cfg['img_path']=self._node_cfg.get('imgPath')<line_sep>data_cfg["img_path"]=ProjectDataManager().change_to_sdk_path(data_cfg["img_path"])<line_sep># rois = self._node_cfg.get('ROI')
# if rois is not None:
roi=rois[0]<line_sep>x=int(get_value(roi 'x' 0))<line_sep>y=int(get_value(roi 'y' 0))<line_sep>w=int(get_value(roi 'w' 0))<line_sep>h=int(get_value(roi 'h' 0))<line_sep>threshold=float(roi.get('templateThreshold' DEFAULT_TEMPLATE_THRESHOLD))<line_sep>data_cfg['roi']=ROI(x y w h threshold)<if_stmt>data_cfg["action_type"]<eq>'click'<block_start>data_cfg['action']=self.get_click_action()<block_end><elif_stmt>data_cfg['action_type']<eq>'drag'<block_start>data_cfg['drag_start'],data_cfg['drag_end']=self.get_drag_action()<block_end><return>data_cfg<block_end><block_end> |
"""In this example we plot a record fragment with sequence over multiple lines.
"""<import_from_stmt>dna_features_viewer BiopythonTranslator<line_sep>translator=BiopythonTranslator()<line_sep>graphic_record=translator.translate_record("example_sequence.gb")<line_sep>subrecord=graphic_record.crop((1700 2000))<line_sep>fig,axes=subrecord.plot_on_multiple_lines(nucl_per_line=70 plot_sequence=<true>)<line_sep>fig.savefig("multiline_plot.png")<line_sep> |
# Set of input tags for L1Extra in agreement with L1Reco_cff
#
# <NAME> 2012-05-22
<import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep>L1ExtraInputTagSet=cms.PSet(L1ExtraInputTags=cms.PSet(TagL1ExtraMuon=cms.InputTag("l1extraParticles") TagL1ExtraIsoEG=cms.InputTag("l1extraParticles" "Isolated") TagL1ExtraNoIsoEG=cms.InputTag("l1extraParticles" "NonIsolated") TagL1ExtraCenJet=cms.InputTag("l1extraParticles" "Central") TagL1ExtraForJet=cms.InputTag("l1extraParticles" "Forward") TagL1ExtraTauJet=cms.InputTag("l1extraParticles" "Tau") TagL1ExtraEtMissMET=cms.InputTag("l1extraParticles" "MET") TagL1ExtraEtMissHTM=cms.InputTag("l1extraParticles" "MHT") TagL1ExtraHFRings=cms.InputTag("l1extraParticles")))<line_sep> |
"""
<NAME> - The Curse of the Excluded Middle
DOI:10.1145/2605176
CACM vol.57 no.06
"""<def_stmt>less_than_30 n<block_start>check=n<l>30<line_sep>print('%d < 30 : %s'%(n check))<line_sep><return>check<block_end><def_stmt>more_than_20 n<block_start>check=n<g>20<line_sep>print('%d > 20 : %s'%(n check))<line_sep><return>check<block_end>l=[1 25 40 5 23]<line_sep>q0=(n<for>n l<if>less_than_30(n))<line_sep>q1=(n<for>n q0<if>more_than_20(n))<for_stmt>n q1<block_start>print('-> %d'%n)<block_end> |
<import_stmt>torch<import_from_stmt>fastai.core to_np<import_stmt>numpy<as>np<import_from_stmt>nltk.translate.bleu_score sentence_bleu SmoothingFunction<def_stmt>token_accuracy preds targs<block_start>preds=torch.max(preds dim=-1)[1]<line_sep><return>(preds[:-1]<eq>targs.data).float().mean()<block_end><def_stmt>perplexity preds targs<block_start><return>torch.exp(-preds.mean())<block_end><def_stmt>bleu_score preds targs stoi=<none><block_start>sf=SmoothingFunction().method1<line_sep>preds=torch.max(preds dim=-1)[1][:-1]<line_sep>bleus=np.zeros(targs.size(1))<for_stmt>res zip(to_np(targs preds))<block_start><if_stmt>len(res[1])<g>2<block_start>bleu=sentence_bleu([res[1]] res[2] smoothing_function=sf weights=(1/3. 1/3. 1/3.))<block_end><elif_stmt>len(res[1])<eq>2<block_start>bleu=sentence_bleu([res[1]] res[2] smoothing_function=sf weights=(0.5 0.5))<block_end><else_stmt><block_start>bleu=sentence_bleu([res[1]] res[2] smoothing_function=sf weights=(1.0 ))<block_end>bleus.append(bleu)<block_end><return><block_end> |
<import_from_stmt>abc ABC<class_stmt>ImagePathToInformationMapping(ABC)<block_start><def_stmt>__init__ self<block_start><pass><block_end><def_stmt>__call__ self full_path<block_start><pass><block_end><block_end><class_stmt>ImageNetInfoMapping(ImagePathToInformationMapping)<block_start>"""
For ImageNet-like directory structures without sessions/conditions:
.../{category}/{img_name}
"""<def_stmt>__call__ self full_path<block_start>session_name="session-1"<line_sep>img_name=full_path.split("/")[-1]<line_sep>condition="NaN"<line_sep>category=full_path.split("/")[-2]<line_sep><return>session_name img_name condition category<block_end><block_end><class_stmt>ImageNetCInfoMapping(ImagePathToInformationMapping)<block_start>"""
For the ImageNet-C Dataset with path structure:
...{corruption function}/{corruption severity}/{category}/{img_name}
"""<def_stmt>__call__ self full_path<block_start>session_name="session-1"<line_sep>parts=full_path.split("/")<line_sep>img_name=parts[-1]<line_sep>category=parts[-2]<line_sep>severity=parts[-3]<line_sep>corruption=parts[-4]<line_sep>condition="{}-{}".format(corruption severity)<line_sep><return>session_name img_name condition category<block_end><block_end><class_stmt>InfoMappingWithSessions(ImagePathToInformationMapping)<block_start>"""
Directory/filename structure:
.../{session_name}/{something}_{something}_{something}_{condition}_{category}_{img_name}
"""<def_stmt>__call__ self full_path<block_start>session_name=full_path.split("/")[-2]<line_sep>img_name=full_path.split("/")[-1]<line_sep>condition=img_name.split("_")[3]<line_sep>category=img_name.split("_")[4]<line_sep><return>session_name img_name condition category<block_end><block_end> |
# Basic configuration, you should not use this directly
# instead checkout local_config.py or local_dockermacine_config.py
# spawn with custom docker containers
c.JupyterHub.spawner_class='everware.CustomDockerSpawner'<line_sep>c.Spawner.tls=<false><line_sep>c.Spawner.debug=<true><line_sep>c.Spawner.start_timeout=1000<line_sep>c.Spawner.http_timeout=60<line_sep>c.Spawner.poll_interval=5<line_sep>c.Spawner.remove_containers=<true><line_sep>c.Spawner.tls_assert_hostname=<false><line_sep>c.Spawner.use_docker_client_env=<true><line_sep># give users an opportunity to restore any images via docker or not. Default: True
# c.Spawner.share_user_images = False
# c.Authenticator.admin_users = {'anaderi', 'astiunov'}
# The docker containers need access to the Hub API, so the default
# loopback address doesn't work
<import_from_stmt>jupyter_client.localinterfaces public_ips<line_sep>c.JupyterHub.hub_ip=public_ips()[0]<line_sep>c.JupyterHub.data_files_path='share'<line_sep>c.JupyterHub.template_paths=['share/static/html']<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>webkitpy.layout_tests.models testharness_results<class_stmt>TestHarnessResultCheckerTest(unittest.TestCase)<block_start><def_stmt>test_is_testharness_output self<block_start>test_data=[{'content':'foo' 'result':<false>} {'content':'' 'result':<false>} {'content':' ' 'result':<false>} {'content':'This is a testharness.js-based test.\nHarness: the test ran to completion.' 'result':<true>} {'content':'\n \r This is a testharness.js-based test. \n \r \n \rHarness: the test ran to completion. \n\n' 'result':<true>} {'content':' This \nis a testharness.js-based test.\nHarness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test. Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\nFoo bar \n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\nFAIL: bah \n Harness: the test ran to completion.\n\n\n' 'result':<true>} ]<for_stmt>data test_data<block_start>self.assertEqual(data['result'] testharness_results.is_testharness_output(data['content']))<block_end><block_end><def_stmt>test_is_testharness_output_passing self<block_start>test_data=[{'content':'This is a testharness.js-based test.\n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\n \n Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\n PASS: foo bar \n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\n PASS: foo bar FAIL \n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\n PASS: foo bar \nFAIL \n Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\n CONSOLE ERROR: BLAH \n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\n CONSOLE WARNING: BLAH \n Harness: the test ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\n Foo bar \n Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\n FAIL: bah \n Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\n TIMEOUT: bah \n Harness: the test ran to completion.' 'result':<false>} {'content':'This is a testharness.js-based test.\n NOTRUN: bah \n Harness: the test ran to completion.' 'result':<false>} {'content':'CONSOLE LOG: error.\nThis is a testharness.js-based test.\nPASS: things are fine.\nHarness: the test ran to completion.\n\n' 'result':<true>} {'content':'CONSOLE ERROR: error.\nThis is a testharness.js-based test.\nPASS: things are fine.\nHarness: the test ran to completion.\n\n' 'result':<true>} {'content':'CONSOLE WARNING: error.\nThis is a testharness.js-based test.\nPASS: things are fine.\nHarness: the test ran to completion.\n\n' 'result':<true>} {'content':'RANDOM TEXT.\nThis is a testharness.js-based test.\nPASS: things are fine.\n.Harness: the test ran to completion.\n\n' 'result':<false>} ]<for_stmt>data test_data<block_start>self.assertEqual(data['result'] testharness_results.is_testharness_output_passing(data['content']))<block_end><block_end><def_stmt>test_is_testharness_output_with_console_errors_and_warnings self<block_start>test_data=[{'content':'This is a testharness.js-based test.\nCONSOLE ERROR: This is an error.\nTest ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\nCONSOLE WARNING: This is a warning.\nTest ran to completion.' 'result':<true>} {'content':'CONSOLE ERROR: This is an error.\nTest ran to completion.' 'result':<true>} {'content':'CONSOLE WARNING: This is a warning.\nTest ran to completion.' 'result':<true>} {'content':'This is a testharness.js-based test.\nCONSOLE ERROR: This is an error.' 'result':<true>} {'content':'CONSOLE ERROR: This is an error.' 'result':<true>} {'content':'CONSOLE WARNING: This is a warning.' 'result':<true>} {'content':'This is a testharness.js-based test.\nCONSOLE MESSAGE: This is not error.' 'result':<false>} {'content':'This is a testharness.js-based test.\nNo errors here.' 'result':<false>} {'content':'This is not a CONSOLE ERROR, sorry.' 'result':<false>} {'content':'This is not a CONSOLE WARNING, sorry.' 'result':<false>} ]<for_stmt>data test_data<block_start>self.assertEqual(data['result'] testharness_results.is_testharness_output_with_console_errors_or_warnings(data['content']))<block_end><block_end><block_end> |
<import_from_stmt>django.core.management.base BaseCommand<import_from_stmt>oscar_accounts.setup create_default_accounts<class_stmt>Command(BaseCommand)<block_start>help="Initialize oscar accounts default structure"<def_stmt>handle self *args **options<block_start>create_default_accounts()<block_end><block_end> |
<import_from_stmt>fontTools.fontBuilder TTFont<line_sep>fonts={}<def_stmt>check char font_path<block_start><if_stmt>font_path<in>fonts<block_start>font=fonts.get(font_path)<block_end><else_stmt><block_start>font=TTFont(font_path)<line_sep>fonts[font_path]=font<block_end>utf8_char=char.encode("unicode_escape").decode('utf-8')<if_stmt>utf8_char.startswith('\\u')<block_start>uc="uni"+utf8_char[2:].upper()<line_sep>f=font.getGlyphSet().get(uc)<if_stmt>f<and>f._glyph.numberOfContours<block_start><return><true><block_end><else_stmt><block_start><return><false><block_end><block_end><return><true><block_end> |
<async_keyword><def_stmt>m001_initial db<block_start>"""
Initial lnurlpos table.
"""<line_sep><await>db.execute(f"""
CREATE TABLE lnurlpos.lnurlposs (
id TEXT NOT NULL PRIMARY KEY,
key TEXT NOT NULL,
title TEXT NOT NULL,
wallet TEXT NOT NULL,
currency TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
""")<line_sep><await>db.execute(f"""
CREATE TABLE lnurlpos.lnurlpospayment (
id TEXT NOT NULL PRIMARY KEY,
posid TEXT NOT NULL,
payhash TEXT,
payload TEXT NOT NULL,
pin INT,
sats INT,
timestamp TIMESTAMP NOT NULL DEFAULT {db.timestamp_now}
);
""")<block_end> |
<import_stmt>random<line_sep>print(random.random())<line_sep># 0.4496839011176701
random.seed(0)<line_sep>print(random.random())<line_sep># 0.8444218515250481
print(random.random())<line_sep># 0.7579544029403025
random.seed(0)<line_sep>print(random.random())<line_sep># 0.8444218515250481
print(random.random())<line_sep># 0.7579544029403025
|
##
# @file density_overflow.py
# @author <NAME>
# @date Jun 2018
# @brief Compute density overflow
#
<import_stmt>math<import_stmt>torch<import_from_stmt>torch nn<import_from_stmt>torch.autograd Function<import_from_stmt>dreamplace.ops.density_map.density_map DensityMap<as>DensityMap<import_stmt>pdb<class_stmt>DensityOverflow(DensityMap)<block_start>"""
@brief Compute density overflow for both movable and fixed cells.
The density map for fixed cells is pre-computed.
Each call will only compute the density map for movable cells.
"""<def_stmt>__init__ self node_size_x node_size_y bin_center_x bin_center_y target_density xl yl xh yh bin_size_x bin_size_y num_movable_nodes num_terminals num_filler_nodes<block_start>"""
@brief initialization
@param node_size_x cell width array consisting of movable cells, fixed cells, and filler cells in order
@param node_size_y cell height array consisting of movable cells, fixed cells, and filler cells in order
@param bin_center_x bin center x locations
@param bin_center_y bin center y locations
@param target_density target density
@param xl left boundary
@param yl bottom boundary
@param xh right boundary
@param yh top boundary
@param bin_size_x bin width
@param bin_size_y bin height
@param num_movable_nodes number of movable cells
@param num_terminals number of fixed cells
@param num_filler_nodes number of filler cells
"""<line_sep>super(DensityOverflow self).__init__(node_size_x=node_size_x node_size_y=node_size_y bin_center_x=bin_center_x bin_center_y=bin_center_y xl=xl yl=yl xh=xh yh=yh bin_size_x=bin_size_x bin_size_y=bin_size_y num_movable_nodes=num_movable_nodes num_terminals=num_terminals num_filler_nodes=num_filler_nodes)<line_sep>self.target_density=target_density<block_end><def_stmt>forward self pos<block_start>"""
@brief API
@param pos cell locations. The array consists of x locations of movable cells, fixed cells, and filler cells, then y locations of them
"""<line_sep>density_map=super(DensityOverflow self).forward(pos)<line_sep>bin_area=self.bin_size_x<times>self.bin_size_y<line_sep>density_cost=(density_map-self.target_density<times>bin_area).clamp_(min=0.0).sum()<line_sep><return>density_cost density_map.max()/bin_area<block_end><block_end> |
<import_from_stmt>moto.core.models base_decorator<import_from_stmt>tests.deployment.sagemaker.sagemaker_moto.model sagemaker_backends<line_sep>moto_mock_sagemaker=base_decorator(sagemaker_backends)<line_sep> |
# Copyright 2013 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.
"""Backward compatibility for old results API.
This module helps convert the old PageMeasurementResults API into the new
style one. This exists as a bridging solution so we can change the underlying
implementation and update the PageMeasurementResults API once we know the
underlying implementation is solid.
"""<import_from_stmt>telemetry value<as>value_module<import_from_stmt>telemetry.value histogram<import_from_stmt>telemetry.value list_of_scalar_values<import_from_stmt>telemetry.value scalar<def_stmt>ConvertOldCallingConventionToValue page trace_name units value chart_name data_type<block_start>value_name=value_module.ValueNameFromTraceAndChartName(trace_name chart_name)<if_stmt>data_type<eq>'default'<block_start><if_stmt>isinstance(value list)<block_start><return>list_of_scalar_values.ListOfScalarValues(page value_name units value important=<true>)<block_end><else_stmt><block_start><return>scalar.ScalarValue(page value_name units value important=<true>)<block_end><block_end><elif_stmt>data_type<eq>'unimportant'<block_start><if_stmt>isinstance(value list)<block_start><return>list_of_scalar_values.ListOfScalarValues(page value_name units value important=<false>)<block_end><else_stmt><block_start><return>scalar.ScalarValue(page value_name units value important=<false>)<block_end><block_end><elif_stmt>data_type<eq>'histogram'<block_start><assert_stmt>isinstance(value basestring)<line_sep><return>histogram.HistogramValue(page value_name units raw_value_json=value important=<true>)<block_end><elif_stmt>data_type<eq>'unimportant-histogram'<block_start><assert_stmt>isinstance(value basestring)<line_sep><return>histogram.HistogramValue(page value_name units raw_value_json=value important=<false>)<block_end><elif_stmt>data_type<eq>'informational'<block_start><raise>NotImplementedError()<block_end><else_stmt><block_start><raise>ValueError('Unrecognized data type %s' data_type)<block_end><block_end> |
<import_from_stmt>torch.utils.data Dataset<import_stmt>tqdm<import_stmt>json<import_stmt>torch<import_stmt>random<import_stmt>numpy<as>np<import_from_stmt>sklearn.utils shuffle<class_stmt>BERTDataset(Dataset)<block_start><def_stmt>__init__ self corpus_path word2idx_path seq_len hidden_dim=384 on_memory=<true># hidden dimension for positional encoding
<block_start>self.hidden_dim=hidden_dim<line_sep># define path of dicts
self.word2idx_path=word2idx_path<line_sep># define max length
self.seq_len=seq_len<line_sep># load whole corpus at once or not
self.on_memory=on_memory<line_sep># directory of corpus dataset
self.corpus_path=corpus_path<line_sep># define special symbols
self.pad_index=0<line_sep>self.unk_index=1<line_sep>self.cls_index=2<line_sep>self.sep_index=3<line_sep>self.mask_index=4<line_sep>self.num_index=5<line_sep># 加载字典
<with_stmt>open(word2idx_path "r" encoding="utf-8")<as>f<block_start>self.word2idx=json.load(f)<block_end># 加载语料
<with_stmt>open(corpus_path "r" encoding="utf-8")<as>f<block_start><if_stmt><not>on_memory# 如果不将数据集直接加载到内存, 则需先确定语料行数
<block_start>self.corpus_lines=0<for_stmt>_ tqdm.tqdm(f desc="Loading Dataset")<block_start>self.corpus_lines<augadd>1<block_end><block_end><if_stmt>on_memory# 将数据集全部加载到内存
<block_start>self.lines=[eval(line)<for>line tqdm.tqdm(f desc="Loading Dataset")]<line_sep>self.corpus_lines=len(self.lines)<block_end><block_end><if_stmt><not>on_memory# 如果不全部加载到内存, 首先打开语料
<block_start>self.file=open(corpus_path "r" encoding="utf-8")<line_sep># 然后再打开同样的语料, 用来抽取负样本
self.random_file=open(corpus_path "r" encoding="utf-8")<line_sep># 下面是为了错位抽取负样本
<for_stmt>_ range(np.random.randint(self.corpus_lines<if>self.corpus_lines<l>1000<else>1000))<block_start>self.random_file.__next__()<block_end><block_end><block_end><def_stmt>__len__ self<block_start><return>self.corpus_lines<block_end><def_stmt>__getitem__ self item<block_start>t1,t2,is_next_label=self.random_sent(item)<line_sep>t1_random,t1_label=self.random_char(t1)<line_sep>t2_random,t2_label=self.random_char(t2)<line_sep>t1=[self.cls_index]+t1_random+[self.sep_index]<line_sep>t2=t2_random+[self.sep_index]<line_sep>t1_label=[self.pad_index]+t1_label+[self.pad_index]<line_sep>t2_label=t2_label+[self.pad_index]<line_sep>segment_label=([0<for>_ range(len(t1))]+[1<for>_ range(len(t2))])[:self.seq_len]<line_sep>bert_input=(t1+t2)[:self.seq_len]<line_sep>bert_label=(t1_label+t2_label)[:self.seq_len]<line_sep>output={"bert_input":torch.tensor(bert_input) "bert_label":torch.tensor(bert_label) "segment_label":torch.tensor(segment_label) "is_next":torch.tensor([is_next_label])}<line_sep><return>output<block_end><def_stmt>tokenize_char self segments<block_start><return>[self.word2idx.get(char self.unk_index)<for>char segments]<block_end><def_stmt>random_char self sentence<block_start>char_tokens_=list(sentence)<line_sep>char_tokens=self.tokenize_char(char_tokens_)<line_sep>output_label=[]<for_stmt>i,token enumerate(char_tokens)<block_start>prob=random.random()<if_stmt>prob<l>0.30<block_start>prob<augdiv>0.30<line_sep>output_label.append(char_tokens[i])<line_sep># 80% randomly change token to mask token
<if_stmt>prob<l>0.8<block_start>char_tokens[i]=self.mask_index<block_end># 10% randomly change token to random token
<elif_stmt>prob<l>0.9<block_start>char_tokens[i]=random.randrange(len(self.word2idx))<block_end><block_end><else_stmt><block_start>output_label.append(0)<block_end><block_end><return>char_tokens output_label<block_end><def_stmt>random_sent self index<block_start>t1,t2=self.get_corpus_line(index)<line_sep># output_text, label(isNotNext:0, isNext:1)
<if_stmt>random.random()<g>0.5<block_start><return>t1 t2 1<block_end><else_stmt><block_start><return>t1 self.get_random_line() 0<block_end><block_end><def_stmt>get_corpus_line self item<block_start><if_stmt>self.on_memory<block_start><return>self.lines[item]["text1"] self.lines[item]["text2"]<block_end><else_stmt><block_start>line=self.file.__next__()<if_stmt>line<is><none><block_start>self.file.close()<line_sep>self.file=open(self.corpus_path "r" encoding="utf-8")<line_sep>line=self.file.__next__()<block_end>line=eval(line)<line_sep>t1,t2=line["text1"] line["text2"]<line_sep><return>t1 t2<block_end><block_end><def_stmt>get_random_line self<block_start><if_stmt>self.on_memory<block_start><return>self.lines[random.randrange(len(self.lines))]["text2"]<block_end>line=self.random_file.__next__()<if_stmt>line<is><none><block_start>self.random_file.close()<line_sep>self.random_file=open(self.corpus_path "r" encoding="utf-8")<for_stmt>_ range(np.random.randint(self.corpus_lines<if>self.corpus_lines<l>1000<else>1000))<block_start>self.random_file.__next__()<block_end>line=self.random_file.__next__()<block_end><return>eval(line)["text2"]<block_end><block_end> |
<import_from_stmt>tempfile mkdtemp<import_stmt>os<import_stmt>sys<import_stmt>subprocess<import_stmt>shutil<import_stmt>time<class_stmt>Mounter<block_start><def_stmt>__init__ self src_path mount_root="."<block_start>self.src_path=src_path<line_sep>self.mount_root=os.path.abspath(mount_root)<line_sep>mount_name=os.path.splitext(os.path.split(self.src_path)[1])[0]<line_sep>self.mount_point=os.path.join(self.mount_root mount_name)<block_end><block_end><class_stmt>TarMounter(Mounter)<block_start><def_stmt>__enter__ self<block_start>self.tempdir=mkdtemp()<line_sep># this only supports compressed tarball: *.tar.gz and *.tgz
args=["tar" "-zxf" self.src_path "-C" self.tempdir]<line_sep>extra_args=["--strip-components" "1"]<line_sep>args.extend(extra_args)<line_sep>is_success=subprocess.run(args).returncode<eq>0<if_stmt>is_success<block_start><return>self.tempdir<block_end><raise>IOError(f"could not untar {self.src_path}")<block_end><def_stmt>__exit__ self type value tb<block_start>shutil.rmtree(self.tempdir)<block_end><block_end><class_stmt>DmgMounter(Mounter)<block_start><def_stmt>__init__ self src_path mount_root="." verbose=<false> max_try=5<block_start>super(DmgMounter self).__init__(src_path mount_root)<line_sep>self.extra_args=["-mount" "required"]<line_sep>self.max_try=max_try<if_stmt><not>verbose<block_start>self.extra_args.append("-quiet")<block_end><block_end>@staticmethod<def_stmt>umount mount_point<block_start><if_stmt>os.path.exists(mount_point)<block_start>rst=subprocess.run(["umount" mount_point])<line_sep><return><not>rst.returncode<block_end><return><true><block_end><def_stmt>__enter__ self<block_start><assert_stmt>sys.platform<eq>"darwin"<line_sep>args=["hdiutil" "attach" self.src_path "-mountpoint" self.mount_point]<line_sep>args.extend(self.extra_args)<line_sep>DmgMounter.umount(self.mount_point)<line_sep># the mount might fail for unknown reason,
# set a max_try here to work it around
cur_try=1<while_stmt>cur_try<le>self.max_try<block_start>is_success=subprocess.run(args).returncode<eq>0<if_stmt>is_success<block_start><return>self.mount_point<block_end>time.sleep(0.5)<line_sep>cur_try<augadd>1<block_end><raise>IOError(f"{self.src_path} is not mounted successfully")<block_end><def_stmt>__exit__ self type value tb<block_start>DmgMounter.umount(self.mount_point)<block_end><block_end> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.