text stringlengths 38 1.54M |
|---|
import os
import multiprocessing
# Properties
daemon = True
workers = multiprocessing.cpu_count() * 2 + 1
# Setup server
ip = os.environ['OPENSHIFT_GEO_IP']
port = os.environ['OPENSHIFT_GEO_PORT']
bind = '{}:{}'.format(ip, port)
|
import asyncio
import json
import websockets
async def consumer_handler(frames):
async for frame in frames:
trade = json.loads(frame)
print(trade)
async def connect():
async with websockets.connect("wss://stream.binance.com:9443/ws/btcusdt@trade") as ws:
await consumer_handler(ws)
... |
# Authors: Nanda H Krishna (https://github.com/nandahkrishna), Abhijith Ragav (https://github.com/abhijithragav)
import os
from datetime import *
from dateutil.relativedelta import *
from dateutil.rrule import *
import json
import requests
import threading
from flask import Flask, jsonify, render_template, request
imp... |
from cdat import vcswidget
import vcs
class FillPreviewWidget(vcswidget.QVCSWidget):
def __init__(self, parent=None):
super(FillPreviewWidget, self).__init__(parent=parent)
self.fillobj = None
def setFillObject(self, fillobject):
self.fillobj = fillobject
tmpobj = vcs.createfi... |
from django.shortcuts import render,redirect
from .models import Question,Choice
from django.contrib import messages
# Create your views here.
def home(request):
question = Question.objects.all()
messages.success(request, " | Vote Now!")
return render(request, 'pollapp/home.html', {'question':question})
d... |
print("#"*1)
print("#"*2)
print("#"*3)
print("#"*4)
print("#"*5)
for item in list(range(1,6,1)):
print("#"*item)
|
#Identifica se os números de 1 a 9 qual é primo,
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print(n, 'igual a', x, '*',n // x)
break
else:
print(n, 'é número primo') |
# coding: utf-8
import math
import numpy as np
from collections import Counter
import torch
import torch.nn.init as init
from torch import nn
from torch.autograd import Variable
#####################################################################################################################
def batch(iterable,... |
from django.apps import AppConfig
from django.db.models.signals import post_save, post_delete
from django.conf import settings
class ProductConfig(AppConfig):
name = 'utilities.product'
def ready(self):
import drf_nest.signals
from utilities.product.models import ProductOffering
from u... |
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@return: The maximum size
"""
def backPack(self, m, A):
# write your code here
n = len(A)
res = [[False] * (m + 1) for _ in range(n + 1)]
for i in ra... |
from __future__ import unicode_literals
import os
import importlib
import six
import cherrypy
from sideboard._version import __version__
import sideboard.server
from sideboard.internal.imports import _discover_plugins
from sideboard.internal.logging import _configure_logging
import sideboard.run_mainloop
if 'SIDEBO... |
#!/usr/bin/python
import os
import sys
import re
property_seperator = '='
def print_error(msg):
print "[ERROR] %s" % msg
sys.exit(1)
def print_usage():
print "[USAGE] python migrate_gradle.py {project_folder_path}"
def read_property_file(f):
props = {}
for line in f:
i... |
#!/usr/bin/python3
from flask import Flask, url_for
from flask import Response, make_response
from flask import request
app = Flask(__name__)
@app.route('/')
def v_index():
rsp = make_response('go <a href = "%s">page2</a>' % url_for('v_page2'))
rsp.set_cookie('user','JJJJohnny')
return rsp
#
@app.rou... |
from topic_modelling import *
# This file is used to create a beta matrix for LDA
Corpus(transf=transformations, transf_parameters={'tfidf': {'load': False, 'bzip2': True},
'lsi': {'load': False, 'topics': n_topics},
'... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
'''
通用方法工具类
@author: 'wanggongzheng'
'''
import sys
import datetime
import time
import config
import math
def is_null_str(src_str):
"""判断字符串是否为缺省值"""
null_str_list = [r'NULL', r'NONE', r'\N']
if src_str.upper() in null_str_list :
return True
return F... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 7 18:41:11 2017
@author: brendontucker
"""
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
rowCount = len(matrix)
total = 0
current = 0
row = 0
col = 0
columnCount = len(matrix[0])
'''
while row < rowCoun... |
from std_msgs import String
from uros import NodeHandle
import time
def cb(msg):
print(msg.data)
msgp = String()
msgp.data = "ItsMeLuigi"
node = NodeHandle(2, 57600)
node.subscribe("chatter", String, cb)
while True:
node.publish("groop", msgp)
time.sleep(1)
|
class EventHandler:
def is_event_as_expected(self, event):
pass
def build_message_string(self, event):
pass
|
from copy import deepcopy
class Solution:
def minPathCost(self, g, mc):
m,n,dp = len(g), len(g[0]),deepcopy(g)
for i in range(1, m):
for j in range(n):
crow = float("inf")
for k in range(n): crow = min(crow, dp[i-1][k] + mc[g[i-1][k]][j])
d... |
import json
import unittest
from tests.helper_tests import InitTests
class UserTests(unittest.TestCase):
def setUp(self):
InitTests.testSetUp(self)
def tearDown(self):
InitTests.testTearDown(self)
def test_can_create_user(self):
self.user = {"email": "juma@ymail.com", "username"... |
from RetimingProject_Main import *
from memory_profiler import memory_usage
import sys
if(len(sys.argv)<=2):
print("Error. You must specify the value to iterate. E.g: python3 timeProfiler.py correlator/generator 10")
else:
opt1x = []
opt1y = []
opt2x = []
opt2y = []
for i in range(int(sys.arg... |
import string
import no_bytecode
def pw_check(password):
if len(password) >= 24:
ABC = dict.fromkeys(string.uppercase, True)
abc = dict.fromkeys(string.lowercase, True)
nums = dict.fromkeys(string.digits, True)
sym = dict.fromkeys(string.punctuation, True)
ABC_flag = abc_fla... |
# process_memory_scanner.py by Cadaver
# this is written for Python 2.7 and tested on windows 7 64bit with 32bit processes.
# it can scan an entire process for a integer value in under half a second.
# it can also scan for any ctype within python ctypes or ctypes.wintypes modules \
# simply by creating an instance of ... |
from palindrome import palindrome as p
class Test_time:
def test_p_correct(self):
assert p("racecar") == "racecar is a palindrome"
assert p("snickers") == "snickers is not a palindrome"
assert p("blalb") == "blalb is a palindrome"
def test_p_type(self):
assert p("~~.~~") == "~~.~~ is a palindrome"
... |
from tools.db_oprt_base import DataBaseOprt
import mysql.connector
class DataBaseOprtMySQL(DataBaseOprt):
class DataBaseParams:
class DB5:
host = '0.0.0.5'
port = '3306'
user = 'steff'
pwd = 'password'
class DB11:
host = '0.0.0.11'
... |
import os
f = 30
gitpull = 1
#[37,32,27,22]
qps = [20,32,43,55]
OPT = 0 # optimizacoes ligadas = 1
gprof = 1
threads = 5 # numero de processos em parelelo
#gitpath = "git_repo/pesquisa_av1"
gitpath = "pesquisa_ucpel/pesquisa_av1"
gitscript = "git_upl"
#shpath = "git_repo/common_research/codes/run-sh/aom"
shpath... |
x = 1
while x<20:
x+=1
if x == 2:
pass
if x == 3:
continue
if x < 100:
print(x)
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------------------------
# - Generated by tools/entrypoint_co... |
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
from model_rnn import rnn
from dataset import isear
torch.manual_seed(814)
def test():
with torch.no_grad():
correct = 0
total = 0
for i, data in enumerate(valid_loader):
... |
# Создайте программу с двумя кнопками растягиваемые по горизонтали,
# прикрепленными к верхней и нижней границам окна.
from tkinter import *
root = Tk()
btn1 = Button(root, text="Button 1")
btn1.pack(side=TOP, fill=X)
btn2 = Button(root, text="Button 2")
btn2.pack(side=BOTTOM, fill=X)
root.mainloop() |
from selenium.common.exceptions import *
from selenium.webdriver.common.by import By
class ElementUtil():
def __init__(self,driver):
self.driver = driver
def getPageTitle(self):
return self.driver.title
def getElement(self,byLocator):
return self.driver.find_element(*byLocator)
... |
from lib.helpers.parse_name import ParseName
from lib.helpers.parse_credits import ParseCredits
from lib.helpers.parse_field_of_study import ParseFieldOfStudy
from lib.helpers.parse_fos import ParseFos
from lib.helpers.parse_date import ParseDate
from lib.helpers.parse_completion_date import ParseCompletionDate
from li... |
import functools
import logging
import os
import shutil
import subprocess
import tempfile
from source.storage.stores.artifact_store.interface import ArtifactStoreInterface
from source.storage.stores.artifact_store.types import DurationMetricArtifact
from source.storage.stores.artifact_store.types.data_ingestion import... |
import openpyxl
from openpyxl.styles import Alignment
book = openpyxl.load_workbook('xlf/7.xlsx')
sheet = book["Sheet1"]
sheet.sheet_properties.tabColor = "00ff33"
book.save('xlf/7.xlsx')
sheet = book.active
sheet.merge_cells('A1:B2')
cell = sheet.cell(row=1, column=1)
cell.value = 'WOW ITS BIG'
cell.alignment = Al... |
# Reset the console
%reset -f
# Import libraries
# Importing requests to extract content from a url
import requests
from bs4 import BeautifulSoup as bs # for web scraping
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# Creating empty review list
poco_reviews = []
for i in range(1,100... |
from lewis.core.statemachine import State
class DefaultState(State):
# Default state
NAME = 'Default'
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 8 07:12:56 2016
@author: PM5
Experiment with adding a variable to an existing NetCDF file.
"""
import netCDF4 as nc
import numpy as np
import os
dir0 = os.environ.get('HOME') + '/Desktop/'
# function to check results
def check(fn, hstr):
print('\n** ' + hstr + '... |
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import base64
def avg_lap_speed_ts(df, max_speeds, min_speeds):
constructor_names = {'alfa': 'Alfa Romeo', 'alphatauri': 'AlphaTauri',
'mclaren': 'McLaren', 'mercedes': 'Mercedes', 'racing_point': 'Racing Point',
... |
numbers = []
while True:
n = int(input())
numbers.append(n)
if n < 0:
numbers.pop()
avg = sum(numbers)/len(numbers)
print('{:.2f}'.format(avg))
break
|
# Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
var = float(input("Quantos litros foram comprados?"))
total = var * 1/3
print(round(var * 1/3, 3 ))
|
#!/usr/bin/python
import string
import time
import numpy as np
import os
import glob
import matplotlib
import matplotlib.pyplot as plt
import math
import colorsys
import cStringIO
import cPickle as pickle
from snap.iw import iw_pb2
from snap.iw.matching import py_featureextractor
from snap.iw.matching import py_feat... |
from rest_framework import serializers
from .models import app
class appSerializer(serializers.ModelSerializer):
class Meta:
model = app
fields = ('id', 'username', 'lastname', 'age','weight','gender') |
N = int(input("Digite o número:") )
soma = 0
while N >= 1:
digito = N % 10
N = N // 10
soma = digito + soma
print("A soma dos dígitos é", soma) |
# D-Wave Leap access: https://cloud.dwavesys.com/leap/
#
# Docs for QPU / Hybrid samplers
# https://docs.ocean.dwavesys.com/projects/system/en/stable/reference/samplers.html#dwave.system.samplers.LeapHybridDQMSampler
# pip install numpy
# pip install dimod
# pip install dwave-hybrid
# pip install dwave-system
impor... |
from django.contrib import admin
from etat_civil.deeds.jobs import import_data_async
from etat_civil.deeds.models import (
Data,
Deed,
DeedType,
Gender,
Origin,
OriginType,
Party,
Person,
Profession,
Role,
Source,
)
class BaseALAdmin(admin.ModelAdmin):
list_display = [... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 17:24:39 2015
Sample use cases of the HackerNews API
@author: Rupak Chakraborty
"""
import HackerNewsUser as HNUser
import HackerNews as HN
def sample():
user = HNUser.User("pg")
user.userProcessingPipeline()
print "User Id : ",user.Id
print "Creat... |
from turtle import Turtle, Screen
import random
import turtle
tim=Turtle()
turtle.colormode(255)
colours=["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]
'''Square'''
# tim.forward(100)
# tim.left(90)
# tim.forward(100)
# tim.left(90)
# tim... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 18:33:14 2019
@author: vkrin
"""
x=list(map(int, input().split(' ')))
if ((x[0]-x[1])%2==0):
for i in range(x[0]-x[1]):
if (i+1)%2==0:
print(2, end=' ')
else: print(1, end=' ')
for j in range(x[1]):
print(j+1, end=' ')
else... |
from AnagramDrawer import *
ad = AnagramDrawer()
ad.draw_image("Guilherme Kuro","Leg Hike Rumour","out.png")
|
"""
Django settings for gb_blog project.
Generated by 'django-admin startproject' using Django 1.11.16.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""... |
# This is a program for getting which number is negative and which is positive.
the_number = input('Enter any number')
print(the_number)
if int(the_number) >= 0:
print("The number you entered is a positive number")
else:
print("The number you entered is negative number")
|
# A simple Json Web Server
import re
import json
# from socket_server import WSGIServer
from asynic_server import server_run
from urllib import parse
class BaseHttpServer(object):
def __init__(self):
self.routes = []
self.router = Router()
self.request_method = None
self.path = ''
... |
import os
import warnings
import numpy as np
import skopt
import torch
import torchvision
import tabulate
import datasets
from lenet5 import lenet5
from resnet import resnet18
from evaluate import eval_bnn
from sampling import invert_factors
from utils import (accuracy, setup, expected_calibration_error, predictive_e... |
import numpy as np
import torch
from torch.autograd import Variable
import cv2
import dlib
from .utils.img_allign_expnet import img_align_modified
from .utils.model_phase2_expnet_CPU import ExpNet_p2
import os
import datetime
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
class VideoCamera(object):
emo_li... |
import os
import pytest
from sqlalchemy import inspect, create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
pytest.TEST_DB_FILEPATH = 'tests/test.db'
@pytest.fixture(scope="session")
def db_engine():
engine_ = create_engine(f"sqlite:///{pytest.TEST_DB_FILEPATH}", echo=True)
yield engine_
... |
import logging
from cdsagent import cfg
LOG = logging.getLogger(__name__)
__author__ = 'Hardy.zheng'
conf = cfg.CONF
class ApiBase(object):
def __init__(self):
pass
class CdsClient(ApiBase):
def __init__(self):
super(CdsClient, self).__init__()
def get_floating_ips(self):
... |
#!/usr/bin/env python3
import cv2
import numpy as np
import os
import time
#from matplotlib import pyplot as plt
thisdir = os.getcwd() + "/captures/2020-12-29-02-22-32"
print (thisdir)
img = None
for i in range(1,3132):
image_name = os.path.join(thisdir, 'grayscale_{:d}.pgm'.format(i))
img = cv2.imread(image... |
"""the_class.py
Temporary name of the file for the class that can be used
to interface with the code generation stuff.
"""
import sympy as sym
from sympy.core.symbol import var
import dendrosym
class DendroGRCodeGen:
"""Class for generating code files for Dendro computations"""
def __init__(self, project_... |
import unittest
from pymmbot.coinpit import crypto
class Test(unittest.TestCase):
def test_get_headers(self):
apikey = {
"name" : "18e5f6966c901e78",
"role" : "trade",
"apikey" : "18e5f6966c901e78f5946bfdd798981559e8df0be73d746d90a458779fddc05b",
... |
import os
from setuptools import setup
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='photoage',
version='0.1.1',
description='Calculate the age of a photo.',
long_descript... |
from Tkinter import *
v0=Tk()
v0.geometry("242x100")
Label(v0,text="").grid(row=1,column=1)
Label(v0,text="BIENVENIDO AL PROYECTO").grid(row=1,column=2)
Label(v0,text="").grid(row=1,column=3)
Label(v0,text="T E X T O").grid(row=2,column=1)
Label(v0,text="T E X T O").grid(row=2,column=3)
Label(v0,text="T E X T O").gri... |
import functools
from behave import step
from acceptance_tests.utilities.fieldwork_helper import fieldwork_create_message_callback, field_work_update_callback
from acceptance_tests.utilities.rabbit_helper import start_listening_to_rabbit_queue
from acceptance_tests.utilities.test_case_helper import test_helper
from c... |
num = int(input('Enter a number: '))
if 100 <= num < 1000:
c = num // 100
r = num % 100
d = r // 10
r = r % 10
if c > 1 and d > 1 and r > 1:
print(f'{num} = {c} hundreds, {d} dozens and {r} units.')
elif c <= 1 and d > 1 and r > 1:
print(f'{num} = {c} hundred, {d} dozens and {r} ... |
# Generated by Django 3.0.3 on 2020-02-06 10:24
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("example", "0007_artproject_description"),
]
operations = [
migrations.CreateModel(
name="LabResu... |
# import queue
#
# q = queue.Queue()
# q.put(1)
# q.put(2)
# q.put(3)
#
# print(q.get())
# print(q.get())
# print(q.get())
# 生产者消费者
from threading import Thread, current_thread
import time
import random
from queue import Queue
queue = Queue(5)
class ProducerThread(Thread):
def run(self):
name = current... |
import unittest
import game_of_chess
class TestPart1(unittest.TestCase):
"""
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers
that seem to have acquired most of their security knowledge by watching
hacking movies.
The eight... |
from django.db import models
# Create your models here.
from apps.user.models import User
# faved_books
class Book(models.Model):
title = models.CharField(max_length=45)
favs = models.ManyToManyField(User, related_name="faved_books")
|
from django.shortcuts import render, redirect, reverse
from .models import Product
from accounts.models import UserProfile
"""
View for all products
"""
def all_products(request):
# Make sure pro version product not added again
added = False
cart = request.session.get('cart')
# If i... |
# Typy zmiennych:
a = 5 #liczba całkowita (int)
b = 4.3 #liczba zmiannoprzecinkowa (float)
imie = 'Wojciech' #ciąg znaków (string)
mleko = True #true or false (bool) |
from odoo import api, fields, models,exceptions
import logging
_logger = logging.getLogger(__name__)
class ResPartner(models.Model):
_inherit = "res.partner"
# Change the display name when user select partner
# def name_get(self):
# res = []
# for field in self:
# ... |
"""
title: helloWorld
author: mfp4311
date: 6/25/19 2:08 PM
"""
print("Elizabeth,", end=" ")
print("Emily,", end=" ")
print("Bob,", end=" ")
print("Antonio")
print("\t\t\t\t\t|||")
print("\t\t\t\t\t O")
print("\t\t\t\t / \ ")
print("\t\t\t\t\t| |") |
from django.contrib import admin
# Register your models here.
from .models import Bb
from .models import Rubric
class BbAbmin(admin.ModelAdmin):
list_display = ('title', 'content','price','published','rubric','img','image_img')
list_display_links = ('title','content','img','image_img')
search_fields = ('ti... |
from unittest.mock import patch
import pytest
from linnapi import exceptions, inventory
from linnapi.requests.inventory import GetStockItemIDsBySKU
@pytest.fixture
def sku():
return "E32-99X-8G2"
@pytest.fixture
def stock_item_id():
return "965c4c47-227d-4b87-913f-0114dab13b61"
@pytest.fixture
def skus(... |
height = int(input('Введите рост в сантиметрах: '))
mas = int(input('Введите массу в килограммах: '))
#перевод роста с сантиметров в метры
height_m = height/100
#вычисление индекса массы тела
index= mas/(height_m*height_m)
#вывод индекса массы тела
print('Индекс массы тела: ' + str(index))
#Интерпретирование показа... |
def check(number):
answer = number % 2
return answer
number = int(input("enter a number: "))
if check(number) == 0:
print(number, "is even")
else:
print(number, "is odd")
|
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'}},
SITE_ID=1,
SECRET_KEY='not very secret in tests',
... |
from django.contrib.auth.models import User
from model_mommy.recipe import Recipe
from documents.models import Document
from interface.models import Repo
document = Recipe(Document)
repo = Recipe(Repo)
user = Recipe(User)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def dark_start(target):
from dark_core.database.mysqlManger import sqlMg
from hiddenDetect import hiddenlink_obj
from dark_core.output.console import consoleLog
from dark_core.output.textFile import fileLog
from dark_core.output.logging import logger
... |
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
return Browser('chrome', **executable_path, headless=False)
def scrape():
browser = init_browser()
u... |
import asyncio
from config import DISCOVERY_PORT, HOST, MESSAGE_PORT
from handlers.discovery_handler import handle_discovery_request
from handlers.message_handler import handle_message
from controller import interact
loop = asyncio.get_event_loop()
discovery_job = asyncio.start_server(handle_discovery_request, HOST,... |
from tkinter import *
root = Tk()
x = 0
def increase():
global x
x += 1
label.configure(text=x)
def decrease():
global x
x -= 1
label.configure(text=x)
label = Label(text=x)
sendbutton = Button(text="increase", command=increase)
deletebutton = Button(text="decrease", command=decrease)
send... |
"""
for elemento in interável:
faça algo
Para cada 'elemento' dentro da 'interável':
faça algo
"""
palavra = 'python'
for posição, letra in enumerate(palavra):
print(posição, letra) |
print("Welcome to the tip calculator.")
bill = float(input("What was the total bill? $"))
tip = float(input("What percentage tip would you like to give? 10, 12, or 15? "))
person = int(input("how many people to split the bill? "))
result = float(bill * ( 1 + (tip / 100 ) ) / person)
totalbill = float(round(result,... |
import markdown
from flask import abort, flash, redirect, render_template, request
from flask_babel import gettext as _
from flask_login import current_user, login_required
from ..ext import db
from ..forms.base import DeleteForm
from ..models import Brew, TastingNote
from ..utils.pagination import get_page
from ..uti... |
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print ('x = %d, y = %d'%(ix, iy))
global coords
coords.append((ix, iy))
if l... |
__version__ = '0.0.8'
# 0.0.8 - Multiple major changes
# - Finding label errors is no fully parallelized.
# - prune_count_method parameter has been removed.
# - estimate_confident_joint_from_probabilities now automatically calibrates confident joint to be a true joint estimate.
# - Confident joint algorithm ... |
import tweepy
consumer_key = "kJw5DKyNxQUUgaT5trGZX09a4"
consumer_secret = "HiLwij1CAMB4R618sQ7zFs7mDpEaKkoVaDXpNaN7FjFoGqiDK4"
access_token = "1092953497392242688-dX4PP4DyMtVihRUNnURKnJGTDYaUfk"
access_token_secret = "v8sgivQiAqHv5FRPsupb5YfJTicft35SoxOA6mLozSwJy"
# Creating the authentication object
auth = tweepy.OA... |
@app.route("/user/<username>", methods=["GET"])
@my_profiler
def route_one():
api_live = ping_api()
if not api_live:
return make_response('', 503)
return make_response('', 200)
@app.route("/login/0000")
@my_profiler
def route_two():
api_live = ping_api()
if not api_live:
... |
# Copyright (C) 2021 by Kevin D. Woerner
##-# =KDW= ################# BUILDER $KWROOT/0lib/vkkcp.sh ##################
##-# =KDW= ############# SOURCE $KWROOT/codekdw/kw-lib/Kw.fwipp #############
##-# =KDW= #### THIS FILE CAN BE OVERWRITTEN BY KEVIN D. WOERNER OR HIS #####
##-# =KDW= ############ MINIONS AT *ANY* T... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 09:49:15 2017
@author: andre
"""
instructor = input("Enter the prof's name: ")
subject= input("Enter the subject name: ")
term = input("Enter the term: ")
format= '{} will teach {} in {} . '
print(format.format (instructor,subject,term))
|
# statistical_tests.py
# Benjamin Crestel, 2020-08-07
import numpy as np
from scipy.stats import t
def two_tailed_t_test(samples: np.ndarray, H0: float):
"""
Calculate a two-tailed t-test on the samples
null hypothesis: samples_mean = H0
:param samples: array of shape (size of each sample, number of... |
import numpy as np
import pandas as pd
import time
print("Reading full csv...")
overall_start = time.time()
full_tweets = pd.read_csv('corona_tweets_data.csv', error_bad_lines=False)
reading_time = time.time() - overall_start
print("Reading time: ", reading_time)
print(len(full_tweets), " tweets")
print("Filtering..... |
import librosa
import numpy as np
import os
#pip install progressbar2
from progressbar import ProgressBar
import shutil
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matpl... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
# dfs, check all val equal to root
return se... |
from fastapi_sqlalchemy import db
from loguru import logger
from sqlalchemy.exc import SQLAlchemyError
class ModelManagementMixin:
def save(self):
logger.info(f"Saving {self!r}")
db.session.add(self)
self._flush()
return self
def update(self, **kwargs):
for attr, value... |
import time
import ctypes, sys
from Offsets import *
sys.path.insert(1, "classes/")
import pymem
import pymem.process
from features_reads import read
import features_check
import keyboard
import win32api
class rapidfire():
def __init__(self) :
read("rapid fire")
key = self.get_key... |
result=int(0);
def sum(i):
global result;
if(i>0):
remainder=int(i%10);
result=result+remainder;
sum(i/10);
return result;
def main():
i=int(input("Enter a value: "));
print("Result is: ",sum(i));
if __name__=="__main__":
main(); |
#!/usr/bin/env python3
"""
Deploy and execute a simple "standalone program" that just
returns a constant value:
AARCH64: 0x666badc0ffeed00d
ARM: 0xc0ffee
"""
import sys
from depthcharge import cmdline, log
from depthcharge.cmdline import create_depthcharge_ctx
parser = cmdline.ArgumentParser()
args = parser.pa... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 13:01:14 2020
@author: ADubey4
"""
import onnx
model = onnx.load(".\model\model.onnx")
onnx.checker.check_model(model)
onnx.helper.printable_graph(model.graph) # to check in python console
input_node = model.graph.input[0]
print(input_node.type.tensor_type)
|
import entropy._entropy as _entropy
def entropy(data):
"""Compute the Shannon entropy of the given string.
Returns a floating point value indicating how many bits of entropy
there are per octet in the string."""
return _entropy.shannon_entropy(data)
def absolute_entropy(data):
"""Compute the "absolute" entropy ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.