content
stringlengths
0
894k
type
stringclasses
2 values
corruptionValues = { "Glimpse_of_Clarity_1": 15, "Crit_DMG_1": 10, "Crit_DMG_2": 15, "Crit_DMG_3": 20, "Flash_of_Insight_1": 20, "Lash_of_the_Void_1": 25, "Percent_Crit_1": 10, "Percent_Crit_2": 15, "Percent_Crit_3": 20, "Percent_Haste_1": 10, "Percent_Haste_2": 15, "Perc...
python
from enum import Enum, auto from fastapi import Request from fastapi.responses import JSONResponse class ErrCode(Enum): NO_ERROR = 0 EMAIL_DUPLICATED = auto() NO_ITEM = auto() ErrDict = { ErrCode.NO_ERROR: "정상", ErrCode.EMAIL_DUPLICATED: "동일한 이메일이 존재합니다.", ErrCode.NO_ITEM: "해당 항목이 존재하지 않습니다. "...
python
import numpy as np from sklearn.model_selection import TimeSeriesSplit from sklearn.utils import indexable from sklearn.utils.validation import _num_samples import backtrader as bt import backtrader.indicators as btind import datetime as dt import pandas as pd import pandas_datareader as web from pandas import Series, ...
python
import argparse parser = argparse.ArgumentParser(prog='build_snp_map_for_neale_lab_gwas.py', description=''' Build the SNP map table: phased genotype variant <=> Neale's lab GWAS ''') parser.add_argument('--genotype-pattern', help=''' In the form: prefix{chr}suffix. Will load 1..22 chromosomes (no X). ''') ...
python
def hello_world(): return "hi"
python
import filecmp import os import subprocess import unittest from clockwork import gvcf from cluster_vcf_records import vcf_record modules_dir = os.path.dirname(os.path.abspath(gvcf.__file__)) data_dir = os.path.join(modules_dir, "tests", "data", "gvcf") def lines_from_vcf_ignore_file_date(vcf): with open(vcf) as...
python
from torch.utils.data import dataloader from torchvision.models.inception import inception_v3 from inception_v4 import inceptionv4 import torch import torch.distributed as dist import argparse import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.d...
python
# Generated by Django 2.1.3 on 2018-11-02 08:18 from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('pages', '0007_language_code'), ] operations = [ migrations.AlterField( model...
python
from enum import Enum, unique @unique class BrowserType(Enum): """Class to define browser type, e.g. Chrome, Firefox, etc.""" CHROME = "Chrome" EDGE = "Edge" FIREFOX = "Firefox" INTERNET_EXPLORER = "Internet Explorer" OPERA = "Opera" SAFARI = "Safari"
python
# -*- coding: utf-8 -*- """End to end test of running a job. :copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest import os # TODO(e-carlin): Tests that need to b...
python
n = int(input()) suma = 0 dif = [] for i in range(n): a , b = map(int, input().split()) suma += b*(n-1) dif.append(a-b) dif = sorted(dif, reverse = True) for j in range(n): suma+= j*dif[j] print(suma)
python
"""Tools for converting model parameter from Caffe to Keras.""" import numpy as np import os import sys import shutil import h5py import collections import pickle def dump_weights(model_proto, model_weights, weight_output, shape_output=None, caffe_home='~/caffe'): """Helper function to dump caffe model weithts i...
python
import logging from typing import List from homeassistant.helpers.entity import Entity from gehomesdk.erd import ErdCode, ErdApplianceType from .base import ApplianceApi from ..entities import GeErdSensor, GeErdBinarySensor _LOGGER = logging.getLogger(__name__) class DryerApi(ApplianceApi): """API class for dr...
python
import re m = re.search(r'([a-zA-Z0-9])\1+', input().strip()) print(m.group(1) if m else -1)
python
import logging import sys, os import datetime import eons, esam import pandas as pd #Class name is what is used at cli, so we defy convention here in favor of ease-of-use. class in_excel(esam.DataFunctor): def __init__(self, name=eons.INVALID_NAME()): super().__init__(name) self.requiredKWArgs.app...
python
from django.test import Client, TestCase from django.urls import reverse from django.contrib.auth import get_user_model from posts.forms import PostForm from posts.models import Post User = get_user_model() class TaskCreateFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() ...
python
from abc import ABC, abstractmethod import asyncio from typing import Callable class AbstractConnectSignal(ABC): def __init__(self) -> None: self.targets = set() def connect(self, target: Callable): if target not in self.targets: self.targets.add(target) @abstractmethod ...
python
#pip install pdfplumber import pdfplumber pdf = pdfplumber.open('./Relação') paginas = len(pdf.pages) #quantidade de paginas text = "" for i in range(paginas): page = pdf.pages[i] text += page.extract_text() print(text)
python
import logging import json logger = logging.getLogger(__name__) def __virtual__(): ''' Only load if jenkins_common module exist. ''' if 'jenkins_common.call_groovy_script' not in __salt__: return ( False, 'The jenkins_smtp state module cannot be loaded: ' 'j...
python
from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserChangeForm, UserCreationForm CustomUser = get_user_model() # TODO: are we using this form now that we have django-allauth? class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields...
python
from fairseq.tasks import register_task from fairseq.tasks.translation import TranslationTask from fairseq import utils, search from glob import glob import os from morphodropout.binarize import SRC_SIDE, TGT_SIDE from morphodropout.dataset import build_combined_dataset from morphodropout.seq_gen import SequenceGener...
python
name = "pip_test_package"
python
#!/usr/bin/env python import os, os.path, sys import socket if __name__ == "__main__": PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',)) print "PROJECT_ROOT=", PROJECT_ROOT sys.path.append(PROJECT_ROOT) # Add virtualenv dirs to python path host = socket.gethostn...
python
import glob import os import re import requests from Bio.SeqIO import SeqRecord from Bio import SeqIO from .utils import is_fasta class PrimerDesigner: """Class for designing primers from FASTA files. It will send a FASTA alignment to `primers4clades`_ in order to design degenerate primers. Input data ...
python
#!/bin/env python3 import random import sys import os import time from collections import defaultdict from typing import Dict, Tuple, Union, Set import requests sys.path.append(os.path.dirname(os.path.abspath(__file__))) import expand_utilities as eu from expand_utilities import QGOrganizedKnowledgeGraph sys.path.app...
python
import pprint import cyok bit_file = 'foobar.bit' # load DLL cyok.load_library() # check version print('FrontPanel DLL built on: %s, %s' % cyok.get_version()) # connect to device dev = cyok.PyFrontPanel() print('Opening device connection.') dev.open_by_serial() print('Getting device information.') dev_info = dev...
python
import electrum from aiohttp import web from base import BaseDaemon class BTCDaemon(BaseDaemon): name = "BTC" electrum = electrum DEFAULT_PORT = 5000 daemon = BTCDaemon() app = web.Application() daemon.configure_app(app) daemon.start(app)
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def migrate_HeatSensor(apps, schema_editor): HeatSensor = apps.get_model('heatcontrol', 'HeatSensor') HeatControl = apps.get_model('heatcontrol', 'HeatControl') HeatControlProfile = apps.get_model('hea...
python
from __future__ import print_function from loguru import logger import io3d import io3d.datasets import sed3 import numpy as np import matplotlib.pyplot as plt logger.enable("io3d") logger.disable("io3d") import matplotlib.pyplot as plt from pathlib import Path import bodynavigation import exsu import sys import os ...
python
""" -*- test-case-name: PyHouse.Modules.Computer.Mqtt.test.test_computer -*- @name: PyHouse/src/Modules/Computer/Mqtt/mqtt_client.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2015-2016 by D. Brian Kimmel @license: MIT License @note: Created on Jun 5, 2015 @Sum...
python
import torch.nn as nn from ..builder import VQA_MODELS, build_backbone, build_encoder, build_head @VQA_MODELS.register_module() class VISDIALPRINCIPLES(nn.Module): def __init__(self, vocabulary_len, word_embedding_size, encoder, backbone, head): super().__init__() self.embedding_model = nn.Embe...
python
import numpy as np from mchap import mset from mchap.assemble import inheritence def test_gamete_probabilities__hom(): genotypes = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], np.int8) probabilities = np.array([1]) gametes_expect = np.array([[[0, 0, 0], [0, 0, 0]]], np.int8) probs_expec...
python
# Copyright 2019 New Relic, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
python
import altair as alt from data import get_nullity_matrix_data def nullity_matrix_chart( data, keep_original_col_order=True, show_tooltip=False, threshold=0.5, h=400 ): nm_data, n_rows = get_nullity_matrix_data(data) text_font_size = 10 base = alt.Chart(nm_data, height=h) chart = base.mark_rect(...
python
#!encoding=utf-8 from textblob import TextBlob import os, sys, re def textblob_process(line): blob = TextBlob(line) return blob.tags def process_tag_result(tag_res): nps = [] i = 0 while i < len(tag_res): while i < len(tag_res) and not tag_res[i][1].startswith('NN'): i += 1...
python
from ..crypto import Nonce from . import constants from io import BytesIO from datetime import datetime import binascii import struct import base58 import json FIELDS = { 'i64le': [8, '<q'], 'i64be': [8, '>q'], 'u64le': [8, '<Q'], 'u64be': [8, '>Q'], 'i32le': [4, '<i'], 'i32be': [4, '>i'], 'u32le': [4, '<I'], ...
python
#---------- #author:someone120 #---------- import pypinyin as py import lxml import sqlite3 as sql from urllib import request as url #导包结束 def run(): print(get(1).decode('gbk')) def get(num): """ num为页码 """ header={ 'User-Agent':'Mozilla/5.0 (Linux; Android 8.1.0; Redmi 5 Build/OPM1.171019....
python
# pylint: disable=not-callable # pylint: disable=no-member import torch import torch.nn as nn from torch.nn import functional as F class RecurrentDynamics(nn.Module): def __init__( self, hidden_size, state_size, action_size, node_size, embedding_size, act_f...
python
import vcr import zlib import json import six.moves.http_client as httplib from assertions import assert_is_json def _headers_are_case_insensitive(host, port): conn = httplib.HTTPConnection(host, port) conn.request("GET", "/cookies/set?k1=v1") r1 = conn.getresponse() cookie_data1 = r1.getheader("set-...
python
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.toon.NameTag from panda3d.core import TextNode from direct.fsm import ClassicFSM, State from lib.coginvasion.globals imp...
python
# Copyright 2016-2021 IBM Corp. 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 law or...
python
# --------------------------------------------------------------------- # Project "Track 3D-Objects Over Time" # Copyright (C) 2020, Dr. Antje Muntzinger / Dr. Andreas Haja. # # Purpose of this file : Parameter file for tracking # # You should have received a copy of the Udacity license together with this program. # # ...
python
#-*- encoding=utf-8 -*- #a example to demo multi threading python app for mq handling #ganben import Queue import threading import time import paho.mqtt.client as mqtt queueLock = threading.Lock() posiQueue = Queue.Queue(100) callQueue = Queue.Queue(100) threads = [] threadID = 1 def on_connect(client, userdata, rc)...
python
from flask_plugin import Plugin from flask import redirect, url_for, abort plugin = Plugin() @plugin.route('/say/<string:name>', methods=['GET']) def say(name: str): return 'Hello ' + name @plugin.route('/admin', methods=['GET']) def hello2admin(): return redirect(url_for('.say', name='Doge')) @plugin.r...
python
import os from chr.core import chr_compile_module chr_compile_module(os.path.dirname(__file__), verbose=False, overwrite=True)
python
from django.test import TestCase # Create your tests here. from selenium import webdriver from selenium.webdriver.common.keys import Keys class MultiSelectFunctionalTests(TestCase): base_url = 'http://localhost:8000/tests' fixtures=['publications'] def setUp(self): self.driver = webdriver.Firefox...
python
import tkinter as tkinter from tkinter import filedialog as FileDialog from Properties import Properties class Main(): def __init__(self): self.Window = tkinter.Tk() self.Properties = Properties() self.setTitle('Bloc Note') self.setSize(self.Properties.x, self.Properties.y) self.Frame = tkinter.Frame(self.W...
python
import unittest from unittest.mock import MagicMock import builtins class micropython: def const(self, number): return number class TestCase(unittest.TestCase): orig_import = __import__ module_mock = MagicMock() @classmethod def import_mock(cls, name, *args): if name == "uasyncio": return cls...
python
# http://github.com/timestocome # adapted from http://natureofcode.com/book/chapter-9-the-evolution-of-code/ # 3 letter match ~ 20 generations # 4 letters ~ 120 generations import string as st import re import numpy as np import copy bots = [] new_bots = [] scores = [] n_letters = 4 n_bots = 100 target =...
python
#encoding:utf-8 subreddit = 'CryptoMoonShots' t_channel = '@r_CryptoMoonShot' def send_post(submission, r2t): return r2t.send_simple(submission)
python
from seagulls.engine import ActiveSceneClient class FakeGameScene: pass class TestActiveSceneClient: def test_apply(self) -> None: fake_scene = FakeGameScene() def callback(scene: FakeGameScene) -> None: assert scene == fake_scene client = ActiveSceneClient(fake_scene) ...
python
import asyncio import logging from struct import Struct from time import time logger = logging.getLogger(__name__) class CyKitClient: def __init__(self, reader, writer, channels=14, sample_rate=128): self.sample_rate = sample_rate self._reader, self._writer = reader, writer self._struct ...
python
__author__ = "Anand Krishnan Prakash" __email__ = "akprakash@lbl.gov" import pymortar import datetime import pandas as pd import argparse def get_error_message(x, resample_minutes=60): dt_format = "%Y-%m-%d %H:%M:%S" st = x.name st_str = st.strftime(dt_format) et_str = (st+datetime.timedelta(minutes=...
python
# Данные для входа LOGIN = "логин" PASSWORD = "пароль" # Некоторые параметры API MAX_COUNT = 100 # Максимальное кол-во записей, которое можно получить по *.wall.get, деленное на 25. LIMIT = 500 AGE1 = 14 AGE2 = 20 AGE3 = 35 AGE4 = 50 """ LIMIT - Максимальное кол-во записей, скачиваемое со страницы по *wall.get (в...
python
""" Sponge Knowledge Base Provide action arguments - element value set """ class FruitsElementValueSetAction(Action): def onConfigure(self): self.withLabel("Fruits action with argument element value set") self.withArg(ListType("fruits", StringType()).withLabel("Fruits").withUnique().withProv...
python
# dna.py - DNA class and related functions # RMM, 11 Aug 2018 # # This file contains the implementation of DNA in the txtlsim toolbox. # This includes objects that represent the individual elements of a # DNA assembly as well as the functions required to create the models # associated with gene expression. # # Copyrigh...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from services import svcProject from utils.exceptionHandle import DefaultError def list_project(): """ GET /api/projects :return: """ try: return { 'title': 'Succeed to List Project', 'detail': svcProject.list_project(...
python
import pytz from cogs.Permissions import dm_commands, moderator_perms from GompeiFunctions import load_json, save_json from dateutil.parser import parse from discord.ext import commands from datetime import datetime from config import Config import asyncio import discord import os class Voting(commands.Cog): ""...
python
from typing import List, Type import warnings import numpy as np import matplotlib.patches as mpatches import matplotlib.pyplot as plt from astropy import wcs from astropy.coordinates import SkyCoord from astropy.io import fits from astropy.modeling import models from astropy.utils.exceptions import AstropyWarning fr...
python
import socket, time from kubism.util.dkr import PyApp_Image import docker import kubism.util.dkr as dkr SERVER = '172.24.12.161' CLIENT = '172.24.12.160' echo_port = 8080 # Echo Test # Create Echo Server print('Building and pushing images...') echo_srv = PyApp_Image('./examples/py/echo_server.py', parent_image...
python
from flask_security_bundle import FlaskSecurityBundle class SecurityBundle(FlaskSecurityBundle): pass
python
from .parse_html_index import parse_html_index from .parse_html_raceindex import parse_html_raceindex from .parse_html_racelist import parse_html_racelist from .parse_html_oddstf import parse_html_oddstf from .parse_html_oddsk import parse_html_oddsk from .parse_html_odds2tf import parse_html_odds2tf from .parse_html_o...
python
from .common import * # NOQA import pytest HUAWEI_CCE_ACCESS_KEY = os.environ.get('RANCHER_HUAWEI_CCE_ACCESS_KEY', "") HUAWEI_CCE_SECRET_KEY = os.environ.get('RANCHER_HUAWEI_CCE_SECRET_KEY', "") HUAWEI_CCE_PROJECT = os.environ.get('RANCHER_HUAWEI_CCE_PROJECT', "") HUAWEI_CCE_AMI = os.environ.get('RANCHER_HUAWEI_CCE_A...
python
from jewelry import Jewelry class Necklace(Jewelry): DEFAULT_METAL : str = "gold" DEFAULT_GEM : str = "diamond" def __init__(self, metal : str = DEFAULT_METAL, gem : str = DEFAULT_GEM): super(Necklace,self).__init__(polished = True) self._metal = metal self._gem = gem @propert...
python
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to t...
python
import functools from collections import OrderedDict, namedtuple from http import HTTPStatus from types import FunctionType from typing import Callable, Iterable, Optional from werkzeug.routing import Map, MethodNotAllowed, NotFound, RequestRedirect, Rule from PythonPlug import Conn from PythonPlug.plug import Plug ...
python
import unittest from test_support import run_unittest, TESTFN import glob import os def mkdirs(fname): if os.path.exists(fname) or fname == '': return base, file = os.path.split(fname) mkdirs(base) os.mkdir(fname) def touchfile(fname): base, file = os.path.split(fname) mkdirs(base) ...
python
from selenium import webdriver import os import subprocess driver = webdriver.Chrome(service_log_path=os.path.devnull) driver.set_window_size(1500, 900) fname = "file://" + os.getcwd() + "/opcodes.html" driver.get(fname) driver.save_screenshot("../images/opcode_map.png") driver.quit() subprocess.check_output([ "c...
python
# 增加的一个类属性用于统计Student的数量,每创建一个实例,该属性自动加一 class Student(object): count = 0 def __init__(self, name, score): Student.name = name Student.score = score if Student.name != []: Student.count += 1 # 测试: if Student.count != 0: print('测试失败!') else: bart = Student('Bart', 90...
python
#User function Template for python3 class Solution: #Function to find if there exists a triplet in the #array A[] which sums up to X. def find3Numbers(self,A, n, X): # Your Code Here A.sort() for i in range(n-2): start=i+1 end=n-1 sum1=0 ...
python
# Created: 17.05.2019 # Copyright (c) 2019, Manfred Moitzi # License: MIT License from typing import TYPE_CHECKING, Iterable, List, Mapping, Set import json from ezdxf.sections.tables import TABLENAMES from ezdxf.lldxf.tags import Tags if TYPE_CHECKING: from ezdxf.eztypes import Insert, MText, LWPolyline, Polylin...
python
from astropy.coordinates import Angle from neclib.parameters import PointingErrorData class TestPointingErrorData: expected = { "dAz": Angle("5314.2466754691195arcsec"), "de": Angle("382arcsec"), "chi_Az": Angle("-27.743114809726713arcsec"), "omega_Az": Angle("-10.004233550100272...
python
import pyglet.resource import pyglet.sprite import pyglet.graphics def get_room_wall_image(room): filename = 'res/rooms/walls/{}.jpg'.format(room.wall_variant) return pyglet.resource.image(filename) def get_forniture_image(forniture): filename = 'res/forniture/{}.png'.format(forniture.name) return...
python
# UNDER CONSTRUCTION ! light_metadata = { "name": { "type": "string" }, "version": { "type": "string" }, "data_preparation": { "type": "object", "properties": { "accepted_margin_of_error": { "type": "number" }, "total_row_count": { "type": "nu...
python
# -*- coding: utf-8 -*- """ Created on Thu Jun 20 22:56:12 2019 @author: Suman JaipurRentals Jaipur’s Real Estate Market is experiencing an incredible resurgence, with property prices soaring by double-digits on an yearly basis since 2013. While home owne...
python
import data as tours_data def data_html(): ret = "<h1>Все туры:</h1>"+"\n" for i in tours_data.tours.keys(): ret = ret + "<p>"+\ tours_data.tours[i]["country"]+\ ': <a href="/data/tours/'+str(i)+'/">'+\ tours_data.tours[i]["title"]+\ "</a></p>" ...
python
# The MIT License (MIT) # # Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries # # 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 limita...
python
__author__ = 'yinjun' #@see http://www.jiuzhang.com/solutions/longest-common-subsequence/ class Solution: """ @param A, B: Two strings. @return: The length of longest common subsequence of A and B. """ def longestCommonSubsequence(self, A, B): # write your code here x = len(A) ...
python
import sys from typing import Any, Collection, Dict, List, Optional, Union from pydantic import BaseModel from rest_api.config import DEFAULT_TOP_K_READER, DEFAULT_TOP_K_RETRIEVER MAX_RECURSION_DEPTH = sys.getrecursionlimit() - 1 class Question(BaseModel): questions: List[str] filters: Optional[Dict[str, O...
python
from hyperadmin.links import LinkPrototype class FormStepLinkPrototype(LinkPrototype): def get_link_kwargs(self, **kwargs): link_kwargs = {'on_submit':self.handle_submission, 'method':'POST', 'url':self.get_url(), 'form_class': self.get_...
python
from tests import PMGLiveServerTestCase from mock import patch import unittest from pmg.models import db, User from tests.fixtures import dbfixture, UserData, RoleData, OrganisationData class TestAdminUsersPage(PMGLiveServerTestCase): def setUp(self): super(TestAdminUsersPage, self).setUp() self....
python
from model import db, Product, Accounts def deleteUser(rowid) user = db.session.query(User).filter(User.id == user_id).first() if user: db.session.query(User).filter(User.id==user_id).delete() db.session().commit() def deleteProduct(rowid): user = db.session.query(User).filter(...
python
"""Hata Yönetimi - Raise Deyimi.""" # Python dili kırmızı yazılar ile kendine has hata mesajları yayınlamaktadır # Bizde bir hata meydana geldiğinde bu şekilde mesajlar yayınlayabiliriz. # Bunun için Raise deyimi kullanılır. sayi = 5 try: if sayi == 5: raise Exception('Sayı 5\'e eşit olamaz!') else: ...
python
# -*- coding: utf-8 -*- import copy __author__ = "Grant Hulegaard" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __license__ = "" __maintainer__ = "Grant Hulegaard" __email__ = "grant.hulegaard@nginx.com" def collect_cache_size(collector, data, stamp): collector.object.statsd.gauge('plus.cach...
python
from abc import ABCMeta import numpy as np from falconcv.decor import typeassert import logging logger = logging.getLogger(__name__) class ApiModel(metaclass=ABCMeta): def train(self, *args, **kwargs): return self def freeze(self, *args, **kwargs): return self def eval(self, *args, **k...
python
import sqlite3 CREATE_QUERY = """ CREATE TABLE IF NOT EXISTS chat_table ( chat_id INT PRIMARY KEY ) """ SELECT_ALL_QUERY = """ SELECT chat_id from chat_table """ INSERT_ONE_QUERY = """ INSERT INTO chat_table (chat_id) VALUES (%s) """ def execute_query(query): try: sqlite_con...
python
import pandas from openpyxl import load_workbook from openpyxl.utils.dataframe import dataframe_to_rows wb = load_workbook('data/regions.xlsx') ws = wb.active df = pandas.read_excel('data/all_shifts.xlsx') df1 = df[['Sales Rep', 'Cost per', 'Units Sold']] df1['Total'] = df1['Cost per'] * df1['Units Sold'] rows = data...
python
from __future__ import unicode_literals, print_function, division import os import matplotlib.pyplot as plt from compute_scores import compute_scores # Draw figures in Figure 2. for rel in ['mirgene', 'ppi', 'ploc']: # Heuristic of trigger words. scores = compute_scores(rel, 'h2') precisions = [s[2] for ...
python
#You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id. # For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee...
python
import copy import cv2 # import torch from mindspore import Tensor import numpy as np from PIL import Image from util.config import config as cfg from util.misc import find_bottom, find_long_edges, split_edge_seqence, \ norm2, vector_sin, split_edge_seqence_by_step, sample, fourier_transform, \ clockwise, find_...
python
#!/usr/bin/python import broker import select ## demo receiver that is subscribed to the topic "demo/select_fd" ep = broker.Endpoint() subscriber = ep.make_subscriber("demo/select_fd") ep.listen("127.0.0.1", 9999) while(True): ## this will block until we have read-readiness on the file descriptor # print("...
python
# # @lc app=leetcode.cn id=275 lang=python3 # # [275] H 指数 II # # https://leetcode-cn.com/problems/h-index-ii/description/ # # algorithms # Medium (41.25%) # Likes: 139 # Dislikes: 0 # Total Accepted: 39K # Total Submissions: 85.6K # Testcase Example: '[0,1,3,5,6]' # # 给定一位研究者论文被引用次数的数组(被引用次数是非负整数),数组已经按照 升序排列 。...
python
from twotest.fixtures import client, django_client from wheelcms_axle.tests.fixtures import localtyperegistry, localtemplateregistry, root
python
resposta = 'S' soma = count = maior = menor = 0 while resposta in 'Ss': num = int(input('Digite um numero: ')) soma += num count += 1 if count == 1: maior = menor = num else: if num > maior: maior = num else: menor = num resposta = str(input('Quer...
python
#!/usr/bin/env python # to be used with 'rps_pico_client.py' # Example to illustrate RPS feature to run tiny (pico) services, such as reading sensor data or # controlling a device; here, time at server is requested. In this example a new service task is # created to serve a request. Compare this to 'task_pico_service...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals __doc__ = """ hgvs.edit -- representation of edit operations in HGVS variants NARefAlt and AARefAlt are abstractions of several major variant types. They are distinguished by whether the ref and alt elements of...
python
#!/usr/bin/env python """"Downloads and unzips the KITTI tracking data. Warning: This can take a while, and use up >100Gb of disk space.""" #ref from https://github.com/utiasSTARS/pykitti/blob/master/pykitti/downloader/tracking.py from __future__ import print_function import argparse import os import sys from subpro...
python
from collections.abc import Iterable from enum import Enum import json import logging import subprocess from typing import Union, Any, Optional from pathlib import Path from scipy import sparse import scipy from typer.models import NoneType logger = logging.getLogger(__name__) def expand_paths(path_or_pattern): ...
python
#---------------------------------------------------------------------- # This programme provides a simple example of how to use "approach control" # for colour light (and to improve the automation of semaphore signals. # # For Colour Light Signals - this can be used where it is necessary to slow # a train down to take...
python
import subprocess import json from datetime import datetime from pydruid.client import PyDruid from pydruid.utils.aggregators import (longmax, doublemax) from pydruid.utils.filters import Dimension from kafka import KafkaProducer from iso8601utils import validators class KafkaAc...
python