content
stringlengths
0
894k
type
stringclasses
2 values
# coding:utf-8 import time from util.tools import * from util.city import * from search import Search from comment import Comments from exception import InvalidCityUrl from util.http import send_http from util.thread import CrawlThread from decorator.city import recover, \ has_id, has_city_list, map_required from d...
python
def item_already_equipped(lingo, item): if item == 'streak_freeze': return lingo.__dict__['user_data'].__dict__['tracking_properties']['num_item_streak_freeze'] if item == 'rupee_wager': return lingo.__dict__['user_data'].__dict__['tracking_properties']['has_item_rupee_wager'] def process_singl...
python
""" This modul contains benchmark script testing performance of modul cevast.certdb.cert_file_db Run as:> python3 -m cProfile -s calls cert_file_db.py {storage} {10000_certs.gz} {CPUs} > profiles/{commit}_cert_file_db_CPUs """ import sys import time import shutil import cevast.dataset.unifiers as unifier from cev...
python
print("Initializing...")
python
import mock import pytest from utils.objects import immutable from utils.objects import get_attr class ObjectsTestCase(object): @pytest.fixture def simple_object(self): return mock.Mock( first=mock.sentinel.FIRST, second=mock.Mock( first=mock.sentinel.SECOND, ...
python
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.18.0'...
python
#!/usr/bin/env python # Copyright (c) 2014, Tully Foote # 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, ...
python
import tempfile import webbrowser TEMPLATE_FILENAME = 'templates/color_sample.html' class Page: def __init__(self): self.baseHtml = self._get_base_html() @staticmethod def _get_base_html(): with open(TEMPLATE_FILENAME, 'r') as templateFile: return templateFile.read() def...
python
# # Embed a photo data inside a Tk frame # import tkinter as tk import smimgpng as smimg AUTHOR = "Alexandre Gomiero de Oliveira" REPO = "https://github.com/gomiero/bin2src" class App(tk.Frame): def __init__(self, master): super().__init__(master) self.config(width=427, height=640) canvas ...
python
# necessary packages import cv2 import imutils class AspectAwarePreprocessor: def __init__(self, width, height, inter=cv2.INTER_AREA): # store the target image width, height, and interpolation self.width = width self.height = height self.inter = inter def preprocess(self, imag...
python
# Databricks notebook source dbutils.widgets.text("infilefolder", "", "In - Folder Path") infilefolder = dbutils.widgets.get("infilefolder") dbutils.widgets.text("loadid", "", "Load Id") loadid = dbutils.widgets.get("loadid") # COMMAND ---------- import datetime # For testing # infilefolder = 'datalake/data/lnd/201...
python
import torch import torchvision.transforms as transforms import torchvision from tqdm import tqdm from torch.quantization import QuantStub, DeQuantStub import torch.nn as nn import torchvision.models as models transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5,...
python
""" Write a client program permutation.py that takes an integer k as a command-line argument; reads a sequence of strings from standard input, and prints exactly k of them, uniformly at random. Print each item from the sequence at most once. """ import sys from deque import RandomizedQueue if __name__ == "__main__"...
python
#!/usr/bin/env python # coding: utf-8 ############################################################################### # PARAMETERS # # change these values to change the protocol behavior # ############################################################################### # doesn't matter which units (uM or ug/mL) # as l...
python
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import ones, zeros p_st = util.get_output('immersed_bump.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) #p_dev = ...
python
"""Integration tests module. """ from revived.action import action from revived.action import ActionType from revived.reducer import combine_reducers from revived.reducer import Module # from revived.reducer import reducer from revived.store import ActionType as StoreAT from revived.store import Store # # Building rev...
python
from django.db import models from django.utils.translation import ugettext_lazy as _ class OrderStatusName(models.CharField): def __init__( self, verbose_name=_('Name'), max_length=255, *args, **kwargs): super(OrderStatusName, self).__init__( ...
python
from wsrpc.websocket.handler import WebSocketRoute, WebSocket, WebSocketThreaded
python
# # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # 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 notice, this # list o...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2014, 2015 Robert Simmons # # This file is part of PlagueScanner. # # PlagueScanner 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...
python
def load_assets(): assets = {} # background do jogo assets['background'] = pygame.image.load(r'img\spacebg.jpg').convert() assets['background']= pygame.transform.scale(assets['background'],(largura,altura)) # tela inicial assets['tela_init'] = pygame.image.load(r'img\screen_start1.png')....
python
import os from ...helpers import DIV PRELOADER = DIV( DIV( DIV( DIV( DIV(_class="phanterpwa_square"), _class="phanterpwa_square_container" ), _class='preloader-wrapper enabled' ), _class="phanterpwa-preloader-wrapper"), ...
python
# Copyright (C) 2015-2021 Swift Navigation Inc. # Contact: https://support.swiftnav.com # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIN...
python
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ if not s: return [] current = [] result = [] self.helper(s, current, result) return result def helper(self, s, cur, r...
python
import logging from nightshift import constants from typing import Dict, List, Tuple import matplotlib.cm from matplotlib.axes import Axes from matplotlib.colors import is_color_like AXIS_LABELS: Dict[str,str] = { 'H': r'$^{1}$H (ppm)', 'N': r'$^{15}$N (ppm)', 'C': r'$^{13}$C (ppm)', } Correlations = ...
python
# Generated by Django 3.0.7 on 2020-08-01 10:48 import django.core.validators from django.db import migrations from django.db import models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Social", fiel...
python
import math import numpy as np import viz def is_collinear(p1, p2, p3): return (p2[0] - p3[0]) * (p1[1] - p2[1]) == (p2[1] - p3[1]) * (p1[0] - p2[0]) def on_segment(p1, p2, p3): return (p1[0] < p3[0] < p2[0]) or (p1[0] > p3[0] > p2[0]) def orientation(p, q, r): return (q[1] - p[1]) * (r[0] - q[0]) -...
python
""" Texext package """ from . import math_dollar from . import mathcode from ._version import get_versions __version__ = get_versions()['version'] del get_versions def setup(app): math_dollar.setup(app) mathcode.setup(app)
python
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension( "qdr.ranker", sources=['qdr/ranker.pyx'], extra_compile_args=['-std=c++0x'], language="c++"), ] setup(name='qdr', version='0.0', de...
python
from django.shortcuts import render from twobuntu.routers import ReadOnlyError class ReadOnlyMiddleware(object): """ Catch ReadOnlyError exceptions and display the appropriate error page. """ def process_exception(self, request, exception): if isinstance(exception, ReadOnlyError): ...
python
import re from django import forms from .models import ( Filtro, ClasseFiltro, ItemFiltro ) class BaseModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for key in self.fields: field = self.fields[key] if type(fi...
python
import os import logging from .app import app from .weather_services import OpenWeatherMapAPI, FakeWeatherAPI DEBUG = os.environ.get("FLASK_ENV", "production") == "dev" logging.basicConfig( level=logging.DEBUG if DEBUG else logging.INFO, format="[%(levelname)-5s] <%(name)-10s> %(lineno)-4s - %(message)s'", )...
python
######################################################################### # File Name: test.py # Author: Walker # mail:qngskk@gmail.com # Created Time: Thu Dec 9 11:25:59 2021 ######################################################################### # !/usr/bin/env python3 import numpy as np import pandas as pd impor...
python
import bpy, os from math import * def MAT_texture_new(name,size, colorspc, q_alpha = True): tex = bpy.data.images.get(name) if tex is None: tex = bpy.data.images.new(name, width=size[0], height=size[1], alpha = q_alpha) tex.colorspace_settings.name = colorspc else: #change re...
python
from typing import TypedDict import re from xml.etree import ElementTree as ET ET.register_namespace("", "http://www.w3.org/2000/svg") class License(TypedDict): """License information for each icon.""" type: str url: str class Icon: """An icon with all relevant data and methods.""" def __init...
python
import argparse class BaseEngine(object): def __init__(self, opt) -> None: self.opt = opt @staticmethod def modify_commandline_options(parser: argparse.ArgumentParser, additional_args=None): return parser
python
from enum import Enum import pygame from pygame.locals import * import random from cell import Cell from pprint import pprint as pp from utils import _time class MouseBtnState(Enum): LEFT_BTN = 1 RIGHT_BTN = 3 NOTHING = 0 class GameOfLife: def __init__(self, width: int = 640, ...
python
from app import app from flask import flash, redirect, url_for, render_template, request from app.forms import URLForm, LoginForm from app.pulltext import pull_text @app.route("/", methods=['GET','POST']) @app.route("/index", methods=['GET','POST']) def index(): form = URLForm() if form.validate_on_submit(): ...
python
import mysql.connector class Database: mydb = mysql.connector.connect( host="localhost", user="root", passwd="Piku123.", database="datascience" ) mycursor = mydb.cursor() def __init__(self): pass def execute_query_with_params(self, query, params): ...
python
# Copyright (C) 2017, 2018 International Business Machines Corporation # All Rights Reserved import os import sys import json import streamsx.rest ################### parameters used in this script ############################ here = os.path.dirname(os.path.realpath(__file__)) vcapFilename = here + '/vcap.json' #...
python
import os relative_path = "../hierarchical_localization/Hierarchical-Localization/datasets/inloc/query/iphone7/" image_paths = [relative_path + f for f in os.listdir(relative_path) if f.endswith(".JPG")] with open("image_list_inloc.txt", 'w') as f: f.write("\n".join(map(str, image_paths)))
python
# Copyright 2016 Euclidean Technologies Management LLC 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 requi...
python
import DistConvGAN as model import lbann.contrib.launcher import lbann.contrib.args import argparse import os from lbann.core.util import get_parallel_strategy_args import lbann import lbann.modules as lm def list2str(l): return ' '.join([str(i) for i in l]) def construct_lc_launcher_args(): parser = argpars...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """django-sqlprint-middleware - pretty-print Django's SQL statments. """ import io from setuptools import setup version = '0.1.3' setup( name='django-sqlprint-middleware', version=version, packages=['django_sqlprint_middleware'], install_requires=[ ...
python
from dirutility import DirPaths from looptools.timer import Timer def test_case(case): test_cases = { 'projects': { 'rootpath': '/Volumes/Storage/HPA Design', 'exclude': [ '20080081_Rosenfeld_Realty', '20080082_Clarewood_Homes_WEB', '20080083_Dipersio_WE...
python
from graphviz import Digraph from nujo.autodiff._node import _Node from nujo.autodiff.tensor import Tensor class ComputationGraphPlotter: ''' Computation Graph Plotter Uses graphviz. ''' def __init__(self, **kwargs): self.computation_graph = Digraph(**kwargs) @staticmethod def ...
python
import math def cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0): """ This function is used to calculated Predicted Mean Vote(PMV) through environmental parameters cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0) ta: Air temp...
python
from pydantic import ValidationError from one_time_secret.app import schemas def test_good_argument(): validation_model = schemas.SecretKey( secret_key="984ae013e1304e54a5b2a1aec57fac36", ) expected = "984ae013e1304e54a5b2a1aec57fac36" assert validation_model.secret_key == expected def test...
python
input() l = list(map(int, input().split())) l_ = [str(i) for i in range(len(l))] again = True while again: again = False for i in range(len(l)-1): if l[i] > l[i+1]: l[i], l[i+1], l_[i], l_[i+1] = l[i+1], l[i], l_[i+1], l_[i] again = True print(" ".join(l_))
python
from boa.interop.Neo.App import RegisterAppCall CalculatorContract = RegisterAppCall(b'W\xa7\x18\x08MZh\xbdu\xb7%\x88\x8e\x19J\x9e\xd4|\xe1\xe3\xaa', 'operation', 'a', 'b') def Main(operation, a, b): result = CalculatorContract(operation, a, b) return result
python
import numpy as np import config class Trajectory: """ Trajectory class using trajectory generation with via points, with constant velocity segments and continous acceleration blends. For more info on this check out W.Khalils book Modeling, identification and control of robots Formulas and c...
python
import numpy as np np.random.seed(38) def generate_synth_part_circle_dataset(boundary, N_data=1000000, dataset_save_path_prefix_name='circle_random'): """ Generate 2 datasets on a circle of radius 1.0 (unit circle): [1] Training dataset: between boundary and 2*pi ...
python
import logging from submission_broker.submission.entity import Entity from submission_broker.submission.submission import Submission from submission_broker.validation.base import BaseValidator from submission_validator.services.ena_taxonomy import EnaTaxonomy class TaxonomyValidator(BaseValidator): def __init__...
python
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.rl.agents.agent import Agent class OptimizationAgent(Agent): """ A simple wrapper to allow optimizers to conform to the RL interface. Works only in conjunction with EpisodicExperiment. """ def __init__(self, module, learner): self.module...
python
import register while True: cadastro = [ register.registro() ] historico_paciente = register.historico() break salvar = register.cria_arquivo(cadastro, historico_paciente)
python
# Contributed by t0rm3nt0r (tormentor2000@mail.ru) to the Official L2J Datapack Project # Visit http://www.l2jdp.com/forum/ for more details. import sys from com.l2jserver.gameserver.model.quest import State from com.l2jserver.gameserver.model.quest import QuestState from com.l2jserver.gameserver.model.quest.jython imp...
python
import os import sys from scrapy.cmdline import execute from .settings import TEMPLATES_DIR def main(): argv = sys.argv if len(argv) > 1: cmdname = argv[1] if cmdname == 'genspider': argv += ['-s', f'TEMPLATES_DIR={TEMPLATES_DIR}'] execute(argv=argv) if __name__ == "__main_...
python
"""Check that static assets are available on consumerfinance.gov""" import argparse import logging import sys import time import requests from bs4 import BeautifulSoup as bs logger = logging.getLogger('static_asset_smoke_tests') logger.setLevel(logging.ERROR) shell_log = logging.StreamHandler() shell_log.setLevel(lo...
python
import numpy as np import os import pickle import torch from torch.utils.data import Dataset import bball_data.cfg as cfg from bball_data.utils import normalize DATAPATH = cfg.DATAPATH N_TRAIN = cfg.N_TRAIN N_TEST = cfg.N_TEST SEQ_LENGTH = cfg.SEQUENCE_LENGTH X_DIM = cfg.SEQUENCE_DIMENSION class BBallData(Dataset...
python
transitions = None events = None commands = None def reset_events(_): pass def actions(_): pass def state(_): pass initial_state = state
python
import pyb import data_logger kill_switch = data_logger.SoftSwitch() pyb.Switch().callback(lambda:kill_switch.press()) log = data_logger.logger_Rx(6, 1, 32, kill_switch, '/sd/data-set.bin', \ pyb.LED(4)) def main(): pyb.LED(3).on() log.begin() log.end(5000) pyb.LED(3).off...
python
#!/usr/bin/env python """ ipmongo Author: wal1ybot <https://github.com/wal1ybot/ipmongo> Please refer to readme for details. <https://github.com/wal1ybot/ipmongo/blob/master/README.md> Please refer to the following LICENSE file for licence information. <https://github.com/wal1ybot/ipmongo/blob/master/LICENSE> """...
python
import os import re # resolves name to an object has in the repo from util.ref_handling.ref_resolver import ref_resolver from util.repo_handling.repo_dir import repo_dir def object_resolve(repo, name): candidates = list() hashReg = re.compile(r"^[0-9A-Fa-f]{1.16}$") smallHashReg = re.compile(r"^[0-9A-Fa-f...
python
import unittest class JoystickTypeTest(unittest.TestCase): def todo_test_Joystick(self): # __doc__ (as of 2008-08-02) for pygame.joystick.Joystick: # pygame.joystick.Joystick(id): return Joystick # create a new Joystick object # # Create a new joystick to...
python
# from rest_framework.parsers import JSONParser # from rest_framework.decorators import api_view from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import status from .models import Dog from .models import Breed from .serializ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created on 9/18/19 by Pat Daburu """ .. currentmodule:: synolo_flask.apis .. moduleauthor:: Pat Daburu <pat@daburu.net> This package contains the API descriptions. """ from .api import api, API_ROOT
python
#PyBank Script import os import csv import numpy as np #Get the filename to open fileName = "budget_data_1.csv" #set paths for files bankBudget_csv = os.path.join("raw_data", fileName) #Variables to track budget totMonths = 0 totRev = 0 lmRev = 0 revChg = 0 revChgLst = [] #create a list to store the monthly rev ch...
python
import torch from allrank.data.dataset_loading import PADDED_Y_VALUE from allrank.models.losses import DEFAULT_EPS """Here are the NDCGLoss1 and NDCGLoss2(++) losses from The LambdaLoss Framework for Ranking Metric Optimization. Please note that we are sticking to array operations most of the time, only applying a pa...
python
import os.path import fipy as fp import matplotlib.pyplot as plt import numpy as np from .dicttable import DictTable class _BaseViewer(object): def plot(self, indices=[0], filename=None, times=None, cutoffvalue=-1, mirror=False, cutoff=True, labels=False, show=True, xlim=12e-6, ylim=-60e-6): self.mirror ...
python
# -*- coding: utf-8 -*- import datetime import difflib import time import re def allmusic_albumfind(data, artist, album): data = data.decode('utf-8') albums = [] albumlist = re.findall('class="album">\s*(.*?)\s*</li', data, re.S) for item in albumlist: albumdata = {} albumartist = re.s...
python
import json import random import copy activity_dict_file = open('/media/minhhieu/DATA/HOC/Thesis/reinforcement_bot/reinforcement_learning_bot/activity_dict.json',encoding='utf-8') activity_dict = json.load(activity_dict_file) activity_list = [activity for activity in list(activity_dict[0].keys()) if activity != 'othe...
python
# author: Bartlomiej "furas" Burek (https://blog.furas.pl) # date: 2022.03.30 # [python - How to export scraped data as readable json using Scrapy - Stack Overflow](https://stackoverflow.com/questions/71679403/how-to-export-scraped-data-as-readable-json-using-scrapy) import time import scrapy #import json from scrapy....
python
from django.core.exceptions import ObjectDoesNotExist from rest_framework import status from rest_framework.response import Response from crosswalk.authentication import AuthenticatedView from crosswalk.models import Domain, Entity class DeleteMatch(AuthenticatedView): def post(self, request, domain): ""...
python
# -*- coding: utf-8 -*- import sys sys.path.append('..') import ecopann.ann as ann import ecopann.coplot.plot_contours as plc import ecopann.cosmic_params as cosmic_params import simulator import matplotlib.pyplot as plt import numpy as np #%% observational data fid_params = [-1, 0.3] sim_mu = simulator.sim_SNe(fid...
python
from Chamaeleo.methods.default import AbstractCodingAlgorithm from Chamaeleo.utils.indexer import connect from Chamaeleo.methods import inherent ''' Typical values that we use are p = 8, q = 10, s = 46, so that p + q + s = 64 bits s bits of "salt" low q bits of index i p bits of previous bits ''' class HEDGES(Abst...
python
from projects.models.k8s import * from projects.models.project import *
python
import argparse import skorch import torch from sklearn.model_selection import GridSearchCV import data from model import RNNModel from net import Net parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model') parser.add_argument('--data', type=str, default='./data/penn', ...
python
import pytest from kopf.structs.references import EVERYTHING, Resource, Selector @pytest.fixture() def resource(): return Resource( group='group1', version='version1', preferred=True, plural='plural1', singular='singular1', kind='kind1', shortcuts=['shortcut1', 'shortcut2'], categ...
python
# Copyright (c) 2015. Mount Sinai School of Medicine # # 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 o...
python
"""Behave environment setup commands""" import os import shutil import stat import tempfile from pathlib import Path from features.steps.sh_run import run from features.steps.util import create_new_venv def before_scenario(context, scenario): # pylint: disable=unused-argument """Environment preparation before ...
python
import json class FileService: ''' Contains methods responsible with handling files. ''' def __init__(self, filepath): ''' Configure the filepath for use in methods. ''' self.filepath = filepath def read_appsettings(self): ''' Reads the a...
python
''' Tests the io functions of prysm. ''' from pathlib import Path import pytest from prysm.io import read_oceanoptics def test_read_oceanoptics_functions(): # file, has 2048 pixels p = Path(__file__).parent / 'io_files' / 'valid_sample_oceanoptics.txt' data = read_oceanoptics(p) # returns dict with...
python
from django.urls import path from django.shortcuts import render from . import views app_name = 'api' urlpatterns = [ path('network/online', views.network_online), path('node/<yagna_id>', views.node), path('website/globe_data', views.globe_data), path('website/index', views.golem_main_website_index), ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/9 15:45 # @Author : Hyperwd # @contact : 435904632@qq.com # @File : sign.py # @description : 华为云基于AK,SK的认证 # This version makes a GET request and passes the signature in the Authorization header. import datetime import hashl...
python
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\routing\portals\portal_cost.py # Compiled at: 2017-10-12 02:00:35 # Size of source mod 2**32: 1719 b...
python
import numpy as np from numpy.testing import assert_raises from pysplit import make_trajectorygroup def test_bogus_signature(): signature = './nothing_to_see_here*' assert_raises(LookupError, make_trajectorygroup, signature) def test_bogus_filenames(): filenames = ['./not_a_trajectory0', ...
python
#!/usr/bin/env python # coding: utf8 """Example of training spaCy's entity linker, starting off with a predefined knowledge base and corresponding vocab, and a blank English model. For more details, see the documentation: * Training: https://spacy.io/usage/training * Entity Linking: https://spacy.io/usage/linguistic-...
python
import text_plus_image import os ''' Test cases: image_size text_word_number 40 x 40 1 60 x 400 2 400 x 600 * 5 600 x 40 10 600 x 400 100 ''' image = ["40_40.jpg", "60_400.jpg", "400_600.jpg", "600_40.jpg", "600_400.jpg"] text = ['c...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/30 下午6:07 # @Author : Lee才晓 # @Site : www.rich-f.com # @File : dict_view.py # @Software: 富融钱通 # @Function: 字典模块逻辑操作 import io import time import xlrd import xlwt import logging from flask import Blueprint, render_template, request, json, make_res...
python
def BLEU_score(gt_caption, sample_caption): """ gt_caption: string, ground-truth caption sample_caption: string, your model's predicted caption Returns unigram BLEU score. """ reference = [x for x in gt_caption.split(' ') if ('<END>' not in x and '<START>' not in x and '<UNK>' ...
python
# -*- coding: utf-8 -*- ''' Created on 2020.05.19 @author: Jiahua Rao, Weiming Li, Hui Yang, Jiancong Xie ''' import os import json import yaml import pickle import logging import numpy as np import pandas as pd from tqdm import tqdm from pathlib import Path import torch import torch.nn as nn from rdkit import C...
python
import json import os import sys import click from rich import print_json from labfunctions import client, defaults from labfunctions.client.diskclient import DiskClient from labfunctions.conf import load_client from labfunctions.context import create_dummy_ctx from labfunctions.executors import jupyter_exec from lab...
python
from django.shortcuts import render from product.models import Product # Create your views here. def index(request): ''' Disp the home page ''' context = {'product': Product.objects.all().filter(on_sale=True)} context['loop_times'] = range(0, len(context['product'])) return render(request, 'captain/ind...
python
import pyotp from datetime import datetime import hashlib from random import randint from wallet.models import Transaction def getOTP(): sysotp = pyotp.TOTP('base32secret3232') sysotp = int(sysotp.now()) time = datetime.now() time = str(time) hash = hashlib.sha3_512(time.encode('utf-8')).hexdige...
python
import requests import time import math # insert api token api_token = "" # called in _get_user_data. Returns all pages that a user follows def _get_user_subscriptions(user_id): try: # The VK api returns 1000 results a time so we need to make multiple requests to collect all data amou...
python
from .http import Http import json class Friends: def getFriendList(id, page): try: res = Http.sendRequest("https://api.roblox.com/users/" + str(id) + "/friends?page=" + str(page)) res_decoded = res.decode("utf-8") res_loads = json.loa...
python
# Generated by Django 3.2 on 2021-09-04 13:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('deals', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='deal', name='deal_date', ), ]
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-05-21 14:31 from __future__ import unicode_literals from django.db import migrations, models import localflavor.us.models class Migration(migrations.Migration): dependencies = [ ('business', '0005_business_status'), ] operations = [ ...
python
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import json import os import warnings from unittest import mock import nose.tools as nt from IPython.core import display from IPython.core.getipython import get_ipython from IPython.utils.io import capture_output fr...
python
""" Copyright 2020-2021 Nocturn9x, alsoGAMER, CrisMystik 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 t...
python