text
string
size
int64
token_count
int64
# coding: utf-8 """ Trakt Playback Manager """ from __future__ import absolute_import from __future__ import unicode_literals import io import json import os.path def save(path, data): with io.open(path, 'w', encoding='utf-8', newline='\n') as fh: # Must NOT use `json.dump` due to a Python 2 bug: ...
945
318
#!/usr/bin/env python3 import sys import os.path import re from datetime import date, datetime, time, timedelta # helper def is_timeformat(s): p = re.compile('^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}$') if p.match(s) is None: return False else: return True def is_time_line(l): p = re.c...
2,810
979
from typing import Optional from .glyph import Glyph class Font: def __init__( self, name: str, em_size: float, cap_height: float, x_height: float, line_height: float, slope: float, char_spacing: float, ): raise NotImplementedError ...
1,195
347
# encoding: utf-8 import copy import itertools import numpy as np import torch import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from torch import nn, optim from .resnet import ResNet def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: ...
2,739
991
import csv DIR = 'credo-data-export/detections' CSV = 'credo-data-export/credocut.tsv' PLOT = 'credo-data-export/credocut.plot' JSON = 'credo-data-export/credocut.json' DEVICES = 'credo-data-export/device_mapping.json' PNG = 'credo-data-export/png' CREDOCUT = 10069 DELIMITER='\t' QUOTECHAR='"' QUOTING=csv.QUOTE_MINIM...
710
315
# The following comments couldn't be translated into the new config version: #------------------------------------------------ #AlCaReco filtering for phi symmetry calibration: #------------------------------------------------ # # Passes events that are coming from the online phi-symmetry stream # # import FWCore.P...
540
166
import re import json import logging import hmac import base64 import hashlib import jsonschema from uuid import uuid4 from aiohttp import web from pathlib import Path from yaml import safe_load from http import HTTPStatus from datetime import datetime, timezone from {{cookiecutter.project_name}}.routes import setup...
13,456
3,474
def load(): with open("input") as f: yield next(f).strip() next(f) for x in f: yield x.strip().split(" -> ") def pair_insertion(): data = list(load()) polymer, rules = list(data[0]), dict(data[1:]) for _ in range(10): new_polymer = [polymer[0]] for...
669
248
# Author: Jintao Huang # Email: hjt_study@qq.com # Date: from .KMeans import KMeans
85
38
import pygame, sys, cmath, time, math def get_mandlebrot(x, y): num = complex(x, y) curr_num = complex(0, 0) max_iter = 100 for a in range(max_iter): curr_num = (curr_num * curr_num) + num r, phi = cmath.polar(curr_num) if r > 2: return a/max_iter return 1 def ...
5,000
1,796
#!/usr/bin/python import urllib2 import random # A list of places we've deployed ricochet ricochet_servers = [ "http://127.0.0.1:8080/ricochet/ricochet?url=", "http://127.0.0.1:8080/ricochet/ricochet?url=" ] # We're identifying ourselves to ourself here, this will show up in the server logs (unless you've disabled th...
835
306
def compChooseWord(hand, wordList, n): """ Given a hand and a wordList, find the word that gives the maximum value score, and return it. This word should be calculated by considering all the words in the wordList. If no words in the wordList can be made from the hand, return None. hand: ...
2,054
583
import argparse from typing import Optional import annofabcli import annofabcli.common.cli import annofabcli.filesystem.draw_annotation import annofabcli.filesystem.filter_annotation import annofabcli.filesystem.mask_user_info import annofabcli.filesystem.merge_annotation import annofabcli.filesystem.write_annotation_...
1,172
422
import getpass import os import sys VER = '1.0.1.7' VERSION = 'Version=%s' % VER MANUFACTURER = 'Manufacturer=Vinay Sajip' X86 = 'Platform=x86' X64 = 'Platform=x64' TOWIN = 'ToWindows' def main(): signpwd = getpass.getpass('Password for signing:') import builddoc builddoc.main() os.envi...
780
353
#!/usr/bin/env python from __future__ import print_function import json from spyne import AnyUri, Unicode, ComplexModel, M, UnsignedInteger16, Array from spyne.protocol.json import JsonDocument from spyne.util.dictdoc import get_object_as_dict class BenchmarkConfigElement(ComplexModel): # exclude this from the...
2,736
995
# Copyright 2019 The Johns Hopkins University # # 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...
2,557
717
from .response import BoltResponse
35
9
#!/usr/bin/env python from __future__ import division from get_sub_dir_dates import get_sub_dir_dates from get_table_hdfs_location import get_table_hdfs_location import unittest import sys __author__ = 'youval.dar' class CollectDates(unittest.TestCase): def test_get_sub_dir_dates(self): print sys._getfr...
1,063
355
# Copyright (c) 2018-2021 Kaiyang Zhou # SPDX-License-Identifier: MIT # # Copyright (c) 2018 davidtvs # SPDX-License-Identifier: MIT # # Copyright (c) 2018 Facebook # SPDX-License-Identifier: MIT # # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # from __future__ import absolute_impor...
5,831
1,923
from setuptools import setup, Extension # Compile parts of `freq.cpp` into a shared library so we can call it from Python setup( #... ext_modules=[Extension('gof_test', ['freq.cpp'],),], )
198
65
from .network import ClusterNetwork
36
9
# Hangman game import random WORDLIST_FILENAME = "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ # inFile: file inFile = open(WORDLIST_FILE...
3,534
1,027
class Colors: END = '\033[0m' ERROR = '\033[91m[ERROR] ' INFO = '\033[94m[INFO] ' WARN = '\033[93m[WARN] ' def get_color(msg_type): if msg_type == 'ERROR': return Colors.ERROR elif msg_type == 'INFO': return Colors.INFO elif msg_type == 'WARN': return Colors.WARN else: return Colors.END...
520
220
""" This Module defines the main the main component of the Agent service, a bridge that listens to UDP messages from the LoRa gateway's Packet Forwarder and encapsulates and sends them using the AMQP protocol to the Test Application Server (TAS). """ #####################################################################...
9,689
3,012
from abc import ABC, abstractmethod from typing import TypeVar, Generic T = TypeVar("T") class AbstractResourceResolver(Generic[T], ABC): """ The resolver takes care of creating fully qualified names from resource keys. For instance, when working with files this would be the file path, when working w...
461
117
from .star import * from .partitioned_norm import *
51
15
__author__ = 'Bohdan Mushkevych' from odm.document import BaseDocument from odm.fields import StringField, ObjectIdField, ListField, IntegerField MAX_NUMBER_OF_LOG_ENTRIES = 32 TIMEPERIOD = 'timeperiod' PROCESS_NAME = 'process_name' START_OBJ_ID = 'start_obj_id' END_OBJ_ID = 'end_obj_id' STATE = 'state' RELATED_UNIT_...
3,409
1,146
def naive_string_matching(t, w, n, m): for i in range(n - m + 1): j = 0 while j < m and t[i + j + 1] == w[j + 1]: j = j + 1 if j == m: return True return False
187
85
from django.test import TestCase, Client from django.contrib.auth.models import User from .models import * from django.urls import reverse from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import InMemoryUploadedFile from io import BytesIO import pyotp import json # Cre...
27,291
8,868
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.rulefit import H2ORuleFitEstimator def football(): df = h2o.import_file("https://h2o-public-test-data.s3.amazonaws.com/mli-testing/manual-test/small-dataset/binomial/football_prediction.csv") df["FTR"] = df...
1,965
750
import pandas as pd import os from pathlib import Path import warnings warnings.filterwarnings('ignore') DATA_PATH = os.path.join( os.fspath(Path(__file__).parents[1]), "data") IMDB_DATA_PATH = os.path.join(DATA_PATH, "imdb_category.csv") EXPORT_PATH = os.path.join(DATA_PATH, "imdb_category_binary.csv") ca...
1,140
377
from functools import wraps import numpy as np import SimpleITK as sitk from ..utils import array_to_image, image_to_array def accepts_segmentations(f): @wraps(f) def wrapper(img, *args, **kwargs): result = f(img, *args, **kwargs) if isinstance(img, Segmentation): result = sit...
3,003
965
from __future__ import division """ critical properties of diffBragg objects which should be logged for reproducibility """ # TODO : implement a savestate and getstate for these objects # attrs of diffBragg() instances DIFFBRAGG_ATTRS = [ 'Amatrix', 'Bmatrix', 'Ncells_abc', 'Ncells_abc_aniso', 'Ncells_def', 'N...
1,432
596
from allennlp.data.fields import Field def test_eq_with_inheritance(): class SubField(Field): __slots__ = ["a"] def __init__(self, a): self.a = a class SubSubField(SubField): __slots__ = ["b"] def __init__(self, a, b): super().__init__(a) ...
1,571
598
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 22 10:19:44 2021 @author: sb069 """ import os import errno from os.path import expanduser os.system("sudo apt-get update") os.system("sudo apt install nvidia-cuda-toolkit") os.system("sudo apt install python3.8") os.system("conda install flye") tr...
1,870
742
""" Wrapper for epi_reg command """ import fsl.utils.assertions as asrt from fsl.wrappers import wrapperutils as wutils @wutils.fileOrImage('data', 'roi', outprefix='out') @wutils.fileOrArray('veslocs', 'encdef', 'modmat') @wutils.fileOrText(' ') @wutils.fslwrapper def veaslc(data, roi, veslocs, encdef, imlist, modm...
1,006
395
# Leo colorizer control file for kivy mode. # This file is in the public domain. # Properties for kivy mode. properties = { "ignoreWhitespace": "false", "lineComment": "#", } # Attributes dict for kivy_main ruleset. kivy_main_attributes_dict = { "default": "null", "digit_re": "", "esc...
3,455
1,657
# -*- coding: utf-8 -*- # ©Prem Prakash # Predictor module import os import sys import pdb from copy import deepcopy import argparse import onnx import onnxruntime as ort import math from matplotlib.pyplot import imshow import numpy as np import pandas as pd import torch import torch.nn as nn from torch.utils.dat...
10,642
4,137
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
4,004
1,352
import torchaudio.transforms from torch import nn from hw_asr.augmentations.base import AugmentationBase from hw_asr.augmentations.random_apply import RandomApply class SpecAug(AugmentationBase): def __init__(self, freq_mask: int, time_mask: int, prob: float, *args, **kwargs): self.augmentation = nn.Sequ...
643
212
import json import pathlib DEFAULT_CONFIG = { # 设置默认class 'EngineClass': 'acrawler.engine.Engine', 'SchedulerClass': 'acrawler.scheduler.Scheduler', 'FilterClass': 'acrawler.filterlib.memfilter.MemFilter', 'QueueClass': 'acrawler.queuelib.sqlitequeue.PrioritySQLiteQueue', ...
1,982
624
from functools import reduce import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import yaml from matplotlib import cm import pymongo import matplotlib from matplotlib.backends.backend_pdf import PdfPages from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from co...
13,658
4,798
# -*- coding: utf-8 -*- """ Created on Fri Apr 23 17:18:39 2021 @author: Koustav """ import os import glob import matplotlib.pyplot as plt import seaborn as sea import numpy as np import pandas as pan import math import collections import matplotlib.ticker as mtick from mpl_toolkits import mplot3d from matplotlib.col...
45,476
17,153
# Copyright (c) 2014, Salesforce.com, Inc. All rights reserved. # Copyright (c) 2015, Google, Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright ...
7,558
2,421
# Created by rahman at 16:54 2019-10-20 using PyCharm import os import sys from attacks.Linkability import Link from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LinearRegression from attacks import BinaryDNN from sklearn import svm from link_utils import linkability_bl expdict =...
1,948
766
import streamlit as st import numpy as np import pandas as pd import requests import re import altair as alt # Find all available data def find_all_spreadsheets(): available_data = {} r = requests.get('https://www.football-data.co.uk/downloadm.php') if r.status_code != 200: print('Oh dear. Error {}...
28,849
9,472
from toontown.avatar import ToontownAvatarUtils from toontown.avatar.CogExtras import * PROPS = [ ( 5, 'modules', 'suit_walls', (0.0, 342.4, 0.0), (-10.5, 0.0, 0.0), (54.6, 54.6, 54.6), 'wall_suit_build5', None, None), ( 5, 'modules', 'suit_walls', (53.686, 332.45, 0.0), (-16.5, 0.0, 0.0), (54.6, 54.6, 54.6), '...
40,610
11,190
import json import requests import tempfile import shutil import subprocess import os import logging import urllib.request from multiprocessing import Pool import app.easyCI.docker as docker from contextlib import contextmanager LOG = logging.getLogger(__name__) CONFIG = "config.json" PASSWORDS = "passwords.json" MAX...
4,309
1,426
from django.contrib.gis.geos import Point from data_collection.management.commands import BaseShpStationsShpDistrictsImporter class Command(BaseShpStationsShpDistrictsImporter): srid = 27700 council_id = "W06000021" districts_name = "polling_district" stations_name = "polling_station.shp" election...
1,201
402
from .node import Node class TypeAnnotation(Node): def __init__(self, location: [int], kind: str): super().__init__(location, kind)
147
45
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @Daddy_Blamo wrote this file. As long as you retain this notice you # can do whatever you want wi...
2,821
810
import cv2 import numpy as np import argparse def main(image_file_path): img = cv2.imread(image_file_path) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) name_window_1 = "original" name_window_2 = "grayscale" while True: cv2.imshow(name_window_1, img) cv2.imshow(name_window_2, im...
808
278
from functools import partial from kivy.clock import Clock def to_task(s): s.press("//MenuButtonTitled[@name='LOGO']") s.assert_on_screen('activity') s.press('//StartNowButton') s.assert_on_screen('tasks') s.tap("//TestIntro//TestCarouselForwardButton") s.assert_on_screen("test", manager_sele...
862
277
import requests as rq import cv2 import time import os from picdiv import divide from knn import getVeryValue from utils import showimg url = 'http://222.194.10.249/inc/validatecode.asp' res = rq.get(url) # 文件名加个时间戳 fileName = str(int(time.time())) + '.jpg' # 由于不会在内存中直接转换二进制到rgb就只能存了再读了qwq with open(fileName, 'wb') as...
1,726
813
# Generated by Django 4.0.1 on 2022-02-12 11:07 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('auctions', '0019_alter_list_date_alte...
808
282
# -*- coding: utf-8 -*- from math import isclose import pytest from pyCRGI.pure import ( get_coeffs as pure_get_coeffs, get_value as pure_get_value, get_variation as pure_get_variation, ) from pyCRGI.jited import ( get_coeffs as jited_get_coeffs, get_value as jited_get_value, get_variation as...
1,896
909
"""Update maritime data using update modules""" from __future__ import annotations from argparse import ArgumentParser import base64 import hashlib import os import shelve import toml from .modules import get_update_module def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('config...
1,188
368
""" Information on the Rozier Cipher can be found at: https://www.dcode.fr/rozier-cipher ROZIER.py Written by: MrLukeKR Updated: 16/10/2020 """ # The Rozier cipher needs a string based key, which can be constant for ease # or changed for each message, for better security constant_key = "DCODE" def encrypt(plaintext:...
4,627
1,200
from seamless.highlevel import Context from pprint import pprint ctx = Context() ctx.a = 12 ctx.compute() print(ctx.a.value) print(ctx.a.schema) # None def triple_it(a): return 3 * a def triple_it_b(a, b): print("RUN!") return 3 * a + b ctx.transform = triple_it ctx.transform.debug.direct_print = True ...
3,324
1,211
from astropy import units as u degree: u.Unit = u.degree
58
22
from typing import Tuple import numpy as np import pandas as pd import time def split_train_test(X: pd.DataFrame, y: pd.Series, train_proportion: float = .75) \ -> Tuple[pd.DataFrame, pd.Series, pd.DataFrame, pd.Series]: """ Randomly split given sample to a training- and testing sample Parameters...
2,374
765
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-15 08:30 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('review', '0003_auto_20170314_2217'), ] operations ...
2,583
773
from __future__ import unicode_literals from .backends import UrlAuthBackendMixin from .compatibility import urlencode from .middleware import TOKEN_NAME def get_parameters(user): """ Return GET parameters to log in `user`. """ return {TOKEN_NAME: UrlAuthBackendMixin().create_token(user)} def get_...
459
146
from ..helpers import IFPTestCase from intficpy.things import Thing, Container, Liquid class TestDropVerb(IFPTestCase): def test_verb_func_drops_item(self): item = Thing(self.game, self._get_unique_noun()) item.invItem = True self.me.addThing(item) self.assertIn(item.ix, self.me.c...
1,743
583
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from woot.apps.catalog.models.forum import Question, Answer from woot.apps.catalog.models.core import Makey, Comment from woot.ap...
3,076
899
from django.contrib import admin from .models import MarketplaceAccount, Plan, Subscription # Register your models here. admin.site.register(Plan) admin.site.register(Subscription) admin.site.register(MarketplaceAccount)
223
61
# Copyright 2013 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. """A module for the info implementation of Command.""" from __future__ import print_function import cr class InfoCommand(cr.Command): """The cr info co...
1,316
406
"""计算分位数""" from scipy import stats import numpy as np S = 47 N = 100 a = S + 1 b = (N -S) + 1 alpha = 0.05 lu = stats.beta.ppf([alpha/2, 1-alpha/2], a, b) print(lu) ## MC方法 S = 1000 X = stats.beta.rvs(a, b, size=S) X = np.sort(X, axis=0) l = X[round(S*alpha/2)] u = X[round(S*(1-alpha)/2)] print(l,u)
304
171
import json import os from concurrent.futures import ProcessPoolExecutor import numpy as np import torch from PIL import Image from nltk.tokenize import word_tokenize from torch.utils.data import Dataset, DataLoader class CQADataset(Dataset): def __init__(self, cqa_data, ans2idx, ques2idx, maxlen, split, config)...
5,009
1,746
from re_calc.config import * from re_calc.exceptions import CalcException from re_calc.util import is_number import re_calc.meta_containers as meta_containers def peek(stack): return stack[-1] def should_move_to_queue(stack, c_token_prc): ''' Checks token's precedence and associativity to decide if it should...
4,363
1,287
# Copyright (c) 2021 PPViT 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
28,944
9,373
import learntools from setuptools import setup from setuptools import find_packages setup(name='learntools', version=learntools.__version__, description='Utilities for Kaggle Learn exercises', url='http://github.com/kaggle/learntools', author='Dan Becker', author_email='dan@kaggle.com', ...
740
221
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse import json from redis import Redis from .utils import load_cluster_details, load_job_details def create_job_details(cluster_name: str, job_name: str): # Load details cluster_details = load_cluster_details(cluster_nam...
1,102
349
#!/usr/bin/env python3 # xml 资源 xml_w3_book = """ <?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> <title lang="eng">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.95</price> </book> </bookstore> """
287
138
#!env python3 """ Introducing static object in the world. Tasks: 1. File got really long - move all classes to library file and import them here. """ import pygame from pygame import K_ESCAPE, K_LEFT, K_RIGHT, K_UP, K_DOWN, QUIT class Game(): def __init__(self): """ Set basic configura...
5,855
1,878
# admin.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 0.0.0 from __future__ import unicode_literals from django.apps import AppConfig class EarthEngineConfig(AppConfig): name = 'earth_engine'
256
96
""" __init__.py State Estimation and Analysis for PYthon Module for working with oceanographic data and models Copyright (c)2019 University of Hawaii under the MIT-License. Requires the following packages: joblib Import classes include: - :class:`~seapy.environ.opt` - :class:`~seapy.progressbar....
1,333
526
from pypy.rpython.rctypes.tool import ctypes_platform from pypy.rpython.rctypes.tool.libc import libc import pypy.rpython.rctypes.implementation # this defines rctypes magic from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import W_Root, ObjSpace, Wrappable from pypy.interpreter.type...
22,776
8,241
# -*- coding: utf-8 -*- """ Created on Wed Nov 29 00:56:43 2017 @author: roshi """ import pandas as pd import matplotlib.pyplot as plt import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from app import app data = pd.read_csv('./data/youth_to...
2,576
879
from phc.easy.patients.name import expand_name_value def test_name(): assert expand_name_value( [{"text": "ARA251 LO", "given": ["ARA251"], "family": "LO"}] ) == {"name_given_0": "ARA251", "name_family": "LO"} def test_name_with_multiple_values(): # NOTE: Official names are preferred first and t...
1,084
326
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from sqlalchemy import create_engine from helpers.transport import RMQEventMap, KafkaEventMap, get_rmq_connection_parameters, get_kafka_connection_parameters from configs.helper import get_abs_static_dir, create_message_bus, create_rpc import os ...
2,249
906
from app import app from flask import request @app.route("/user-agent/a") def useragent_a(): assert "Mozilla/5.0 A" == request.headers["User-Agent"] return "" @app.route("/user-agent/b") def useragent_b(): assert "Mozilla/5.0 B" == request.headers["User-Agent"] return ""
292
105
import argparse import datetime import errno import json import logging import os import random import re import shutil import subprocess import sys import time import traceback import zipfile import zlib from functools import wraps from types import SimpleNamespace import psutil import py7zr from artifactory import A...
61,398
16,885
"""utility library for interacting with remote services, such as: * dashboard * journal * elife-bot * journal-cms contains no tests to be run.""" from os import path import random import string import requests from econtools import econ_workflow from pollute import modified_environ import mechanicalsoup from spectru...
14,752
4,721
import os import subprocess from . import settings from .exceptions import BadExitStatusError from .exceptions import wait_and_raise_if_fail def build_osmtools(path, output=subprocess.DEVNULL, error=subprocess.DEVNULL): src = { settings.OSM_TOOL_UPDATE: "osmupdate.c", settings.OSM_TOOL_FILTER: "o...
2,858
1,019
from flask import Flask, render_template, redirect, request, url_for, session from flask_sqlalchemy import SQLAlchemy from src import DB import subprocess import os import signal app = Flask(__name__, template_folder='templates') app.secret_key = 'super secret key' app.config['SESSION_TYPE'] = 'filesystem' #app.config...
3,210
996
from transformers import RobertaTokenizer, RobertaForSequenceClassification, AdamW import torch import json from sklearn import metrics from tqdm import tqdm import numpy as np from time import time from datetime import timedelta import pandas as pd from sklearn.model_selection import train_test_split import argparse i...
9,027
3,024
import unittest from dmLibrary import create_app from dmLibrary.external.googleBook import GoogleBook import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class TestClass(unittest.TestCase): def setUp(self): app = create_app() self.ctx = app.app_c...
5,065
1,663
""" Title: 0035 - Search Insert Position Tags: Binary Search Time: O(logn) Space: O(1) Source: https://leetcode.com/problems/search-insert-position/ Difficulty: Easy """ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype:...
697
214
# pylint: disable=global-statement """ Module providing unittest test discovery hook for our Doctest testcases Copyright (C) 2015, 2016 ERT Inc. """ import unittest import doctest from time import sleep from api import app_module as app from api import ( config_loader ,aes ,json ,resource_util ) __au...
1,337
456
from __future__ import absolute_import from __future__ import print_function import unittest from aiida.manage.fixtures import PluginTestCase import subprocess, os def backend_obj_users(): """Test if aiida accesses users through backend object.""" backend_obj_flag = False try: from aiida.backends...
9,736
3,329
#!/usr/bin/env python # -*- coding:utf-8 -*- # @FileName : knn.py # @Time : 2020/9/25 12:29 # @Author : 陈嘉昕 # @Demand : k-临近算法,和训练的模型作比较 import csv import math import operator from random import shuffle import matplotlib.pyplot as plt # 数据集 training_set = [] # 测试集 test_set = [] def cross_validation(fil...
4,017
1,383
# encoding: UTF-8 import os import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import json ######################################################################## class StockHandler(tornado.web.RequestHandler): """handler""" def initialize(self, mainEngine...
5,530
1,934
import numpy as np import tensorflow as tf import os import navirice_image_pb2 import cv2 import random import sys from navirice_generate_data import generate_bitmap_label from navirice_helpers import navirice_image_to_np from navirice_helpers import navirice_ir_to_np from navirice_helpers import map_depth_and_rgb fro...
7,126
2,679
# -*- coding: UTF-8 -*- import cv2 import numpy as np # 仿射变换(图像位置校正) def img_three(imgPath): # ---------------------------三点得到一个变换矩阵 --------------------------- """ 三点确定一个平面,通过确定三个点的关系来得到转换矩阵 然后再通过warpAffine来进行变换 """ img = cv2.imread(imgPath) rows,cols,_ = img.shape points1 ...
1,448
701
from progressbar import progressbar from tqdm import tqdm import multiprocessing as mp import pandas as pd import numpy as np import pyemblib import scipy import queue import time import sys import os ''' preprocessing.py Preprocessing methods for cuto.py. ''' #========1=========2=========3=========4=========5=...
6,836
2,172
import argparse from profile import Profile PROXY = 'proxy' VERIFY = 'verify' DEBUG = 'verbose' class CliParser(): def __init__(self, requests, profiles, options): self.requests = requests self.profiles = profiles self.options = options self.args = None # Use a pre-parser...
6,931
1,690
"""Builds a button according to the theme of the app.""" import PySimpleGUI as sg from src.globals import colors def build(text, key, font, size): """Returns a button with the current theme""" button = sg.Button( button_text=text, button_color=(colors.WHITE, colors.LIGHT_GRAY), mou...
448
142
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2022 NVIDIA Corporation. 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://...
8,005
3,046
"""Class static method test""" class TestClass(): """Test class""" def __init__(self, a=1, b=2): self.a = a self.b = b def add(self): return self.a + self.b @staticmethod def static_add(a, b): return 2 * a + 2 * b def add2(self): return self.static_a...
435
172