text
string
size
int64
token_count
int64
# encoding=utf-8 import rospy import tf if __name__ == '__main__': rospy.init_node('py_tf_broadcaster') br = tf.TransformBroadcaster() x = 0.0 y = 0.0 z = 0.0 roll = 0 pitch = 0 yaw = 1.57 rate = rospy.Rate(1) while not rospy.is_shutdown(): yaw = yaw + 0.1 roll...
625
245
# Imports import numpy as np class TechnicalIndicators: cci_constant = 0.015 def __init__(self): self.df = None # Exponentially-weighted moving average def ewma(self, periods): indicator = 'EWMA{}'.format(periods) self.df[indicator] = self.df['close'].ewm(span=periods).mean()...
2,674
909
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_description = models.CharField(max_length=200, null=True) user_avatar = models.ImageField(null=True, blank=True) user_uploaded_rec...
440
142
import torch import logging # Transformer version 4.9.1 - Newer versions may not work. from transformers import AutoTokenizer from trained_gpt_model import get_inference2 def t5_supp_inference(review_text): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # CPU may not work, got to check. ...
5,332
1,822
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import os import sys import...
5,979
1,773
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys reload(sys) sys.path.append("..") sys.setdefaultencoding('utf-8') from jinja2 import Environment from jinja2 import Template import re from sqlalchemy import schema, types from sqlalchemy.engine import create_engine import yyutil import CodeGen project_...
4,919
1,361
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import turtle >>> tao = turtle.Turtle() >>> tao.shape('turtle') >>> tao.forward(100) >>> tao.left(90) >>> tao.forward(100) >>> tao.left(90) ...
2,333
1,310
""" Pythonista3 app CodeMirror """ import pythonista.wkwebview as wkwebview import ui import pathlib uri = pathlib.Path('./main_index.html') class View(ui.View): def __init__(self): self.wv = wkwebview.WKWebView(flex='WH') self.wv.load_url(str(uri)) self.add_subview(self.wv) def will_close(self): ...
424
168
import wrapper as w from multiprocessing import Process import atexit import time from queue import Queue ''' 8 Processes, 24 threads per process = 192 threads ''' NUM_PROCESSES = 8 workerList = [] # Worker processes class Worker(Process): # Need multiple threads or else it takes forever def __init__(self, queue):...
1,363
470
from typing import Callable, Sequence, Any, Dict import functools import torch import torch.overrides from torch._prims.utils import torch_function_passthrough import torch._refs as refs import torch._refs import torch._refs.nn import torch._refs.nn.functional import torch._refs.special import torch._prims # TOD...
2,702
918
from django.test import TestCase from search.read_similarities import build_manual_similarity_map from common.testhelpers.random_test_values import a_string, a_float class TestReadingManualTaskSimilarities(TestCase): def test_convert_matrix_to_map_from_topic_to_array_of_services(self): data = [ ...
1,868
540
""" Fortuna Python project to visualize uncertatinty in probabilistic exploration models. Created on 09/06/2018 @authors: Natalia Shchukina, Graham Brew, Marco van Veen, Behrooz Bashokooh, Tobias Stål, Robert Leckenby """ # Import libraries import numpy as np import glob from matplotlib import pyplot as plt import...
7,535
2,492
from PIL import Image # open an image file (.bmp,.jpg,.png,.gif) you have in the working folder # //imageFile = "03802.png" import os arr=os.listdir() for imageFile in arr: if "png" in imageFile: im1 = Image.open(imageFile) # adjust width and height to your needs width = 416 heigh...
1,104
370
class InvalidMovementException(Exception): pass class InvalidMovementTargetException(InvalidMovementException): pass class InvalidMovimentOriginException(InvalidMovementException): pass
200
52
#!/usr/bin/env python3 import argparse import bisect import csv import json import os from collections import defaultdict from functools import reduce from tqdm import tqdm def get_best_evidence(scores_file, max_sentences_per_claim): weighted_claim_evidence = defaultdict(lambda: []) with open(scores_file, "...
2,517
874
from telegram.ext import CommandHandler, run_async from bot.gDrive import GoogleDriveHelper from bot.fs_utils import get_readable_file_size from bot import LOGGER, dispatcher, updater, bot from bot.config import BOT_TOKEN, OWNER_ID, GDRIVE_FOLDER_ID from bot.decorators import is_authorised, is_owner from telegram.error...
4,455
1,418
import pandas as pd import numpy as np from portfoliolab.utils import RiskMetrics from portfoliolab.estimators import RiskEstimators from pypfopt import risk_models as risk_models_ """ Available covariance risk models in PortfolioLab library. https://hudson-and-thames-portfoliolab-pro.readthedocs-hosted.com/en/latest...
8,180
2,777
import cv2 as cv import sys import numpy as np import random as r import os from PIL import Image as im def noisy(noise_typ,image): if noise_typ == "gauss": # Generate Gaussian noise gauss = np.random.normal(0,1,image.size) print(gauss) gauss = gauss.reshape(image.shape[0],image.sh...
2,516
953
from citywok_ms.file.models import EmployeeFile, File import citywok_ms.employee.messages as employee_msg import citywok_ms.file.messages as file_msg from citywok_ms.employee.forms import EmployeeForm from citywok_ms.file.forms import FileForm from flask import Blueprint, flash, redirect, render_template, url_for from ...
3,223
1,034
import calendar from datetime import datetime, timedelta import json import logging import re import rfc822 from django.conf import settings from django.db.utils import IntegrityError import cronjobs from multidb.pinning import pin_this_thread from statsd import statsd from twython import Twython from kitsune.custom...
9,041
2,870
#!/usr/bin/env python from distutils.core import setup try: import setuptools except: pass setup( name='pdfrw', version='0.1', description='PDF file reader/writer library', long_description=''' pdfrw lets you read and write PDF files, including compositing multiple pages together (e.g. to do w...
1,333
386
import argparse import sys import cv2 import os import os.path as osp import numpy as np if sys.version_info[0] == 2: import xml.etree.cElementTree as ET else: import xml.etree.ElementTree as ET parser = argparse.ArgumentParser( description='Single Shot MultiBox Detector ...
2,429
849
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
3,215
881
# -*- coding: utf-8 -*- # This file is part of convertdate. # http://github.com/fitnr/convertdate # Licensed under the MIT license: # http://opensource.org/licenses/MIT # Copyright (c) 2016, fitnr <fitnr@fakeisthenewreal> '''Convert to and from the Dublin day count''' from . import daycount EPOCH = 2415020 # Juli...
656
276
from tensorhive.models.Group import Group from fixtures.controllers import API_URI as BASE_URI, HEADERS from http import HTTPStatus from importlib import reload import json import auth_patcher ENDPOINT = BASE_URI + '/groups' def setup_module(_): auth_patches = auth_patcher.get_patches(superuser=True) for au...
5,250
1,883
import os from os.path import join, isfile import re import numpy as np import pickle import argparse import skipthoughts import h5py def main(): parser = argparse.ArgumentParser() #parser.add_argument('--caption_file', type=str, default='Data/sample_captions.txt', # help='caption file') parser.add_argumen...
1,232
466
"""Parsing responses from the difficulty command.""" from mcipc.rcon.functions import boolmap __all__ = ['parse'] SET = 'The difficulty has been set to (\\w+)' UNCHANGED = 'The difficulty did not change; it is already set to (\\w+)' def parse(text: str) -> bool: """Parses a boolean value from the text re...
415
133
from typing import ( Iterable, Tuple, ) from cytoolz import ( pipe ) from eth._utils import bls from eth._utils.bitfield import ( set_voted, ) from eth.beacon.enums import SignatureDomain from eth.beacon.typing import ( BLSPubkey, BLSSignature, Bitfield, CommitteeIndex, ) def verify_v...
1,558
534
# Copyright 2021 Hewlett Packard Enterprise Development LP # # 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, modif...
7,090
2,052
import unittest from find_x_in_listy import find_x_in_listy, Listy class Test_Case_Find_X_In_Listy(unittest.TestCase): def test_case_find_x_in_listy(self): listy = Listy(list(range(0, 1*10**8))) self.assertEqual(find_x_in_listy(listy, 5678), 5678)
268
119
from scipy.signal import butter,filtfilt from numba import jit import bisect def is_number_in_sorted_vector(sorted_vector, num): index = bisect.bisect_left(sorted_vector, num) return index != len(sorted_vector) and sorted_vector[index] == num # def butter_lowpass(cutoff, fs, order=5): # nyq = 0.5 * fs # ...
979
377
import asyncio from contextlib import asynccontextmanager import pytest from mitmproxy import exceptions from mitmproxy.addons.proxyserver import Proxyserver from mitmproxy.connection import Address from mitmproxy.proxy import layers, server_hooks from mitmproxy.proxy.layers.http import HTTPMode from mitmproxy.test i...
6,856
2,147
# Copyright 2021 The TensorFlow Probability 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 o...
19,608
6,383
import datetime import httplib import urllib from datetime import timedelta #now = datetime.datetime.now(); #today = now.strftime('%Y-%m-%d') #print today def isfloat(value): try: float(value) return True except ValueError: return False def convfloat(value): try: return float(value) except ValueError: ...
1,254
506
import copy import pandas as pd from decouple import config from heuristic.construction.construction import ConstructionHeuristic from config.construction_config import * from simulation.simulator import Simulator from heuristic.improvement.reopt.new_request_updater import NewRequestUpdater class DisruptionUpdater: ...
5,403
1,575
# Generated by Django 2.2.6 on 2019-10-25 12:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("scripts", "0012_auto_20190128_1820")] operations = [ migrations.AlterField( model_name="scriptdb", name="db_typeclass_path", ...
666
205
# -*- coding: utf-8 -*- # # Copyright (c) 2016 - 2020 -- Lars Heuer # All rights reserved. # # License: BSD License # """\ Test against issue <https://github.com/pyqrcode/pyqrcodeNG/pull/13/>. The initial test was created by Mathieu <https://github.com/albatros69>, see the above mentioned pull request. Adapted for Se...
834
318
# -*- coding: utf-8 -*- # Copyright 2019, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """Quantum Operators.""" from .operator import Operator from .unitary import Unitary from .pauli import Pauli, pauli_group f...
384
129
from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('class/', include('classroom.urls')), path('assignment-api/', include('assignment.urls', namespace='assign...
554
166
from src import app, db from .models import User, Role, RoleUsers from .security_admin import UserAdmin, RoleAdmin from flask_security import Security, SQLAlchemyUserDatastore, \ login_required, roles_accepted from flask_security.utils import encrypt_password def config_security_admin(admin): admin.add_view(U...
1,905
608
""" This file defines a series of constants that represent the values used in the API's "helper" tables. Rather than define the values in the db setup scripts and then make db calls to lookup the surrogate keys, we'll define everything here, in a file that can be used by the db setup scripts *and* the application code...
12,251
3,755
#!/bin/env python #-*-coding:utf-8-*- import os import sys import string import time import datetime import MySQLdb class MySQL: def __int__(self,host,port,user,passwd,dbname,timeout,charset): self.host = host self.port = port self.user = user self.passwd = passwd self.dbnam...
1,985
631
import sqlite3 conn = sqlite3.connect("db") cur = conn.cursor() cur.execute("select * from CAR_ID limit 5;") results = cur.fetchall() print(results)
149
52
import time from jina.executors.crafters import BaseCrafter from .helper import foo class DummyHubExecutorSlow(BaseCrafter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) time.sleep(15) foo()
249
84
import numpy as np import pandas as pd from scipy.stats import spearmanr from sklearn.metrics import f1_score, precision_score, recall_score from IPython.display import display, clear_output from sklearn.metrics import confusion_matrix import scipy.stats as st def continuous_to_categorical_with_quantiles(data: np.nda...
8,827
2,823
from collections import defaultdict from poloniex_apis.api_models.ticker_price import TickerData class DWHistory: def __init__(self, history): self.withdrawals = defaultdict(float) self.deposits = defaultdict(float) self.history = history def get_dw_history(self): for deposit...
1,709
485
from datetime import datetime,timezone import sys import boto3 import json def pipeline_event(event, context): state = get_final_state(event) if state is None: return event_time = datetime.strptime(event['time'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) metric_data = [] if eve...
7,320
2,185
import discord import sqlite3 from discord.ext import commands conn= sqlite3.connect("dbs/main.db") class Commands(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.cooldown(1, 30, commands.BucketType.guild) @commands.has_permissions(manage_channels=True) async def setchann...
4,507
1,687
import hashlib import os import shutil import subprocess import sys import tarfile from functools import cmp_to_key from gzip import GzipFile try: from urllib.error import HTTPError from urllib.request import urlopen except ImportError: from urllib2 import HTTPError from urllib2 import urlopen from c...
6,210
1,739
from osp.corpus.syllabus import Syllabus from osp.test.utils import requires_tika def test_empty(mock_osp): """ Should return None if the file is empty. """ path = mock_osp.add_file(content='', ftype='plain') syllabus = Syllabus(path) assert syllabus.text == None def test_plaintext(mock...
1,192
447
from boa_test.tests.boa_test import BoaFixtureTest from boa.compiler import Compiler from neo.Core.TX.Transaction import Transaction from neo.Prompt.Commands.BuildNRun import TestBuild from neo.EventHub import events from neo.SmartContract.SmartContractEvent import SmartContractEvent, NotifyEvent from neo.Settings impo...
19,099
6,534
#!/usr/bin/python # -*- mode: python; -*- ## This file is part of Indian Language Converter ## Copyright (C) 2006 Vijay Lakshminarayanan <liyer.vijay@gmail.com> ## Indian Language Converter is free software; you can redistribute it ## and/or modify it under the terms of the GNU General Public License ## as published...
2,576
898
import requests import crowdstrike_detection as crowdstrike import logging import click import urllib.parse import ConfigParser import os logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-15s [%(levelname)-8s]: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logger = logging.get...
3,765
1,274
FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data' ]
92
39
import requests import json HEADERS = {"Authorization": "OAuth AgAAAAA00Se2AAW1W1yCegavqkretMXBGkoUUQk", "Accept": "*/*"} URL = "https://cloud-api.yandex.net:443/v1/disk/" def get_folder_info(folder_name_1, folder_name_2, url=None, headers=None): """Получение информации о статусе папок на диске Args: ...
4,593
1,652
import os from collections import defaultdict from flask import render_template from flask_login import login_required from sqlalchemy import and_ from app import db from app.decorators import operator_required from app.models import Student, MonthNameList, Course, PaymentStatus, Payment, Teacher, Schedule from app.u...
3,208
982
# Copyright (c) 2017, John Skinner import abc import typing import bson import pymodm import pymodm.fields as fields import arvet.database.pymodm_abc as pymodm_abc from arvet.database.reference_list_field import ReferenceListField import arvet.core.trial_result class Metric(pymodm.MongoModel, metaclass=pymodm_abc.ABC...
5,936
1,575
"""File access utils""" __author__ = 'thorwhalen' # from ut.datapath import datapath import pickle import os from ut.util.importing import get_environment_variable import pandas as pd import ut.pfile.to as file_to import ut.pfile.name as pfile_name import ut.pstr.to as pstr_to from ut.serialize.local import Local from...
19,192
5,740
import subprocess import git from os.path import dirname, join, abspath import pandas as pd from matplotlib import pyplot as plt import requests import io import zipfile import tempfile from datetime import timedelta FILENAME = join(dirname(__file__), "..", "thesis.tex") DISP_PAGESMAX = 80 DISP_WORDSMAX = 10000 def ...
4,309
1,586
"""Installation instructions for enrich_pvalues.""" import os from setuptools import setup import enrich_pvalues # For version VERSION=enrich_pvalues.__version__ GITHUB='https://github.com/MikeDacre/enrich_pvalues' with open('requirements.txt') as fin: REQUIREMENTS = [ i[0] for i in [j.split('>=') for j...
1,966
636
import datetime from homeschool.courses.tests.factories import ( CourseFactory, CourseTaskFactory, GradedWorkFactory, ) from homeschool.schools.tests.factories import GradeLevelFactory from homeschool.students.forms import CourseworkForm, EnrollmentForm, GradeForm from homeschool.students.models import Cou...
11,457
3,360
""" @Author Jchakra""" """ This code is to download project information using GitHub API (Following Amrit's Hero paper criteria of how to find good projects) """ from multiprocessing import Process,Lock import time import json import requests ## Downloading all the projects def func1(): repo_result = [] To...
23,144
7,298
# Copyright 2017 The TensorFlow Authors. 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 applica...
2,173
1,051
""" Simulation parameters. """ SIMULATION_TIME_STEPS = 300
60
28
import cv2 import numpy as np try: import scipy # scipy.ndimage cannot be accessed until explicitly imported from scipy import ndimage except ImportError: scipy = None def flip_axis(x, axis): x = np.asarray(x).swapaxes(axis, 0) x = x[::-1, ...] x = x.swapaxes(0, axis) return x def r...
12,669
3,961
# 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, software # distributed under t...
1,093
334
import functools def create_maybe_get_wire(conn): c = conn.cursor() @functools.lru_cache(maxsize=None) def get_tile_type_pkey(tile): c.execute('SELECT pkey, tile_type_pkey FROM phy_tile WHERE name = ?', (tile, )) return c.fetchone() @functools.lru_cache(maxsize=None...
2,927
1,128
"""A module that provides functionality for accessing the Payments API.""" import enum import http import logging import requests from fastapi import Depends, Header, HTTPException from fastapi.security.http import HTTPAuthorizationCredentials import auth.authentication import config import schemas.payment logger ...
2,443
667
def numb_of_char(a): d = {} for char in set(a): d[char] = a.count(char) return d a = numb_of_char(str(input("Input the word please: "))) print(a)
168
71
class Vector2D: def __init__(self, v: List[List[int]]): def getIt(): for row in v: for val in row: yield val self.it = iter(getIt()) self.val = next(self.it, None) def next(self) -> int: result = self.val ...
589
186
from datetime import datetime import inspect def log_time(msg=None): def decorator(f): nonlocal msg if msg is None: msg = '{} time spent: '.format(f.__name__) def inner(*args, **kwargs): # check if the object has a logger global logger if ar...
1,049
295
from lf3py.di.di import DI # noqa F401
40
21
import logging from django.utils.safestring import mark_safe from django_rq import job from inline_static.css import transform_css_urls logger = logging.getLogger(__name__) @job def calculate_critical_css(critical_id, original_path): from .exceptions import CriticalException from .models import Critical ...
1,418
424
#!/usr/bin/env python # coding=utf-8 """ This script tests the simulations of the experiments. """ import math from utils import coin_var, needle_var def main(): needle_var_vals = [ (1.1, 1.0), (1.4, 1.0), (2.0, 1.0), (2.9, 1.0), (3.3, 1.0), (5.0, 1.0) ] ...
1,837
745
from addressing import * from instructions.base_instructions import SetBit, ClearBit from instructions.generic_instructions import Instruction from status import Status # set status instructions class Sec(SetBit): identifier_byte = bytes([0x38]) bit = Status.StatusTypes.carry class Sei(SetBit): identifi...
2,244
745
# # @lc app=leetcode id=530 lang=python3 # # [530] Minimum Absolute Difference in BST # # https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ # # algorithms # Easy (55.23%) # Total Accepted: 115.5K # Total Submissions: 209K # Testcase Example: '[4,2,6,1,3]' # # Given the root of a Binary S...
1,960
710
# Copyright 2019 The TensorFlow Authors. 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 ...
2,769
999
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Copyright (c) 2017 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test that the blockmaxsize and excessiveblocksize paramete...
1,418
483
#!/usr/bin/env python # Copyright 2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. # standard library modules, , , import unittest # internal modules: from . import util from . import cli Test_Outdated = { 'module.json':'''{ "name": "test-outdated", "version": "...
1,750
643
from django.urls import path, include from django.contrib import admin from example.views import poi_list admin.autodiscover() urlpatterns = [ path('', poi_list), path('admin/', admin.site.urls), ]
208
66
import threading import tushare as ts import pandas as pd import datetime STOCK = {#'002594':[1,170.15], ## 比亚迪 / 几手,成本价 '601012':[11,99.9], ## 隆基股份 '002340':[12,8.72], ## 格林美 '603259':[1,141.7], ## 药明康德 '002346':[10,10.68], ## 柘中股份 #'600438':[9,42.96], ## ...
2,453
1,159
from datetime import datetime from statement_renamer.extractors.etrade import ETradeDateExtractor as EXTRACTOR_UNDER_TEST from statement_renamer.extractors.factory import ExtractorFactory TESTDATA = ( """ PAGE 1 OF 6 February 1, 2019 - March 31, 2019AccountNumber:####-####AccountType:ROTH IRA PAGE 5 OF ...
1,011
383
prod1 = float(input("Insira o valor do produto A: ")) prod2 = float(input("Insira o valor do produto B: ")) prod3 = float(input("Insira o valor do produto C: ")) if prod1 < prod2 and prod1 < prod3: print ("Escolha o produto A é o mais barato") elif prod2 < prod1 and prod2 < prod3: print ("Escolha o produto B é...
425
155
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator/create_python_api.py script. """Public API for tf.train.experimental namespace. """ from __future__ import print_function as _print_function import sys as _sys from tensorflow.python.training.experimental.loss_scale ...
800
222
def plot_3D_Data( self, *arg_list, is_norm=False, unit="SI", component_list=None, save_path=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, z_range=None, is_auto_ticks=True, is_auto_range=False, is_2D_view=False, is_same_s...
4,004
1,325
"""Collection of tests for :mod:`orion.plotting.backend_plotly`.""" import copy import numpy import pandas import plotly import pytest import orion.client from orion.analysis.partial_dependency_utils import partial_dependency_grid from orion.core.worker.experiment import Experiment from orion.plotting.base import ( ...
37,788
11,651
import pdb import warnings from jax import custom_vjp @custom_vjp def debug_identity(x): """ acts as identity, but inserts a pdb trace on the backwards pass """ warnings.warn('Using a module intended for debugging') return x def _debug_fwd(x): warnings.warn('Using a module intended for debu...
478
163
#!/usr/bin/env python # Some helpful links # https://docs.python.org/3/library/tkinter.html # https://www.python-course.eu/tkinter_entry_widgets.php import tkinter as tk class Application(tk.Frame): def __init__(self, root=None): super().__init__(root) self.root = root ...
1,246
463
def elo(winner_rank, loser_rank, weighting): """ :param winner: The Player that won the match. :param loser: The Player that lost the match. :param weighting: The weighting factor to suit your comp. :return: (winner_new_rank, loser_new_rank) Tuple. This follows the ELO ranking method. """ ...
1,087
378
from __future__ import annotations from typing import Any, Callable, Optional, Union import numpy as np # import pandas as pd import statsmodels.api as sm from samplics.estimation.expansion import TaylorEstimator from samplics.utils.formats import dict_to_dataframe, fpc_as_dict, numpy_array, remove_nans from sampli...
3,766
1,335
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `scopes` package.""" import os print(os.getenv('PYTHONPATH')) import pytest from click.testing import CliRunner from scopes.tasks import tasks, bolt, spout, builder from scopes.graph import G, build, topological_sort, traverse from scopes import cli @py...
2,563
969
# -*- coding: utf-8 -*- __author__ = 'isee15' import LunarSolarConverter converter = LunarSolarConverter.LunarSolarConverter() def LunarToSolar(year, month, day, isleap = False): lunar = LunarSolarConverter.Lunar(year, month, day, isleap) solar = converter.LunarToSolar(lunar) return (solar.solarYear, sol...
1,055
414
# Copyright (c) 2021, NVIDIA CORPORATION. # # 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...
4,345
1,329
# MIT License # Copyright (c) 2020-2021 Chris Farris (https://www.chrisfarris.com) # 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 righ...
4,220
1,332
""" State-Value Function Written by Patrick Coady (pat-coady.github.io) Modified by Tin-Yin Lai (wu6u3) into asynchronous version """ import tensorflow as tf import numpy as np from sklearn.utils import shuffle #import os class NNValueFunction(object): """ NN-based state-value function """ def __init__(self...
9,088
3,039
"""mdepub actions -- these modules do the actual work.""" import archive import clean import create import epub import extract import html import newid import version
168
43
from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.decorators.cache import never_cache from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from...
10,439
2,844
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from collections import defaultdict from typing import List, Optional, Iterable, Dict import base62 from sqlalchemy import select, and_ from sqlalchemy.dialects.mysql import insert as mysql_insert from epicteller.core.model.character import Character from epi...
6,977
2,143
#! -*- coding:utf-8 -*- # 情感分类例子,RoPE相对位置编码 # 官方项目:https://github.com/ZhuiyiTechnology/roformer-v2 # pytorch参考项目:https://github.com/JunnYu/RoFormer_pytorch from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding, Call...
4,313
1,654
# Copyright 2014-2018 The PySCF Developers. 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 appl...
1,217
424