content
stringlengths
0
894k
type
stringclasses
2 values
from setuptools import setup from distutils.util import convert_path from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() main_ns = {} ver_path = convert_path('betacal/version.py') with open(...
python
# Accept three subject marks and display % marks. m1 = float(input("Enter marks 1.: ")) m2 = float(input("Enter marks 2: ")) m3 = float(input("Enter marks 3: ")) percent = (m1+m2+m3)/3 print("% marks", percent)
python
class ReturnValue(object): """\brief Container for a return value for a daemon task or command. If the the code is set to 0 the operation succeeded and the return value is available. Any other code indicates an error. [NOTE: we need to define other values, ala HTTP] """...
python
# This example shows how to train a built in DQN model to play CartPole-v0. # Example usage: # python -m example.cartpole.train_dqn # --- built in --- import time import json # --- 3rd party --- import gym import tensorflow as tf # run on cpu tf.config.set_visible_devices([], 'GPU') # --- my module --- import unst...
python
# # General Electricity sector Decarbonization Model (GEDM) # Copyright (C) 2020 Cheng-Ta Chu. # Licensed under the MIT License (see LICENSE file). # # Module note: # Functions to initialize instance settings # #---------------------------------------------------- # sets #---------------------------------------------...
python
from email import header from multimethod import distance import scipy from scipy.signal import find_peaks as scipy_find from core.preprocessing import read_data from scipy.signal._peak_finding_utils import _local_maxima_1d from scipy.signal._peak_finding import _arg_x_as_expected from utils.visualize import see_spec...
python
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> import unittest import units.pressure.pascals class TestPascalsMethods(unittest.TestCase): def test_convert_known_pascals_to_atmospheres(self): self.asser...
python
from binaryninja import * from pathlib import Path import hashlib import os import subprocess class Decompiler(BackgroundTaskThread): def __init__(self,file_name,current_path): self.progress_banner = f"[Ghinja] Running the decompiler job ... Ghinja decompiler output not available until finished." B...
python
# coding: utf8 from __future__ import unicode_literals from ..norm_exceptions import BASE_NORMS from ...attrs import NORM from ...attrs import LIKE_NUM from ...util import add_lookups _stem_suffixes = [ ["ो","े","ू","ु","ी","ि","ा"], ["कर","ाओ","िए","ाई","ाए","ने","नी","ना","ते","ीं","ती","ता","ाँ",...
python
from rpasdt.common.enums import StringChoiceEnum class NodeAttributeEnum(StringChoiceEnum): """Available node attributes.""" COLOR = "COLOR" SIZE = "SIZE" EXTRA_LABEL = "EXTRA_LABEL" LABEL = "LABEL" SOURCE = "SOURCE" class DistanceMeasureOptionEnum(StringChoiceEnum): pass NETWORK_OPTI...
python
"""ProtocolEngine tests module."""
python
# -*- coding: utf-8 -*- import logging import requests from bs4 import BeautifulSoup logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('wb') class Client: def __init__(self): self.session = requests.Session() self.session.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Wi...
python
import json import os from pathlib import Path from time import sleep from tqdm import tqdm from ..graph.models import Concept, Work from ..utils import get_logger from . import get_concepts_es_client from .format import ( format_concept_for_elasticsearch, format_story_for_elasticsearch, format_work_for_e...
python
# ex_sin.py # author: C.F.Kwok # date: 2018-1-5 from simp_py import tft from math import sin, radians import time class SIN: global tft def __init__(self): self.init_plot() tft.tft.clear() def run(self): global sin, radians ang=0 for x in range(320): ...
python
from django import forms class ModelMultiValueWidget(forms.MultiWidget): def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') self.labels = kwargs.pop('labels', [None]) self.field_names = kwargs.pop('field_names', [None]) super(ModelMultiValueWidget, self).__init__...
python
import atexit import subprocess from multimedia.constants import AUDIO_OUTPUT_ANALOG, KEY_DOWN_ARROW, KEY_LEFT_ARROW, KEY_RIGHT_ARROW, KEY_UP_ARROW from multimedia.functions import exit_process_send_keystroke, popen_and_wait_for_exit, send_keytroke_to_process from multimedia.playerhandler import PlayerHandler class O...
python
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. version_info = (0, 5, 4) __version__ = ".".join(map(str, version_info))
python
''' Calculates the Frechet Inception Distance (FID) to evalulate GANs or other image generating functions. The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd distribution is given by a...
python
# Copyright (c) 2014 Scality # # 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, s...
python
from .convunet import unet from .dilatedunet import dilated_unet from .dilateddensenet import dilated_densenet, dilated_densenet2, dilated_densenet3
python
import mlflow.pyfunc class Model(mlflow.pyfunc.PythonModel): """ Abstract class representing an MLFlow model. Methods: fit predict validate register download Attrs: """ def __init__(): self.base_model = init_BaseModel() def fit(...
python
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor class TeleBruxellesIE(InfoExtractor): _VALID_URL = ( r"https?://(?:www\.)?(?:telebruxelles|bx1)\.be/(?:[^/]+/)*(?P<id>[^/#?]+)" ) _TESTS = [ { "url": "http://bx1.be/news/que-ri...
python
from setuptools import setup, find_packages import sys import os.path import numpy as np # Must be one line or PyPI will cut it off DESC = ("A colormap tool") LONG_DESC = open("README.rst").read() setup( name="viscm", version="0.9", description=DESC, long_description=LONG_DESC, author="Nathaniel...
python
# -*- coding: utf-8 -*- import llbc class pyllbcProperty(object): """ pyllbc property class encapsulation. property can read & write .cfg format file. file format: path.to.name = value # The comments path.to.anotherName = \#\#\# anotherValue \#\#\# # The comments too Property clas...
python
# -*- coding: utf-8 -*- """ @author: Fredrik Wahlberg <fredrik.wahlberg@it.uu.se> """ import numpy as np import random from sklearn.base import BaseEstimator, ClassifierMixin from scipy.optimize import fmin_l_bfgs_b from sklearn.gaussian_process.gpc import _BinaryGaussianProcessClassifierLaplace as BinaryGPC from skle...
python
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import Optional, List from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject from UM.Logger import Logger from UM.Preferences import Preferences from UM.Resources import Resources from UM.i18n i...
python
import numpy as np from utils import resize, opt from skimage import morphology def find_focal_points(image, scope='local', maxima_areas='large', local_maxima_threshold=None, num_points=None): """ Finds the 'focal_points' of a model, given a low resolution CAM. Has two modes: a 'local' scope and a 'global' on...
python
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may...
python
from core import views from django.urls import path urlpatterns = [ path('user/', views.UserListView.as_view()), path('user/<username>/', views.UserDetailView.as_view()), path('wallet/', views.WalletListView.as_view()), path('subacc/', views.SubAccountListView.as_view()), path('subacc/<sub_address...
python
from math import gcd from functools import reduce def fun(a): return reduce(gcd,a) for i in range(int(input())): n = int(input()) a = list(set([int(j) for j in input().split()])) if(len(a)==1): print(a[0]+a[0]) else: b = max(a) a.remove(b) m = b+fun(a) c = m...
python
OTHER_METAl_TYPE = { 'chromium':True, 'kanthal':False, 'solder':False, 'aluminium_steel':True, 'weak_aluminium_steel':False, 'bismuth_steel':True, 'weak_bismuth_steel':False, 'damascus_steel':True, 'weak_damascus_steel':False, 'stainless_steel':False, 'weak_stainless_steel':False, 'rose_alloy':F...
python
# coding:utf-8 from .util import * from .abstract_predictor import AbstractPredictor from .average_predictor import AveragePredictor from .average_predictor_without_outliers import AveragePredictorWithoutOutliers from .average_predictor_without_outliers2 import AveragePredictorWithoutOutliers2 from .average_predictor_...
python
import os import uuid class CommitTreeToScriptConverter: def __init__(self, skip_single_child_nodes, post_conversion_commands, script_file): self.skip_single_child_nodes = skip_single_child_nodes self.post_conversion_commands = post_conversion_commands self.print_debug = False self...
python
class Queue(object): def __init__(self): self.q = [] def push(self, value): self.q.insert(0, value) def pop(self): return self.q.pop() def is_empty(self): return self.q == [] def size(self): return len(self.q) # Example q = Queue() q.push(1...
python
import os from datetime import datetime, timedelta import pytz import requests from google.transit import gtfs_realtime_pb2 GTFS_API_KEY = os.environ.get('TRANSPORT_NSW_API_KEY') GTFS_REALTIME_URL = 'https://api.transport.nsw.gov.au/v1/gtfs/realtime/buses/' GTFS_VEHICLE_URL = 'https://api.transport.nsw.gov.au/v1/gtf...
python
# Generated by Django 3.0.6 on 2020-05-25 01:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sme_management', '0008_auto_20200525_0113'), ] operations = [ migrations.AlterField( model_name='smeproject', name='...
python
"""Build an online book using Jupyter Notebooks and Jekyll.""" from pathlib import Path import os # Load the version from the template Jupyter Book repository config path_file = Path(__file__) path_yml = path_file.parent.joinpath('book_template', '_config.yml') # Read in the version *without* pyyaml because we can't ...
python
# importing forms from django import forms from messenger.models import Message from newsletter.models import * class MessageForm(forms.ModelForm): OPTIONS = (('Y', 'Yes'), ('N', 'No'),) is_encrypted = forms.ChoiceField(required=True, choices=OPTIONS, help_text="Encrypt this message?") mess...
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-08-16 09:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('program_manage', '0001_initial'), ] operations = [ migrations.AlterField( ...
python
class Shark: animal_type = "fish" location = "ocean" followers = 5 def __init__(self, name, age): self.name = name self.age = age s1 = Shark("Frederick", 12) s2 = Shark("Nicholas", "10") print("\n>>> Shark 1 <<<") print("Name:", s1.name) print("Age:", s1.age) print("Type:", s1.ani...
python
import requests import os from core.client import TweepyClient, OpenaiClient BEARER_TOKEN = "" API_SECRET_KEY = "" CLIENT_SECRET = "" API_KEY = "" CLIENT_KEY = "" OPENAI_KEY = "" def bearer_oauth(r): # To set your environment variables in your terminal run the following line: # export 'BEARER_TOKEN'='<your_bea...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Category, Choice, BallotPaper class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class CategoryAdmin(admin.ModelAdmin): readonly_fields = ('ballot_paper', 'category_name', 'created...
python
import torch import torch.nn as nn import torch.nn.functional as F class CTLSTMCell(nn.Module): def __init__(self, hidden_dim, beta=1.0, device=None): super(CTLSTMCell, self).__init__() device = device or 'cpu' self.device = torch.device(device) self.hidden_dim = hidden_dim ...
python
"""tools.""" from collections import OrderedDict import yaml def ordered_yaml_load(filepath, loader=yaml.Loader, object_pairs_hook=OrderedDict): """ordered_yaml_load.""" class OrderedLoader(loader): """OrderedLoader.""" def construct_mapping(loader, node): """cons...
python
from .hankify_pw import hanky_pass # noqa
python
from django import template from ..forms.widgets import LikertSelect, RatingSelect register = template.Library() @register.filter def is_likert(field): return isinstance(field.field.widget, LikertSelect) @register.filter def is_rating(field): return isinstance(field.field.widget, RatingSelect)
python
picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0] ] for row in range(len(picture)): for col in range(len(picture[row])): if picture[row][col] == 1: print('*', end = '') else: print(' ', end = ''...
python
import socket from threading import Thread, Lock import sys def receiver(sock): while flag: data = sock.recv(1024) if data == 'quit': sys.exit(0) print "\t\t"+data host = '192.168.122.1' port = 50020 size = 1024 flag = True sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((host,port)) hop ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pass1objects.py # # Part of MARK II project. For informations about license, please # see file /LICENSE . # # author: Vladislav Mlejnecký # email: v.mlejnecky@seznam.cz from common import * class item(): def __init__(self, parrent, address): self.address...
python
from __future__ import unicode_literals SEQUENCE = [ 'bugzilla_url_charfield', 'repository_raw_file_url', 'repository_visible', 'repository_path_length_255', 'localsite', 'repository_access_control', 'group_site', 'repository_hosting_accounts', 'repository_extra_data_null', 'un...
python
_version='2022.0.1.dev8'
python
import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms from torchsummary import summary # Device configuration device = torch.device('cuda: 0' if torch.cuda.is_available() else 'cup') print(device, torch.__version__) # Hyper parameters num_epo...
python
from queue import PriorityQueue v = 14 graph = [[] for i in range(v)] def best_first_search(source, target, n): visited = [0] * n visited[0] = True pq = PriorityQueue() pq.put((0, source)) while pq.empty() == False: u = pq.get()[1] # Displaying the path having lowest ...
python
#!/usr/bin/python3 from demo_utils.learning import get_model import time import json from demo_utils.general import gamest from demo_utils.general import get_label from sklearn.model_selection import GridSearchCV # Aquí está lo necesario para realizar un expeimento def cross_validate(model, tunning_params, data_tra...
python
from application.models.models import BusinessModel, ExerciseModel, SurveyModel, InstrumentModel def query_exercise_by_id(exercise_id, session): return session.query(ExerciseModel).filter(ExerciseModel.exercise_id == exercise_id).first() def query_business_by_ru(ru_ref, session): return session.query(Busine...
python
from views import * from lookups import * import requests import re from utils import * import itertools from config import config if config.IMPORT_PYSAM_PRIMER3: import pysam import csv #hpo lookup import random from flask import Response, request import os from werkzeug.datastructures import Headers import re @a...
python
import os import io import json import random import uuid from collections import defaultdict, Counter from annoy import AnnoyIndex from tqdm import tqdm from itertools import product import wcag_contrast_ratio as contrast from PIL import Image, ImageDraw, ImageFont import numpy as np from scipy.stats import mode from ...
python
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import json from datetime import datetime from functools import partial from typing import Any from aiohttp import web from sqlalchemy import select from tglib.clients import APIServiceClient, MySQLClient from .models import TopologyHisto...
python
#!usr/bin/python # -*- coding:utf8 -*- class UserModel(object): users = { 1: {'name': 'zhang', 'age': 10}, 2: {'name': 'wang', 'age': 12}, 3: {'name': 'li', 'age': 20}, 4: {'name': 'zhao', 'age': 30}, } @classmethod def get(cls, user_id): return cls.users[user_...
python
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import numpy import pytest import vector._backends.numpy_ import vector._backends.object_ ...
python
import argparse from data.dataset import * from model.network import * from model.representation import * from training.train import * tf.random.set_random_seed(1950) random.seed(1950) np.random.seed(1950) def parse_model(name): ind_str = name.split("_")[1] ind = [int(i) for i in ind_str] return ind d...
python
from worms import * from worms.data import poselib from worms.vis import showme from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from concurrent.futures.process import BrokenProcessPool from time import perf_counter import sys import pyrosetta def main(): pyrosetta.init('-corrections:beta_no...
python
# -*- coding: utf-8 -*- """ requests-toolbelt ================= See http://toolbelt.rtfd.org/ for documentation :copyright: (c) 2014 by Ian Cordasco and Cory Benfield :license: Apache v2.0, see LICENSE for more details """ from .adapters import SSLAdapter, SourceAddressAdapter from .auth.guess import GuessAuth from ...
python
# -*- coding: utf-8 -*- __author__ = 'Marcin Usielski, Michal Ernst' __copyright__ = 'Copyright (C) 2018-2019, Nokia' __email__ = 'marcin.usielski@nokia.com, michal.ernst@nokia.com' import abc import six from moler.event import Event from moler.cmd import RegexHelper @six.add_metaclass(abc.ABCMeta) class TextualEve...
python
from __future__ import print_function import argparse from dataset import CarvanaDataset from net import CarvanaFvbNet import torch import torch.nn.functional as F from torch.utils.data import DataLoader import torch.optim as optim from torch.autograd import Variable parser = argparse.ArgumentParser(description='Carva...
python
# -*- coding: utf-8 -*- """This module implements regularized least square restoration methods adapted to 3D data. The two methods it gathers are * **Cosine Least Square (CLS) algorith**, * **Post-LS Cosine Least Square (Post_LS_CLS) algorithm**. """ import time import numpy as np import numpy.linalg as lin from ....
python
# !/usr/bin/env python # coding:utf-8 # Author:XuPengTao # Date: 2020/4/25 from ssd.config import cfg from ssd.modeling.detector import build_detection_model import os obtain_num_parameters = lambda model: sum([param.nelement() for param in model.parameters()]) def model_size(model):#暂时不能处理最后层量化情况 backbone=model.ba...
python
dic = { 1 : 4, 2 : 4.5, 3 : 5, 4 : 2, 5 : 1.5, } custos = 0 a = [int(x) for x in input().split()] custos += dic[a[0]] custos *= a[1] print("Total: R$ {:0.2f}".format(custos))
python
import discord from discord.ext import commands import os import aiohttp import json from random import choice class Pictures(commands.Cog): """ Category for getting random pictures from the internet. """ def __init__(self, client: commands.Bot) -> None: """ Class init method. """ self.client...
python
import emoji import tempfile from time import sleep from functools import wraps import random import string from typing import Callable import telegram import shutil from django.conf import settings from telegram.error import RetryAfter, NetworkError from telegram import Bot from app.conference.models import Slide from...
python
def bubble_sort(arr): for i in range(len(arr)): swap = False for j in range(len(arr)-1-i): if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] swap=True if swap==False: break return arr array=[8,5,2,4,3,2] print(bu...
python
from rest_framework import serializers from .UbicacionSerializer import UbicacionSerializer from .HorarioSerializer import HorarioSerializer from sucursal_crud_api.models import Sucursal, Ubicacion, Horario class SucursalSerializer(serializers.ModelSerializer): ubicacion = UbicacionSerializer() disponibilidad ...
python
# -*- coding: utf-8 -*- from app.HuobiAPI import HuobiAPI from app.authorization import api_key,api_secret from data.runBetData import RunBetData from app.dingding import Message from data.calcIndex import CalcIndex import time binan = HuobiAPI(api_key,api_secret) runbet = RunBetData() msg = Message() index = CalcInd...
python
# Copyright 2019-present NAVER Corp. # CC BY-NC-SA 3.0 # Available only for non-commercial use import pdb import torch import torch.nn as nn import torch.nn.functional as F from nets.sampler import FullSampler class CosimLoss (nn.Module): """ Try to make the repeatability repeatable from one image to the other....
python
import subprocess from os.path import join prefix = "../split/results/" targets = [ "mergepad_0701_2018/", "mergepad_0701_2019/", "mergepad_0701_2020/", "mergepad_0701_2021/", "mergepad_0701_2022/", "mergepad_0701_2023/", "mergepad_0701_2024/", "mergepad_0701_2025/", "mergepad_0701_2026/", "mergepad_0701_2027/", "merge...
python
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.8' _lr_method = 'LALR' _lr_signature = '1C5696F6C19A1A5B79951B30D8139054' _lr_action_items = {'OP_ADD':([11,],[18,]),'OP_SUB':([11,],[19,]),'LPAREN':([0,1,4,6,7,9,10,12,13,14,15,16,18,19,20,21,22,23,24,26,27,28,29,30,31,32,33,35...
python
# SCH1001.sh --> JB_PARTNER_DETAILS.py #************************************************************************************************************** # # Created by : Vinay Kumbakonam # Modified by : bibin # Version : 1.1 # # Description : # # 1. Reads the 'Partner Summary' worksheet from partner detail...
python
#!/usr/bin/env python2.7 from numpy import * from pylab import * from matplotlib import rc, rcParams trie = genfromtxt('../data/trie_search_found.output') tst = genfromtxt('../data/tst_search_found.output') radix = genfromtxt('../data/radix_search_found.output') _map = genfromtxt('../data/map_search_found.output') u...
python
""" ThirdParty's """ from .LSUV import LSUVinit # minor changes to avoid warnings del LSUV
python
__all__ = [ "configuration", "persistence", ]
python
import argparse import os import pickle as pk import torch with open('../data/corr_networks/yearly_dict.pk', 'rb') as handle: yearly_dict = pk.load(handle) def parameter_parser(): """ A method to parse up command line parameters. """ parser = argparse.ArgumentParser(description="Run SSSNET.") ...
python
# Given a non-empty array of non-negative integers nums, # the degree of this array is defined as the maximum frequency of any one of its elements. # Your task is to find the smallest possible length of a (contiguous) subarray of nums, # that has the same degree as nums. import pytest class Solution: def findSho...
python
# -*- coding: utf-8 -*- # Standard Library import re # Cog Dependencies from redbot.core import commands class GuildConverterAPI(commands.Converter): async def convert(self, ctx: commands.Context, argument: str): guild_raw = argument target_guild = None if guild_raw.isnumeric(): ...
python
# Generated by Django 3.1.3 on 2020-12-05 20:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('type', '0003_remove_product_product_type'), ] operations = [ migrations.RemoveField( model_name...
python
from datetime import datetime import pytz from commcare_cloud.alias import commcare_cloud from commcare_cloud.cli_utils import ask from commcare_cloud.colors import color_notice from commcare_cloud.commands.deploy.sentry import update_sentry_post_deploy from commcare_cloud.commands.deploy.utils import ( record_de...
python
import re import logging logger = logging.getLogger(__name__) def interpolate_text(template, values): if isinstance(template, str): # transforming template tags from # "{tag_name}" to "{0[tag_name]}" # as described here: # https://stackoverflow.com/questions/7934620/python-dots-in...
python
import os import codecs import logging import json from collections import namedtuple from django.utils.datastructures import MultiValueDict as MultiDict from django.conf import settings from django.utils.http import urlencode from django.core.urlresolvers import reverse import datetime from dateutil import parser f...
python
import math import matplotlib.pyplot as plt import matplotlib.colors as mplib_colors import tensorflow as tf import tensorflow.keras as keras import numpy as np import io from . import helpers as h # # HELPERS # INPUT_BANDS=[0] DESCRIPTION_HEAD=""" * batch_index: {} * image_index: {} """ DESCRIPTION_HIST="""{} ...
python
from __future__ import annotations import json import sys from datetime import datetime from typing import Any, List, Optional from meilisearch.client import Client from meilisearch.errors import MeiliSearchApiError from rich.console import Group from rich.panel import Panel from rich.traceback import install from ty...
python
import heapq import operator import os from bitstring import BitArray import json import pickle import codecs DIR_DATA = "media/" DIR_HUFFMAN = DIR_DATA #using to save dictionary temp_reverse = {} #init a seperate sympol as Node of Huffman Tree with value = frequency class Node: #build a class node with sympol, fr...
python
from flask import jsonify, g from app import db from app.api import bp from app.api.auth import auth_tp @bp.route('/tokens', methods=['DELETE']) @auth_tp.login_required def revoke_token(): g.current_user.revoke_token() db.session.commit() return '', 204
python
from . import discord from . import log # noqa def main(): """Run discurses.""" client = discord.DiscordClient() client.run() if __name__ == '__main__': discurses.main()
python
from . import models from . import routes from . import db_session from . import app
python
import pyPdf import time import urllib2 from django.conf import settings #save file locally def archive_file(original_url, gov_id, doc_type, file_type): type_dir = doc_type.lower().replace(' ', '_') file_name = "%s%s/%s.%s" % (settings.DATA_ROOT, type_dir, gov_id, file_type) try: remote_file = url...
python
# -*- coding: utf-8 -*- # @author: Optimus # @since 2018-12-15 class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ num_index_map = {} for index, num in enumerate(nums): if num in num_...
python
#!/usr/bin/env python3 # coding:utf-8 import os, shutil def fun(addr): items = os.listdir(addr) for each in items: if os.path.isfile(each): # 是文件,返回 True;是目录,返回 False item = os.path.splitext(each)[0] name = item.split("-")[0] # 文件名分割,获取 ...
python
"""TRAINING Created: May 04,2019 - Yuchong Gu Revised: May 07,2019 - Yuchong Gu """ import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import time import logging import warnings import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from ...
python
import pathlib import re import sys import setuptools from setuptools.command.test import test as TestCommand class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import tox ...
python
from django.db import models from django.utils.translation import ugettext_lazy as _ from .feedback import Feedback class SearchResultFeedback(Feedback): """ Database model representing feedback about search results (e.g. empty results). """ search_query = models.CharField(max_length=1000, verbose_n...
python
name = "wiki_archive"
python