text stringlengths 2 999k |
|---|
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
sum = 0
for item in student_marks[query_name]:
sum += float(item)
... |
#!/usr/bin/env python
from tkinter import *
from tkinter.messagebox import askyesno
from os.path import isfile
from time import sleep
from tkinter.filedialog import askopenfilename, asksaveasfile
class FileReader(object):
def __init__(self):
self.top = Tk()
self.top.title('new.txt')
sel... |
from django.db import migrations
from api.metadata.constants import OrganisationType
ORGANISATIONS = [
{
"name": "Attorney General's Office",
"organisation_type": OrganisationType.MINISTERIAL_DEPARTMENTS,
},
{
"name": "Cabinet Office",
"organisation_type": OrganisationType.... |
import types
import typing
from aiokraken.rest.schemas.kledger import KLedgersResponseSchema
from aiokraken.rest.schemas.ktrade import TradeResponseSchema
from aiokraken.model.timeframe import KTimeFrameModel
from aiokraken.rest.payloads import TickerPayloadSchema, AssetPayloadSchema, AssetPairPayloadSchema
from a... |
import numpy as np
import pandas as pd
import re
import urllib2
import astropy.table as astro_table
from threeML.catalogs.VirtualObservatoryCatalog import VirtualObservatoryCatalog
from threeML.exceptions.custom_exceptions import custom_warnings
from threeML.config.config import threeML_config
from threeML.io.get_hea... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
N = M = int(input())
result = 0
while True:
M = (M%10*10) + ((M//10 + M%10)%10)
result += 1
if M == N :
break
print(result) |
# administrative username and password for development
ADMIN_USERNAME = 'admin'
ADMIN_PASSWORD = 'password'
ADMIN_TYPE = 'admin'
# for production
# ADMIN_USERNAME = 'environ.get('ADMIN_USERNAME')
# ADMIN_PASSWORD = 'environ.get('ADMIN_PASSWORD')
# ADMIN_TYPE = 'environ.get('ADMIN_TYPE')
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy, math, pdb, sys, random
import time, os, itertools, shutil, importlib
from tuneThreshold import tuneThresholdfromScore
from DatasetLoader import test_dataset_loader
from torch.cuda.amp import autoc... |
import re as REGEX
from yaml import safe_load as yaml
from .dictionary import *
from .file import *
class Config:
class Element:
named_keys = []
class Local:
def __init__ ( self, _local ):
self.keywords = {}
self.names = None
if 'keyw... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator
from matplotlib import rc
from matplotlib import rcParams
font = {'family' : 'Dejavu Sans',
'weight' : 'normal',
'size' : 22}
rc('font', **font)
rcParams['lines.... |
import asyncio
import json
import click
from kubernetes import client, config
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
result = proc.return... |
# Copyright 2021 The Cirq Developers
#
# 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 applicable law or agreed to in ... |
""" exceptions for functions """
class FunctionsException(Exception):
""" main exception """
def __init__(self, message):
self.message = message
class ObjdumpFailure(FunctionsException):
""" objdump does't work """
def __init__(self, message):
self.message = message
class NoSectionEr... |
def sublist(list1, list2):
size_list1 = len(list1)
size_list2 = len(list2)
is_sublist = False
counter = 0
indx2 = 0
temp_indx2 = 0
while indx2 < size_list2:
indx1 = 0
if list2[indx2] == list1[indx1]:
temp_indx2 = indx2
indx1 += 1
temp_indx2 += 1
counter += 1
while indx1 < size_list1 and te... |
"""Package setup."""
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="scrivo",
version="0.0.2",
author="Tom Shafer",
author_email="contact@tshafer.com",
description="A static website generator.",
long_description=long_... |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from valid_switch import _schema
class TestValidSwitch(unittest.TestCase):
def test_valid_switch(self):
r = _schema.parse_file('src/fixed_struct.bin')
|
from flask import Flask
from environs import Env
from app import routes
from app.configs import database, migrations, cors
from app.default import default_types_users, default_client, default_types_sales
env = Env()
env.read_env()
def create_app():
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
import sys
from typing import List, Optional
from sharpy.constants import Constants
from sharpy.interfaces import IZoneManager
from sharpy.knowledges import Knowledge
from sharpy.managers.core.roles import UnitTask
from sharpy.plans.acts import ActBase
from sharpy.sc2math import points_on_circumference_sorted
from sha... |
from django.contrib import admin
from .models import Contact
class ContactAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'listing', 'email', 'contact_date')
list_display_links = ('id', 'name', 'listing')
search_fields = ('name', 'email', 'listing')
list_per_page = 25
admin.site.register(Cont... |
import model
import dataset
import cv2
from trainer import Trainer
import os
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import numpy as np
from PIL import Image
from skimage.io import imsave
from imageio import get_writer
os.environ['CUDA_VISIB... |
# -*- coding: utf-8 -*-
description = 'Detector data acquisition setup'
group = 'lowlevel'
display_order = 10
includes = ['counter']
excludes = ['virtual_daq']
sysconfig = dict(
datasinks = ['yamlformat', 'binaryformat'],
)
tango_base = 'tango://phys.kws3.frm2:10000/kws3/'
basename = (
'%(pointcounter)08d_... |
#
# 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 us... |
""" Module responsibles to communicate with Wenet profile manager, to fill the profiles with
the routines
Copyright (c) 2021 Idiap Research Institute, https://www.idiap.ch/
Written by William Droz <william.droz@idiap.ch>,
"""
import datetime
import json
from collections import defaultdict
from dataclasses import ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ss = ''
result = 0
for i in s:
if i not in ss:
ss += i
else:
result = len(ss) if len(ss) > result else result
ss = ss[ss.index(i)+1:len(ss)]+i
re... |
from urllib.parse import parse_qs, urlparse
def extract_video_id(url):
# Source: https://stackoverflow.com/a/54383711
# Examples:
# - http://youtu.be/nNpvWBuTfrc
# - http://www.youtube.com/watch?v=nNpvWBuTfrc&feature=feedu
# - http://www.youtube.com/embed/nNpvWBuTfrc
# - http://www.youtube.com... |
import binascii
import csv
import hashlib
import hmac
import json
import logging
import os
import time
from base64 import b64decode, b64encode
from http import HTTPStatus
from json.decoder import JSONDecodeError
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optiona... |
"""a Python software that gets basic information about an MCPE server
Packet class
Copyright (c) 2016 w-gao
"""
import struct
class Packet:
def __init__(self):
self.offset = 0
self.buffer = b''
def encode(self):
pass
def decode(self):
self.offset = 0
def read(self... |
# Copyright 2021 Google LLC
#
# 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, ... |
try:
from contextlib import redirect_stdout
except ImportError:
import sys
# noqa # redirect_stdout was introduced in Python 3.4
class _RedirectStream:
"""
Copied from Python 3.5's implementation. See:
https://github.com/python/cpython/commit/83935e76e35cf8d2fb9fe25994... |
# Copyright 2015 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... |
import subprocess
import sys
import time
from flask_unchained.cli import cli
@cli.group()
def celery():
"""
Celery commands.
"""
@celery.command()
def worker():
"""
Start the celery worker.
"""
_run_until_killed('celery worker -A celery_app.celery -l debug',
'celer... |
"""Test that C functions used in primitives are declared in a header such as CPy.h."""
import glob
import os
import re
import unittest
from mypyc.primitives import registry
from mypyc.primitives.registry import CFunctionDescription
class TestHeaderInclusion(unittest.TestCase):
def test_primitives_included_in_he... |
"""
Train the MobileNet V2 model
"""
import os
import sys
import argparse
import pandas as pd
#from mobilenet_v2 import MobileNetv2
from densemobilenet import DenseNet
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import EarlyStopping
from keras.layers... |
from django.apps import AppConfig
class Rest_user_profilesConfig(AppConfig):
name = 'rest_user_profiles'
|
# Generated by Django 3.0.4 on 2021-04-14 21:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content_management', '0019_auto_20210409_1129'),
]
operations = [
migrations.AlterField(
model_name='content',
name=... |
from sklearn.metrics import accuracy_score
import numpy as np
class Ensemble:
def __init__(self, model_preds, ytest=None):
self.ytest = ytest
self.model_preds = model_preds
self.preds = np.array(self._get_predictions())
if self.ytest is not None:
self.acc = accuracy_sco... |
"""
.. module:: gt.procs
:platform: Unix, Windows
:synopsis: Graph-talk file processor classes
.. moduleauthor:: Stas Kravets (krvss) <stas.kravets@gmail.com>
"""
from gt.core import *
class FileProcessor(Process):
"""
File processor contains the graph and the parsing process to parse the file conten... |
from random import choice
class RandomizedSet():
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {}
self.list = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not al... |
"""
@brief: Solve the joints (states) via inverse dynmaics from a list of 2d
frames
@input:
expert_2d_poses
dynamics_model (inverse_dynamics, forward_dynamics)
@output:
qpos, camera_state
@author: Tingwu Wang
@Date: Jan 15, 2019
"""
# from pyquaternion import Quater... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cidonkey', '0002_auto_20140930_2005'),
]
operations = [
migrations.RemoveField(
model_name='buildinfo',
... |
from django.apps import AppConfig
class InstaDeepConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'insta_deep'
|
# Bibliotecas para manuseio dos dados
import pandas as pd
import numpy as np
# datasheet
dataset = pd.read_csv("parametros_ssinal_trasformed.csv", encoding='utf8',
delimiter=';', engine='python')
dataset['Data de Amostragem'] = pd.to_datetime(dataset['Data de Amostragem'])
print(dataset.columns... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from gluon import current
from gluon.html import *
from gluon.storage import Storage
from s3 import ICON, S3DataListLayout, s3_unicode, S3SQLSubFormLayout
def config(settings):
"""
Template settings for Community Resilience Mapping Tool
... |
"""
Simple check list from AllenNLP repo: https://github.com/allenai/allennlp/blob/master/setup.py
To create the package for pypi.
1. Change the version in __init__.py and setup.py.
2. Commit these changes with the message: "Release: VERSION"
3. Add a tag in git to mark the release: "git tag VERSION -m'Add... |
'''Submódulo IBGE contendo os wrappers das APIs do IBGE Cidades.
Este submódulo é importado automaticamente com o módulo `ibge`.
>>> from DadosAbertosBrasil import ibge
Fonte
-----
https://cidades.ibge.gov.br/
'''
from typing import Union
from DadosAbertosBrasil._utils import parse
from DadosAbertosBrasil._utils.g... |
class Config():
@staticmethod
def parse_file(file_name):
config = {}
for line in open(file_name):
line = line.strip()
if line and line[0] is not "#":
var,value = line.split('=', 1)
config[var.strip()] = value.strip()
return config
|
"""cub specific copts.
This file simply selects the correct options from the generated files. To
change Abseil copts, edit cub/copts/copts.py
"""
load(
"//cub:copts/GENERATED_copts.bzl",
"CUB_GCC_EXCEPTIONS_FLAGS",
"CUB_GCC_FLAGS",
"CUB_GCC_TEST_FLAGS",
"CUB_LLVM_EXCEPTIONS_FLAGS",
"CUB_LLVM_... |
# coding:utf-8
import os
import pathlib
import numpy as np
import pandas as pd
import lightgbm as lgb
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.loggers import WandbLogger
from DNNmodel import *
from utils import *
... |
#!/usr/bin/env python3
"""
This module contains functions to work with simple paths.
"""
import networkx as nx
def find_simple_paths(graph, s_node, t_node):
""" Find all simple paths in the graph G from source to target.
Args:
graph (obj): networkx graph object
s_node (node): Starting node fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# collect a set of trip_id s at all stops in a GTFS file over the selected week of the service period starting at serviceweekstartdate
# filter stops near trainstations based on input txt file - stopsneartrainstop_post_edit
# merge sets of trips at stops near each trainstat... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
from django.urls import path, include
from .views import IndexView
urlpatterns = [
path('members/', include('members.urls')),
path('events/', include('events.urls')),
path('blog/', include('blog.urls')),
path('', IndexView.as_view(),
name='index'),
]
|
import random
import os,subprocess
import requests
from bs4 import BeautifulSoup
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; ... |
import pytest
import ptf.testutils as testutils
from ipaddress import ip_address
import logging
import json
from tests.common.fixtures.ptfhost_utils import change_mac_addresses # lgtm[py/unused-import]
from tests.common.fixtures.ptfhost_utils import remove_ip_addresses # lgtm[py/unused-import]
DEFAULT_HLIM... |
# 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 applicab... |
# Copyright (c) Hadrien Chauvin
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Example individual repos for end-to-end tests. This file
is sourced by the CLI and by `e2e_test.py` directly.
"""
from monorepo_tools.import_into import Indiv... |
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
install('beautifulsoup4')
|
# -*- coding: utf-8 -*-
"""
Module to store containers.
"""
from __future__ import absolute_import, unicode_literals
import logging
from abc import ABCMeta, abstractmethod
from maya import cmds
from maya.api import OpenMaya as api
from mampy.core.components import SingleIndexComponent
from mampy.core.dagnodes impor... |
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd.
# 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/LI... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
# This file is generated by objective.metadata
#
# Last update: Sun Aug 4 20:58:09 2019
#
# flake8: noqa
import sys
import objc
if sys.maxsize > 2 ** 32:
def sel32or64(a, b):
return b
else:
def sel32or64(a, b):
return a
misc = {}
misc.update(
{
"SizeResourceRec": objc.creat... |
# 打印输出从文件读取的所有行的字符串(readlines方法)
f = open('hello.txt') # 打开(文本+读取模式)
lines = f.readlines()
for line in lines:
print(line, end='')
f.close() # 关闭
|
import turtle
def main():
trtl = turtle.Turtle()
trtl.hideturtle()
trtl.screen.colormode(255)
trtl.pencolor(0, 0, 255)
trtl.pensize(2)
trtl.speed(0)
fractal_level = int(input("Enter The Fractal Level You Want To Get :\t"))
trtl_position_x, trtl_position_y = 0, 150
if fractal_l... |
import webbrowser
import requests
print("Let's find an old website.")
site = input("Type a website URL: ")
era = input("Type a year, month, and day, like 20150613: ")
url = "http://archive.org/wayback/available?url=%s×tamp=%s" % (site, era)
response = requests.get(url)
data = response.json()
try :
old_site = ... |
# -*- coding: utf-8 -*-
#/usr/bin/python2
'''
Borrowed
from https://github.com/keithito/tacotron/blob/master/text/numbers.py
By kyubyong park. kbpark.linguist@gmail.com.
https://www.github.com/kyubyong/g2p
'''
from __future__ import print_function
import inflect
import re
_inflect = inflect.engine()
_comma_number_re =... |
# Map Code:
# https://www.kaggle.com/txp142130/utd-crimes-in-chicago-with-choropleth-map
#
# Code and Logic:
# CraftingGamerTom (Thomas Rokicki)
df_crime = crimes
# --------------------------------------------------
# ----- Read in Crime Types with weighted values
# -----------------------------------------------... |
from novaclient.v1_1 import client
import prettytable
import sys
import uuid
import datetime
import getpass
import os
import pdb
from novaclient import exceptions
from novaclient import utils
from novaclient.v1_1 import servers
def do_list(cs, args):
#pdb.set_trace()
return cs.images.list()
def retriev... |
# coding: utf-8
"""
Engine api
Engine APIs # noqa: E501
OpenAPI spec version: 1.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import vtpl_api
from vtpl_api.models.track_properties import TrackProperties # noqa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-01-06 16:57
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0026_auto_20170106_1856'),
]
operations = [
migra... |
from sql.Instrucciones.TablaSimbolos.Instruccion import Instruccion
from sql.storageManager.jsonMode import *
from sql.Instrucciones.Sql_select.OrderBy import OrderBy
from sql.Instrucciones.Sql_select.GroupBy import GroupBy
from sql.Instrucciones.Sql_select.Having import Having
from sql.Instrucciones.Sql_select.Limit i... |
import os
import shlex
import subprocess
import parse
import time
import argparse
def parse_imdb(choice):
src_dir = "../texts/IMDB/preprocessed/{}"
log_dir = "imdb_failed_{}.log".format(choice)
choice = choice.replace("_", "/")
assert choice in [
"test/pos", "test/neg", "train/pos", "train/... |
import cv2
import numpy as np
point = []
cropping = False
"""
https://www.pyimagesearch.com/2015/03/09/capturing-mouse-click-events-with-python-and-opencv/
"""
def clickCallback(event,x,y,flags,param):
global point, cropping
if event == cv2.EVENT_LBUTTONDOWN:
point = [(x,y)]
cropping = True
... |
"""Monte Carlo View"""
__docformat__ = "numpy"
from typing import Union
import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from gamestonk_terminal.common.prediction_techniques import mc_model
from gamestonk_terminal.helper_funcs im... |
import spotipy
import configparser
import os
from spotipy.oauth2 import SpotifyOAuth
class Controller:
def __init__(self, config:object):
"""Initiazlization for Controller object
Args:
config (object): configuration object
""" ''''''
self.config = config
... |
from . import db,login_manager
from datetime import datetime
from flask_login import UserMixin,current_user
from werkzeug.security import generate_password_hash,check_password_hash
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
username = db.Column(d... |
"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
from sympy import Matrix, I, Expr, Integer
from sympy.matrices import matrices
from sympy.core.compatibility import all
__all__ = [
'numpy_ndarray',
'scipy_sparse_matrix',
'sympy_to_numpy',
'sympy_to_scipy_sparse',
'numpy_to_sympy'... |
#! /usr/bin/python3
import sys
def main():
formulas = {}
with open(sys.argv[1], "r") as f:
for line in f:
elems = line.split(':')
ray = elems[1].strip()
ref = float(elems[-2].strip())
ours = float(elems[-1].strip())
if not ray in formulas:
... |
from agents.agent import Agent
from models.actor_critic_mlp import ActorCriticMLP
import numpy as np
import torch
import torch.optim as optim
from utils import plot_grad_flow
class A2C(Agent):
def __init__(
self,
state_size,
action_size,
hidden_size,
memory,
lr,
... |
"""
Module: 're' on pyboard 1.13.0-95
"""
# MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG')
# Stubber: 1.3.4 - updated
from typing import Any
def compile(*args) -> Any:
pass
def match(*args) -> Any:
pass
def se... |
import os
import sys
import ast
import json
import types
import collections
import reflectutils
def getclass(obj):
"""
Unfortunately for old-style classes, type(x) returns types.InstanceType. But x.__class__
gives us what we want.
"""
return getattr(obj, "__class__", type(obj))
NameEvaluation =... |
import pandas as pd
def load_dataset(dir_path):
data = dict()
data["aka_name"] = pd.read_csv(dir_path + '/aka_name.csv', header=None)
data["aka_title"] = pd.read_csv(dir_path + '/aka_title.csv', header=None)
data["cast_info"] = pd.read_csv(dir_path + '/cast_info.csv', header=None)
data["char_name"]... |
# 给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
# '.' 匹配任意单个字符
# '*' 匹配零个或多个前面的那一个元素
# 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
# 0 <= s.length <= 20
# 0 <= p.length <= 30
# s 可能为空,且只包含从 a-z 的小写字母。
# p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
# 保证每次出现字符 * 时,前面都匹配到有效的字符
# --------------
# ***... |
import firebase_admin
import jsonpickle as jsonpickle
from firebase_admin import credentials, firestore
from doc_lms.settings import firebase_admin_config_credentials
cred = credentials.Certificate(jsonpickle.encode(firebase_admin_config_credentials))
firebase_admin.initialize_app(cred)
db = firestore.client()
|
import argparse
import time
import math
import numpy as np
import torch
import torch.nn as nn
import data
import model as model_module
from utils import batchify, get_batch, repackage_hidden
parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model')
parser.add_argument('--data', typ... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
#!/usr/bin/python
# ignore frivolous warnings
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
# get the model and the data reorganization
from custom import Data_Obj
from custom import data_func
from custom import train_... |
#!/usr/bin/env python
## -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 ... |
"""
module(matplotlib_utils) - matplotlib绘图工具类.
Main members:
# set_figsize - 设置图片显示尺寸.
# show_x_y_axis - 显示x、y坐标系.
# show_image - 显示图片.
# show_image_augmentation - 显示图片增强.
"""
import pylab
# from IPython import display
from PIL import Image
from matplotlib import ... |
'''
Remove X
Given a string, compute recursively a new string where all 'x' chars have been removed.
Input format :
String S
Output format :
Modified String
Constraints :
1 <= |S| <= 10^3
where |S| represents the length of string S.
Sample Input 1 :
xaxb
Sample Output 1:
ab
Sample Input 2 :
abc
Sample Output 2... |
from mpf.tests.MpfGameTestCase import MpfGameTestCase
from unittest.mock import MagicMock
from mpf.tests.MpfTestCase import test_config
class TestBallSearch(MpfGameTestCase):
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/ball_search/... |
import math
print("helloxxxxxxxxxxxx")
def bisection(
function, a, b
): # finds where the function becomes 0 in [a,b] using bolzano
start = a
end = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
fu... |
import verOrigin
import gameover
import verItem
import setGame
import settings
import loading
import game
if __name__ == '__main__':
game.MainMenu.init()
while settings.state != "quit":
if(settings.state == "gameSetting"):
print("state : set")
setGame.SetGame.gameSet()
i... |
"""
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 ... |
from types import CacheItem, CacheProvider
class MemoryCache:
data = {}
def readCache(filename: str):
cacheData = {}
cacheData = MemoryCache.data[filename]
return cacheData
def writeCache(filename: str, data: CacheItem):
MemoryCache.data[filename] = data
return True
class MemoryCacheProvid... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 14:32:40 2021
@author: doudou
"""
actions = ["add","subtract","multiply","divide","log","sqrt","factorial","gcd","lcm","power","max","min"
,"reminder","reminder","negate","inverse","round","floor","sine","cosine","tangent","radians_to_degree","degree_to_radians"
]
o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.