text
string
size
int64
token_count
int64
import os import json import ConfigParser import logging.config base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # load the shared settings file settings_file_path = os.path.join(base_dir, 'config', 'settings.config') settings = ConfigParser.ConfigParser() settings.read(settings_file_path) # s...
689
203
from flask import Flask from flask_restplus import Api, Resource, fields from services.serviceHandler import convertCurrency, getCurrencyExchangeRates from services.countryCurrencyCodeHandler import ( getCountryAndCurrencyCode, getCurrencyNameAndCode, ) app = Flask(__name__) api = Api( app, version="1....
2,462
715
import sys import io import subprocess import threading import time import uuid import os.path import requests import json from random import randint from UniqueConfiguration import UniqueConfiguration from CommonConfiguration import CommonConfiguration from printer import console_out class BrokerActions: def __in...
6,344
1,717
#!$BEA_HOME/oracle_common/common/bin/wlst.sh # default values admin_name = 'AdminServer' admin_address = 'localhost' admin_port = 7001 admin_protocol = 't3' admin_url = admin_protocol + "://" + admin_address + ":" + str(admin_port) def usage(): print "dump_users [-s|--server -p|--port] [-u|--url] [-d|--delimite...
1,763
599
import numpy as np import pandas as pd from Bio import AlignIO, Seq # parameter to determine the maximum missing proportion that we keep missing_thresh = 0.4 # load the alignments and turn them into a numpy array alignments = AlignIO.read(snakemake.input[0], 'fasta') align_arr = np.array([list(rec) for rec in alignme...
1,082
359
#! /usr/bin/env python import sys from commons import * def print_proc_users(csv_path, condition_number): csv_dat = get_dict_data_from_csv_file(csv_path) if csv_dat: print "Processing user with condition %s\n" % condition_number for email in csv_dat: num = str_to_num(email['src']) % 10 if num in conditio...
626
253
import pandas as pd import sys def fix(lists): df = pd.read_json(lists) df2 = pd.DataFrame([p for p1 in df.players for p in p1]) df2['theme1'] = '' df2['theme2'] = '' for i, l in df2.list2.iteritems(): try: df2.theme2.iloc[i] = l['theme'] except KeyError: c...
1,250
414
# Define a function "warble" that takes in a string as an argument, adds " arglebargle" to the end of it, and returns the result. # Print the result of calling your "warble" function with the argument "hello". # Define a function "wibble" that takes a string as an argument, prints the argument, prepends "wibbly " t...
1,184
304
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: To find (and fix) two syntax errors # A program to display Green Eggs and Ham (v4) def showChorus(): print() print("I do not like green eggs and ham.") print...
1,003
342
import settings import handlers.base_handler import csv class CartogramHandler(handlers.base_handler.BaseCartogramHandler): def get_name(self): return "Singapore (by Region)" def get_gen_file(self): return "{}/singapore_map_processedmap.json".format(settings.CARTOGRAM_DATA_DIR) def v...
1,107
400
import multiprocessing import os import time rootdir = input() keyword = input() batch_size = 1 def try_multiple_operations(file_path): try: with open(file_path, "rb") as f: # open the file for reading for line in f: # use: for i, line in enumerate(f) if you need line numbers ...
1,247
375
from flask import Blueprint, Markup from flask import render_template class Youku(object): """Flask-Youku extents.""" def __init__(self, app=None, **kwargs): """Init Flask-Youku's instance via app object""" if app: self.init_app(app) def init_app(self, app): """Init F...
1,316
398
from backend import Backend, Tutor, Parent from kivy.app import App from kivy.base import Builder from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.properties import ObjectProperty from kivy.core.window import Window from kivy.uix.image import Image from ki...
26,061
8,542
from flask import Blueprint, request router = Blueprint("router", __name__) @router.route("/check") def check(): return "Congratulations! Your app works. :)" @router.route("/add", methods=["POST"]) def add(): first_number = request.form['FirstNumber'] second_number = request.form['SecondNumber'] re...
374
111
_base_ = [ '../_base_/models/repdet_repvgg_pafpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='RepDet', pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth', backbone=dict( ...
1,592
641
import pytest from tests import assert_source_returns_expected BRANCH_CASES = [ # Call ('print("hello world")', 'b | print("hello world")'), # Await ("await noop()", "b | await noop()"), # Class instantiation ("Noop()", "b | Noop()"), ] @pytest.mark.parametrize("source,expected", BRANCH_CAS...
436
152
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO if parse_version(ks_version) < parse_version('0.7'): raise Exception("Incompatible Kai...
4,619
1,939
import io import struct class SteamPacketBuffer(io.BytesIO): """In-memory byte buffer.""" def __len__(self): return len(self.getvalue()) def __repr__(self): return '<PacketBuffer: {}: {}>'.format(len(self), self.getvalue()) def __str__(self): return str(self.getvalue()) ...
1,537
519
# Holy Stone - Holy Ground at the Snowfield (3rd job) questIDs = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448] hasQuest = False for qid in questIDs: if sm.hasQuest(qid): hasQuest = True break if hasQuest: if sm.sendAskYesNo("#b(A mysterious energy surroun...
483
232
#-- coding:utf-8 from .ast import ASTNode from .compute.value import expr_value_calc_funcs,expr_value_prop_funcs from .compute.width import expr_width_calc_funcs,expr_width_fix_funcs from .compute.width import expr_match_width,expr_calc_width from .tools.utility import count_one import warnings __all__ = ['Mux',...
16,256
5,547
""" GLSL shader generation """ from utils import Stages, getHeader, getShader, getMacro, genFnCall, fsl_assert, get_whitespace from utils import isArray, getArrayLen, getArrayBaseName, getMacroName, DescriptorSets, is_groupshared_decl import os, sys, importlib, re from shutil import copyfile def pssl(fsl, dst, rootSi...
13,936
4,477
import pytest import searchsifter.relationships.minhash as mh import searchsifter.relationships.jaccard as jc @pytest.mark.parametrize("a, b, result", [ ({1, 2}, {2}, 0.5), ({1, 2}, {2, 3}, 1/3), ({1}, {2}, 0), ({1}, {1}, 1) ]) def test_jaccard(a, b, result): assert jc.jaccard(a, b) == result ...
1,673
828
def filter_dict(dictionary_to_filter): return dict((k, v) for k, v in dictionary_to_filter.items() if v is not None)
121
41
# Copyright 2018 Davide Spadini # # 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...
1,672
682
from unittest import TestCase from moceansdk.modules.command.button.wa_url_parameter_button import ( WaUrlParameterButton, ) class TestWaUrlParameter(TestCase): def test_type(self): self.assertEqual(WaUrlParameterButton().type(), "url") def test_setter_return(self): obj = WaUrlParameterB...
847
256
input_data = """109,2050,21101,0,966,1,21101,13,0,0,1106,0,1378,21101,20,0,0,1105,1,1337,21101,0,27,0,1105,1,1279,1208,1,65,748,1005,748,73,1208,1,79,748,1005,748,110,1208,1,78,748,1005,748,132,1208,1,87,748,1005,748,169,1208,1,82,748,1005,748,239,21101,0,1041,1,21102,1,73,0,1105,1,1421,21101,0,78,1,21101,1041,0,2,2110...
7,345
7,097
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import os from dataclasses import dataclass from typing import Sequence from pants.core.goals.package import OutputPathField from pants.core.goals.run ...
10,860
3,100
from matplotlib import pyplot as plt import matplotlib.lines as lines from statistics import mode, StatisticsError from csv import QUOTE_ALL import pandas as pd import pathlib import json from iris import logger from iris import config from iris import classifier from iris.helpers.utils import log_function ...
9,623
3,072
from scipy.io import loadmat import numpy as np import os import torch from torch.utils.data import Dataset, TensorDataset from torchvision import transforms # Find unique classes. def get_classes(input_directory, filenames): classes = set() for filename in filenames: with open(filename, 'r') as f: ...
2,328
778
class CustomException(Exception): def __init__(self, *args, **kwargs): return super().__init__(self, *args, **kwargs) def __str__(self): return str(self.args [1]) class DeprecatedException(CustomException): def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs)...
2,191
628
class Solution: 2 def solve(self, matrix): 3 from functools import lru_cache 4 @lru_cache(None) 5 def dp(i, j): 6 if i < 0 or j < 0: 7 return 0 8 return max(dp(i - 1, j), dp(i, j - 1)) + matrix[i][j] 9 return dp(len(matrix) - 1, len(matrix[0]) - 1)
317
126
import pygame, sys, maze_builder, random class Maze(object): def __init__(self, width, height, grid_length, penalizacion = 0.9): # width and height of the window and the grid size (x, y) so there would be a maximum number of nodes which would be x*y super(Maze, self).__init__() pygame.init() ...
12,074
4,090
from __future__ import (division, print_function, absolute_import, unicode_literals) import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline as InterpUS from powderday.nebular_emission.cloudy_tools import sym_to_name """ ---------------------------------------------------...
13,679
4,972
# Generated by Django 3.2.5 on 2021-08-12 02:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('character', '0003_alter_character_id'), ] operations = [ migrations.AlterField( model_name='character', name='alignm...
644
232
from nose.tools import assert_equal class TestCheckBalance(object): def test_check_balance(self): node = Node(5) insert(node, 3) insert(node, 8) insert(node, 1) insert(node, 4) assert_equal(check_balance(node), True) node = Node(5) insert(node, 3) ...
818
288
import keras from keras.models import Sequential, load_model, Model from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from scipy import io mat_contents = io.loadmat('Data/X_test_0.mat') X_test_0 = mat_contents['X_test_0'] mat_contents = io.loadmat('Data/X_test_1.mat') X_tes...
1,129
488
from django.apps import AppConfig class DbManagerConfig(AppConfig): name = 'db_manager'
94
29
from appJar import gui def press(btn): if btn == "info": app.infoBox("Title Here", "Message here...") if btn == "error": app.errorBox("Title Here", "Message here...") if btn == "warning": app.warningBox("Title Here", "Message here...") if btn == "yesno": app.yesNoBox("Title Here", "Message here...") ...
813
267
#!/usr/bin/env python # -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os from sklearn.metrics import confusion_matrix from datetime import datetime class ConvolutionalNeuralNetwork: """ Generic object for create DNN models. This class instinciates all functions needed for D...
19,136
6,268
from flask import request import pytest import json from app import create_app, create_rest_api from db import get_db from change_light import is_aquarium_id_valid @pytest.fixture def client(): local_app = create_app() create_rest_api(local_app) client = local_app.test_client() yield client def get_...
1,571
529
####################### # Dennis MUD # # inventory.py # # Copyright 2018-2020 # # Michael D. Reiley # ####################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal i...
4,293
1,361
import unittest from cozy.polynomials import Polynomial class TestPolynomials(unittest.TestCase): def test_sorting(self): self.assertLess(Polynomial([2019, 944, 95]), Polynomial([2012, 945, 95])) self.assertGreater(Polynomial([2012, 945, 95]), Polynomial([2019, 944, 95]))
296
126
from custom_objects import FinanceCalculator from tkinter import messagebox class CalculationsPresenter(object): def __init__(self, view): self.view = view def convert_price(self, price): try: converted_price = FinanceCalculator.decimal_to_treasury(price) self.view.dis...
823
229
import json class PowerStateMonitor(object): def __init__(self, simulation): self.simulation = simulation self.env = simulation.env self.event_file = simulation.event_file + "_power" self.events = [] def __cal_machine_power(self): machines = self.simulation.cluster.mac...
1,877
574
from sim import Sim import os import cProfile import pylab import math import matplotlib.pyplot as plt import argparse import json import decimal import numpy as np def init_params(): """Set up the simulation parameters.""" p = {} ## The basics: starting population and year, etc. p['initialPop'] = 7...
25,133
9,696
from django.shortcuts import render from rest_framework.viewsets import ViewSet from rest_framework.response import Response from .serializers import WeatherSerializer import requests import json import math import os import yaml from rest_framework.decorators import action from django.conf import settings def api_do...
2,427
708
from algorithms.backtrack import ( add_operators, permute, permute_iter, anagram, array_sum_combinations, unique_array_sum_combinations, combination_sum, find_words, pattern_match, ) import unittest from algorithms.backtrack.generate_parenthesis import * class TestAddOperator(unit...
5,420
2,115
import sys sys.path.append("/usr/lib/python2.7/site-packages") import redis _r = redis.Redis(host='localhost', port=6379, db=0) import cherrypy class Test(object): def index(self): _r.incr("/") return "OK!" index.exposed = True cherrypy.quickstart(Test())
284
106
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from config import db import config app = config.connex_app app.add_api('swagger.yml') @app.route('/') def home(): return 'homepage here' @app.route("/job") @app.route("/job/<string:job_id>") def job(job_id=""): return 'resul...
538
198
# -*- coding: utf-8 -*- import httplib as http from flask import request from framework.exceptions import HTTPError from framework.auth.decorators import must_be_logged_in from website.util import web_url_for from website.project.decorators import ( must_have_addon, must_be_addon_authorizer, must_have_permi...
4,939
1,543
# Copyright 2019 Extreme Networks, 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 i...
2,290
689
class solutionLeetcode_3: def lengthOfLongestSubstring(self, s: str) -> (int, str): if not s: return 0 left = 0 lookup = set() n = len(s) max_len = 0 cur_len = 0 for i in range(n): cur_len += 1 while s[i] in lookup: ...
4,983
1,543
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
9,114
2,492
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from sqlalchemy.ext.declarative import declared_attr from ggrc import db from ggrc.access_control.roleable import Roleable from ggrc.fulltext.mixin import Indexed from ggrc.models.associationproxy import as...
1,681
540
import subprocess, re, sys def get_coref_score(metric, path_to_scorer, gold=None, preds=None): output=subprocess.check_output(["perl", path_to_scorer, metric, preds, gold]).decode("utf-8") output=output.split("\n")[-3] matcher=re.search("Coreference: Recall: \(.*?\) (.*?)% Precision: \(.*?\) (.*?)% F1: (.*?)%", ou...
1,191
578
# coding=utf-8 from __future__ import unicode_literals from tornado.testing import AsyncTestCase from apps.core.models import (ModelBase, _get_master_engine, _get_slave_engine) from tornado.options import options from apps.core.urlutils import urlpattens from ...
16,878
5,378
import sys from sessions import get_session account_number = sys.argv[1] stage = sys.argv[2] function_name = sys.argv[3] version = sys.argv[4] function_arn = f'arn:aws:lambda:eu-west-2:{account_number}:function:{function_name}' boto_session = get_session(account_number, "TDRJenkinsLambdaRole" + stage.capitalize()) c...
622
208
# Árvore Huffman class node: def __init__(self, freq, symbol, left=None, right=None): # Frequência do Símbolo self.freq = freq # Símbolo (caracter) self.symbol = symbol # nó à esquerda do nó atual self.left = left # nó à direita do nó atual self.rig...
2,202
777
import argparse import json import base64 import hashlib import sys import binascii from optigatrust.util.types import * from optigatrust.pk import * from optigatrust.x509 import * private_key_slot_map = { 'second': KeyId.ECC_KEY_E0F1, '0xE0E1': KeyId.ECC_KEY_E0F1, '0xE0F1': KeyId.ECC_KEY_E0F1...
8,927
3,358
import unittest from graph import Graph class TestGraph(unittest.TestCase): def test_create_graph_simple(self): graph = Graph() graph.add_edge(0, 1) graph.add_edge(1, 2) graph.add_edge(2, 0) graph.add_edge(2, 0) # Test double edges don't make a difference self.assert...
3,532
1,411
#============================================================================== # Copyright 2011 Amazon.com, Inc. or its affiliates. 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 ...
2,033
545
import pytest from tequila import numpy as np from tequila.circuit.gradient import grad from tequila.objective.objective import Objective, Variable import operator def test_nesting(): a = Variable(name='a') variables = {a: 3.0} b = a + 2 - 2 c = (b * 5) / 5 d = -(-c) e = d ** 0.5 f = e ** ...
2,798
1,063
from getnear.config import Tagged, Untagged, Ignore from getnear.logging import info from lxml import etree import re import requests import telnetlib def connect(hostname, *args, **kwargs): url = f'http://{hostname}/' html = requests.get(url).text doc = etree.HTML(html) for title in doc.xpath('//titl...
7,649
2,486
from string import ascii_letters import textwrap from fontTools.misc.testTools import getXML from fontTools import subset from fontTools.fontBuilder import FontBuilder from fontTools.pens.ttGlyphPen import TTGlyphPen from fontTools.ttLib import TTFont, newTable from fontTools.subset.svg import NAMESPACES, ranges impo...
16,945
6,074
""" This script downloads the weight file """ import requests URL = "https://pjreddie.com/media/files/yolov3.weights" r = requests.get(URL, allow_redirects=True) open('yolov3_t.weights', 'wb').write(r.content)
211
82
""" Subprocessor for device messages """ import logging from ..utilities.tag import Tag from ..workers import device_worker_forward from ..workers import device_worker_startup from ..utilities.address import Address from ..utilities.status import Status from ..utilities.data_indexes import SubprocessorIndex _Subproces...
1,786
475
#!/usr/bin/env python # encoding: utf-8 """ @Author: yangwenhao @Contact: 874681044@qq.com @Software: PyCharm @File: __init__.py.py @Time: 2020/3/27 10:43 AM @Overview: """
174
94
from ninja.security.apikey import APIKeyQuery, APIKeyCookie, APIKeyHeader from ninja.security.http import HttpBearer, HttpBasicAuth def django_auth(request): if request.user.is_authenticated: return request.user
226
67
"""Add attribute to handle multiline information Revision ID: 66d4be40bced Revises: 6a809295d586 Create Date: 2018-05-16 12:13:32.023450 """ import sqlalchemy as sa from alembic import op from limonero.migration_utils import is_sqlite # revision identifiers, used by Alembic. revision = '66d4be40bced' down_revision =...
1,160
413
import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' SQLITE = 'db.sqlite3' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, SQLITE) + '?check_same_thread=False'
247
109
import pytest from flipy.lp_problem import LpProblem from flipy.lp_objective import LpObjective, Maximize from flipy.lp_variable import LpVariable from flipy.lp_expression import LpExpression from flipy.lp_constraint import LpConstraint from io import StringIO @pytest.fixture def problem(): return LpProblem('te...
4,372
1,442
from django.apps import AppConfig class InvoiceMedicineConfig(AppConfig): name = 'invoice_medicine'
106
35
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 5 08:42:24 2021 @author: gtucker """ from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_raises from landlab import HexModelGrid, RadialModelGrid, RasterModelGrid from landlab.components import Flexure, ListricKinemati...
5,893
2,349
from __future__ import print_function from __future__ import division import numpy as np from numpy import logical_not, ones from numpy.random import seed, randint from numpy import concatenate from random import sample from collections import Counter from .unbalanced_dataset import UnbalancedDataset class UnderSampl...
22,485
6,420
"""Word and pron extraction for (Mandarin) Chinese.""" import itertools import typing import requests from wikipron.extract.default import yield_pron, IPA_XPATH_SELECTOR if typing.TYPE_CHECKING: from wikipron.config import Config from wikipron.typing import Iterator, Word, Pron, WordPronPair # Select pro...
931
325
# (C) Datadog, Inc. 2022-present # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import pytest from datadog_checks.dev.testing import requires_py3 from datadog_checks.iis import IIS @pytest.mark.e2e @requires_py3 def test_e2e_py3(dd_agent_check, aggregator, instance): aggregator = dd...
420
162
from pathlib import Path import click import yaml from sklearn.model_selection import ParameterGrid from ertk.utils import PathlibPath, get_arg_mapping @click.command() @click.argument("param_grid", type=PathlibPath(exists=True, dir_okay=False)) @click.argument("output", type=Path) @click.option("--format", help="F...
1,174
344
from html.parser import HTMLParser class mangabeeSearchParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.lastTag = None self.lastClass = None self.urls = [] # Where we store our results def handle_starttag(self, tag, attr...
6,172
1,866
#!/usr/bin/python3 import os import threading import sys from Adafruit_BME280 import * from datetime import datetime from elasticsearch import Elasticsearch def readSensor(): # Timestamp for report timestamp = datetime.utcnow() # Recursively initiate next reading in a minute threading.Timer(60-float(datetime....
1,831
697
import eel_for_transcrypt as eel from web.common import InventoryItem @eel.expose def i_return_the_same(anything): return anything @eel.expose def a_generator(mn, mx): yield from range(mn, mx) @eel.expose @eel.apply_factories(inputfactory=InventoryItem) def return_a_dataclass(datac: InventoryItem): ...
456
172
# -*- coding: utf-8 -*- """ Tests for vector_tile/polygon.py """ import unittest from mapbox_vector_tile.polygon import make_it_valid from shapely import wkt import os class TestPolygonMakeValid(unittest.TestCase): def test_dev_errors(self): test_dir = os.path.dirname(os.path.realpath(__file__)) ...
6,989
3,413
import gym # from stable_baselines import DQN as deepq from stable_baselines import A2C as ac from stable_baselines.common.policies import MlpLnLstmPolicy import snake_bot if __name__ == '__main__': env = gym.make("snakebot-v0") env.debug_mode() exit(0)
275
107
""" Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considere...
2,179
701
import pyeccodes.accessors as _ def load(h): def wrapped(h): discipline = h.get_l('discipline') parameterCategory = h.get_l('parameterCategory') parameterNumber = h.get_l('parameterNumber') instrumentType = h.get_l('instrumentType') satelliteSeries = h.get_l('satelliteSer...
80,085
22,586
import numpy as np import cv2 import matplotlib.pyplot as plt from calibration_utils import calibrate_camera, undistort import glob import matplotlib.image as mpimg import pickle from threshold import binarize def perspective_transform(img, verbose=False): """ Execute perspective transform """ img_siz...
2,038
735
from __future__ import print_function # for localized messages from . import _, NOTIFICATIONDOMAIN # Config from Components.config import config, ConfigYesNo, ConfigNumber, ConfigSelection, \ ConfigSubsection, ConfigClock, ConfigYesNo, ConfigInteger, NoSave from Screens.MessageBox import MessageBox from Screens.Stan...
12,733
4,240
import numpy as np import pandas as pd import os from copy import deepcopy import datetime import pickle import time import copy os.system('export PYTHONPATH="$(pwd):$PYTHONPATH"') from ongoing.prescriptors.base import BasePrescriptor, PRED_CASES_COL, CASES_COL, NPI_COLUMNS, NPI_MAX_VALUES import ongoing.prescriptors....
29,709
9,419
from gevent import monkey; monkey.patch_all() import logging from gevent.server import StreamServer logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Receiver(object): """ Interface for a receiver - mimics Twisted's protocols """ def __init__(self): self.socket =...
1,876
519
# encoding: utf-8 import os import ssl import sys import csv import json import time import base64 from datetime import datetime from datetime import timedelta try: import pyodbc except ImportError: pass # PYTHON 2 FALLBACK # try: from urllib.request import urlopen, Request from urllib.parse import...
9,289
2,844
# -*- coding: utf-8 -*- import sys, os sys.path.insert(0, os.path.abspath('extensions')) extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'epub2', 'mobi', 'autoimage', 'code_example'] todo_inc...
5,001
1,664
"""Provides a class for constructing simulations based on Firedrake. Simulations proceed forward in time by solving a sequence of Initial Boundary Values Problems (IBVP's). Using the Firedrake framework, the PDE's are discretized in space with Finite Elements (FE). The symbolic capabilities of Firedrake are used t...
17,031
4,434
from collections import Counter import json import os import re import subprocess import attr import yaml @attr.s class ExploreView(object): data = attr.ib(repr=False) explore = attr.ib(init=False, repr=False) name = attr.ib(init=False, repr=True) source_view = attr.ib(init=False, repr=False) d...
16,389
5,411
"""Utilities for writing unit tests""" import numbers import numpy as np ####################################################################### # Assertions # ####################################################################### def is_symmetric(X): ""...
4,306
1,282
import unittest from libsaas.executors import test_executor from libsaas.services import googleoauth2 class GoogleOauth2TestCase(unittest.TestCase): def setUp(self): self.executor = test_executor.use() self.executor.set_response(b'{}', 200, {}) self.service = googleoauth2.GoogleOAuth2('...
1,373
406
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import jsonfield.fields import post_office.fields import post_office.validators import post_office.models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations....
5,654
1,538
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """Store dataset indexes of datapoints selected by k-means algorithm.""" from argparse import ArgumentParser import numpy a...
3,890
1,247
from cattr.errors import StructureHandlerNotFoundError __all__ = ["StructureHandlerNotFoundError"]
100
26
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from main import Config from pyrogram import filters from pyrogram import Client #from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from urllib.parse import quote_plus, unquote import math, os, time, datetime, aiohttp, asyncio, mimetypes, loggi...
4,873
1,764
from __future__ import absolute_import from __future__ import unicode_literals import collections import contextlib import shutil import subprocess import tempfile from git_code_debt.util.iter import chunk_iter from git_code_debt.util.subprocess import cmd_output Commit = collections.namedtuple('Commit', ('sha', 'd...
2,304
727
def f(x): if x <= -2: f = 1 - (x + 2)**2 return f if -2 < x <= 2: f = -(x/2) return f if 2 < x: f = (x - 2)**2 + 1 return f x = int(input()) print(f(x))
215
101