text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/CarePlan Release: DSTU2 Version: 1.0.2 Revision: 7202 """ from typing import Any, Dict from typing import List as ListType from pydantic import Field, root_validator from . import fhirtypes from .backboneelement import BackboneElement from ....
15,002
4,164
""" Socket-only coroutine operations and `Socket` wrapper. Really - the only thing you need to know for most stuff is the :class:`~cogen.core.sockets.Socket` class. """ #TODO: how to deal with requets that have unicode params __all__ = [ 'getdefaulttimeout', 'setdefaulttimeout', 'Socket', 'SendFile', 'Re...
19,993
6,109
from flask import Blueprint, current_app, send_from_directory BLUEPRINT_SIDE = Blueprint('side', __name__) @BLUEPRINT_SIDE.route('/logo.png', endpoint='logo') @BLUEPRINT_SIDE.route('/favicon.ico') @BLUEPRINT_SIDE.route('/favicon.png') def favicon(): return send_from_directory( current_app.static_folder, ...
399
146
t=input("Type a string") s=t.lower() alll="abcdefghijklmnopqrstuvwxyz1234567890" for c in alll: d={c:s.count(c) for c in s} dt=sorted(d.items(), key=lambda x: x[1], reverse=True) for k,v in dt.items(): print(k,":",v)
226
112
from sys import argv from executor_exporter.exporter import metrics def update_readme_metrics(readme_path): columns = ("Name", "Type", "Labels", "Description") sep = " | " table_lines = [sep.join(columns), sep.join(["---"] * len(columns))] for metric in metrics: table_lines.append( ...
1,183
370
import accounts.models import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterModelManagers( name='hierarchicuser', managers=[ ...
1,717
477
___assertIs(not {}, True) ___assertTrue({1: 2}) ___assertIs(bool({}), False) ___assertIs(bool({1: 2}), True)
109
45
from django import forms from django.utils.translation import gettext_lazy as _ from django.conf import settings from django.core.exceptions import ValidationError from datetime import datetime, timedelta from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit from danceschool.c...
8,575
2,452
import torch import torch.nn as nn from torch.nn.parameter import Parameter from typing import List, Tuple, Dict import numpy as np from torch.autograd import Variable class DepGCN(nn.Module): """ Label-aware Dependency Convolutional Neural Network Layer """ def __init__(self, dep_num, dep_dim, in_fe...
32,292
11,162
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
2,293
752
from colorama import Fore good = Fore.GREEN + '[*]' + Fore.RESET bad = Fore.RED + '[!]' + Fore.RESET warning = Fore.RED + '[$]' + Fore.RESET excellent = Fore.CYAN + '[$]' + Fore.RESET debug_point = Fore.RED + '{*}' + Fore.RESET
228
96
"""Define Gaussian function objects. This module defines the Gaussian class and the GaussianRange class. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import object import numpy as np from six.moves import range class Gaussian(object...
7,206
1,988
import requests import re from urlparse import urlparse from bs4 import BeautifulSoup from collections import defaultdict class SavingZelda(object): def __init__(self, url, logger): self.url = url self.logger = logger self.body = "" self.not_checked = [] self.list_of_links...
3,538
1,108
"""forms_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class...
1,352
422
import requests from bs4 import BeautifulSoup from news import News from .abstract_news_extractor import AbstractNewsExtractor class FolhaNewsExtractor(AbstractNewsExtractor): def __init__(self): super().__init__('https://www.folha.uol.com.br') def extract_news(self): news = [] html_...
635
193
""" Provides a simple Python client for RBI REST API """ from . import exceptions import requests __version__ = "0.1.0" class PyRBI: """ A client for RBI Blockchain's REST API Usage: Create a new instance using your credentials >>> cli = PyRBI("user", "pass") From there on you can creat...
3,871
1,082
#!/usr/bin/env python __author__ = 'Sergei F. Kliver' import argparse import os from copy import deepcopy from Bio import SeqIO from Bio.Seq import Seq parser = argparse.ArgumentParser() parser.add_argument("-i", "--input_file", action="store", dest="input_file", help="Input file with sequences...
1,426
452
teste = list() teste.append('Gustavo') teste.append(40) galera = [] galera.append(teste) #neste caso estamos criando uma ligação entre as duas listas teste[0] = 'Maria' teste[1] = 22 galera.append(teste) print(teste) print(galera) # No caso os elementos não se acumularam porque não foi feita uma cópia dos elementos da ...
438
151
from py_db import db import NSBL_helpers as helper db = db("NSBL") table_dict = {"register_batting_analytical": "a.player_name" , "register_batting_primary": "a.player_name" , "register_batting_secondary": "a.player_name" , "register_batting_splits": "a.player_name" , "register_pitching_analytical":...
1,637
689
#!/usr/bin/env python3 # # I waive copyright and related rights in the this work worldwide # through the CC0 1.0 Universal public domain dedication. # https://creativecommons.org/publicdomain/zero/1.0/legalcode # # Author(s): # Tom Parker <tparker@usgs.gov> """ watch for new webcam images.""" import zmq import to...
1,287
403
import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm class KalmanFilter(): def __init__(self, data, dim=1): self.data = data.values self.timelength = len(self.data) # 潜在変数 self.x = np.zeros((self.timelength+1, dim)) self.x_filter = np.zeros((self.timelen...
1,866
781
from PyQt5 import QtWidgets, QtCore from math import floor import numpy as np from . _base import _SelectableArtist2D class _DraggablePoints(_SelectableArtist2D): dragged = QtCore.pyqtSignal(object, int, int, float) dragging_stopped = QtCore.pyqtSignal() point_added = QtCore.pyqtSigna...
4,394
1,931
#!/usr/bin/env python # # Download and convert TartanAir data <https://theairlab.org/tartanair-dataset/>. # # NOTE The whole dataset is several terabytes, so be sure to tune the `LEVELS` and # `DATASETS` variables before running. # # It is recommended to install "AzCopy", an official tool for Azure, to get tolerable # ...
7,370
2,492
# -*- coding: utf-8 -*- """ Module for testing TsDB class """ from qats import TimeSeries, TsDB import unittest import os import numpy as np import sys # todo: add tests for listing subset(s) based on specifying parameter `names` (with and wo param. `keys`) # todo: add test for getm() with fullkey=False (...
24,534
8,076
# Solution of; # Project Euler Problem 105: Special subset sums: testing # https://projecteuler.net/problem=105 # # Let S(A) represent the sum of elements in set A of size n. # We shall call it a special sum set if for any two non-empty disjoint # subsets, B and C, the following properties are true: # # S(B) ≠ S(C);...
1,257
510
# Copyright (c) 2006-2013 Regents of the University of Minnesota. # For licensing terms, see the file LICENSE. import conf import g from item import attachment from item import item_base from item import item_versioned from item.util.item_type import Item_Type from util_.streetaddress import ccp_stop_words log = g.l...
3,673
1,266
from nurses_2.app import App from .sandbox import Sandbox class SandboxApp(App): async def on_start(self): self.add_widget(Sandbox(size=(31, 100))) SandboxApp().run()
183
70
#!/usr/bin/env python3 import os import numpy as np from midas2.common.utils import tsprint, command, split, OutputStream def bowtie2_index_exists(bt2_db_dir, bt2_db_name): bt2_db_suffixes = ["1.bt2", "2.bt2", "3.bt2", "4.bt2", "rev.1.bt2", "rev.2.bt2"] if all(os.path.exists(f"{bt2_db_dir}/{bt2_db_name}.{ext}...
4,985
1,957
import numpy as np import cv2 class FindPoint: def __init__(self,img): self.window_height = 10 self.nwindows = 15 self.margin = 20 self.minpix = 70 self.center = img.shape[1]/2 def findpoint(self, img): out_img = np.dstack((img, img, img)) h, w = img.sha...
3,541
1,361
import time from datetime import datetime from datetime import timedelta from bson import ObjectId from bson.errors import InvalidId from dynaconf import settings from ibutsu_server.mongo import mongo from ibutsu_server.tasks.queues import task from ibutsu_server.tasks.results import add_result_start_time from ibutsu_...
6,198
1,827
# Generated by Django 2.1.7 on 2019-05-14 20:36 from django.db import migrations from blocks.models import AnimationName, AnimationTrigger import anki_vector def generate_names(apps, schema_editor): """ Helper function to populate names of animations and triggers and update their status """ def __update_or_...
1,457
450
from django.apps import AppConfig class GroupsAppConfig(AppConfig): name = 'app.groups' verbose_name = "Учебные группы"
130
43
from collections import namedtuple # É tipo um dicionario, é mais lento, mas é imutável! #Jogador é a classe | #Atributos da classe J = namedtuple('Jogador', ['nome', 'time', 'camisa', 'numero']) j = J('Abel Hernadez', 'Flu', 99, 100) #Adicionando valores j2 = J('Fred', 'Fluminense', 9, 157) ...
830
319
import sys from typing import List import click from decker.conf import Config from decker.utils import print_done from .pool import FormatterBackendPool from .services import run_format @click.option( '-b', '--backend', type=click.Choice([backend.id for backend in FormatterBackendPool.all()]), mul...
1,330
440
from app import app, db from app.models import Category, Priority, Status from sqlalchemy.exc import SQLAlchemyError category = 'Uncategorized' priorities = ['Low', 'Medium', 'High', 'Urgent'] statuses = ['Open', 'Resolved', 'Pending', 'Closed'] def db_commit(): try: db.session.commit() print('Category, prioriti...
709
253
from .objectives import MSELoss, CrossEntropyLoss from .models import Sequential, Model, Module from .grad_fn import Parameter, Tensor from .td_functional import *
164
49
# plot prd scores import os import json from matplotlib import pyplot as plt import argparse parser = argparse.ArgumentParser() parser.add_argument("json_files", nargs="*") parser.add_argument("--output_fig", type=str, default='prd.png') args = parser.parse_args() def load_jsons(file_paths): scores, labels = [], []...
2,527
843
import numpy as np import matplotlib.pyplot as plt import keras def evaluate_model(model, split_sets): training_error = model.evaluate(split_sets['X_train'], split_sets['y_train'], verbose=0) print('training error = ' + str(training_error)) testing_error = model.evaluate(split_sets['X_test'], split_sets[...
2,218
654
#!/usr/bin/env python3.4 import stats.data import stats.plot import stats.preprocess import pandas import numpy as np import matplotlib.pyplot as plt import matplotlib.dates import datetime from statsmodels.tsa.api import VAR, DynamicVAR sse_indices = stats.data.sse_indices() for i in sse_indices: d = stats.data.g...
1,837
638
from typing import Dict, List from classifier.preprocessing.article_theme_tokenizer import ArticleThemeTokenizer from data_models.ThemeStat import ThemeStat class ThemeWeights: theme_stats: List[ThemeStat] theme_tokenizer: ArticleThemeTokenizer def __init__(self, theme_stats: List[ThemeStat], theme_tok...
2,086
614
#!/usr/bin/python from pssh import SSHClient, ParallelSSHClient, utils import datetime import time import random import sys output = [] hosts = ['client0', 'client1', 'client2','client3', 'client4'] client = ParallelSSHClient(hosts) values = ["bear","cake","fork","pipe","gun"] def open_movies(my_values, delay): c...
2,688
988
# -*- coding: utf-8 -*- """Cache Recommender. dump : run topN predict item for each user, and dump them to file like object(disk file or memory). load : recover from file like object, return CacheRecommender. Note that this recommender just a tiny version of the original one, which can...
3,744
1,238
import logging from typing import ( Any, Sequence, Tuple, Type, ) from eth_utils.toolz import accumulate from p2p.abc import ( CommandAPI, ProtocolAPI, TransportAPI, ) from p2p.constants import P2P_PROTOCOL_COMMAND_LENGTH from p2p.typing import Capability class BaseProtocol(ProtocolAPI):...
2,335
714
import binascii import json import time import jsonschema from .crypter import AESCipher from .exceptions import AccessTokenValidationError, RefreshTokenValidationError, TokenExpiredError, TokenSchemaError class BaseToken(dict): _schema = {} def is_valid(self, age=None, raise_exception=False): try...
6,314
1,739
from serial import Serial import struct from math import log10, sin, cos, acos, atan2, asin, pi, sqrt import time from collections import namedtuple from colorama import Fore # agmpt_t = namedtuple("agmpt_t", "accel gyro mag pressure temperature timestamp") # ImageIMU = namedtuple("ImageIMU","image accel gyro tempera...
6,060
2,146
import base64 import svgwrite import svgwrite.container import svgwrite.shapes import svgwrite.image import bs4 import os from urllib.request import urlopen from selenium import webdriver index = 0 code = input('덱 코드를 입력하세요.> ') os.mkdir(code) url = 'https://pokemoncard.co.kr/recipe/search?code=' + code driver = we...
1,718
679
#!/usr/bin/python from database_tables import DrawingHistory from webserver_utils import verify_id import cgi import cgitb import datetime def createNew(title, creator, history, layers): kwargs = {"date": datetime.datetime.now(), "title": title, "history_json": history, ...
967
300
class Environment: PRICE_IDX = 4 # 종가의 위치 def __init__(self, chart_data=None, training_data=None): self.chart_data = chart_data self.training_data = training_data self.observation = None self.idx = -1 def reset(self): self.observation = None self.idx = -1 ...
746
244
''' 2019-08-07 00:01 Method: 20 x 5 grid over (camera x lighting) ''' VIEW_NUM, LIGHTING_NUM = 20, 5 import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from src.param_decomposer import AllParams def generate_params(shape_list, randomizer): nowpath = os.path.dirname(os.path...
2,148
707
import plotly.graph_objects as go import plotly.figure_factory as ff import numpy as np import calculations as calc from plotly.subplots import make_subplots def initialize_albedo_plot(T_min, T_opt): # how does the growth curve of the Daisies look like? gw = [] gb = [] # amount of intervals to plot ...
12,219
4,577
from opendart.config.config import *
36
11
"""A SSH Interface class. An interface to ssh on posix systems, and plink (part of the Putty suite) on Win32 systems. By Rasjid Wilcox. Copyright (c) 2002. Version: 0.2 Last modified 4 September 2002. Drawing on ideas from work by Julian Schaefer-Jasinski, Guido's telnetlib and version 0.1 of pyssh (htt...
10,720
3,413
from clifford import g3c import numpy as np import scipy.optimize as opt from pygacal.rotation.costfunction import restrictedImageCostFunction, restrictedMultiViewImageCostFunction from pygacal.rotation import minimizeError from pygacal.rotation.mapping import BivectorLineImageMapping, BivectorLineMapping, LineProper...
3,894
1,375
import unittest from collections import OrderedDict from dbcut.utils import sorted_nested_dict def test_simple_dict_is_sorted(): data = { "c": 1, "a": 2, "b": 3, } expected = OrderedDict([("a", 2), ("b", 3), ("c", 1)]) assert expected == sorted_nested_dict(data) def test_nes...
1,320
496
# -*- coding: utf-8 -*- # Copyright 2019, Sprout Development Team # Distributed under the terms of the Apache License 2.0 import os import asyncio import asyncpg from tortoise import Tortoise import sprout class Runner(sprout.Log): """An object-oriented interface to the sprout utilities. Args: ...
4,704
1,452
#!/usr/bin/env/python3 import unittest from pi_gpio_service import service class TestPiGpioService(unittest.TestCase): def test_input_pins(self): pins = { '23': {'name': 'IN_23', 'pin_direction': 'input'}, '24': {'name': 'OUT_24', 'pin_direction': 'output'}, '25': {'...
1,033
354
import string import regex import pandas as pd from pandas.tests.io.parser import index_col sangam_text_folder = "./sangam_tamil_text/" sangam_poem_folder = "./sangam_tamil_poems/" sangam_csv_folder = "./sangam_tamil_csv/" data_files = ['agananuru','purananuru','ainkurunuru','kalithokai', 'kurunthokai', 'natrinai', 'p...
2,726
1,353
from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404 from rest_framework import permissions from rest_framework import viewsets from django.views.decorators.csrf import csrf_exempt from django.core.files.storage import FileSystemStorage from rest_framework.generics import ( ...
4,026
1,155
""" Flask Extension for OPA """ import requests from flask.app import Flask __version__ = "1.0.0" class OPAException(Exception): """Exception evaluating a request in OPA""" def __init__(self, message): super().__init__(message) class OPAUnexpectedException(OPAException): """Unexpected error ev...
6,256
1,849
import sys import os import csv from random import shuffle import cv2 import numpy as np import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Flatten,\ Dense,\ ...
8,920
2,909
#! -*- encoding: utf-8 -*- from openerp import addons from openerp.osv import fields, osv, orm from openerp import tools from openerp.tools.translate import _ class ir_ui_view(orm.Model): _inherit = 'ir.ui.view' _columns={ 'enlarge_form' : fields.boolean('Use full width of the screen?' ,help='Set to...
3,807
1,096
from machaon.app import AppRoot, deploy_directory, transfer_deployed_directory from machaon.process import Spirit, TempSpirit from machaon.types.shell import Path def test_deploy(tmpdir): deploydir = tmpdir.mkdir("deploy") deploy_directory(Path(deploydir)) assert deploydir.join("machaon").check() ass...
1,148
381
#Securities array access to Security Objects: self.Securities["IBM"].Price
74
23
"""empty message Revision ID: 1d09e9261d5 Revises: 40d93619b7d Create Date: 2016-12-16 11:38:41.336859 """ # revision identifiers, used by Alembic. revision = '1d09e9261d5' down_revision = '40d93619b7d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - plea...
502
212
""" API for attaching, detaching, and reading extended metadata to HopsFS files/directories. It uses the Hopsworks /xattrs REST API """ from hops import constants, util, hdfs from hops.exceptions import RestAPIError import urllib def set_xattr(hdfs_path, xattr_name, value): """ Attach an extended attribute to...
5,732
1,824
from .vis import df_from_file, df_from_dir, filter_by, PivotTable from .lines import plot_lines
96
33
# 5 27 20 def smallest_subarray_with_given_sum(s, arr): # TODO: Write your code here windowStart, minLen, currSum = 0,100,0 for windowEnd in range(len(arr)): currSum += arr[windowEnd] while currSum >= s: minLen = min(minLen, windowEnd - windowStart +1) currSum -= arr[windowStart] win...
2,173
768
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2014 Lukas Kemmer # # 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 require...
16,028
5,221
class Solution(): def __init__(self, A, B): self.A = A self.B = B def printAlternativelySameSize(self): """ Assumes that len(self.A) == len(self.B) != 0 Alternatively print each element in the two Lists """ if (len(self.A) != len(self.B)): raise Exception("the two lists must be of same ...
2,119
980
import unittest from pokeher.theaigame_bot import TheAiGameBot class QuietBot(TheAiGameBot): def log(self, msg): pass class TheAiGameBotTest(unittest.TestCase): """Test that the bot class is instantiated properly and has all the methods that it's supposed to""" def setUp(self): self.bo...
981
322
import unittest from matterix import Tensor import numpy as np class TestTensorExponents(unittest.TestCase): def test_simple_exp(self): an = np.random.randint(0, 10, (10, 10)) at = Tensor(an, requires_grad=True) result = at * at result.backward(gradient=Tensor.ones_like(result)) ...
429
151
#!/usr/bin/env python2 # -*- Mode: python -*- # # DESCRIPTION: Setup and run n chord nodes. # # import getopt import os import sys import time import random import signal import threading def print_usage(): print print "Usage: run_lookups -p <port> [-t <sleep_time>] [-v <vantages>] [-s <seed>] lookup_exec outp...
2,161
811
""" Тесты для задания 2.4. """ from unittest import TestCase, main from fractions import Fraction from tasks import task_2_4 class TestFractionFromString(TestCase): def test_fraction_from_string__CorrectArguments__ShouldReturnCorrectResult(self): """ Проверяет работу с корректными данными. ...
1,722
584
from aiohttp import web from aiohttp_security import authorized_userid from aioweb.conf import settings async def redirect_authenticated(request): user_id = await authorized_userid(request) if user_id and not request.is_ajax(): redirect_url = request.query.get('redirect_to') if not redirect_ur...
1,007
290
class Solution(object): def subarraySum(self, nums, k): sum = 0 res = 0 sum_history = {0:1} for i in nums: sum+=i if sum - k in sum_history: res+=sum_history[sum-k] if sum in sum_history: sum_history[sum]+=1 ...
442
149
""" Helper script that copies all of the files for an arrays sample into the dev aou input bucket. This will trigger the submit_aou_workload cloud function for each file. When all files have been uploaded, it will launch an arrays workflow via the workflow launcher (but only if a workflow with that chipwell barcode & a...
3,901
1,476
import numpy as np import cv2 from src import lane_finder as lf from src import parameters import argparse class WarpFinder: def __init__(self, image, horizon = 400, x1 = 500): self.image1 = image self._horizon = horizon self._x1 = x1 def onChangeHorizon(pos): self._ho...
2,019
693
############### # Ballot Parser for UC Berkeley Results # # This ballot parser has been tailored to the ballot # system used by UCB. If you use another software # to define ballots, ensure the data returned by the # ballot parser returns data in the following fashion: # # [ # { # "ballot_id": "unique_ballot_i...
2,041
632
import collections import inspect import time import re # module config: disable_tracing = False indent = True # indentation for log output _log_indent = dict() def indent_str(cnt, end=False): """ indent string :param cnt: indentation count :param end: close actual indentation? :return: ""...
5,971
1,849
#!python3 #encoding:utf-8 from urllib.request import build_opener, HTTPCookieProcessor from urllib.parse import urlencode from http.cookiejar import CookieJar import pprint import dataset class HatenaSite(object): def __init__(self, path_hatena_accounts_sqlite3): self.path_hatena_accounts_sqlite3 = path_ha...
1,489
520
# -*- coding: utf-8 -*- # Copyright (c) 2015, Bravo Logistics and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class Vehicle(Document): pass @frappe.whitelist(allow_guest=True) def change_status(**a...
767
285
#!coding:utf-8 import json import pymysql import pandas as pd class ReadJson(): def __init__(self, host, user, passwd, db, table, sort=None, _filter=None): self.host =host self.user =user self.passwd = passwd self.db = db self.table = table self.sort = sort ...
3,780
1,182
# -*- coding: utf-8 -*- from xml.dom import minidom import re # Thrown on any dictionary error class Dict2XMLException(Exception): pass def _dict_sort_key(key_value): key = key_value[0] match = re.match('(\d+)__.*', key) return match and int(match.groups()[0]) or key _iter_dict_sorted = lambda dic: ...
3,583
1,090
import cv2 import argparse import numpy as np ap = argparse.ArgumentParser() ap.add_argument('-i', required = True, help = 'Enter the path of Image') args = vars(ap.parse_args()) image = cv2.imread(args['i']) def wheel(image, center): i = 1 while (True): if i > 359: cv2.imshow('Wheel', image) cv2.waitKey(...
1,247
504
import getflightdata import requests from bs4 import BeautifulSoup import random import json import pymongo import datetime from Utils.config import config # import config mongoConf = config['mongo'] feichangzun = 'http://www.variflight.com/flight/fnum/' feichangzunhouzui = '.html?AE71649A58c77&fdate=' def get_h...
3,972
1,420
import numpy as np import cv2 import face_recognition import time # Load a sample picture and learn how to recognize it. me_image = face_recognition.load_image_file("known/joakim.png") me_face_encoding = face_recognition.face_encodings(me_image)[0] known_face_encodings = [ me_face_encoding, ] known_face_names = [...
2,402
809
# coding: utf-8 """ xlTables - Load/generate table data with Excel from python dictionary structures cunningr - 2020 Requires openpyxl >= 2.6.2, jsonschema """ import os import openpyxl from openpyxl import Workbook from sdtables import xlTables from tabulate import tabulate class SdTables: ...
8,576
2,537
""" --- Compare Functions --- Simple Two functions f and g are provided as inputs to checkio. The first function f is the primary function and the second function g is the backup. Use your coding skills to return a third function h which returns the same output as f unless f raises an exception or returns None. In thi...
2,473
696
""" yawndb.sync ~~~~~~~~~~~ Sync YAWNDB transport. Use standart socket object methods. """ import time import json import socket import urllib2 import logging from collections import deque from yawndb._base import _YAWNDBBase _logger = logging.getLogger(__name__) class YAWNDB(_YAWNDBBase): """Syn...
3,402
1,048
from setuptools import setup, find_packages with open('README.rst', 'r') as infile: read_me = infile.read() setup( packages=find_packages(), name='depq', version='1.5.5', description='Double-ended priority queue', long_description=read_me, author='Ofek Lev', author_email='ofekmeister@...
1,209
367
from hypothesis import strategies from rithm import Fraction from rene import MIN_CONTOUR_VERTICES_COUNT from rene.exact import (Contour, Point) integers = strategies.integers() non_zero_integers = integers.filter(bool) scalars = (integers | strategies.fractions() | strategies.build...
880
266
/* Bendy and the Ink Machine, BATIM, and all graphics and sounds are © The Meatly NOT AN OFFICIAL BENDY AND THE INK MACHINE PRODUCT. NOT APPROVED BY OR ASSOCIATED WITH THEMEATLY GAMES, LTD. Code below released under GPLv2 */ import wx import subprocess from random import randint from time import sleep ...
2,834
1,048
#!/usr/bin/env python3 import os from skimage import io from skimage import color from PIL import Image #TODO Multi-thread def avg_brightness(image_list): """ A list of grey scale images """ brightness_per_block=[] for image in image_list: img_shape = image.shape img_Size = image...
1,347
480
# Copyright 2021 DAI Foundation # # 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,...
5,504
1,791
# Copyright 2019 DeepMind Technologies Ltd. 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 appl...
3,280
1,045
from PyQt6.QtWidgets import QApplication, QWidget import sys # komentarz app = QApplication(sys.argv) # ([]) -bez argumentów window = QWidget() window.show() app.exec()
176
64
import argparse import os import subprocess from typing import List, Sequence, Text import textwrap import numpy as np import pandas as pd import sklearn import tensorflow as tf import tensorflow_addons as tfa import transformers import data import models import ga def train(model_path: Text, train_data_p...
10,952
3,445
import sys from kb import * #receives a list of setences if it is in test mode def main(lista=None): sentences = [] if lista is None: with sys.stdin as f : #open stdin as a file lines = f.readlines() for line in lines: # convert each line to a python object lin...
814
229
from .base_mixins import BaseLoggingMixin from .models import APIRequestLog class LoggingMixin(BaseLoggingMixin): def handle_log(self): """ Hook to define what happens with the log. Defaults on saving the data on the db. """ APIRequestLog(**self.log).save() class Logging...
472
147
from typing import Iterator, List, Optional, Sequence, Tuple, TypeVar _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") def rzip_longest( seq1: Sequence[_T1], seq2: Sequence[_T2] ) -> Iterator[Tuple[_T1, Optional[_T2]]]: """Make an iterator over tuples, with elements from the input sequences. If the second sequ...
758
284