text
string
size
int64
token_count
int64
import numpy as np import pytest from ..shear_bias_meas import ( measure_shear_metadetect, estimate_m_and_c, estimate_m_and_c_patch_avg) def test_measure_shear_metadetect_smoke(): dtype = [('flags', 'i4'), ('wmom_g', 'f4', (2,)), ('wmom_s2n', 'f4'), ('wmom_T_ratio', 'f4'), ('ormask', 'i4')] ...
8,850
4,194
from mininet.net import Mininet from mininet.node import Controller, UserSwitch, IVSSwitch, OVSSwitch from mininet.log import info, setLogLevel setLogLevel("info") import importlib switch_num = 1 def add_switch(net): global switch_num res = "s%s" % str(switch_num) switch_num += 1 return net.addSwitc...
1,221
450
from rest_framework import permissions __author__ = "Ville Myllynen" __copyright__ = "Copyright 2017, Ohsiha Project" __credits__ = ["Ville Myllynen"] __license__ = "MIT" __version__ = "1.0" __maintainer__ = "Ville Myllynen" __email__ = "ville.myllynen@student.tut.fi" __status__ = "Development" class IsOwnerOrReadO...
856
267
## # Copyright (c) 2016, Microsoft Corporation # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions...
3,994
1,455
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
2,899
807
#!/usr/bin/env python import boto import boto.ec2 import sys from boto.ec2.connection import EC2Connection import pprint account_string = "YOUR_ACCOUNT_STRING" #change this for each AWS account class ansi_color: #unused class due to CSV file limitations red = '\033[31m' green = '\033[32m' re...
4,863
1,641
# one hop helper function def one_hop_majority_vote(G, gender_y_update,train_index, test_index): A = np.array(nx.adjacency_matrix(G).todense()) D = np.diag(np.sum(A, axis=1)) d = np.diag(D) theta = [None]*len(gender_y_update) accuracy_score_benchmark = np.sum(gender_y_update[train_index])/len(train...
1,832
701
from collections import OrderedDict import numpy as np from tqdm import tqdm import tensorflow as tf from .player import MCTSPlayer, RandomPlayer, OptimalPlayer from .evaluator import evaluate from .mcts_tree import MCTSNode, mcts from .utilities import sample_distribution __all__ = ["train_alphago", "self_play", "p...
18,284
5,526
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-29 14:52 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reuse', '0001_initial'), ] operations = [ m...
835
281
import numpy as np import matplotlib.pyplot as plt from .rule_manager import RuleManager class CA1D(): def __init__(self, N): """ Creates an uninitialized 1D cellular automata object with length N ------------- Parameters: N = number of cells n1 : left neigh...
5,976
1,660
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # @Time : 2020/6/25 22:41 # @Author : Yongfei Liu # @Email : liuyf3@shanghaitech.edu.cn import numpy as np import os.path as osp import os import pickle from collections import OrderedDict import torch import json from detectron2.data.datasets.builtin_meta import CO...
4,373
1,606
# -*- coding: utf-8 -*- """ Attributes: config (dict): Description logger (logging.Logger): Description """ import logging import pymongo logger = None config = {} class MongoMap(object): """Info about MongoDB Attributes: ca (None, optional): ssl-ca cert (None, optional): ssl-cert ...
4,909
1,582
# input N, M = map(int, input().split()) As = [*map(int, input().split())] Bs = [*map(int, input().split())] # compute # output print(sum(A > B for B in Bs for A in As))
172
72
#!/usr/bin/python a, b = [int(i) for i in input().split()] c = a * b if c % 2 == 0: print('[:=[first]') else: print('[second]=:]')
141
65
import os from shutil import which from .pipeline_config import load_config __all__ = ["load_config"] def export_env(outdir="."): if which("conda") is not None: os.system((f"conda env export > {os.path.join(outdir, 'conda_env.yml')}")) elif which("pip") is not None: os.system(f"python -m pip ...
374
130
import os import sys import stakkr.stakkr_compose as sc import subprocess import unittest base_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, base_dir + '/../') # https://docs.python.org/3/library/unittest.html#assert-methods class StakkrComposeTest(unittest.TestCase): services = { '...
2,337
796
import os,sys BASE_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(BASE_DIR) import datetime import time from backtesting.backtest import Backtest from backtesting.data import HistoricCSVDataHandler from backtesting.execution import SimulatedExecutionHandler from backtesting.portfolio import Portfolio...
2,792
832
import matplotlib.pylab as plt import numpy as np import pandas as pd from COMMONTOOL import PTCureve DB = pd.read_csv('0_228.txt') # DB = pd.read_csv('../3차 검증/322.txt') # target_time = 100 # for i in range(0, len(DB)): # if DB['KCNTOMS'].loc[i] != target_time: # DB.drop([i], inplace=True) # else: #...
3,306
1,647
# -*- coding: utf-8 -*- """ Transparent PNG conversion ~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from PIL import Image def get_new_size(original_size): """ Returns each width and height plus 2px. :param original_size: Original image's size :return: Width / height after calculation :rtype: tuple """ ...
658
217
from django.core.management.commands import makemessages class Command(makemessages.Command): def build_potfiles(self): potfiles = super().build_potfiles() for potfile in sorted(set(potfiles)): self._remove_pot_creation_date(potfile) return potfiles @staticmethod def...
678
200
"""Views for users""" from flask_restful import Resource from flask import jsonify, request from app.api.v2.users.models import UserModel from app.api.v2.decorator import token_required, get_token from app.api.v2.send_email import send class UserStatus(Resource): """Class with method for updating a specific user...
6,529
1,703
# -*- coding: utf-8 -*- import sys import os import traceback import ujson from pprint import pprint from textblob import TextBlob as tb from textblob import Word as wd import shutil from collections import defaultdict from gensim.corpora import Dictionary from socialconfig import config class get_reviews_iterable(ob...
7,357
3,439
from pages.demo_page import DemoPage class TestDemo: def test_open_page(self, browser): """ :param browser: :return: """ obj = DemoPage(browser) obj.open_page() def test_verify_page_title(self, browser): """ :param browser: :return: ...
434
133
from helpers.cyclic_list import CyclicList from helpers.coordinates2d import Coordinates2D RUN_TEST = False TEST_SOLUTION = 7 TEST_INPUT_FILE = 'test_input_day_03.txt' INPUT_FILE = 'input_day_03.txt' START = Coordinates2D((0, 0)) # top left corner TRAJECTORY = Coordinates2D((3, 1)) # right 3, down 1 ARGS = [START...
1,126
414
############################################### # LeetCode Problem Number : 112 # Difficulty Level : Easy # URL : https://leetcode.com/problems/path-sum/ ############################################### from binary_search_tree.tree_node import TreeNode class BinaryTree: def hasPathSum(self, root: TreeNode, sum: in...
807
226
st1 = input() st2 = input() st3 = input() listy = [st1, st2, st3] listy.sort() print(listy[0]) print(listy[1]) print(listy[2])
127
63
# Copyright 2017 IBM Corp. # # 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, sof...
3,900
1,242
import sys, os, errno, shutil, signal, subprocess from glob import glob class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printTitle(): print bcolors.WARNING print " _ _...
5,888
2,375
import logging from typing import Callable, Dict import torch import torch.nn as nn from torch.utils.data import DataLoader # the accelerator library is a requirement for the Trainer # but it is optional for grousnd base user of kornia. try: from accelerate import Accelerator except ImportError: Accelerator =...
5,479
1,579
# python3.7 """Implements JPEG compression on images.""" import cv2 import numpy as np try: import nvidia.dali.fn as fn import nvidia.dali.types as types except ImportError: fn = None from utils.formatting_utils import format_range from .base_transformation import BaseTransformation __all__ = ['JpegComp...
2,795
833
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 00:31:35 2021 @author: RayaBit """ from flask import Flask, render_template, Response from imutils.video import VideoStream from skeletonDetector import skeleton import cv2 from skeleton3DDetector import Skeleton3dDetector from visualization import Visualizer import t...
2,046
762
"""Define the :class:`Thread`.""" import threading from schedsi.cpu import request as cpurequest from schedsi.cpu.time import Time #: Whether to log individual times, or only the sum LOG_INDIVIDUAL = True class _ThreadStats: # pylint: disable=too-few-public-methods """Thread statistics.""" def __init__(s...
8,144
2,213
def fill_team_about(db): ############################### # FILL TEAM ABOUT TABLE # ############################### print('Inserting data into team member profiles table') add_about_team_query = ("INSERT INTO team_about " "(name, link, position, image, description,...
5,552
2,049
import copy from pyBRML import utils from pyBRML import Array def multiply_potentials(list_of_potentials): """ Returns the product of each potential in list_of_potentials, useful for calculating joint probabilities. For example, if the joint probability of a system is defined as p(A,B,C) = p(...
1,335
374
import re class KnownUncategories(object): """ List of known entries in test_data which are no categories, but are recognized as such """ def __init__(self): # un-category regex strings (care for commas) self.uc = [ "Beteiligung", # 1956: is part of B...
2,098
607
from django import template register = template.Library() def mostrar_resumen_mapa(context, m, order_by): # print context to_return = { 'mapa': m, 'order_by': order_by, } return to_return @register.inclusion_tag('mapas/lista_mapas.html') def mostrar_mapas(lista_mapas, order_by): to_return = { ...
1,640
574
import pandas as pd from pydash.objects import get class Aggregator(object): def __init__(self, field, lens=None, sublens='_id', include=[], opts={}): self._field = field self._lens = lens self._sublens = sublens self._result = [] self._transf = [] self._include = ...
1,868
573
from email.parser import BytesParser, Parser from email.policy import default, HTTP def FuzzerRunOne(FuzzerInput): try: Parser(policy=HTTP).parsestr(FuzzerInput.decode("utf-8", "replace")) # #Parser(policy=default).parsestr(FuzzerInput.decode("utf-8", "replace")) except: pass
310
104
from flask import Flask from flask_sqlalchemy import SQLAlchemy import pytest @pytest.fixture def app(): return Flask(__name__) @pytest.fixture def db(app): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False return SQLAlchemy(app)
315
119
def selection_sort(A): n = len(A) for i in range(n - 1): position = i for j in range(i + 1, n): if A[j] < A[position]: position = j temp = A[i] A[i] = A[position] A[position] = temp A = [3, 5, 8, 9, 6, 2] print('Original Array: ', A) selectio...
357
141
from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone from django.utils.text import slugify class Author(models.Model): name = models.CharField(max_length=50, unique=False) slug = models.SlugField(max_length=200, blank=True, unique=False) def ...
3,465
1,125
# load defaults and override with devlopment settings from defaults import * DEBUG = True WSGI_APPLICATION = 'bucketlist_django.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bucketlist', 'USER': 'bucketlist', 'PASSWORD': ...
341
112
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # 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...
1,198
349
import os import os.path import pickle from shutil import copyfile import numpy as np import pandas as pd import xgboost as xgb from sklearn.decomposition import KernelPCA from sklearn.decomposition import PCA from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import GradientBoostingClassifier from ...
13,019
3,770
from flask import Blueprint from flask import abort from flask import render_template from flask import request from flask import current_app from sqlalchemy import desc from gleague.core import db from gleague.models import Match from gleague.models import Season from gleague.models import SeasonStats from gleague.mo...
2,495
811
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : 822.py @Contact : huanghoward@foxmail.com @Modify Time : 2022/3/29 13:19 ------------ """ from typing import List class Solution: def flipgame(self, fronts: List[int], backs: List[int]) -> int: ans = float('+inf') fo...
941
290
#! /usr/bin/python3 # -*- coding: utf-8 -*- import pickle import pandas as pd import xml.etree.ElementTree as ET import math import seaborn as sns import matplotlib.pyplot as plt import numpy as np import csv import glob import scikit_posthocs as sp from scipy import stats import os from scipy import stats import scik...
22,795
8,419
import unittest from podb import DB from tqdm import tqdm from . import HugeDBItem db = DB("huge") class HugeDBTest(unittest.TestCase): def test_huge_insert(self): for _ in tqdm(range(1000000)): db.insert(HugeDBItem.random()) if __name__ == '__main__': unittest.main()
302
116
from .models import sts_backend from ..core.models import base_decorator sts_backends = {"global": sts_backend} mock_sts = base_decorator(sts_backends)
153
54
# Database switched from having nsrId to using orgnr, this script helps with this conversion. import os import re import json import subprocess from glob import glob from utility_to_osm import file_util if __name__ == '__main__': data_dir = 'data' #'barnehagefakta_osm_data/data' nsrId_to_orgnr_filename = 'nsr...
3,005
885
from django.test import TestCase from regcore.layer import standardize_params class LayerParamsTests(TestCase): def test_old_format(self): lp = standardize_params('label', 'version') self.assertEqual(lp.doc_type, 'cfr') self.assertEqual(lp.doc_id, 'version/label') self.assertEqual...
769
262
while True: try: i = int(input("Sayı giriniz: ")) # 2 except ValueError: print("Hata Kodu: 5786, \nAçıklama: Lütfen bir \"tam sayı\" giriniz.") else: for s in range(2, i, 1): if i%s == 0: print(f"{i} sayısı, asal değildir.") break else: if s == i - 1: print(f"{i} sayısı, as...
459
272
"""Main entrypoint for this application""" from pathlib import Path from math import degrees from datetime import datetime import logging import warnings from environs import Env from streamz import Stream from paho.mqtt.client import Client as MQTT from pycluon import OD4Session, Envelope as cEnvelope from pycluo...
5,859
2,130
from typing import Any, Optional from dataclasses import dataclass, field import aiohttp from ..types import aliases from ..types import exceptions @dataclass class BaseMethod: # config base_url: aliases.Url | None = field(init=False, default=None) default_http_method: aliases.RequestMethod | None = fie...
7,569
2,392
#!/usr/bin/python3 import re import json import random from pathlib import Path from datetime import date from typing import Any, Callable, Set, Tuple import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from tags import Filter, Box, CompilationError, escape, enum_subject_parser_factory, tagset,...
28,594
10,616
import numpy as np from serial.serialutil import SerialException import serial.tools.list_ports as port_list import serial import time def Hex_To_Dec(input): # input of form "40048024" return int(input, 16) def Hex_To_Bin(input): # input of form "40048024" return bin(int(input, 16)) def Hex_To_Bytes(input):...
10,218
3,579
from geosolver.ontology.ontology_definitions import FunctionSignature, signatures from geosolver.text.rule import TagRule from geosolver.utils.num import is_number __author__ = 'minjoon'
190
63
from __future__ import annotations from itertools import tee from typing import Iterable, Optional, Sequence, Union import pandas as pd from tiro_fhir import Resource from fhir_dataframes import code_accessor class LocalFHIRStore: def __init__(self, resources: Iterable[Resource] = []): self._resources: It...
1,433
425
# -*- coding: utf-8 -*- import json import logging from .request import RequestApi from .exceptions import ApiError, WrongId, HttpError logger = logging.getLogger(__name__) class Senler: def __init__(self, secret, vk_group_id=None): self.vk_group = vk_group_id self.__secret = str(secret).strip() self._rq = Re...
1,189
451
import pyotp import robin_stocks as r import pandas as pd import numpy as np import ta as ta from pandas.plotting import register_matplotlib_converters from ta import * from misc import * from tradingstats import * from config import * #Log in to Robinhood #Put your username and password in a config.py file in the sam...
11,354
3,552
import io import os import shutil from base64 import urlsafe_b64decode from bson import ObjectId from slivka.db.documents import UploadedFile, JobRequest class FileProxy: _file: io.IOBase = None closed = property(lambda self: self._file is None or self.file.closed) fileno = property(lambda self: self.f...
3,401
1,031
import typing as t from fastapi import Request, Response from pyinstrument import Profiler from starlette.concurrency import run_in_threadpool from debug_toolbar.panels import Panel from debug_toolbar.types import Stats from debug_toolbar.utils import is_coroutine, matched_endpoint class ProfilingPanel(Panel): ...
1,160
331
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
3,003
923
import imp import sys from sqlalchemy.exc import ProgrammingError from featurehub.user.session import Session from featurehub.admin.admin import Commands try: for _problem in Commands().get_problems(): # Create a session for each problem and make it importable _commands = Session(_problem) ...
660
173
from dataclasses import dataclass from functools import reduce from typing import Callable, Iterable, Iterator ''' The first phase of a compiler is called `lexical analysis` implemented by a `scanner` or `lexer`. It breaks a program into a sequence `lexemes`: meaningful substrings of the input. It also transforms...
12,107
3,890
from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def dashboard(req): return render(req, "dashboard.html")
179
58
import tool_utils as tu import PyQt4.QtGui as qtg import PyQt4.QtCore as qtc from PyQt4.QtGui import * from PyQt4.QtCore import * import smach import rospy from msg import Trigger TRIGGER_TOPIC = 'trigger' class TriggerTool(tu.ToolBase): def __init__(self, rcommander): tu.ToolBase.__init__(self, rcomman...
2,830
948
from contextlib import contextmanager from idact import ClusterConfig from idact.detail.nodes.node_impl import NodeImpl from idact.detail.tunnel.tunnel_internal import TunnelInternal class FakeTunnel(TunnelInternal): """Does nothing besides holding the remote port. Local port is ignored. :param ...
1,488
444
from datetime import date from typing import Optional, Union from pydantic import BaseModel, Field, validator from . import educators as educators_models from . import schools as schools_models from app.airtable.response import AirtableResponse from app.airtable.validators import get_first_or_default_none class Cr...
3,226
987
# Copyright 2021, Guillermo Adrián Molina # # 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 ...
4,003
1,034
#!/usr/bin/python3 import playback import display import navigation import device import pygame done = False music = playback.music() view = display.view() menu = navigation.menu() PiPod = device.PiPod() menu.loadMetadata() status = PiPod.getStatus() songMetadata = music.getStatus() displayUpdate = pygame.USEREVENT ...
3,736
943
import socket import telnetlib from collections import OrderedDict from cloudshell.cli.session.connection_params import ConnectionParams from cloudshell.cli.session.expect_session import ExpectSession from cloudshell.cli.session.session_exceptions import ( SessionException, SessionReadEmptyData, SessionRea...
3,250
904
""" Cross-object data auditing Schema validation allows for checking values within a single object. We also need to perform higher order checking between linked objects. """ from past.builtins import basestring import logging import venusian logger = logging.getLogger(__name__) def includeme(config): config.re...
5,698
1,598
''' Created on 14.10.2019 @author: JM ''' from PyTrinamic.ic.TMC2130.TMC2130_register import TMC2130_register from PyTrinamic.ic.TMC2130.TMC2130_register_variant import TMC2130_register_variant from PyTrinamic.ic.TMC2130.TMC2130_fields import TMC2130_fields from PyTrinamic.helpers import TMC_helpers class TMC2130():...
1,694
589
from setuptools import setup, find_packages # Get version from tncontract/version.py exec(open("tncontract/version.py").read()) setup( name = "tncontract", version = __version__, packages = find_packages(), author = "Andrew Darmawan", license = "MIT", install_requires = ["numpy", "scipy"], )
319
105
#exampleb generates a full tweet #examplet only calls get_string() def get_string(): '''generate full tweet text''' return 'example #text'
150
46
for x in range(1,100,2): print(x)
37
20
# -*- coding: utf-8 -*- from datetime import timedelta from delorean import Delorean from sqlalchemy import and_ from twisted.internet import defer from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.internet.task import LoopingCall from twisted.python import log from ...
3,213
961
""" Shablbot manager commands """ import sys def main(): try: from shablbot.core.manager_commands import manager_command except ImportError as exc: raise ImportError( "Couldn't import Shablbot. Are you sure it's installed and activate venv?" ) from exc manager_command(...
370
113
#Print Custom Row-Column Patterns.. #e.g. '''@ @ @ @ # @ @ @ @ # @ @ @ @''' w = print("What do you want to print?") wa = str(input("Answer : ")) try: m1 = print("How many rows do you want to print?") n1 = int(input("Answer : ")) m2 = print("How many columns do you want to print?...
726
261
"""cluegame.py -- Classes to track Clue game events and make inferences The board game Clue is also known as Cluedo. This module contains classes that make it possible to record specific knowledge-generating events that a Clue player may observe during the course of a game (such as, for example, that Player A showed ...
17,116
4,791
"""Flask configuration.""" from os import environ, path basedir = path.abspath(path.dirname(__file__)) class Config: """Base config.""" SECRET_KEY = "qsZ5srBF9-j3tgdMsd11hdbg2VLUyKQYqWFQ1EZyKI6PDVVTLXduxWoM1N0wESR0zFvSPFDs9ogpMjgl9wFxXw" STATIC_FOLDER = 'static' TEMPLATES_FOLDER = 'templates'...
726
326
from nomad_alt import Nomad import json import uuid from pprint import pformat import os import pytest import nomad_alt.exceptions import tests.common as common @pytest.fixture def nomad_setup(): n = Nomad(host=common.IP, port=common.NOMAD_PORT, ssl_verify=False, token=common.NOMAD_TOKEN) with open(common.EX...
691
251
from django.shortcuts import render from django.http import HttpResponse import logging import json import base64 import time # Create your views here. logger = logging.getLogger(__name__) # 文件上传:form-data/Multipart方式 POST方法 def index(request): sendfile = request.FILES.items() haveFiles = False for key,...
5,979
2,083
# Log Parser for RTI Connext. # # Copyright 2016 Real-Time Innovations, 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 # # ...
2,191
678
from bson.objectid import ObjectId from torrents.file import TorrentFile class TestTorrentFile: def test_get_output_file(self): id1 = ObjectId() file1 = TorrentFile(id1) assert file1.get_output_file() == 'torrent_files/' + str(id1) + '.torrent'
276
96
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # 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 ...
2,444
895
# Generated by Django 2.2.12 on 2020-05-22 19:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.AddField( model_name='product', name='baby_product', ...
711
229
import argparse import logging from vietocr.model.trainer import Trainer from vietocr.tool.config import Cfg import sys sys.path.insert(0, './') from char import character logging.basicConfig(level=logging.INFO, ) def main(): parser = argparse.ArgumentParser() parser.add_argument('config', help='see example at ...
939
301
# Generated by Django 2.2.10 on 2020-02-27 18:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('django_eveonline_connector', '0017_primaryevecharacterassociation'), ] operations = [ migrations.RemoveField( model_name='evetoken', ...
363
124
import torch.nn as nn """ https://zhuanlan.zhihu.com/p/76378871 arxiv: 1804.03821 ExFuse """ class SematicEmbbedBlock(nn.Module): def __init__(self, high_in_plane, low_in_plane, out_plane): super(SematicEmbbedBlock, self).__init__() self.conv3x3 = nn.Conv2d(high_in_plane, out_plane, 3, 1, 1) ...
598
273
from datetime import date, datetime from base64 import b64encode from string import ascii_letters as letters, digits from sys import argv from os import environ as env from os.path import join, dirname, expanduser from itertools import product import json import logging import re _LOGGER = logging.getLogger(__name__) ...
1,539
568
from IPython import get_ipython from ._version import get_versions __version__ = get_versions()['version'] del get_versions def import_star(module, ns): def public(name): return not name.startswith('_') ns.update({name: getattr(module, name) for name in dir(module) if public(name)}) d...
9,874
2,904
import numpy as np from typing import List from copy import deepcopy from utils.customer import Customer class Depot: """ Depot class represents a list of nodes assigned to this depot which we call a route. This class is going to be filled by `Customers` class. """ def __init__(self, id, x, y, c...
6,260
1,761
"""create fake data to the db file""" from config import data_nodes, get_db from type import DataNodeStatus, DataNode from datetime import timedelta from config import get_second_datetime def create_fake_data_status(data_node: DataNode): now = get_second_datetime() db = get_db() for i in range(100): ...
714
248
#!/usr/bin/env python # coding: utf-8 # In[ ]: gkey="Enter Your Key Here"
78
35
from category_tree.categories import data def get_store_name_from_child(store_id): while data[store_id]['parent_category'] is not None: store_id = data[store_id]['parent_category'] return store_id
215
67
''' Module to pull keys from test geckoboard widgets. ''' import os import json def get_keys(): settings_folder = os.path.dirname(__file__) settings_file = os.path.join(settings_folder,'gecko_settings.json') with open(settings_file, 'r') as file: json_data = json.load(file) return json_dat...
371
124
from __future__ import annotations from typing import Any, Dict, List, Union import logging from pajbot.web.utils import get_cached_enabled_modules log = logging.getLogger(__name__) class MenuItem: def __init__( self, href: Union[str, List[MenuItem]], menu_id: str, caption: str...
2,596
733
""" @no 463 @name Island Perimeter """ class Solution: def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ ans = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: ...
611
235