text
string
size
int64
token_count
int64
""" This script is intended to be used as mask maker using maskrcnn. We use a separate script because mask rcnn has different dependencies from the rest. """ import numpy as np from tqdm import tqdm import sys import argparse from configparser import ConfigParser sys.path.append("../libs") from tiff import Tiff from...
4,502
1,653
import csv from biosppy.signals import tools as st from biosignals.BioSignal import BioSignal from scipy.signal import butter, lfilter import numpy as np #from scipy.fftpack import rfft, irfft class ECG(BioSignal): # CONSTRUCTORS-------------------------------------------------------------- def __init__(self,...
6,560
2,192
import re import math import pytest from exercises import stretched, powers, say, top_ten_scorers, interpret def test_stretched(): assert stretched([]) == [] assert stretched([1]) == [1] assert stretched([10, 20]) == [10, 20, 20] assert stretched([5, 8, 3, 2]) == [5, 8, 8, 3, 3, 3, 2, 2, 2, 2] def t...
3,894
1,698
from locations.items import * from locations.constants import INVENTORY_NAME from utils import formatText hint_text_ids = [ # Overworld owl statues 0x1B6, 0x1B7, 0x1B8, 0x1B9, 0x1BA, 0x1BB, 0x1BC, 0x1BD, 0x1BE, 0x22D, 0x288, 0x280, # D1 0x28A, 0x289, 0x281, # D2 0x282, 0x28C, 0x28B, ...
2,199
1,089
import tensorflow as tf import tensorflow_probability as tfp # from tensorflow_probability import edward2 as ed2 tfd = tfp.distributions tfb = tfp.bijectors tfp_kernels = tfp.positive_semidefinite_kernels import sys sys.path.insert(0, './self_py_fun') from self_py_fun.PreFun import * # import scipy as sp import seaborn...
49,756
17,619
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
10,446
3,602
from PIL import Image import os import numpy as np import tensorflow as tf TRAIN_PATH = './tfrecords/train.tfrecords' TEST_PATH = './tfrecords/test.tfrecords' # 把传入的value转化为整数型的属性,int64_list对应着 tf.train.Example 的定义 def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[v...
2,342
1,074
__all__ = [] from . import core from .core import * # noqa __all__.extend(core.__all__)
92
37
from ramda.curry import curry @curry def tap(f, v): f(v) return v
76
35
# %% import torch import string from transformers import RobertaTokenizer, RobertaForMaskedLM roberta_tokenizer = RobertaTokenizer.from_pretrained('roberta-base') roberta_model = RobertaForMaskedLM.from_pretrained('roberta-base').eval() top_k = 10 def decode(tokenizer, pred_idx, top_clean): ignore_tokens = stri...
1,530
521
""" Django settings for app project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from .e...
5,686
2,125
import functools from flask import ( Blueprint,flash,g,redirect,render_template,request,session,url_for ) from werkzeug.security import check_password_hash,generate_password_hash from flaskr.db import get_db bp=Blueprint('auth',__name__,url_prefix='/auth') @bp.route('/register',methods=('GET','POST')) def regi...
2,406
692
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyOlefile(PythonPackage): """Python package to parse, read and write Microsoft OLE2 files"...
572
247
T = int(input()) while T != 0: tot = 0 for k in range(T): S = input().split() N = int(S[0]) A = ' '.join(S[1:]) if A == "suco de laranja": tot += N*120 elif A == "morango fresco": tot += N*85 elif A == "mamao": tot += N*85 elif A == "goiaba vermelha": tot += N*70 elif A == "manga": to...
575
309
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket import ssl import time import selectors class SyncTcpClient(object): def __init__(self, *, host='localhost', port=783, timeout=60.0, ssl_context=None ...
5,334
1,567
# -*- coding:utf-8 -*- from selenium import webdriver # apk参数 def init_driver(): desired_caps = {} # 手机 系统信息 desired_caps['platformName'] = 'Android' # 设置平台 desired_caps['platformVersion'] = '10.0' # 系统版本 # 设备号 desired_caps['deviceName'] = '61359515231666' # 设备id # 包名 desired_caps['a...
1,700
722
import glob import os import sys from deep_utils import dump_pickle, load_pickle import time from itertools import chain from argparse import ArgumentParser import torch from pretrainedmodels.utils import ToRange255 from pretrainedmodels.utils import ToSpaceBGR from scipy.spatial.distance import cdist from torch.utils....
5,886
2,000
""" Problem 1: Toivonen Algorithm Executing code: 1) $ python toivonen.py input.txt 4 2) $ python toivonen.py input1.txt 20 """ # note: error existing inside apriori import sys import re import random def toivonen(inputfile, support): iterations = 0 result = [] ck = True while ck: ans_...
8,100
2,450
import sys, os os.environ["PATH"] = os.path.dirname(sys.executable) + os.pathsep + os.environ["PATH"] import click import subprocess import pandas as pd @click.command() @click.option('--output_path', '-out', type=click.Path(exists=True), required = True, help="O...
4,168
1,343
# Copyright The Linux Foundation # SPDX-License-Identifier: Apache-2.0 import os from pathlib import Path from fossdriver.tasks import SPDXTV from datatypes import Status, ProjectRepoType def doGetSPDXForSubproject(cfg, fdServer, prj, sp): uploadName = os.path.basename(sp._code_path) uploadFolder = f"{prj._...
1,351
456
# -*- coding: utf-8 -*- """ Created on Thu Mar 18 01:58:05 2021 @author: ASUS """ D = {} list_1 = [] list_2 = [] def main(): global list_1 global list_2 def number(): Contact_No = input("3) Contact No:") n = str(Contact_No) if int(len(n)) == 10: ...
3,164
1,021
import csv import datetime import logging import time from io import StringIO import numpy as np import pandas as pd from django.db.models import Q from django.utils import timezone from iotile_cloud.utils.gid import IOTileBlockSlug, IOTileDeviceSlug, IOTileStreamSlug, IOTileVariableSlug from apps.physicaldevice.mo...
23,066
7,088
import shutil import tempfile import discord.ext.test as dpytest import pytest from discord import Intents from stonkmaster.core.bot import create_bot from stonkmaster.core.config import get_config from stonkmaster.core.setup import create_data_dir, delete_data_dir @pytest.fixture def config(): conf = get_confi...
746
251
""" ASGI config for websocketSessions project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('D...
835
253
import pytest from co2_diag.formatters import numstr, my_round, \ tex_escape def test_number_string_formatting_2decimals(): assert numstr(3.14159, decimalpoints=2) == '3.14' def test_number_string_formatting_largenumber(): assert numstr(3141592.6534, decimalpoints=3) == '3,141,592.653' def test_round...
788
325
import pandas as pd import fasttext from scipy.spatial import distance from itertools import product import sys import numpy as np model = fasttext.load_model("embedding/wiki.en/wiki.en.bin") #Return sentence embeddings for a list of words def get_word_embedding(list_of_words): return [model.get_sentence_vector(...
5,151
2,047
from netapp.netapp_object import NetAppObject class AdapterSffInfo(NetAppObject): """ Information on small form factor transceiver/connector (also known as sff). """ _part_number = None @property def part_number(self): """ Vendor's part number for the sff. If da...
2,515
716
#!/usr/bin/python3 from datetime import datetime, timedelta import os yesterday = datetime.now() - timedelta(1) yesterday = datetime.strftime(yesterday, '%Y-%m-%d') a_year_ago = datetime.now() - timedelta(365) a_year_ago = datetime.strftime(a_year_ago, '%Y-%m-%d') os.system(f"python3 processing/charts.py --START-DA...
552
205
# encoding: utf-8 import os import subprocess import netCDF4 import matplotlib.pyplot as plt import octant def make_movie(filelst, varname, cmin, cmax, view, lev=0, istart=None, iend=None, grd=None, proj='merc', imode='on', title='', clean=False): """ make a movie using a 2D hor...
5,389
1,844
from typing import List import numpy as np from random import choices from models import Genotype, Generation from selection import Selection class Breed: def __init__(self, parent_genotypes: np.ndarray, possibilites: List[float], population_of_progeny: int, maximum_feature=None, selection: str ...
5,251
1,556
# Generated by Django 3.2.6 on 2021-09-02 02:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app2', '0004_alter_ticket_filed_by'), ] operations = [ migrations.AlterField( model_name='ticket', name='status', ...
502
173
N = int(input()) P = (int(n) for n in input().split()) Q = (int(n) for n in input().split()) def kaijyou(n): if n <= 1: return 1 return n * kaijyou(n-1) def pos(n): l = [n for n in range(1,N+1)] a = sum([l.index(p)*kaijyou(N-i) for i,p in enumerate(P, start=1)]) b = sum([l.index(q)*kaijyou(N-i) for i,q in e...
359
171
import os # Config class for Application Factory class Config: basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(basedir, "alpha.db") # You should change this secret key. But make sure it's done before any data # is included in the database ...
684
256
from math import gcd from functools import reduce N, *A = map(int, open(0).read().split()) print(100 // reduce(gcd, A))
122
48
#------------------------------------------------------------------------------- # Name: CLUS_GDAL_Rasterize_VRI # Purpose: This script is designed to read a list of input PostGIS source # Vectors and Rasterize them to GeoTiff using GDAL Rasterize and # then load them into PostGIS...
8,311
2,744
from redbot.core.bot import Red from starboard.starboard import Starboard def setup(bot: Red): bot.add_cog(Starboard(bot))
129
46
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
6,344
2,322
#from .base import * #from .single_route import * #from .multiple_route import *
84
29
#!/usr/bin/env python import os import os.path import sys W3JS = "https://www.w3schools.com/lib/w3.js" W3CSS = "https://www.w3schools.com/w3css/4/w3.css" def _print(s): print(s) sys.stdout.flush() def _exit(rc): if rc != 0: _print("lib generate failed!") sys.exit(rc) def _call(cmd): _print(cmd) rc = os.sys...
757
390
from pathlib import Path from source.install import Installer class Importer(): help_msg = """ Comandi disponibili: import-ca <ca_cert_path> <ca_key_path> importa un certificato, la sua chiave privata """ def __init__(self, args): # nessun comando if len(args) == 0: prin...
1,705
479
"""Unit tests for keyer module.""" import pytest import numpy as np from enigma.keyer import Keyer def mock_signal(*args): """Mock creation of a binary signal array. :return: binary array :rtype: np.ndarray """ signal = np.array([1, 0, 1]) return signal def mock_audio(*args): """Return ...
2,740
976
from .reference_utils import get_source_genome_reference_file_paths, download_reference_data_from_latest_ensembl, download_grch37_reference_data
144
43
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import yaml import getpass ROOTDIR = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(ROOTDIR, 'config.yaml'), 'r') as f: CONFIGDATA = yaml.load(f.read(), Loader=yaml.FullLoader) FILEDIR = CONFIGDATA['folders'][getpass.getuser()]['datpath'...
333
130
# Python 3.9.0 # AveragedTimeOfTravel def AveragedTimeOfTravel( P1FractionOfPeriodPerPeriod, P1BPeriod, P1BDistance, P1APeriod, P1ADistance, P2FractionOfPeriodPerPeriod, P2BPeriod, P2BDistance, P2APeriod, P2ADistance, P3FractionOfPeriodPerPeriod, P3BPeriod, P3BDi...
3,859
1,288
# from NCNet import shutil import torch from torch.autograd import Variable from os import makedirs, remove from os.path import exists, join, basename, dirname import collections from lib.dataloader import default_collate def collate_custom(batch): """ Custom collate function for the Dataset class * It does...
3,001
974
# 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") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def fastIo(): http_archive( name = "fast_io", build_file ...
658
323
import torch from src.util.metrics._ssim import ssim __all__ = ["ssim_per_frame"] def ssim_per_frame(pred, gt): assert pred.shape == gt.shape _, sequence, _, _, _ = pred.shape SSIM = [] for s in range(sequence): SSIM.append(ssim(pred[:, s], gt[:, s]).item()) return SSIM if __name__ ==...
584
238
# # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type """ The nxos_logging_global config file. It is in this file where the current confi...
7,297
2,164
ordem = list() for c in range(0, 5): n = int(input('Digite um numro: ')) if c == 0 or n > ordem[-1]: ordem.append(n) print('Numero adicionado na ultima posição') else: pos = 0 while pos < len(ordem): if n <= ordem[pos]: ordem.insert(pos, n) ...
860
288
import json import pyaml import yaml from lib.util import Util from lib.parser import Parser import logging import traceback import glob import os logging.basicConfig(level=logging.DEBUG) log = logging.getLogger('NemoParser') class NemoParser(Parser): """Parser methods for nemo project type """ def __in...
1,987
574
#!/usr/bin/env python3 # testNamedTuples.py """ Test named tuples. """ import unittest from collections import namedtuple class TestNamedTuples(unittest.TestCase): """ Test behavior of named tuples. """ def test_functionality(self): """ Nested named tuples work more or less as expected. L...
2,375
789
import requests from bs4 import BeautifulSoup import json def get_projects(github_user, query): URL = f"https://github.com/{github_user}?tab=repositories&q={query}&type=source" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") projects = soup.body.find("ul", {"data-filterable...
1,234
393
codigos = [100, 101, 102, 103, 104, 105] comidas = ['Cachorro Quente', 'Bauru Simples', 'Bauru com ovo', 'Hamburguer', 'ChesseBurguer', 'Refrigerante'] precos = [1.20, 1.30, 1.50, 1.20, 1.30, 1.0] codigo = True n_pedido = 1 pedido = [] while codigo != 0: print("\nPedido n°", n_pedido) codigo = int(input("Digit...
971
416
from torch.utils.data import DataLoader from torchvision import transforms import torchvision.datasets as datasets from torchvision.transforms import ToTensor from transformations.image_random_crop import ImageRandomCropFactory from transformations.image_resize import ImageResize from transformations.image_to_ten...
1,587
471
# coding: utf-8 """ rokka.io digital image processing done right. [Documentation](https://rokka.io/documentation). [Changelog](https://api.rokka.io/changelog.md). # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ impo...
3,944
1,244
import json import dash import dash_cytoscape as cyto import dash_html_components as html from dash.dependencies import Input, Output # Dashインスタンスの生成 app = dash.Dash(__name__) # ネットワークの構成要素の定義 elements = [ # ノードの定義 {"data": {"id": "A", "name": "Alice", "age": 14},}, {"data": {"id": "B", "name": "Bob", "a...
1,843
840
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from aws_cdk.aws_ec2 import SubnetConfiguration, SubnetType # Subnets for undistinguished render farm back-end infrastructure INFRASTRUCTURE = SubnetConfiguration( name='Infrastructure', subnet_type=Sub...
1,902
663
from unittest import TestCase from ghgi.origin import Origin from ghgi.reference import Reference class TestOrigin(TestCase): def test_origins_valid(self): try: Origin.validate() except: self.fail('Origins failed to validate') def test_origins_meta(self): # m...
1,591
408
# this script reads the data into a parquet format. # we specify types to make the data "cleaner" import pandas as dd print("converting bureau balance") bureau_balance = dd.read_csv('data/bureau_balance.csv') bureau_balance['STATUS'] = bureau_balance.STATUS.astype('category') bureau_balance.to_parquet('raw_data/burea...
4,998
1,868
"""Solution to an exercise from Think Python: An Introduction to Software Design Copyright 2010 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html This program requires Gui.py, which is part of Swampy; you can download it from thinkpython.com/swampy. """ import os, sys from swampy.Gui import * ...
676
228
from setuptools import setup, find_packages setup( name="keras-deeplab-v3-plus", version="1.0", packages=["deeplab"], install_requires=["tensorflow>2.0.0"] )
176
71
from django.core.exceptions import PermissionDenied from django.http import Http404 from rest_framework import exceptions, metadata from rest_framework.request import clone_request class ActionMeta(metadata.SimpleMetadata): """ Metadata class for determining metadata based on the used serializer. """ ...
1,742
410
import math import os import random import torch from tensorboardX import SummaryWriter from torch import nn from torch.autograd import Variable from torch.backends import cudnn from torch.optim import Adam from tqdm import tqdm from memory import ReplayMemory from utils import process_state class DQAgent: """ ...
10,051
2,822
from pymongo import MongoClient from config import config import os import urllib.parse def upload_to_mongodb(timeline, db, coolections): client = MongoClient(os.environ.get('mongodb_connect_string')) db = client[db] mongo_timeline_collection = db[coolections] mongo_timeline_collection.delete_many({}) ...
457
146
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config from typing import Dict # -- Path setup -----------------------------------...
8,968
2,658
from fastapi import APIRouter, status from rdkit.Chem import MolFromSmiles, RDKFingerprint from rdkit.DataStructs import FingerprintSimilarity, CreateFromBitString, BulkTanimotoSimilarity from app import main, schemas smiles_router = APIRouter() @smiles_router.post("/add-to-hash", status_code=status.HTTP_201_CREATE...
1,501
526
from django.urls import path from .views import ( create_booking, generate_payment, mark_booking_as_error, register_booking_event, get_booking_by_session, ) app_name = 'bookings' urlpatterns = [ path(r'generate/payment/', generate_payment, name='generate-payment'), path(r'create/booking/'...
730
254
import numpy as np import pdb class BaselineAgent(): def __init__(self, mdp): self.mdp = mdp self.DECELERATE = -4. # in actions [-2., -1., 0, 1., 2.] self.ACCELERATE = 1 # in actions [-2., -1., 0, 1., 2.] def act(self, state): ttc, _ = self.mdp._get_smallest_TTC(state) if ttc <= 10: return self.DECELER...
358
174
#!/usr/bin/python # # Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
24,300
7,531
import chromedriver_binary # これは必ず入れる from selenium import webdriver from selenium.webdriver.chrome.options import Options import os import time import yaml import datetime import numpy as np import textwrap from bs4 import BeautifulSoup import requests from fastprogress import progress_bar import slackweb import war...
5,013
1,854
import logging import sys import xarray as xr # http://xarray.pydata.org/ from metpy.units import units import metpy.calc as mpcalc from czml3 import Packet from czml3.properties import ( # Billboard, # Clock, Color, # Label, # Point, # Material, # Model, # ViewFrom, # Orientation...
5,354
1,621
from marshmallow import Schema from marshmallow.fields import String from marshmallow.validate import Length class AuthenticateSchema(Schema): email = String(required=True) password = String( required=True, load_only=True, validate=( Length(min=8, max=255) ), ...
366
111
from tensorflow.keras.layers import Input, Add, Dropout, Permute, add, concatenate, UpSampling2D from tensorflow.keras.layers import Convolution2D, ZeroPadding2D, MaxPooling2D, Cropping2D, Conv2D, BatchNormalization from tensorflow.compat.v1.layers import conv2d_transpose from tensorflow.keras.models import Model from ...
4,616
1,771
# Hint: You may not need all of these. Remove the unused functions. from hashtables import (HashTable, hash_table_insert, hash_table_remove, hash_table_retrieve, hash_table_resize) class Ticket: def __init__(self, s...
981
296
#!/usr/bin/env python # pylint: disable=bad-whitespace, line-too-long '''User interface submodule for dGraph scene description module based on glfw David Dunn Feb 2017 - created ALL UNITS ARE IN METRIC ie 1 cm = .01 www.qenops.com ''' __author__ = ('David Dunn') __version__ = '1.6' __all__ = [] from dGraph.ui...
2,546
875
import abc import asyncio import fnmatch from abc import ABC from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Tuple @dataclass class Notification: topic: str subject_id: str data: dict class Handler(ABC): @abc.abstractmethod async def handle(se...
1,855
520
from django.urls import reverse from social_django.models import UserSocialAuth from rest_framework.test import APITestCase from ...users.models import User from ...changeset.tests.modelfactories import SuspicionReasonsFactory from ..models import ChallengeIntegration class TestChallengeIntegrationListCreateView(AP...
8,106
2,481
import random import cv2 import numpy as np import torch from torchvision.transforms import RandomApply, Compose class PrepareImageAndMask(object): """Prepare images and masks like fixing channel numbers.""" def __call__(self, data): img = data['input'] img = img[:, :, :3] # max 3 channels ...
12,475
4,146
import re import os # import shutil import sys import tempfile import hashlib # import sys import json from operator import itemgetter from bdscan import classComponent, classNugetComponent, classNpmComponent, classMavenComponent, classPyPiComponent, \ classConanComponent, classCargoComponent, classHexComponent, c...
21,391
5,977
from django.db import models from django.utils.translation import gettext as _ class QuestionCase(models.Model): input = models.TextField( _('Question Case\'s Input'), ) output = models.TextField( _('Question Case\'s Output'), ) question = models.ForeignKey( 'questions.Qu...
464
138
from django.db import models from django.contrib.auth import get_user_model from django.utils import timezone # Saving media locally is not a good practice # for a big social network actually. GoogleCloud or AWS # migth be a better alternative def get_user_image_path(instance, filename): return f'users/{instanc...
1,334
418
# ABC104b import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) s = input()[:-1] #print(s.count('C', 2, -1)) if (s[0] != 'A' or s.count('C', 2, -1) != 1): print('WA') # print('hi') exit() cPos = s.find('C', 2, -1) if (s[1:cPos].islower() and s[cPos + 1:].islower()): # print('hi') print...
350
171
import json from tqdm import tqdm import re from sys import argv f = open(argv[1]) data = f.read() rows = re.findall('{.*?}',data) f = open('{}.json'.format(argv[1]),'w') for row in tqdm(rows): f.write(row) f.write('\n') f.close()
242
104
#!/usr/bin/env python """ File Name : s01-make_tree_dataset.py Author : Max Bernstein Created On : 2019-07-12 Last Modified : 2019-12-17 Description : A program to prep and rename sequences in order to make tree anlaysis easier Dependencies : py-biopython Usage ...
2,761
909
#!/usr/bin/env python3.5 """Spacecraft made up of Modules used in conjunction with morse for simulation""" import math import operator as op import numpy as np import jsonpickle as pickler from .craftmodule import Module as Module from .scripts import modControl as modCon _authors_ = ["Mark A Post", "Rebecca Wardle...
39,391
11,883
# -*- coding: utf-8 -*- """ Created on Fri Mar 8 14:43:01 2019 @author: astar """ import random import math import matplotlib.pyplot as plt from time import clock def generate_random_nodes(size): return [(random.uniform(0, size), random.uniform(0, size)) for i in range(size)] def read_map(source): with ...
3,344
1,232
import bs4 import json import os import re import requests import sqlite3 from . import renderer def get_webpage(*args, **kwargs): """ get_webpage(...) -- request webpage content / text """ return requests.get(*args, **kwargs).text.encode('ISO-8859-1').decode('utf-8') def map_num(s): """ map_num(str) --...
5,625
2,067
import os from subprocess import getstatusoutput as cmd from __main__ import args def clean_env(): for var in [e for e in os.environ.keys() if e.startswith("_SCRAM_SYSVAR_")]: val = os.environ[var] del os.environ[var] var = var[14:] if val: os.environ[var] = val ...
423
142
def _bind_context(function): """ Lifts function from ``RequiresContext`` for better composition. In other words, it modifies the function's signature from: ``a -> RequiresContext[env, b]`` to: ``Container[env, a, c]`` -> ``Container[env, b, c]`` .. code:: python >>> from returns.conte...
952
277
import discord from discord.ext import commands import sys def mods_or_owner(): """ Check that the user has the correct role to execute a command """ def predicate(ctx): return commands.check_any(commands.is_owner(), commands.has_role("Moderator")) return commands.check(predicate) class ...
2,112
641
import modelexp from modelexp.experiments.sas import Saxs from modelexp.models.sas import Cube import numpy as np import random app = modelexp.Cli() app.setExperiment(Saxs) modelRef = app.setModel(Cube) modelRef.addModel(np.linspace(1e-2, 0.5, 300)) modelRef.setParam('a', 50) modelRef.setParam('sldCube', 45e-6) mode...
815
374
import os from conda_build.metadata import MetaData import requests import hashlib import tarfile import tempfile from glob import glob from shutil import move, copy from os.path import join, normpath, dirname from os import makedirs, getenv from sys import exit import patch import re def get_tar_xz(url, md5): tm...
3,621
1,264
import argparse import os import torch import numpy as np from cyolo_score_following.dataset import load_dataset, collate_wrapper, iterate_dataset, CLASS_MAPPING from cyolo_score_following.utils.data_utils import FPS from cyolo_score_following.models.yolo import load_pretrained_model from torch.utils.data import Dat...
4,404
1,437
#!/usr/bin/env python # -*- coding: utf-8 -*- """segnet package file tf_record Segmentation_base_class -> SegmentationInput -> SegmentationCompile -> SegmentationSummaries -> Segmentation_model_utils -> Segmentation_train """ from datetime import datetime from tqdm import trange from ..net_utils import ScoreRecor...
16,344
4,897
from test_dali import Mat, random, MatOps, Graph num_examples = 100 example_size = 3 iterations = 150 lr = 0.01 X = random.uniform( 0.0, 1.0 / example_size, size=(num_examples, example_size) ) ones = Mat.ones((X.shape[1], 1)) Y = X.dot(ones) X = MatOps.consider_constant(X) Y = MatOps.consider...
757
307
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from legion.sdk.models.base_model_ import Model from legion.sdk.models import util class TrainingConfiguration(Model): """NOTE: This class is auto generated by th...
1,717
503
""" Functions: search_gene find_antibodies """ # _search_gene_raw # _parse_gene_search # # _parse_gene_page_keyvalue # _parse_gene_page_table # _group_keyvalue_by_antibody def search_gene(gene_name, wait=5): # Return a URL or None if gene not found. import urlparse html = _search_gene_raw(gene_name, w...
9,839
3,304
import os from src.domain.ErrorTypes import ErrorTypes from src.utils.code_generation import CodeGenerationUtils from src.validity import IncomingEdgeValidityChecker # Add other join options as well # How about join cascades # Add necessary checks for stream-stream, stream-batch joins... # Note that for stream-stati...
1,628
503
## Automatic type case and broadcast import pyOcean_cpu as ocean import sys def exceptionMsg() : print("Expected error: %s" % str(sys.exc_info()[1])) def failTest(command) : try : eval(command) except : exceptionMsg() a = ocean.int16([1,2,3]) b = ocean.float([1]) print(a+b) ocean.setAutoTypec...
464
201
from setuptools import setup with open("README.md", "r") as f: long_description = f.read() setup(name='nbquestions', version='0.0.1', description='Helper functions for creating questions', long_description=long_description, long_description_content_type="text/markdown", url='http://g...
502
155