text
string
size
int64
token_count
int64
""" Created on 22 Feb 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) source repo: scs_analysis """ import optparse # -------------------------------------------------------------------------------------------------------------------- class CmdCSVJoin(object): """unix command line handler""" ...
3,410
953
import os from easymq.mq import MQ def receive(headers, body): print("---->", body) mq = MQ( mq_user=os.environ.get("mq_user"), password=os.environ.get("password"), host_and_ports=[ (os.environ.get("host"), os.environ.get("port")), ], func=receive, queue_name="/queue/test_queue"...
338
129
# -*- coding: utf-8 -*- from hamcrest import * from test.base import BaseTestCase from amplify.agent.common.util.text import ( decompose_format, parse_line, parse_line_split ) __author__ = "Grant Hulegaard" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __license__ = "" __maintainer__ = "Grant...
12,383
4,425
#!/usr/bin/env python # Copyright 2014 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 ...
9,982
3,750
from random import randint import numpy as np from collections import Counter from pprint import pprint import time # Aufgaben Siehe Buch print('-------------Aufgabe 1-------------') outcomes = [ randint(1,6) for _ in range(10000)] even_pips = [ x for x in outcomes if x % 2 == 0] greater_two = [ x for x in outcomes i...
6,149
1,946
from pygears import gear, Intf from pygears.lib import dreg, decouple, saturate, qround @gear def iir_1dsos(din, *, a, b, gain): # add input gain and init delayed inputs zu0 = din * gain zu1 = zu0 | dreg(init=0) zu2 = zu1 | dreg(init=0) # perform b coefficient sum a1 = (zu1 * b[1]) + (zu2 * ...
2,183
890
#!/usr/bin/env python u""" read_iceye_h5.py Written by Enrico Ciraci' (03/2022) Read ICEYE Single Look Complex and Parameter file using GAMMA's Python integration with the py_gamma module. usage: read_iceye_h5.py [-h] [--directory DIRECTORY] TEST: Read ICEye Single Look Complex and Parameter. optional arguments: ...
3,752
1,212
#!/usr/bin/env python """Calculate transformation matrices and broadcast transform from robot's base to head markers.""" import rospy import tf import math from PyKDL import Vector, Frame, Rotation if __name__ == '__main__': rospy.init_node('baxter_find_transformation') listener = tf.TransformListener() b...
1,877
698
# Generated by Django 3.2.9 on 2022-01-10 12:39 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('car', '0003_auto_20220110_1507'), ] operations = [ migrations.AddField( model_name='sale', ...
475
169
import pandas as pd import pytask from src.config import BLD @pytask.mark.depends_on(BLD / "data" / "raw_time_series" / "reproduction_number.csv") @pytask.mark.produces(BLD / "data" / "processed_time_series" / "r_effective.pkl") def task_prepare_rki_r_effective_data(depends_on, produces): df = pd.read_csv(depend...
509
207
import numpy as np def convolucion(Ioriginal, kernel): '''Método encargado de realizar una convolución a una imagen Entrada: Ioriginal - imagen original en forma de matríz kernel - kernel para barrer la imagen Salida: res - imagen resultante''' #fr - filas, cr - columnas fr = len(Ioriginal)-(len(kernel)-1) c...
701
295
import os from distutils.core import setup from setuptools import find_packages package = 'vtr_utils' version = "0.1.0" packages = find_packages() def get_package_data(package): """ Return all files under the root package, that are not in a package themselves. """ walk = [(dirpath.replace(packag...
1,124
363
from collections import defaultdict import pytest from radical_translations.agents.models import Organisation, Person pytestmark = pytest.mark.django_db @pytest.mark.usefixtures("vocabulary") class TestOrganisation: def test_agent_type(self, title): obj = Person(name="person name") obj.save() ...
2,925
983
# -*- coding: utf-8 -*- from odoo import http from odoo.addons.website_sale.controllers.main import WebsiteSale from odoo.http import request class WebsiteSale(WebsiteSale): @http.route(['/shop/pricelist']) def pricelist(self, promo, **post): order = request.website.sale_get_order() coupon_st...
1,557
508
from go.apps.tests.view_helpers import AppViewsHelper from go.base.tests.helpers import GoDjangoTestCase class TestHttpApiViews(GoDjangoTestCase): def setUp(self): self.app_helper = self.add_helper(AppViewsHelper(u'http_api')) self.client = self.app_helper.get_client() def test_show_stopped(...
4,462
1,342
# -*- coding: utf-8 -*- # Copyright: (c) 2019-2021, Dell EMC """Helper module for PowerStore""" import logging from pkg_resources import parse_version provisioning_obj = None def set_provisioning_obj(val): global provisioning_obj provisioning_obj = val def prepare_querystring(*query_arguments, **kw_query_...
5,306
1,480
#!/usr/bin/env python3 # # Author: # Tamas Jos (@skelsec) # import io import enum #https://msdn.microsoft.com/en-us/library/windows/desktop/ms680388(v=vs.85).aspx class MinidumpMiscInfo2Flags1(enum.IntFlag): MINIDUMP_MISC1_PROCESS_ID = 0x00000001 #ProcessId is used. MINIDUMP_MISC1_PROCESS_TIMES = 0x00000002 #Proce...
5,680
2,348
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=redefined-builtin """Tests basic functionality of the transpile function""" from qiskit import QuantumReg...
2,565
869
import random class Calculator(): symbol=["+","-","*","/","(",")"] def __init__(self): pass def cal(self,s): if self.isnumber(s[0]): return s elif s[0]=="error": return ["error",s[1]] elif "(" in s[0] or ")" in s[0]: #or "^" in s[0]: el=sel...
7,039
2,034
# import os # import uuid # import numpy as np # import pandas as pd # import pytest # mocked_uuid = "00000000-0000-1111-00000-000000000000" # @pytest.fixture(scope="session") # def data(): # filename = "bsd.picarro.1minute.248m.dat" # dir_path = os.path.dirname(__file__) # test_data = "../data/proc_t...
624
269
from setuptools import setup with open('README.md') as f: long_description = f.read() setup( name='break_my_python', version='0.0.2', description='This package tries to breaks your python interpreter, do not install it', long_description=long_description, author='Jonathan J. Helmus', autho...
891
288
""" MIT License Copyright (c) 2020-present noaione 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 without limitation the rights to use, copy, modify, merge, publis...
12,039
4,055
# This software is open source software available under the BSD-3 license. # # Copyright (c) 2020 Triad National Security, LLC. All rights reserved. # Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights # reserved. # Copyright (c) 2020 UT-Battelle, LLC. All rights reserved. # # Additional copyright...
11,612
3,093
import sys import os.path as osp import math import torchvision.utils sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from data import create_dataloader, create_dataset # noqa: E402 from utils import util # noqa: E402 def main(): dataset = 'REDS' # REDS | Vimeo90K | DIV2K800_sub opt = {} ...
3,682
1,370
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
3,663
1,073
import argparse import numpy as np import pandas as pd import sklearn.metrics import sklearn.metrics parser = argparse.ArgumentParser(description='') parser.add_argument('--output_path', type=str, help='') parser.add_argument('--answer_path', type=str, help='') parser.add_argument('--task', type=str, default="binary"...
3,067
1,139
from django.apps import AppConfig class ChainlicenseConfig(AppConfig): name = 'ChainLicense'
99
32
# Copyright (c) Trainline Limited, 2016-2017. All rights reserved. See LICENSE.txt in the project root for license information. from os.path import join import unittest from mock import patch from agent.find_deployment import find_deployment_dir_win class Fake(object): def __init__(self, **kwargs): self._...
1,403
420
import os import logging import argparse import numpy as np import tensorflow as tf from keras_preprocessing.text import Tokenizer from tqdm import tqdm from data import DataLoader class EmbeddingsBuilder: def __init__(self, args): logging.info('initializing...') self.args = args self.da...
2,585
823
############################################################################# # # Author: Michel F. SANNER # # Copyright: M. Sanner and TSRI 2015 # ######################################################################### # # $Header: /mnt/raid/services/cvs/mglkeyDIST/mglkey/__init__.py,v 1.1.1.1 2016/12/07 23:27:34 sa...
430
175
""" Profile ../profile-datasets-py/div83/027.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div83/027.py" self["Q"] = numpy.array([ 1.51831800e+00, 2.02599600e+00, 2.94787100e+00, 3.99669400e+00, 4.71653800e+00, 4.89106600e+00, 5.1439...
13,342
10,436
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao File: breakoutgraphics.py Name: 林坤毅 Jordan ------------------------- This python file will create a class named BreakoutGraphics for the break out game. This class will contain the building b...
10,386
3,208
from random import shuffle a1 = str(input('Digite o nome de um aluno: ')) a2 = str(input('Digite o nome de outro aluno: ')) a3 = str(input('Digite o nome de mais outro aluno: ')) a4 = str(input('Digite o nome do último aluno: ')) lista = [a1, a2, a3, a4] shuffle(lista) print(f'A ordem de apresentação é: \033[34m{lista}...
329
138
# flake8: noqa """ Copyright 2021 - Present Okta, 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 ...
3,940
1,035
import datetime import unittest import luigi import numpy as np from netCDF4 import Dataset from iasi.compression import (CompressDataset, CompressDateRange, DecompressDataset) class TestCompression(unittest.TestCase): def test_dataset_compression(self): task = CompressDat...
1,478
458
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
6,310
1,847
import unittest import uuid from memory.client import MemoryClient from hailtop.aiocloud.aiogoogle import GoogleStorageAsyncFS from hailtop.config import get_user_config from hailtop.utils import async_to_blocking from gear.cloud_config import get_gcp_config PROJECT = get_gcp_config().project class BlockingMemoryC...
2,959
933
# feladat.py # 1. feladat # Írjon függvényt szokoev_e néven # A függvény térjen vissza igaz értékkel, ha a paraméterben megadott évszám szőköév def szokoev_e(ev:int) -> bool: # 2. feladat # A függvény bemenő paraméterei az a, b, c egész számok # Írjon kódot amely eredményeként az a változóba lesz a legnagyobb szám,...
990
441
#from editgui import EditGUI #from only_layout import OnlyLayout as EditGUI
76
23
import librosa import numpy as np from . import base from . import spectral class OnsetStrength(base.Computation): """ Compute a spectral flux onset strength envelope. Based on http://librosa.github.io/librosa/generated/librosa.onset.onset_strength.html Args: n_mels (int): Number of mel ban...
1,210
425
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog import sys from .readNanoscopeForceRamps import * import matplotlib.pyplot as plt from ..qt5_ui_files.ForceRampGUI import * from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar) import os import math from ..qt5_ui_fi...
2,496
1,057
"""Create your tests for the admin app here.""" import pytest from django.contrib.auth import get_user_model from django.urls import reverse pytestmark = pytest.mark.django_db User = get_user_model() class TestUserAdmin: """Test the admin interface.""" def test_changelist(self, admin_client): """Tes...
1,250
372
from flask_apispec import MethodResource, marshal_with, doc, use_kwargs from webargs import fields from ..models import Dataset from ..core import cache from .utils import first_or_404 from ..schemas.dataset import DatasetSchema class DatasetResource(MethodResource): @doc(tags=['dataset'], summary='Get dataset by...
1,129
360
import numpy as np from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge from graph_tiger.measures import run_measure def test_measures(): measure_ground_truth = { # graph order: o4,...
2,194
1,151
import verifyController import pyodbc from PyQt5.QtWidgets import QMessageBox from PyQt5 import QtCore, QtGui, QtWidgets from PySide2.QtCore import (QCoreApplication, QMetaObject,QSize,Qt) from PySide2.QtGui import (QCursor, QFont,QIcon) from PySide2.QtWidgets import * from PySide2 import QtCore, QtGui, QtWidg...
13,679
4,151
"""Association mining -- apriori algo""" __author__ = 'thor' from numpy import * # Modified from: # Everaldo Aguiar & Reid Johnson (https://github.com/cse40647/cse40647/blob/sp.14/10%20-%20Apriori.ipynb) # # Itself Modified from: # Marcel Caraciolo (https://gist.github.com/marcelcaraciolo/1423287) # # Functions to c...
13,195
3,924
try: from setuptools import setup except ImportError: from distutils.core import setup setup( description='Tech@NYU API Python Client', author='TechatNYU', url='https://github.com/TechAtNYU/pytnyu', author_email='hello@techatnyu.org', version='0.0.4', install_requires=['requests'], ...
397
146
import spidev columns = [0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8] LEDOn = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] LEDOff = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] LEDEmoteSmile = [0x0,0x0,0x24,0x0,0x42,0x3C,0x0,0x0] LEDEmoteSad = [0x0,0x0,0x24,0x0,0x0,0x3C,0x42,0x0] LEDEmoteTongue = [0x0,0x0,0x24,0x0,0x42,0x3C,0xC,0x0] LEDEmoteS...
2,949
1,352
#!/usr/bin/env python from datapackage_pipelines.wrapper import ingest, spew import logging, collections from pipeline_params import get_pipeline_param_rows from google.cloud import storage from contextlib import contextmanager from tempfile import mkdtemp import os import pywikibot import time from pywikibot.pagegener...
9,236
2,868
#!/usr/bin/env python import DIRAC from DIRAC import S_OK, S_ERROR from DIRAC.Core.Base import Script Script.setUsageMessage( """ Insert random trigger file into the File Catalog Usage: %s [option] lfn """ % Script.scriptName ) fcType = 'FileCatalog' Script.parseCommandLine( ignoreErrors = False ) options = S...
1,348
390
import pickle import networkx as nx import numpy as np import torch for name in ('cora', 'citeseer', 'pubmed'): with open(f'data/datasets/{name}.pkl', 'rb') as fin: dataset = pickle.load(fin) test_graph = dataset['original_graph'] e2i = dataset['edge2idx'] H = dataset['H'] node_fts = to...
1,037
405
import os import fnmatch import smtplib import email.mime.application import sys import subprocess from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from pathlib import Path home = str(Path.home()) # Return a string representing the user’s home directory fileFound = 0 # Number of f...
3,243
1,015
# 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 # d...
2,092
653
#!/usr/bin/python # -*- coding: UTF-8 -* from db.it.db_it_mgr import it_mgr __all__ = {"itSingleton"} class itSingleton(): def get_cmd_sql(self, sql): return it_mgr.get_cmd_sql(sql) it_singleton = itSingleton()
231
100
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from pathlib import Path from wildfires.utils import handle_array_job_args try: # This will only work after the path modification carried out in the job script. from specific import ( CACHE_DIR, SimpleCache, get_model, da...
25,437
12,359
#!/usr/bin/env python3 # Copyright (c) 2019, AT&T Intellectual Property. # All rights reserved. # # SPDX-License-Identifier: LGPL-2.1-only # """ Unit-tests for the qos_config.py module. """ from vyatta.res_grp.res_grp_config import ResGrpConfig TEST_DATA = { 'vyatta-resources-v1:resources': { 'vyatta-re...
1,954
732
#!/usr/bin/env python2.5 ############################################################################# ## ## file : objects.py ## ## description : see below ## ## project : Tango Control System ## ## $Author: srubio@cells.es, tcoutinho@cells.es, homs@esrf.fr $ ## ## ## $Revision: 2008 $ ## ## copyleft : A...
36,145
10,736
# coding=utf-8 # Copyright 2021 DeepMind Technologies Limited and 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...
5,877
1,787
import pytest import json import numpy as np @pytest.mark.parametrize("candidate, expected", [ (1.345, True), (-4.554, True), ('9999', True) ]) def test_number_please(candidate, expected): from hrm_code import number_please assert number_please(candidate) == expected def test_import_data(): ...
2,605
1,116
# Generated by Django 2.1.7 on 2019-05-10 09:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0043_auto_20190424_1029'), ] operations = [ migrations.RemoveField( model_name='statetransition', name='stat...
1,068
324
import re from abc import ABCMeta, abstractmethod from datetime import datetime from typing import Callable, Iterator from apache_beam.io import iobase from apache_beam.io.range_trackers import (LexicographicKeyRangeTracker, OffsetRangeTracker, ...
6,661
1,960
from stk_sequence import * from stk_tcp_server import * from stk_tcp_client import * from stk_data_flow import * from stk_options import stk_clear_cb import time class stk_callback: def __init__(self): self._caller = None self._mapobj = None pass def add_callback_ref(self,caller): self._caller = caller def ...
5,827
2,504
import numpy as np ## ## @brief function_description ## ## @param filename The filename ## ## @return description_of_the_return_value ## def readfile(filename): csvfile = open(filename, "r") if not csvfile: print "error" return -1 rows = [] for row in csvfile: if row[0] != '#' : # linhas ...
1,163
390
import numpy as np import cv2 as cv import os import shutil from skimage.util.shape import view_as_windows import torch.nn.functional as F import torch from functools import lru_cache @lru_cache(maxsize=None) def get_exp_decay_filter(filter_size=1, decay=.9, avg=True): side = 2 * filter_size + 1 filter = torc...
3,255
1,225
s = input().strip() res = [c for c in set(s.lower()) if c.isalpha()] if len(res) == 26: print("pangram") else: print("not pangram")
134
60
from __future__ import print_function import pkgutil import stream_decoders # this module decodes stream based protocols. # and resolves retransmissions. decoders= [] # __path__ is used to find the location of all decoder submodules for impimp, name, ii in pkgutil.iter_modules(stream_decoders.__path__): impload= ...
8,423
2,974
import logging import aioredis from app.core.config import REDIS_DSN, REDIS_PASSWORD logger = logging.getLogger(__name__) async def get_redis_pool(): return await aioredis.create_redis(REDIS_DSN, encoding='utf-8', password=REDIS_PASSWORD)
247
90
from math import pi u0 = 4.*pi*1E-7 # T m /A hbar = 1.0545718E-34 # J s # 1 T = kg s^-2 A-1 = J A^-1 m^-2 g = { '1H' : 267.513E6, # rad T^-1 s^-1 '13C': 67.262E6, '15N': -27.116E6, 'e': 176086E6 } # nuc_i, nuc_j: nucleus string. ex: '1H' # r_ij: distance in Angstroms DCC = lambda nuc_i, nuc_j, ...
1,434
911
import pathlib from typing import Any, Dict, List, Tuple from torchdata.datapipes.iter import IterDataPipe, Mapper, Filter from torchvision.prototype.datasets.utils import Dataset, DatasetConfig, DatasetInfo, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import path_comparator, hint_...
2,197
733
import numpy as np from math import sqrt def robot_distance_incorrect(robot_actual_location, hexagon_pixel_values): distance_to_get_back = [] distances = [] pixel_distance = [] for i in range(0, len(hexagon_pixel_values)): dist = sqrt((robot_actual_location[0] - hexagon_pixel_values[i][0]) ** ...
934
310
import warnings from typing import List from fastapi import APIRouter, FastAPI from fastapi.routing import APIRoute from fastapi.testclient import TestClient from pydantic import BaseModel def custom_generate_unique_id(route: APIRoute): return f"foo_{route.name}" def custom_generate_unique_id2(route: APIRoute)...
68,172
14,411
#!/usr/bin/env python # encoding: utf-8 #------------------------------------------------------------------------------ # Naked | A Python command line application framework # Copyright 2014 Christopher Simpkins # MIT License #------------------------------------------------------------------------------ #-----------...
11,880
2,757
""" Advent Of Code 2021 Day 7 Date: 07-12-2021 Site: https://adventofcode.com/2021/day/7 Author: Tayyrov """ import sys file1 = open('../input_files/day7_input', 'r') numbers = list(map(int, file1.readlines()[0].split(","))) numbers.sort() middle = numbers[len(numbers)//2] ans = 0 for n in numb...
366
174
import datetime import re import pytz from django.utils.timezone import make_aware, is_aware def seconds_resolution(dt): return dt - dt.microsecond * datetime.timedelta(0, 0, 1) def minutes_resolution(dt): return dt - dt.second * datetime.timedelta(0, 1, 0) - dt.microsecond * datetime.timedelta(0, 0, 1) ...
4,270
1,556
import json import operator import os import webbrowser from timeit import default_timer as timer from kivy.app import App from kivy.config import Config from kivy.properties import ObjectProperty from kivy.uix.stacklayout import StackLayout from nltk.stem.wordnet import WordNetLemmatizer Config.set('input', 'mouse',...
4,282
1,372
from tkinter import * import tkinter.ttk as ttk from PIL import ImageTk,Image """ root = Tk() canvas = Canvas(root, width = 300, height = 300) canvas.pack() img = ImageTk.PhotoImage(Image.open("output/collage1/FinalCollage.jpg")) canvas.create_image(0,0,anchor=NW, image=img) root.mainloop() """ root = Tk(...
1,244
450
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2021 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
10,817
3,145
import time import xappt @xappt.register_plugin class AutoAdvance(xappt.BaseTool): message = xappt.ParamString(options={"ui": "label"}) next_iteration_advance_mode = xappt.ParamInt(choices=("no auto advance", "auto advance")) def __init__(self, *, interface: xappt.BaseInterface, **kwargs): super...
3,283
898
""" Discovery: broadcasts a query, attempting to discover all running RPyC servers over the local network/specific subnet. """ import socket import select import struct __all__ = ["discover_servers"] UDP_DISCOVERY_PORT = 18813 QUERY_MAGIC = "RPYC_QUERY" MAX_DGRAM_SIZE = 100 def discover_servers(subnet = "255.255.25...
962
370
try: import exceptions except ImportError: # Python 3 import builtins as exceptions class ObjectToReturn: def __init__(self, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): exception = getattr(exceptions, name) raise ...
335
96
from django.db import models # Create your models here. class quiz_short(models.Model): AssignNum = models.ForeignKey('teacher.Assignment', on_delete=models.CASCADE) Question = models.TextField() Answer = models.TextField() def __str__(self): return "AssignNum : %s, question: %s Answer: %s" % ...
2,068
661
# coding: utf-8 from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals
165
47
"""Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ import math import numpy as np def largest_prime_factor_naive(number): """ Let the given number be n and let k = 2, 3, 4, 5, ... . For each k, if it is a factor of n ...
3,479
1,057
class DataStream: async def create_private_listen_key(self) -> dict: """**Create a ListenKey (USER_STREAM)** Notes: ``POST /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream """ retu...
1,312
424
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack, LLC. # 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...
2,484
810
""" This module defines the class QueryUniprot which connects to APIs at http://www.uniprot.org/uploadlists/, querying reactome pathways from uniprot id. * map_enzyme_commission_id_to_uniprot_ids(ec_id) Description: map enzyme commission id to UniProt ids Args: ec_id (str): enzyme commissio...
8,850
2,987
import torch from network.siamese import SiameseNet from network.resnet import ResidualEmbNetwork import os import numpy as np from utils.datasets import DeepFashionDataset from torchvision.transforms import Compose from torchvision.transforms import Resize from torchvision.transforms import ToTensor from torchvision.t...
1,624
616
from enum import Enum # ifu ifu = {"name": "IFU", "geo_lat": 47.476180, "geo_lon": 11.063350} # tereno stations tereno_stations = [ {"name": "Fendth", "geo_lat": 47.83243, "geo_lon": 11.06111}, {"name": "Grasswang", "geo_lat": 47.57026, "geo_lon": 11.03189}, {"name": "Rottenbuch", "geo_lat": 47.73032, "ge...
507
260
#!/usr/bin/python2.6 """ Here a comment starts, with 3 quotation marks. In the same way, the comment ends ... Purpose: Draw a base map of the CORDEX domain Selected projection: Lambert Conformal Projection Date: Sept. 26, 2018 Author: S. STRADA REFERENCES: Basemap Tool http://basemaptutorial.re...
2,217
758
from . import characters from . import teams from . import hotmaps from . import pygwrap import pygame from . import maps import collections from . import image from . import pfov import random from . import stats from . import rpgmenu from . import animobs from . import effects from . import enchantments from . import...
24,369
7,779
import unittest import redis from jobQueue import JobQueue from tangoObjects import TangoIntValue, TangoJob from config import Config class TestJobQueue(unittest.TestCase): def setUp(self): if Config.USE_REDIS: __db = redis.StrictRedis( Config.REDIS_HOSTNAME, Config.REDIS_PO...
4,096
1,407
#!/usr/bin/python import sys sys.path.append('./') import QuantLib as ql from hybmc.simulations.Payoffs import Payoff, Fixed, ZeroBond, LiborRate, Cache, Asset from hybmc.simulations.AmcPayoffs import AmcSum from hybmc.products.Product import Product def DiscountedPayoffFromCashFlow(cf, obsTime, payOrReceive, discY...
6,891
2,299
import re from streamlink.plugin import Plugin from streamlink.plugin.api import validate from streamlink.stream import HTTPStream from streamlink import NoStreamsError class Tamago(Plugin): _url_re = re.compile(r"https?://(?:player\.)?tamago\.live/w/(?P<id>\d+)") _api_url_base = "https://player.tamago.liv...
1,571
520
""" Name: modules.py Desc: This script defines some base module for building networks. """ from typing import Any import torch import torch.nn as nn import torch.nn.functional as F class UNet_down_block(nn.Module): def __init__(self, input_channel, output_channel, down_size=True): super(UNet_down_block,...
17,811
7,394
import os from flask_unchained import AppConfig class Config(AppConfig): WEBPACK_MANIFEST_PATH = os.path.join( AppConfig.STATIC_FOLDER, 'assets', 'manifest.json') class ProdConfig: # use relative paths by default, ie, the same host as the backend WEBPACK_ASSETS_HOST = '' class StagingConfig(P...
341
117
# Copyright 2014 Isotoma 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/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
2,458
724
import xxhash import numpy as np from base.grid import SimpleGRID import scipy.sparse as SP h = xxhash.xxh64() s_to_i = lambda x,size : size*x[0]+x[1] i_to_s = lambda x,size : (x%size,x//size) def hash(x): h.reset() h.update(x) return h.digest() class Indexer(object): def __init__(self): ...
4,197
1,444
import random import numpy as np import pytest import tempfile import shutil from idpflex import properties as ps from idpflex.properties import SecondaryStructureProperty as SSP class TestRegisterDecorateProperties(object): def test_register_as_node_property(self): class SomeProperty(object): ...
14,324
4,942
from os.path import join def create_particle_file_name(folder_path: str, img_number: int, coord_indx: int, ext: str) -> str: file_name = str(img_number) + 'particle' + str(coord_indx) + '.' + ext return join(folder_path, file_name)
272
94
import logging import torch import torch.nn as nn import torch.nn.functional as F from .... import extensions as E from . import accuracy as A logger = logging.getLogger('global') def _reduce(loss, reduction, **kwargs): if reduction == 'none': ret = loss elif reduction == 'mean': normalizer...
13,807
4,813