content
stringlengths
0
894k
type
stringclasses
2 values
import os import pathlib import urllib import bs4 from .subsearcher import HTMLSubSearcher, SubInfo class SubHDSubSearcher(HTMLSubSearcher): """SubHD 字幕搜索器(https://subhd.tv)""" SUPPORT_LANGUAGES = ['zh_chs', 'zh_cht', 'en', 'zh_en'] SUPPORT_EXTS = ['ass', 'srt'] API_URL = 'https://subhd.tv/search/' ...
python
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import pickle class MyContainer(object): def __init__(self, data): self._data = data def get_data(self): return self._data d1 = MyContainer([2, 5, 4, 3, [ 12, 3, 5 ], 32, { 'a': 12, 'b': 43}]) with open('/tmp/pickle_data.dat', "wb") as f: ...
python
import os import urllib import elasticsearch import elasticsearch_dsl import es2json.helperscripts as helperscripts class ESGenerator: """ Main generator Object where other Generators inherit from """ def __init__(self, host='localhost', port=9200, es=None, ...
python
from copy import deepcopy from sqlalchemy import ( Table, Column, Integer, String, DateTime, UniqueConstraint, DECIMAL, LargeBinary, Boolean, ForeignKey, PrimaryKeyConstraint, ) from wt.common import Currency from wt.entities.deliverables import DeliverableStatus from wt.id...
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 ckitagawa <ckitagawa@edu.uwaterloo.ca> # # Distributed under terms of the MIT license. import logging import threading import serial import serial.tools.list_ports import fiber_reading from collections import deque def select_devic...
python
# 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 ...
python
# -*- coding: utf-8 -*- from typing import Dict, List, Optional, Tuple from django.conf import settings from rest_framework import serializers from backend.components import bk_repo from backend.helm.helm.models.chart import Chart, ChartVersion, ChartVersionSnapshot def get_chart_version( project_name: str, rep...
python
import os from collections import OrderedDict from coverage_checker.utils import get_all_path_combinations def test_get_all_path_combinations(): facets = OrderedDict([('a', ['1', '2']), ('b', ['3', '4']), ('c', ['5', '6'])]) all_paths = get_all_path_combinations(facets) expected_result = ['1/3/5', '...
python
import re from math import sqrt, atan2 if __name__ == "__main__": """ This script file demonstrates how to transform raw CSI out from the ESP32 into CSI-amplitude and CSI-phase. """ FILE_NAME = "./example_csi.csv" f = open(FILE_NAME) for j, l in enumerate(f.readlines()): imaginary = ...
python
# Recording video to a file # https://picamera.readthedocs.io/en/release-1.13/recipes1.html#recording-video-to-a-file import picamera camera = picamera.PiCamera() camera.resolution = (640, 480) camera.start_recording('output/07_video.h264') camera.wait_recording(5) camera.stop_recording()
python
# Copyright 2015 Google Inc. 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
# ----------------------------------------------------------------------------- # Copyright (c) 2013-2022, NeXpy Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING, distributed with this software. # -------------------------------------------------...
python
import os import sys from PIL import Image import glob import numpy as np import h5py import csv import time import zipfile import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve def reporth...
python
import sys # Expose the public API. from ehrpreper.api import * # Check major python version if sys.version_info[0] < 3: raise Exception("Ehrpreper does not support Python 2. Please upgrade to Python 3.") # Check minor python version elif sys.version_info[1] < 6: raise Exception( "Ehrpreper only suppo...
python
__author__ ='Jacques Saraydaryan' class ColorRange(): min_H=0 max_H=0 label='' def getColor(self,minH,maxH,label): self.min_H=minH self.max_H=maxH self.label=label
python
#! /usr/bin/env python import rospy, std_msgs.msg from sensor_msgs.msg import Temperature pub = rospy.Publisher('henri/temp_average', Temperature, queue_size=10) average = 0 variance = 0 def callback(data): global average, variance, pub rospy.loginfo('Temperature Received: %f', data.temperature) average =...
python
from flask import Flask from config import config_options from flask_sqlalchemy import SQLAlchemy from flask_uploads import UploadSet,configure_uploads,IMAGES from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_bootstrap import Bootstrap from flask_simplemde import SimpleMDE from flask_mail ...
python
# import numpy as np # import matplotlib.pyplot as plt # import cv2 # img = cv2.imread('8.jpeg',0) # dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT) # dft_shift = np.fft.fftshift(dft) # magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])) # plt.subplot(121),plt.imshow...
python
from flask import json, render_template, g, abort from flask_login import current_user, login_required import urllib, json from thanados import app from thanados.models.entity import Data @app.route('/vocabulary/') def vocabulary(): hierarchytypes = app.config["HIERARCHY_TYPES"] systemtypes = app.config["SY...
python
# TensorFlow and tf.keras import tensorflow as tf # Helper libraries import numpy as np import matplotlib.pyplot as plt # Display the image, labeled with the predicted label (blue if accurate to true label, red if not) def plot_image(i, predictions_array, true_label, img): true_label, img = true_label[i], img[i] ...
python
import os import os.path as osp import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import default_collate from torchvision.transforms import functional as F import numpy as np import numpy.linalg as LA import cv2 import json import csv import matplotlib.pyplot as plt from pylsd import ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2015-07-10 14:13:05 import os import sys from os import path import re import tempfile import shutil import time ''' clean idea project files param: max_depth -> max depth for recursively, default=3 param: permanently -> move to ...
python
import os from .handler import QuickOpenHandler from ._version import get_versions from notebook.utils import url_path_join __version__ = get_versions()['version'] del get_versions def _jupyter_server_extension_paths(): """Defines the entrypoint for the Jupyter server extension.""" return [{ "modul...
python
from abc import ABC from typing import Type from bokeh.models.glyph import Glyph from bokeh.models.renderers import GlyphRenderer from xbokeh.common.assertions import assert_type class Renderer(ABC): def __init__(self, type_: Type, renderer: GlyphRenderer) -> None: """ :renderer: instance of Gly...
python
from math import log from utils import iter_primes __author__ = 'rafa' def algorithm(limit): n = 1 for p in iter_primes(): if p > limit: return n exponent = int(log(limit, p)) n *= p**exponent def solver(): """ 2520 is the smallest number that can be divided by e...
python
import matplotlib.pyplot as plt import seaborn as sns import numpy as np def plot_time_series(x: np.ndarray, title=None) -> None: sns.set(font_scale=1.5) sns.set_style("white") t = np.arange(start=0, stop=x.shape[0]) plt.plot(t, x, linestyle='-', marker='o') plt.title(title) plt.xlabel(r'$t$')...
python
from __future__ import print_function import argparse import os import sys import time import random import string from typing import getch import torch import torch.nn as nn from torch.autograd import Variable from char_rnn import CharRNN class ProgressBar(object): def __init__(self, total=100, stream=sys.std...
python
from zipline.errors import UnsupportedPipelineOutput from zipline.utils.input_validation import ( expect_element, expect_types, optional, ) from .domain import Domain, GENERIC, infer_domain from .graph import ExecutionPlan, TermGraph, SCREEN_NAME from .filters import Filter from .term import AssetExists, C...
python
#!/usr/bin/env python # ToMaTo (Topology management software) # Copyright (C) 2010 Dennis Schwerdel, University of Kaiserslautern # # This program 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 versio...
python
# This file is part of Radicale Server - Calendar Server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud <unrud@outlook.com> # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publi...
python
import cv2 import numpy as np from moviepy.editor import VideoFileClip from .logger import Log from .calibration import GetCalibratedCamera, WarpMachine from .filtering import EdgeDetector from .lane_fitting import LaneFit from .save import chmod_rw_all, delete_file from .profiler import Profiler def draw_overlay(wa...
python
from rest_framework import serializers from chigre.models import KegType class KegTypeSerializer(serializers.ModelSerializer): class Meta: model = KegType fields = ('id', 'name', 'size', 'pints', 'canyas')
python
import numpy as np import pandas as pd from calParser import obtainSchedule from audit_parser import audit_info from lsa_recommender import export_to_master,filter_available_classes from decision_tree import preference_score,top_preferred_courses from collaborative_filtering import loadAudits, inputData, buildRecommend...
python
''' File: property.py Project: 08-class File Created: Saturday, 25th July 2020 9:16:43 pm Author: lanling (https://github.com/muyuuuu) ----------- Last Modified: Saturday, 25th July 2020 9:16:46 pm Modified By: lanling (https://github.com/muyuuuu) Copyright 2020 - 2020 NCST, NCST ----------- @ 佛祖保佑,永无BUG-- ''' # Python...
python
# -*- coding: utf-8 -*- import json import os import os.path import logging log = logging.getLogger(__name__) def filelist(folderpath, ext=None): ''' Returns a list of all the files contained in the folder specified by `folderpath`. To filter the files by extension simply add a list containing all the e...
python
''' Copyright (C) 2016-2021 Mo Zhou <lumin@debian.org> License: MIT/Expat ''' import os import math import time import random from .cuda_selector import CudaSelector RESOURCE_DEFAULT = 'void' RESOURCE_TYPES = (RESOURCE_DEFAULT, 'virtual', 'cpu', 'memory', 'gpu', 'vmem') if str(os.getenv('TASQUE_RESOURCE', '')): RE...
python
# -*- coding: utf-8 -*- from wcstring import wcstr import re class PipelineTable(object): ''' Pipeline Table Object. Attributes ---------- data : 2-dimension list 1st dimension indicates the column 2nd dimension indicates the index, with combined indexes grouped in a l...
python
from itertools import groupby from pathlib import Path inp = Path('input.txt').read_text() vowels = set('aeiou') nope = 'ab cd pq xy'.split() print(sum( ( sum(c in vowels for c in line) >= 3 and len(list(groupby(line))) < len(line) and not any(s in line for s in nope) ) for line ...
python
import matplotlib.pyplot as plt x_values = list(range(1, 5001)) y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values) plt.show()
python
# 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 ...
python
from enum import Enum import regex from ..config import Config from ..utils import Api class OsuConsts(Enum): """ all constants related to osu """ # "": 0, MODS = { "NF": 1 << 0, "EZ": 1 << 1, "TD": 1 << 2, "HD": 1 << 3, "HR": 1 << 4, "SD": 1 << 5,...
python
""" This file is part of L3Morpho. L3Morpho 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 of the License, or (at your option) any later version. L3Morpho is distributed in ...
python
# This program allows you to mark a square on the map using a two-digit system. # The first digit is the vertical column number and the second digit is the horizontal row number. row1 = ["⬜️", "⬜️", "⬜️"] row2 = ["⬜️", "⬜️", "⬜️"] row3 = ["⬜️", "⬜️", "⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") p...
python
# -*- coding: utf-8 -*- from django import template import datetime # import timedelta register = template.Library() def nice_repr(timedelta, display="long", sep=", "): """ Turns a datetime.timedelta object into a nice string repr. display can be "minimal", "short" or "long" [default]. >>> f...
python
''' Escreva um programa que converta uma temperatura digitada em °C e converta em °F. ''' c = float(input('Digite a temperatura em °C: ')) f = (9*c + 160)/5 print(f'A temperatura de {c}°C é {f}°F!')
python
import logging import numpy as np import pandas as pd import scipy.special import scipy.stats def encode_array(vals, sep=',', fmt='{:.6g}'): return sep.join(map(fmt.format, vals)) def decode_array(vals, sep=','): return np.asarray(list(map(float, vals.split(',')))) def encode_matrix(vals, sep1=',', sep2=';'...
python
import unittest import sys sys.path.insert(0, '../') from view_header import Route, PresentView, Flash, MSG_TYPE class TestRoute(unittest.TestCase): r1 = Route(True, 'test', {}) r2 = Route(True, 'test', {0:1, 1:'obj'}) def test_is_redirect(self): self.assertEqual(self.r1.is_redirect(), True) ...
python
from datetime import datetime def from_iso8601(date): return datetime.fromisoformat(date) def to_iso8601(year, month, day, hour, minute, second): return datetime(year, month, day, hour, minute, second, 0).isoformat()
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-17 06:04 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0007_auto_20171005_1713'), ] operations = [...
python
# # Copyright Bernhard Firner, 2019-2020 # # Ship class and supporting classes from collections import OrderedDict from enum import Enum import torch from dice import ArmadaDice from game_constants import ( ArmadaDimensions, ArmadaTypes ) class UpgradeType(Enum): commander = 1 officer ...
python
import os import sys import time import wave import numpy as np from datetime import datetime from pyaudio import PyAudio, paInt16 class GenAudio(object): def __init__(self): self.num_samples = 2000 # pyaudio内置缓冲大小 self.sampling_rate = 8000 # 取样频率 self.level = 1500 # 声音保存的阈值 sel...
python
# -*- coding: utf-8 -*- """ Created on Fri Nov 16 00:13:05 2018 @author: Gireesh Sundaram """ import pandas as pd import numpy as np import seaborn as sns from sklearn.preprocessing import OneHotEncoder, LabelEncoder from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNe...
python
# # Copyright (c) 2020 Xilinx, Inc. All rights reserved. # SPDX-License-Identifier: MIT # platform = "microblaze" procs = ["microblaze"] serial_port = "serial" arch = "microblaze" linux_compiler = "microblazeel-xilinx-linux-gnu-" dtb_loadaddr = 0x81E00000 dtb_arch = "microblaze" dtb_dtg = "microblaze-generic" dtb_de...
python
# -*- coding: utf-8 -*- from terminaltables import AsciiTable from colorclass import Color class CostAnalysis: def __init__(self, db): self.db = db def draw(self, market, symbol, args): if len(args) != 0: raise Exception('no argument required for {}'.format(CostAnalysis.__name__)...
python
# Size of program memory (bytes) MAX_PGM_MEM = 4096 # Size of context memory (bytes) MAX_DATA_MEM = 2048 # Max stack size (bytes) MAX_STACK = 512 # Number of registers MAX_REGS = 11 # Default output indentation for some debug messages IND = " " * 8 # Maximum values for various unsigned integers MAX_UINT8 = 0xff MAX...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutStrings(Koan): # https://docs.python.org/3/library/stdtypes.html#textseq # https://docs.python.org/3/library/unittest.html#assert-methods # https://docs.python.org/3/library/functions.html#isinstance def test_double_...
python
# Mount RPC client -- RFC 1094 (NFS), Appendix A # This module demonstrates how to write your own RPC client in Python. # When this example was written, there was no RPC compiler for # Python. Without such a compiler, you must first create classes # derived from Packer and Unpacker to handle the data types for the # s...
python
import os import librosa import numpy as np import pandas as pd from pandas import DataFrame from sklearn.preprocessing import LabelEncoder # def get_feature_label(row, directory): def get_feature_label(row, directory): file_name = os.path.join(directory, str(row.ID) + '.wav') # file_name = os.path.join("da...
python
from urllib.parse import urlencode,parse_qs,unquote def stringify(d,u=False): qs = urlencode(d) if u: qs = unquote(qs) return qs def parse(url): d = dict( (k, v if len(v)>1 else v[0] ) for k, v in parse_qs(url).items() ) return d
python
#!/usr/bin/python #coding:utf-8 import json import copy import time import os endpoint = "bind9" name_stats_path = "/var/named/data/named_stats.txt" def main(): if os.path.isfile(name_stats_path): os.remove(name_stats_path) os.system("rndc stats") ts = int(time.time()) payload = [] data = {"endpoint":endpoint...
python
from plugins.database import db class BaseModel: def save(self): try: db.session.add(self) db.session.commit() return True except: return False
python
"""Creates a custom kinematics body with two links and one joint """ from openravepy import * from numpy import eye, array, zeros env = Environment() # create openrave environment env.SetViewer('qtcoin') # attach viewer (optional) with env: robot=RaveCreateRobot(env,'') robot.SetName('camera') linkinfo=Ki...
python
import itertools from surprise import accuracy from collections import defaultdict class RecommenderMetrics: def mae(predictions): return accuracy.mae(predictions, verbose=False) def rmse(predictions): return accuracy.rmse(predictions, verbose=False)
python
from setuptools import setup install_requires = ( 'beautifulsoup4==4.6.3', ) tests_require = ( 'pytest', 'pytest-cov', 'mock', ) setup_requires = ( 'pytest-runner', 'flake8', ) setup( name='tracking-id-injector', version='1.0.1', url='https://github.com/msufa/tracking-id-injector...
python
import argparse import time import math import numpy as np import sklearn.metrics as sk import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import data import model from utils_lm import batchify, get_batch, repackage_hidden # go through rigamaroo to do ..utils.displ...
python
from typing import Optional from openslides_backend.action.actions.user.user_scope_permission_check_mixin import ( UserScope, ) from openslides_backend.permissions.management_levels import ( CommitteeManagementLevel, OrganizationManagementLevel, ) from openslides_backend.permissions.permissions import Perm...
python
""" GUI layout that allows free positioning of children. @author Ben Giacalone """ from tools.envedit.gui.gui_layout import GUILayout class GUIFreeLayout(GUILayout): def __init__(self): GUILayout.__init__(self) self.children = [] # Adds a child to the layout def add_child(self, child): ...
python
#!/bin/python # # File: test-all.py # Authors: Leonid Shamis (leonid.shamis@gmail.com) # Keith Schwarz (htiek@cs.stanford.edu) # # A test harness that automatically runs your compiler on all of the tests # in the 'samples' directory. This should help you diagnose errors in your # compiler and will help you ga...
python
number_1 = int(input('Enter your first number:')) number_2 = int(input('Enter your second number:')) operator = str(input('Enter your operator')) if operator=='+': print(number_1 + number_2) elif operator=='-': print(number_1 - number_2) elif operator=='*': print(number_1 * number_2) elif operator=='/': ...
python
# Winston Peng # SoftDev1 pd9 # K10 -- Jinja Tuning # 2019-9-23 from flask import Flask, render_template import static.script as script app = Flask(__name__) @app.route('/occupyflaskst') def occupations(): return render_template( 'occ.html', team = 'Connor Oh, Nahi Khan, Winston Peng -- T...
python
#!/usr/bin/env python # macro_avg.py v1.0 9-19-2012 Jeff Doak jeff.w.doak@gmail.com from chargedensity import * import numpy as np import sys if len(sys.argv) > 1: if str(sys.argv[1]) == "CHG": a = ChargeDensity(str(sys.argv[1]),format_="chgcar") else: a = ChargeDensity(str(sys.argv[1])) else...
python
""" A python module to communicate with Elecrolux Connectivity Platform """ __all__ = [ 'Error', 'LoginError', 'RequestError', 'ResponseError', 'Session' ] from .Session import ( Error, LoginError, RequestError, ResponseError, Session )
python
from enum import Enum class Transition(Enum): """ Enumeration of the transitions a job can go through. """ ACQUIRE = 0 RELEASE = 1 START = 2 PROGRESS = 3 FINISH = 4 ERROR = 5 RESET = 6 ABORT = 7 CANCEL = 8 @property def json_property_name(self) -> str: ...
python
from ..models.box_daily_square import BoxDailySquare class BoxDailySquareManager(object): def create_box(self, data): box, created = BoxDailySquare.objects.get_or_create( user=data['user'], office=data['office'] ) return box
python
import os import shutil import subprocess CONNECT_REPORTS_REPO_URL = 'https://github.com/cloudblue/connect-reports.git' BASE_DIR = os.path.abspath( os.path.normpath( os.path.join( os.path.dirname(__file__), '..', ), ), ) REPO_EMBED_DIR = os.path.join( BASE_DIR, ...
python
from scipy import integrate def integrand(x0, x1, x2): return x2 * x1**2 + x0 x2_lim = (0.0, 0.5) x1_lim = lambda x2:(0.0, 1.0-2.0*x2) x0_lim = lambda x1,x2:(-1.0, 1.0+2.0*x2-x1) # int_{x2=0}^{0.5} int_{x1=0}^{1-2x2} int_{x0=-1}^{1+2x2-x1} (x2 x1**2 + x0) dx0 dx1 dx2 integral,error = integrate.nquad(integrand, [x0_...
python
#!/usr/bin/env python # # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Da...
python
"""Dyson new v2 pure Hot+Cool device.""" import logging from .const import HeatMode from .dyson_pure_cool import DysonPureCool from .utils import printable_fields _LOGGER = logging.getLogger(__name__) class DysonPureHotCool(DysonPureCool): """Dyson new Pure Hot+Cool device.""" def _parse_command_args(self...
python
from .data import COVID19India from .mongo_db import get_data, upload_data from .data_processing import get_daily_data, get_state_daily, get_interval_data from .inshorts_news import InshortsNews
python
from .csr import skeleton_to_csgraph, branch_statistics, summarize, Skeleton __version__ = '0.10.0-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarize', 'Skeleton']
python
class NumMatrix: def __init__(self, matrix: List[List[int]]): if len(matrix) == 0: self.dp = [] return width, height = len(matrix[0]), len(matrix) self.dp = [[0] * (width + 1) for _ in range(height + 1)] for i in range(1, height+1): for...
python
# ############################################################################ # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
python
import os, sys, re, time import urllib, urllib2 from BeautifulSoup import BeautifulSoup #import beautifulsoup4 import gzip from StringIO import StringIO import MySQLdb import simplejson as json import datetime import pandas as pd import pymongo #from cassandra.cluster import Cluster import conf.config as config from cr...
python
n = input('Digite algo: ') print('O timpo primitivo do que foi digitado é: {}'.format(type(n))) print('Ele é numérico? {}'.format(n.isnumeric())) # Compara se é um numero, se sim envia a mensagem True print('Ele é um texto? {}'.format(n.isalpha())) # Compara se é Letra, se sim envia a mensagem Tru...
python
import sys from rpython.tool.pairtype import pairtype from rpython.flowspace.model import Constant from rpython.rtyper.rdict import AbstractDictRepr, AbstractDictIteratorRepr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi from rpython.rlib import objectmodel, jit, rgc, types from rpython.rlib.signature ...
python
import numpy as np i8 = np.int64() i4 = np.int32() u8 = np.uint64() b_ = np.bool_() i = int() f8 = np.float64() b_ >> f8 # E: No overload variant i8 << f8 # E: No overload variant i | f8 # E: Unsupported operand types i8 ^ f8 # E: No overload variant u8 & f8 # E: No overload variant ~f8 # E: Unsupported operan...
python
# -*- coding: utf-8 -*- import datetime, json, logging, os, subprocess from fast_reconcile_app import settings_app from django.conf import settings # from django.core.urlresolvers import reverse log = logging.getLogger(__name__) def get_commit(): """ Returns commit-string. Called by views.info() """ ...
python
# Copyright 2019-2021 Foreseeti AB <https://foreseeti.com> # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
python
# # Copyright 2016 The BigDL Authors. # # 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 ...
python
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ This module contains collection of classes which implement collate functionalities for various tasks. Collaters should know wh...
python
# coding: utf-8 import clinica.engine as ce class PetSurfaceLongitudinalCLI(ce.CmdParser): def define_name(self): """Define the sub-command name to run this pipeline.""" self._name = "pet-surface-longitudinal" def define_description(self): """Define a description of this pipeline."""...
python
import time from threading import Thread from cassandra import ConsistencyLevel from ccmlib.node import ToolError from dtest import Tester, debug from tools import insert_c1c2, query_c1c2, since class TestRebuild(Tester): def __init__(self, *args, **kwargs): kwargs['cluster_options'] = {'start_rpc': 't...
python
from django.core.management.base import BaseCommand from schedule import models from django.utils import timezone from django.conf import settings import requests import requests.auth import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): sch...
python
###################################### # # Nikolai Rozanov (C) 2017-Present # # nikolai.rozanov@gmail.com # ##################################### import numpy as np # # This file is a way of learning the Kernel and performing a hypothesis test, by computin the test statistics # class TEST(object): ''' main...
python
import os from PIL import Image import tensorflow as tf from Fishnet import FishNets import numpy as np import json def onehot(label): n_sample = len(label) # n_class=max(label)+1 onehot_labels = np.zeros((n_sample, 6)) onehot_labels[np.arange(n_sample), label] = 1 return onehot_labels def read(file_list): ...
python
from numpy import dot, diag, ones, zeros, sqrt from openopt.kernel.ooMisc import norm def amsg2p(f, df, x0, epsilon, f_opt, gamma, callback = lambda x, f: False): # returns optim point and iteration number f0 = f(x0) if f0 - f_opt <= epsilon: return x0, 0 x, n = x0.copy(), x0.size df0 = df(x0) ...
python
import torch as t import torch.nn as nn import torch.nn.functional as f from config import config from torch.optim import Adam, SGD, Adagrad from torch.autograd import Variable from data_utils import batch_by_num from base_model import BaseModel, BaseModule import logging import os class RotatEModule(BaseMo...
python
import math import numpy as np from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F import logging from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from src.datasets.utility import find_sub_list from src.scripts.tools.utility import get_device class Em...
python
# run tests to check coverage import os import asyncio import discord as dpy import prettify_exceptions prettify_exceptions.hook() import viper from viper.exts import discord basic_test = os.path.join("tests", "test_script.vp") discordpy_test = os.path.join("tests", "discordpy_script_test.vp") loop = asyncio.get_ev...
python
from flask import Flask from flask_sslify import SSLify app = Flask(__name__) app.config.from_object('config') sslify = SSLify(app) from jawfish import views
python