content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import numpy as np def new_result(team1, team2, result): """add a new [result, opponent] to team1""" return team1.append([result, team2]) def spread(e1, e2, c): """points spread between e1, e2""" #recommend c between 25 (football, 10 pts = 1.5 scores) and ~15 return (e1-e2)/c def pwin(e1, e2): """probability e1 beats e2""" return (1.0/(1+(10**((e2-e1)/float(400))))) def elo(team, k): """season-long evaluation of team""" x = 1500.0 for t in team: #teams are composed of matches: [result, opponent] + auxiliary info like home_away, date x += k*(s_to_r(t[0])-(pwin(x, elo(t[1], k)))) return x def s_to_r(x): """score to result""" if x == 0: return 0.5 elif x > 0: return 1 return 0 def elo_plus(team, k, f): """elo accounting for margin of result""" x = 1500.0 for t in team: #teams are composed of matches: [relscore, opponent] + auxiliary info like home_away, date r = s_to_r(t[0]) x += f(t[0])*k*(r-(pwin(x, elo_plus(t[1], k, f)))) return x def baby_elo(e1, e2, result, k): """change in e1 given e2, result, k""" return k*(result-(pwin(e1, e2)))
[ 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 4299, 649, 62, 20274, 7, 15097, 16, 11, 1074, 17, 11, 1255, 2599, 201, 198, 220, 220, 220, 37227, 2860, 257, 649, 685, 20274, 11, 6125, 60, 284, 1074, 16, 37811, 201, 198, 220, 22...
2.1787
554
from __future__ import annotations import pytest from aiohttp import web @pytest.mark.asyncio
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 12972, 9288, 198, 6738, 257, 952, 4023, 1330, 3992, 628, 198, 31, 9078, 9288, 13, 4102, 13, 292, 13361, 952, 198 ]
3.233333
30
#!/usr/bin/env python2 import sys print "\n----- DECODE -----" for line in sys.stdin: line = line.strip() for number in line.split(' '): number = int(number) % 127 char = chr(number) sys.stdout.write(char) sys.stdout.flush() print "\n------------------"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 11748, 25064, 198, 198, 4798, 37082, 77, 30934, 27196, 16820, 13498, 21215, 198, 198, 1640, 1627, 287, 25064, 13, 19282, 259, 25, 198, 220, 1627, 796, 1627, 13, 36311, 3419, 1...
2.349206
126
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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 json import logging from contextlib import contextmanager from functools import lru_cache from typing import Any, Dict, Optional, Tuple from kubernetes.client import ApiClient from kubernetes.client.exceptions import ApiException from kubernetes.dynamic import DynamicClient, Resource, ResourceInstance from kubernetes.dynamic.exceptions import ResourceNotUniqueError from backend.container_service.clusters.base.models import CtxCluster from backend.utils.error_codes import error_codes from ..client import BcsKubeConfigurationService from .dynamic.discovery import BcsLazyDiscoverer, DiscovererCache logger = logging.getLogger(__name__) class CoreDynamicClient(DynamicClient): """为官方 SDK 里的 DynamicClient 追加新功能: - 使用 sanitize_for_serialization 处理 body - 提供获取 preferred resource 方法 - 包装请求失败时的 ApiException - 提供 get_or_none、update_or_create 等方法 """ def serialize_body(self, body: Any) -> Dict: """使用 sanitize 方法剔除 OpenAPI 对象里的 None 值""" body = self.client.sanitize_for_serialization(body) return body or {} def get_preferred_resource(self, kind: str) -> Resource: """尝试获取动态 Resource 对象,优先使用 preferred=True 的 ApiGroup :param kind: 资源种类,比如 Deployment :raises: ResourceNotUniqueError 匹配到多个不同版本资源,ResourceNotFoundError 没有找到资源 """ try: return self.resources.get(kind=kind, preferred=True) except ResourceNotUniqueError: # 如果使用 preferred=True 仍然能匹配到多个 ApiGroup,使用第一个结果 resources = self.resources.search(kind=kind, preferred=True) return resources[0] def get_or_none( self, resource: Resource, name: Optional[str] = None, namespace: Optional[str] = None, **kwargs ) -> Optional[ResourceInstance]: """查询资源,当资源不存在抛出 404 错误时返回 None""" try: return self.get(resource, name=name, namespace=namespace, **kwargs) except ApiException as e: if e.status == 404: return None raise def delete_ignore_nonexistent( self, resource: Resource, name: Optional[str] = None, namespace: Optional[str] = None, body: Optional[Dict] = None, label_selector: Optional[str] = None, field_selector: Optional[str] = None, **kwargs, ) -> Optional[ResourceInstance]: """删除资源,但是当资源不存在时忽略错误""" try: return resource.delete( name=name, namespace=namespace, body=body, label_selector=label_selector, field_selector=field_selector, **kwargs, ) except ApiException as e: if e.status == 404: logger.info( f"Delete a non-existent resource {resource.kind}:{name} in namespace:{namespace}, error captured." ) return raise def update_or_create( self, resource: Resource, body: Optional[Dict] = None, name: Optional[str] = None, namespace: Optional[str] = None, update_method: str = "replace", auto_add_version: bool = False, **kwargs, ) -> Tuple[ResourceInstance, bool]: """创建或修改一个 Kubernetes 资源 :param update_method: 修改类型,默认为 replace,可选值 patch :param auto_add_version: 当 update_method=replace 时,是否自动添加 metadata.resourceVersion 字段,默认为 False :returns: (instance, created) :raises: 当 update_method 不正确时,抛出 ValueError。调用 API 错误时,抛出 ApiException """ if update_method not in ["replace", "patch"]: raise ValueError("Invalid update_method {}".format(update_method)) obj = self.get_or_none(resource, name=name, namespace=namespace, **kwargs) if not obj: logger.info(f"Resource {resource.kind}:{name} not exists, continue creating") return resource.create(body=body, namespace=namespace, **kwargs), True # 资源已存在,执行后续的 update 逻辑 if update_method == 'replace' and auto_add_version: self._add_resource_version(obj, body) update_func_obj = getattr(resource, update_method) return update_func_obj(body=body, name=name, namespace=namespace, **kwargs), False def generate_api_client(access_token: str, project_id: str, cluster_id: str) -> ApiClient: """ 根据指定参数,生成 api_client """ ctx_cluster = CtxCluster.create(id=cluster_id, project_id=project_id, token=access_token) config = BcsKubeConfigurationService(ctx_cluster).make_configuration() return ApiClient( config, header_name='X-BKAPI-AUTHORIZATION', header_value=json.dumps({"access_token": access_token}) ) def generate_core_dynamic_client(access_token: str, project_id: str, cluster_id: str) -> CoreDynamicClient: """ 根据指定参数,生成 CoreDynamicClient """ api_client = generate_api_client(access_token, project_id, cluster_id) # TODO 考虑集群可能升级k8s版本的情况, 缓存文件会失效 discoverer_cache = DiscovererCache(cache_key=f"osrcp-{cluster_id}.json") return CoreDynamicClient(api_client, cache_file=discoverer_cache, discoverer=BcsLazyDiscoverer) def get_dynamic_client( access_token: str, project_id: str, cluster_id: str, use_cache: bool = True ) -> CoreDynamicClient: """ 根据 token、cluster_id 等参数,构建访问 Kubernetes 集群的 Client 对象 :param access_token: bcs access_token :param project_id: 项目 ID :param cluster_id: 集群 ID :param use_cache: 是否使用缓存 :return: 指定集群的 CoreDynamicClient """ if use_cache: return _get_dynamic_client(access_token, project_id, cluster_id) # 若不使用缓存,则直接生成新的实例返回 return generate_core_dynamic_client(access_token, project_id, cluster_id) @lru_cache(maxsize=128) def _get_dynamic_client(access_token: str, project_id: str, cluster_id: str) -> CoreDynamicClient: """ 获取 Kubernetes Client 对象(带缓存)""" return generate_core_dynamic_client(access_token, project_id, cluster_id) @lru_cache(maxsize=128) def get_resource_api(dynamic_client: CoreDynamicClient, kind: str, api_version: Optional[str] = None) -> Resource: """获取绑定到具体资源类型的 Resource API client""" if api_version: return dynamic_client.resources.get(kind=kind, api_version=api_version) return dynamic_client.get_preferred_resource(kind) def make_labels_string(labels: Dict) -> str: """Turn a labels dict into string format :param labels: dict of labels """ return ",".join("{}={}".format(key, value) for key, value in labels.items()) @contextmanager
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 24893, 1087, 318, 10607, 284, 1104, 262, 1280, 2723, 2055, 416, 1642, 5525, 241, 251, 165, 110, 116, 162, 247, 118, 12859, 239, 47, 7252, 50, 33176, 111, 2...
2.132026
3,416
from graphene import List from graphene_django.types import DjangoObjectType from articles.models import Article
[ 6738, 42463, 1330, 7343, 198, 6738, 42463, 62, 28241, 14208, 13, 19199, 1330, 37770, 10267, 6030, 198, 198, 6738, 6685, 13, 27530, 1330, 10172 ]
4.708333
24
from dexp.utils.backends import Backend def wiener_kernel(kernel, alpha: float = 1e-3, frequency_domain: bool = False, dtype=None): """Computes the Wiener filter for a given kernel and alpha parameter. Parameters ---------- kernel : kernel alpha : alpha parameter frequency_domain : if True then the wiener kernel is returned in the frequency domain dtype : dtype for kernel Returns ------- Wiener kernel """ backend = Backend.current() xp = backend.get_xp_module() if dtype is None: dtype = kernel.dtype psf_fft = xp.fft.fftn(kernel) kernel_fft = psf_fft / (xp.abs(psf_fft) * xp.abs(psf_fft) + alpha) if frequency_domain: return kernel_fft else: kernel = xp.real(xp.fft.ifftn(kernel_fft)) kernel = kernel / kernel.sum() kernel = kernel.astype(dtype, copy=False) return kernel
[ 6738, 36017, 79, 13, 26791, 13, 1891, 2412, 1330, 5157, 437, 628, 198, 4299, 45967, 877, 62, 33885, 7, 33885, 11, 17130, 25, 12178, 796, 352, 68, 12, 18, 11, 8373, 62, 27830, 25, 20512, 796, 10352, 11, 288, 4906, 28, 14202, 2599, ...
2.532213
357
# Generated by Django 2.1.4 on 2019-01-06 09:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 19, 319, 13130, 12, 486, 12, 3312, 7769, 25, 1065, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 142...
3.019231
52
import lab as B import numpy as np from plum import convert, Union from .. import _dispatch from ..aggregate import Aggregate, AggregateInput from ..datadims import data_dims from ..util import ( register_module, register_composite_coder, split, split_dimension, merge_dimensions, select, ) __all__ = [ "RepeatForAggregateInputs", "SelectFromChannels", "RepeatForAggregateInputPairs", "SelectFromDenseCovarianceChannels", ] @register_composite_coder @register_module class RepeatForAggregateInputs: """If the coder `coder` encounters an aggregate of target inputs, perform the coding operation for every element in the aggregate with the keyword argument `select_channel` set to the index of the particular output selected in the element of the aggregate of inputs. Args: coder (coder): Coder. """ @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @_dispatch @register_module class SelectFromChannels: """Select an output channel within a :class:`.RepeatForAggregateInputs`. The channels dimension is supposed to be a concatenation of multiple blocks of channels, where selecting the `i`th output is performed by selecting the `i`th element of every block. The elements of `sizes` specify the lengths of the blocks. If an element of `sizes` is a tuple, then it is assumed that the channels of that block must be further reshaped into that tuple. The selection will then happen on the _last_ unpacked dimension. Args: *sizes (int or tuple[int]): Specification of the channel blocks. """ @_dispatch @register_composite_coder @register_module class RepeatForAggregateInputPairs: """If the coder `coder` encounters an aggregate of target inputs, perform the coding operation for every pair of elements in the aggregate with the keyword arguments `select_channel_i` and `select_channel_j` set to the indices of the particular outputs selected in the pair of elements of the aggregate of inputs. Args: coder (coder): Coder. """ @_dispatch @_dispatch @_dispatch @register_module class SelectFromDenseCovarianceChannels: """Select a pair of output channels from a dense covariance within a :class:`RepeatForAggregateInputPairs`.""" @_dispatch
[ 11748, 2248, 355, 347, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 22802, 1330, 10385, 11, 4479, 198, 198, 6738, 11485, 1330, 4808, 6381, 17147, 198, 6738, 11485, 9460, 49373, 1330, 19015, 49373, 11, 19015, 49373, 20560, 198, 6738, 114...
3.105469
768
import os import os.path from datetime import datetime from unittest import TestCase import cate.core.ds as io from cate.conf import get_data_stores_path from cate.core.ds import DATA_STORE_REGISTRY from cate.ds.esa_cci_ftp import FileSetDataStore, set_default_data_store
[ 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 269, 378, 13, 7295, 13, 9310, 355, 33245, 198, 6738, 269, 378, 13, 10414, 1330, 651, 62,...
2.978495
93
#!/usr/bin/env python3 import math insert_sizes = [] with open('insertsize.sam', 'rt') as sam: for sam_line in sam: try: sam_parts = sam_line.split('\t') sam_flags = int(sam_parts[1]) if sam_flags & 2: # read mapped in proper pair insert_size = int(sam_parts[8]) if insert_size > 0: insert_sizes.append(insert_size) except (ValueError, IndexError): pass insert_sizes = sorted(insert_sizes) #insert_size_1st = get_percentile(insert_sizes, 1.0) insert_size_99th = get_percentile(insert_sizes, 99.0) print(insert_size_99th)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 10688, 198, 198, 28463, 62, 82, 4340, 796, 17635, 198, 4480, 1280, 10786, 28463, 7857, 13, 37687, 3256, 705, 17034, 11537, 355, 6072, 25, 198, 220, 220, 220, 329, 6072,...
2.060703
313
# Plot Spectrum at a list of positions in a FITS ImageMF # On either raw (no PBCor) or PBCorImageMF.py PB corrected name = 'Abell_194' # Base of plot name inFile = 'Abell_194.fits'; fdisk=0 # Input file on cwd # Specify positions (name, ra, dec) srcpos = [ \ ('core', '01:26:00.597', '-01:20:43.71'), \ ('src_1', '01:25:38.632', '-01:11:43.34'), \ ('src_2', '01:25:13.0137','-01:28:02.41'), \ ('src_5', '01:24:00.795', '-01:05:04.99'), \ ('src_8', '01:27:02.936' ,'-02:08:19.02'), \ ('src_9', '01:23:10.24', '-01:56:24.7'), \ ('src_10','01:23:21.18', '-01:58:36.75'), \ ('src_11','01:23:27.71', '-02:04:45.92'), \ ] # Shouldn't need to change below here import math from math import isnan import FITS, OPlot, Image, ImageDesc, ImageMF, FArray, FInterpolate, ImageUtil # Setup Obit import OErr, OSystem adirs = [] fdirs = ['./'] # Init Obit err=OErr.OErr() user = 100 ObitSys=OSystem.OSystem ("plotSpectrum", 1, user, len(adirs), adirs, \ len(fdirs), fdirs, True, False, err) OErr.printErrMsg(err, "Error with Obit startup") fblank = FArray.fblank # In image icube = Image.newPFImage('In', inFile, fdisk, True, err) # Image info nterm = icube.Desc.List.Dict['NTERM'][2][0] nspec = icube.Desc.List.Dict['NSPEC'][2][0] freqs = [] for i in range(1,nspec+1): key = 'FREQ%4.4d'%i freqs.append(1.0e-9*icube.Desc.List.Dict[key][2][0]) # GHz # end loop # Interpolator fi = FInterpolate.FInterpolate('FI', icube.FArray, icube.Desc, 2) # Get pixel locations pixels = []; vals = [] for s in srcpos: pos = [ImageDesc.PHMS2RA(s[1]), ImageDesc.PDMS2Dec(s[2])] pixel = ImageDesc.PGetPixel(icube.Desc, pos, err) pixels.append(pixel) vals.append(nspec*[fblank]) # end loop OErr.printErrMsg(err,message='Finding positions') # Loop over planes interpolating values rms = [] for i in range(0,nspec): # Read plane plane=[i+nterm+1,1,1,1,1] Image.PGetPlane (icube, None, plane, err) rms.append(icube.FArray.RMS) # Plane RMS # Interpolate positions for j in range(0,len(pixels)): pixel = pixels[j] val = FInterpolate.PPixel(fi, pixel, err) print (i,j,val,rms[i],freqs[i]) if val>0.0: vals[j][i] = val # end loop over planes OErr.printErrMsg(err,message='Interpolating values') # Plot pname = name plot=OPlot.newOPlot("Plot", err,output=pname+".ps/ps") i = -1 for s in srcpos: i += 1 plot.List.set("TITLE"," %s %s %s %s"\ %(name, s[0], s[1],s[2])) plot.List.set("YLABEL","Flux density (Jy)") plot.List.set("XLABEL","Frequency (GHz)") plot.List.set("XOPT","LBCN") plot.List.set("YOPT","LBCN") #plot.List.set("XMAX",1.1*max(freqs)) #plot.List.set("XMIN",0.9*min(freqs)) ymn = 0.9*10**int(-0.9+math.log10(min(vals[i]))) #ymx = ymn * 10. print (ymn,min(vals[i])) plot.List.set("YMIN",ymn) #plot.List.set("YMAX",ymx) plot.List.set("CSIZE",1) plot.List.set("SSIZE",3) plot.List.set("LWIDTH",3) OPlot.PXYErr(plot, 2, freqs, vals[i], rms, err) OErr.printErrMsg(err,message='Plotting Spectrum') # end loop over positions OPlot.PShow(plot,err) OErr.printErrMsg(err,message='Plotting Spectrum') # Shutdown Obit OErr.printErr(err) #OSystem.Shutdown(ObitSys)
[ 2, 28114, 27217, 379, 257, 1351, 286, 6116, 287, 257, 376, 29722, 7412, 49800, 198, 2, 1550, 2035, 8246, 357, 3919, 350, 2749, 273, 8, 393, 350, 2749, 273, 5159, 49800, 13, 9078, 30524, 19267, 198, 198, 3672, 220, 220, 796, 705, 482...
2.04899
1,633
#!/usr/bin/env python """Test the collector flows. To reduce the size of this module, additional collector flow tests are split out into collectors_*_test.py files. """ import os import mock import psutil from grr import config from grr.client.client_actions import standard from grr.lib import flags from grr.lib import utils from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import paths as rdf_paths from grr.server import aff4 from grr.server import artifact from grr.server import artifact_registry from grr.server import artifact_utils from grr.server import flow from grr.server import sequential_collection from grr.server.flows.general import collectors from grr.test_lib import action_mocks from grr.test_lib import client_test_lib from grr.test_lib import flow_test_lib from grr.test_lib import test_lib from grr.test_lib import vfs_test_lib class TestArtifactCollectors(flow_test_lib.FlowTestsBaseclass): """Test the artifact collection mechanism with fake artifacts.""" def setUp(self): """Make sure things are initialized.""" super(TestArtifactCollectors, self).setUp() test_artifacts_file = os.path.join(config.CONFIG["Test.data_dir"], "artifacts", "test_artifacts.json") artifact_registry.REGISTRY.AddFileSource(test_artifacts_file) self.fakeartifact = artifact_registry.REGISTRY.GetArtifact("FakeArtifact") self.fakeartifact2 = artifact_registry.REGISTRY.GetArtifact("FakeArtifact2") self.output_count = 0 with aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw") as fd: fd.Set(fd.Schema.SYSTEM("Linux")) kb = fd.Schema.KNOWLEDGE_BASE() artifact.SetCoreGRRKnowledgeBaseValues(kb, fd) fd.Set(kb) def testGetArtifact1(self): """Test we can get a basic artifact.""" client_mock = action_mocks.FileFinderClientMock() client = aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw") client.Set(client.Schema.SYSTEM("Linux")) client.Flush() # Dynamically add an ArtifactSource specifying the base path. file_path = os.path.join(self.base_path, "test_img.dd") coll1 = artifact_registry.ArtifactSource( type=artifact_registry.ArtifactSource.SourceType.FILE, attributes={"paths": [file_path]}) self.fakeartifact.sources.append(coll1) artifact_list = ["FakeArtifact"] for _ in flow_test_lib.TestFlowHelper( collectors.ArtifactCollectorFlow.__name__, client_mock, artifact_list=artifact_list, use_tsk=False, token=self.token, client_id=self.client_id): pass # Test the AFF4 file that was created. fd1 = aff4.FACTORY.Open( "%s/fs/os/%s" % (self.client_id, file_path), token=self.token) fd2 = open(file_path, "rb") fd2.seek(0, 2) self.assertEqual(fd2.tell(), int(fd1.Get(fd1.Schema.SIZE))) def testRunGrrClientActionArtifact(self): """Test we can get a GRR client artifact.""" with utils.Stubber(psutil, "process_iter", ProcessIter): client_mock = action_mocks.ActionMock(standard.ListProcesses) client = aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw") client.Set(client.Schema.SYSTEM("Linux")) client.Flush() coll1 = artifact_registry.ArtifactSource( type=artifact_registry.ArtifactSource.SourceType.GRR_CLIENT_ACTION, attributes={"client_action": standard.ListProcesses.__name__}) self.fakeartifact.sources.append(coll1) artifact_list = ["FakeArtifact"] for s in flow_test_lib.TestFlowHelper( collectors.ArtifactCollectorFlow.__name__, client_mock, artifact_list=artifact_list, token=self.token, client_id=self.client_id): session_id = s fd = flow.GRRFlow.ResultCollectionForFID(session_id) self.assertTrue(isinstance(list(fd)[0], rdf_client.Process)) self.assertTrue(len(fd) == 1) def testRunGrrClientActionArtifactSplit(self): """Test that artifacts get split into separate collections.""" with utils.Stubber(psutil, "process_iter", ProcessIter): client_mock = action_mocks.ActionMock(standard.ListProcesses) client = aff4.FACTORY.Open(self.client_id, token=self.token, mode="rw") client.Set(client.Schema.SYSTEM("Linux")) client.Flush() coll1 = artifact_registry.ArtifactSource( type=artifact_registry.ArtifactSource.SourceType.GRR_CLIENT_ACTION, attributes={"client_action": standard.ListProcesses.__name__}) self.fakeartifact.sources.append(coll1) self.fakeartifact2.sources.append(coll1) artifact_list = ["FakeArtifact", "FakeArtifact2"] for s in flow_test_lib.TestFlowHelper( collectors.ArtifactCollectorFlow.__name__, client_mock, artifact_list=artifact_list, token=self.token, client_id=self.client_id, split_output_by_artifact=True): session_id = s # Check that we got two separate collections based on artifact name fd = collectors.ArtifactCollectorFlow.ResultCollectionForArtifact( session_id, "FakeArtifact") self.assertTrue(isinstance(list(fd)[0], rdf_client.Process)) self.assertEqual(len(fd), 1) fd = collectors.ArtifactCollectorFlow.ResultCollectionForArtifact( session_id, "FakeArtifact2") self.assertEqual(len(fd), 1) self.assertTrue(isinstance(list(fd)[0], rdf_client.Process)) def testConditions(self): """Test we can get a GRR client artifact with conditions.""" with utils.Stubber(psutil, "process_iter", ProcessIter): # Run with false condition. client_mock = action_mocks.ActionMock(standard.ListProcesses) coll1 = artifact_registry.ArtifactSource( type=artifact_registry.ArtifactSource.SourceType.GRR_CLIENT_ACTION, attributes={"client_action": standard.ListProcesses.__name__}, conditions=["os == 'Windows'"]) self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertEqual(len(fd), 0) # Now run with matching or condition. coll1.conditions = ["os == 'Linux' or os == 'Windows'"] self.fakeartifact.sources = [] self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertNotEqual(len(fd), 0) # Now run with impossible or condition. coll1.conditions.append("os == 'NotTrue'") self.fakeartifact.sources = [] self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertEqual(len(fd), 0) def testSupportedOS(self): """Test supported_os inside the collector object.""" with utils.Stubber(psutil, "process_iter", ProcessIter): # Run with false condition. client_mock = action_mocks.ActionMock(standard.ListProcesses) coll1 = artifact_registry.ArtifactSource( type=artifact_registry.ArtifactSource.SourceType.GRR_CLIENT_ACTION, attributes={"client_action": standard.ListProcesses.__name__}, supported_os=["Windows"]) self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertEqual(len(fd), 0) # Now run with matching or condition. coll1.conditions = [] coll1.supported_os = ["Linux", "Windows"] self.fakeartifact.sources = [] self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertNotEqual(len(fd), 0) # Now run with impossible or condition. coll1.conditions = ["os == 'Linux' or os == 'Windows'"] coll1.supported_os = ["NotTrue"] self.fakeartifact.sources = [] self.fakeartifact.sources.append(coll1) fd = self._RunClientActionArtifact(client_mock, ["FakeArtifact"]) self.assertEqual(fd.__class__, sequential_collection.GeneralIndexedCollection) self.assertEqual(len(fd), 0) if __name__ == "__main__": flags.StartMain(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 14402, 262, 22967, 15623, 13, 198, 198, 2514, 4646, 262, 2546, 286, 428, 8265, 11, 3224, 22967, 5202, 5254, 389, 6626, 503, 198, 20424, 26668, 62, 9, 62, 9288, 13, 9078, 3696, ...
2.491433
3,502
from flask import Flask from flask_restful import Api from flask_apispec import FlaskApiSpec from resources import HelloWorld, Car from models import db from resources import CarByName if __name__ == '__main__': app = create_app() app.run(port=7654, host='0.0.0.0', debug=True)
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 2118, 913, 1330, 5949, 72, 198, 6738, 42903, 62, 499, 271, 43106, 1330, 46947, 32, 14415, 22882, 198, 198, 6738, 4133, 1330, 18435, 10603, 11, 1879, 198, 6738, 4981, 1330, 20613, 198, 198,...
2.969388
98
""" Base class for building blockchain transactions to issue Blockchain Certificates. """ import logging import json from pycoin.serialize import h2b from cert_issuer.errors import BroadcastError MAX_TX_RETRIES = 5
[ 37811, 198, 14881, 1398, 329, 2615, 11779, 8945, 284, 2071, 29724, 14965, 811, 689, 13, 198, 37811, 198, 11748, 18931, 198, 11748, 33918, 198, 198, 6738, 12972, 3630, 13, 46911, 1096, 1330, 289, 17, 65, 198, 198, 6738, 5051, 62, 747, ...
3.639344
61
#!/usr/bin/python import os import sys import time import Adafruit_DHT temperature_file = "/tmp/dht.temperature" humidity_file = "/tmp/dht.humidity" run_file = "/tmp/dht-run.pid" sensor = Adafruit_DHT.AM2302 pin = 22 if os.path.isfile(run_file): pid = read_runpid() exe = "/proc/{}/exe".format(pid) if os.path.isfile(exe): exit(0) write_runpid() while True: humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None: file = open(humidity_file, 'w') str = '{0:0.1f}\n'.format(humidity) file.write(str) file.close() if temperature is not None: file = open(temperature_file, 'w') str = '{0:0.1f}\n'.format(temperature) file.write(str) file.close() time.sleep(1)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 1215, 1878, 4872, 62, 35, 6535, 198, 198, 11498, 21069, 62, 7753, 796, 12813, 22065, 14, 67, 4352, 13, 11498, 21069, 1, 198,...
2.087629
388
import os import sys import html from flask import Flask, render_template INDENT = ' ' class Page(Tag): ''' include a <html> ''' @page_switch_gstate @property @property @page_switch_gstate def display(self, host='0.0.0.0', port=8081, tpl_dir='template', args={}): ''' start a flask service and display this page. ''' SERVER_PATH = os.path.abspath(os.path.dirname(sys.argv[0])) STATIC_DIR = os.path.join(SERVER_PATH, tpl_dir) if not os.path.isdir(tpl_dir): os.mkdir(tpl_dir) with open(os.path.join(tpl_dir, self.filename), 'w') as f: f.write(self.state.compile()) print('server root', SERVER_PATH) print('static dir', STATIC_DIR) app = Flask( __name__, static_url_path=STATIC_DIR, template_folder=STATIC_DIR) #app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/') app.run(debug=True, host=host, port=port) @page_switch_gstate @page_switch_gstate def enable_echarts(self): ''' Add pyecharts scripts ''' host = "https://pyecharts.github.io/assets/js" with self._body: RawHtml('\n'.join([ '{% for jsfile_name in script_list %}', '<script src="%s/{{ jsfile_name }}.js"></script>' % host, '{% endfor %}', ])) return self def compile(li): ''' li: a list compile and skip duplicate items. ''' compiled = set() lines = [] for item in li: if isinstance(item, Tag): if item not in compiled: c = str(item) lines.append(c) compiled.add(item) else: lines.append(str(item)) return '\n'.join(lines) if __name__ == '__main__': page = Page(title='hello world') page.enable_bootstrap() with page.body: Tag('h1', c='hello world') # page.display() page1 = Page(title='another page') page1.enable_bootstrap() with page1.body: Tag('h1', c='hello world, superjomn') Tag('h2', c='there are many fruits') page1.display()
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 27711, 198, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 198, 12115, 3525, 796, 705, 220, 220, 220, 705, 628, 628, 628, 628, 198, 4871, 7873, 7, 24835, 2599, 198, 220, 220, 220,...
2.0625
1,056
from typing import List
[ 6738, 19720, 1330, 7343, 628, 220, 220, 220, 220, 198 ]
3
10
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: sample Filter(logname),只允许来自logname或其子日志的消息通过 app.net是app的子日志 消息传播propagate和分层记录器:消息会传播给父记录器 log.propagate属性获取是否传播标志 """ import logging import logging.handlers as handlers import logging.config as config __author__ = 'Xiong Neng' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[logging.FileHandler('message.log', 'a', 'utf-8')]) # 模块基本用_,类级别用__ _log = logging.getLogger('app.' + __name__) if __name__ == '__main__': my_log()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 47373, 25, 6291, 628, 220, 220, 220, 25853, 7, 75, 2360, 480, 8, 171, 120, 234, 20998, 1...
1.549774
442
# coding: utf-8 """ Matplotlib figure functionality for the Traits GUI. """ from __future__ import division, print_function __author__ = "Andy Casey <arc@ast.cam.ac.uk>" # Third-party import wx from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.pyplot import Figure, subplot from matplotlib.ticker import MaxNLocator # Editor factories for matplotlib figures from traitsui.wx.editor import Editor from traitsui.wx.basic_editor_factory import BasicEditorFactory class _MPLFigureEditor(Editor): """ Editor class for containing a matplotlib figure within a Traits GUI. """ scrollable = True def _create_canvas(self, parent): """ Create the matplotlib canvas """ panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) mpl_control = FigureCanvasWxAgg(panel, -1, self.value) sizer.Add(mpl_control, 1, wx.LEFT | wx.TOP | wx.GROW) toolbar = NavigationToolbar2Wx(mpl_control) sizer.Add(toolbar, 0, wx.EXPAND) self.value.canvas.SetMinSize((10,10)) return panel class MPLFigureEditor(BasicEditorFactory): """ Factory class for generating editors that contain matplotlib figures and can be placed within a Traits GUI. """ klass = _MPLFigureEditor
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 6550, 29487, 8019, 3785, 11244, 329, 262, 4759, 896, 25757, 13, 37227, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 198, 198, 834, 9800, 834, 796, 366, 35314, 21...
2.660413
533
from tflite_support import metadata_schema_py_generated as _metadata_fb from constants import IMAGE_NAME, IOU_NAME, CONF_NAME, NORMALIZED_SUFFIX, QUANTIZED_SUFFIX from tf_metadata.metadata_utils import MetadataHelper
[ 6738, 256, 2704, 578, 62, 11284, 1330, 20150, 62, 15952, 2611, 62, 9078, 62, 27568, 355, 4808, 38993, 62, 21855, 198, 198, 6738, 38491, 1330, 8959, 11879, 62, 20608, 11, 314, 2606, 62, 20608, 11, 7102, 37, 62, 20608, 11, 25273, 42126,...
3.084507
71
# Sergio, 2020 __all__ = ['misc']
[ 2, 220, 220, 36759, 11, 12131, 198, 198, 834, 439, 834, 796, 37250, 44374, 20520, 198 ]
2.3125
16
# -*- coding: utf-8 -*- # This module contains all the Object classes used by the MIT Core Concept # Catalog (MC3) Handcar based implementation of the OSID Id Service. from ...abstract_osid.id import objects as abc_id_objects from ..osid import objects as osid_objects from .. import settings from ..primitives import Id, Type, DisplayText from ..osid.osid_errors import NullArgument, InvalidArgument, NotFound, NoAccess, IllegalState, OperationFailed, Unimplemented, Unsupported INVALID = 0 VALID = 1 class IdList(abc_id_objects.IdList, osid_objects.OsidList): """Like all OsidLists, IdList provides a means for accessing Id elements sequentially either one at a time or many at a time. Examples: while (il.hasNext()) { Id id = il.getNextId(); } or while (il.hasNext()) { Id[] ids = il.getNextIds(il.available()); } """ def get_next_id(self): """Gets the next Id in this list. return: (osid.id.Id) - the next Id in this list. The has_next() method should be used to test that a next Id is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request compliance: mandatory - This method must be implemented. """ try: next_item = next(self) except StopIteration: raise IllegalState('no more elements available in this list') except Exception: # Need to specify exceptions here! raise OperationFailed() else: return next_item __next__ = next def get_next_ids(self, n=None): """Gets the next set of Ids in this list. The specified amount must be less than or equal to the return from available(). arg: n (cardinal): the number of Id elements requested which must be less than or equal to available() return: (osid.id.Id) - an array of Id elements. The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request compliance: mandatory - This method must be implemented. """ if n > self.available(): # !!! This is not quite as specified (see method docs) !!! raise IllegalState('not enough elements available in this list') else: next_list = [] x = 0 while x < n: try: next_list.append(next(self)) except Exception: # Need to specify exceptions here! raise OperationFailed() x = x + 1 return next_list next_id = property(get_next_id)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 770, 8265, 4909, 477, 262, 9515, 6097, 973, 416, 262, 17168, 7231, 26097, 198, 2, 44515, 357, 9655, 18, 8, 7157, 7718, 1912, 7822, 286, 262, 7294, 2389, 5121, ...
2.535809
1,131
# dataframe column names SURNAME = 'surname' ORIGIN = 'nationality' # split types TRAIN = 'train' VALID = 'val' TEST = 'test' # special tokens START_TOKEN = '<start>' END_TOKEN = '<end>' MASK_TOKEN = '<mask>' UNK_TOKEN = '<unk>' # data dictionary keys X_DATA = 'x_data' Y_TARGET = 'y_target'
[ 2, 1366, 14535, 5721, 3891, 198, 50, 4261, 20608, 796, 705, 82, 700, 480, 6, 198, 1581, 3528, 1268, 796, 705, 14648, 414, 6, 198, 198, 2, 6626, 3858, 198, 51, 3861, 1268, 796, 705, 27432, 6, 198, 23428, 2389, 796, 705, 2100, 6, ...
2.251908
131
"""Delete duplicate atom entries""" import numpy as np import argparse import logging import os import sys import time from string import ascii_uppercase from . import Structure from .structure import residue_type from .structure.residue import _RotamerResidue from .structure.rotamers import ROTAMERS
[ 37811, 38727, 23418, 22037, 12784, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 4731, 1330, 355, 979, 72, 62, 7211, 2798, 589, 198...
3.607143
84
from scipy.linalg import solve from scipy.special import erf as erf import matplotlib.pyplot as plt import numpy as np n = 20 dt, T = 1., int(1e4) l = np.int(np.ceil(T / dt)) sqrt_dt = np.sqrt(dt) sqrt_2 = np.sqrt(2) rat = sqrt_dt / sqrt_2 w = np.random.uniform(-0.5, 0.5, size=(n, n)) w[np.diag_indices_from(w)] -= 2.0 w /= np.sqrt(n) x = np.zeros((n, l)) x[:, 0] = np.random.uniform(-1, 1, size=n) noise = np.random.normal(size=(n, l - 1)) for t in range(1, l): x[:, t] = x[:, t - 1] + w.dot(x[:, t - 1]) * dt + noise[:, t - 1] * sqrt_dt plt.figure(figsize=(16, 4)) plt.plot(x[:, -100:].T) plt.show() x1, x2 = x[:, :-1], x[:, 1:] sign_dx = np.sign(np.diff(x)) mean_x = x.mean(1) cov_x = np.cov(x) x1_mean0 = x1 - mean_x[:, np.newaxis] w_fit = np.empty((n, n)) e = [] for i in range(n): res = fit(i) w_fit[i] = res[0] / rat e.append(res[1]) w_flat = w.flatten() w_fit_flat = w_fit.flatten() plt.scatter(w_flat, w_fit_flat, c='k', s=0.1) grid = np.linspace(w_flat.min(), w_flat.max()) plt.plot(grid, grid, 'r--', lw=0.5) plt.show() for ei in e: plt.plot(ei) plt.show()
[ 6738, 629, 541, 88, 13, 75, 1292, 70, 1330, 8494, 198, 6738, 629, 541, 88, 13, 20887, 1330, 1931, 69, 355, 1931, 69, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 77, 7...
1.890034
582
# Create your views here. from django.shortcuts import render from .froms import SampleSearchForm
[ 2, 13610, 534, 5009, 994, 13, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 764, 6738, 82, 1330, 27565, 18243, 8479, 628, 198 ]
3.846154
26
from pyspark.sql import SparkSession from pyspark.sql.functions import avg spark = SparkSession\ .builder\ .appName("SparkApp")\ .master("local[*]")\ .getOrCreate() # Create a DataFrame using SparkSession data_df = spark.createDataFrame([("Brooke", 20), ("Denny", 31), ("Jules", 30), ("TD", 35), ("Brooke", 25)], ["name", "age"]) # Group the same names together, aggregate their age, and compute an average avg_df = data_df.groupBy("name").agg(avg("age")) # Show the results of the final execution avg_df.show()
[ 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 198, 6738, 279, 893, 20928, 13, 25410, 13, 12543, 2733, 1330, 42781, 198, 198, 2777, 668, 796, 17732, 36044, 59, 198, 220, 220, 220, 220, 220, 220, 220, 764, 38272, 59, 198, 220, ...
2.707921
202
#!/usr/bin/env python3 # -*- coding: utf-8 -*-+ import sys sys.path.insert(1,'/usr/local/lib/python3.5/dist-packages') import numpy as np import cv2 INNER_X = 100 INNER_Y = 30 OUTER_X = 150 OUTER_Y = 60 RANGE = 20 if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 19529, 201, 198, 201, 198, 11748, 25064, 201, 198, 17597, 13, 6978, 13, 28463, 7, 16, 4032, 14, 14629, 14, 12001, 14,...
2.05303
132
""" Video Face Manipulation Detection Through Ensemble of CNNs Image and Sound Processing Lab - Politecnico di Milano Nicolò Bonettini Edoardo Daniele Cannas Sara Mandelli Luca Bondi Paolo Bestagini """ from typing import List import albumentations as A import pandas as pd from albumentations.pytorch import ToTensorV2 from .data import FrameFaceIterableDataset, get_iterative_real_fake_idxs
[ 37811, 198, 10798, 15399, 35045, 1741, 46254, 9561, 2039, 15140, 286, 8100, 82, 198, 198, 5159, 290, 9506, 28403, 3498, 532, 2165, 578, 31522, 3713, 2566, 4460, 5733, 198, 198, 45, 27045, 127, 110, 7979, 3087, 5362, 198, 36, 4598, 13109...
3.133858
127
from nlplib.general.represent import represented_nonliterally __all__ = ['Base'] class Base : ''' A base class for all of the core classes. '''
[ 198, 198, 6738, 299, 75, 489, 571, 13, 24622, 13, 15603, 1330, 7997, 62, 13159, 43819, 198, 198, 834, 439, 834, 796, 37250, 14881, 20520, 198, 198, 4871, 7308, 1058, 198, 220, 220, 220, 705, 7061, 317, 2779, 1398, 329, 477, 286, 262...
3.122449
49
#!/usr/bin/env python """ @package mi.dataset.parser.test.test_presf_abc_dcl @file marine-integrations/mi/dataset/parser/test/test_presf_abc_dcl.py @author Christopher Fortin @brief Test code for a presf_abc_dcl data parser """ import os from nose.plugins.attrib import attr from mi.core.log import get_logger log = get_logger() from mi.core.exceptions import RecoverableSampleException from mi.dataset.test.test_parser import \ ParserUnitTestCase, \ BASE_RESOURCE_PATH from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.parser.presf_abc_dcl import \ PresfAbcDclRecoveredTideDataParticle, \ PresfAbcDclTelemeteredTideDataParticle, \ PresfAbcDclRecoveredWaveDataParticle, \ PresfAbcDclTelemeteredWaveDataParticle, \ DataTypeKey, \ TIDE_PARTICLE_CLASS_KEY, \ WAVE_PARTICLE_CLASS_KEY, \ PresfAbcDclParser RESOURCE_PATH = os.path.join(BASE_RESOURCE_PATH, 'presf_abc', 'dcl', 'resource') MODULE_NAME = 'mi.dataset.parser.presf_abc_dcl' # The list of generated tests are the suggested tests, but there may # be other tests needed to fully test your parser @attr('UNIT', group='mi') class PresfAbcDclParserUnitTestCase(ParserUnitTestCase): """ presf_abc_dcl Parser unit test suite """ def pub_callback(self, pub): """ Call back method to watch what comes in via the publish callback """ self.publish_callback_value = pub def test_simple(self): """ Read data from a file and pull out data particles one at a time. Verify that the results are those we expected. """ log.debug('===== START TEST SIMPLE =====') with open(os.path.join(RESOURCE_PATH, '20140417.presf3.log'), 'r') as file_handle: parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) # file has one tide particle and one wave particle particles = parser.get_records(2) # Make sure we obtained 2 particles self.assertTrue(len(particles) == 2) self.assert_particles(particles, '20140417.presf3_telem.yml', RESOURCE_PATH) with open(os.path.join(RESOURCE_PATH, '20140417.presf3.log'), 'r') as file_handle: parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_RECOVERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) # file has one tide particle and one wave particle particles = parser.get_records(2) # Make sure we obtained 2 particles self.assertTrue(len(particles) == 2) self.assert_particles(particles, '20140417.presf3_recov.yml', RESOURCE_PATH) log.debug('===== END TEST SIMPLE =====') def test_get_many(self): """ Read test data and pull out multiple data particles at one time. Assert that the results are those we expected. """ log.debug('===== START TEST MANY =====') with open(os.path.join(RESOURCE_PATH, '20140105_trim.presf.log'), 'r') as file_handle: parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(20) # Make sure we obtained 20 particles self.assertTrue(len(particles) == 20) self.assert_particles(particles, "20140105_trim.presf_telem.yml", RESOURCE_PATH) with open(os.path.join(RESOURCE_PATH, '20140105_trim.presf.log'), 'r') as file_handle: parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_RECOVERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(20) # Make sure we obtained 20 particles self.assertTrue(len(particles) == 20) self.assert_particles(particles, "20140105_trim.presf_recov.yml", RESOURCE_PATH) log.debug('===== END TEST MANY =====') def test_long_stream(self): """ Test a long stream """ log.debug('===== START TEST LONG STREAM =====') with open(os.path.join(RESOURCE_PATH, '20140105.presf.log'), 'r') as file_handle: parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(48) # Make sure we obtained 20 particles self.assertTrue(len(particles) == 48) log.debug('===== END TEST LONG STREAM =====') def test_invalid_tide_record(self): """ The file used here has a damaged tide record ( the p = $$$ is replaced by a q = $$$ ) """ log.debug('===== START TEST INVALID TIDE RECORD =====') with open(os.path.join(RESOURCE_PATH, '20140105_invts.presf.log'), 'r') as file_handle: NUM_PARTICLES_TO_REQUEST = 20 NUM_EXPECTED_PARTICLES = 19 parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(NUM_PARTICLES_TO_REQUEST) self.assertEquals(len(particles), NUM_EXPECTED_PARTICLES) self.assert_particles(particles, "20140105_invts.presf_telem.yml", RESOURCE_PATH) for i in range(len(self.exception_callback_value)): self.assert_(isinstance(self.exception_callback_value[i], RecoverableSampleException)) with open(os.path.join(RESOURCE_PATH, '20140105_invts.presf.log'), 'r') as file_handle: NUM_PARTICLES_TO_REQUEST = 20 NUM_EXPECTED_PARTICLES = 19 parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_RECOVERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(NUM_PARTICLES_TO_REQUEST) self.assertEquals(len(particles), NUM_EXPECTED_PARTICLES) self.assert_particles(particles, "20140105_invts.presf_recov.yml", RESOURCE_PATH) for i in range(len(self.exception_callback_value)): self.assert_(isinstance(self.exception_callback_value[i], RecoverableSampleException)) log.debug('===== END TEST INVALID TIDE RECORD =====') def test_invalid_wave_record(self): """ Two of the wave records in this file are damaged. The first is missing the pt subrecord, and the second is missing the termination of the wave record. """ log.debug('===== START TEST INVALID WAVE RECORD =====') with open(os.path.join(RESOURCE_PATH, '20140105_invwv.presf.log'), 'r') as file_handle: NUM_PARTICLES_TO_REQUEST = 20 NUM_EXPECTED_PARTICLES = 18 parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(NUM_PARTICLES_TO_REQUEST) self.assertEquals(len(particles), NUM_EXPECTED_PARTICLES) self.assert_particles(particles, "20140105_invwv.presf_telem.yml", RESOURCE_PATH) for i in range(len(self.exception_callback_value)): self.assert_(isinstance(self.exception_callback_value[i], RecoverableSampleException)) with open(os.path.join(RESOURCE_PATH, '20140105_invwv.presf.log'), 'r') as file_handle: NUM_PARTICLES_TO_REQUEST = 20 NUM_EXPECTED_PARTICLES = 18 parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_RECOVERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(NUM_PARTICLES_TO_REQUEST) self.assertEquals(len(particles), NUM_EXPECTED_PARTICLES) self.assert_particles(particles, "20140105_invwv.presf_recov.yml", RESOURCE_PATH) for i in range(len(self.exception_callback_value)): self.assert_(isinstance(self.exception_callback_value[i], RecoverableSampleException)) log.debug('===== END TEST INVALID TIDE RECORD =====') def test_no_particles(self): """ Verify that no particles are produced if the input file has no instrument records. """ log.debug('===== START TEST NO PARTICLES =====') with open(os.path.join(RESOURCE_PATH, '20140417.presf1.log'), 'r') as file_handle: NUM_PARTICLES_TO_REQUEST = 10 NUM_EXPECTED_PARTICLES = 0 parser = PresfAbcDclParser(self.config.get(DataTypeKey.PRESF_ABC_DCL_TELEMETERED), None, file_handle, lambda state, ingested: None, lambda data: None, self.exception_callback) particles = parser.get_records(NUM_PARTICLES_TO_REQUEST) self.assertEquals(len(particles), NUM_EXPECTED_PARTICLES) self.assertEqual(self._exception_occurred, False) log.debug('===== END TEST NO PARTICLES =====')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 31, 26495, 21504, 13, 19608, 292, 316, 13, 48610, 13, 9288, 13, 9288, 62, 18302, 69, 62, 39305, 62, 67, 565, 198, 31, 7753, 16050, 12, 18908, 9143, 14, 11632, 14, ...
2.023452
5,330
from . import indicator_base from . import indicator from . import regex from . import yara
[ 6738, 764, 1330, 16916, 62, 8692, 198, 6738, 764, 1330, 16916, 198, 6738, 764, 1330, 40364, 198, 6738, 764, 1330, 331, 3301, 198 ]
4
23
""" A module to assist with using the Python logging module """ import errno import logging import logging.handlers import os import time def configure(*args, **kwargs): """ Borrowed from logging.basicConfig Uses the UTCFormatter instead of the regular Formatter Also, opts you into syslogging. """ syslog_address = kwargs.setdefault('syslog_address', '/dev/log') handlers = [] if len(logging.root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", 'a') handlers.append(logging.FileHandler(filename, mode)) else: stream = kwargs.get("stream") handlers.append(logging.StreamHandler(stream)) try: # Nobody can escape syslog, for now, and this default only # works on Linux. See: # # http://docs.python.org/library/logging.handlers.html#sysloghandler handlers.append(logging.handlers.SysLogHandler(syslog_address)) except EnvironmentError, e: if e.errno == errno.ENOENT: # Silently do-not-write to syslog if the socket cannot # be found at all. pass else: raise fs = kwargs.get("format", logging.BASIC_FORMAT) dfs = kwargs.get("datefmt", None) style = kwargs.get("style", '%') fmt = UTCFormatter(fs, dfs) for handler in handlers: handler.setFormatter(fmt) logging.root.addHandler(handler) level = kwargs.get("level") if level is not None: logging.root.setLevel(level)
[ 37811, 198, 32, 8265, 284, 3342, 351, 1262, 262, 11361, 18931, 8265, 198, 198, 37811, 198, 198, 11748, 11454, 3919, 198, 11748, 18931, 198, 11748, 18931, 13, 4993, 8116, 198, 11748, 28686, 198, 11748, 640, 628, 198, 198, 4299, 17425, 46...
2.211564
761
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # 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 logging from oauthlib import oauth2 from time import sleep from urllib.parse import urlparse import bravado_core import bravado from bravado.client import ( SwaggerClient, ResourceDecorator, CallableOperation, construct_request ) from bravado.config import bravado_config_from_config_dict from bravado.swagger_model import Loader from .exceptions import AetherAPIException from .basic_auth import BasicRealmClient from .oidc import OauthClient from .logger import LOG # monkey patch so that bulk insertion works from .patches import patched__marshal_object, patched__unmarshal_object bravado_core.marshal._marshal_object = patched__marshal_object bravado_core.unmarshal._unmarshal_object = patched__unmarshal_object _SPEC_URL = '{}/v1/schema/?format=openapi' # useful for debugging issues with outgoing requests. Only called when ll == DEBUG ''' Some arguments don't properly display in the swagger specification so we have to add them at runtime for the client to support them. This includes all payload filters like payload__name=John. Normally payload__name wouldn't be found in the spec and an error would be produced. '''
[ 2, 15069, 357, 34, 8, 13130, 416, 304, 18081, 5478, 1058, 2638, 1378, 2503, 13, 68, 18081, 17584, 30997, 13, 2398, 198, 2, 198, 2, 4091, 262, 28536, 2393, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 198, 2,...
3.590133
527
import asyncio import json import logging import sys from abc import ABC, abstractmethod from typing import List, TypeVar, Generic, Union, NoReturn, Iterator, Iterable from sqlalchemy import and_, or_ from .models import session_scope, Session from .twitter import * T = TypeVar("T") class BaseCrawler(ABC, Generic[T]): """Abstract base class for all crawlers.""" timeout_seconds = 15 * 60 # Twitter limits are usually "per 15 minutes" def log(self, msg: str) -> None: """Helper to log progress.""" print("[" + self.__class__.__name__ + "] " + msg) # temporary solution only @abstractmethod def exec(self, job: T) -> None: """Implement to execute the crawlers task.""" pass @abstractmethod def done(self) -> None: """Implement to issue new tasks when all existing tasks are complete.""" pass async def __get_and_exec_job(self): """Pulls a job from the queue and executes it. Might raise QueueEmpty exception.""" job = self.queue.get_nowait() try: self.exec(job) self.queue.task_done() except RateLimitError: self.log(f"Rate limit reached. Sleep {self.timeout_seconds} seconds…") await asyncio.sleep(self.timeout_seconds) self.queue.put_nowait(job) class UsersCrawler(BaseCrawler[Union[str, List[int]]]): """Crawler to fetch Twitter profiles either by screen name of IDs.""" class RelationsCrawler(BaseCrawler[str]): """Crawler to fetch all friends of a given Twitter users screen name. (Note: A friend in Twitters definition is somebody you follow.) """ class StatusesCrawler(BaseCrawler[str]): """Crawler to fetch all statuses (=tweets) by a given Twitter users screen name.""" async def __run_forever(crawler: BaseCrawler) -> None: """Internal helper to run a crawler forever with asyncio.""" while True: try: await crawler.run() except KeyboardInterrupt: print("\n --- INTERRUPT SIGNAL RECEIVED --- \n") sys.exit(0) except: logging.error("Unexpected exception occurred!", exc_info=True) sys.exit(-1) async def crawl(args) -> NoReturn: """Initiates the crawling process.""" with open('config.json') as config_file: config = json.load(config_file) twitter = TwitterClient(config["twitter"]) users_crawler = UsersCrawler(twitter) if args.users: for user in args.users: users_crawler.schedule(user.strip()) relations_crawler = RelationsCrawler(twitter) statuses_crawler = StatusesCrawler(twitter) await asyncio.wait(map(__run_forever, [ users_crawler, relations_crawler, statuses_crawler ]))
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 25064, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 7343, 11, 5994, 19852, 11, 42044, 11, 4479, 11, 1400, 13615, 11, 40806, 1352, 11, 4080...
2.611996
1,067
from django.core.exceptions import ObjectDoesNotExist from django.db.models.signals import post_save from django.dispatch import receiver from courses.models import ( Content, CourseUserRelations, ) from .models import Exam from .models import ExamUserRelations @receiver(post_save, sender=Content) @receiver(post_save, sender=CourseUserRelations)
[ 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 198, 6738, 42625, 14208, 13, 6381, 17147, 1330, 9733, 198, 6738, 109...
3.373832
107
from math import pi, pow from datetime import datetime, timedelta, timezone from doop.constants import Earth from collections import namedtuple from enum import IntFlag ID = namedtuple("ID", "launch_year launch_number piece") Object = namedtuple("Object", "name number classification") EphemerisType = IntFlag("EphemerisType","SGP SGP4 SDP4 SGP8 SDP8") TLE = namedtuple("TLE", 'object ' 'id ' 'coe ' 'ballistic_coeffecient ' 'bstar ' 'line1 line2' ) OE = namedtuple("OE", "a e i raan w v") def fix_sci(x): """ TLE have a shorthand for storing scientific numbers, just fixing it """ # leading +/- can trip this up if x[0] == '+' or x[0] == '-': xx = x[1:] else: xx = x s = xx.split("-") ss = xx.split("+") if len(s) == 2: x = float(s[0] + "e-" + s[1]) elif len(ss) == 2: s = ss x = float(s[0] + "e+" + s[1]) else: x = float(xx) return x def fix_dec(x): """ TLE formate assumes a leading decimal point, just putting it back in """ if x[0] == "-": ret = float("-0." + x[1:]) else: ret = float("0." + x) return ret def fix_epoch(day:float, year:int): """https://ubuntuforums.org/archive/index.php/t-2032246.html""" # print(f"day {day} year {year}") yr = fix_year(year) return datetime(year=yr, month=1, day=1, tzinfo=timezone.utc) + timedelta(days=day-1) def parse_tle(tle:str): """ Format https://en.wikipedia.org/wiki/Two-line_element_set https://celestrak.com/NORAD/documentation/tle-fmt.php https://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/SSOP_Help/tle_def.html AAAAAAAAAAAAAAAAAAAAAAAA 1 NNNNNU NNNNNAAA NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN 2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN ISS (ZARYA) 1 25544U 98067A 20060.61908565 .00000737 00000-0 21434-4 0 9993 2 25544 51.6436 165.6500 0005418 332.6966 228.1099 15.49204316215186 TLE are in ECI frame """ # name, onel, twol = tle.split("\n") tle.strip() if tle[-1] == "\n": tle = tle[:-1] tmp = tle.split("\n") if len(tmp) == 2: name = "unknown" onel = tmp[0] twol = tmp[1] elif len(tmp) >= 3: name, onel, twol = tmp[:3] else: print(tmp) raise Exception(f"tle_parse: too many lines: {len(tmp)}") one = onel.split() two = twol.split() # print(f"name: {name}\n one: {one}\n two: {two}\n") cat = str(one[1]).strip() cl = fix_classification(cat[-1]) obj = Object(name.strip(), int(cat[:-1]),cl) yr = fix_year(int(one[2][:2])) piece = str(one[2][-1]) num = str(one[2][2:-1]) id = ID(yr, num, piece) yr = int(one[3][:2]) day = float(one[3][2:]) # print("epoch", fix_epoch(day, yr)) n = float(two[7][:11]) # mean motion, or period of orbit u = Earth.mu a = pow(u,1/3)/pow(2*n*pi/86400, 2/3) e = fix_dec(two[4]) i = float(two[2]) raan = float(two[3]) w = float(two[5]) v = float(two[6]) # classic orbital elements: a e i raan w v coe = OE(a,e,i,raan,w,v) d = int(one[7]) if d > 0: print(EphemerisType(d)) # else: # print(f"unknown ephemeris type: {d}") return TLE( obj, id, coe, # float(two[63:68]), # rev num at epoch - this number isn't useful/accurate float(one[4]), # ballistic coeff fix_sci(one[6]), # bstar # n, # mean motion # fix_sci(one[44:52]), # 2nd der mean motion onel, twol )
[ 6738, 10688, 1330, 31028, 11, 7182, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 11, 640, 11340, 198, 6738, 466, 404, 13, 9979, 1187, 1330, 3668, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 6738, 33829, 1330, 2558, ...
2.022246
1,843
import os import torch from time import strftime from util.optimization import load_sched from log_util import set_gpu_recursive, get_last_epoch, update_metric, best_performance
[ 11748, 28686, 198, 11748, 28034, 198, 6738, 640, 1330, 965, 31387, 198, 6738, 7736, 13, 40085, 1634, 1330, 3440, 62, 1416, 704, 198, 6738, 2604, 62, 22602, 1330, 900, 62, 46999, 62, 8344, 30753, 11, 651, 62, 12957, 62, 538, 5374, 11, ...
3.509804
51
__all__ = ["BinaryEmbeddings"] from dataclasses import dataclass, field import numpy as np from gensim.models import KeyedVectors from .embeddings import Embeddings @dataclass
[ 834, 439, 834, 796, 14631, 33, 3219, 31567, 6048, 654, 8973, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 308, 641, 320, 13, 27530, 1330, 7383, 276, 53, 478, ...
2.967213
61
''' Ostur Cheese Cave Controller Logger ''' import serial import sys import time from datetime import datetime
[ 7061, 6, 198, 38919, 333, 27601, 18603, 22741, 5972, 1362, 198, 7061, 6, 198, 198, 11748, 11389, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 4818, 8079, 1330, 4818, 8079, 628, 198 ]
3.59375
32
# This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. # See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. # Author(s): Marc Glisse # # Copyright (C) 2020 Inria # # Modification(s): # - YYYY/MM Author: Description of the modification from .knn import KNearestNeighbors __author__ = "Marc Glisse" __copyright__ = "Copyright (C) 2020 Inria" __license__ = "MIT" class DistanceToMeasure: """ Class to compute the distance to the empirical measure defined by a point set, as introduced in :cite:`dtm`. """ def __init__(self, k, q=2, **kwargs): """ Args: k (int): number of neighbors (possibly including the point itself). q (float): order used to compute the distance to measure. Defaults to 2. kwargs: same parameters as :class:`~gudhi.point_cloud.knn.KNearestNeighbors`, except that metric="neighbors" means that :func:`transform` expects an array with the distances to the k nearest neighbors. """ self.k = k self.q = q self.params = kwargs def fit(self, X, y=None): """ Args: X (numpy.array): coordinates for mass points. """ if self.params.setdefault("metric", "euclidean") != "neighbors": self.knn = KNearestNeighbors( self.k, return_index=False, return_distance=True, sort_results=False, **self.params ) self.knn.fit(X) return self def transform(self, X): """ Args: X (numpy.array): coordinates for query points, or distance matrix if metric is "precomputed", or distances to the k nearest neighbors if metric is "neighbors" (if the array has more than k columns, the remaining ones are ignored). Returns: numpy.array: a 1-d array with, for each point of X, its distance to the measure defined by the argument of :func:`fit`. """ if self.params["metric"] == "neighbors": distances = X[:, : self.k] else: distances = self.knn.transform(X) distances = distances ** self.q dtm = distances.sum(-1) / self.k dtm = dtm ** (1.0 / self.q) # We compute too many powers, 1/p in knn then q in dtm, 1/q in dtm then q or some log in the caller. # Add option to skip the final root? return dtm
[ 2, 770, 2393, 318, 636, 286, 262, 402, 463, 5303, 10074, 532, 3740, 1378, 70, 463, 5303, 13, 259, 7496, 13, 8310, 14, 532, 543, 318, 2716, 739, 17168, 13, 198, 2, 4091, 2393, 38559, 24290, 393, 467, 284, 3740, 1378, 70, 463, 5303,...
2.34267
1,071
num = int(input("Digite o numero:")) print(f"Divisores de {num} -",end=" ") for i in range(1, (num//2) + 1): if num % i == 0: print(f"{i}",end=" ")
[ 198, 22510, 796, 493, 7, 15414, 7203, 19511, 578, 267, 997, 3529, 11097, 4008, 198, 4798, 7, 69, 1, 24095, 271, 2850, 390, 1391, 22510, 92, 532, 1600, 437, 2625, 366, 8, 198, 198, 1640, 1312, 287, 2837, 7, 16, 11, 357, 22510, 1003...
2.0125
80
#!/usr/bin/env python3 import subprocess import netfilterqueue import sys import optparse DEFAULT_QUEUE_NUM = 0 exit_code = 0 dropped_packet_count = 0 parser = optparse.OptionParser() parser.add_option("-q", "--queue-num", dest="queue_num", default=DEFAULT_QUEUE_NUM, help="IPTables Queue Num") parser.add_option("-s", "--start-queue", dest="start_queue", action="store_true", default=False, help="Start IPTables Queue at the beginning") parser.add_option("-c", "--cleanup-queue", dest="cleanup_queue", action="store_true", default=False, help="Stop IPTables Queue at the cleanup") options = get_arguments() if (options.start_queue): start_queue(options.queue_num) try: run_netfilter(options.queue_num) except KeyboardInterrupt: print("\n[-] Detected CTRL+C... Quitting!!!") except Exception as e: print("\n[-] An exception occurred:\n\t" + str(e)) exit_code = 1 finally: if (options.cleanup_queue): cleanup_queue(options.queue_num) exit(exit_code)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 850, 14681, 198, 11748, 2010, 24455, 36560, 198, 11748, 25064, 198, 11748, 2172, 29572, 198, 198, 7206, 38865, 62, 48, 8924, 8924, 62, 41359, 796, 657, 198, 37023, 62, 8189, ...
2.764706
357
#!/usr/bin/env python3 from app.lib.utils.request import request from app.lib.utils.common import get_useragent if __name__ == "__main__": CVE_2019_2618 = CVE_2019_2618_BaseVerify('http://127.0.0.1:7001') print(CVE_2019_2618.check())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 598, 13, 8019, 13, 26791, 13, 25927, 1330, 2581, 198, 6738, 598, 13, 8019, 13, 26791, 13, 11321, 1330, 651, 62, 7220, 25781, 198, 198, 361, 220, 11593, 3672, 834, 6624...
2.47
100
# Copyright 2021 Prayas Energy Group(https://www.prayaspune.org/peg/) # # 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 pandas as pd from rumi.processing import demand from rumi.io import loaders from rumi.io import demand as demandio import pytest
[ 2, 15069, 33448, 1736, 323, 292, 6682, 4912, 7, 5450, 1378, 2503, 13, 1050, 323, 5126, 1726, 13, 2398, 14, 22071, 34729, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, ...
3.615023
213
#!/usr/bin/env python # test_errors.py - unit test for psycopg2.errors module # # Copyright (C) 2018-2019 Daniele Varrazzo <daniele.varrazzo@gmail.com> # # psycopg2 is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # In addition, as a special exception, the copyright holders give # permission to link this program with the OpenSSL library (or with # modified versions of OpenSSL that use the same license as OpenSSL), # and distribute linked combinations including the two. # # You must obey the GNU Lesser General Public License in all respects for # all of the code used other than OpenSSL. # # psycopg2 is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. import unittest from .testutils import ConnectingTestCase import psycopg2 from psycopg2 import errors from psycopg2._psycopg import sqlstate_errors from psycopg2.errors import UndefinedTable if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 1332, 62, 48277, 13, 9078, 532, 4326, 1332, 329, 17331, 22163, 70, 17, 13, 48277, 8265, 198, 2, 198, 2, 15069, 357, 34, 8, 2864, 12, 23344, 6035, 494, 293, 12372, 430, 4780...
3.582633
357
#!/usr/bin/env python # Copyright (c) 2012 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. """google_api's auto-internal gyp integration. Takes one argument, a path. Prints 1 if the path exists, 0 if not. """ from __future__ import print_function import os import sys if __name__ == '__main__': if os.path.exists(sys.argv[1]): print(1) else: print(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 66, 8, 2321, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, ...
2.937107
159
# Generated from TacticNotations.g by ANTLR 4.7 from antlr4 import * if __name__ is not None and "." in __name__: from .TacticNotationsParser import TacticNotationsParser else: from TacticNotationsParser import TacticNotationsParser # This class defines a complete generic visitor for a parse tree produced by TacticNotationsParser. # Visit a parse tree produced by TacticNotationsParser#top. # Visit a parse tree produced by TacticNotationsParser#blocks. # Visit a parse tree produced by TacticNotationsParser#block. # Visit a parse tree produced by TacticNotationsParser#repeat. # Visit a parse tree produced by TacticNotationsParser#curlies. # Visit a parse tree produced by TacticNotationsParser#whitespace. # Visit a parse tree produced by TacticNotationsParser#meta. # Visit a parse tree produced by TacticNotationsParser#atomic. # Visit a parse tree produced by TacticNotationsParser#hole. del TacticNotationsParser
[ 2, 2980, 515, 422, 309, 12009, 3673, 602, 13, 70, 416, 3537, 14990, 49, 604, 13, 22, 198, 6738, 1885, 14050, 19, 1330, 1635, 198, 361, 11593, 3672, 834, 318, 407, 6045, 290, 366, 526, 287, 11593, 3672, 834, 25, 198, 220, 220, 220,...
3.395189
291
# -*- coding: utf-8 -*- from collections import Counter if __name__ == '__main__': solution = Solution() assert solution.areOccurrencesEqual('abcabc') assert not solution.areOccurrencesEqual('aaabb')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 17268, 1330, 15034, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 4610, 796, 28186, 3419, 628, 220, 220, 220, ...
2.855263
76
from common import * import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from matplotlib.lines import Line2D import matplotlib.ticker as ticker import os from matplotlib import container from common import * from collections import OrderedDict from matplotlib.markers import MarkerStyle from matplotlib.ticker import FormatStrFormatter from matplotlib.ticker import FuncFormatter import traceback ################################################# ################################################# print("Plotting VSDROPPED") traces = ["Campus", "Campus_4" ] labels = ["Campus", "Campus #4"] styles= ['-', ':'] for i,trace in enumerate(traces): count = pandaload("iter-count-nodiff/%sCOUNT.csv" % trace) print("Number of packet in %s : %d" % (trace, np.nanmedian(count))) cbytes = pandaload("iter-count-nodiff/%sBYTES.csv" % trace) print("Number of bytes in %s : %d" % (trace, np.nanmedian(cbytes))) print("Average packet size in %s : %f" % (trace, float(np.nanmedian(cbytes)) / np.nanmedian(count))) count = pandaload("iter-count-nodiff/%sTX.csv" % trace) print("TX in %s : %d" % (trace, np.nanmedian(count))) count = pandaload("iter-count-nodiff/%sCOUNTN.csv" % trace) print("Number of flows in %s : %d" % (trace, np.nanmedian(count[-1,1]))) print("") try: start = 4 plt.rcParams["figure.figsize"] = (6,3) fig, ax1 = plt.subplots() for i,trace in enumerate(traces): nflows = pandaload("iter-count-diff/%sNFLOWS.csv" % trace) print("Average number of active flows : ", np.mean(nflows[10:60,1])) ax1.plot(nflows[:,0] - start,nflows[:,1]/1000, label=labels[i]) #marker=markers[si] #facecolors=[scolor,'none'][i]) ax1.legend(loc="lower right", bbox_to_anchor=(0.5,1.02), ncol=2, title="Active flows") ax2 = ax1.twinx() for i,trace in enumerate(traces): newflows = pandaload("iter-count-diff/%sNEWFLOWS.csv" % trace) print("Average number of new flows : ", np.mean(newflows[10:60,1])) # ax1.scatter(x, y, label=label, color=scolor, marker=markers[si]) #facecolors=[scolor,'none'][i]) ax2.plot(newflows[:,0] - start,newflows[:,1]/1000, label=labels[i], linestyle=':') #marker=markers[si] #facecolors=[scolor,'none'][i]) ax2.legend(loc="lower left", bbox_to_anchor=(0.5,1.02), ncol=2,title="New flows") ax1.set_xlim(0,60) #ax1.set_yscale("symlog") ax1.set_ylim(0,100) ax2.set_ylim(0,100) # ax1.set_xlabel('Time (s)') ax1.set_ylabel('Number of active flows X1000') ax2.set_ylabel('Number of new flows X1000') #plt.grid(True,axis="y") #ax1.yaxis.set_major_formatter(FormatStrFormatter('%d')) # plt.tight_layout() plt.subplots_adjust(top=0.8) plt.savefig('count-nflows.pdf') # print("Figure saved to loadvsdrop.pdf") except Exception as e: print("Could not plot:") traceback.print_exc() plt.clf() print("Plotting histogram") try: plt.rcParams["figure.figsize"] = (6,3) plt.rcParams['axes.axisbelow'] = True fig, ax1 = plt.subplots() plt.grid(True,axis="y") sz=64 for i,trace in enumerate(traces): nflows = pandaload("iter-count-nodiff/%sLENGTHT.csv" % trace) mi = 64 ma = np.max(nflows[:,0] + 4) bins = np.arange((ma-mi) / sz) vals = [] binsx = [] for j in bins: x = mi + (j * sz) vals.append(np.sum(nflows[(nflows[:,0] >= x-4) & (nflows[:,0] < x - 4 + sz),1])) binsx.append(x) #print("%d-%d -> %d" % (x,x+sz,vals[-1])) ax1.bar(np.array(binsx) + (i - 0.5) * (sz/2), np.array(vals) / 1000000, label=labels[i], width=(sz*0.8)/len(traces), align="center") #marker=markers[si] #facecolors=[scolor,'none'][i]) ax1.legend(loc="lower center", bbox_to_anchor=(0.5,1.02), ncol=2, title="Trace") binsx.append(ma) ax1.set_xticks(np.array(binsx) -( sz /2)) ax1.set_xticklabels([("%d" %x) if i%2==0 else "" for i,x in enumerate(binsx)]) ax1.set_yscale("symlog") ax1.set_yticks([0,1,2,4,8,16,32,64]) #ax1.set_ylim(0,100) ax1.set_xlabel('Packet size (bytes)') ax1.set_ylabel('Number of packets (M)') ax1.yaxis.set_major_formatter(FormatStrFormatter('%d')) plt.tight_layout() #plt.subplots_adjust(top=0.8) plt.savefig('length-hist.pdf') print("Figure saved to length-hist.pdf") except Exception as e: print("Could not plot:") traceback.print_exc() plt.clf() print("Plotting histogram of flow duration") try: plt.rcParams["figure.figsize"] = (6,3) plt.rcParams['axes.axisbelow'] = True fig, ax1 = plt.subplots() plt.grid(True,axis="y") sz=64 for i,trace in enumerate(traces): val = pandaload("iter-count-nodiff/%sCOUNTN.csv" % trace) freq= [0] freq.extend(val[:,1][:-1]) freq=val[:,1] - freq # print(val[:,0],freq) fake = np.repeat(val[:,0], [int(f) for f in freq]) tot = np.sum(val[:,0] * freq) print("Average flow size for trace %s : %d %d %d" % (trace, tot / np.sum(freq), np.mean(fake),np.median(fake))) cdf = pandaload("iter-count-nodiff/%sCOUNTCDF.csv" % trace) p = ax1.plot(cdf[:,0], cdf[:,1], label=labels[i], ls=styles[i]) #marker=markers[si] #facecolors=[scolor,'none'][i]) plt.annotate("100%% = %d flows" % val[np.argmax(val[:,0]),1],xy= (np.max(val[:,0]),cdf[np.argmax(val[:,0]),1]), xytext=(0.9,0.8 - i*0.11), textcoords="axes fraction",color=p[0].get_color(), horizontalalignment="right") ax1.legend(loc="lower center", bbox_to_anchor=(0.5,1.02), ncol=2, title="Trace") ax1.set_xscale("symlog") ax1.set_xlim(1) #ax1.set_yscale("symlog") #ax1.set_yticks([0,1,2,4,8,16,32,64]) #ax1.set_ylim(0,100) ax1.set_ylabel('Fraction of flows') ax1.set_xlabel('Number of packets in flows') ax1.yaxis.set_major_formatter(FormatStrFormatter('%d%%')) ax1.xaxis.set_major_formatter(FuncFormatter(lambda x,pos : "%d" % int(x) if int(x) < 1000 else "%dK" % (int(x)/1000))) plt.tight_layout() #plt.subplots_adjust(top=0.8) plt.savefig('count-hist.pdf') print("Figure saved to count-hist.pdf") except Exception as e: print("Could not plot:") traceback.print_exc()
[ 6738, 2219, 1330, 1635, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, ...
2.170007
2,894
''' A&B.png .intersection() The .intersection() operator returns the intersection of a set and the set of elements in an iterable. Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set. The set is immutable to the .intersection() operation (or & operation). >>> s = set("Hacker") >>> print s.intersection("Rank") set(['a', 'k']) >>> print s.intersection(set(['R', 'a', 'n', 'k'])) set(['a', 'k']) >>> print s.intersection(['R', 'a', 'n', 'k']) set(['a', 'k']) >>> print s.intersection(enumerate(['R', 'a', 'n', 'k'])) set([]) >>> print s.intersection({"Rank":1}) set([]) >>> s & set("Rank") set(['a', 'k']) Task The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to both newspapers. Input Format The first line contains , the number of students who have subscribed to the English newspaper. The second line contains space separated roll numbers of those students. The third line contains , the number of students who have subscribed to the French newspaper. The fourth line contains space separated roll numbers of those students. Output Format Output the total number of students who have subscriptions to both English and French newspapers. Sample Input 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output 5 Explanation The roll numbers of students who have both subscriptions: 1,2,3,6 and 8. Hence, the total is 5 students. ''' number_of_eng = int(input()) eng_subs = set(input().split()) number_of_fren = int(input()) fren_subs = set(input().split()) s = eng_subs.intersection(fren_subs) print(len(s))
[ 7061, 6, 198, 32, 5, 33, 13, 11134, 220, 198, 13, 3849, 5458, 3419, 198, 464, 764, 3849, 5458, 3419, 10088, 5860, 262, 16246, 286, 257, 900, 290, 262, 900, 286, 4847, 287, 281, 11629, 540, 13, 198, 15468, 11, 262, 1222, 10088, 318...
3.482394
568
import matplotlib.pyplot as plt import numpy as np from fuzzysets import utils from fuzzysets.sets.base import FuzzySet from fuzzysets.sets.continuous import ContinuousFuzzySet from fuzzysets.sets.finite import FiniteFuzzySet from fuzzysets.tfn import TriangularFuzzyNumber as TFN _X_LIMITS = (0., 10.) _Y_LABEL = "μ(x)" def plot_tfn_operations(first_name="A", second_name="B", x_lim=_X_LIMITS): """ Reads two TFNs as input and plots the results of their addition, subtraction, multiplication and division. :param first_name: a str - the name for the first TFN. Defaults to 'A'. :param second_name: a str - the name for the second TFN. Defaults to 'B'. :param x_lim: a pair of floats - the limits on the x axis of the plot. Defaults to X_LIMITS. """ lhs, rhs = _read_numbers(x_lim, first_name, second_name) if (lhs is not None and rhs is not None): figure, ((ax_add, ax_sub), (ax_mul, ax_div)) = \ plt.subplots(2, 2) _set_up_and_plot_on(ax_add, lhs + rhs, f"{first_name} + {second_name}") _set_up_and_plot_on(ax_sub, lhs - rhs, f"{first_name} - {second_name}") _set_up_and_plot_on(ax_mul, lhs * rhs, f"{first_name} * {second_name}") _set_up_and_plot_on(ax_div, lhs / rhs, f"{first_name} / {second_name}") plt.show() def plot_tfn(tfn, name="A"): """ :param tfn: an instance of TriangularFuzzyNumber. :param name: a str - the name of the TFN. Defaults to 'A'. """ _, axes = plt.subplots() _set_up_and_plot_on(axes, tfn, name) def plot_fuzzy_set_operations(a, b, a_name="A", b_name="B", t_norm=min, s_norm=max, comp=utils.complement): """ Plots the complements, t-norm and s-norm of two fuzzy sets of the same type. :param a: a FuzzySet. :param b: a FuzzySet whose type is the same as `a`'s. :param a_name: a str - the name of the first set. Defaults to 'A'. :param b_name: a str - the name of the second set. Defaults to 'B'. :param t_norm: a callable to use for t-norm, see `t_norm`. Defaults to min. :param s_norm: a callable to use for s-norm, see `s_norm`. Defaults to max. :param comp: a callable to use for complement, see `complement`. Defaults to `1 - x`. """ if (isinstance(a, FuzzySet) and type(a) == type(b) and a.domain == b.domain): intersection = a.t_norm(b, t_norm) union = a.s_norm(b, s_norm) a_complement = a.complement(comp) b_complement = b.complement(comp) _, ((ax_a, ax_b), (ax_t_norm, ax_s_norm)) = \ plt.subplots(2, 2) _set_up_and_plot_complement_on(ax_a, a, a_complement, a_name) _set_up_and_plot_complement_on(ax_b, b, b_complement, b_name) _set_up_and_plot_norm_on(ax_t_norm, a, b, intersection, a_name, b_name, norm_name="t") _set_up_and_plot_norm_on(ax_s_norm, a, b, union, a_name, b_name, norm_name="s") plt.show() def plot_fuzzy_set(s, title="", x_label="x", y_label=_Y_LABEL): """ :param s: an instance of FuzzySet. :param title: an optional str - the title of the plot. :param x_label: a str - the label for the x axis of the plot. Defaults to 'x'. :param y_label: a str - the label for the y axis of the plot. Defaults to Y_LABEL. """ if (isinstance(s, FuzzySet)): _, axes = plt.subplots() xs = np.array(list(s.domain)) ys = np.array(list(s.range)) _set_up(axes, x_lim=_x_limits_for(xs, s), title=title, x_label=x_label, y_label=y_label) _plot_on(axes, xs, ys, connect=isinstance(s, ContinuousFuzzySet)) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 26080, 893, 1039, 1330, 3384, 4487, 198, 6738, 26080, 893, 1039, 13, 28709, 13, 8692, 1330, 376, 4715, 88, 7248, 198, 6738, 2...
1.756746
2,631
import tensorflow as tf from evaluation.unsupervised_metrics.disentangle_api import unsupervised_metrics from utils.data_and_files.file_utils import log
[ 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 12660, 13, 403, 16668, 16149, 62, 4164, 10466, 13, 6381, 298, 9248, 62, 15042, 1330, 555, 16668, 16149, 62, 4164, 10466, 198, 6738, 3384, 4487, 13, 7890, 62, 392, 62, 16624, 1...
3.25
48
import pytest from top_secret import CastError from top_secret.cast_handlers import bool_cast_handler
[ 11748, 12972, 9288, 198, 198, 6738, 1353, 62, 21078, 1330, 5833, 12331, 198, 6738, 1353, 62, 21078, 13, 2701, 62, 4993, 8116, 1330, 20512, 62, 2701, 62, 30281, 628, 198 ]
3.5
30
from django import forms from .models import Kura,Post,Comment
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 764, 27530, 1330, 509, 5330, 11, 6307, 11, 21357 ]
3.875
16
"""Plot contours of first stage unvaiable mass vs recovery hardware factor and recovery propellant factor.""" import os.path from collections import namedtuple import numpy as np from matplotlib import pyplot as plt from lvreuse.performance.unavail_mass import unavail_mass fontsize = 15 if __name__ == '__main__': main()
[ 37811, 43328, 542, 4662, 286, 717, 3800, 555, 85, 1872, 540, 2347, 3691, 7628, 6890, 5766, 290, 7628, 46059, 415, 5766, 526, 15931, 198, 198, 11748, 28686, 13, 6978, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 11748, 299, 32152, ...
3.316832
101
print('版本1.0终于完成了!!!')
[ 4798, 10786, 48304, 17312, 105, 16, 13, 15, 163, 119, 230, 12859, 236, 22522, 234, 22755, 238, 12859, 228, 10185, 11537, 198 ]
1.045455
22
# -*- coding: utf-8 -*- ''' salt.serializers.python ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 2016.3.0 Implements a Python serializer (via pprint.format) ''' from __future__ import absolute_import, unicode_literals import pprint try: import simplejson as _json except ImportError: import json as _json # pylint: disable=blacklisted-import import salt.utils.json __all__ = ['serialize', 'available'] available = True def serialize(obj, **options): ''' Serialize Python data to a Python string representation (via pprint.format) :param obj: the data structure to serialize :param options: options given to pprint.format ''' #round-trip this through JSON to avoid OrderedDict types # there's probably a more performant way to do this... # TODO remove json round-trip when all dataset will use # serializers return pprint.pformat( salt.utils.json.loads( salt.utils.json.dumps(obj, _json_module=_json), _json_module=_json ), **options )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 220, 220, 220, 8268, 13, 46911, 11341, 13, 29412, 198, 220, 220, 220, 220, 27156, 15116, 4907, 93, 628, 220, 220, 220, 11485, 2196, 29373, 3712, 1584, 13...
2.74677
387
""" rkQuery is a library for programmatically building Riak search queries. It aims to be easy to use, powerful, and protect from injection attacks that would be possible with simple string interpolation. Just start playing around with the ``Q`` object: >>> from rkquery import Q >>> Q("some literal") <Q: "some literal"> >>> Q(field="literal value") <Q: field:"literal value"> >>> Q.not_(blocked="yes") <Q: NOT blocked:yes> You can provide multiple arguments, too. The default query combinator is `AND`: >>> Q("word1", "word2") <Q: word1 AND word2> >>> Q(username='foo', password='s3cr3t') <Q: password:s3cr3t AND username:foo> This is just a synonym for `Q.all()`: >>> Q.all("word1", "word2") <Q: word1 AND word2> >>> Q.all(username='foo', password='s3cr3t') <Q: password:s3cr3t AND username:foo> Of course you can construct `OR` queries, using `Q.any()`: >>> Q.any("word1", "word2") <Q: word1 OR word2> >>> Q.any(username='foo', email='foo@example.com') <Q: email:"foo@example.com" OR username:foo> >>> Q(field=Q.any("string1", "string2")) <Q: field:(string1 OR string2)> Or by combining existing `Q` objects: >>> Q.any("word1", "word2") & Q("word3") <Q: (word1 OR word2) AND word3> >>> Q("word3") | Q.all("word1", "word2") <Q: (word1 AND word2) OR word3> >>> Q.any(email="foo@example.com", username="foo") & Q(password="s3cr3t") <Q: (email:"foo@example.com" OR username:foo) AND password:s3cr3t> There are helpers for negation as well (note that 'none' means 'not any'): >>> Q.none(blocked="yes", cheque_bounced="yes") <Q: NOT (blocked:yes OR cheque_bounced:yes)> >>> ~Q.any(blocked="yes", cheque_bounced="yes") <Q: NOT (blocked:yes OR cheque_bounced:yes)> You can do range queries with `Q.range()`: >>> Q.range("red", "rum") <Q: [red TO rum]> >>> Q(field=Q.range("red", "rum")) <Q: field:[red TO rum]> Note that the default is an *inclusive* range (square brackets). The full set of range queries: >>> Q.range_inclusive("red", "rum") <Q: [red TO rum]> >>> Q.range_exclusive("red", "rum") <Q: {red TO rum}> >>> Q.between("red", "rum") <Q: {red TO rum}> Term boosting is a simple unary operation: >>> Q("red").boost(5) <Q: red^5> As is proximity: >>> Q("See spot run").proximity(20) <Q: "See spot run"~20> """ import itertools as it import re class Query(object): """ A Riak query. This object represents a Riak query. You can add more constraints using the various methods and operators defined on this class. To get your generated query, just use ``unicode()``: >>> unicode(Q(field1="foo", field2="bar")) u'field1:foo AND field2:bar' """ __slots__ = ('root', '__weakref__') def boost(self, factor): """Set the result importance factor of this term.""" return Query(Boost(self.root, factor)) def proximity(self, proximity): """Set a proximity for this term.""" return Query(Proximity(self.root, proximity)) class QueryNode(object): """Query node base class.""" __slots__ = () # Is it safe to display this node without parentheses as part of a complex # query? no_parens = False def sort_key(self): """Return a tuple by which this node may be sorted.""" return (unicode(self),) def parens(self): """Return a unicode representation, in parentheses.""" if self.no_parens: return unicode(self) return u'(%s)' % unicode(self) def Q(*args, **kwargs): """ Build Riak search queries safely and easily. This is the primary point of interaction with this library. For examples of how to use it, consult the docstring on the ``rkquery`` module. """ return q_all(*args, **kwargs) q_any = combinator('q_any', Any) q_all = combinator('q_all', All) Q.all = q_all Q.any = q_any Q.none = q_none Q.not_ = q_not Q.range = q_inclusive_range Q.range_inclusive = q_inclusive_range Q.range_exclusive = q_exclusive_range Q.between = q_exclusive_range
[ 37811, 198, 81, 74, 20746, 318, 257, 5888, 329, 1430, 49454, 2615, 30385, 461, 2989, 20743, 13, 632, 12031, 198, 1462, 307, 2562, 284, 779, 11, 3665, 11, 290, 1805, 422, 16954, 3434, 326, 561, 307, 198, 79, 4733, 351, 2829, 4731, 39...
2.569839
1,618
import numpy as np import torch from sklearn.metrics import accuracy_score from sklearn.metrics import roc_curve from sklearn.metrics import confusion_matrix class Classifier: ''' An extension to the original Deep SVDD to enable classification of test cases. optim_thresh(): get the threshold at which your metric is maximized classifier(): get y_pred based on optimum threshold wrong_answers(): get the list of test examples the classifier() wrongly classified in order to optimize the metric '''
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 9922, 62, 26675, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 686, 66, 62, 22019, 303, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 108...
3.73913
138
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import common_pb2 as common__pb2
[ 2, 2980, 515, 416, 262, 308, 49, 5662, 11361, 8435, 17050, 13877, 13, 8410, 5626, 48483, 0, 198, 11748, 1036, 14751, 198, 198, 11748, 2219, 62, 40842, 17, 355, 2219, 834, 40842, 17, 628, 628 ]
3.4
35
from django import template register = template.Library() @register.simple_tag
[ 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 628, 198, 31, 30238, 13, 36439, 62, 12985, 198 ]
3.727273
22
from django.conf import settings from django.contrib.admin.decorators import register from django.utils.module_loading import autodiscover_modules from elasticsearch import Elasticsearch __author__ = 'guillaume' # cache es_instance es_instance = getattr(settings, 'ES_CLIENT', Elasticsearch()) # This import need to be placed after for avoiding circular dependencies from .mappings import IndexMapping, mapping, ModelIndex __all__ = [ "register", "ModelIndex", "IndexMapping", "mapping", "autodiscover", ] default_app_config = 'django_es.apps.DjangoESConfig'
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 28482, 13, 12501, 273, 2024, 1330, 7881, 198, 6738, 42625, 14208, 13, 26791, 13, 21412, 62, 25138, 1330, 1960, 375, 29392, 62, 18170, 198, 6738, 2746...
3.39881
168
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) jobs = [0] * n for i in range(n): jobs[i] = tuple(map(int, input().split())) jobs = sorted(jobs, key=lambda x: x[1]) _sum = 0 for j in jobs: _sum += j[0] if _sum > j[1]: print('No') sys.exit(0) print('Yes')
[ 11748, 25064, 198, 15414, 796, 25064, 13, 19282, 259, 13, 961, 1370, 198, 17597, 13, 2617, 8344, 24197, 32374, 7, 940, 12429, 767, 8, 198, 198, 77, 796, 493, 7, 15414, 28955, 198, 43863, 796, 685, 15, 60, 1635, 299, 198, 1640, 1312,...
2.146667
150
#Usage: python Gquadruplex_cgcc.py <fasta> <windowsize> <output> <class> <region> import re import sys from Bio import SeqIO import numpy as np scores, medianscores, maxscores = iteratefasta(sys.argv[1], sys.argv[2]) with open(sys.argv[3], 'a') as outfile: ''' for score in scores: cGcCscore, binnumber = score[0], score[1] outfile.write(str(cGcCscore) + '\t' + str(binnumber) + '\t' + sys.argv[4] + '\t' + sys.argv[5] + '\n') ''' outfile.write(('\t').join(['Gene', 'medianscore', 'maxscore']) + '\n') for record in medianscores: outfile.write(('\t').join([record, str(medianscores[record]), str(maxscores[record])]) + '\n')
[ 2, 28350, 25, 21015, 402, 47003, 622, 11141, 62, 66, 70, 535, 13, 9078, 1279, 7217, 64, 29, 1279, 28457, 1096, 29, 1279, 22915, 29, 1279, 4871, 29, 1279, 36996, 29, 198, 198, 11748, 302, 198, 11748, 25064, 198, 6738, 16024, 1330, 10...
2.290323
279
import datetime import time import requests import json import xundaili from lxml import etree class VariFlightSpider(object): ''' 获得所有的航班列表 :return: list 访问的航班url列表 ''' ''' 爬取航班页面,用xpath找到下一个需要跳转的页面 //a[@class="searchlist_innerli"]/@href /schedule/HRB-HGH-3U2014.html?AE71649A58c77= @param flight_url :传入的航班url : http://www.variflight.com/flight/fnum/3U2014.html?AE71649A58c77= ''' ''' 这个函数是为了获得那个需要的json的url @param next_url http://www.variflight.com/schedule/HRB-HGH-3U2014.html?AE71649A58c77= @param flight_url 作为访问的header里面的Referer是上一个跳转过来的url : http://www.variflight.com/flight/fnum/3U2014.html?AE71649A58c77= ''' ''' 把获得的时间标准化处理一下 ''' ''' 访问那个json_url 提取出我们所需要的数据 ''' if __name__ == "__main__": main()
[ 11748, 4818, 8079, 198, 11748, 640, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 2124, 917, 603, 72, 198, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 198, 4871, 15965, 43069, 41294, 7, 15252, 2599, 628, 220, 220, 220, 705, 7061, ...
1.457597
566
# Copyright (c) 2014 Red Hat, Inc. # 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 collections from keystoneauth1 import exceptions as ks_exc from oslo_log import log as logging from stevedore import driver from zun.common import consts from zun.common import exception import zun.conf from zun.scheduler.client import report from zun.scheduler import request_filter from zun.scheduler import utils CONF = zun.conf.CONF LOG = logging.getLogger(__name__) class SchedulerClient(object): """Client library for placing calls to the scheduler."""
[ 2, 15069, 357, 66, 8, 1946, 2297, 10983, 11, 3457, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220...
3.340361
332
import unittest import lattice_mc import random import numpy as np if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 47240, 501, 62, 23209, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198...
2.738095
42
import os import time import requests url = os.environ.get("PINGER") if url: if url.endswith("/"): url = url[:-1] while True: time.sleep(int(os.environ.get("PINGER_INTERVAL", 900))) requests.get("%s/api/v1/ping" % (url))
[ 11748, 28686, 198, 11748, 640, 198, 198, 11748, 7007, 198, 198, 6371, 796, 28686, 13, 268, 2268, 13, 1136, 7203, 47, 2751, 1137, 4943, 198, 361, 19016, 25, 198, 220, 220, 220, 611, 19016, 13, 437, 2032, 342, 7203, 30487, 2599, 198, ...
2.125
120
from __future__ import absolute_import from sentry.utils.strings import truncatechars, strip
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 1908, 563, 13, 26791, 13, 37336, 1330, 40122, 40340, 945, 11, 10283, 628, 198 ]
3.84
25
import random import os from art import logo, vs from game-data import data score = 0 start_game()
[ 11748, 4738, 198, 11748, 28686, 198, 6738, 1242, 1330, 11112, 11, 3691, 198, 6738, 983, 12, 7890, 1330, 1366, 198, 198, 26675, 796, 657, 628, 198, 9688, 62, 6057, 3419, 198 ]
3.290323
31
import json import unittest from osmtogeojson import osmtogeojson if __name__ == '__main__': unittest.main()
[ 11748, 33918, 198, 11748, 555, 715, 395, 198, 198, 6738, 267, 5796, 1462, 469, 13210, 1559, 1330, 267, 5796, 1462, 469, 13210, 1559, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395...
2.533333
45
pai = input("genótipo do pai: ") mae = input("genótipo da mãe: ") if pai="AA": print("dominante")
[ 49712, 796, 5128, 7203, 5235, 10205, 22504, 78, 466, 279, 1872, 25, 366, 8, 198, 2611, 68, 796, 5128, 7203, 5235, 10205, 22504, 78, 12379, 285, 26102, 68, 25, 366, 8, 198, 198, 361, 279, 1872, 2625, 3838, 1298, 198, 220, 220, 220, ...
2.081633
49
#!/usr/bin/python # -*- coding: utf-8 -*- # # Ansible module to manage Foreman hostgroup resources. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: foreman_hostgroup short_description: Manage Foreman Hostgroup using Foreman API v2 description: - Manage Foreman Hostgroup using Foreman API v2 options: architecture: description: Architecture name required: False default: None domain: description: Domain name required: False default: None environment: description: Environment name required: False default: None medium: description: Medium name required: False default: None name: description: Hostgroup name required: True operatingsystem: description: Operatingsystem name required: False default: None parameters: description: List of parameters and values required: false default: None partition_table: description: Partition table name required: False default: None pxe_loader: description: PXE Loader required: False default: None realm: description: Realm name required: false default: None root_pass: description: root password required: false default: None force_update: description: forces update of hostgroup, usefull when in need of password update required: false default: false smart_proxy: description: Smart Proxy name required: False default: None subnet: description: Subnet name required: False default: None state: description: Hostgroup state required: false default: present choices: ["present", "absent"] locations: List of locations the subnet should be assigned to required: false default: None organizations: List of organizations the subnet should be assigned to required: false default: None foreman_host: description: Hostname or IP address of Foreman system required: false default: 127.0.0.1 foreman_port: description: Port of Foreman API required: false default: 443 foreman_user: description: Username to be used to authenticate on Foreman required: true foreman_pass: description: Password to be used to authenticate user on Foreman required: true foreman_ssl: description: Enable SSL when connecting to Foreman API required: false default: true notes: - Requires the python-foreman package to be installed. See https://github.com/Nosmoht/python-foreman. version_added: "2.0" author: "Thomas Krahn (@nosmoht)" ''' EXAMPLES = ''' - name: Ensure Hostgroup foreman_hostgroup: name: MyHostgroup state: present architecture: x86_64 domain: MyDomain operatingsystem: MyOS subnet: MySubnet foreman_host: 127.0.0.1 foreman_port: 443 foreman_user: admin foreman_pass: secret ''' try: from foreman.foreman import * except ImportError: foremanclient_found = False else: foremanclient_found = True try: from ansible.module_utils.foreman_utils import * has_import_error = False except ImportError as e: has_import_error = True import_error_msg = str(e) def get_resource(module, resource_type, resource_func, resource_name, search_title=False): """ Look for a resource within Foreman Database. Return the resource if found or fail. If the Resource could not be found by name search by title. :param module: :param resource_type: :param resource_func: :param resource_name: :return: """ try: result = resource_func(data=dict(name=resource_name)) if not result and search_title: result = resource_func(data=dict(title=resource_name)) if not result: module.fail_json(msg='{0} {1} not found'.format(resource_type, resource_name)) except ForemanError as e: module.fail_json(msg='Error while getting {0}: {1}'.format(resource_type, e.message)) return result def split_parent(name): """ Split hostgroup name in parent part and name: >>> split_parent("a/b/c") ('c', 'a/b') """ if '/' in name: parent, name = name.rsplit('/', 1) else: return name, None return name, parent # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 28038, 856, 8265, 284, 6687, 4558, 805, 2583, 8094, 4133, 13, 198, 2, 198, 2, 770, 8265, 318, 1479, 3788, 25, ...
2.952182
1,673
""" Tests for source_transformer """ from ast import ClassDef from unittest import TestCase from unittest.mock import patch from cdd.pure_utils import PY_GTE_3_9 from cdd.tests.utils_for_tests import unittest_main class TestSourceTransformer(TestCase): """ Tests for source_transformer """ def test_to_code(self) -> None: """ Tests to_source in Python 3.9 and < 3.9 """ class_def = ClassDef( name="Classy", bases=tuple(), decorator_list=[], body=[], keywords=tuple(), identifier_name=None, expr=None, ) with patch("cdd.source_transformer.version_info", (3, 9, 0)): import cdd.source_transformer self.assertEqual( cdd.source_transformer.to_code(class_def).rstrip("\n"), "class Classy:", ) if PY_GTE_3_9 else self.assertRaises( AttributeError, lambda: cdd.source_transformer.to_code(class_def) ) with patch("cdd.source_transformer.version_info", (3, 8, 0)): import cdd.source_transformer self.assertEqual( "class Classy:" if PY_GTE_3_9 else cdd.source_transformer.to_code(class_def).rstrip("\n"), "class Classy:", ) unittest_main()
[ 37811, 198, 51, 3558, 329, 2723, 62, 7645, 16354, 198, 37811, 198, 198, 6738, 6468, 1330, 5016, 7469, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 6738, 269, 1860, 13, 374...
1.959212
711
import sqlite3 import json import datetime import pause import utils import math import socket import time from dateutil.parser import parse from multiprocessing.connection import Listener from selenium.webdriver import Firefox from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from apscheduler.schedulers.background import BackgroundScheduler init_config = json.loads(open('config.json', 'r').read()) scheduler = BackgroundScheduler() jobs = {} load_jobs() scheduler.start() while True: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('localhost', init_config['port'])) s.listen() conn, addr = s.accept() with conn: data = conn.recv(1024) if not data: continue msg = data.decode('ascii') if msg == 'close': scheduler.shutdown() exit() elif msg == 'update': remove_jobs() load_jobs() elif msg == 'dump': job_list = list(jobs.items()) job_list.sort(key=lambda job: job[1]['job'].next_run_time) for key, value in job_list: print('Job for item #' + key + ' scheduled to run at ' + str(value['job'].next_run_time) + ' | ' + str(value['listing']['name'] + ' | Max Bid: ' + str(value['listing']['max_bid'])))
[ 11748, 44161, 578, 18, 198, 11748, 33918, 198, 11748, 4818, 8079, 198, 11748, 14985, 198, 11748, 3384, 4487, 198, 11748, 10688, 198, 11748, 17802, 198, 11748, 640, 198, 6738, 3128, 22602, 13, 48610, 1330, 21136, 198, 6738, 18540, 305, 919...
2.331871
684
import requests from api.models import * from django.core.management import BaseCommand from api.utils.utilities import get_agency_type
[ 11748, 7007, 198, 6738, 40391, 13, 27530, 1330, 1635, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 7308, 21575, 198, 198, 6738, 40391, 13, 26791, 13, 315, 2410, 1330, 651, 62, 40955, 62, 4906, 628, 628 ]
3.783784
37
import unittest from django.conf import settings from django.test import TestCase, RequestFactory from django_cradmin import cradmin_testhelpers from model_mommy import mommy from devilry.devilry_account.models import PermissionGroup from devilry.devilry_admin.views.dashboard import overview
[ 11748, 555, 715, 395, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 11, 19390, 22810, 198, 6738, 42625, 14208, 62, 6098, 28482, 1330, 1067, 28482, 62, 9288, 16794, 364, 198, 6...
3.597561
82
#!/usr/bin/env python """ config_parse Configuration parser """ from __future__ import absolute_import import os import sys import configparser import core_scripts.other_tools.list_tools as nii_list_tools import core_scripts.other_tools.display as nii_display __author__ = "Xin Wang" __email__ = "wangxin@nii.ac.jp" __copyright__ = "Copyright 2020, Xin Wang" class ConfigParse: """ ConfigParse class to parse input configuration file """ def __init__(self, config_path): """ initialization """ # get configuration path self.m_config_path = None if os.path.isfile(config_path): self.m_config_path = config_path else: nii_display.f_die("Cannot find %s" % (config_path), 'error') # path configuration file self.m_config = self.f_parse() if self.m_config is None: nii_display.f_die("Fail to parse %s" % (config_path), 'error') # done return def f_parse(self): """ f_parse parse the configuration file """ if self.m_config_path is not None: tmp_config = configparser.ConfigParser() tmp_config.read(self.m_config_path) return tmp_config else: nii_display.f_print("No config file provided", 'error') return None def f_retrieve(self, keyword, section_name=None, config_type=None): """ f_retrieve(self, keyword, section_name=None, config_type=None) retrieve the keyword from config file Return: value: string, int, float Parameters: keyword: 'keyword' to be retrieved section: which section is this keyword in the config. None will search all the config sections and return the first config_type: which can be 'int', 'float', or None. None will return the value as a string """ tmp_value = None if section_name is None: # if section is not given, search all the sections for section_name in self.m_config.sections(): tmp_value = self.f_retrieve(keyword, section_name, \ config_type) if tmp_value is not None: break elif section_name in self.m_config.sections() or \ section_name == 'DEFAULT': tmp_sec = self.m_config[section_name] # search a specific section if config_type == 'int': tmp_value = tmp_sec.getint(keyword, fallback=None) elif config_type == 'float': tmp_value = tmp_sec.getfloat(keyword, fallback=None) elif config_type == 'bool': tmp_value = tmp_sec.getboolean(keyword, fallback=None) else: tmp_value = tmp_sec.get(keyword, fallback=None) else: nii_display.f_die("Unknown section %s" % (section_name)) return tmp_value
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 11250, 62, 29572, 198, 198, 38149, 30751, 198, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4566, 4...
2.107119
1,475
maps={} maps['닭갈비']=[] maps['닭갈비'].append(["고수닭갈비",{'lat':35.8430711,'lon':127.1279931}]) maps['닭갈비'].append(["춘천닭갈비",{'lat':35.8430713,'lon':127.1279933}]) maps['닭갈비'].append(["황제춘천닭갈비",{'lat':35.8430712,'lon':127.1279929}])
[ 31803, 34758, 92, 198, 31803, 17816, 46695, 255, 166, 108, 230, 167, 117, 226, 20520, 28, 21737, 198, 31803, 17816, 46695, 255, 166, 108, 230, 167, 117, 226, 6, 4083, 33295, 7, 14692, 166, 111, 254, 168, 230, 246, 46695, 255, 166, 1...
1.300578
173
# 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. """ This implements an in-memory cache. We use an LRU to maintain the size of the cache, this is simple and only tracks number of items in the cache. We're using a dictionary and moving items to the top of the dictionary when it's accessed. This relies on Python dictionaries being ordered. """ import io from opteryx.storage import BaseBufferCache
[ 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330, 257, 4866, 286, 262, 13789, 379, 198, 2,...
3.921397
229
# Benchmarking Suite # Copyright 2014-2017 Engineering Ingegneria Informatica S.p.A. # # 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. # # # Developed in the ARTIST EU project (www.artist-project.eu) and in the # CloudPerfect EU project (https://cloudperfect.eu/) import os from setuptools import setup, find_packages from setuptools.command.install import install # import the VERSION from the source code import sys sys.path.append(os.getcwd() + '/src/benchsuite') from cli import VERSION class CustomInstallCmd(install): """ Custom install command that before running the actual install command. Invoke the argparse-manpage to build the manpage from the argparse parser of the cli. """ setup( name='benchsuite.cli', version='.'.join(map(str, VERSION)), description='A command line interface for the Benchmarking Suite', long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), url='https://github.com/benchmarking-suite/benchsuite-cli', author='Gabriele Giammatteo', author_email='gabriele.giammatteo@eng.it', license='Apache', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Topic :: System :: Benchmark', 'Topic :: Utilities', 'Topic :: Software Development :: Testing', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3 :: Only', 'Environment :: Console', 'Operating System :: Unix' ], keywords='benchmarking cloud testing performance', packages=find_packages('src'), namespace_packages=['benchsuite'], package_dir={'': 'src'}, entry_points={ 'console_scripts': ['benchsuite=benchsuite.cli.command:main'], }, data_files = [('man/man1', ['benchsuite.1'])], setup_requires=['wheel', 'argparse-manpage @ git+https://github.com/gabrielegiammatteo/build_manpage.git'], install_requires=['prettytable', 'benchsuite.core', 'argcomplete', 'argparse-manpage @ git+https://github.com/gabrielegiammatteo/build_manpage.git'], cmdclass={'install': CustomInstallCmd}, )
[ 2, 25187, 4102, 278, 26264, 198, 2, 15069, 1946, 12, 5539, 14044, 554, 469, 70, 1008, 544, 45255, 1512, 64, 311, 13, 79, 13, 32, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 1...
2.831643
986
import pytest import otscrape as ot import time @pytest.mark.slow @pytest.mark.integration @pytest.mark.ot_mp @pytest.mark.slow @pytest.mark.integration @pytest.mark.ot_mp
[ 11748, 12972, 9288, 198, 198, 11748, 267, 912, 66, 13484, 355, 30972, 198, 11748, 640, 628, 628, 198, 31, 9078, 9288, 13, 4102, 13, 38246, 198, 31, 9078, 9288, 13, 4102, 13, 18908, 1358, 198, 31, 9078, 9288, 13, 4102, 13, 313, 62, ...
2.452055
73
from django.conf.urls import url from django.urls import path, include from apps.intro import views app_name = "intro" urlpatterns = [ url(r'^$', views.homepage, name='homepage'), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 198, 6738, 6725, 13, 600, 305, 1330, 5009, 628, 198, 1324, 62, 3672, 796, 366, 600, 305, 1, 198, 6371, 33279, 82,...
2.724638
69
import os import pandas import glob import json from src.utils import definitions import matplotlib.pyplot as plt from sklearn import metrics
[ 11748, 28686, 198, 11748, 19798, 292, 198, 11748, 15095, 198, 11748, 33918, 198, 6738, 12351, 13, 26791, 1330, 17336, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 1341, 35720, 1330, 20731, 628, 628, 628, 628, ...
3.619048
42
# auth: christian bitter # desc: in this tutorial we register key events and display some text accordingly # specifically, we are going to listen for the 4 arrow keys import pygame from pygame.locals import K_LEFT, K_RIGHT, K_DOWN, K_UP, QUIT if not pygame.font: print("Pygame - fonts not loaded") if not pygame.mixer: print("Pygame - audio not loaded") # init pygame - create the main window, and a background surface pygame.init() w, h, t = 640, 480, "Elisa 4 - key map and input handling" c_white = (250, 250, 250) c_blue = (0, 0, 255) screen_buffer = pygame.display.set_mode(size=(w, h)) pygame.display.set_caption(t) pygame.mouse.set_visible(True) back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size()) back_buffer = back_buffer.convert() back_buffer.fill(c_white) # FPS watcher fps_watcher = pygame.time.Clock() is_done = False # Display some text font = pygame.font.Font(None, 36) text = font.render("You pressed: <PLACEHOLDER>", 1, c_blue) key_map = pygame.key.get_pressed() pressed = False while not is_done: fps_watcher.tick(60) for event in pygame.event.get(): if event.type == QUIT: is_done = True else: pressed = event.type == pygame.KEYDOWN key_map = pygame.key.get_pressed() text_help = font.render("Press any of the arrow keys ...", 1, c_blue) text = font.render( "You pressed: {}".format(update_keytext(pressed, key_map)), 1, c_blue ) back_buffer.fill(c_white) back_buffer.blit(text_help, (100, 100)) back_buffer.blit(text, (100, 150)) screen_buffer.blit(back_buffer, (0, 0)) pygame.display.flip()
[ 2, 6284, 25, 33826, 666, 12922, 198, 2, 1715, 25, 287, 428, 11808, 356, 7881, 1994, 2995, 290, 3359, 617, 2420, 16062, 198, 2, 220, 220, 220, 220, 220, 220, 5734, 11, 356, 389, 1016, 284, 6004, 329, 262, 604, 15452, 8251, 198, 198...
2.530488
656
from enums import enum from fontlist import FontList from datetime import datetime __all_fonts__ = FontList.all() font_roles = enum(title=0, body=1, mono=2, cursive=3, inherit=-1) if __name__ == "__main__": import lipsum block_styles, inline_styles = default_styles() font_set = FontSet(FontFamily("DejaVu Sans"), FontFamily("DejaVu Serif"), FontFamily("Hack"), FontFamily("URW Chancery")) doc = Document(Block(Block(Span("Here is a Top-Level Heading", get_style(inline_styles, "Plain")), style=block_styles[0]), Span(lipsum.generate_paragraphs(1), get_style(inline_styles, "Plain")), Block(Span("Here is a Smaller Heading", get_style(inline_styles, "Plain")), style=block_styles[1]), Span(lipsum.generate_paragraphs(1), get_style(inline_styles, "Plain")), Block(Span("Here is an Even Smaller Heading", get_style(inline_styles, "Plain")), style=block_styles[2]), Span("This is a ", get_style(inline_styles, "Plain")), Span("test paragraph. ", get_style(inline_styles, "Forceful")), Span("This should be emphasized. ", get_style(inline_styles, "Emphatic")), style=get_style(block_styles, "Paragraph")), title="A Test Document", author="Jason R. Fruit") from format import Htmlinator h = Htmlinator(font_set) print(h.htmlinate(doc))
[ 6738, 551, 5700, 1330, 33829, 198, 6738, 10369, 4868, 1330, 24060, 8053, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 834, 439, 62, 10331, 82, 834, 796, 24060, 8053, 13, 439, 3419, 198, 198, 10331, 62, 305, 829, 796, 33829, 7, ...
1.700254
1,181
""" This module provides classes for testing RatingChange object """ import unittest from codeforces import RatingChange if __name__ == '__main__': unittest.main()
[ 37811, 198, 1212, 8265, 3769, 6097, 329, 4856, 12028, 19400, 2134, 198, 37811, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 14873, 891, 273, 728, 1330, 12028, 19400, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, ...
3.264151
53
# Copyright 1999-2021 Alibaba Group Holding 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 os import subprocess import weakref from urllib.parse import urlparse from typing import List, Dict, Union, Tuple, Iterator, BinaryIO, TextIO import pyarrow as pa from pyarrow.fs import ( FileSystem as ArrowFileSystem, LocalFileSystem as ArrowLocalFileSystem, HadoopFileSystem as ArrowHadoopFileSystem, FileSelector, FileInfo, FileType, ) from ...utils import implements, stringify_path from .core import FileSystem, path_type __all__ = ("ArrowBasedLocalFileSystem", "HadoopFileSystem") # When pyarrow.fs.FileSystem gc collected, # the underlying connection will be closed, # so we hold the reference to make sure # FileSystem will not be gc collected before file object _file_to_filesystems = weakref.WeakKeyDictionary() class ArrowBasedFileSystem(FileSystem): """ FileSystem implemented with arrow fs API (>=2.0.0). """ @staticmethod @implements(FileSystem.cat) @implements(FileSystem.ls) @implements(FileSystem.delete) @implements(FileSystem.rename) @implements(FileSystem.stat) @implements(FileSystem.mkdir) @implements(FileSystem.isdir) @implements(FileSystem.isfile) @implements(FileSystem._isfilestore) @implements(FileSystem.exists) @implements(FileSystem.open) @implements(FileSystem.walk) @implements(FileSystem.glob)
[ 2, 15069, 7358, 12, 1238, 2481, 41992, 4912, 31703, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, ...
3.106858
627
import os import cv2 import glob import torch import imageio import numpy as np import pandas as pd import seaborn as sn import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from scipy.io import wavfile from PIL import Image from losses.losses import *
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 15095, 198, 11748, 28034, 198, 11748, 2939, 952, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 198, 11748, 28034, 13, ...
3.237624
101
''' Link check_all script to a manage.py command ''' from django.core.management import BaseCommand from ._script import run_script class Command(BaseCommand): ''' Run general script for checking ''' help = "Run general script for checking"
[ 7061, 6, 198, 11280, 2198, 62, 439, 4226, 284, 257, 6687, 13, 9078, 3141, 198, 7061, 6, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 7308, 21575, 198, 6738, 47540, 12048, 1330, 1057, 62, 12048, 628, 198, 4871, 9455, 7, 1...
3.25
80
# Create a class called Article. The __init__ method should accept 3 arguments: title: str, content: str, and author: str. # The class should also have 4 methods: # • edit(new_content: str) - changes the old content to the new one # • change_author(new_author: str) - changes the old author with the new one # • rename(new_title: str) - changes the old title with the new one # • __repr__() - returns the following string "{title} - {content}: {author}" # Test code article = Article( "Highest Recorded Temperature", "Temperatures across Europe are unprecedented, according to scientists.", "Ben Turner" ) article.edit( "Syracuse, a city on the coast of the Italian island of Sicily, registered temperatures of 48.8 degrees Celsius" ) article.rename( "Temperature in Italy" ) article.change_author( "B. T." ) print(article)
[ 2, 13610, 257, 1398, 1444, 10172, 13, 383, 11593, 15003, 834, 2446, 815, 2453, 513, 7159, 25, 3670, 25, 965, 11, 2695, 25, 965, 11, 290, 1772, 25, 965, 13, 220, 198, 2, 383, 1398, 815, 635, 423, 604, 5050, 25, 198, 2, 5595, 197,...
3.289575
259
import os # import bag package import bag from bag.io import read_yaml #import scripts_dsn.diffamp_simple as diffamp # import BAG demo Python modules import xbase_demo.core as demo_core import xbase_demo.demo_layout.core as layout_core import bag_testbenches.scripts_dsn.CML as diffamp from bag_testbenches.verification.mos.query import MOSDBDiscrete # load circuit specifications from file #spec_fname = os.path.join(os.environ['BAG_WORK_DIR'], 'specs_demo/demo.yaml') #top_specs = read_yaml(spec_fname) # obtain BagProject instance local_dict = locals() #if 'bprj' in local_dict: if False: print('using existing BagProject') bprj = local_dict['bprj'] else: print('creating BagProject') bprj = bag.BagProject() #diffamp.run_main() diffamp.run_main(bprj)
[ 11748, 28686, 198, 198, 2, 1330, 6131, 5301, 198, 11748, 6131, 198, 6738, 6131, 13, 952, 1330, 1100, 62, 88, 43695, 198, 2, 11748, 14750, 62, 9310, 77, 13, 26069, 696, 62, 36439, 355, 814, 696, 198, 2, 1330, 347, 4760, 13605, 11361,...
2.713287
286
import sys import time import curses import pickle from collections import deque import copy from .arena import Arena, BlockEfir, BlockSnake, BlockFood, BlockBorder from . import settings, windows from .exeptions import *
[ 11748, 25064, 198, 11748, 640, 198, 11748, 43878, 198, 11748, 2298, 293, 198, 6738, 17268, 1330, 390, 4188, 198, 11748, 4866, 198, 198, 6738, 764, 533, 2616, 1330, 10937, 11, 9726, 36, 69, 343, 11, 9726, 49795, 11, 9726, 24602, 11, 97...
3.813559
59
import os from glob import glob from pathlib import Path from typing import Union, List import numpy as np from tensorflow.keras.utils import get_file from facegan import ROOT_PATH from facegan.ffhq.face_alignment import image_align from facegan.ffhq.landmarks_detector import LandmarksDetector from facegan.utils.utils import unpack_bz2
[ 11748, 28686, 198, 6738, 15095, 1330, 15095, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 4479, 11, 7343, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 26791, 1330, 651, 62, 775...
3.31068
103
from marshmallow import Schema, fields
[ 6738, 22397, 42725, 1330, 10011, 2611, 11, 7032, 628 ]
4.444444
9
# Task 08. Mutate Strings str_1 = input() str_2 = input() new_str = list(str_1) for ch in range(len(str_2)): if new_str[ch] == str_2[ch]: continue else: new_str[ch] = str_2[ch] print(''.join(new_str))
[ 2, 15941, 8487, 13, 13859, 378, 4285, 654, 198, 198, 2536, 62, 16, 796, 5128, 3419, 198, 2536, 62, 17, 796, 5128, 3419, 198, 198, 3605, 62, 2536, 796, 1351, 7, 2536, 62, 16, 8, 198, 198, 1640, 442, 287, 2837, 7, 11925, 7, 2536, ...
1.982906
117
import unittest from algorithm_collection.mathematics import iterative_logarithm
[ 11748, 555, 715, 395, 198, 6738, 11862, 62, 43681, 13, 6759, 10024, 873, 1330, 11629, 876, 62, 6404, 283, 342, 76, 628 ]
3.727273
22
# Copyright 2016 Battelle Energy Alliance, LLC # # 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. from __future__ import unicode_literals, absolute_import from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed import logging, traceback from ci.github.api import GitException from ci import models, PushEvent, PullRequestEvent, GitCommitData, ReleaseEvent import json logger = logging.getLogger('ci') def process_release(user, data): """ Called on the "release" webhook when a user does a GitHub release. A GitHub release is basically just a tag along with some other niceties like auto tarballing the source code for the tag. """ rel_event = ReleaseEvent.ReleaseEvent() rel_event.build_user = user release = data['release'] rel_event.release_tag = release['tag_name'] repo_data = data['repository'] rel_event.description = "Release: %s" % release['name'][:150] branch = release['target_commitish'] repo_name = repo_data['name'] owner = repo_data['owner']['login'] if len(branch) == 40: # We have an actual SHA but the branch information is not anywhere so we just assume the commit was on master tag_sha = branch branch = "master" else: # Doesn't look like a SHA so assume it is a branch and grab the SHA from the release tag api = user.api() tag_sha = api._tag_sha(owner, repo_name, rel_event.release_tag) if tag_sha is None: raise GitException("Couldn't find SHA for %s/%s:%s." % (owner, repo_name, rel_event.release_tag)) logger.info("Release '%s' on %s/%s:%s using commit %s" % (rel_event.release_tag, owner, repo_name, branch, tag_sha)) rel_event.commit = GitCommitData.GitCommitData( owner, repo_name, branch, tag_sha, repo_data['ssh_url'], user.server ) rel_event.full_text = data rel_event.save() @csrf_exempt
[ 198, 2, 15069, 1584, 12350, 13485, 6682, 10302, 11, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789...
2.883908
870
#!/usr/bin/env python # Copyright 2016-2020 Workiva Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # create_sns_topic.py # # Script that create an SNS Topic. # system imports import argparse import logging import sys # library imports # application imports from aws_lambda_fsm.constants import AWS from aws_lambda_fsm.aws import get_connection from aws_lambda_fsm.aws import get_arn_from_arn_string from aws_lambda_fsm.aws import validate_config import settings # setup the command line args parser = argparse.ArgumentParser(description='Creates AWS SNS topics.') parser.add_argument('--sns_topic_arn', default='PRIMARY_STREAM_SOURCE') parser.add_argument('--log_level', default='INFO') parser.add_argument('--boto_log_level', default='INFO') args = parser.parse_args() logging.basicConfig( format='[%(levelname)s] %(asctime)-15s %(message)s', level=int(args.log_level) if args.log_level.isdigit() else args.log_level, datefmt='%Y-%m-%d %H:%M:%S' ) logging.getLogger('boto3').setLevel(args.boto_log_level) logging.getLogger('botocore').setLevel(args.boto_log_level) validate_config() # setup connections to AWS sns_topic_arn = getattr(settings, args.sns_topic_arn) logging.info('SNS topic ARN: %s', sns_topic_arn) logging.info('SNS endpoint: %s', settings.ENDPOINTS.get(AWS.SNS)) if get_arn_from_arn_string(sns_topic_arn).service != AWS.SNS: logging.fatal("%s is not an SNS ARN", sns_topic_arn) sys.exit(1) sns_conn = get_connection(sns_topic_arn, disable_chaos=True) sns_topic = get_arn_from_arn_string(sns_topic_arn).resource logging.info('SNS topic: %s', sns_topic) # configure the topic response = sns_conn.create_topic( Name=sns_topic ) logging.info(response)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 1584, 12, 42334, 5521, 12151, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 7...
2.844072
776