text
string
size
int64
token_count
int64
#!/usr/bin/env python ''' This example shows how to use the call_in_background macro ''' from pyscf import lib import time def fa(): print('a') time.sleep(0.5) def fb(): print('b') time.sleep(0.8) print('type 1') w0 = time.time() with lib.call_in_background(fa) as afa, lib.call_in_background(fb) as...
671
279
from abc import ABCMeta, abstractmethod class SegmentsCommon(metaclass=ABCMeta): @abstractmethod def analyze(self, marker, body): pass
158
49
import autofront from simple_functions import foo autofront.add(foo) autofront.run()
86
30
from .imagenet_dataset import ImageNetDataset # noqa
54
18
class Solution(object): def findDuplicate(self, nums): low = 0 high = len(nums) - 1 mid = (high + low) / 2 while high - low > 1: count = 0 for k in nums: if mid < k <= high: count += 1 if count > high - mid: ...
859
238
def subset_x_y(target, features, start_index:int, end_index:int): ''' ''' return features[start_index:end_index], target[start_index:end_index] def split_sets_by_time(df, target_col, test_ratio=0.2): ''' ''' df_copy = df.copy() target = df_copy.pop(target_col) cutoff = int(len(target)/...
1,826
670
# Works """ Given a quantity of money and a list of coins, return the minimum number of coins. """ def DPChange(money, coins): MinNumCoins = [0]*(money+1) MinNumCoins[0] = 0 for m in range(1, money+1): MinNumCoins[m] = 100000 for i in range(0, len(coins)): if m >= coins[i]: # ...
853
384
# -*- coding: utf-8 -*- ''' feedgen.entry ~~~~~~~~~~~~~ :copyright: 2013-2020, Lars Kiesow <lkiesow@uos.de> :license: FreeBSD and LGPL, see license.* for more details. ''' from datetime import datetime import dateutil.parser import dateutil.tz import warnings from lxml.etree import CDATA # nosec -...
30,286
7,955
#!/usr/bin/python #coding:utf8 import mybaselib import logging import jieba import jieba.analyse import numpy as np import csv import sys import stat import os reload(sys) sys.setdefaultencoding('utf-8') logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) if __name__ == '__main__': fname = sys.argv[...
527
207
#!/usr/bin/env python # coding: utf-8 DESCRIPTION="This script reduce dimensionality of input data." #from memory_profiler import profile import numpy as np import argparse from sklearn.decomposition import PCA from sklearn.decomposition import NMF import logging import sys from os.path import dirname sys.path.append...
3,165
1,050
from __future__ import print_function, unicode_literals, division arp_table = [('10.220.88.1', '0062.ec29.70fe'), ('10.220.88.20', 'c89c.1dea.0eb6'), ('10.220.88.21', '1c6a.7aaf.576c'), ('10.220.88.28', '5254.aba8.9aea'), ('10.220.88.29', '5254.abbe.5b7b'), ...
981
538
from django.test import TestCase from django.urls import reverse class CourseBuilderViewTest(TestCase): def test_landing_page(self): url = reverse("coursebuilder:landing_page") response = self.client.post(url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(resp...
834
254
class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ d=collections.defaultdict(list) for s in strings: d[tuple([((ord(s[i])-ord(s[0]))%26) for i in range(len(s))])].append(s) return [d[ke...
336
114
import discord, os from discord.ext import commands from utils import checks, output from aiohttp import ClientSession import urllib.request import json class Stats: def __init__(self, bot: discord.ext.commands.Bot): self.bot = bot @commands.command() async def stats(self, amount=1): """ ...
2,460
798
from requests import Session from .__about__ import __title__, __version__ from .models import Version class Client(object): """Initializes the API client :param url: URL of the headquarters app :param api_user: API user name :param api_password: API user password :param workspace:...
996
308
from DeepChecker.Checkers import *
35
11
class Solution: """ @param candies: a list of integers @return: return a integer """ def distributeCandies(self, candies): # write your code here return min(len(set(candies)), len(candies) // 2)
231
74
# -*- coding: utf-8 -*- """Unit tests for CMGroup class.""" import os import shutil from itertools import islice from commongroups.env import CommonEnv from commongroups import cmgroup as cmg # Locate the test params to use. _CUR_PATH = os.path.abspath(os.path.dirname(__file__)) PARAMS_JSON = os.path.join(_CUR_PATH,...
3,496
1,215
#!/usr/bin/env python # -*- Coding: utf-8 -*- from argparse import ArgumentParser from os import environ, makedirs from datetime import datetime from os.path import abspath, join, dirname, exists, splitext from time import time from dotenv import load_dotenv import slack DIR = dirname(dirname(abspath(__file__))) l...
5,563
1,866
import tensorflow as tf # Create TensorFlow object called tensor hello_constant = tf.constant('Hello World!') with tf.Session() as sess: # Run the tf.constant operation in the session output = sess.run(hello_constant) print(output.decode())# bytestring decode to string.
294
86
# encoding: utf-8 # module PySide.QtGui # from C:\Python27\lib\site-packages\PySide\QtGui.pyd # by generator 1.147 # no doc # imports import PySide.QtCore as __PySide_QtCore import Shiboken as __Shiboken class QClipboardEvent(__PySide_QtCore.QEvent): # no doc def __init__(self, *args, **kwargs): # real signa...
348
128
# coding: utf-8 # 2021/03/12 @ zhaoguanhao
43
28
#!/usr/bin/env python3 import os import logging import time from datetime import datetime import subprocess as sp import json from flask import Flask, request, jsonify, send_from_directory LOG_LEVEL = 'INFO' LOG_PATH = 'dwg2dxf.log' LOG_DIR = 'log' PORT=8001 try: from local_config import * except: pass fmt =...
3,207
1,333
import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.clock import Clock from kivy.core.window import Window ...
6,856
2,346
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from parlai.core.agents import Agent from parlai.core.utils import warn_once from parlai.core.utils import padded_3d from parlai.core.torch_gene...
4,607
1,436
import sys from pathlib import Path import cv2 import numpy as np import pandas as pd import torch from torch.utils.data import Dataset import torchvision from torchvision import transforms import torchvision.transforms.functional as F from skimage.util import random_noise from dataloading.camera import Camera cl...
20,972
8,447
from ilexconf.console.application import Application def main(): # pragma: no cover return Application().run()
118
32
# Copyright (C) [2013] [The FURTHeR Project] # # 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...
7,206
2,416
from django.contrib.auth.views import LoginView from django.contrib.auth.forms import AuthenticationForm class SignInView(LoginView): ''' Sign in for vendor ''' form_class = AuthenticationForm template_name = 'vendor/sign_in.html' redirect_field_name = 'vendor:root_path' success_url = 've...
337
105
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-excel-to-model ------------ Tests for `django-excel-to-model` models module. """ from django.test import TestCase # from unittest import TestCase from django_excel_to_model.openpyxl_reader import OpenpyxlExcelFile from sap_asset_master_data20191224.model...
692
264
from flask import Flask, render_template, jsonify from mongo import mongo import json # from persona import persona import time app = Flask(__name__, static_url_path='/static') cliente=mongo() peoples=cliente['mydb']['people'].find() def parsePerson(person): return { 'id':person['id'], ...
1,461
506
# -*- coding: utf-8 -*- # Attempt to convert audio to video by visualizing audio import argparse from lib.audio_utils import * from lib.collection_utils import * from lib.io_utils import * from lib.math_utils import * import librosa import os import numpy as np from pprint import pprint import sys # input parser = a...
1,592
504
from flask import jsonify, abort from flask_restful import reqparse, Resource from config import db from data.user import UserData from datetime import datetime, timedelta from data.user_session import UserSessionData parser = reqparse.RequestParser() parser.add_argument('username') parser.add_argument('password') c...
982
261
# -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2021 OpenALTO Community # # 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 the Software without restriction, including without limitation t...
1,775
627
import re import requests import json # 从百度的php接口中获取到数据 def catch_url_from_baidu(calcultaion_year, month): header = { "Content-Type": "application/json;charset=UTF-8" } param = { "query": str(calcultaion_year) + "年" + month + "月", "resource_id": "39043", "t":...
2,501
1,226
from yacs.config import CfgNode as CN from lib.classes.dataset_classes.SubjectDataset import SubjectDataset from config.model_helper import get_size_input _C = CN() _C.framework = "Keras" _C.model_type = "ConvAutoencoder" _C.build_type = "subclass" # Define encoder parameters _C.Encoder = CN() _C.Encoder.n_filters...
1,377
618
import pydot callgraph = pydot.Dot(graph_type='digraph', fontname="Verdana", compound='true') cluster_foo = pydot.Cluster('foo', label='foo') callgraph.add_subgraph(cluster_foo) node_foo = pydot.Node('foo_method_1', label='method_1') cluster_foo.add_node(node_foo) cluster_bar = pydot.Cluster('bar', label='Component...
577
229
import networkx as nx import os from diagram import Diagram from spf import spf class lfa: """This class provides RFC5286 lfa calculations""" def __init__(self, debug=0): """ Init the lfa class. :param int debug: debug level, 0 is disabled. :return None: __init__ shouldn't re...
12,544
3,476
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..models.claim_format import ClaimFormat from ..models.input_descriptors import InputDescriptors from ..models.submission_requirements import SubmissionRequirements from ..types import UNSET, Unset T = TypeVar("T", bound="PresentationDefinitio...
4,523
1,341
""" Launch a proxy for tranforming `/paths/like/these` to PostgREST filters. Usage: aiodata -h | --help aiodata <file> [--host=<str>] [--port=<int>] [--query=<str>] [--state=<str>] aiodata [--db-uri=<uri>] [--pr-uri=<uri>] [--host=<str>] [--port=<int>] [--schema=<str>] [--secret=<str>] [--query=<str>] [--...
12,344
3,675
LB_media = { "EX_ni2_e": -1000, "EX_dcyt_e": -1000, "EX_hg2_e": -1000, "EX_ins_e": -1000, "EX_cd2_e": -1000, "EX_so4_e": -1000, "EX_uri_e": -1000, "EX_tungs_e": -1000, "EX_glu__L_e": -1000, "EX_slnt_e": -1000, "EX_trp__L_e": -1000, "EX_dad__2_e": -1000, "EX_mobd_e": -...
3,685
1,960
# coding:utf-8 import codecs class DataOutput(object): def __init__(self): self.datas = [] def store_data(self, data): if data is None: return self.datas.append(data) def output_html(self, path, data): fout = codecs.open(path, 'w+', encoding='utf-8') f...
838
300
# -*- coding: utf-8 -*- """Validates htsget response matches JSON schema""" import inspect import json import os from jsonschema import validate from jsonschema import RefResolver from jsonschema.exceptions import ValidationError from ga4gh.htsget.compliance.config import constants as c class SchemaValidator(object):...
2,600
676
import xmlrpc.client proxy = xmlrpc.client.ServerProxy("http://localhost:6789/") num = 7 result = proxy.double(num) print("Dwukrotność liczby %s jest równa %s" % (num, result))
178
70
import begin from sails.server import Server @begin.start def main(): """Start a sailsd server.""" s = Server() s.start_loop() print('Stopping sailsd.')
172
60
from .AND import * from .COMP import * from .NAND import * from .NOR import * from .NOT import * from .OR import * from .PAR import * from .XNOR import * from .XOR import *
173
60
def accepts(*types): def check_accepts(f): assert len(types) == f.func_code.co_argcount def new_f(*args, **kwds): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" % (a,t) return f(*args, **kwds) ...
843
277
"""Test classes defined within pbtranscript.CombineUtils.""" import unittest import os.path as op from pbcore.io import FastaReader, FastqReader from pbtranscript.Utils import rmpath, mkdir from pbtranscript.ClusterOptions import IceQuiverHQLQOptions from pbtranscript.CombineUtils import CombineRunner from test_setpa...
2,412
921
import config from gmusicapi import Mobileclient import logging from gi.repository import Gst, GLib from collections import deque from gevent import Greenlet import gevent class PlayerStates: Stopped = "Stopped" Paused = "Paused" Playing = "Playing" class RattleMediaPlayer: def __init__(self): ...
7,063
2,039
# -*- coding: utf-8 -*- """ Created on Thu Mar 25 18:17:13 2021 @author: AndyWang """ from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from datetime import datetime from time import sleep import pandas as pd import numpy as np import os ...
16,116
5,568
class Solution: def getMaximumGold(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) res = 0 visited = set() for i in range(m): for j in range(n): if grid[i][j]!=0: x = self.helper(grid, i, j, visited) ...
796
289
import random, time, os def m(): l, t, d = 3,0.5,1 o=input("Opp\n0)Yes\n1)No\n:") while l>0: S=r(d,"") print("Lives:"+str(l)+"\nSimon Says:"+str(S)) time.sleep(t*d) os.system("clear") if int(input("RPT\n>> "))!=S: l=(l - 1) else: d+=1 print("PTS:"+str((d...
419
200
# -*- coding: utf-8 -*- def rename_function(ss, oldname, newname): """Replaces all occurences of a name by a new name """ #return ss.replace("conjugate","numpy.conj") return ss.replace(oldname, newname) def fce2array(sr, pat): """Converts functions into arrays """ se = "".joi...
1,572
537
test_case_1 = """ 5 # N 4 1 5 2 3 5 # M 1 3 7 9 5 """ ''' result 1 1 0 0 1 ''' N = int(input()) A = list(map(int, input().split())) A_set = set(A) # Set in으로 문제 한 번에 해결... M = int(input()) B = list(map(int, input().split())) for i in range(0, M): if B[i] in A_set: print(1) ...
345
172
import argparse import os import numpy as np import matplotlib.pyplot as plt import torch import yaml import cv2 from PIL import Image, ImageFilter from base64 import b64decode, b64encode import io from predictors.predictor import Predictor from src.models.modnet import MODNet import torch import torch.nn as nn im...
5,246
1,870
import re from HTMLParser import HTMLParser class HTMLPassThrough(HTMLParser): """Maintains a stack of tags and returns the same HTML it parses. Base class for more interesting parsers in markup.py. """ def reset(self): HTMLParser.reset(self) self.stack = [] self.out = [] ...
1,853
600
import databases from database_handler import load_session, func from flask_login import LoginManager, UserMixin class AccessModule: session, Base = load_session(databases.urls['DATABASE_ACCESS_URL']) def __init__(self): ''' for item in self.session.query(User.us_id): print(item.fi...
1,452
443
# @lc app=leetcode id=75 lang=python3 # # [75] Sort Colors # # https://leetcode.com/problems/sort-colors/description/ # # algorithms # Medium (49.90%) # Likes: 5201 # Dislikes: 298 # Total Accepted: 663.5K # Total Submissions: 1.3M # Testcase Example: '[2,0,2,1,1,0]' # # Given an array nums with n objects colore...
2,675
1,167
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.cnn import ConvModule from mmcv.runner import BaseModule, force_fp32 from torch import nn as nn class DGCNNFAModule(BaseModule): """Point feature aggregation module used in DGCNN. Aggregate all the features of points. Args: m...
2,245
716
#!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import call def test_flake8(): return_code = call(['flake8']) assert return_code == 0
158
61
#!/usr/bin/env python ''' dir_monch: a utility to help shorten paths. ''' from __future__ import print_function from os.path import expanduser from os import sep as os_sep from sys import exit import sys def dir_monch(path): # Substitute ~ for the home dir path when possible HOME = expanduser("~") if pat...
1,653
595
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # based on: http://code.activestate.com/recipes/573463/ # Modified by Philippe Normand # Copyright 2008, Frank Scholz <coherence@beebits.net> from coherence.extern.et import ET as ElementTree, indent, parse_xml...
7,302
2,179
import casadi as ca import casadi.tools as cat __author__ = 'belousov' class Planner: # ======================================================================== # Simple planning # ======================================================================== @classmethod de...
8,519
2,888
# Copyright 2019 Arie Bregman # # 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 agree...
4,526
1,280
# Import shawk from shawk import Contact # Prepare contacts used throughout tests mini_contact = Contact(12345678, 'Verizon') name_contact = Contact(12345678, 'Verizon', 'Somebody') def test_repr_minimal(): assert(repr(mini_contact) == "<shawk.Contact('12345678', 'Verizon', '<No name>')>") def test_repr_with_na...
844
346
#coding=utf-8 # coding=utf-8 ''' Created on 2014-1-5 @author: ETHAN ''' from rest_framework import generics from doraemon.api.ci.serializer import ci_serializer from rest_framework.permissions import AllowAny from doraemon.ci.mongo_models import CITaskParameterGroup from business.ci.ci_task_parameter_service import CI...
1,090
328
# @l2g 106 python3 # [106] Construct Binary Tree from Inorder and Postorder Traversal # Difficulty: Medium # https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal # # Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder i...
2,097
714
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ ptr = root if(ptr=...
666
208
#!/usr/bin/python # -*- coding: utf-8 -*- from conf.dbconfig import TB_SESSION from core.err_code import DB_ERR, OCT_SUCCESS from core.log import WARNING,DEBUG from utils.commonUtil import getUuid, transToStr, transToObj from utils.timeUtil import get_current_time, getStrTime SESSION_EXPIRE_TIME = 86400 * 30...
2,695
1,212
class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: """ You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference b...
1,379
410
import sys n, *a = map(int, sys.stdin.read().split()) def main(): a.sort() return a[-1] - a[0] if __name__ == "__main__": ans = main() print(ans)
180
83
# -*- coding: utf-8 -*- broker_url = 'redis://192.168.33.10/0' result_backend = 'redis://192.168.33.10/1' imports = ('learn_celery.tasks',)
143
81
from typing import Union from seqwise_cont_skillspace.networks.rnn_vae_classifier import \ RnnVaeClassifierContSkills class RnnStepwiseSeqwiseClassifierObsDimSelect(RnnVaeClassifierContSkills): def __init__(self, *args, input_size, obs_dims_selected: Union[...
1,044
308
#!/usr/bin/env python2 import os import nltk import cfg_parser as parser def main(): cfg_grammar_file = '../../dropbox/context_free_grammars/prog_leftskew.grammar' grammar = parser.Grammar(cfg_grammar_file) ts = parser.parse( 'v1=sin(v0);v2=v0*4;v3=v1/v2;v4=cos(v0);v5=v0*3;v6=sin(v1);v7=v3-v6;...
1,165
466
import balanced balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY') settlement = balanced.Settlement.fetch('/settlements/ST6HmBuLJSEa82oUwId1AShW')
161
80
import typing import numpy as np import trade_environment def detect_turning_points(values: np.ndarray, gap: int) -> typing.Tuple[np.ndarray, np.ndarray]: """指定数列の折返しポイントの地点を検出する. Args: values: 数列. gap: 折返し判定閾値、この値を超えて反転したら折返しと判断する. Returns: (折返しインデックス, 検出途中に生成した一定値以上距離を保って付いてくる値の数列) のタプル. """ indices = ...
5,857
3,532
from models.EstadoSolicitud import EstadoSolicitud """ De Pendiente puede pasar a: controlado, retenido. De controlado puede pasar a: retenido, evaluado, numerado. De Retenido puede pasar a:controlado, evaluado De Evaluado puedo pasar a: numerado """ class FSMSolicitud: def __init__(self): self.estados = {...
1,284
497
# Class: CSC-648-848 Fall 2021 # Author: Manali Seth # Description: Contains columns and datatypes of Messaging Table of database from wtforms import * class MessageVO: msgId = IntegerField msgTo_loginId = IntegerField msgFrom_loginId = IntegerField msg_majorId = IntegerField msg_courseNo = Integ...
405
126
import sys import socket from mesylib import send_cmd try: addr = sys.argv[1] rate = int(sys.argv[2]) except (ValueError, IndexError): print('usage: mesyparams.py ipaddr rate') sys.exit(1) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) send_cmd(sock, addr, 0xF1F0, 'IH', rate, 0) print('confi...
330
131
# from bin.x64.iFinDPy import * import urllib.request import json from abc import ABC import matplotlib.pyplot as plt import pandas as pd import os from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from datetime import datetime import t...
11,751
3,460
from PyPDF2 import PdfFileWriter, PdfFileReader import daily_learn def read_book(path): input1 = PdfFileReader(open(path, "rb")) my_book=[] for i in xrange(input1.getNumPages()): my_book.append(input1.getPage(i)) return my_book def write_files(output_file,folder,name): j=0 output = [] ...
947
377
import numpy as np from matplotlib import pyplot as plt def function_to_approximate(x): return 128*(np.sin((np.pi*x/256)-(0.5*np.pi))+1) def calculate_poly(z, x): return np.round(z[3]+x*(z[2]+x*(z[1]+z[0]*x))) def quantize(z, fraction_bits): q = 2.0**fraction_bits z = z * q z = np.round(z) z ...
592
296
from django.conf import settings from enum import Enum from selenium.webdriver.common.by import By class Action(Enum): LOAD_PAGE = 1 FIND_CLICK = 2 FIND = 3 FIND_SEND_KEY = 4 CHECK = 5 BACK = 6 LOGIN = 7 CONTAIN_TEXT = 8 GET_SAMPLE_TOKEN_START = 9 SLEEP = 10 ...
11,718
4,952
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: lizheming @contact: nkdudu@126.com @site: lizheming.top @file: Zhuanlan.py """ from zhihu import headers, clear, error, session from bs4 import BeautifulSoup import re import webbrowser import termcolor import requests import json import sys class Z...
4,854
1,609
import manga109api import argparse import os import glob from PIL import Image def args_parser(): """ :return: This function returns the manual input of book, annotation_type, and page count. """ parser = argparse.ArgumentParser() parser.add_argument('--book', type=str, help='Name of b...
2,202
756
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from uuid import UUID from typing import List from botframework.streaming.transport import TransportConstants from .models import Header _CHAR_TO_BINARY_INT = {val.decode(): list(val)[0] for val in [b".", b"\n", b"1", b"0"...
5,565
1,627
#!/usr/bin/env python3 ############################################################################### # Copyright 2020 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
6,849
1,986
import numpy as np import pytest from cblearn.datasets import fetch_musician_similarity @pytest.mark.remote_data def test_fetch_musician_similarity(tmp_path): data_home = tmp_path / 'cblearn_datasets' bunch = fetch_musician_similarity(data_home=data_home, shuffle=False) assert bunch.data.shape == (131_9...
1,273
510
from django.utils.decorators import method_decorator from rest_framework import viewsets, status, generics from rest_framework.response import Response from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from drf_yasg.utils import swa...
2,847
775
from mail_bug.mail_bug import MailBug def test_return_code(): bug = MailBug([]) assert bug.run() == 0
112
43
# _*_coding:utf-8_*_ from django.conf import settings import uuid, os, json, logging, time, shutil from datetime import datetime, date from PIL import Image, ImageFile import mimetypes import re logger = logging.getLogger(__name__) def get_file_path(instance, filename): folder = instance.__class__.__name__.lower...
8,244
2,956
import requests from tqdm import tqdm from time import sleep import os class DataLoader(): """ This class is used to download a pre-trained neural network model from url. It stores model name and the link to a model. """ def __init__(self): # url where model is stored self.model_ur...
1,853
563
"""Bottle route plugins.""" from .injection_plugin import InjectionPlugin
75
22
from enum import Enum from typing import List, Union from urllib.parse import urljoin import warnings from airflow.exceptions import AirflowException from airflow.providers.siafi.hooks.siafi import SIAFIHook import requests warnings.filterwarnings('ignore', message='Unverified HTTPS request') class TesouroGerencial...
4,419
1,450
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers class OffensiveLSTMModel: def __init__(self, args, embedding_matrix): emb = layers.Embedding(args.max_features, args.embed_size, trainable=False, name="embedding_layer") inp = t...
843
290
import backoff import psycopg2 from psycopg2.extras import DictCursor, NamedTupleCursor from st_library.utils.generics.connectors import ConnectorContainer _disconnect_errors = (psycopg2.InterfaceError, psycopg2.OperationalError,) _backoff = backoff.on_exception(backoff.expo, _disconnect_errors, max_time=30, max_tri...
2,852
853
import gooeypie as gp date_formats = ['28/8/20', '8/28/20', '28/08/2020', '08/28/2020', '2020-08-28', '28-Aug-2020', 'Friday, August 28, 2020', 'Friday, 28 August, 2020', 'August 28, 2020', '28 August, 2020'] app = gp.GooeyPieApp('Time and date') app.width = 250 label = gp.Label(app, ...
566
299
# https://www.w3.org/TR/filter-effects/#funcdef-grayscale # https://www.w3.org/TR/filter-effects/#grayscaleEquivalent # https://www.w3.org/TR/SVG/filters.html#feColorMatrixElement import numpy as np from . import rgb_clamp _CONST_PART = np.array([[0.2126, 0.7152, 0.0722], [0.2126, 0.7152, 0....
1,131
483
# Specialization: Google IT Automation with Python # Course 01: Crash Course with Python # Week 5 Module Part 3 Exercise 02 # Student: Shawn Solomon # Learning Platform: Coursera.org # Let’s expand a bit on our Clothing classes from the previous in-video question. Your mission: # Finish the "Stock_by_Material"...
2,285
830
import requests from bs4 import BeautifulSoup def find_word_meaning(word): r = requests.get(f"https://www.dictionary.com/browse/{word}") if r.status_code == 200: page = BeautifulSoup(r.text, "html.parser") luna_pos = page.find("span", {"class": "luna-pos"}).text word_meaning = f"{word}...
845
303