content stringlengths 5 1.05M |
|---|
from cardboard import types
from cardboard.ability import (
AbilityNotImplemented, spell, activated, triggered, static
)
from cardboard.cards import card, common, keywords, match
@card("Lifespinner")
def lifespinner(card, abilities):
def lifespinner():
return AbilityNotImplemented
return lifespi... |
import subprocess
import requests
import spacy
import sys
import json
import os
import glob
import geocoder
from fuzzywuzzy import process, fuzz
from sklearn.cluster import AgglomerativeClustering
import numpy as np
ACCEPTED_TAGS = ["GPE", "LOC"]
CMD_TEMPLATE = "./runGeoParse.sh"
GEONAME_URL = "http://api.geonames.org... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from unittest import TestCase
from auror_azkaban_jobtype_{{cookiecutter.project_name.lower()}}.v2.params import {{cookiecutter.project_name}}
class {{cookiecutter.project_name}}ParamsTest(TestCase):
def test_example(self):
self.assertEqual("true", "true") |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manag... |
"API Datasets resource."
import http.client
import flask
import flask_cors
from datagraphics.datasets import (get_datasets_public,
get_datasets_all,
get_datasets_owner,
get_datasets_editor)
import datagraphics.us... |
# -*- coding: utf-8 -*-
# Imports
import numpy as np
import vtk
def read_vti(fname):
reader = vtk.vtkXMLPImageDataReader()
reader.SetFileName(fname)
reader.Update()
data = reader.GetOutput()
pointData = data.GetPointData()
sh = data.GetDimensions()[::-1]
ndims = len(sh)
# get vector field
v = np.array(poi... |
# PGD code, generic
import time
import pandas as pd
import numpy as np
from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm
pd.options.display.precision = 2
pd.set_option('display.precision', 2)
np.random.seed(42)
df_b = pd.read_excel('data_10PQ.xlsx', sheet_name="buses")
df_l = pd.read_excel('d... |
#Execute configuration commands and save configuration
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '192.168.100.20',
'username': 'admin',
'password': 'cisco',
'port' : 22, # optional, defaults to 22
}
#Establish an SSH connection to the device
net... |
# Tai Sakuma <tai.sakuma@gmail.com>
from ..progressbar import ProgressReport
##__________________________________________________________________||
class EventLoopProgressReportWriter(object):
"""A progress report writer of an event loop
"""
def __repr__(self):
return '{}()'.format(
se... |
from analyze.calc_run import *
# burst mode
d=-5 # delay
base = 'G:/Prive/MIJN-Documenten/TU/62-Stage/20180131-compare/'
# run 1 and 2 are only spectra, no waveforms.
calc_run(base + 'run1',
REACTOR_GLASS_SHORT_QUAD,
meas=SHORT_MEAS_LEN,
scope_dir=None,
)
calc_run(base + 'run2',
... |
import faker.config
from django.conf import settings
from elasticsearch.helpers.test import get_test_client
from elasticsearch_dsl.connections import add_connection
from pytest import fixture
from rest_framework.test import APIClient
from connections.tests.factories import ApartmentMinimalFactory
faker.config.DEFAULT... |
from .time_utils import *
from .printing import *
|
# -*- coding: utf-8 -*-
class DataInterface:
def __init__(self, mac_addr, ip_addr, port):
self.mac_addr = mac_addr
self.ip_addr = ip_addr
self.port = port
self.available = True
def get_ip_addr(self):
return self.ip_addr
def get_mac_addr(self):
return self... |
import os
import yaml
import segmentation_models_pytorch as smp
import torch
import argparse
import torch.nn as nn
def prepare_model(opt):
with open(opt.hyp) as f:
experiment_dict = yaml.load(f, Loader=yaml.FullLoader)
model = smp.Linknet(encoder_name=experiment_dict["model"]["name"], encoder_depth=5,... |
# -*- coding: utf-8 -*-
#
# split line with TNM codes (for clinical texts)
#
import sys, os
import re
tnm_re = re.compile("((?:c|p|yc|r)?(?:T(?:is|1(?:mi|[abc])?|2[ab]?|3|4)|N[0-3]|M(?:0|1[abc]?)))")
def split_by_tnm(txt):
return filter(lambda x: x, re.split(tnm_re, txt))
def main():
for line in sys.stdin:
... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
from algolib.graph import Undirected
from algolib.graph import Directed
from algolib.graph import DFS
from algolib.graph import BFS
from algolib.graph import bipartite
from algolib.graph import top_sort
from algolib.graph import cut_edges, cut_vertices
... |
import os
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from kayddrl.agents.base import BaseAgent
from kayddrl.comp.ounoise import OUNoise
from kayddrl.configs.default import Configs, default
from kayddrl.envs.base import BaseEnv
from kayddrl.memory imp... |
import requests
from blablacarapi.debug import Debug
from blablacarapi.api_exceptions import BlaBlaCarRequestApiException
__author__ = 'ivan.arar@gmail.com'
def bind_request(**request_data):
class ApiRequest(object):
model = request_data.get('model')
api_path = request_data.get('api_path')
... |
import mysql.connector
class UseDataBase:
#This is a constructor
def __init__(self, config: dict) -> None:
self.configuration = config
def __enter__(self) -> 'cursor':
try:
self.conn = mysql.connector.connect(**self.configuration)
self.cursor = self.conn.cursor()... |
#!/usr/bin/env python3
"""
This script allows you to manually control the simulator
using the keyboard arrows.
"""
import sys
import argparse
import pyglet
import math
from pyglet.window import key
from pyglet import clock
import numpy as np
import gym
import gym_miniworld
import csv
parser = argparse.ArgumentParser... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Functions for working with i3cols versions of I3Particle (I3PARTICLE_T) and
I3MCTree (FLAT_PARTICLE_T).
See dataclasses/private/dataclasses/physics/I3MCTreePhysicsLibrary.cxx
and dataclasses/private/dataclasses/physics/I3Particle.cxx
"""
from __future__ import abso... |
#!/usr/bin/env python
# BUSCO_phylogenomics.py
# 2019 Jamie McGowan <jamie.mcgowan@mu.ie>
#
# Utility script to construct species phylogenies using BUSCO results.
# Can perform ML supermatrix or generate datasets for supertree methods.
# Works directly from BUSCO output, as long as the same BUSCO dataset
# has been us... |
print("""
086) Crie um programa que crie uma matriz de dimensão 3x3 e preencha
com valores lidos pelo teclado. No final, mostre a matriz na tela com
a formatação correta.
""")
tamanhoDaMatriz = 3
matriz = []
saida = ''
titulo = f' Usando números inteiros preencha \
a matriz {tamanhoDaMatriz}x{tamanhoDaMatriz} a seguir... |
# Generated by Django 2.2.13 on 2021-11-18 13:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('i_rorelse', '0017_remove_story_media_container_height'),
]
operations = [
migrations.RemoveField(
model_name='story',
name=... |
# Generated by Django 3.0.7 on 2020-06-05 04:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coleta', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='point',
name='image',
fiel... |
# -*- coding: utf-8 -*-
"""
@author: Hugh Bird
@copyright Copyright 2016, Hugh Bird
@lisence: MIT
@status: alpha
"""
import Elements as Elements
import numpy as np
class ElemMesh:
def __init__(self):
self.nodes = {}
self.elems = {}
self.nodes_in_physical_groups = {}
... |
# -*- coding: utf-8 -*-
import scrapy
import datetime
from cmccb2b.items import BidNoticeItem
from scrapy.exceptions import NotSupported, CloseSpider
from cmccb2b.utils.html2text import filter_tags
class BidNoticeSpider(scrapy.Spider):
name = 'BidNotice'
domain = 'https://b2b.10086.cn'
# Bug102: 2019.5.... |
from flask import render_template,request,redirect,url_for,abort
from . import main
from ..models import User,Pitches,Comments,Upvote,Downvote
from flask_login import login_required,current_user
from .forms import UpdateProfile,PitchForm,CommentsForm
from .. import db,photos
from ..search import get_pitches,get_pitch
... |
import torch
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import uuid
import os, time, json, pickle
import argparse
from networks.openpose import OpenPoseNet
from utils.decode import decode_pose
from utils.transform import transform
def load_weight(net, filename="./m... |
import numpy as np
from config import ERASE_FACTOR
from loggers import logger_her
class Buffer:
"""
Experience replay buffer
"""
factor = ERASE_FACTOR
def __init__(self, size):
self.max_size = size
self.data = []
@property
def size(self):
return len(self.data... |
import math
import torch
import torch.nn as nn
class TrimmedConv(nn.Module):
def __init__(self,
in_features,
out_features,
bias=False,
tperc=0.45):
super().__init__()
self.in_features = in_features
self.out_... |
# SPDX-FileCopyrightText: Fondazione Istituto Italiano di Tecnologia
# SPDX-License-Identifier: BSD-3-Clause
import os
import json
import matplotlib.pyplot as plt
# =============
# CONFIGURATION
# =============
# Path to the data for regenerating Fig.8 in the paper
data_path = "../datasets/inference/fig_8_blending_c... |
#! /usr/bin/python
import sys
from string import split
import numpy as np
#------------------------FL_image.py--------------------
#------Jennifer S. Sims, Columbia University, 2016------
# This program can be run on any histogram exported from Photoshop and transposed such that Col0=numerals 0-255 representi... |
import json
import random
def get_random_object_type() -> str:
with open('/app/resources/object_types.json', 'r') as f_in:
return random.choice(json.load(f_in))
|
"""
RiscEmu (c) 2021 Anton Lydike
SPDX-License-Identifier: MIT
"""
from .Config import RunConfig
from .helpers import *
from collections import defaultdict
from .Exceptions import InvalidRegisterException
class Registers:
"""
Represents a bunch of registers
"""
def __init__(self, conf: RunConfig):
... |
def load(h):
return ({'abbr': 129, 'code': 129, 'title': 'Z Geopotential', 'units': 'm**2 s**-2'},
{'abbr': 130, 'code': 130, 'title': 'T Temperature', 'units': 'K'},
{'abbr': 131,
'code': 131,
'title': 'U U component of wind',
'units': 'm s**-1'},
... |
import pdb
import numpy as np
from cvxopt import spmatrix, matrix, solvers
from numpy import linalg as la
from scipy import linalg
from scipy import sparse
from cvxopt.solvers import qp
import datetime
from Utilities import Curvature
from numpy import hstack, inf, ones
from scipy.sparse import vstack
# from osqp import... |
# -*- coding: utf-8 -*-
from functools import total_ordering
@total_ordering
class Metric:
"""A Metric object to represent evaluation metrics.
Arguments:
name(str): A name for the metric that will be kept internally
after upper-casing
score(float): A floating point score
d... |
def validate_npi(npi):
valid = False # assume in the beginning that number hasn't been validated
data_type = type(npi)
# check what datatype npi is
if data_type is str:
# parameter is a string
# check if it has 10 characters
if len(npi) == 10:
# number has the valid ... |
import numpy as np
from scipy.sparse import issparse
from sklearn.utils import sparsefuncs
import anndata
from typing import Union
from ..dynamo_logger import LoggerManager, main_tqdm
from ..utils import copy_adata
def lambda_correction(
adata: anndata.AnnData,
lambda_key: str = "lambda",
inplace: bool = ... |
# Standard scale crop flip, scale is important
train_augmentation = dict(
name='Compose',
transforms=[
dict(
name='ToTensor'
),
dict(
name='RandomScale',
min_scale=0.5,
max_scale=1.5
),
dict(
name='RandomCrop',
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-21 18:59
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('openid_provider', '0007_client'),
]
operations = [
migrations.RemoveField(
model_name='accesstoken',
... |
"""added guild_id column to reminders table
Revision ID: 97d93ee5aec8
Revises: 213b2c97361f
Create Date: 2021-09-19 14:22:15.752826
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '97d93ee5aec8'
down_revision = '213b2c97361f'
branch_labels = None
depends_on = N... |
# This is a sample macro file with a single command. When NatSpeak has the
# focus, say "demo sample one". It should recognize the command and print it.
import natlink
from natlinkutils import *
class ThisGrammar(GrammarBase):
gramSpec = """
<start> exported = demo sample one;
"""
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import urlparse
import re
### M3U8 Tag
TAG_PREFIX = '#EXT'
PLAYLIST_HEADER = '#EXTM3U'
TAG_ENDLIST = '#EXT-X-ENDLIST'
TAG_KEY = '#EXT-X-KEY'
TAG_MEDIA_DURATION = "#EXTINF";
TAG_STREAM_INF = '#EXT-X-STREAM-INF'
TAG_DISCONTINUITY = '#EXT-X-DISCONTINUITY'
### M3... |
import sys,os
import numpy as np
def divide_into_states(st_dur, fn_dur, num_states):
state_dur = np.zeros((2, num_states), np.int64)
state_dur[0][0] = st_dur
state_dur[1][num_states-1] = fn_dur
num_of_frames = (fn_dur-st_dur)/50000
nof_each_state = num_of_frames/num_states
#if nof_each_stat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2021-07-27
# @Filename: fvc.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Optional, cast
impo... |
import logging
import os
import queue
import random
import shutil
import subprocess
import threading
import tkinter as tk
import tkinter.messagebox as tkMessageBox
import webbrowser
from pathlib import Path
from tkinter import PhotoImage, ttk
from tkinter.scrolledtext import ScrolledText
import requests
from packaging... |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2018-2020 azai/Rgveda/GolemQuant
#
# 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... |
"""
MX-Font
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
import torch
import utils
def torch_eval(val_fn):
@torch.no_grad()
def decorated(self, gen, *args, **kwargs):
gen.eval()
ret = val_fn(self, gen, *args, **kwargs)
gen.train()
return ret
return decorated
... |
from aiopoke.objects.resources.pokemon.ability import Ability
from aiopoke.objects.resources.pokemon.characteristic import Characteristic
from aiopoke.objects.resources.pokemon.egg_group import EggGroup
from aiopoke.objects.resources.pokemon.gender import Gender
from aiopoke.objects.resources.pokemon.growth_rate import... |
n = str(input('Digite um número inteiro entre 0 e 9999: ')).strip()
print('Unidade: {}'.format(n[3]))
print('Dezena: {}'.format(n[2]))
print('Centena: {}'.format(n[1]))
print('Milhar: {}'.format(n[0]))
|
def default() -> int:
"""Returns 2."""
return 2
def minimum() -> int:
"""Returns 0."""
return 0
def maximum() -> int:
"""Returns 9."""
return 9
|
from django.urls import path
from .views import RegisterView, UserEditView, PasswordChangeUserView
from django.contrib.auth import views as auth_views
urlpatterns = [
path('register/', RegisterView.as_view(), name='register'),
path('edit-profile/', UserEditView.as_view(), name='edit-profile'),
path('change... |
import numpy as np
import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
from .PwGaANLayer import MultiHeadPwGaANLayer
class SpatAttLayer(nn.Module):
def __init__(self, feat_dim, hidden_dim, num_heads, gate=False, merge='mean'):
super(SpatAttLayer, self).__init__()
self.fe... |
from .message import HerokuLogParser, ParseError
version_info = (0, 0, 4)
__version__ = '.'.join(map(str, version_info))
__author__ = 'Chris De Cairos <chris@chrisdecairos.ca>'
__all__ = [
'HerokuLogParser',
'ParseError',
'version_info',
'__version__',
'__author__'
]
|
##########################################################################
# simple example GET API calls to a local server running on localhost:8080
##########################################################################
import requests, json, time
# make a call to the route-planning function
# doc'ed at http://... |
import logging
import os
import unittest
import pandas as pd
from pandas.io.sql import DatabaseError
import psycopg2
from ml_toolkit.db_interaction.api import PostgreSQLManager
from ml_toolkit.utils.io_utl import get_decorators
print({k: v for k, v in os.environ.items() if k.startswith('POSTGRES')})
CFG = dict(user... |
'''
Created on 05-Feb-2015
@author: Asawari.Vaidya
'''
from PythonNetBanxSDK.common.DomainObject import DomainObject
class CardExpiry(DomainObject):
'''
classdocs
'''
def __init__(self, obj):
'''
Constructor
'''
# Handler dictionary
handler = dict()
ha... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import logging
import sys
from sentry_sdk import init as SentryInit
from sentry_sdk import push_scope as SentryPushScope
from sentry_sdk import capture_message as SentryCaptureMessage
from sentry_sdk import capture_exception as SentryCaptureException
from sentry_sdk import ... |
import graphene
from dagster import check
from dagster.core.snap import ConfigSchemaSnapshot, ModeDefSnap
from ..util import non_null_list
from .logger import GrapheneLogger
from .resource import GrapheneResource
class GrapheneMode(graphene.ObjectType):
id = graphene.NonNull(graphene.String)
name = graphene... |
"""
template loading helper
"""
from jinja2 import FileSystemLoader, Environment
template_engine = Environment(loader=FileSystemLoader("web/templates"))
def get_template(name):
"""get and return a template"""
return template_engine.get_template(name)
|
from audiobonsai import settings
from django.http import HttpResponse, HttpResponseRedirect
import json
from spotify_helper.helpers import get_spotipy_oauth
from spotify_helper.models import SpotifyUser
import spotipy
from spotipy import oauth2
# Create your views here.
def spotify_ask_user(request):
html = '<HT... |
#
# MIT 6.01 (Week 1)
# Design Lab 1. Problem 1.3.4: 2D vector arithmetic
# Define a Python class V2 , which represents two-dimensional vectors and
# supports the following operations:
# - Create a new vector out of two real numbers: v = V2(1.1, 2.2)
# - Convert a vector to a string (with the __str__ method)... |
# *********************************************************************************
# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions a... |
import numpy as np
import matplotlib.pyplot as plt
def V(x):
return 0.5*x*x
def numerov(E,plot=0,normalize=0,returnfi=0):
#lim=5*np.sqrt(2*E)
xmin = -8.0
xmax = 8.0
ndivide = 1000
s=(xmax-xmin)/(ndivide-1)
G = np.zeros(ndivide,dtype=np.dtype('f16'))
f = np.zeros(ndivide,dtype=np.dtype('f16'))
x = np.lins... |
#
# Uncomplicated VM Builder
# Copyright (C) 2010-2015 Canonical Ltd.
#
# See AUTHORS for list of contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016,小忆机器人
All rights reserved.
摘 要:
创 建 者:余菲
创建日期:16/12/17
"""
import json
import redis
scene_redis = redis.Redis('127.0.0.1', '6579', 0, socket_timeout=2)
class RobotScene(object):
"""
管理机器人的场景
"""
def __init__(self):
... |
import scrapy
from scrapy.loader import ItemLoader
from FiScrape.items import ZhArtItem, \
parse_to_os_tz
from FiScrape.search import query, start_date
from scrapy_splash import SplashRequest, SplashFormRequest
from itertools import count
from ln_meta_template import zh_user, zh_pass
class ZhSpider(scrapy.Spider)... |
from flask import (abort, jsonify, g, session, render_template, redirect,
request, url_for)
from manage import app#, client
from . import main
# import self written modules from modules dir
# from ..modules import ...
@main.route('/')
def index():
return render_template('index.html') |
import subprocess
import sys
import click
def _is_clean():
result = subprocess.run(
["git", "status", "--porcelain"], capture_output=True, encoding="utf-8",
)
return result.stdout.strip() == ""
@click.command()
def cmd():
"""Check that the repository is in a clean state."""
if not _is_c... |
import numpy as np
from AbstractNeuralNetwork import AbstractNeuralNetwork as ANN
class NNReluSigmoid(ANN):
def __init__(self):
super().__init__()
def findActivationImplementation(self, activation_type):
if activation_type == "sigmoid":
return self.sigmoid
elif activat... |
import pickle as pkl
import numpy as np
def parse_index_file(filename):
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def load_data(dataset):
# load feature matrix
with open('./data/{}_feats.pkl'.format(dataset), 'rb') as f1:
features = pkl... |
from actfw_raspberrypi.edid import *
from warnings import warn
warn(DeprecationWarning("actfw is DEPRECATED. Use actfw-raspberrypi instead"))
|
'''input
6
-679 -2409 -3258 3095 -3291 -4462
21630
21630
19932
8924
21630
19288
3
3 5 -1
12
8
10
5
1 1 1 2 0
4
4
4
2
4
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem C
if __name__ == '__main__':
spot_count = int(input())
spots = [0] + list(map(int, input(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import time
from threading import Thread
try:
from Queue import Queue
from BeautifulSoup import BeautifulSoup
except ImportError:
from queue import Queue
from bs4 import BeautifulSoup
from lib import END
class Wiki(Thread):
def __in... |
from itertools import product
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
import seaborn as sns
from keras import backend as K
from keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard
from keras.layers import TimeDistributed, Input, LSTM, Lambda, Dense, Reshap... |
# Find the contiguous sub-array(containing at least one number) which has the maximum sum
"""
EXAMPLE:
INPUT : [1, 2, 3, -2, 5]
OUTPUT : 9
EXPLANATION :
Because sub-array (1,2,3,-2,5) has maximum sum among all sub-array.
For example : sub-array (1,2,3) has sum 6
sub-array (... |
import os
import base64
from datetime import datetime, timedelta
from operator import attrgetter, itemgetter
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
import sqlalchemy as sa
from sqlalchemy_continuum.plugins import FlaskPlu... |
# Form implementation generated from reading ui file 'ic.ui'
#
# Created by: PyQt6 UI code generator 6.2.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_ic(obje... |
#!/usr/bin/env python
# coding=utf-8
import json
from logging import getLogger
import redis
logger = getLogger(__name__)
def get_pending_task_list():
r = redis.Redis()
raw_task_info_list = r.lrange("celery", -100, 100)
task_info_list = list()
for raw_task_info in raw_task_info_list:
j = js... |
# -*- coding: utf-8 -*-
import requests , os , time , datetime , re
from bs4 import BeautifulSoup
W = '\033[0m' # white (default)
R = '\033[1;31m' # red
G = '\033[1;32m' # green bold
O = '\033[1;33m' # orange
B = '\033[1;34m' # blue
P = '\033[1;35m' # purple
C = '\033[1;36m' # cyan
GR = '\033[1;37... |
'''
Problem Link - https://www.codechef.com/JULY20B/problems/ADAKING
'''
from sys import *
from math import *
from collections import *
mod = 1000000007
def get_array(): return list(map(int, stdin.readline().split()))
def get_ints(): return map(int, stdin.readline().split())
def get_int(): return int(stdin.readli... |
from urllib import request
import lxml
from lxml import html
import Utils as utils
import re
from data_amount import *
import data_amount as data_amount
def prune(url, browse_boolean):
"""
This function will return true when the graph should continue searching
and false when the graph should stop.
"""... |
import kaldi_io
import numpy as np
import argparse
import sys
import os
import math
if sys.version > '3':
import pickle
else:
import cPickle as pickle
from tqdm import tqdm
def ctc_len(label):
extra = 0
for i in range(len(label)-1):
if label[i] == label[i+1]:
extra += 1
return... |
# imports
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from src.visualization_description.descriptive_tool import DescribeData
update_report_figs = False
fig_path_report = '../Thesis-report/00_figures/describe_data/'
# reading data
df = pd.read_csv('data/processed/taiwanese_cr... |
import hashlib
import json
import requests
import shutil
from judge_pics import judge_pics
from dateutil import parser
from lxml import html
token = ""
if token:
headers = {"Authorization": "Token %s" % token}
else:
print(
"Warning: No CourtListener token used. You'll run out of free queries to the ... |
import argparse
import numpy as np
import pandas as pd
import re
import sys
import urllib.request
import yaml
from urllib.parse import urljoin, urlencode
from bs4 import BeautifulSoup
from transliterate import translit
"""
Check for version of Python and exit with error when version is older than 3
"""
def check_versi... |
geral = list()
nomepeso = list()
maiorpeso = list()
while True:
nomepeso.append(str(input('Nome: ')))
nomepeso.append(int(input('Peso: ')))
geral.append(nomepeso[:])
nomepeso.clear()
sn = str(input('Deseja continuar? [S/N] '))
if sn in 'Nn':
break
for c in geral:
maiorpeso.append(c[1... |
import db
def GetResourceTypeMap(vars):
# DB connections
# --------------
c = vars['core']
core_db_selector = db.Selector(c['host'], c['user'], c['password'], c['port'], c['db'])
return {x['resource_type_content']: x['resource_type_id'] for x in core_db_selector.query("SELECT * FROM resource_t... |
#!/usr/bin/python
"""
ZetCode PyQt6 tutorial
This example shows a QCalendarWidget widget.
Author: Jan Bodnar
Website: zetcode.com
"""
from PyQt6.QtWidgets import (QWidget, QCalendarWidget,
QLabel, QApplication, QVBoxLayout)
from PyQt6.QtCore import QDate
import sys
class Example(QWidget):
def __init_... |
import random
def randomFirstPanel(verib):
if (verib == 1):
Typelist = [DIK_6, DIK_7, DIK_8, DIK_9, DIK_0]
elif verib == 2:
Typelist = [DIK_1, DIK_2, DIK_3, DIK_4, DIK_5]
elif verib == 3:
Typelist = [DIK_Q, DIK_E, DIK_R, DIK_T]
elif verib == 4:
Typelist = [... |
__all__ = ['to_dt', 'Config']
import argparse
from dataclasses import dataclass
import datetime as dt
import json
import os
from pathlib import Path
from typing import Tuple, Dict, Optional, TYPE_CHECKING
import jsonschema
import numpy as np
from slim.types.TreatmentTypes import Treatment, TreatmentParams, GeneticMe... |
import unittest
from datetime import datetime
from datetime import timedelta
from smtm import MassSimulator
from unittest.mock import *
class MassSimulatorUtilTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
@patch("builtins.print")
@patch("psutil.Process")
... |
from SnakeGame import SnakeGame
import time
class Test(object):
def __init__(self):
self.game = None
def run(self):
self.game = SnakeGame(reinforcement_learning = False, population_size = 10)
self.game.train_agent(30)
self.game.test_agent(100)
#self.game.game_loop()
|
from .pconv2d_layer import myPConv2D
from .pconv2d_loss import total_loss
from keras.layers import BatchNormalization, Input
from keras.layers import ReLU, LeakyReLU, UpSampling2D, Concatenate
from keras.models import Model
from keras.optimizers import Adam
def encoder_block(input_img, input_mask, filters, kernel_size... |
import sys
from data_storing.assets.common import Timespan
from utilities.common_methods import Methods as methods
from utilities.common_methods import getDebugInfo
from data_storing.assets.common import Benchmark
import fundamentals.miscellaneous as fund_utils
from utilities.exchange_rates import Exchange
from utiliti... |
from scannerpy import Database, Job
import os.path
import glob
import argparse
from os.path import join
import pickle
import cv2
import soccer.depracated.kernels_c.resize_op.build.resize_pb2 as resize_pb2
import numpy as np
parser = argparse.ArgumentParser(description='Depth estimation using Stacked Hourglass')
parse... |
from .Fields import * |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='cabot-alert-twilio',
version='1.3.3',
description='A twilio alert plugin for Cabot by Arachnys',
author='Arachnys',
author_email='info@arachnys.org',
url='http://cabotapp.com',
packages=find_packages(),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.