text
string
size
int64
token_count
int64
""" Content negotiation selects a appropriated parser and renderer for a HTTP request. """ from abc import ABCMeta, abstractmethod from .mimetypes import MimeType class ContentNegotiation(metaclass=ABCMeta): """ Base class for all content negotiations. """ @abstractmethod def select_parser(self,...
2,354
632
import unittest import mock import six import codecs import os import json import logging import shutil import tarfile import io from io import BytesIO import uuid from docker_squash.squash import Squash from docker_squash.errors import SquashError, SquashUnnecessaryError from docker_squash.lib import common if not s...
48,070
14,487
import torch import math import torch.nn as nn import torch.nn.functional as F class SpatialGate(nn.Module): def __init__(self, gate_channel, reduction_ratio, dilation_conv_num=2): super(SpatialGate, self).__init__() dilation_val = [1, 2] self.gate_s = nn.Sequential() self...
1,627
627
import cv2 faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") #capture = cv2.VideoCapture(0) capture = cv2.VideoCapture('Elon Musk 320.mp4') while True: _, frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #faces = faceCascade.de...
736
329
from setuptools import setup import sys if sys.version_info < (2,5): raise NotImplementedError( "Sorry, you need at least Python 2.5 to use cprofilev.") VERSION = '1.0.4' __doc__ = """\ An easier way to use cProfile. Outputs a simpler html view of profiled stats. Able to show stats while the code is st...
1,110
351
# standard libraries import os # third party libraries pass # first party libraries from . import (application, routing, static, surly, requests, responses, utils, cookies, exceptions, middleware, ) __where__ = os.path.dirname(os.path.abspath(__file__)) __all__ = ('Application', 'application', 'routin...
566
158
import sys # this is for extracting command line arguments. def parse_activator(flag, value): if flag[1] == 'a': return (True, value) else: return (False,None) pass def parse_optimizer(flag, value): if flag[1] == 'o': return (True, value) else: return (False,None) ...
5,947
2,158
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # Python modules from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import pyqtSignal import logging # Wizard modules from wizard.core import assets from wizard.core import project from wizard.vars import ressources # Wizard gui modules ...
7,658
2,381
from .BaseAgent import BaseAgent import pandas as pd import numpy as np from itertools import islice class SixMonthCycle_Agent(BaseAgent): def __init__(self, window_size, small, large, signal, up, down): super().__init__(window_size) self.up = up self.down = down self.large = large ...
1,591
518
n = float(input()) m = float(input()) max = max(n, m) min = min(n, m) time = max - min print(time // 60, time % 60)
116
54
import tensorflow as tf import matplotlib.pyplot as plt X = [1, 2, 3] Y = [1, 2, 3] W = tf.placeholder(tf.float32) hypothesis = X * W cost = tf.reduce_mean(tf.square(hypothesis - Y)) sess = tf.Session() sess.run(tf.global_variables_initializer()) W_val = [] cost_val = [] for i in range(-30, 50): feed_W = i *...
485
219
""" .. module:: test_multisampling :synopsis: Test multisampling strategy .. moduleauthor:: David Eriksson <dme65@cornell.edu> """ from pySOT import Ackley, CandidateDYCORS, GeneticAlgorithm, \ MultiStartGradient, SyncStrategyNoConstraints, \ RBFInterpolant, CubicKernel, LinearTail, \ SymmetricLatinHyper...
2,078
689
import torch import argparse from selfplaylab.game.go import CaptureGoState, PixelCaptureGoState, GoState from selfplaylab.game.gomoku import GoMokuState, GoMokuStateAugmented, TicTacToe, TicTacToeAugmented from selfplaylab.game.nim import NimState from selfplaylab.game.othello import OthelloState from selfplaylab.play...
1,172
399
import re def try_parse_int(s, base=10, val=None): try: return int(s, base) except ValueError: return val def test_version(): """Test version string""" from coco2customvision import __version__ version_parts = re.split("[.-]", __version__) if __version__ != "UNKNOWN": ...
558
182
# -*- coding: utf-8 -*- from Pages.PageObject import PageObject import time class ITProPage(PageObject): firstHandle = "" secondHandle = "" def __init__(self, driver): PageObject.__init__(self, driver) def click_picture(self): self.firstHandle = self.driver.wi...
1,266
421
import requests from bs4 import BeautifulSoup notebook_html = requests.get('https://search.shopping.naver.com/search/all?pagingIndex=2&pagingSize=80&query=노트북') notebook_soup = BeautifulSoup(notebook_html.text,"html.parser") notebook_list_box = notebook_soup.find("ul", {"class" : "list_basis"}) notebook_list = noteboo...
1,328
528
#!/usr/bin/env python3 # -*- coding: utf-8 -*- QUANDLKEY = '<Enter your Quandl APT key here>' """ Created on Fri Oct 5 23:24:35 2018 @author: jeff """ '''************************************* #1. Import libraries and define key variables ''' import pandas as pd import numpy as np import quandl import matplotlib.pyplo...
9,891
3,685
import random uppercase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase_letters = "abcdefghijklmnopqrstuvwxyz" digits = "0123456789" symbols = "!@#$%^&*()_+-=[]{}|;':,./<>?" upper, lower, digit, symbol = True, True, True, True all = "" if upper : all += uppercase_letters if lower : all += lo...
530
228
import sqlite3 import pandas import itertools import networkx as nx from gtfspy.gtfs import GTFS from gtfspy.util import timeit from scripts.all_to_all_settings import * def attach_database(conn, other_db_path, name="other"): cur = conn.cursor() cur.execute("ATTACH '%s' AS '%s'" % (str(other_db_path), name)...
20,517
6,258
from flowsaber.api import * def test_snakemake_workflow(): # EnvTask is the real dependent task when using conda/image option @shell def bwa(self, fa: File, fastq: File): # input will be automatically converted if has type annotation """bwa mem -t {self.config.cpu} {fa} {fastq} | samtools view -...
2,258
757
mass = eval(input("Enter the amount of water in kilograms: ")) initial_temp = eval(input("Enter the initial temperature: ")) final_temp = eval(input("Enter the final temperature: ")) energy = mass * (final_temp - initial_temp) * 4184 print("The energy needed is {}".format(energy))
282
85
from django.apps import AppConfig from django.conf import settings class PortalCoreConfig(AppConfig): name = 'portal_core'
129
36
import glob import SimpleITK as sitk import numpy as np class CTScanMhd(object): def __init__(self, base_dir, filename): self.filename = filename self.coords = None self.base_dir = base_dir path = glob.glob(self.base_dir + '/*/' + self.filename + '.mhd') self.ds = sitk.ReadI...
1,482
561
""" Section 1 Multithreading - Thread (2) - Daemon, Join Keyword - DaemonThread, Join """ """ DaemonThread(데몬스레드) (1). 백그라운드에서 실행 (2). 메인스레드 종료시 즉시 종료 (서브 스레드의 경우는 메인 스레드와 상관없이 자기 작업을 끝까지 수행함.) (3). 주로 백그라운드 무한 대기 이벤트 발생 실행하는 부분 담당 -> JVM(가비지 컬렉션), 자동 저장 (4). 일반 스레드는 작업 종료시까지 실행 """ import logging import threading # 스...
1,324
769
#!/usr/bin/env python3 # PURPOSE: studying function side effects import os os.system('clear') orgList = [5, 3, 2, 1, 4] def sumList(myList): for i in range(1, len(myList)): myList[i] += myList[i-1] return myList[len(myList)-1] print(sumList(orgList)) print(orgList)
287
120
import pandas as pd import numpy as np serie = pd.Series(['a', 'b', 'c', 'd', 'e'], index=['a', 'b', 'c', 'd', 'e'], name="Ejemplo Serie") print(serie) ecoli_matraz = pd.Series([0.1, 0.15, 0.19, 0.5, 0.9, 1.4, 1.8, 2.1, 2.3], ...
2,029
886
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """ Script to prepare mit67 dataset for pytorch dataloader. """ from typing import List, Dict, Tuple, Union, Optional import os import pdb import time import argparse import os import tempfile import requests from torchvision.datasets.utils imp...
6,209
2,086
from tail.core import read_last_lines, follow_lines __all__ = ["read_last_lines", "follow_lines"]
99
34
# Copyright 2018 IBM Corp. 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 agre...
89,305
29,703
""" _InsertRecoReleaseConfig_ Oracle implementation of InsertRecoReleaseConfig """ from WMCore.Database.DBFormatter import DBFormatter class InsertRecoReleaseConfig(DBFormatter): def execute(self, binds, conn = None, transaction = False): sql = """INSERT INTO reco_release_config (RUN_I...
713
185
import wave import os import sys from glob import glob import argparse parser = argparse.ArgumentParser() parser.add_argument("--length", type=int, default=30) parser.add_argument("--offset", type=int, default=15) args = parser.parse_args() unit_time_length = args.length start_time_offset = args.offset output_dir =...
1,652
549
import sys import qbittorrentapi import json from ui import UI print("Connecting to qBittorrent WebUI...") with open('config.json') as json_file: config = json.load(json_file) host = config['host'] username = config['username'] password = config['password'] if not host: host = inp...
726
253
from tkinter import * janela = Tk() lista = [] texto1 = StringVar() texto2 = StringVar() texto3 = StringVar() texto4 = StringVar() #--------------------- PROCESSAMENTO DO COMANDO ------ def click_bt1(): lista.append(int(et1.get())) lista.append(int(et2.get())) lista.append(int(et3.get())) lista.appe...
2,454
981
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ プレイヤーのうち、NPCのクラス """ """ - Playerクラスを継承している - 全体的に未実装 - 将来的にはここでAIを読み込ませる? """ __author__ = "aseruneko" __date__ = "28 May 2020" from main.Player import Player class Computer(Player): pass
247
148
# More details on this kata # https://www.codewars.com/kata/52b7ed099cdc285c300001cd def sum_of_intervals(intervals): s, ret = [list(x) for x in sorted(intervals)], 0 if len(s) == 1: return abs(s[0][0] - s[0][1]) for i in range(len(s)): if i + 1 > len(s) - 1: break if s[i][0] <= s[i + 1][0]...
650
296
""" This module contains white-box unit tests of CertDB package """ # pylint: disable=W0212, C0103, C0302 import sys import os import subprocess import time import shutil import string import random import unittest import unittest.mock from collections import OrderedDict import toml from cevast.utils import make_PEM_fi...
59,170
17,934
import uuid import numpy as np class BColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class Indv: def __init__(self, indv_size): self.indv_size = indv_size self.weights = np.random.unifo...
2,325
960
# Generated by Django 2.2.1 on 2020-01-14 19:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0022_auto_20200111_2058'), ] operations = [ migrations.RemoveField( model_name='users', name='expires_at', ...
516
175
import sc2 from sc2.constants import * #our own classes from unit_counters import UnitCounter from warpprism import WarpPrism as wpControl from immortal import Immortal as imControl from stalker import Stalker as skControl from zealot import Zealot as zlControl from sentry import Sentry as snControl from ade...
11,197
4,584
from .Versioned import Versioned class Addon(Versioned): """ Implements the addon support to the versioned. """ def __init__(self, *args, **kwargs): """ Create an addon object. """ super(Addon, self).__init__(*args, **kwargs) # setting default options s...
619
171
# Generated by Django 3.2.8 on 2021-11-15 20:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('usuarios', '0005_rename_ponto_id_funcionario_ponto'), ('agendamentos', '0001_initial'), ] operations = [ migrations.RenameModel( ...
393
144
from datetime import date from django.contrib import admin, messages from django.core.management import call_command from django.utils.html import format_html from django.http import HttpResponseRedirect from django.urls import path # Register your models here. from .models import ( FilingList, Filing, H...
5,988
2,006
"""Advent of Code 2019 Day 6 - Universal Orbit Map.""" with open('inputs/day_06.txt', 'r') as f: orbits = f.read().split() objects_dict = {} for orbit in orbits: orbited, orbiter = orbit.split(')') objects_dict[orbiter] = orbited num_orbits = 0 for orbiter in objects_dict: next_orbit = objects_dict....
1,039
394
from hookery import Handler, Hook def test_handler_from_func(): def f(a, b): return a - b h = Handler(f, Hook('hook1')) assert callable(h) assert h.__name__ == 'f' assert h.name == 'f' assert h.hook_name == 'hook1' assert not h.is_generator assert h(c=8, b=10, a=25) == 15 ...
663
248
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/25 14:14 # @Author : ZJJ # @Email : 597105373@qq.com from .views import UserViewset, ChangeUserPasswdView, GroupsViewset, UserGroupViewset, GroupMemberViewset, \ PermissionViewset, GroupPermViewset, PersonalInfoViewset from rest_framework...
1,057
346
# TODO: Add an appropriate license to your skill before publishing. See # the LICENSE file for more information. # Below is the list of outside modules you'll be using in your skill. # They might be built-in to Python, from mycroft-core or from external # libraries. If you use an external library, be sure to include...
3,742
1,071
"""Set up the package interface.""" from .add_update import add, update from .show import show from .delete import delete
123
33
import webbrowser as web from bs4 import BeautifulSoup STARTING_URL = 'https://www.google.com/search?q=' def get_first_website(phrase): phrase_split = phrase.split() phrase_url = '+'.join(phrase_split) search_url = STARTING_URL + phrase_url web.open_new_tab(search_url)
300
112
"""Test suite for the Talks Feedback microservice."""
54
16
from django.db import models from django.contrib.auth.models import User import json class Attribute(models.Model): name = models.CharField(max_length=200, unique=True) label = models.CharField(max_length=200) description = models.TextField() attribute_type = models.CharField(max_length=30) class Reco...
867
268
from .bigGay import bigGay def setup(bot): cog = bigGay(bot) bot.add_cog(cog)
86
40
from ai_constants import * import ai_generator def get_tab_string(tabment): return '\t' * tabment def express_node(cur_node, tabment = 0): child_nodes = cur_node.children if cur_node.type == 'DEFRULE': return "(defrule\n" \ + express_node(child_nodes[0], tabment + 1) \ ...
2,039
656
import numpy as np from tabulate import tabulate np.set_printoptions(linewidth=400, threshold=100000) def product(gen): ans = 1 for g in gen: ans *= g + 1 return ans def count_divs_pow(p): if p == 0 or p == 1: return 0 else: full_size = 7**(p-1) * (7**(p-1) - 1) // 2 ...
1,316
573
from django.conf import settings if 'modeltranslation' in settings.INSTALLED_APPS: from modeltranslation.translator import translator, NotRegistered def get_translated_fields(model): """Get translated fields from a model""" try: mto = translator.get_options_for_model(model) except NotRegister...
440
127
# # PySNMP MIB module OSPF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OSPF-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:18:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1...
141,668
52,110
from csv import reader import yaml import json def splitrow(row, DELIMETER): x = row.split(DELIMETER) return ([] if row == '' else x) def get_data_from_csv(settings, DELIMETER = '|'): rules = [] with open(settings['CSV_FILENAME'], 'r') as csv_file: csv_reader = reader(csv_file) for r...
1,695
548
import numpy as np import pandas as pd from types import FunctionType import warnings from .transform import BaseTransformer def drop_na(x, y, according='both'): """ Drop the values in both x and y if the element in `according` is missing ex. drop_na([1, 2, np.nan], [1, 2, 3], 'x') => [1, 2], [1, 2] ...
4,018
1,292
__author__ = 'yinjun' """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: A ListNode @return: A ListNode """ def deleteDuplicates(self, head): # write your code here ...
821
263
class Object: def __init__(self, type): self.type = type def square(self, a, b): if self.type == 'square': return a * b if self.type == 'triangle': return (a * b) / 2 vid = input() object = Object(vid) a = int(input()) b = int(input()) print(f'{object.square(a,b...
325
116
from .main import Main from .arguments import arg from textwrap import dedent main = Main() command = main.command @command('install-bash-completions', arg('--dest', help="destination file. Typically ~/.bashrc or ~/.profile", default="~/.bashrc"), arg('script_name'), ) def install_bash_completions(dest, scr...
809
262
# ********************************************************* # Relative Stage Movement # # Stephanie Fung 2014 # ********************************************************* # Import modules. # --------------------------------------------------------- import visa import string import struct import sys import serial # =...
1,500
420
# Copyright (c) 2013 Per Unneberg # # 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,...
7,794
2,543
import sys import pandas as pd # Can open csv files as a dataframe dframe = pd.read_csv('lec25.csv') # Can also use read_table with ',' as a delimiter dframe = pd.read_table('lec25.csv', sep=',') # If we dont want the header to be the first row dframe = pd.read_csv('lec25.csv', header=None) # We can also indicate a...
1,092
367
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: x.huang # @date:17-8-17 from Crypto.Hash import MD5 def encrypto(val): # python3 需要把进行 encode # todo 更改项目加密 key m = MD5.new('python-framework'.encode('utf-8')) m.update(val.encode('utf-8')) return m.hexdigest() def decrypto(val): pa...
385
169
from django.conf.urls import patterns from comments.views import CommentDebateList # This url file is included from items.urls with the prefix /comments/ urlpatterns = patterns('', # Add a comment to a topic (r'^(?P<topic_id>\d+)/add/$', 'comments.views.add'), ...
1,428
366
import sys from threading import Thread from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from pyqtconsole.console import PythonConsole from view.console import Console from view.gui_dock import * from util.logger import * from model.engine import * # clear logs logge...
2,022
669
#!/usr/bin/env python # -*- coding: utf-8 -*- # ˅ from behavioral_patterns.command.command import Command # ˄ # Holder of the past commands class HistoryCommand(Command): # ˅ # ˄ def __init__(self): # A set of past commands self.__past_commands = [] # ˅ pass # ...
845
317
import logging, os, time, multiprocessing, sys, signal logging.disable(logging.WARNING) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import tensorflow as tf import gym import pybullet, pybullet_envs, pybullet_data import numpy as np import pandas as pd from stable_baselines.sac.policies import MlpPolicy from stable_ba...
8,710
3,190
""" Copyright 2016 Andrea McIntosh 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...
1,274
427
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Graphic User Interface.""" import sys import os import glob import ConfigParser from PyQt4.QtCore import * from PyQt4.QtGui import * from version import __version__ from algorithm.imtool import label...
81,886
22,842
import yaml import json from pprint import pprint as pp my_list = [] while True: x = raw_input("Enter num or text to add to list or press enter to finish: ") if not x: break my_list.append(x) my_list.append({}) while True: y = raw_input("Enter the name of the key in the list or press enter to finish...
975
310
import colander from sqlalchemy import Column, ForeignKey from sqlalchemy.types import DateTime, Integer, Unicode, UnicodeText from naki.model.meta import Base class DigitalItem(Base): __tablename__ = "tDigitalItem" id_item = Column('sID_Item', Unicode(64), primary_key = True, info={'colanderalchemy': {'m...
1,475
458
#!/usr/bin/python -u # -*- coding: latin-1 -*- # # Labeled dice and Building block problems in Z3 # # * Labeled dice # # From Jim Orlin 'Colored letters, labeled dice: a logic puzzle' # http://jimorlin.wordpress.com/2009/02/17/colored-letters-labeled-dice-a-logic-puzzle/ # ''' # My daughter Jenn bough a puzzle...
4,389
1,968
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017 Ben Lindsay <benjlindsay@gmail.com> from job_tree import job_tree # Tier 1 is 3 values of VAR_1 (1, 2, and 3) found in 'tier_1.csv' tier_1_csv_file = 'tier_1.csv' # Tier 2 is 2 values of VAR_2 for each VAR_1, defined as a function of VAR_1 def tier...
2,741
1,489
import pickle import random from argparse import ArgumentParser # Requires NLTK to be installed: # python3 -m pip install nltk # python3 -c 'import nltk;nltk.download("punkt")' # May be slow at first start due to NLTK preparing its dependencies from nltk.tokenize.treebank import TreebankWordDetokenizer from nltk.lm im...
1,602
484
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who i...
7,529
2,518
######################### AABCAAADA from collections import OrderedDict def remove_duplicates(block): """ >>> remove_duplicates('AAB') >>> 'AB' """ freq = OrderedDict() for c in block: freq[c] = freq.get(c, 0) + 1 return ''.join(freq.keys()) def solve(text, block_size): re...
456
177
__all__ = 'TMP_NAME_FACTORY', 'tmp_file_name', 'str_uuid' import os from tempfile import NamedTemporaryFile from uuid import uuid4 def tmp_file_name(): with NamedTemporaryFile() as named_tmp_file: return os.path.basename(named_tmp_file.name) def str_uuid(): return str(uuid4()) TMP_NAME_FACTORY =...
335
130
import sys sys.path.append("apps/controllerx")
48
17
from django_unicorn.components import UnicornView from django_unicorn.views.utils import _is_component_field_model_or_unicorn_field from example.coffee.models import Flavor class TypeHintView(UnicornView): model: Flavor = None class ModelInstanceView(UnicornView): model = Flavor() def test_type_hint(): ...
884
279
import pytest testdata = [ (2, True), (3, False), (4, True), (5, True) # We expect this test to fail ] def check_if_even(a): """ Returns True if 'a' is an even number """ return a % 2 == 0 @pytest.mark.parametrize('sample, expected_output', testdata) def test_check_if_even(sample...
431
155
import numpy as np from scipy.optimize import minimize from intvalpy.MyClass import Interval from intvalpy.intoper import zeros def Uni(A, b, x=None, maxQ=False, x0=None, tol=1e-12, maxiter=1e3): """ Вычисление распознающего функционала Uni. В случае, если maxQ=True то находится максимум функционала. ...
4,970
1,613
import math R_EARTH = 6371000 # meter def angle2radian(angle): """ convert from an angle to a radian :param angle: (float) :return: radian (float) """ return math.radians(angle) def radian2angle(radian): return math.degrees(radian) def spherical_law_of_cosines(phi1, lambda1, phi2, la...
3,648
1,300
""" Python Template for docstring ----------------------------- python.docstring is a package cotaining TEMPLATE for docstring in python. usage: >>> from python import docstring >>> help(docstring) >>> print(docstring.module_.__doc__) >>> print(docstring.class_.__doc__) >>> print(docstrin...
1,154
398
import logging import sys import socket from cliff.app import App from cliff.command import Command from cliff.commandmanager import CommandManager class RegisteredCommand(Command): def __init__(self, app, app_args): super(RegisteredCommand, self).__init__(app, app_args) @classmethod def registe...
6,234
1,943
from format2 import Format2 from format40 import Format40 from format80 import Format80
88
26
import sys import os import gzip import argparse import numpy as np import pysam import util import snptable import tables MAX_SEQS_DEFAULT = 64 MAX_SNPS_DEFAULT = 6 class DataFiles(object): """Object to hold names and filehandles for all input / output datafiles""" def __init__(self, bam_filen...
20,705
5,987
# generated by update to not change manually import typing as t from bungieapi.base import BaseClient, clean_query_value from bungieapi.forge import forge from bungieapi.generated.components.responses import ( CEListOfGroupOptionalConversationClientResponse, DictionaryOfint32AndstringClientResponse, ListOf...
25,145
6,814
from causalprob import CausalProb import unittest import jax.numpy as jnp import numpy as np class TestNFConfounderModel(unittest.TestCase): def test_is_inverse_function(self): from models.nf_confounder_model import define_model dim = 2 model = define_model(dim=dim) cp = CausalPr...
1,475
527
''' Generate a bar chart with error bars -- might be easier to read than a line graph with error bars. ''' import matplotlib.pyplot as plt import pandas as pd import numpy as np def plot_result(idx, filename, xlabel, ylabel, linelabel, fig=None): if fig is None: fig = plt.figure(figsize=(5, 4)) else: ...
1,713
631
from .loader import * from .model import * from .train_and_test import *
74
24
# Program 77 : make Tkinter menu from tkinter import * from tkinter import * root = Tk() menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New') filemenu.add_command(label='Open...') filemenu.add_separator() filemenu.add_command(...
468
169
import factory from chat.models import Chat, ChatRoom from users.factories import UserFactory class ChatRoomFactory(factory.django.DjangoModelFactory): class Meta: model = ChatRoom name = factory.Faker('word') class ChatFactory(factory.django.DjangoModelFactory): class Meta: model = Cha...
445
137
"""Downloads the training dataset and removes bad samples. """ import csv import os import urllib.request import tarfile import glob DATA_URL = 'http://download.tensorflow.org/data/speech_commands_v0.01.tar.gz' TRAIN_DIR = '../dataset/train/audio/' FILE_BAD = 'bad_samples.txt' def maybe_download(data_url, dest_di...
1,335
487
from django.apps import AppConfig class RemoteControlConfig(AppConfig): name = 'remote_control' def ready(self): import remote_control.signals
162
47
from http import HTTPStatus from authlib.jose import jwt from pytest import fixture from .utils import get_headers from api.errors import AUTH_ERROR def routes(): yield '/health' yield '/deliberate/observables' yield '/observe/observables' yield '/refer/observables' yield '/respond/observables' ...
4,232
1,269
#!/usr/bin/env python3 # # Copyright 2020 IBM # 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 t...
1,562
560
def sum_all_to(num: int) -> int: """ Return the sum of all numbers up to and including the input number """ return num * (num + 1) // 2 def square_pyramidal_number(num: int) -> int: """ Return the sum of the squares of all numbers up to and including the input number """ # https://en.wikipedia.org/wik...
394
130
import numpy as np def place_camera(time, data, camera, camera_distance, view): # Define camera parameters camera.SetViewUp([0,0,1]) if view == 1: # General view chs_pos = data[0][0].path_loc[time] # Chassis CG @ time cam_d = 12 # [m] cam_h = 4.5 # [m] chs2cam...
2,143
869
""" .. /------------------------------------------------------------------------------\ | -- FACADE TECHNOLOGIES INC. CONFIDENTIAL -- | |------------------------------------------------------------------------------| | ...
16,405
4,590