text
string
size
int64
token_count
int64
import abc from typing import List, Tuple class WorkList: def __init__(self, items_to_complete: Tuple): self._progress_current_task = 0 self._items_to_complete = items_to_complete self._current_item_index = 0 self._training_rate = 0 self._generating_rate = 0 def get_ti...
1,769
542
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 25 09:56:15 2019 @author: yujijun Description: QC by FRiP >= 0.25 and filter out non-information tissues Input: 03-Homo_sapiens_ca_DNase_QC(906)_add_info_mannually.csv Output: 04-Homo_sapiens_ca_DNase_QC(906)_non-info-tissue_FRiP0p25(5...
2,547
1,127
import sys import json alifile = sys.argv[1] srcfile = sys.argv[2] tgtfile = sys.argv[3] outdir = sys.argv[4] src = sys.argv[5] tgt = sys.argv[6] mistakes = "summary."+src+"-"+tgt talk = srcfile.split('/')[1].split('.')[0] srcs = [] tgts = [] with open(srcfile,'r') as f: line = f.readline().strip() while ...
1,558
590
from ..schema.nexusphp import BakatestHR class MainClass(BakatestHR): URL = 'https://52pt.site/' USER_CLASSES = { 'downloaded': [2748779069440, 6047313952768], 'share_ratio': [3.05, 4.55], 'days': [280, 700] }
249
126
from django.core.exceptions import ValidationError from django.test import TestCase from app.accounts.models import User class UserModelTestCase(TestCase): def setUp(self): self.user = User.objects.create(first_name='James', last_name='Njenga', password='this!@#', email='jamesn...
2,095
737
from __future__ import annotations import json import pickle from types import TracebackType from typing import ( Any, Dict, Iterable, List, Literal, Optional, Sequence, Tuple, Type, Union, ) import grpc import grpc.aio from meadowgrid.config import ( DEFAULT_COORDINATOR_A...
29,754
8,722
from django.conf.urls import patterns, url from contact import views urlpatterns = patterns( '', url(r'^$', views.contact_form, name='contact_form'), )
162
52
""" @file @brief Direct calls to libraries :epkg:`BLAS` and :epkg:`LAPACK`. """ import numpy from scipy.linalg.blas import sgemm, dgemm # pylint: disable=E0611 from .direct_blas_lapack import ( # pylint: disable=E0401,E0611 dgemm_dot, sgemm_dot) def pygemm(transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C...
7,387
2,645
class Solution: """ first time: total time: time complexity:O(m+n) space complexity:O(m+n) idea:KMP算法。将needle字符串、"#"、haystack字符串连接组成新的字符串s,利用kmp算法记录下needle字符串的所有位置的前缀函数值,迭代s中haystack部分字符串,依次计算每个位置的前缀函数值,但不用记录下来,只需用一个临时变量记下上一个位置的前缀函数值即可,直到找到某个位置的前缀函数值为m,停止迭代,利用停止迭代的下标值可以计算出needle字符串第一次在haystack中...
1,037
544
# -*- coding:utf-8 -*- __author__ = 'Fangyang' import pandas as pd if __name__ == '__main__': df = pd.read_csv('30#RBL8.csv', '\t', encoding='gbk', skiprows=1) df.dropna(inplace=True) df.columns = [i.strip() for i in df.columns] df['时间'] = df['时间'].apply(lambda x: f' {int(x):04d}') df['datetime']...
942
412
""" A module for defining inventories of unstable nuclides """ import collections from .exceptions import UnphysicalValueException class UnstablesInventory(): """ A simple data structure to represent inventory data. A list of zais and activities (Bq). Note that this should only be us...
2,270
653
import kobra.core def main(): kobra.core.kobra() if __name__ == "__main__": main()
93
41
# Additional constants and definition of compressible reference state: Ra = Constant(1e5) # Rayleigh number Di = Constant(0.5) # Dissipation number T0 = Constant(0.091) # Non-dimensional surface temperature tcond = Constant(1.0) # Thermal conductivity rho_0, alpha, cpr, cvr, gruneisen = 1.0, 1.0, 1.0, 1.0, 1.0 rhobar =...
1,903
700
from typing import Optional from fastapi import FastAPI, Request, Response from fastapi.responses import JSONResponse from pydantic import BaseModel from bs4 import BeautifulSoup from datetime import datetime import hashlib import struct import logging import json_logging import urllib.parse import redis import httpx ...
3,229
1,093
def hash(astring, tablesize): sum = 0 for pos in range(len(astring)): sum = sum + ord(astring[pos]) return sum%tablesize
142
50
import synthtool as s import synthtool.gcp as gcp import logging import re logging.basicConfig(level=logging.DEBUG) gapic = gcp.GAPICGenerator() # Temporary until we get Ruby-specific tools into synthtool def merge_gemspec(src, dest, path): regex = re.compile(r'^\s+gem.version\s*=\s*"[\d\.]+"$', flags=re.MULTIL...
3,270
1,330
# Library Imports import nextcord, json from nextcord.ext import commands # Custom Imports from Functions.Embed import * # Options from Json with open('Config/Options.json') as RawOptions: Options = json.load(RawOptions) # onMessage Class class Tags(commands.Cog): def __init__(self, bot:commands.Bot): ...
1,341
377
#============================================================================== # These are some scripts for testing the functionality of LSDMappingTools #============================================================================== # -*- coding: utf-8 -*- """ Created on Mon May 22 14:08:16 2016 @author: smudd """ i...
1,469
485
# Third-Party Libraries import numpy as np import scipy.integrate as sci import matplotlib.pyplot as plt import matplotlib.animation as ani def solve(**kwargs): kwargs = kwargs.copy() kwargs["dense_output"] = True y0s = kwargs["y0s"] del kwargs["y0s"] results = [] for y0 in y0s: kwargs...
4,156
1,632
from warnings import warn from torch import einsum from torch.nn import BatchNorm2d import torch from backpack.core.derivatives.basederivatives import BaseParameterDerivatives class BatchNorm2dDerivatives(BaseParameterDerivatives): def get_module(self): return BatchNorm2d def hessian_is_zero(self): ...
1,962
664
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ self.longest...
1,527
557
import re def no_accent_vietnamese(s): s = re.sub(r'[àáạảãâầấậẩẫăằắặẳẵ]', 'a', s) s = re.sub(r'[ÀÁẠẢÃĂẰẮẶẲẴÂẦẤẬẨẪ]', 'A', s) s = re.sub(r'[èéẹẻẽêềếệểễ]', 'e', s) s = re.sub(r'[ÈÉẸẺẼÊỀẾỆỂỄ]', 'E', s) s = re.sub(r'[òóọỏõôồốộổỗơờớợởỡ]', 'o', s) s = re.sub(r'[ÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠ]', 'O', s) s = r...
607
541
from logging import INFO, getLogger, Formatter from logging.handlers import TimedRotatingFileHandler from gevent.wsgi import WSGIServer import os from octopus.app import create_app from octopus.settings import ProdConfig def main(): # Init the app app = create_app(ProdConfig) if not os.path.exists(os.path.dir...
1,362
452
# -- coding: utf-8 -- # 当前版本 VERSION = "0.0.1" DEBUG_SWITCH = True FACE_PATH = 'face/' # 你的adb安装目录 中间不能有空格 adb_path = "D:\\ClockworkMod\\Universal\\adb.exe" # 视频下载目录 需要先创建目录 没有新增创建方法 localVideoPath = 'E:/download' # 模拟器视频存放地址 # 我使用的逍遥模拟器,不同模拟器储存路径不一样,需要确认 address = '/storage/emulated/0/DCIM/Camera/' # 百度开放人脸识别API...
604
464
import json import pytest from django.utils.encoding import force_str from gore.tests.utils import create_events from gore.utils.event_grouper import group_events @pytest.mark.django_db def test_groups_api(project, admin_client): events = create_events(project, 10) group_events(project, events) list_res...
850
288
# -*- encoding: utf-8 -*- """ Copyright (c) 2021 - present SharpObjects """ from datetime import datetime from flask_login import UserMixin from sqlalchemy import Binary, Column, Integer, String, TIMESTAMP from app import db, login_manager from app.base.util import hash_pass class Recommendation(db.Model, UserMixin...
3,084
969
import dbgz from tqdm.auto import tqdm # Defining a scheme scheme = [ ("anInteger","i"), ("aFloat","f"), ("aString","s"), ("anIntArray","I"), ("aFloatArray","F"), ("anStringArray","S"), ] # Writing some data to a dbgz file totalCount = 1000000; with dbgz.DBGZWriter("test.dbgz",scheme) as fd: # New entr...
2,134
794
import pytest from graphql import GraphQLError from graphql.validation.rules import ValidationRule from ariadne import graphql, graphql_sync, subscribe class AlwaysInvalid(ValidationRule): def leave_operation_definition( # pylint: disable=unused-argument self, *args, **kwargs ): self.context...
2,994
903
from math import factorial as f a,b =map(int,input().split()) a-=1 b-=1 print((f(a+b) // (f(a) * f(b))) %1000000000)
116
63
import random import numpy as np from keras.models import Model from keras.applications.resnet50 import ResNet50 from keras.layers import Input, Conv2D, MaxPool2D, Flatten, Dense from keras.layers import BatchNormalization, Activation, Dropout def build_embedding(param, inp): network = eval(param["network_name"]) ...
2,298
865
import os import numpy as np # PyTorch import torch import torch.nn as nn import torch.nn.functional as F import importlib import itertools from trainers.base_trainer import BaseTrainer import toolbox.lr_scheduler import models.embeddings def KLD(mu, logvar): KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar...
11,068
4,006
#!/usr/bin/env python # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is under a BSD license, see LICENSE.TXT. import demo_setup demo_setup.sys_path() from jenkinsflow.flow import serial import demo_security as security def main(api): with serial(api, timeout=70, ...
1,355
458
from basetest import * import logging import StringIO import subprocess import sys from synchronizers.base.event_loop import XOSObserver from synchronizers.model_policy import run_policy_once from xos.config import set_override from xos.logger import Logger, observer_logger class BaseObserverToscaTest(BaseToscaTest)...
3,010
903
# coding=utf-8 import time import pub.response.error as error import pub.settings as s import pub.tables.resources as resource import pub.tables.template as template import pub.tables.comments as comments import pub.tables.user as user import pub.response.json as j from django.core.paginator import Paginator,EmptyPa...
11,763
3,766
# Copyright Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" ...
5,932
1,999
print('824','176','070', sep= '.', end= '-') print('18') print('ola', type('ola')) print(10, type(10)) print(10.5, type(10.5)) print(True, type(True)) nome = 'heder' idade = 22 altura = 1.72 print('\n') print(f'{nome} tem {idade} anos e {altura} de altura') print('{} tem {} anos e {} de altura'.format(nome,idade,altu...
325
147
# -*- coding: utf-8 -*- """ Created on Wed Jul 18 10:46:25 2012 @author: pietro """ import ctypes import re from collections import namedtuple import numpy as np import grass.lib.gis as libgis import grass.lib.vector as libvect from grass.pygrass.utils import decode from grass.pygrass.errors import GrassError, map...
65,211
22,179
# # @lc app=leetcode.cn id=86 lang=python3 # # [86] 分隔链表 # # https://leetcode-cn.com/problems/partition-list/description/ # # algorithms # Medium (60.30%) # Likes: 286 # Dislikes: 0 # Total Accepted: 61.5K # Total Submissions: 102K # Testcase Example: '[1,4,3,2,5,2]\n3' # # 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大...
1,144
528
# Generated by Django 2.1.3 on 2018-11-17 06:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterUniqueTogether( name='website', unique_together=set(), ), ...
325
114
import argparse import sys import traceback import textwrap import colorama from dbgr.requests import get_requests, execute_request, parse_cmd_arguments, parse_module_name from dbgr.environment import init_environment, get_environments, DEFAULT_ENVIRONMENT, Environment from dbgr.session import close_session from dbgr.c...
6,121
1,770
import json import subprocess import numpy as np import pandas as pd import matplotlib.pyplot as plt from shutil import copy from scipy import interpolate from statsmodels.tsa.seasonal import STL def import_datasets(datalist, vdfname): """ Creates Vensim script to convert CSVs to VDFs """ print("Importing da...
14,965
4,942
import sys import urllib.request, urllib.error, urllib from os import system, path import warnings import socket from time import time #resolve dependencies in general system("pip install pytube3") # test: https://www.youtube.com/watch?v=ZW0evffIxEM def validate(_url): try: conn = urllib....
15,992
4,766
import tensorflow as tf from tensorflow import keras import json import os import tempfile import numpy as np import base64 from rafiki.model import BaseModel, InvalidModelParamsException, validate_model_class, load_dataset from rafiki.constants import TaskType class TfSingleHiddenLayer(BaseModel): ''' Implem...
9,100
4,678
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020-2021 Alibaba Group Holding Limited. # # 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/LI...
3,140
1,162
from pl_bolts.models.gans.basic.basic_gan_module import GAN
60
23
import os from dodo_commands import Dodo from dodo_commands.framework.config import Paths def _args(): Dodo.parser.add_argument("--alt", help="Run an alternative git command") Dodo.parser.add_argument( "--message", "-m", dest="message", help="The commit message" ) args = Dodo.parse_args() ...
815
291
# Specific response models of the OPERANDI server will be implemented here # TODO: Implement proper response models
116
26
class Solution: def solve(self, heights): if len(heights) == 0: return [] unobstructedBuildings = [] for i in range(len(heights) - 1): taller = False for j in range(i + 1, len(heights)): if heights[j] >= heights[i]: ...
567
166
# coding=utf-8 # Copyright 2021 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
6,698
2,211
import argparse import numpy as np import torch import torch.nn as nn import wandb from tqdm import tqdm from utils import plot_points from dataset import make_loader from model import TripletNet def train(args): model_config = { "batch_size": args.batch_size, "epochs": args.epochs, ...
4,171
1,354
import json import logging import os import re import unicodedata from typing import Optional import torch from pytorch_lightning import LightningDataModule from torch import Tensor from torch.nn.utils.rnn import pad_sequence from torch.utils.data import Dataset, DataLoader from tqdm import trange from teach.logger i...
10,573
3,236
from pydocx.openxml import wordprocessing from pydocx.export import PyDocXHTMLExporter from pydocx.export.html import HtmlTag, is_only_whitespace, is_not_empty_and_not_only_whitespace from itertools import chain #https://pydocx.readthedocs.io/en/latest/extending.html BLOCK_ELEMENTS = ['document', 'body', 'head', 'h1...
8,551
2,745
# Copyright 2014 hm authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from hm import lb_managers, log, model from hm.model.host import Host class LoadBalancer(model.BaseModel): def __init__(self, id, name, address, conf=None, **kw...
2,704
843
from simplenlg import Lexicon from simplenlg import NLGFactory from simplenlg import Realiser words = ['Month', 'Infected'] correlation_value = -0.4444 lexicon = Lexicon.getDefaultLexicon() nlgFactory = NLGFactory(lexicon) realiser = Realiser(lexicon) start_s = nlgFactory.createClause("From the above scatterplot ma...
1,409
439
def keygen(id): table = "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF" indices = [9, 8, 1, 6, 2, 4] x = (id ^ 177451812) + 8728348608 result = list(f"1 4 1 7 ") for i in range(len(indices)): result[indices[i]] = table[x // 58 ** i % 58] return "".join(result)
308
175
from __future__ import division, print_function, absolute_import import copy import warnings import numpy as np import astropy from astropy.table import Table, Column HSCFILTERS = ['g', 'r', 'i', 'z', 'y'] SNRBANDS = {'g': 80, 'r': 100, 'i': 100, 'z': 100, 'y': 50} __all__ = ['calc_kcor', 'deredden_hsc_flux_s18a']...
18,410
9,429
from typing import Union, Dict, List, Tuple, Callable, Optional import numpy as np import torch from torch import Tensor from .utilities import ShapeBufferType, DtypeBufferType, BufferType def buffer_fill_information(buffer: BufferType, shape: Optional[ShapeBufferType] = None, ...
12,947
3,680
#-*-coding:utf8-*- ''' Created on 2013-4-27 @author: lan ''' from firefly.utils.singleton import Singleton from app.share.dbopear import dbCharacter from firefly.dbentrust.memclient import mclient from mcharacter import Mcharacter class McharacterManager: __metaclass__ = Singleton def __init__(self)...
1,076
345
import numpy as np from osgeo import gdal, ogr, gdal_array# I/O image data import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from PyQt5.QtWidgets import QFileDialog, QMessageBox class InputModule(): Training_File_Path = "" Validation_File_Path = "" Trg_Attribute_Selected = "" ...
6,596
2,213
""" Testing Models """ from django.contrib.auth import get_user_model from plugs_core.testcases import PlugsAPITestCase model = get_user_model() class TestModels(PlugsAPITestCase): """ Testing Models """ def test_superuser_can_login_with_new_account(self): """ Ensures superuser is c...
675
204
#------------------------------------------------------------------------------ # elftools tests # # Maxim Akhmedov (max42@yandex-team.ru) # This code is in the public domain #------------------------------------------------------------------------------ import unittest import os from elftools.elf.elffile import ELFFi...
8,882
2,921
# -*- coding: utf-8 -*- # """ Solve a linear equation system with the kinetic energy operator. """ import numerical_methods as nm import sys from scipy.sparse.linalg import LinearOperator import time import numpy import cmath import matplotlib.pyplot as pp from matplotlib import rc rc("text", usetex=True) rc("font", ...
7,818
2,726
import os import sys import functions as func print (f'version -> {sys.version}') print (f'version info -> {sys.version_info}') print (f'path -> {sys.path}') print (f'cwd -> {os.getcwd()}') for k, v in os.environ.items(): print(f'{k} -> {v}') print (f'arguments -> {str(sys.argv)}') x = 3 # a whole...
605
241
# -*- coding:utf-8 -*- from django.conf.urls import url, include from apps.query.views import * from rest_framework import routers router = routers.DefaultRouter() router.register(r'querysqllog', QuerySqlLogViewSet, basename="querysqllog") urlpatterns = [ # url(r'^', include(router.urls)), url(r'querysql...
462
159
import sympl as sp import numpy as np from marble.state import AliasDict class NotAColumnException(Exception): pass class ColumnStore(sp.Monitor): """ Stores single-column values as numpy arrays to later retrieve a timeseries. """ def __init__(self, *args, **kwargs): super(ColumnStore, ...
1,478
415
from shamir.io import IO import os import string import random TEST_FILE = './test/test_assets/io_test.txt' class TestIO: def test_read_write_text(self): length = random.getrandbits(8) content = ''.join(random.choice(string.ascii_letters) for _ in range(length)) IO.write_file(TEST_FILE, ...
678
222
import unittest from stix2 import Indicator, Sighting from .message_mapping import map_bundle_to_sightings class TestMessageMapping(unittest.TestCase): def setUp(self): self.observations = [ { "type": "identity", }, {"type": "observed-data", "some-prop":...
999
328
import pytest from polka_curses.views.list_page import ListPage, BookInListItem @pytest.fixture def listpage(list_): return ListPage(list_) @pytest.fixture def bookitem(listpage): return BookInListItem(listpage.list_.books[0]) def test_get_list_from_page(listpage): assert listpage.list_ def test_ge...
767
282
import requests def get_event_match_keys_with_vidoes(event_key): r = requests.get('http://www.thebluealliance.com/api/v3/event/%s/matches' % event_key, headers={'':''}) json = r.json() match_video = {} for match in json: if len(match['videos']): if match['videos'][0]['type'] == 'yo...
756
257
while True: n = int(input("n=?")) for x in range(0, n, 1): print(" "*(n-(x+1)), "*"*(x+1))
111
54
from dskc.clean import get_text_from from dskc.visualization import graphs from dskc.visualization.graphs.types.word_cloud.word_cloud import word_cloud, text_proportion_success from dskc._util.string import get_display_text import pandas as pd from . import util from matplotlib import pyplot as plt def _wordcloud(ser...
2,592
736
import numpy as np import matplotlib.pyplot as pl yearInSec = 365.0*24.0*3600.0 solarMassPerYear = 1.99e33 / yearInSec RStar = 4e13 TStar = 2330.0 MStar = 0.8 * 1.99e33 R0 = 1.2 * RStar Rc = 5 * RStar Rw = 20.0 * RStar vexp = 14.5 * 1e5 vturb = 1.0 MLoss = 2e-5 * solarMassPerYear G = 6.67259e-8 k = 1.381e-16 mg = 2.3 ...
1,333
796
print "Buna! Sung gigi! Sunt petrolier! Gigi Petrolieru'!" print "Gigi este momentan conflictuat despre ce sa faca..." print "Azi sunt mai vorbaret decat deobicei! N-am ce face, se termina sesiunea..."
203
76
import click import questionary class QuestionaryOption(click.Option): def __init__(self, param_decls=None, **attrs): click.Option.__init__(self, param_decls, **attrs) def prompt_for_value(self, ctx): return questionary.select(self.prompt, choices=self.type.choices).unsafe_ask()
307
99
#coding=utf-8 import csv import base64 def image_to_base64(): '''封装把图片转换为base64编码格式''' o = open(r"./1-0.jpg", 'rb') base64_data = base64.b64encode(o.read()) s = base64_data.decode() return ("data:image/png;base64,%s"%s) def base64_write_csv(): '''把生成的base64写入CSV文件''' f = open(r'./image.csv...
516
242
from .ipc_teleop import Teleoperator from .message_queue import NotebookBackend
80
23
import datetime import re from collections import defaultdict from dataclasses import dataclass, field from enum import Enum from typing import List, Tuple from ray import logger __all__ = ['BitTypes', 'HistoryTypes', 'ChunkTypes', 'EventTypes', 'Elimination', 'Stats', 'TeamStats', 'Header', 'H...
4,822
1,637
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr from frappe.model.document import Document class CustomScript(Document): def autoname(self): self.name = self.dt + "-" + sel...
457
171
# Computational Linear Algebra #4 Structured Gaussian Elimination # By: Nick Space Cowboy import numpy as np class Cowboy_Lin_Alg(object): def solve_utri(self, Utri, b): n = len(Utri) # row dimension of the Utri matrix x = np.zeros_like(b, dtype=np.float64) for i in range(n - 1, -1, -1): # loop to iterate thro...
1,160
591
#!/usr/bin/env python # Copyright 2018 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. """ If should_use_hermetic_xcode.py emits "1", and the current toolchain is out of date: * Downloads the hermetic mac toolchain *...
6,819
2,351
try: from urllib.parse import quote_plus except ImportError: from urllib import quote_plus import processout from processout.networking.request import Request from processout.networking.response import Response # The content of this file was automatically generated class Activity(object): def __init__(...
5,050
1,395
import data as csv __version__ = "0.2" callsign_endpoint = "http://hamcall.net/call?callsign=" print(f"AirLog Version: {__version__}") questions = ["Callsign", "Name", "Location", "Comm type", "Notes", "signal ( x/10 )"] data = {} while 0 < len(questions): for question in questions: print(question + "?") answ...
475
182
from os import path from subprocess import check_call import click def run_hook(name, *args): hook_path = path.expanduser('~/.sweep/hooks/' + name) if path.exists(hook_path): # run the script with the given args click.secho('Found hook for {}, running {}'.format(name, hook_path), fg='blue') ...
364
117
"""Unit test to test get test result.""" from unittest import TestCase from adefa import cli from adefa.tests import runner import mock class TestResult(TestCase): """Unit test class to test get test result.""" def test_valid_result(self): cli.client.get_run = mock.MagicMock(return_value={'run': {...
2,642
893
import numpy as np import matplotlib.pyplot as plt import sncosmo from simlc import simlc from astropy.table import Table class lcfit: def __init__(self): self.model = sncosmo.Model(source='Hsiao') def obs_tab(self, taxis, bandarr): """ Create the astropy table with the...
876
311
import os from argparse import ArgumentParser from collections import OrderedDict import torch import torch.nn as nn import random import pickle import pytorch_lightning as pl from options.train_options import TrainOptions from pytorch_lightning.callbacks import ModelCheckpoint import numpy as np import sys sys.path.ap...
2,082
791
import unittest from unittest.mock import patch import base58 from pyacryl2 import AcrylClient from pyacryl2.utils import AcrylAddress from pyacryl2.utils import AcrylAddressGenerator from pyacryl2.utils import AcrylAsyncAddress class AddressGeneratorTest(unittest.TestCase): def setUp(self): self.addre...
1,758
542
# This file was automatically created by FeynRules 2.3.36 # Mathematica version: 11.3.0 for Linux x86 (64-bit) (March 7, 2018) # Date: Tue 15 Feb 2022 16:39:02 from object_library import all_couplings, Coupling from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot GC_1 = Coupling(name =...
9,606
4,125
"Обработка событий из логов с использованием потоков (Rx)" from __future__ import annotations import logging from typing import Tuple from rx.subject import Subject from rx.core.abc.disposable import Disposable from .atypes import Atype0, Atype1, Atype2, Atype3, Atype4, Atype5, Atype6, Atype7, Atype8, Atype9, \ Aty...
1,871
648
#!/usr/bin/env python # -*- coding: utf-8 -*- import timeit from math import radians import pytest import torch from combustion.points import RandomRotate, Rotate, random_rotate, rotate class TestRotateFunctional: @pytest.mark.parametrize( "x,y,z", [ pytest.param(0.0, 0.0, 0.0, id="...
7,825
3,149
from typing import Generic, Protocol, TypeVar from uuid import UUID from fastapi.security.base import SecurityBase from fastapi import Response from kitman.core.domain import DependencyCallable, OpenAPIResponseType, IModel from kitman.core.schemas import Schema # Types TUser = TypeVar("TUser", bound="IUser") TSubje...
2,101
664
# import torch import torch import torch.nn as nn import torch.nn.functional as F # import applied transformers from .base import ABSA_Model from ..datasets.base import ABSA_Dataset, ABSA_DatasetItem from applied.core.model import Encoder, InputFeatures # import utils from applied.common import align_shape from typing ...
7,835
2,546
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. import re from copy import deepcopy from typing import List import numpy as np from pymatgen.electronic_structure.plotter import BSPlotter from pymatgen.io.vasp import Vasprun from vise.analyzer.plot_band import BandPlotIn...
5,604
1,793
import logging.handlers import logging import os from config import Config from base.singleton import Singleton class Logger(metaclass=Singleton): def __init__(self, dir_path=os.path.dirname(os.path.realpath(__file__))+os.path.sep): formatter = logging.Formatter('%(levelname)s %(asctime)s file ...
2,298
710
"""Example of a simple calculator written using shimmer.""" from typing import Optional, List, Callable from pyglet.window import key import cocos from shimmer.components.box_layout import create_box_layout, BoxGridDefinition from shimmer.components.font import FontDefinition from shimmer.data_structures import Whit...
6,445
1,773
from typing import Tuple class ServiceClientException(Exception): __http_status_code = None # type: int __message = None # type: str __details = None # type: Tuple[str] def __init__(self, http_status_code, message, details=()): # type: (int, str, Tuple[str]...
776
221
# -*- coding: utf-8 -*- # © 2017-2019, ETH Zurich, Institut für Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """A tool to find and identify nodal features in band structures. """ __version__ = '0.1.1' from . import coordinate_system from . import search from . import identify from . import io from ....
398
143
from typing import Optional import numpy as np import pandas as pd from fipie import tree from fipie.cluster import ClusterAlgo, NoCluster from fipie.weighting import Weighting class Portfolio: """ A portfolio of instrument returns """ def __init__(self, ret: pd.DataFrame): """ Create a ``Portfolio...
6,891
1,728
import numpy as np import tensorflow as tf import logging from CNN_input import read_dataset logging.basicConfig(format='%(levelname)s:%(asctime)s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') DATASET_DIR = r'C:\Users\PycharmProjects\Cifar' N_FEATURES = 3072 # 3072 = 32*32*3 N_CLASSES = 7 ...
7,113
2,661
import unittest import numpy as np from src.scene.point import ImagePoint, WorldPoint class TestImagePoint(unittest.TestCase): def test_p_x(self) -> None: """ Assert the self.x property. """ with self.subTest(msg="Return correct property"): x: int = 5 y: int...
6,588
2,152