text
string
size
int64
token_count
int64
from . import events # noqa from django.core.wsgi import get_wsgi_application import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hoover.site.settings") application = get_wsgi_application()
200
70
#!/usr/bin/env python #Copyright (C) 2013 by Glenn Hickey # #Released under the MIT license, see LICENSE.txt #!/usr/bin/env python """This is a two-state continuous time markov model: 0: unconstratined. 1: constrained. There are two transition rates to go between states. lossRate: 1->0 and gainRate: 0->1. Probabi...
9,413
3,046
from django.test import TestCase from .validators import validate_budget_period from .models import Budget, Expense, Payment from django.contrib.auth.models import User from django.core.exceptions import ValidationError class ExpenseTestCases(TestCase): def setUp(self) -> None: user = User.objects.create...
3,610
1,014
# Generated by Django 3.2.3 on 2021-06-13 19:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('feed', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='player', name='finished_decks', ), ...
322
113
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import re from spack.package import * class Abacus(MakefilePackage): """ABACUS (Atomic-orbital Based Ab-initio Com...
3,440
1,356
print(18 * 1234) print(18 * 1234 * 2) print(0 * 1) print(1 * 0) print(0.0 * 1.0) print(1.0 * 0.0)
98
68
num = int(input()) d1 = (num % 10 ** 4) // 10 ** 3 d2 = (num % 10 ** 3) // 10 ** 2 d3 = (num % 10 ** 2) // 10 d4 = num % 10 print("Цифра в позиции тысяч равна", d1) print("Цифра в позиции сотен равна", d2) print("Цифра в позиции десятков равна", d3) print("Цифра в позиции единиц равна", d4) # print("Python", , "is the ...
354
181
import csv from os import listdir from os.path import isfile, join from osgeo import ogr from multiprocessing import Pool driver = ogr.GetDriverByName('GeoJSON') countryFile = driver.Open("../data/external/countries.json") layer = countryFile.GetLayer() class Point(object): """ Wrapper for ogr point """ de...
2,349
745
import cv2 import numpy as np def process_core(image): ''' Returns an inverted preprocessed binary image, with noise reduction achieved with greyscaling, Gaussian Blur, Otsu's Threshold, and an open morph. ''' #apply greyscaling, Gaussian Blur, and Otsu's Threshold greyscale = cv2.cvtColor...
3,126
1,048
# Copyright (c) Facebook, Inc. and its affiliates. """ Tasks come above datasets in hierarchy level. In case you want to implement a new task, you need to inherit ``BaseTask`` class. You need to implement ``_get_available_datasets`` and ``_preprocess_item`` functions to complete the implementation. You can check the so...
7,419
1,980
from numba import jit import numpy as np @jit(nopython=True, parallel=True) def gauss_n(X, Y, mu_x = 0.0, mu_y = 0.0, amp = 1.0, sigma = 3.0): ''' Function that generates 2D discrete gaussian distribution. Boosted with Numba: works in C and with parallel computing. Parameters ---------- X : nu...
862
289
# vim:ts=4:sts=4:sw=4:expandtab from token import token_container from satori.core.export.type_helpers import DefineException AccessDenied = DefineException('AccessDenied', 'You don\'t have rights to call this procedure') class PCDeny(object): def __call__(__pc__self, **kwargs): return False def __...
5,403
1,876
# Copyright 2021 Alexis Lopez Zubieta # # 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 the # rights to use, copy, modify, merge, publi...
6,982
1,918
# python3 --> Enter Python Shell # from geocode import getGeocodeLocation # getGeocodeLocation("Place you wanto to query") import httplib2 import json def getGeocodeLocation(inputString): google_api_key = "AIzaSyDZHGnbFkjZcOEgYPpDqlO2YhBHKsNxhnE" locatationString = inputString.replace(" ", "+") url = ('...
2,743
1,174
""" The roseguarden project Copyright (C) 2018-2020 Marcus Drobisch, This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
1,717
521
""" MIT License Copyright (c) 2018 Aaron Michael Scott 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 the rights to use, copy, modify, merge, pu...
5,877
1,586
from PyQt4.QtGui import QImage, QPainter from PyQt4.QtCore import QSize # configure the output image width = 800 height = 600 dpi = 92 img = QImage(QSize(width, height), QImage.Format_RGB32) img.setDotsPerMeterX(dpi / 25.4 * 1000) img.setDotsPerMeterY(dpi / 25.4 * 1000) # get the map layers and extent layers ...
1,056
386
""" Load a dataset of historic documents by specifying the folder where its located. """ import argparse # Utils import itertools import logging import math from datetime import datetime from pathlib import Path from torchvision.datasets.folder import has_file_allowed_extension, pil_loader from torchvision.transforms...
13,604
4,172
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2021/12/27 14:04 # @Author : zhangjianming # @Email : YYDSPanda@163.com # @File : run_task.py # @Software: PyCharm import sys sys.path.extend(["."]) from torch_model_demo.task.run_task import train_fashion_demo if __name__ == '__main__': train_fas...
332
151
import numpy as np import math import logging as log import sys from tqdm import tqdm from common.feature_distance import calc_features_similarity from common.common_objects import DetectedObject, validate_detected_object, Bbox from common.common_objects import get_bbox_center, get_dist, calc_bbox_area from common.find...
11,275
3,490
from django.db import router from django.db.models import Q, Manager from django.db import connections from .contenttypes import ct, get_content_type from .query import GM2MTgtQuerySet class GM2MBaseManager(Manager): use_in_migration = True def __init__(self, instance): super(GM2MBaseM...
16,308
5,087
from selenium.webdriver.chrome.options import Options from selenium import webdriver import logging import coloredlogs import os import pathlib import time import twitter as tt from utils import retry from fetch_likes import get_user_likes, login from conf.settings import USER_ID, USERNAME, PASSWORD CURR_PATH = path...
6,802
2,131
class Dummy(): def __init__(self, data): self.name = data['name'] self.age = data['age'] self.city = data['city'] class DummyData(): def __init__(self): self.results = [ Dummy({ 'name': 'PA', 'age': 29, 'city': 'Paris'...
1,243
386
#!/usr/bin/python import sys import os from os.path import join, isdir import sentencepiece as spm #-------------------------- def Load_sp_models(PATH): PATH_model = spm.SentencePieceProcessor() PATH_model.Load(join(PATH)) return PATH_model #--------------------------
296
88
import typing from fiepipelib.gitlabserver.data.gitlab_server import GitLabServer from fiepipelib.gitlabserver.routines.manager import GitLabServerManagerInteractiveRoutines from fiepipedesktoplib.gitlabserver.shell.gitlab_hostname_input_ui import GitLabHostnameInputDefaultShellUI from fiepipedesktoplib.gitlabserver.s...
2,213
622
import torch class MultiSequential(torch.nn.Sequential): """Multi-input multi-output torch.nn.Sequential""" def forward(self, *args): for m in self: args = m(*args) return args def repeat(N, fn): """repeat module N times :param int N: repeat time :param function fn:...
470
146
import torch import torch.nn as nn import torch.nn.functional as F class MediumNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d( 3, out_channels=6, kernel_size=5, padding=0) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv2 = nn....
857
363
from runner import runner if __name__ == '__main__': r = runner() p = 'public class main{public static void main (String[] args){' \ 'public String StudentAnswer(String myInput){' \ 'return "myOutput"; ' \ '}System.out.println("hello world!");}}' print (r.sendCode(p, ''))
309
95
import traceback import telebot from telebot import apihelper from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, MessageEntity, Message, CallbackQuery from beancount_bot import transaction from beancount_bot.config import get_config, load_config from beancount_bot.dispatcher import Dispatcher from b...
8,101
2,478
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import pytest import numpy as np import sklearn.metrics as skm import fairlearn.metrics as metrics # ====================================================== a = "a" b = "b" c = "c" Y_true = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0...
8,933
3,054
""" Adapted from OpenAI Baselines. """ import numpy as np import tensorflow as tf # pylint: ignore-module import random import copy import os import functools import collections import multiprocessing def switch(condition, then_expression, else_expression): """Switches between two operations depending on a scala...
12,833
4,242
# Under MIT License, see LICENSE.txt """ Module définissant des constantes de programmations python pour l'IA """ from enum import Enum ROBOT_RADIUS = 90 ROBOT_DIAMETER = ROBOT_RADIUS * 2 ROBOT_CENTER_TO_KICKER = 60 BALL_RADIUS = 21 MAX_PLAYER_ON_FIELD_PER_TEAM = 6 BALL_OUTSIDE_FIELD_BUFFER = 200 # Radius and angle...
1,695
773
import numpy as np x_pi = 3.14159265358979324 * 3000.0 / 180.0 pi = 3.1415926535897932384626 a = 6378245.0 ee = 0.00669342162296594323 def gcj02tobd09(lng, lat): """ Convert coordinates from GCJ02 to BD09 Parameters ------- lng : Series or number Longitude lat : Series or number ...
9,102
4,472
######## # Copyright (c) 2014 GigaSpaces 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...
8,343
2,210
import boto3 import logging import os from random import randrange from urllib.request import urlopen # It is not recommended to enable DEBUG logs in production, # this is just to show an example of a recommendation # by Amazon CodeGuru Profiler. logging.getLogger('botocore').setLevel(logging.DEBUG) SITE = 'http://w...
1,570
509
from functools import wraps from werkzeug.exceptions import HTTPException from api.exceptions import MessageNotFound def api_error_handler(func): @wraps(func) def handle_errors(*args, **kwargs): try: return func(*args, **kwargs) except MessageNotFound as e: return e.mes...
475
128
"""Command to run Nile scripts.""" import logging from importlib.machinery import SourceFileLoader from nile.nre import NileRuntimeEnvironment def run(path, network): """Run nile scripts passing on the NRE object.""" logger = logging.getLogger() logger.disabled = True script = SourceFileLoader("scrip...
406
118
array = [] for _ in range(int(input())): command = input().strip().split(" ") cmd_type = command[0] if (cmd_type == "print"): print(array) elif (cmd_type == "sort"): array.sort() elif (cmd_type == "reverse"): array.reverse() elif (cmd_type == "pop"): array.pop() ...
548
186
# Created by Qingzhi Ma at 2019-07-23 # All right reserved # Department of Computer Science # the University of Warwick # Q.Ma.2@warwick.ac.uk from sklearn.neighbors import KernelDensity class DBEstDensity: def __init__(self, kernel=None): if kernel is None: self.kernel = 'gaussian' s...
441
157
#!/usr/bin/env python import setuptools from setuptools import setup from os import path # Read the package requirements with open("requirements.txt", "r") as f: requirements = [line.rstrip("\n") for line in f if line != "\n"] # Read the contents of the README file this_directory = path.abspath(path.dirname(__fi...
920
287
# -*- coding: utf-8 -*- """ mundiapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class UpdatePlanRequest(object): """Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's n...
5,096
1,308
from hearthstone.enums import GameTag, TAG_TYPES def parse_enum(enum, value): if value.isdigit(): value = int(value) elif hasattr(enum, value): value = getattr(enum, value) else: raise Exception("Unhandled %s: %r" % (enum, value)) return value def parse_tag(tag, value): tag = parse_enum(GameTag, tag) if...
528
207
# Archivo ejemplo 00 de creacion de clases en Python from math import gcd # greatest common denominator = Maximo Comun Divisor (MCD) class Fraccion: """ La clase Fraccion: Una fraccion es un part de enteros: un numerador (num) y un denominador (den !=0 ) cuyo MCD es 1. """ def __init__(self,numer...
2,364
759
from . import models from . import components from . import http
65
16
import os import pandas as pd class LiveProjectPopularityBasedRecs: def __init__(self): self.charts = {} charts_folder = "charts" if os.path.isdir(charts_folder): for file in os.listdir("charts"): name, ext = file.split('.') if ext == "csv" an...
732
218
from distutils.core import setup import snip_basic_verify setup( py_modules=['snip_basic_verify'], ext_modules=[snip_basic_verify.ffi.verifier.get_extension()])
178
67
#!../env/bin/python """A simple test script for the PCE portion of OnRamp. Usage: ./test_pce.py This script is only intended to be run in a fresh install of the repository. It has side-effects that could corrupt module and user data if run in a production setting. Prior to running this script, ensure that onramp/pce...
647
211
import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import logging from .analysis import lifetime_histogram from .analysis import histogram_cellwise,histogram_featurewise import numpy as np def plot_tracks_mask_field_loop(track,field,mask,features,axes=None,name=None,plot_dir='./', ...
58,893
19,645
from sanic import Blueprint from sanic_transmute import add_route from .views import ( get_all, get_status_by_country_id, get_status_by_country_name, get_deaths, get_active_cases, get_recovered_cases, get_confirmed_cases, list_countries, ) cases = Blueprint("cases", url_prefix="/cases")...
608
229
from ..downloader import Downloader import os import pytest @pytest.fixture def cwd_to_tmpdir(tmpdir): os.chdir(str(tmpdir)) def test_audiobook_download(cwd_to_tmpdir, monkeypatch): audiobook_url = "https://www.scribd.com/audiobook/237606860/100-Ways-to-Motivate-Yourself-Change-Your-Life-Forever" audio...
1,860
772
# Generated by Django 3.2.4 on 2021-06-19 16:10 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20210619_1802'), ] operations = [ migrations.AddField( model_name='comment', ...
863
274
import copy import json from .dataset_info import DatasetInfoFactory class DatasetRegistry: """ A central registry of all available datasets """ def __init__(self, datasets_json: str): self.datasets = [DatasetInfoFactory.create(d) for d in json.loads(datasets_json)] def get_dataset_info(...
1,441
411
# -*- coding:utf-8 -*- # edit by fuzongfei import base64 import datetime # Create your views here. import json from django.http import Http404, HttpResponse from django.utils import timezone from django_filters.rest_framework import DjangoFilterBackend from rest_framework import filters from rest_framework.exceptions ...
20,941
6,655
import glove_util as gut import numpy as np from sklearn.decomposition import TruncatedSVD import json with open('freq_count_pred.json') as f: freq_count_pred = json.load(f) def get_pc(sentences): svd = TruncatedSVD(n_components=1, n_iter=7, random_state=0) svd.fit(sentences) return svd.components_ def weight...
1,489
620
# Importing Fernet class from cryptography.fernet import Fernet # Importing dump and load function from pickle import dump,load # To generate a strong pw def generate_pw(): from random import choice choices = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=.,/<>?;:\\|[...
3,009
972
# -*- encoding=utf-8 -*- """ # ********************************************************************************** # Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. # [oecp] is licensed under the Mulan PSL v1. # You can use this software according to the terms and conditions of the Mulan PSL ...
1,107
375
from django.db import models from django.utils import timezone # Course Category class Course_category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) date_of_creation = models.DateTimeField(default=timezone.now) # Course Subcategory class ...
1,518
490
# 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, software # distributed under the Li...
2,732
785
#!/usr/bin/env python # Script for parsing prometheus metrics format and send it into zabbix server # MIT License # https://github.com/Friz-zy/telegraf-monitoring-agent-setup import re import os import sys import time import json import socket import optparse try: from urllib.request import urlopen except: fr...
4,779
1,460
# CompOFA – Compound Once-For-All Networks for Faster Multi-Platform Deployment # Under blind review at ICLR 2021: https://openreview.net/forum?id=IgIk8RRT-Z # # Implementation based on: # Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song ...
6,239
2,132
# coding: utf-8 import pickle # import json # import types path = 'application/model/radar_score_20180117/' def f(x, x_range, score): bottom = 20 y = [] for i in x: if i < x_range[0]: pos = 0 else: for j in range(len(x_range)): if j == len(x_range) - 1 or \ i >= x_range[...
2,911
1,187
#!/bin/python3 import math import os import random import re import sys from typing import Counter # # Complete the 'numCells' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY grid as parameter. # def numCells(grid): # Write your code here n = [] ...
951
346
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ # Examples: # url(r'^$', 'evetool.views.home', name='home'), url(r'^', include('users.urls')), url(r'^', include('apis.urls')), ] + static(settings.STATIC_URL, document_...
347
119
import os # virtualenv SCRIPTDIR = os.path.realpath(os.path.dirname(__file__)) venv_name = '_ck' osdir = 'Scripts' if os.name is 'nt' else 'bin' venv = os.path.join(venv_name, osdir, 'activate_this.py') activate_this = (os.path.join(SCRIPTDIR, venv)) # Python 3: exec(open(...).read()), Python 2: execfile(...) exec(op...
375
147
#!/usr/bin/env python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import os import sys import common def main_run(args): with common.temporary_file() as tempfile_path: rc = common...
1,036
373
from autoPyTorch.utils.config.config_option import ConfigOption from autoPyTorch.pipeline.base.sub_pipeline_node import SubPipelineNode import traceback class ForAutoNetConfig(SubPipelineNode): def fit(self, pipeline_config, autonet, instance, data_manager, run_id, task_id): for config_file in self.get_co...
2,139
653
import csv import requests import sys """ A simple program to print the result of a Prometheus query as CSV. """ if len(sys.argv) != 3: print('Usage: {0} http://prometheus:9090 a_query'.format(sys.argv[0])) sys.exit(1) response = requests.get('{0}/api/v1/query'.format(sys.argv[1]), params={'query': s...
913
306
class AuthError(Exception): pass class JsonError(Exception): pass
76
23
from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory import requests import pytest import json from django.core.management import call_command from django.db.models.signals import pre_save, post_save, pre_delete, post_delete, m2m_changed from rest_framework.test import APIClien...
4,696
1,641
# 3. Define a function to check whether a number is even def even(num): if num%2 == 0: return True else: return False print(even(4)) print(even(-5))
175
61
""" Posterior for Cauchy Distribution --------------------------------- Figure 5.11 The solid lines show the posterior pdf :math:`p(\mu|{x_i},I)` (top-left panel) and the posterior pdf :math:`p(\gamma|{x_i},I)` (top-right panel) for the two-dimensional pdf from figure 5.10. The dashed lines show the distribution of ap...
4,229
1,616
# -*- coding: utf-8 -*- """The file system stat event formatter.""" from __future__ import unicode_literals from dfvfs.lib import definitions as dfvfs_definitions from plaso.formatters import interface from plaso.formatters import manager from plaso.lib import errors class FileStatEventFormatter(interface.Conditio...
9,090
3,224
from rest_framework import serializers from applications.models import Application class ApplicationSerializer(serializers.Serializer): content = serializers.JSONField() portfolio = serializers.FileField() class ApplicationAdminSerializer(serializers.ModelSerializer): class Meta: model = Appli...
555
133
from pathlib import Path import requests from requests_toolbelt.multipart.encoder import MultipartEncoder # api_token = "iNKzBVNVAoTMhwnT2amhZRAP4dTBjkEVw9AbpRWg" # brand_center = "mdanderson.co1" # data_center = "iad1" # headers = {"x-api-token": api_token} class QualtricsTool: """Data model to manage Qualtrics...
8,440
2,399
from SublimeLinter.lint import Linter, STREAM_STDOUT class CSpell(Linter): cmd = 'cspell stdin' defaults = {'selector': 'source'} regex = r'^[^:]*:(?P<line>\d+):(?P<col>\d+) - (?P<message>.*)$' error_stream = STREAM_STDOUT
241
100
from metal.gdb.metal_break import Breakpoint, MetalBreakpoint from metal.gdb.exitcode import ExitBreakpoint from metal.gdb.timeout import Timeout from metal.gdb.newlib import NewlibBreakpoints from metal.gdb.argv import ArgvBreakpoint
238
77
#!/usr/bin/python3 from datetime import datetime from PyQt5.QtWidgets import QTableWidgetItem, QTableWidget, QAbstractItemView, QMenu, QMessageBox from PyQt5.QtGui import QCursor from PyQt5.QtCore import Qt, pyqtSignal, QObject from portfolio.db.fdbhandler import results, strategies, balances def updatingdata(func...
11,693
3,084
class OverlapResult: def __init__(self, overlap_map: dict[tuple[float, float], int]): self._overlap_map = overlap_map self._overlaps = overlap_map_to_overlaps(overlap_map) @property def overlaps(self) -> int: return self._overlaps @property def overlap_map(self) -> dict[tu...
567
185
#!/usr/bin/env python from distutils.core import setup VERSION = "0.0.1" setup( author='Nikolai Tschacher', name = "proxychecker", version = VERSION, description = "A Python proxychecker module that makes use of socks", url = "http://incolumitas.com", license = "BSD", author_email = "admin...
451
155
class Config: def __init__(self, config_file_name): self.config_file_name = config_file_name
99
38
#!/usr/bin/env python3 from app.lib.utils.request import request from app.lib.utils.encode import base64encode from app.lib.utils.common import get_capta, get_useragent class S2_052_BaseVerify: def __init__(self, url): self.info = { 'name': 'S2-052漏洞,又名CVE-2017-9805漏洞', 'descriptio...
5,156
1,265
import sys # def get_tools(): # manager = PluginManager() # manager.setPluginPlaces(["plugins/file_cabinet"]) # manager.collectPlugins() # return [plugin.plugin_object for plugin in manager.getAllPlugins()] def get_tools(): import importlib tools = ['file_cabinet', 'us', 'automator', 'main'] ...
905
285
from __future__ import absolute_import, print_function, unicode_literals # "preload" for FindIt #2: iterate over same journal list, but actually # load a PubMedArticle object on each PMID. (no list output created) from metapub import FindIt, PubMedFetcher from metapub.findit.dances import the_doi_2step from config...
1,574
575
from __future__ import absolute_import from select import select import errno import functools import itertools import json import logging import os import socket import threading import time import traceback log = logging.getLogger(__name__) from .utils import makedirs, unlink class TimeOut(Exception): pass ...
7,640
2,162
# -*- coding: utf-8 -*- """ lantz.drivers.tektronix.tds1012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements the drivers to control an oscilloscope. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from lantz.core import Feat, MessageBase...
502
207
########################################################################## # # Copyright 2014 VMware, Inc # Copyright 2011 Jose Fonseca # All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
48,209
22,011
import numpy as np import cv2 import glob import matplotlib.pyplot as plt def camera_calibrate(images_list, nx=9, ny=6, show_corners=False): # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((ny*nx,3), np.float32) objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2) # Ar...
1,465
508
""" module logging""" # logging
34
12
# Copyright 2021 Red Hat, 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 in writing...
22,135
6,430
# -*- coding: utf-8 -*- # Author: Ivan Senin import calendar import time import datetime as dt import json class User(object): def __init__(self, id, name, last_seen, want_time, muted, username="", additional_keys="{}"): super(User, self).__init__() self.id = id self.name = name self.username = username se...
1,474
596
from datetime import datetime, timezone from enum import Enum from typing import Dict, List, Optional import pydantic from fastapi import HTTPException, Path, status from pydantic import BaseModel, EmailStr, Field from contaxy.schema.exceptions import ClientValueError from contaxy.schema.shared import MAX_DESCRIPTION...
16,294
4,570
import setuptools from hugdatafast.__init__ import __version__ with open("README.md", "r") as fh: long_description = fh.read() REQUIRED_PKGS = [ 'fastai>=2.0.8', 'fastscore>=1.0.1', # change of store_attr api 'datasets', ] setuptools.setup( name="hugdatafast", version=__version__, author=...
1,193
383
import pytest from leapp.repository.actor_definition import ActorDefinition, ActorInspectionFailedError, MultipleActorsError from leapp.exceptions import UnsupportedDefinitionKindError from leapp.repository import DefinitionKind from helpers import repository_dir import logging import mock _FAKE_META_DATA = { 'de...
3,591
967
from django.db import models # Create your models here. from utils.models import BaseModel class House(BaseModel): '''房屋信息''' user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='房屋用户') area = models.ForeignKey('address.Area', on_delete=models.SET_NULL, null=True, verbo...
2,139
865
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Cltwit is a command line twitter utility Author : Jérôme Launay Date : 2013 """ import os import sys import re import getopt import gettext import sqlite3 import webbrowser import ConfigParser from sqlite2csv import sqlite2csv from cltwitdb import cltwitdb from utils...
15,863
5,075
# @AUTHOR : lonsty # @DATE : 2020/3/28 18:01 class CookiesExpiredException(Exception): pass class NoImagesException(Exception): pass class ContentParserError(Exception): pass class UserNotFound(Exception): pass
235
84
import requests from bs4 import BeautifulSoup import re # 设置请求头 # 更换一下爬虫的User-Agent,这是最常规的爬虫设置 headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} # 获取天气信息 def get_weather(): html = requests.get("http://www.wea...
1,135
508
import numpy as np import math import matplotlib.pyplot as plt U = 5 # equival a l'E R = 2 # equival a R1 R2 = 3 P = 1.2 Vt = 0.026 Is = 0.000005 n = 200 # profunditat Vd = np.zeros(n) # sèries Vl = np.zeros(n) I1 = np.zeros(n) I1[0] = U / R # inicialització de les sèries Vd[0] = Vt * math.log(1 + I1[0] / Is)...
1,158
625
"""Errors.""" class ProxyError(Exception): pass class NoProxyError(Exception): pass class ResolveError(Exception): pass class ProxyConnError(ProxyError): pass class ProxyRecvError(ProxyError): # connection_is_reset pass class ProxySendError(ProxyError): # connection_is_reset pass ...
614
194
import torch from torch import nn as nn from torch import autograd class LogSumExpPooling1d(nn.Module): """Applies a 1D LogSumExp pooling over an input signal composed of several input planes. LogSumExp is a smooth approximation of the max function. 在由多个输入平面组成的输入信号上应用1D LogSumExp池。 LogSumExp是max函数的平滑近...
729
281