content stringlengths 5 1.05M |
|---|
from typing import List
from apscheduler.schedulers.twisted import TwistedScheduler
from twisted.words.protocols import irc
from twisted.internet import reactor, threads, task
from loguru import logger
from bot.config import (
BOT_NICKNAME, CLIENT_ID, BOT_AUTH_TOKEN,
WS_HOST, WS_PORT
)
from bot.twitch_bot imp... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
def isPalindrome(number):
return str(number) == str(number)[::-1]
set = set()
for firstnumber in range(999,900, -1):
for secondnumber in range(999,900, -1):
set.add(firstnumber*secondnumber)
for element in set:
if(isPalindrome(element)):
print(element)
|
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
class UserSerializer(serializers.ModelSerializer):
"""User serializer"""
password2 = serializers.CharField(write_only=True,
style... |
# GLOVAR.PY
import os
# FUNCTION DEFINATION
# initialize variable
def _init():
global global_files
global_files = []
# add cppfiles
def add_files(cxxfile):
for filename in cxxfile:
fullDir = os.getcwd() + '/' + filename
# relPath = os.path.relpath(fullDir, root_path)
global_files.append(fullDir)
# return va... |
from io import BytesIO
from PIL import Image
def dummy_image(
filename='dummy.png', size=(100, 100), color='white', mode='RGB'
):
"""Creates single color dummy image"""
im = Image.new(mode, size, color)
blob = BytesIO()
file_format = 'png' if filename.endswith('png') else 'jpeg'
im.save(blob,... |
# ==========================================================================
#
# Copyright NumFOCUS
#
# 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... |
from gi.repository import Gtk as g,GdkPixbuf,Wnck, Gio
import psutil as ps
from time import time,sleep,ctime
import re,os,signal,sys
from math import pow
from csv import writer
try:
from filter_prefs import filter_process_matching_func
except ImportError:
from sysmontask.filter_prefs import filter_process_matc... |
import hashlib
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http.response import Http404
from django.shortcuts import render
from django.utils import timezone
from django.utils.translation import ugettext as _
from rr.forms.testuser import Te... |
#/usr/bin/env python3
import socket
from OpenSSL import SSL, crypto
import requests
import OpenSSL
import asn1crypto
import cert_human
methods = [
'SSLv23_METHOD',
'SSLv2_METHOD',
'SSLv3_METHOD',
'TLSv1_1_METHOD',
'TLSv1_2_METHOD',
'TLSv1_METHOD']
# openssl s_client -servername <server_name>... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 10:52:19 2017
@author: jkcm
"""
import pickle
import os
import re
import datetime as dt
import xarray as xr
import numpy as np
import glob
import netCDF4 as nc4
import sys
sys.path.insert(0, '/home/disk/p/jkcm/Code')
from Lagrangian_CSET import ut... |
from util import hook
import random, os, re, math
from collections import Counter
# The max chain length determines the maximum complexity of markov chains formed
# during word analysis. Larger numbers will cause more realistic chains to be formed, provided
# enough text, but will slow down analysis and message gene... |
"""
[Fast Sort](https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/fast-sort-1/)
PROBLEM STATEMENT
Points: 30
From the childhood we are taught that a comes before b then b comes before c and so on.So whenever we try to sort any
given string we sort it in that ... |
import torch as t
import torch.nn as nn
from components.sequence.LSTM import BiLstmEncoder
class RelationNet(nn.Module):
def __init__(self,
pretrained_matrix,
embed_size,
hidden=128,
layer_num=1,
self_attention=False,
... |
import factory
from factory import Faker
from factory.django import DjangoModelFactory
from ..models import Agency, Correspondence, RecordRequest, RecordRequestFile
class AgencyFactory(DjangoModelFactory):
class Meta:
model = Agency
name = Faker("company")
class RecordRequestFactory(DjangoModelFac... |
from enum import Enum
class PerformanceMetric(Enum):
OVERALL_PERFORMANCE = "OVERALL_PERFORMANCE"
DELTA = "DELTA"
@staticmethod
def from_string(value: str):
if isinstance(value, str):
for entry in PerformanceMetric:
if value.upper() == entry.value:
... |
class Node:
def __init__(self, data, depth=1):
self.data = data
self.left = None
self.right = None
self.depth = depth
def insert(self, arr):
leftNode = rightNode = None
left, right = arr
if left != -1:
leftNode = Node(left, self.depth+1)
... |
"""Helper functions for training
Author: Ryo Yonetani
Affiliation: OSX
"""
from typing import Tuple, Sequence, Union
import random
from dataclasses import dataclass
import numpy as np
import torch
import torch.nn as nn
from torch.nn.modules.loss import _Loss
from torchvision.utils import make_grid
from PIL import Ima... |
"""
*******************************************************************************
* Ledger Blue
* (c) 2019 Ledger
*
* 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.... |
import os
import re
class FileFinder(object):
def __init__(self, par_id_pattern="EML1_[0-9][0-9][0-9]"):
self.par_id_pattern = par_id_pattern
def handle_dictionary_storage(self, _m_dict, _m_key, _m_val, how="append-if-exists"):
if how == "append-if-exists":
if _m_key in _m_dict.k... |
from django.urls import path
from artworks.views import market_place_views as views
urlpatterns = [
path('', views.fetch_market_place, name='fetch_market_place'),
path('deploy/', views.deploy_market_place, name='deploy_market_place'),
path('fees/<str:pk>', views.fetch_transaction_fee, name='market_place_fe... |
from .gl_gui import GLGui
|
from os import listdir
from os.path import isfile, join
import unittest
from parse_apache_configs import parse_config
import pprint
class testGetApacheConfig(unittest.TestCase):
#print "ENTERING TEST_PARSE_CONFIG" + "-"*8
def test_get_apache_config(self):
test_files = [ f for f in listdir("./test_conf... |
import numpy as np
import pandas as pd
from keras.models import Model
from keras.layers import Dense, Embedding, Input
from keras.layers import LSTM, Bidirectional, GlobalMaxPool1D, Dropout, Conv1D, MaxPooling1D, Flatten
from keras.preprocessing import text, sequence
max_features = 2000
maxlen = 450
train = pd.read_... |
"""Functions for parallel computation on multiple cores.
Copied from Python-RSA
"""
import multiprocessing as mp
from .prime import is_prime
from .utils import read_random_odd_int
def _find_prime(nbits, pipe):
while True:
integer = read_random_odd_int(nbits)
# Test for primeness
if is_... |
"""Contains model code for the CycleGAN
"""
import itertools
import torch
from torch import nn
import torch.utils.data
import pytorch_lightning as pl
from .losses import discriminator_loss, generator_loss, cycle_loss, identity_loss
def weights_init(m):
"""Initializes weights with a 0 mean and 0.02 stdev
Args... |
import random
import json
import urllib.request
import subprocess
import os
output = ""
operators = ["+", "-", "*", "/"] # add more operators here
functions = ["abs", "sqrt", "max", "min"] # add more functions here
left_paren = 0
right_paren = 0
for _ in range(3): # How many rounds
for i in range(1, 1000): # Le... |
# @Title: 下一个排列 (Next Permutation)
# @Author: KivenC
# @Date: 2018-07-19 21:21:29
# @Runtime: 44 ms
# @Memory: N/A
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
flag ... |
from selenium import webdriver
from time import sleep
class instagramBot(object):
"""docstring for instagramBot"""
def __init__(self, username, password):
self.opts = webdriver.ChromeOptions()
self.opts.add_experimental_option("detach", True)
self.driver = webdriver.Chrome(o... |
# Generated by Django 4.0.1 on 2022-01-15 00:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core_user', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='avatar',
fie... |
"""
WTForms fields and widgets with ParsleyJS headers.
This is a fork of wtforms-parsleyjs
based on https://github.com/johannes-gehrs/wtforms-parsleyjs and
https://github.com/fuhrysteve/wtforms-parsleyjs. We've forked it into Baseframe because
the upstream repositories appear unmaintained, and from past experience, we... |
from setuptools import setup, find_packages
setup(
name='python-derrick',
version='0.0.13',
description="An automation tool to help you dockerize App in seconds",
keywords='Docker dockerize automation dockerfile docker-compose Jenkinsfile DevOps',
author="ringtail",
author_email="zhongwei.lzw@a... |
import sqlalchemy
from flask import current_app
from app.util import ResultCode
from app import db
from app.db.orm import SensorType
class SensorModel(object):
def __init__(self):
pass
def getSensorType(self):
try:
sensorType_result = db.session.query(SensorType).all()
except Exception as exc:
curre... |
salario_bruto=float(input())
horas_de_trabalho=float(input())
ganhos_por_hora=salario_bruto / horas_de_trabalho
IR=salario_bruto * 0.11
INSS=salario_bruto * 0.08
sindicato=salario_bruto * 0.05
salario_liquido=salario_bruto-IR-INSS-sindicato
hora_liquida=salario_liquido/horas_de_trabalho
print(f'Salário Bruto = {salar... |
import argparse
import json
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
from joblib import load
from sklearn.metrics import f1_score, plot_confusion_matrix, roc_auc_score
from utils.load_params import load_params
def eval(metrics_fpath,
cm_fpath,
models_dir,
... |
import logging
from datetime import datetime
from typing import Optional
import flask
from flask import Blueprint
from flask import Response
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_login import current_user, login_required
from waitli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sunday 16 May 2020
@author: earjba
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import chardet
import statsmodels.formula.api as smf
def substring_after(s, delim):
return(s.partition(delim)[0])
def plot(df1, d... |
import numpy as np
from autograd.misc import flatten
from autograd.wrap_util import wraps
from autograd import grad, value_and_grad
from functools import partial
get_name = lambda f: getattr(f, '__name__', '[unknown name]')
get_doc = lambda f: getattr(f, '__doc__' , '')
def flatten_to_dim(X, d):
"""
Flatten... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
kwargs = {
'name':'cynamedtuple',
'version':'0.1.0',
'description':'Memory efficient and fast namedtuple implementation using Cython',
'long_description':long_description,
'lo... |
# Automatically generated SST Python input
import sst
from mhlib import componentlist
# Global variables
debugScratch = 0
debugL1 = 0
debugCore0 = 0
debugCore1 = 0
debugNIC = 0
DEBUG_MEM = 0
core_clock = "2GHz"
###########################################################################################################... |
from pgquery.builder.actor import BuildingPayload
from pgquery.builder.clauses.op import BinaryOp, EqMixin
from pgquery.builder.mixins.expression import SupportsBeExpression
from pgquery.builder.tokens import PGToken
class Func(SupportsBeExpression, EqMixin):
def __init__(self, name: str, *args: SupportsBeExpress... |
# Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
# coding=utf-8
import csv
import sys
import json
import logging
import time
from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler
from django.core.handlers.wsgi import WSGIHandler
#from django.core import urlresolvers
from django.core import signals
from django import http
from django.core import ex... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... |
"""Module for fetching remote graph."""
import logging
from aiohttp import ClientError, hdrs
from aiohttp_client_cache import CachedSession
from rdflib import Graph
SUPPORTED_FORMATS = set(["text/turtle", "application/ld+json", "application/rdf+xml"])
class FetchError(Exception):
"""Class representing custom e... |
###################THIS FILE DOES NOT WORK#################
import requests
import html_to_json
#URL = "https://modelo-prueba.herokuapp.com/result"
url = "http://127.0.0.1:8080/result"
data = {'a':1, 'b':2, 'c':3, 'd':4}
####################Alternativa1###############################
r = requests.post(url,data=data)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def get_func(tag):
def func(s):
group = tag, s
return group
return func
|
#!/usr/env python3
import atexit
import os
import sys
import readline
from seval.seval import parse_string
from seval.repls import readline_completer
from seval.constants import global_env
# Make the history file hidden on UNIX type operating systems
if sys.platform == "win32":
HISTFILE = os.path.join(os.path.ex... |
import numpy as np
from utils import expect_equal, expect_false, expect_identical
from ebnmpy.ashr import normalmix
from ebnmpy.ebnm import ebnm
from ebnmpy.ebnm_fns import ebnm_point_normal
from ebnmpy.estimators import PointNormalEBNM
from ebnmpy.output import g_ret_str, llik_ret_str, samp_arg_str, samp_ret_str
from... |
import numpy as np
import tensorflow as tf
import cv2
import PIL.Image
import pickle
import time
from os import listdir
from os.path import isfile, join
import datetime
from os import listdir
from os.path import isfile, join
import datetime
from controller import Camera
from flockai.PyCatascopia.Metrics import *
from ... |
#!/usr/bin/env python
# md5: 32805c20c00faf98300ce45648f2dec6
# coding: utf-8
import json
import os
from memoized import memoized
from get_database_name import getDatabaseName
@memoized
def getViewersToLecturesJsonMemoized(dbname):
jsonfile = dbname + '_viewerstolectures.json'
if not os.path.exists(jsonfile):
... |
from django.contrib import admin
from .models import *
# Register your models here.
class CharacterAdmin(admin.ModelAdmin):
list_display = ('hero','first_name' , 'last_name', )
admin.site.register(Character, CharacterAdmin)
class GroupAdmin(admin.ModelAdmin):
list_display = ('name' ,)
admin.site.register(Gro... |
# -*- coding:utf-8 -*-
import numpy as np
import cv2
try:
import config
except Exception:
from train_code.train_ctpn import config
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
"""
This function resizes the image to the specified width and height.
It also provides the interpo... |
import pyttsx3
from moviepy.editor import *
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()
speak("give the file location including name of video file")
mp4 = str(inpu... |
# Gerador de grafos
class GeradorGrafo:
def __init__(self, n):
self.n = n
self.grafo = [[] for i in range(n)]
def gerar_grafo(self):
for i in range(self.n):
for j in range(self.n):
if i != j:
self.grafo[i].append(j)
def mostrar_grafo(self):
for i in range(self.n):
print('Adjacentes de %... |
"""
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Inpu... |
#
# This file is part of the Ingram Micro CloudBlue Connect Python OpenAPI Client.
#
# Copyright (c) 2021 Ingram Micro. All Rights Reserved.
#
import time
import httpx
import requests
from httpx import HTTPError
from requests.exceptions import RequestException
from connect.client.exceptions import ClientError
cl... |
""" CISCO_IPSEC_FLOW_MONITOR_MIB
This is a MIB Module for monitoring the
structures in IPSec\-based Virtual Private Networks.
The MIB has been designed to be adopted as an IETF
standard. Hence Cisco\-specific features of IPSec
protocol are excluded from this MIB.
Acronyms
The following acronyms are used in this doc... |
from ebl.atf_importer.application.atf_importer import ATFImporter
from ebl.atf_importer.domain.atf_preprocessor import ATFPreprocessor
# Test case for insertion of placeholder if "<<"
def test_placeholder_insert(database):
atf_preprocessor = ATFPreprocessor("../logs", 0)
converted_lines = []
c_line, c_arr... |
import json
import os
import sys
import unittest
from distutils.version import LooseVersion
from collections import OrderedDict
if sys.version_info[0] >= 3:
from unittest import mock
else:
import mock
import numpy as np
import scipy.optimize
import scipy.stats
import sklearn.base
import sklearn.datasets
impor... |
'''
Example compound concentration timecourses. Figure 3A.
'''
import os
import sys
import numpy as np
import pandas as pd
import networkx as nx
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.font_manager as fm
from matplotlib.ticker import MaxNLocator
... |
"""Streaming pickle implementation for efficiently serializing and
de-serializing an iterable (e.g., list)
Created on 2010-06-19 by Philip Guo
http://code.google.com/p/streaming-pickle/
Modified by Brian Thorne 2013 to add base64 encoding to support
python3 bytearray and the like.
"""
import base64
from pickle imp... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
import argparse
import random
import xml.etree.cElementTree as ET
import os
from xml.dom import minidom
import codecs
def parseProbability(value):
if float(value) >= 0.0 and float(value) <= 1.0:
return float(value)
else:
parser.error('Incorrect parameter {}!'.format(value))
def parsePositiveInteger(value):
if ... |
import unittest
import eson
import json
from datetime import datetime, date, timezone, timedelta
class TestCase(unittest.TestCase):
def test_simple_encode(self):
normal_dict = dict(name="Jane Doe", sibling="Jane Doe")
self.assertEqual(json.dumps(normal_dict), eson.encode(normal_dict))
self... |
from pymongo import MongoClient
from pprint import pprint
import json
import certifi
from dotenv import load_dotenv
import os
# loads in the .env file (The access string), loaded into an environmental variable. Safer for access
load_dotenv()
def insertSampleCourse(c_client, c_db):
# Loads in the COS126 JSON file... |
# (c) 2017 Gregor Mitscha-Baude
"""common interface for all pore geometries
should behave as follows:
-) defines default parameters for the geometry
-) provides function that takes geoname, geo params (including dim) plus
small additional number of non-geo (solver) params
(h, reconstruct, subs), ... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
"""Project settings."""
import sys
from dynaconf import LazySettings
# --- BEGIN OF DYNACONF HEADER ---
settings = LazySettings(
GLOBAL_ENV_FOR_DYNACONF='GALAXY',
)
# --- END OF DYNACONF HEADER ---
# ---------------------------------------------------------
# Django settings
# --------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
setup(name='Hilbert_Autoencoder',
version='0.0.1',
packages=find_packages(
exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
description='Hilbert Autoencoder')
|
# Generated by Django 2.2.4 on 2019-09-30 18:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_adminuser'),
]
operations = [
migrations.AddField(
model_name='adminuser',
name='bank',
... |
import pandas as pd
import glob
def get_list_with_all_csv_with_format(path,model_type:str,extra_info:str,day:int,hour:int) ->list:
#the format is {model_type}_ {with/without}*date/hour.csv
#adversarial=with/without
last_folder=path.split("/")
if last_folder[-1]=="results_experiment_4":
for... |
"""Double gamma distribution."""
import numpy
from scipy import special
from ..baseclass import SimpleDistribution, ShiftScaleDistribution
class double_gamma(SimpleDistribution):
"""Double gamma distribution."""
def __init__(self, a):
super(double_gamma, self).__init__(dict(a=a))
def _pdf(self,... |
# EIA_MER.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
EIA Energy Monthly Data, summed to yearly
https://www.eia.gov/totalenergy/data/monthly/
2010 - 2020
Last updated: September 8, 2020
"""
import io
import pandas as pd
from flowsa.flowbyfunctions import assign_fips_location_system
def eia_mer_url_helper... |
import torch
from torch import nn
from torch import optim
from tqdm import tqdm
from torch_utils import *
from skempi_lib import *
from loader import *
num_bins = 301
DDG = np.asarray(s2648_df.DDG.values.tolist() + varib_df.DDG.values.tolist())
Min, Max = min(min(DDG), min(-DDG)), max(max(DDG), max(-DDG))
bins = np.l... |
# Only use on Linux
# For Windows, use com0com port emulator to link ports together
from subprocess import call
import getpass
user = getpass.getuser()
call_string = "sudo socat -d -d PTY,link=/dev/ttySx,user=%s PTY,link=/dev/ttySy,user=%s" %(user, user)
call_string = call_string.split(' ')
call(call_string) |
test_cases = int(input())
for t in range(1, test_cases + 1):
D, A, B, F = map(int, input().strip().split())
print('#{} {}'.format(t, D / (A + B) * F))
|
'''
Interactive problems
'''
# Know the final price of a purchase
# All the products costs 14.99 €
# Non seasonal products have 30% discount
# 1. Ask the user the total number of seasonal and non seasonal products that have brougth
# 2. Obtain the total discount applied
# 3. Tell the user how may products has brougth ... |
import pywhatkit as kit
kit.image_to_ascii_art(r"C:\Users\luana\OneDrive\Imagens\301-3017270_128-kb-png-honk-honk-pepe-gif-clipart.png",R"C:\Users\luana\OneDrive\Área de Trabalho\ESTUDOS\python\ASCII3.txt")
|
"""empty message
Revision ID: d5a88426c7b5
Revises:
Create Date: 2021-03-19 18:23:58.840503
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'd5a88426c7b5'
down_revision = None
branch_labels = None
depends_on = None
def up... |
# Copyright 2016-2018, Pulumi 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 t... |
#
# 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... |
from .account_details import AccountDetailsResponse
from .address import AddressResponse
from .routing_details import RoutingDetailsResponse
class InternalAccountResponse:
def __init__(self, json):
self.json = json
@property
def id(self):
return self.json.get('id')
@property
def ... |
from praw import Reddit as PrawReddit
import os
import sys
import string
import random
import time
from random import randint
from urllib import request
import pyimgur
class Reddit():
def __init__(self, **kwargs):
self._subreddit = kwargs["subreddit"]
self._reddit = PrawReddit(
usernam... |
class MultiStack:
def __init__(self) -> None:
self.list = [None] * 3
self.start_1 = 0
self.end_1 = 0
self.start_2 = 1
self.end_2 = 1
self.start_3 = 2
self.end_3 = 2
def __str__(self):
return str(
[
self.list[self.start_... |
import moeda
preco = float(input(' - Digite um preco \033[1;32mR$\033[m: '))
print(f' - A metade de {preco} e {moeda.metade(preco)}')
print(f' - O dobro de {preco} e {moeda.dobro(preco)}')
print(f' - Aumentando 10%, temos {moeda.aumentar(preco, 10)}')
print(f' - Diminuindo 13%, temos {moeda.diminuir(preco, 13)}'... |
# -*- coding: utf-8 -*-
from tkinter import *
import tkinter.ttk as ttk
from tkinter.filedialog import *
from remove_Char.remove_Char import remove_Char
from CRC_Generator.CRC_Generator import crc_Generator
import os
from CRC_print.CRC_print_V2 import crc_FileWrite
from ToolTip.ToolTip import ToolTip as TTip
debuggi... |
from datauploader.common.interfaces import AbstractClient
import io
import os
import logging
import json
logger = logging.getLogger(__name__)
"""
output sample:
{"dtypes": {"ts": "int64", "value": "float64"}, "type": "metric", "names": ["ts", "value"]}
123 123.123
456 456.456
123 123.123
456 456.456
"""
class L... |
#!/usr/bin/env python
import tornado.template
import logging.handlers
import tornado.options
import tornado.ioloop
import dns.resolver
import tornado.web
import logging
import binascii
import unirest
import urllib
import copy
import json
import time
import yaml
import sys
import os
import io
from models.initiate_datab... |
import boto3
import json
import requests
from botocore.exceptions import ClientError
def do_get(url, params=None):
r = requests.get(url, params)
print(f'status code {r.status_code}')
print(f'{r.text}')
return r.status_code, json.loads(r.text)
def get_ticker(currency_id):
url = f'https://api.coin... |
import requests
import warnings
from zope import component
from zope.component.factory import Factory
from zope import interface
from zope.schema.fieldproperty import FieldProperty
from .interfaces import IRequest, IRequestResolver
from sparc.config import IConfigContainer
@interface.implementer(IRequest)
class Reque... |
from .push_inbound_oracle import PushInboundOracle, ArrivalState |
# Generated by Django 2.2.1 on 2019-06-24 19:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Espanol',
fields=[
... |
# -*-coding:utf-8-*-
from flask import request
from flask_babel import gettext
from flask_login import current_user, logout_user
import time
from werkzeug.security import generate_password_hash
from apps.core.template.get_template import get_email_html
from apps.core.utils.get_config import get_config
from apps.modules... |
#!/bin/python
from deap import base, tools
from copy import deepcopy
import random
import promoterz.supplement.age
import promoterz.supplement.PRoFIGA
import promoterz.supplement.phenotypicDivergence
import itertools
# population as last positional argument, to blend with toolbox;
def immigrateHoF(HallOfFame, pop... |
""""
Normalizations / batch_norm under tensorflow environment.
Supports NCCL multi-gpu environment.
To activate the environment, use code below in your
main.py.
>> os.environ['nccl_multigpu_env'] = 'true'
"""
__version__ = "1.0.0"
import os
import tensorflow as tf
NCCL_FLAG = os.environ.get('nccl_multigpu_env')
__al... |
import asyncio
from websockets import ConnectionClosed
import auditor
import conf
from constants.experiment_jobs import get_experiment_job_container_name
from db.redis.to_stream import RedisToStream
from events.registry.experiment_job import EXPERIMENT_JOB_RESOURCES_VIEWED
from options.registry.k8s import K8S_NAMESP... |
from kevblog.models import create_article
if __name__ == '__main__':
title = "this is title2"
summary = "this is summary"
content = "this is a content"
tags = ['test']
create_article(title, summary, content, tagnames=tags)
|
from hypothesis import given
from cfractions import Fraction
from tests.utils import is_fraction_valid
from . import strategies
@given(strategies.fractions, strategies.positive_integers)
def test_basic(fraction: Fraction, denominator: int) -> None:
result = fraction.limit_denominator(denominator)
assert isi... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.