text
string
size
int64
token_count
int64
from server import crud def test_filter(product_1, product_2): result, content_range = crud.product_crud.get_multi(filter_parameters=["name:duct 1"], sort_parameters=[]) assert len(result) == 1 assert content_range == "products 0-100/1" # Will not filter but return all results result, content_ran...
1,926
646
import numpy as np import trimesh try: from Satellite_Panel_Solar import Panel_Solar from SatelitteActitud import SatelitteActitud except: from src.data.Satellite_Panel_Solar import Panel_Solar from src.data.SatelitteActitud import SatelitteActitud # noinspection SpellCheckingInspection """Sa...
18,815
6,272
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class ResPartner(models.Model): _inherit = 'res.partner' # Use in view attrs. Need to required state_id if Country is India. ...
744
263
import numpy as np from scipy.interpolate import BSpline from colossus.cosmology import cosmology """ Helper routines for basis functions for the continuous-function estimator. """ ################ # Spline basis # ################ def spline_bases(rmin, rmax, projfn, ncomponents, ncont=2000, order=3): ''' Co...
5,037
1,796
import glob import os import pandas as pd import json import ast from tqdm import tqdm import click import pickle from multiprocessing import Pool, cpu_count, Queue from functools import partial import itertools import sys sys.setrecursionlimit(15000) import logging logpath = "./tree_matches.log" logger = loggin...
17,587
5,403
# ================================================================= # # Authors: Stephen Lloyd # Ian Edwards # # Copyright (c) 2020, OpenCDMS Project # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to dea...
3,273
1,025
import os from selenium import webdriver from sa11y.analyze import Analyze import urllib3 urllib3.disable_warnings() class TestAccessibilitySa11y(object): def test_analysis(self): capabilities = { 'browserName': 'chrome', 'sauce:options': { 'username': os.enviro...
663
216
# 275. H-Index II # Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? class Solution(object): # http://blog.csdn.net/titan0427/article/details/50650006 def hIndex(self, citations): """ :type citations: List[int] :rtype: i...
653
215
from django.conf import settings from django import template from news.models import NewsItem, NewsAuthor, NewsCategory register = template.Library() @register.tag def get_news(parser, token): """ {% get_news 5 as news_items %} """ bits = token.split_contents() if len(bits) == 3: limit = None elif len(bits)...
6,172
2,211
import math import falcon import jsonschema class Model(object): db_table=""# db table name properties={} #schema properties schema={} #to hold schema for each model required=[] #list of required fields def __init__(self,db): self._db=db self.validated_data={} self.r...
1,731
524
import os from goldminer import game if __name__ == "__main__": print("Initializing") print("Working directory: " + os.getcwd()) game.start()
155
52
#!/usr/bin/env python from math import ceil import os import sys import argparse import multiprocessing import subprocess as sp import re #from pprint import pprint from array import array from yaml import load, dump contexts = ('CG','CHG','CHH') def main(): fCheck = fileCheck() #class for checking parameters pars...
15,337
5,502
import json import pytest from microdata_validator import Metadata, PatchingError RESOURCE_DIR = 'tests/resources/metadata_model' with open(f'{RESOURCE_DIR}/KREFTREG_DS_described.json') as f: TRANSFORMED_METADATA = json.load(f) with open(f'{RESOURCE_DIR}/KREFTREG_DS_described_update.json') as f: UPDATED_METAD...
4,316
1,605
# metrics/__init__.py # author: Playinf # email: playinf@stu.xmu.edu.cn from .metrics import create_tagger_evaluation_metrics
127
48
import sys import pytest from briefcase.platforms.macOS.dmg import macOSDmgCreateCommand if sys.platform != 'darwin': pytest.skip("requires macOS", allow_module_level=True) def test_binary_path(first_app_config, tmp_path): command = macOSDmgCreateCommand(base_path=tmp_path) binary_path = command.binary...
680
237
from flask import Flask app = Flask(__name__) if app.config["ENV"] == "production": app.config.from_object("config.ProductionConfig") elif app.config["ENV"] == "testing": app.config.from_object("config.TestingConfig") else: app.config.from_object("config.DevelopmentConfig") from app import views from app im...
336
111
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : MeUtils. # @File : conf # @Time : 2021/1/31 10:20 下午 # @Author : yuanjie # @Email : yuanjie@xiaomi.com # @Software : PyCharm # @Description : from meutils.pipe import * # 定义参数 class TrainConf(BaseConfig): epoch = ...
674
315
install Request module pip install requests import requests r = requests.get('https://xkcd.com/353/') print(r) print(r.text) #Download image r = requests.get('https://xkcd.com/comics/python.png') print(r.content) with open('comic.png', 'wb') as f: f.write(r.content) print(r.status_code) print(r.ok)...
888
346
from django.conf.urls import url, include from django.contrib import admin from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token from rest_framework_jwt.views import verify_jwt_token # Configuration API Router from rest_framework import routers #router = routers...
1,231
430
import numpy as np from scipy.optimize import curve_fit, minimize_scalar h_planck = 4.135667662e-3 # eV/ps h_planck_bar = 6.58211951e-4 # eV/ps kb_boltzmann = 8.6173324e-5 # eV/K def get_standard_errors_from_covariance(covariance): # return np.linalg.eigvals(covariance) return np.sqrt(np.diag(covariance)) ...
13,432
3,891
from __init__ import print_msg_box class Node: def __init__(self, dataValue=None): self.dataValue = dataValue self.next = None class singleLinkedList: def __init__(self): self.headValue = None self.temp = None def insertLast(self, *elements): for data in elements...
4,517
1,275
# Generated by Django 2.2.14 on 2020-08-23 10:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0006_referral_amount'), ] operations = [ migrations.AddField( model_name='item', name='paystack_link', ...
407
141
"""Decorators for auth module.""" from functools import wraps from src.protocol import make_response from src.database import session_scope from .models import Session def login_required(func): """Check that user is logged in based on the valid token exists in request.""" @wraps(func) def wrapper(reques...
798
218
# Name: # Date: # proj05: functions and lists # Part I def divisors(num): """ Takes a number and returns all divisors of the number, ordered least to greatest :param num: int :return: list (int) """ # Fill in the function and change the return statment. numlist = [] check = 1 whil...
3,607
1,235
# Copyright 2015 Bloomberg Finance L.P. # # 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 i...
2,034
674
''' Une case est definie par sa couleur, ses coordonnees et un acces a la grille pour recuperer ses voisins ''' class Case(): def __init__(self, x, y, couleur, grille): self._x = x self._y = y self._couleur = couleur self._grille = grille self.GREY = "g...
1,915
700
#import Libraries import cv2 import sys import numpy as np from matplotlib import pyplot as plt import matplotlib.image as mpimg ################################################## ''' This example illustrates how to extract interesting key points as features from an image Usage: keypointsSIFTDescriptor.py [<image...
1,280
408
import xml.etree.ElementTree as ET from .baseVmWareXmlResponse import BaseVmWareXmlResponse class GetHostInfoResponse(BaseVmWareXmlResponse): def __str__(self): return ('GetHostInfoResponse[vendor={} model={} vCPUs={} memory={}]').format( self.vendor, self.model, self.vCPUs, self.memory) ...
1,103
338
import sys import logging if sys.version_info[:2] <= (2, 6): logging.Logger.getChild = lambda self, suffix:\ self.manager.getLogger('.'.join((self.name, suffix)) if self.root is not self else suffix) import pytest from chatexchange.markdown_detector import markdown logger = logging.getLogger(__name__) ...
2,900
857
x_indexes = [i for i, j in enumerate(xaddr)] if j == myxaddr] y_indexes = [i for i, j in enumerate(yaddr)] if j == myyaddr] print('x_indexes: ' + str(x_indexes)) print('y_indexes:' +str(y_indexes)) # keep common indexes common = [i for i, j in zip(x_indexes, y_indexes) if i == j] print('common: ' + str(common))
313
127
import os from typing import Optional, List from fastapi import APIRouter, Request, Response, status, Depends from pyefriend_api.models.setting import Setting as SettingModel from pyefriend_api.app.auth import login_required from .schema import SettingOrm, SettingUpdate r = APIRouter(prefix='/setting', ...
1,651
601
"""Unit tests for util/multi_analysis.py""" import os import unittest from dsi.multi_analysis import MultiEvergreenAnalysis, main from test_lib.fixture_files import FixtureFiles from test_lib.test_requests_parent import TestRequestsParent FIXTURE_FILES = FixtureFiles() class TestMultiEvergreenAnalysis(TestRequest...
20,031
7,796
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-08 03:42 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('pacientes'...
6,356
1,891
from typing import Any, List, Dict RAW_INFO: Dict[str, List[Dict[str, Any]]] = { "streams": [ { "index": 0, "codec_name": "h264", "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", "profile": "High", "codec_type": "video", ...
7,308
2,955
from simulator import PolychromaticField, cf, mm F = PolychromaticField( spectrum=1.5 * cf.illuminant_d65, extent_x=12.0 * mm, extent_y=12.0 * mm, Nx=1200, Ny=1200, ) F.add_aperture_from_image( "./apertures/circular_rings.jpg", pad=(9 * mm, 9 * mm), Nx=1500, Ny=1500 ) rgb = F.compute_colors_at...
368
191
from items import vehicles, _xml from gui.Scaleform.daapi.view.lobby.trainings.training_room import TrainingRoom; from helpers.statistics import StatisticsCollector; from game import init import ScoreViewTools def exportAll(): ScoreViewTools.Export.init() ScoreViewTools.Export.cleanup() ScoreVi...
2,581
754
import random def mergeSort(numbers): if len(numbers) <= 1: return numbers left = numbers[:len(numbers)//2] right = numbers[len(numbers)//2:] left = mergeSort(left) right = mergeSort(right) numbers = merge(left, right, numbers) return numbers def merge(left, right, numbers): ...
897
315
from utilsw2 import * from Reader import * from Adapted_voc_evaluation import * import glob path_to_video = 'datasets/AICity_data/train/S03/c010/vdo.avi' path_to_frames = 'datasets/frames/' results_path = 'Results/Task1_1' def task4(color_space=cv2.COLOR_BGR2GRAY, mu_file = f"W2/task1_1/mu.pkl",sigma_file= f"W2/task...
1,586
626
# Copyright 2021 Sai Sampath Kumar Balivada # 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 ...
3,207
909
# -*- coding: utf-8 -*- # Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
2,432
832
def euclidean_gcd(first, second): """ Calculates GCD of two numbers using the division-based Euclidean Algorithm :param first: First number :param second: Second number """ while(second): first, second = second, first % second return first def euclidean_gcd_recursive(first, seco...
1,265
304
""" Distances metrics based on the covariance matrix (mostly in the context of merging and compress)""" import torch import numpy as np import torch.nn.functional as F np.random.seed(0) def cov(m, y=None): """computes covariance of m""" if y is not None: m = torch.cat((m, y), dim=0) m_exp = torch....
1,627
750
import tensorflow as tf import tensorflow_hub as hub import numpy as np class TFHubContext: def __init__(self, url="https://tfhub.dev/google/universal-sentence-encoder-large/3") -> None: super().__init__() print('Initialize graph:') # Create graph and finalize (finalizing optional but recommended). ...
3,415
1,170
from __future__ import unicode_literals from netmiko.endace.endace_ssh import EndaceSSH __all__ = ['EndaceSSH']
117
46
# -*- coding: utf-8 -*- # pylint: disable=wildcard-import,redefined-builtin,unused-wildcard-import from __future__ import absolute_import, division, print_function from builtins import * # pylint: enable=wildcard-import,redefined-builtin,unused-wildcard-import from genemap.mappers import get_mappers def main(args):...
1,020
351
import gzip import random import subprocess import sys def get_acceptors(filename): accs = [] with gzip.open(filename, 'rt') as fp: for line in fp.readlines(): (exon1, intron, exon2, expression, gene) = line.split() s1 = intron[-22:-2] s2 = intron[-2:] s3 = exon2[0:20] accs.append((s1, s2, s3, expre...
3,463
1,660
from sklearn.cluster import KMeans import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt def get_columns(db, col1, col2): inputs = db[[col1, col2]] coords = inputs.as_matrix(columns=None) return np.array(coords) def plot_colored_graph(inputs, kmeans_result): x = inputs.t...
1,300
528
# Generated by Django 2.1.4 on 2018-12-12 16:51 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Test', fields=[ ('id', models.AutoField(aut...
783
235
import os import pandas import time from datetime import datetime, timedelta from collections import defaultdict from copy import deepcopy from googleapiclient.discovery import build """ All functions that are used for querying, processing, and saving the data are located here. """ VALID_PERIOD_LENGTHS = ["day", "w...
19,216
5,095
import os from dotenv import load_dotenv from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Cryptodome.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 from Cryptodome.PublicKey import RSA load_dotenv() API_URI = os.environ.get("API_URI", "https://nodes.thetangle.org:443").split(",") API_OPEN = ...
659
305
# Copyright 2015 Google 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 ag...
3,620
1,042
from .global_hac import GlobalHAC
34
12
from dataclasses import dataclass from functools import total_ordering from collections import Counter import typing import textwrap @dataclass(frozen=True) @total_ordering class Point: x: int y: int def __add__(self, they): return Point(self.x + they.x, self.y + they.y) def __sub__(self, the...
3,195
1,188
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2021 Beartype authors. # See "LICENSE" for further details. ''' **Beartype forward reference data submodule.** This submodule exercises **forward reference type hints** (i.e., strings whose valu...
3,270
940
# coding: utf-8 StatusContinue = 100 StatusSwitchingProtocols = 101 StatusProcessing = 102 StatusEarlyHints = 103 StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 StatusMultiStatus = 207 StatusAlreadyRepor...
1,701
663
import logging import oscar x0a_name="User lookup" log = logging.getLogger('oscar.snac.x0a') subcodes = {} def x0a_init(o, sock, cb): log.info('initializing') cb() log.info('finished initializing') def x0a_x01(o, sock, data): ''' SNAC (xa, x1): User lookup Family Error refere...
1,064
469
#!/usr/bin/env python """setup.py Defines the setup instructions for the punch framework Copyright (C) 2016 Rodrigo Chacon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, in...
2,928
873
''' Drilling info analysis This program reads well header data and production logs (e.g. exported from Drilling Info as .csv files) and walks the user through the genreation of decline curves for each well provided in the input data. Decine curves are fit with a the hyperbolic curve that is estimated using an iterativ...
13,664
5,103
#!/usr/bin/env python import os import re import unittest from git import Repo from semver import match from click import option, argument, echo, ClickException from touchresume.cli import cli from touchresume import __version__ @cli.command(with_appcontext=False) @option('-d', '--dir', default='tests', help='Dire...
2,745
956
from reb.src import pynyt from reb.conf import APIKEY_NYT_ARTICLE nyt = pynyt.ArticleSearch(APIKEY_NYT_ARTICLE) nytArchive = pynyt.ArchiveApi(APIKEY_NYT_ARTICLE) # # get 1000 news articles from the Foreign newsdesk from 1987 # results_obama = nyt.query( # q='obama', # begin_date="20170101", # end_date="...
485
218
"""A file system service for managing CVMFS-based client file systems.""" import os from cm.services import service_states import logging log = logging.getLogger('cloudman') class CVMFS(object): def __init__(self, filesystem, fs_type): self.fs = filesystem # File system encapsulating this implementati...
1,403
428
# -*- coding: utf-8 -*- import re, web, datetime, hashlib, struct, yaml, sys, wikipedia import xml.etree.ElementTree as ET re_NUMERIC = re.compile("(-?\d+)[ ,]+(-?\d+)") re_NUMERICF = re.compile("(-?[\.\d]+)[ ,]+(-?[\.\d]+)") #fractions allowed re_EXPEDITION = re.compile('\[\[(\d{4}-\d{2}-\d{2} -?\d+ -?\d+)') def g...
3,240
1,229
def nearest_smallest_element(arr): """ Given an array arr, find the nearest smaller element for each element. The index of the smaller element must be smaller than the current element. """ smaller_numbers = [] def nearest(n): def find_previous_num(): for previous_num in reve...
1,034
320
# -*- coding: utf-8 -*- ''' Relations for BIRD. ''' import socket import netaddr import netifaces from charmhelpers.core import hookenv from charmhelpers.core.services.helpers import RelationContext def router_id(): ''' Determine the router ID that should be used. This function uses the common logic of...
3,385
1,015
from hashlib import sha1 from django.core.cache import cache from django.utils.encoding import smart_str def cached(key=None, timeout=300): """ Cache the result of function call. Args: key: the key with which value will be saved. If key is None then it is calculated automatically ...
1,136
287
#!/usr/bin/env python3 """ 1. Go to: https://usage.dteenergy.com/?interval=hour 2. Download CSV 3. Run: python dtecsv.py .\electric_usage_report_05-31-2021_to_06-05-2021.csv """ import csv import datetime import click import matplotlib.pyplot as plt x = [] y = [] @click.command() @click.argument('file', type=c...
1,417
527
# Copyright (c) 2021, NVIDIA CORPORATION. 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 applic...
12,598
3,677
# The following comments couldn't be translated into the new config version: # Test storing OtherThing as well # Configuration file for PrePoolInputTest import FWCore.ParameterSet.Config as cms process = cms.Process("TEST2ND") process.load("FWCore.Framework.test.cmsExceptionsFatal_cff") #process.maxEvents = cms.un...
906
311
import datetime import os, sys import numpy as np import matplotlib.pyplot as plt import casadi as cas ##### For viewing the videos in Jupyter Notebook import io import base64 from IPython.display import HTML # from ..</src> import car_plotting # from .import src.car_plotting PROJECT_PATH = '/home/nbuckman/Dropbox (...
24,165
11,427
import numpy as np from tensorflow.keras.callbacks import TensorBoard import cv2 import sys import threading import keras from keras.layers import Conv2D,Dense,MaxPooling2D,Flatten,BatchNormalization,Dropout from IPython.display import display from PIL import Image import tensorflow as tf np.random.seed(1) with tf.dev...
2,082
774
#!/usr/bin/env python import distutils from setupfiles.dist import DistributionMetadata from setupfiles.setup import setup __all__ = ["setup"] distutils.dist.DistributionMetadata = DistributionMetadata distutils.core.setup = setup
233
61
import Gramatica def testSeparadorDeSilabas(entrada, esperado): try: salida = Gramatica.separarEnSilabas(entrada) except Gramatica.NoHayVocal: print("[ERROR]","Salida esperada:", "\"" + esperado + "\"", "|", "Salida obtenida:", "Excepcion: No hay vocal") return if esperado != salid...
3,002
1,256
# # Minify JSON data files in the `/dist` directory. # Script invoked by the npm postbuild script after building the project with `npm run build`. # from os import ( path, listdir, fsdecode ) import json from datetime import datetime class JSONMinifier: DIST_CONSTITUENT_DATA_DIRECTORY = path.abspath(...
1,201
397
import subprocess import platform from Scripts import plist, utils class CPUName: def __init__(self, **kwargs): self.u = utils.Utils("CPU-Name") self.plist_path = None self.plist_data = {} self.clear_empty = True self.detected = self.detect_cores() self.cpu_model = s...
13,751
4,705
# -*- coding: UTF-8 -*- # # Copyright (c) 2016, Yung-Yu Chen <yyc@solvcon.net> # BSD 3-Clause License, see COPYING import os import numpy as np import solvcon as sc class Probe(object): """ Represent a point in the mesh. """ def __init__(self, *args, **kw): self.speclst = kw.pop('speclst'...
3,853
1,368
class BuyingCheap: def thirdBestPrice(self, prices): ls = sorted(set(prices)) return -1 if len(ls) < 3 else ls[2]
134
48
""" COCO dataset (quick and dirty) Hacked together by Ross Wightman """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.utils.data as data import os import cv2 import random import torch import numpy as np from PIL import Image from pycocotool...
8,600
3,072
'''OpenGL extension EXT.sRGB_write_control This module customises the behaviour of the OpenGL.raw.GLES2.EXT.sRGB_write_control to provide a more Python-friendly API Overview (from the spec) This extension's intent is to expose new functionality which allows an application the ability to decide if the conversion...
1,292
350
from imagenet.models.biggan import BigGAN from imagenet.models.u2net import U2NET from imagenet.models.cgn import CGN from imagenet.models.classifier_ensemble import InvariantEnsemble __all__ = [ CGN, InvariantEnsemble, BigGAN, U2NET ]
241
88
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def osdialog(): http_archive( name="osdialog" , build_file="//bazel/deps/osdialog:build.BUILD" , sha256="3fc6dabcf...
595
283
from yaml import safe_load from .blocklist import Blocklist class Configuration: def __init__(self, location): self.__location = location with open(location) as file: data = safe_load(file) self.repo_path = data["repository"]["path"] self.dnsmasq_path = data["dnsmasq"][...
529
146
""" Create meta data file 'metadata.yaml' for :class:`~pySPACE.resources.dataset_defs.feature_vector.FeatureVectorDataset` Used for external files, which can not be read directly in pySPACE. Eg. csv files without names. To be called in the dataset directory. """ def main(md_file): # Request all necessary data fr...
5,532
1,749
""" Testing Abstract LUT model """ import unittest import os import shutil import tempfile from PyOpenColorIO.Constants import INTERP_LINEAR, INTERP_TETRAHEDRAL from utils import lut_presets as presets from utils.lut_presets import PresetException, OUT_BITDEPTH import utils.abstract_lut_helper as alh from utils.colors...
12,715
3,935
import argparse import sys import logging import json def args_parser(): parser = argparse.ArgumentParser(prog='booktracker', description='book update tracker in python') parser.add_argument('-f', '--urls_file', type=argparse.FileType('r'), help='a file contains book urls,...
4,704
1,388
import math def rectangle_area(b=None, h=None): if b is None or b is None: print("Error wrong parameters") return return b * h def circle_area(radium): return (radium ** 2) * math.pi print(circle_area(5)) def intermediate_number(a, b): return (a + b) / 2 print(intermediate_numb...
667
262
#!/usr/bin/env python # # Copyright (c) 2010, iPlant Collaborative, University of Arizona, Cold Spring Harbor Laboratories, University of Texas at Austin # This software is licensed under the CC-GNU GPL version 2.0 or later. # License: http://creativecommons.org/licenses/GPL/2.0/ # # Author: Seung-jin Kim # Contact: s...
3,647
1,285
import json import os classlist = os.listdir("./image/") for classname in classlist: # "./Classification/"+classname+"/" try: os.mkdir("./Classification/"+classname+"/") except: pass filenamelist = os.listdir("./image/"+classname) url = "https://cdn.jsdelivr.net/gh/2x-ercha/twikoo-magic/image/" +...
554
203
#!/usr/bin/env python3 import sys from multiprocessing import Queue,Process,Lock from datetime import datetime import getopt import configparser class Config(object): def __init__(self,filename,arg='DEFAULT'): self._filename = filename self._arg = arg self._obj = configparser.ConfigParser(...
4,964
1,698
#!/usr/bin/env python3 import argparse import yaml import pathlib import decimal import datetime import os decimal.getcontext().prec = 10 parser = argparse.ArgumentParser() parser.add_argument('--data', help='path to data directory', required=True) args = parser.parse_args() script_path = os.path.dirname(os.path.re...
1,730
562
# -*- coding: utf-8 -*- #for local #import config #config.write_environ() import os,json from flask import Flask, render_template, request, redirect, url_for, session from requests_oauthlib import OAuth1Session from datetime import timedelta import twitter_auth import twitter_delete import postTweet import databaseI...
4,131
1,265
from PySide.QtGui import QKeySequence from PySide.QtCore import Qt from .menu import Menu, MenuEntry, MenuSeparator class DisasmInsnContextMenu(Menu): def __init__(self, disasm_view): super(DisasmInsnContextMenu, self).__init__("", parent=disasm_view) self.insn_addr = None self.entries....
882
279
""" shades contains classes and functions relating to Shades' shade object """ from abc import ABC, abstractmethod from typing import Tuple, List import numpy as np from PIL import Image from .noise_fields import NoiseField, noise_fields from .utils import color_clamp class Shade(ABC): """ An Abstract bas...
21,209
6,890
def CA(file): """correspondence analysis. Args: file (directory): csv file contains genes' RSCU values Returns: - csv file contains genes' values for the first 4 axes of the correspondence analysis result - csv file contains codons' values for the first 4 axes o...
4,104
1,594
""" Main RenderChan package """
32
12
import sys import os import shutil sys.path.append('.') import chia_rep def test_filter_peaks(): sample_dict = chia_rep.read_data('test/sample_input_file.txt', 'test/test_files/hg38.chrom.sizes', output_dir='test/output') for sample in...
5,110
1,796
# Jacqueline Kory Westlund # May 2016 # # The MIT License (MIT) # # Copyright (c) 2016 Personal Robots Group # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including w...
4,343
1,389
# Generated by Django 4.0.1 on 2022-01-11 19:00 from django.db import migrations, models import django.db.models.deletion import scans.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Host', ...
7,470
2,100
#!/usr/bin/env python # -*- coding: utf-8 -*- # ** # # ======================== # # CHECK_RESERVATIONS_COMMAND # # ======================== # # Command for checking reservations. # # @author ES # ** import logging from collections import OrderedDict from es_common.command.es_command import ESCommand from es_common.enu...
1,447
424
# coding: utf-8 from email.mime.text import MIMEText from email.parser import Parser import os import pytest @pytest.fixture def debugsmtp(request, tmpdir): from mr.hermes import DebuggingServer debugsmtp = DebuggingServer(('localhost', 0), ('localhost', 0)) debugsmtp.path = str(tmpdir) yield debugsmt...
2,471
871
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
21,967
5,910