text
string
size
int64
token_count
int64
# Auto generated by 'inv collect-airflow' from airfly._vendor.airflow.models.baseoperator import BaseOperator class DockerOperator(BaseOperator): image: "str" api_version: "typing.Union[str, NoneType]" command: "typing.Union[str, typing.List[str], NoneType]" container_name: "typing.Union[str, NoneType...
1,573
576
import databases import os import sqlalchemy import sys import urllib from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from nanoid import generate from pathlib import Path from pydantic import BaseModel sys.path.append(str(Path(__file__).resolve().parents[1].joinpath("ml"))) from processte...
3,311
1,121
from dataclasses import dataclass from types import FunctionType from typing import Optional import ppb from ppb.systemslib import System from ppb.utils import get_time @dataclass class Timer: end_time: float callback: FunctionType repeating: float = 0 clear: bool = False until: float = None ...
1,496
444
from django.contrib import admin from django.urls import path, include from user import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static import notifications.urls from django.conf.urls import url # from chat import views ...
2,813
905
import os import shutil import logging import urllib.request import subprocess from molot.builder import git_hash class Context: """Base context with common operations.""" def ensure_dir(self, path: str, keep_files: bool): """Ensures directory path exists. Arguments: path {str} -...
1,974
566
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from base_functions import BaseFunctions class SpringIO(BaseFunctions): def __init__(self): self.sub_eco = 'spring' self._output_file = None super().__init__(self.sub_eco) def process(self): for item in self._config.get('depende...
2,720
721
from tests.utils import W3CTestCase class TestGridItemsSizingAlignment(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'grid-items-sizing-alignment-'))
171
60
from conans import CMake, ConanFile, tools from conan.tools.microsoft import is_msvc import functools required_conan_version = ">=1.33.0" class LightGBMConan(ConanFile): name = "lightgbm" description = "A fast, distributed, high performance gradient boosting (GBT, GBDT, GBRT, GBM or MART) framework based on ...
3,923
1,281
import unittest try: from coding_problems.src.algorithms.highest_product_of_3 import solution except ImportError as e: from coding_problems.src.algorithms.answers.highest_product_of_3 import \ solution class Test_Highest_Product_Of_3(unittest.TestCase): def test_short_list(self): actual =...
1,417
489
# Generated by Django 2.2.4 on 2019-09-09 10:51 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('marketing', '0011_auto_20190904_1143'), ] operations = [ migrations.AlterModelOptions( name='duplicatecontacts', options={'o...
357
133
from argparse import ArgumentParser from pathlib import Path import time import numpy as np import cv2 from datetime import datetime import requests DIFF_THRESHOLD = 30 DEFFAULT_SLEEP = 1 LINE_ENDPOINT = 'https://uketori.herokuapp.com/important' VISION_ENDPOINT = 'https://southcentralus.api.cognitive.microsoft.com/cus...
2,574
918
#!/usr/bin/python # -*- coding: UTF-8 -*- import sys, os sys.path.append('../') from BAAlgorithmUtils.TireTreeUtil import TireTree if __name__ == '__main__': treeInstance = TireTree() treeInstance.train('aababbaba') treeInstance.train('aababba') treeInstance.train('aababbabab') treeInstance.train...
820
307
"""Mie module.""" import numpy as np NANG = 91 NMXX = 150e3 def mie_bohren_huffman(x, refrel, nang=NANG): """ Compute mie scattering based on Bohren and Huffman theory Parameters ---------- x: float Size parameter = k*radius = 2π/λ * radius (λ is the wavelength in the medium ar...
7,286
2,963
from __future__ import absolute_import import redis import re import ujson as json from itertools import islice, izip from ..data import Store, ObjectStore, FieldStore, SetStore from nel import logging log = logging.getLogger() class RedisStore(Store): """ Abstract base class for stores built on redis """ de...
4,516
1,511
import torch import torch.nn.functional as F from torch import nn from models import MLP from action_utils import select_action, translate_action class CommNetMLP(nn.Module): """ MLP based CommNet. Uses communication vector to communicate info between agents """ def __init__(self, args, num_inputs...
9,885
3,036
n1 = int(input('Digite um número')) n2 = int(input('Digite um número')) n3 = int(input('Digite um número')) if n1 > n2 and n1 > n3 : print('o maior é {}'.format(n1)) elif n2 > n1 and n2 > n3 : print('o maior é {}'.format(n2)) else : print('o maior é {}'.format(n3)) if n1 < n2 and n1 < n3 : print('o meno...
449
188
import logging import json from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import ParseError from rest_framework import status from rest_framework.authentication import BasicAuthentication from rest_framework.permissions import IsAuthenticated from d...
2,361
698
from .bilibiliuploader import BilibiliUploader from .core import VideoPart from . import BiliAuth __version__ = '0.0.6'
121
42
from database.database import NichijouDatabase NichijouDatabase()
68
20
#!/usr/bin/python3 def teste_biometry(): print('Em desenvolvimento')
73
29
# https://zhuanlan.zhihu.com/p/25610149 import numpy as np import matplotlib.pyplot as plt import math def p(x): #standard normal mu=0 sigma=1 return 1/(math.pi*2)**0.5/sigma*np.exp(-(x-mu)**2/2/sigma**2) #uniform proposal distribution on [-4,4] def q(x): #uniform return np.array([0.12...
927
458
from django.shortcuts import render # Create your views here. def myfunc_with_events(event, context): print('here!!!') print(event)
140
43
from io import StringIO import traceback import numpy as np import zmq import errno import uuid import logging from awrams.utils.metatypes import ObjectDict as o import subprocess class Chunk: def __init__(self,x,y): self.x = x self.y = y self.shape = (1,self.y.stop - self.y.start) def...
4,573
1,492
from .tendermint_block_ingester import TendermintBlockIngester from common.utils.networks import ATOM, RUNE, SCRT, KAVA, OSMO atom_block_ingester = TendermintBlockIngester(ATOM) rune_block_ingester = TendermintBlockIngester(RUNE) scrt_block_ingester = TendermintBlockIngester(SCRT) kava_block_ingester = TendermintBlock...
387
153
from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.html import format_html, urlencode from django.utils.translation import ugettext_lazy as _ from apps.projects.models import Case from app...
1,941
607
import time import gfootball.env as football_env import random class Agent: def __init__(self): pass if __name__ == '__main__': env = football_env.create_environment(env_name='1_vs_1_easy', representation='extracted', render=True) state = env.reset() action_simple = ...
931
275
import numpy as np import seaborn as sns import matplotlib.pyplot as plt # plot edible / poisonous def basic_plots(data): plt.figure(figsize=(15, 8)) fig, ax = plt.subplots() sns.countplot(x=data['odor'], hue=data['is-edible'], palette=['black', 'blue'], data=data) plt.ylabel('Number of Mushrooms') ...
2,724
1,043
#!/usr/bin/env python3 class Fdisk(): ''' Composes bash command string capable of creating partitions for given disk ''' def __init__(self, disk): self.disk = disk self.query = '' self.partitionsCount = 0 def addPrimaryPartition(self, size, type): self.partitionsCo...
3,499
1,092
import unittest from simpletr64.devicetr64 import DeviceTR64 class TestLan(unittest.TestCase): def test_AmountOfHostsConnected(self): data = """<?xml version="10"?> <root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:ms="urn:microsoft-com:wmc-1-0" xmlns:pnpx="http://schemasmicrosoftcom/windows/pnp...
4,583
1,534
# Purpose: Following clean up and preparation of downloaded ABS data, this script will provide a summary # Display on screen and write a csv file with summary data for input csv file(s) # SUMMARY OUTPUT FIELDS, by variable excluding index (col 1): # count mean std min 25% 50% 75% max # Author...
1,979
636
#!/usr/bin/python from common import createTopology createTopology( 's1', [ [ 'red1', { 'ip': '10.0.0.1/8', 'mac': '00:00:00:00:aa:01' } ], [ 'blue1', { 'ip': '10.0.0.1/8', ...
391
153
#PALINDROMIC CIPHERS def value(s): i = 0 prod = 1 for i in range(len(s)): prod = prod * (ord(s[i])-96) return prod test = int(input()) for i in range(test): string = str(input()) stringr = string[::-1] if string == stringr: print("Palindrome") else: print(value(...
329
126
import numpy as np import sys import math import sqlite3 import scipy from scipy.sparse.linalg.isolve import _iterative from scipy.sparse.linalg.isolve.utils import make_system import scipy.sparse.linalg import random def cgr(A, b, k, eps): A = np.matrix(A) b = np.matrix(b) n = length(b) residuals = np.zeroes(k,1...
435
197
import torch import torch.nn as nn import torch.nn.functional as F from archs.encoder3D import SimpleEncoder3D import numpy as np class MetricLearner(nn.Module): def __init__(self, num_objects=150, repr_dim=128): super(MetricLearner, self).__init__() self.pred_dim = repr_dim # We need a S...
2,897
970
import harness_util harness_factory = harness_util.TemplateHarnessFactory() config = { 'corpusCol': 'description', 'lstmSize': 64, 'dropoutRate': 0, 'kernelRegPenalty': 0.01, 'method': 'sequence', 'numWords': 2000, 'sourceCol': 'source', 'sourceIdCol': 'sourceId', 'sourceIdVectorCo...
528
203
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE...
9,124
2,064
import matplotlib matplotlib.use('Agg') import keras import numpy as np import tensorflow as tf import os from matplotlib import pyplot as plt from scipy.cluster.hierarchy import dendrogram from sklearn.cluster import AgglomerativeClustering class Cluster(): """ A class for conducting an cluster study on a trained ...
4,473
1,865
# For some unknown reason... UVA keeps return RunTimeError for Python is this question... DEBUG = 0 inf = 2**33 while (True): rooms = -2 while (rooms == -2): try: rooms = int(input()) except EOFError: break except ValueError: continue if (rooms ...
1,032
349
import re import base64 import logging from functools import wraps from ipaddress import ip_address, ip_network from .settings import HEARTBEAT from django.http import HttpResponse from django.core.exceptions import ImproperlyConfigured logging.basicConfig( format='%(levelname)s - %(message)s', level=logging....
3,531
1,192
from django.contrib import admin from .models import EmailInfo, DOIQuery, EmailInfoJournal, JournalQuery # Register your models here. admin.site.register(EmailInfo) admin.site.register(DOIQuery) admin.site.register(JournalQuery) admin.site.register(EmailInfoJournal)
267
78
""" Player for the competition """ from players.AbstractPlayer import AbstractPlayer #TODO: you can import more modules, if needed class Player(AbstractPlayer): def __init__(self, game_time): AbstractPlayer.__init__(self, game_time) # keep the inheritance of the parent's (AbstractPlayer) __init__() ...
1,782
456
import requests import socket import shutil import psutil def check_localhost(): localhost = socket.gethostbyname('localhost') return localhost == '127.0.0.1' def connectivity_check(): request = requests.get('https://www.google.com') return request.ok def check_disk_usage(disk): du = shutil.disk_usage(disk) f...
629
222
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup import os package_dirs = { 'controllers': os.path.join('src', 'vision-interaction', 'controllers'), 'interaction_builder': os.path.join('src', 'vision-interaction', 'interaction_builder'), '...
686
223
from django import forms from django.conf import settings from django.core.validators import MinValueValidator from django.urls import reverse_lazy from django.utils.translation import npgettext_lazy, pgettext_lazy from django_prices.forms import MoneyField from payments import PaymentError, PaymentStatus from ...acco...
14,578
4,070
import sys from write import write from update import edit from delete import delete from search import search from read import read tasks_description = ["Write", "Read", "Update", "Delete", "Search", "Exit"] tasks = [1, 2, 3, 4, 5, 6] def show_menu(): print() print("----------------------------[Main Menu]--...
2,133
1,000
from django.db import models from django.utils.translation import gettext as _ from django.conf import settings from decimal import Decimal from product.models import Product, ProductGroup from reference.models import Currency, Category # Create your models here. class CartRule(models.Model): name = models.CharFie...
3,938
1,247
import unittest class WorkerTest(unittest.TestCase): def test_dummy(self): self.assertEqual(True, True)
118
40
from amaranth_boards.qmtech_10cl006 import * from amaranth_boards.qmtech_10cl006 import __all__ import warnings warnings.warn("instead of nmigen_boards.qmtech_10cl006, use amaranth_boards.qmtech_10cl006", DeprecationWarning, stacklevel=2)
254
103
from selenium.webdriver.remote.webdriver import WebDriver class XpathExists: """ Sprawdz czy xpath istnieje """ def __init__(self, xpath: str): self.__xpath = xpath # noinspection PyBroadException def __call__(self, driver: WebDriver): try: driver.find_element_by_xpath(sel...
523
153
from finq import FINQ def collector(l: list): def write(s: str): l.append(s) write.collector = l return write def test_foreach(): a = [1, 2, 5, 7] expected = ['1', '2', '5', '7'] mock = collector([]) a_f = FINQ(a) a_f.map(str).for_each(mock) assert mock.collector == ...
329
139
#!/usr/bin/env python3 import requests, configparser import os import pandas as pd import json import base58 import time import urllib.request from google.cloud import bigquery pd.options.mode.chained_assignment = None # Mina constants MINA_DECIMALS = 1 / 1000000000 SLEEP_TIME = 60 class MinaTelegram(): def __...
9,740
2,790
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing def load_df(directory): df = pd.read_excel(directory) return df def subtract_baseline(df, baseline): x = df.values cols = df.columns baseline_col = df[baseline].values for i in range(1...
1,935
717
import os import cv2 import time import math import ctypes import random import win32ui import win32gui import warnings import win32con import threading import subprocess import pytesseract import numpy as np import pydirectinput from fuzzywuzzy import process from custom_input import CustomInput from win32api import G...
85,687
29,547
import json import pathlib import ssl from urllib.request import Request, urlopen # Change this to False to use the file data. use_live_data = True if use_live_data: # Fetching the live data from reddit. url = "http://www.reddit.com/r/aww.json" request = Request( url, headers={ ...
2,072
691
from projectq.meta import Dagger from projectq.ops import H, CRz from src.shared.rotate import calculate_phase def qft(eng, circuit, qubits): m = len(qubits) for i in range(m - 1, -1, -1): circuit.apply_single_qubit_gate(H, qubits[i]) for j in range(2, i + 2): circuit.a...
501
200
import dl import dlm import conll3 import csv import argparse import textwrap def create(fileName1): # store the dependency tree in a dict T = conll3.conllFile2trees(fileName1) stats = [] c=0 for tree in T: c+=1 l = len(tree) # length d = dl.DL_T(tree) # ob...
1,777
592
#!/usr/bin/env python3.6 import os import sys import argparse try: import json except ImportError: import simplejson as json gce = True evn = 'prod' count = 0 #Подключаем модули для использования API GCE try: from googleapiclient import discovery from oauth2client.client import GoogleCredentials ex...
3,323
927
#!/usr/bin/env python # (C) Copyright 1996- ECMWF. # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status...
3,689
1,522
from unicodeset import UnicodeSet from .reporter import Reporter class Smorgasbord(UnicodeSet): paths = [] def __init__(self, iterable): super(Smorgasbord, self).__init__(iterable) self.reports = Reporter(self, self.__class__.paths)
261
86
# -*- coding: utf-8 -*- # # Copyright (c) 2008, Stephen Hansen # Copyright (c) 2009, Robert Corsaro # Copyright (c) 2010, Robert Corsaro # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # ...
3,907
1,218
import requests from bs4 import BeautifulSoup global json_content import sqlite3 conn = sqlite3.connect("khusrau.db") cur = conn.cursor() blues_words=["","",""] tag_strip=['wafa', 'Wahm', 'Wahshat', 'Waiz', 'Wajood', 'Waqt', 'Welcome', 'Yaad', 'Yaad-e-Raftagan', 'Zindagi', 'zindan', 'Zulf'] top100=['https:/...
5,946
2,097
import sqlite3 from typing import List from sqlalchemy import Table from portfolio_api.domains import user from portfolio_api import exceptions from .schema import UserSchema from .. import connection async def get_users() -> List[user.UserGet]: users = UserSchema().get_table() query = users.select() re...
2,818
852
from nose.tools import assert_equal, assert_in from cutecharts.charts.basic import BasicChart from cutecharts.faker import Faker from cutecharts.globals import AssetsHost def test_engine_render(): basic = BasicChart() html = basic.render() assert_in(AssetsHost.DEFAULT_HOST, html) assert_in...
657
226
from django.contrib import admin from locations.models import * from rest_framework.authtoken.models import Token # Register your models here. admin.site.register(Provider) admin.site.register(Coordinate) admin.site.register(Polygon) admin.site.register(Token)
263
75
from face_normalisation import get_normalised_faces from train_model import * import cv2 cap = cv2.VideoCapture(0) faceCascade = cv2.CascadeClassifier('P:\\GIT_FILE\\Face_Recognition\\OpenCVDemo\\haarcascade_frontalface_default.xml') while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2....
1,532
595
from RoiMatching import * def Roimatching(RoiZipPath1, RoiZipPath2): # [Dic1, DirPath1] = DicBuild('C:\Result\JR1.zip') # [Dic2, DirPath2] = DicBuild('C:\Result\JR4.zip') [Dic1, DirPath1] = DicBuild(RoiZipPath1) [Dic2, DirPath2] = DicBuild(RoiZipPath2) Rename((Match(Dic1, Dic2))[0], DirPat...
721
319
# 695. Max Area of Island # Time: O(size(grid)) # Space: O(1) except recursion stack, since modifying grid in-place else O(size(grid)) class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: max_count = 0 for row in range(len(grid)): for col in range(len(grid[0])): ...
861
300
""" Thermocouple library. Configure ADC, read ambient, read thermocouples, and calculate temperatures. """ from mcp9800 import MCP9800 class OutOfRangeError(Exception): pass class TC(object): """ Thermocouple interface using MCP3428 """ _temps = [None, None, None, None] _count = 0 # ...
5,103
2,549
from .. spirit_utils import import_spirit SPIRIT_ROOT_PATH = "~/Coding" def choose_spirit(x): return "5840c4564ba5275dc79aa7ae4cd4e79d6cf63b87".startswith(x.revision) and x.openMP and x.pinning # check for solver info revision and openMP and pinning spirit_info = import_spirit.find_and_insert(SPIRIT_ROOT_PATH, s...
418
171
# -*- coding: utf-8 -*- import abc import collections import six class BasePage(six.with_metaclass(abc.ABCMeta, collections.Sequence)): """A page of results. """ def __init__(self, paginator, results): self.paginator = paginator self.results = results def __len__(self): retur...
1,293
405
from mkcommit import to_stdout, include commit, on_commit = include( "https://raw.githubusercontent.com/kjczarne/mkcommit/master/test/res/example.semantic.mkcommit.py") # noqa: E501 commit, on_commit = include( "https://raw.githubusercontent.com/kjczarne/mkcommit/master/test/res/example.semantic.mkcommit.py",...
417
158
from typing import Optional from boto3.session import Session from startifact.parameters.parameter import Parameter class LatestVersionParameter(Parameter[str]): """ Systems Manager parameter that holds the latest version number of an artifact. """ def __init__( self, project: s...
713
201
import datetime import json import os import platform import subprocess from typing import List import playsound import speech_recognition as sr from gtts import gTTS from ..Spotify import Album, Artist, Playlist, Track track = Track.Track() playlist = Playlist.Playlist() album = Album.Album() artist = Artist.Artist...
5,786
1,759
#!/usr/bin/python # (c) 2018, NetApp, Inc # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
11,805
3,315
from flask import Flask, render_template, request from random import choice web_site = Flask(__name__) @web_site.route('/') def login(): return render_template('login.html') @web_site.route('/') def main(): return render_template('index.html') @staticmethod def insert_record(doc): Database.DB.Database.insert_...
380
136
""" Rackspace Cloud Backup Agent API """ from __future__ import print_function import datetime import gzip import hashlib import json import logging import os import requests import time import threading import six from cloudbackup.common.command import Command requests.packages.urllib3.disable_warnings() class Pa...
81,054
21,210
import json def dumpdump(s): """double json.dumps string""" return json.dumps(json.dumps(s)) def test_crud(graphene_client): # test create object sample_key = 'whatever' sample_value = {'foo': 'bar'} query = ''' mutation testCreateItem { createItem(key: %s, value: %s) { ...
987
306
import os import cv2 # OpenCV lib for image manipulation RAW_ROOT = "../data/PVTL_dataset/" PCD_ROOT = "../data/processed/" TRAIN_PATH = "train/" VAL_PATH = "val/" def get_image_names(path_type): return [f"{path_type}{img_class}/{image}" for img_class in os.listdir(path_type) for image in os.listdir(f"{path_type}...
2,226
805
import threading import ntplib from time import ctime from datetime import datetime from dateutil import tz from dateutil.tz import tzlocal def query_ntp_server(server_url, request_timeout, result_handler): client = ntplib.NTPClient() try: response = client.request(server_url, version=3, timeout=reques...
2,622
822
import torch import sys sys.path.append('../') from binary_tree.utils import BinaryTree, build_tree from estimators import uniform_to_exp def bin_tree_struct(exp, lengths=None, **kwargs): ''' Defines F_struct for binary tree Applies the divide and conquer algorithm from the paper Input ----------...
3,707
1,146
import dash import dash_core_components as dcc import dash_html_components as html from flask import Flask server = Flask(__name__) app = dash.Dash(server=server) app.css.append_css({ 'external_url': ( 'https://cdn.rawgit.com/chriddyp/0247653a7c52feb4c48437e1c1837f75' '/raw/a68333b876edaf62df2efa...
569
247
# Created byMartin.cz # Copyright (c) Martin Strohalm. All rights reserved. import pero import numpy # init size width = 400 height = 300 padding = 50 # init data x_data = numpy.linspace(-numpy.pi, numpy.pi, 50) y_data = numpy.sin(x_data) # init scales x_scale = pero.LinScale( in_range = (min...
1,022
423
from .maxcut import MaxCut from .graph_partition import GraphPartitioning from .vertex_cover import VertexCover from .stable_set import StableSet from .generators import get_random_hamiltonians_for_problem from ._problem_evaluation import solve_problem_by_exhaustive_search
279
86
import tensorflow as tf from MultiHeadAttention import * from MLP import * class AttentionalPropagation(tf.keras.layers.Layer): def __init__(self, feature_dim, num_heads): super(AttentionalPropagation,self).__init__() self.attention = MultiHeadAttention(num_heads, feature_dim) self.mlp = MLP([feature_di...
703
275
import pytest import aioboto3 from dynamodb_doctor import Model, String, Many from dynamodb_doctor.exceptions import MissingAttributeException ENDPOINT_URL = "http://localhost:58000" @pytest.mark.asyncio async def test_model_with_many_to_model_relationship(table_fixture): class TestModelA(Model): name =...
1,683
561
from multiprocessing import Process, current_process import time import os def worker(): name = current_process().name print('==='*15 + ' < ' + f'{name}' + ' > ' + '==='*15) time.sleep(1) print(f'{name} Exiting...') def worker_1(): name = current_process().name print('===' * 15 + ' < ' + f...
1,179
456
import PyPDF4 import slate3k as slate import os import logging logging.propagate = False logging.getLogger().setLevel(logging.ERROR) def findWords(documentName) : with open(documentName, 'rb') as f: extracted_text = slate.PDF(f) with open("names.txt") as n: names = [name.rstrip() for name in...
1,238
372
import asyncio from argparse import ArgumentParser from aiohttp import ClientSession from cloudpiercer import CloudPiercer SOLVER_ENDPOINT = 'http://localhost:8081/solve' def main(): parser = ArgumentParser() parser.add_argument('url') args = parser.parse_args() cloudpiercer = CloudPiercer(SOLVER_END...
624
209
from .lines import *
21
7
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os.path import simplejson from .load_schema import load_schema from .model import SwaggerSchema from .spec import validate_swagger_schemas API_DOCS_FILENAME = 'api_docs.json' class ResourceListingNotFoundError(Exception): pass class ApiD...
4,074
1,122
a, b = map(int, input().split()) print(a+b if a+b <= 9 else 'error')
69
31
#!/pxrpythonsubst # # Copyright 2020 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
4,038
1,333
import pytest def test_bad_file_checker(style_checker): """Check behavior when pep8 is missing """ style_checker.enable_unit_test() # Derive the TypificChecker class without providing the mandatory # methods which are otherwise abstract. from asclib.checkers.typific import TypificChecker, Typ...
3,218
953
import tensorflow as tf from enum import Enum # Note all functions below represent negative scores. # Thus minimization of a score means maximization of the corresponding entropy class MutualInfoType(Enum): JS = "Jensen-Shannon" DV = "Donsker-Varadhan" def get_mutual_info_scorer(type: MutualInfoType): ...
927
316
#!/usr/bin/env python import h5py import json import os import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim from datetime import datetime from tqdm import tqdm from typing import List, Tuple import amnre from amnre.simulators.slcp import SLCP from amnre.simulators.g...
10,980
3,603
#imports from Bb_rest_helper import Get_Config from Bb_rest_helper import Auth_Helper from Bb_rest_helper import Bb_Requests from Bb_rest_helper import Bb_Utils def main(): #Initialize an instance of the Get_Config class, passing the file path of the configuration file as argument. config=Get_Config("./lea...
1,039
358
import numpy as np from numba import roc import numba.unittest_support as unittest class TestPositioning(unittest.TestCase): def test_kernel_jit(self): @roc.jit def udt(output): global_id = roc.get_global_id(0) global_size = roc.get_global_size(0) local_id = ro...
1,376
523
# -*- coding: utf-8 -*- import numpy as np import sklearn.mixture from sklearn.mixture.gaussian_mixture import _compute_precision_cholesky class BlockDiagonalGaussianMixture(sklearn.mixture.GaussianMixture): """GMM with block diagonal covariance matrix This class offers the training of GMM with block diagona...
6,563
1,999
# -*- coding: utf-8 -*- """ Created on Wed Apr 11 23:31:51 2018 @author: Marcus """ import numpy as np import time N = 2**4 samples = np.random.normal(0, 1, N) + 1j * np.random.normal(0, 1, N) pre_calc = np.zeros(N, dtype=np.complex) pre_m = np.zeros((N, N), dtype=np.complex) for n in range(N): pre_calc[n...
1,168
510
import os from itertools import chain JSON_EXT = '.json' JSON_FOLDER = 'JSON_Files' def shambler(source_file, target_file_path, json_key): # Checking whether the user has input file names, file paths # If they are relative, we will let python take care of it. source_file = _resolve_path(source_file) ...
3,348
1,047