text
string
size
int64
token_count
int64
import io import zipfile import csv from util.ncconv.experimental.ocg_converter.subocg_converter import SubOcgConverter class CsvConverter(SubOcgConverter): # __headers__ = ['OCGID','GID','TIME','LEVEL','VALUE','AREA_M2','WKT','WKB'] def __init__(self,*args,**kwds): self.as_wkt = kwds.pop('as_wkt'...
4,200
1,342
import torch import torch.nn as nn class SqueezeModule(nn.Module): def forward(self, x: torch.Tensor) -> torch.Tensor: return x.squeeze() class GapSqueezeModule(nn.Module): """ global average pooling and squeezing """ def __init__(self): super().__init__() self.gap = nn.Adaptive...
839
316
""" Example shows how to use UIAnchorWidget to position widgets on screen. Dummy widgets indicate hovered, pressed and clicked. """ import arcade from arcade.gui import UIManager from arcade.gui.widgets import UIDummy from arcade.gui.widgets.layout import UIAnchorLayout class UIMockup(arcade.Window): def __init_...
1,634
518
import os import glob import pickle import sys import tensorflow as tf from numba import cuda from python_tools.OSUtils import ensure_dir from offline_predict import get_boxes_from_detection_predictions_data, convert_boxes_to_bboxes, predict_on_image_list, load_skeleton_model DETECTION_RESEARCH_FOLDER = os.path.expand...
3,897
1,377
#!/usr/bin/python import os import csv import time from datetime import datetime import requests from bs4 import BeautifulSoup url = 'https://www.fundsexplorer.com.br/ranking' # Data Cleansing # 'R$' => '' # '%' => '' # '.0' => '' # '.' => '' # ',' => '.' # 'N/A' => '' print("Starting...{}".format(datetime.now())...
1,234
465
""" Module 3D Point Selector Provides functionality view slices and to select points in multiplanar reconstructions. """ import os, time, sys import numpy as np import visvis as vv from visvis.utils.pypoints import Point, Pointset, Aarray import OpenGL.GL as gl import OpenGL.GLU as glu class VolViewer: ...
14,546
5,115
class Estimator: def __init__(self, name:str): self.name = name def getName(self) -> str : return self.name def setName(self, name:str): self.name = name def fit(self, X:[str], y:[int]): raise NotImplementedError() def predict(self, X:[str]): raise...
343
114
from flask import Flask, request, jsonify, Blueprint, json, make_response from flask_restplus import Resource, reqparse, Api, Namespace, fields from ..models.user_model import User api = Namespace('Register Endpoint', description='A collection of register endpoints for the user model') ns = Namespace('Users Endpoints...
4,386
1,210
import os import aiohttp from discord.ext import commands import xml.etree.ElementTree as ET from cogs.utils.dataIO import dataIO from .utils import checks from .utils.chat_formatting import escape_mass_mentions from .utils.chat_formatting import box from __main__ import send_cmd_help class Wolfram: def __init__(...
2,687
835
from abc import ABC,abstractmethod from Servers.ABCServer import ABCServer class ProbabilisticServer(ABCServer): @abstractmethod def sample_model(self): pass
176
49
from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncEngine from sqlalchemy.orm import sessionmaker from typing import AsyncGenerator from fastapi_crud.session import Session from fastapi_crud.router import ModelRouter from fastapi_crud.types import Model class FastapiCRUD: def __init__(self, engi...
718
198
"""update blog to add a title. Revision ID: 98f3e3ad195c Revises: 2d98c5165674 Create Date: 2019-12-02 22:58:10.377423 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '98f3e3ad195c' down_revision = '2d98c5165674' branch_labels = None depends_on = None def upg...
671
274
from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework import status from users.models import UserProfile from .serializers import MessageSerializer , ThreadSerializer from .models import ...
2,691
736
import PyQt5.QtWidgets as Qtw import PyQt5.QtCore as QtCore from widgets.labels import LabelsWidget DATE_FORMAT = 'yyyy-MM-dd' class TransactionDialog(Qtw.QDialog): """ A dialog used to edit a transaction """ def __init__(self, parent, model_cat, desc='', category=0, amount=0, date=''): supe...
3,691
1,239
import base64 import concurrent.futures import json import logging import sys import time import traceback as tb import uuid from google.api_core import retry from google.cloud import pubsub_v1 import octue.exceptions import twined.exceptions from octue.cloud.credentials import GCPCredentialsManager from octue.cloud.p...
20,416
5,275
from collections import defaultdict class Graph: metro = ['El Rosario', 'Instituto del Petroleo', 'Tacuba', 'Hidalgo', 'Tacubaya', 'Deportivo 18 de Marzo', 'Centro Medico', 'Mixcoac', 'Balderas', 'Bellas Artes', 'Guerrero', 'Martin Carrera', 'Zapata', 'Chabacano', 'Salto del...
1,978
895
# coding: utf-8 """ Octopus Server API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a Generated by: https://github.com/swagger-api...
9,807
3,108
# ###################### # Some useful utilities. # ###################### import json, os, pickle def listPrettyPrint(l, n): """Prints a list l on n columns to improve readability""" if(n == 5): for a,b,c,d,e in zip(l[::5],l[1::5],l[2::5],l[3::5],l[4::5]): print('{:<22}{:<22}{:<22}{:<22}...
1,691
699
#!/usr/bin/env python3 from algutils.primes import cached_primes def factorise(n): if n <= 0: raise ValueError("n must be a positive integer") ps = cached_primes.get_primes_list(min_lim=int(n**.5) + 1) ret = {} for p in ps: if n == 1: break if p**2 > n: # n is prime break i...
489
211
# -*- coding:utf8 -*- # Copyright (c) 2020 PaddlePaddle Authors. 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 # # ...
1,133
337
from .domain_sampler import SamplingError, SplitSampler from .feature_sampler import FeatureSampler, LateFeatureSampler from .halton import HaltonSampler from .cross_entropy import (CrossEntropySampler, ContinuousCrossEntropySampler, DiscreteCrossEntropySampler) from .random_sampler import RandomSampler from .bayes...
627
185
from setuptools import setup setup(name='gym_iotmarket', version='0.0.1', install_requires=['gym','scipy','numpy'] # And any other dependencies )
159
54
# Inspired by https://github.com/cogu/cfile c_indent_char = ' ' def set_indent_char(char): global c_indent_char c_indent_char = char class blank: def __init__(self, num=1): self.indent = 0 #Irrelevant, kept because it simplifies sequences self.num = num def __str__(self): #...
13,064
4,270
from typed_python import Entrypoint, SubclassOf, Class, Final, Function, ListOf class A(Class): pass class B(A): pass class C(B, Final): pass def test_can_cast_subclass_of_correctly(): @Function def f(c: SubclassOf(C)): return "C" @f.overload def f(c: SubclassOf(B)): ...
906
354
from vision import * from vision.track import alearn, interpolation from vision import visualize from vision.toymaker import * import os import multiprocessing g = Geppetto() b = Rectangle() b = b.linear((300,300), 100) b = b.linear((0,300), 200) b = b.linear((300,0), 300) g.add(b) path = b.groundtruth() pathdict = d...
1,442
513
import logging from .base import SimSootStmt l = logging.getLogger('angr.engines.soot.statements.goto') class SimSootStmt_Goto(SimSootStmt): def _execute(self): jmp_target = self._get_bb_addr_from_instr(instr=self.stmt.target) self._add_jmp_target(target=jmp_target, ...
355
128
import arcade from ..constants import TILE_SIZE, PLAYER_SCALING from ..utils import Vector class PlayerInventory: keys: int = 0 class Player(arcade.Sprite): def __init__(self, *args, **kwargs): super().__init__( "game/assets/sprites/square.png", PLAYER_SCALING, *args, **kwargs )...
979
317
__version__ = '0.7.1' try: from regularsmooth import * except ImportError: from .regularsmooth import *
112
38
import math import string from itertools import groupby from operator import itemgetter from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize N = 10788.0 # Number of documents, in float to make division work. class TermMapper(object): def __init__(self): if 'stopwords' in self....
2,389
755
from django.contrib import admin from admin_interface.models import Theme as Th from .models import Genre, Platform, Screenshot, Artwork, Mode, PlayerPerspective, Engine, Theme, Game admin.site.unregister(Th) admin.site.register(Genre) admin.site.register(Platform) admin.site.register(Mode) admin.site.register(Playe...
1,046
341
#!/usr/bin/env python import sys import json import matplotlib.pyplot as plt result = json.load(sys.stdin) x = result["hour"] y = result["wbgt"] fig = plt.figure(figsize=(8, 4)) ax1 = fig.add_subplot(1,1,1) ax1.set_xlabel("hour") ax1.set_ylabel("wbgt") ax1.set_xticks(list(range(0,24,1))) ax1.set_yticks(list(range(1...
589
287
from functools import cache def split_row(row): instructions, output = row.split(' -> ') return output, tuple(instructions.split(' ')) @cache def solve(key): if key.isdigit(): return int(key) else: instructions = circuit[key] if len(instructions) == 1: return solv...
1,005
321
""" Test nb-only filter """ from io import StringIO from noteout.nb_only import NbonlyFilter as nnbo from .tutils import (read_md, assert_json_equal, filter_doc) def test_nb_only(): content = """/ Some text [notebook only]{.nb-only}more text. ::: nb-only Only in notebook. ::: More text. """ doc = read_md...
523
197
# -*- coding: utf-8 -*- import operator class Comparable(object): @property def _repr(self): """Unique representation of an instance""" return "{}{}".format(type(self).__name__, id(self)) def _cmpkey(self, other): return self._repr def _sortkey(self, other): return s...
1,386
445
# !/usr/bin/env python # -*- coding: UTF-8 -*- """ from gevent import monkey monkey.patch_all() from gevent.queue import Queue """ import requests import time import random proxies=[] with open('./ips.txt') as f: proxies = [line.split('@')[0] for line in f] def randomProxy(proxies): ip = random.choice(proxies...
3,241
1,126
import setuptools version = "1.0.0" with open("README.md", "r", encoding="utf-8") as fh: readme = fh.read() setuptools.setup( name="asyncode", version=version, author="Loïc Simon", author_email="loic.simon@espci.org", description="Emulating Python's interactive interpreter in asynchronous con...
1,156
367
function solution(x1, y1, x2, y2) { const x1 = 8; const y1 = 4; const x2 = 8; const y2 = 10; let soundSum = 0; // 두 스피커 사이가 가까워 음량이 5를 넘는 경우 if (Math.abs(x1 - x2) + Math.abs(y1 - y2) < 4) return -1; if (3 < x1 && x1 < 13 && 3 < x2 && x2 < 13 && 3 < y1 && y1 < 13 && 3 < y2 && y2 < 13) { ...
1,926
972
"""========== This script will remove a number of residues from a sequence file in agreement to the intervals and other details supplied. """ from crops.about import __prog__, __description__, __author__, __date__, __version__ import argparse import os from crops.io import check_path from crops.io import outpathgen...
8,328
2,660
#!/usr/bin/env python # coding: utf-8 # In[95]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # get_ipython().run_line_magic('matplotlib', 'inline') from sklearn.neighbors import LocalOutlierFactor from sklearn.model_selection import train_test_split from sklearn.line...
13,189
5,082
from django.contrib.auth import authenticate from msa.utils.ipware import get_ip from msa.views import LoggedAPIView from rest_framework import status from rest_framework.authentication import TokenAuthentication, BasicAuthentication from rest_framework.authtoken.models import Token from rest_framework.permissions impo...
6,127
1,601
#!/use/bin/python import tempfile import os import dicom import pandas import json import numpy as np from os.path import join import glob import errno import shutil class dcm2niix(object): """A wrapper for the dcm2niix command """ def __init__(self, row, bids_dir, intent = None): self.intent = intent #Dico...
4,830
2,164
# # Copyright 2018-2020 NXP # SPDX-License-Identifier: Apache-2.0 # # """License text""" import logging from . import sss_api as apis from .keystore import KeyStore from .keyobject import KeyObject from .getkey import Get from .util import get_ecc_cypher_type log = logging.getLogger(__name__) class Generate: "...
4,479
1,411
#!/usr/bin/env python3 # # To communicate with UDS server by nc: "echo -e "string\c" | sudo nc -q 1 -U /var/run/uds_led" import socket serverAddress = '/tmp/portex_tmp' def main(): try: while True: message = input( 'Enter the message send to server ("Quit" to quit): ') ...
979
291
# Generated by Django 3.0.3 on 2021-02-19 18:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workspaces', '0006_workspacegeneralsettings_import_categories'), ] operations = [ migrations.AddField( model_name='workspacegene...
502
163
#!/usr/bin/python3 """ Module 100-singly_linked_list Defines class Node (with private data and next_node) Defines class SinglyLinkedList (with private head and public sorted_insert) """ class Node: """ class Node definition Args: data (int): private next_node : private; can be None or Node...
2,967
832
from django.conf.urls import url from . import views app_name = 'campaigns' urlpatterns = [ url( r'^$', views.JsonView.response, name='index' ), url( r'^(?P<app_code>[a-zA-Z0-9]+)/info/$', views.info, name='info' ), url( r'^(?P<app_code>[a-zA-Z0-9]+)/services/$', views.services, name='services' ), ]
310
129
import torch import torch.nn as nn class Gated_Sum(nn.Module): def __init__(self, opt): super(Gated_Sum, self).__init__() hidden_size = opt['dim_hidden'] nf = opt.get('num_factor', 512) self.hidden_size = hidden_size self.num_feats = len(opt['modality']) - sum(opt['skip_in...
5,802
2,054
import collections from scream.files import Docs, Scream, Tox class Monorepo(object): def __init__(self, root_dir): self.root_dir = root_dir self.config = Scream(self.root_dir) def sync(self): """Used internally ensure monorepo maintains certain standards. """ self.co...
2,489
728
''' Python3 implementation of oddball @author: Tao Yu (gloooryyt@gmail.com) ''' import numpy as np from sklearn.linear_model import LinearRegression from sklearn.neighbors import LocalOutlierFactor # feature dictionary which format is {node i's id:Ni, Ei, Wi, λw,i} def star_or_clique(featureDict): N = [] ...
9,837
3,718
import logging import os logging.basicConfig( level=logging.INFO, format='%(asctime)s %(filename)s[%(lineno)d] %(levelname)s %(message)s') logger = logging.getLogger() dir_name = os.path.join("/tmp", "tbase") if not os.path.exists(dir_name): os.makedirs(dir_name) handler = logging.FileHandler(os.path.jo...
538
204
# Generated by Django 2.2.4 on 2019-09-28 23:38 import address.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('address', '0002_auto_20160213_1726'), ('profesionales', '0004_auto_20190927_0004'), ] ...
3,125
976
from functools import partial from django.db import models from standards.fields import CharIdField # MODEL FIXTURES ################################################################################ class CharIdModel(models.Model): field = CharIdField() class CharIdModelWithPrefix(models.Model): field = C...
757
224
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py def get_upsample_filter(size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (size + 1) // 2 if size % 2 == 1: ...
10,070
4,311
from pydantic import BaseModel from typing import List # The models used in this module are being used by the API # for type validation using Pydantic as FastAPI is reliant # on pydantic for Data validation class GeographySchema(BaseModel): id: int short_name: str name: str class EntrySchema(BaseModel)...
1,067
324
from django.contrib import admin from .models import Product class ProductAdmin(admin.ModelAdmin): fields = ('name', 'price', 'category', 'image') list_display = ('name', 'price', 'category', 'image') list_filter = ('category', 'price', ) list_editable = ('price', 'category', 'image', ) admin.site.reg...
348
101
import subprocess f = open("app_list.csv","r") lines = f.readlines() for line in lines: print(line.strip()) command = "node app.js " + line.strip(); display = subprocess.run(command, stdout=subprocess.PIPE, shell=True) # display = subprocess.run(["sudo","-u",username,"tshark", "-r", pcapname, "-Y", disp...
404
141
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
20,260
7,046
from django.contrib.auth.models import User from django.db import models from django.utils.timezone import now class Vendor(models.Model): user = models.ManyToManyField(User) name = models.CharField(max_length=30, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.Date...
4,035
1,367
from keras.models import Sequential from keras.layers import Dense, Dropout def denseNet(input_dim, output_dim=4): model = Sequential() model.add(Dense(1024, input_shape=(input_dim,), kernel_initializer='normal', activation='relu')) model.add(Dense(1024, kernel_initializer='normal', activation='relu')) ...
1,500
528
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
13,242
3,828
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from numpy.testing import assert_allclose from astropy.coordinates import Angle from astropy.tests.helper import pytest, assert_quantity_allclose from ast...
12,287
4,617
# Generated by Django 2.2.16 on 2020-12-13 02:28 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("applications", "0041_goodonapplication_is_precedent"), ("applications", "0041_goodonapplicationdocument"), ] operations = []
298
108
### A module containing various utilities used at various points throughout the processes of submitting and analyzing problems ### import os import json import subprocess import hashlib import sys import random import string from .output_processor import process_output from . import code_templates def make_file(path,...
5,829
1,770
from __future__ import division from collections import OrderedDict from sqlalchemy import create_engine, MetaData, func from sqlalchemy.orm import sessionmaker, class_mapper from django.conf import settings from django.db.backends.base.creation import TEST_DATABASE_PREFIX from django.db import connection if settin...
21,136
6,011
from time import time from typing import * import torch from booster import Diagnostic from torch import Tensor from tqdm import tqdm from .utils import cosine, percentile, RunningMean, RunningVariance from ..estimators import GradientEstimator from ..models import TemplateModel def get_grads_from_tensor(model: Tem...
9,913
3,011
def carrega_cidades(): resultado = [] with open('cidades.csv', 'r', encoding='utf-8') as arquivo: for linha in arquivo: uf, ibge, nome, dia, mes, pop = linha.split(';') resultado.append( (uf, int(ibge), nome, int(dia), int(mes), int(pop)) ) arquivo...
1,081
428
# -*- coding: utf-8 -*- import re # from pyltp import Segmentor import jieba.posseg as pseg import jieba import os import sys import json import math # import kenlm import nltk from collections import Counter def dataSplit(inputpath, count): (filepath, tempfilename) = os.path.split(inputpath) (filename, exten...
1,428
494
""" Practice problems, Python fundamentals 1 -- Solutions @authors: Balint Szoke, Daniel Csaba @date: 06/02/2017 """ #------------------------------------------------------- # 1) Solution good_string = "Sarah's code" #or good_string = """Sarah's code""" #------------------------------------------------------- ...
2,435
837
""" This is a python script that converts u(rho, T), P(rho, T), Cs(rho,T), S(rho, T) to T(rho, u), P(rho, u), Cs(rho, u), S(rho, u), which is more useful for SPH calculations """ import matplotlib.pyplot as plt from collections import OrderedDict import numpy as np import pandas as pd import csv import sys from scipy...
7,178
2,772
from django.urls import path from . import views urlpatterns = [ path('post_posts', views.post_posts), path('fetch_posts', views.get_posts), path('fetch_post/<pk>', views.get_post), path('delete_post/<pk>', views.delete_post), path('edit_post/<pk>', views.edit_post), path('search_for_a_post', v...
346
126
import os def getDataPath(): return os.getcwd().replace("dato-graphlab/src", "data/") def getSmall(): return getDataPath() + "sample-small.txt" def getMedium(): return getDataPath() + "sample-medium.txt" def getLarge(): return getDataPath() + "sample-large.txt" def getGoogle(): return getDa...
506
184
import numpy as np def generate_cost_dict(): def inner_func(i, j): x1 = i % 10 y1 = i // 10 x2 = j % 10 y2 = j // 10 alpha = 5 x_center = 5.5 x_radius = 7.5 y_center = 1 y_radius = 4.5 dist = np.sqrt(47 * 47 * np.square(x1 - x2) + 7...
950
383
from django.contrib import admin from django.urls import path, include from rest_framework_jwt.views import ( obtain_jwt_token, refresh_jwt_token, ) urlpatterns = [ path('admin/', admin.site.urls), path('token-auth/', obtain_jwt_token), path('token-refresh/', refresh_jwt_token), path('employ...
377
124
#General libs import sys import os import json from datetime import datetime import time #Data wrangling libs import pandas as pd import numpy as np #DB related libs from sqlalchemy import create_engine #ML models related libs from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.metrics import confusion_...
15,989
4,592
import struct MAX_UINT = 2 ** (struct.calcsize('I') * 8) - 1 MAX_ULONG = 2 ** (struct.calcsize('L') * 8) - 1 UINT8_T = 1 UINT32_T = 4 UINT64_T = 8
148
82
import pytest from django.contrib.auth.models import User from django.urls import reverse from selenium.webdriver.common.by import By from .base import AuthorBaseFunctionalTest @pytest.mark.functional_test class AuthorLoginTest(AuthorBaseFunctionalTest): def test_user_valid_data_can_login_successfully(self): ...
2,103
645
class ContactHelper: def __init__(self, app): self.app = app def submit_specified_user(self): wd = self.app.wd wd.find_element_by_xpath("(//input[@name='submit'])[2]").click() def add_user(self, add_new_contact): wd = self.app.wd wd.find_element_by_...
3,873
1,320
from .commons import VCFEntry, LabeledMat
42
13
from simulation.common import Storage from simulation.common import BatteryEmptyError class BaseBattery(Storage): def __init__(self, initial_energy, max_current_capacity, max_energy_capacity, max_voltage, min_voltage, voltage, state_of_charge): super().__init__() # Constants ...
2,612
720
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 17 21:04:48 2018 @author: Alex Alves Programa para determinar se um tumor de mama é benigno (saida 0) ou maligno (saida 1) """ import pandas as pa # Importação para poder dividir os dados entre treinamento da rede e testes de validação from skl...
2,757
1,074
# Solution of; # Project Euler Problem 736: Paths to Equality # https://projecteuler.net/problem=736 # # Define two functions on lattice points:$r(x,y) = (x+1,2y)$$s(x,y) = # (2x,y+1)$A path to equality of length $n$ for a pair $(a,b)$ is a sequence # $\Big((a_1,b_1),(a_2,b_2),\ldots,(a_n,b_n)\Big)$, where:$(a_1,b_1...
1,214
579
#!/usr/bin/env python3 # https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/0000000000209a9e t, b = map(int, input().split()) for _ in range(t): xs = [None] * b q, k, k1, k2 = 0, 0, None, None def query(k): global q q += 1 print(k) r = int(input()) ...
1,728
608
class Standard(object): """Abstract class for representation of Standard LTS""" def __init__(self): super(Standard, self).__init__() def get_any_trace(self, boundary): # Return any of the traces of standard LTS S raise NotImplementedError('Abstract method not implemented!') def get_traces(self, boundary): ...
431
131
import requests from Stephanie.configurer import config class Updater: def __init__(self, speaker): self.speaker = speaker self.c = config self.current_version = self.c.config.get("APPLICATION", "version") self.update_url = "https://raw.githubusercontent.com/SlapBot/va-version-check/master/version.json" se...
1,388
496
#!/usr/bin/env python # Copyright 2020 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # 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...
24,533
7,614
import os import sys from setuptools import setup, find_packages ROOT = os.path.realpath(os.path.join(os.path.dirname( sys.modules['__main__'].__file__))) sys.path.insert(0, os.path.join(ROOT, 'src')) setup( name='pgworker', packages=find_packages('src'), package_dir={'': 'src'}, classifiers=[ ...
727
231
import os import csv path = '/Users/kevinkosumi12345/Genti/python-challenge/PyBank/Resources/budget_data.csv' budget_csv=os.path.join("../Resources", "budget_data.csv") csvfile = open(path, newline="") reader=csv.reader(csvfile, delimiter=",") header = next(reader) # print(header) # the columns we have to convert ...
2,040
756
import numpy as np import matplotlib.pyplot as plt T = 30000 # v = 0.02906 # v = 0.617085 v = 0.99 h = 0.01 a = 0.5 b = 0.5 epsilon = 0.05 c = 0.4 eta = lambda rho: np.exp(-(rho)**2/(2*c**2)) nrho = lambda rho, v: -2.0*(rho**3 + (rho-1.0)*v/2.0 - rho)/(rho + 1.0) nu = lambda rho: (b - eta(rho+1))/a u = np.zeros(T) ...
1,516
886
import numpy as np import os my_array = np.zeros(10) print(my_array) os.system('pip freeze > requirements.txt') my_list = [1,2,3,4,5] for item in my_list: print(item)
176
77
#! /usr/bin/python3 import argparse import os import re import sqlite3 as sql import sys import xml.etree.cElementTree as et import traceback import lib.initialize as initialize import lib.sqlite_interface as misc import lib.meta as meta # ================== # EXPORTED FUNCTIONS # ================== def parse(pare...
6,058
1,908
from matplotlib.pyplot import get import pyhips from pyhips import get_image def test_get_image(): """ Tests the get_image() function to make sure no errors are thrown. """ assert get_image("Vega", frame="ICRS", survey="DSS", cmap="plasma") == 0 assert get_image("notanid", frame="ICRS", survey="D...
646
228
""" Template module for cumulus. template class for reading yaml tempalte and creating data_source objects to retrieve external data. """
138
37
# Bubble sort steps through the list and compares adjacent pairs of elements. The elements are swapped if they are in the wrong order. The pass through the unsorted portion of the list is repeated until the list is sorted. Because Bubble sort repeatedly passes through the unsorted part of the list, it has a worst case...
700
221
def minion_game(string): # Stuart score s_idx = [i for i, c in enumerate(string) if c not in 'AEIOU'] s_score = sum([len(string)-i for i in s_idx]) # Kevin score k_idx = [i for i, c in enumerate(string) if c in 'AEIOU'] k_score = sum([len(string)-i for i in k_idx]) # final result if k_sc...
551
204
# -*- coding: utf-8 -*- import numpy as np X = np.random.rand(2) #input W = np.random.rand(2,3) #weight B = np.random.rand(3) #bias print(X) print(W) print(B) Y=np.dot(X,W)+B print(Y)
189
98
from pytest_bdd import given, when, then from model.contact import Contact import random @given('a contact list') def contact_list(orm): return orm.get_contact_list() @given('a contact with <firstname>, <lastname> and <address>') def new_contact(firstname, lastname, address): return Contact(firstname=firstnam...
2,485
800
#!/usr/bin/env python """ Figures generated by HiST program intended for use with in/ files including: *_flame.ini *_impulse.ini *_trans.ini Flaming Aurora 2 cameras: ./FigureMaker.py in/2cam_flame.ini Translating Aurora 2 cameras: ./FigureMaker.py in/2cam_trans.ini Impulse Aurora (for testing): ./FigureMaker.py in...
769
307
from django.db import models # Create your models here. from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.core.validators import RegexValidator from django.db import models class UserManager(BaseUserManager): def create_user(self, phone_numb...
3,557
1,136
"""Component to control v6m relays and sensors. For more details about this component, please refer to the documentation at https://home-assistant.io/components/v6m/ """ import logging import voluptuous as vol from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, CONF_HOST, CONF_PORT, CONF_NAME) import homea...
2,998
931
import uuid from django.db import models from django.db.models.fields import TextField class Blog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(verbose_name="Title", max_length=150, default="Happy Blog", blank=False) content = models.T...
550
178