content stringlengths 5 1.05M |
|---|
import time
import random
import statsd
counter_name = 'lmm.test'
wait_s = 1
for i in range(10):
c = statsd.StatsClient('127.0.0.1', 8125)
random_count = random.randrange(1, 100)
print("Count=(%d)" % (random_count))
c.gauge(counter_name, random_count)
t = c.timer(counter_name)
t.start()
while... |
# modulo aleatorio
from random import choice
from datetime import date
# cores
cores = {'limpa': '\033[m',
'titulo': '\033[1;4;35m',
'preto': '\033[1;30m',
'vermelho': '\01933[1;31m',
'verde': '\033[1;32m',
'amarelo': '\033[1;33m',
'azul': '\033[1;34m',
'roxo'... |
# 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, ... |
# File used by pyinstaller to create the executable
from PFERD.__main__ import main
if __name__ == "__main__":
main()
|
'''Entry point to the Flask application'''
# from .app import create_app
# APP = create_app() |
def giveWord(phrase):
for item in phrase:
print(item[0]))
print(giveWord("tallyhoo")) |
#!/usr/bin/env python3
from importlib import import_module
import sys
SP = '\N{SPACE}'
HLIN = '\N{BOX DRAWINGS LIGHT HORIZONTAL}' * 2 + SP # ──
VLIN = '\N{BOX DRAWINGS LIGHT VERTICAL}' + SP * 3 # │
TEE = '\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}' + HLIN # ├──
ELBOW = '\N{BOX DRAWINGS LIGHT U... |
#!/usr/bin/python
#import
import lcd
import time
import subprocess
def main():
# Main program block
# Initialise display
lcd_init()
ip = subprocess.check_output('hostname -I', shell=True).decode('utf-8')
# Send some right justified text
lcd_byte(LCD_LINE_1, LCD_CMD)
lcd_string(ip, 1)
i... |
# Copyright 2017 AT&T Intellectual Property. All other 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 require... |
#!/usr/bin/env python3
# To find catkin python3 build of tf2_py
import sys
sys.path.insert(0, '/home/smb/catkin_ws/devel/lib/python3/dist-packages')
import json
import rospy
import message_filters
import torch
import numpy as np
import cv2
import tf2_ros
from cv_bridge import CvBridge
from scipy.spatial.transform imp... |
from modules.lexer.position import Position
from modules.lexer.token_types import TT
from modules.visitor import errors as v_errors
from .ast_node import ASTNode
class TernaryOperationNode(ASTNode):
def __init__(self, operations, values):
self.left, self.middle, self.right = values
self.operations ... |
import numpy as np
import pandas as pd
import os
import dotenv
import matplotlib.pyplot as plt
project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
dotenv_path = os.path.join(project_dir, '.env')
dotenv.load_dotenv(dotenv_path)
def ks_gini(loss, score):
"""Calculate KS and Gini score"""
... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
import re
import numpy as np
import warnings
import copy
from .utils import is_pos_int, is_non_neg_int, \
is_proportion, is_positive, is_non_negative, \
inherits
class layout:
def __init__(self,
ncol=None,
nrow=None,
byrow=None,
re... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from .analysis import polyfit
#for task 2E
def plot_water_levels(station, dates, levels):
"""displays a plot of the water level data against time for a station"""
# Plot
plt.plot(dates, levels)
... |
#!/usr/bin/python3
# coding: utf-8
import gensim
import logging
import sys
from evaluate_lemmas import evaluate_synsets
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# Loading model and semantic similarity dataset
modelfile, wordnet_s... |
"""
Here: f(x) = x^2 - A
We've got to minimize f(x) to find the square root of A, which is x.
Newton-Raphson's method -
Primer:
For a curve, tangent at point x_k is:
a) y = f'(x)*(x - x_k) + f(x_k) (slope is f'(x), f(x_k) is "c")
The method now says, let's start from an initial condition: x_k
The ne... |
# MIT License
#
# Copyright (c) 2018 Evgeny Medvedev, evge.medvedev@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# ... |
#!/usr/bin/env python3
PROJECT = 'ai-analytics-solutions'
BUCKET = 'ai-analytics-solutions-kfpdemo'
REGION = 'us-central1'
INPUT = 'input.json'
RUNNER = 'DirectRunner'
OUTPUT = 'output.json'
# to try it in streaming mode, write one json message at a time to pub/sub
# and change the input to beam.io.ReadFromPubSub(top... |
"""Connector stuffs."""
import random
from asyncio import sleep as asyncio_sleep
from asyncio import wait_for
from ssl import SSLContext
from typing import Coroutine
from urllib.parse import ParseResult
# import h2.connection (unused)
from hyperframe.frame import SettingsFrame
# from concurrent import futures (unused... |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RUuid(RPackage):
"""Tools for generating and handling of UUIDs (Universally Unique
Id... |
import logging
import click
import haascli
from haascli import Defaults
from haascli import cluster as haascli_cluster
from haascli import stack as haascli_stack
from haascli import data as haascli_data
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--debug/--no-debug', defau... |
# -*- coding: utf-8 -*-
"""
@author: Yi Zhang
@contact: zhangyi_aero@hotmail.com
@time:
"""
import sys
if './' not in sys.path: sys.path.append('./')
from screws.freeze.base import FrozenOnly
class _2nCSCG_CellIS(FrozenOnly):
""""""
def __init__(self, cell):
""""""
self._cell_ = cell
... |
import os
import sys
import tempfile
import argparse
from generate_complex_files import generate_complexes
from pymol import cmd
def main():
# get form data and initialize parameters
receptor = sys.argv[1] # receptor
poses = sys.argv[2] # ligand poses
score = sys.argv[3] # output file path
rmsd = s... |
# -*-coding:utf-8-*-
import os
from xml.etree.ElementTree import dump
import json
import pprint
import argparse
from Format import VOC, COCO, KITTI, YOLO
parser = argparse.ArgumentParser(description='label Converting example.')
parser.add_argument('--datasets', type=str, help='type of datasets')
parser.add_argumen... |
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import bottle
from bottle import request, route, hook
import beaker.middleware
from setting import session_path
session_opts = {
'session.type': 'file',
'session.data_dir': session_path,
'session.auto': True,
}
app_middlware = beaker.middleware.SessionMiddle... |
# Extremely hard.
import collections
import itertools
inp = open("Day20.txt").read()
tilesLines = inp.strip().split("\n\n")
tilesSides = {}
tiles = {}
for tilelines in tilesLines:
lt = ""
rt = ""
name, lines = tilelines[5:].split(":\n")
lines = lines.split()
for line in lines:
rt += line[-... |
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table
import pandas as pd
import scipy.interpolate
import plotly.express as px
from math import sqrt
import os, random
from scipy.optimize import curve_fit
from numpy import exp, log
# """Extracting all files"""
# files = os.listdir(".")
# d... |
# 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.
# --------------------------------------------------------------------... |
#!/usr/bin/env python3
import pathlib
class TestSet1:
def test_challenge01(self):
from cryptopals.set1.challenge01 import challenge01, BYTES, RESULT
res = challenge01(BYTES)
assert res == RESULT, "The result does not match the expected value"
def test_challenge02(self):
fro... |
from dataclasses import dataclass, field
__NAMESPACE__ = "NISTSchema-SV-IV-atomic-NCName-pattern-5-NS"
@dataclass
class NistschemaSvIvAtomicNcnamePattern5:
class Meta:
name = "NISTSchema-SV-IV-atomic-NCName-pattern-5"
namespace = "NISTSchema-SV-IV-atomic-NCName-pattern-5-NS"
value: str = fie... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from segmentation.models import Image, UserImage, AssignedImage
import sys
# usage: python manage.py assignImage 1 COCO_val2014_000000000042.jpg
class Command(BaseCommand):
def handle(self, *args, **kwargs):
userid = ... |
### Takes in a Caffe log output from training, and extracts
### the training and testing loss at each iteration (multiple of 100).
### Dumps this to a .csv for local visualization.
import re
import pandas as pd
with open('lstm_np_03/lstm_np_03_log.txt', 'rb') as f:
lines = f.read().split('\n')
train_losses = []... |
def sliding_window(image, window_size, step_size):
for y in range(0, image.shape[0], step_size[1]):
for x in range(0, image.shape[1], step_size[0]):
yield (x, y, image[y: y + window_size[1], x: x + window_size[0]]) |
# mimic ffequity.py in process but do it for carbon allocation
from utils.dataframefile import DataFrameFile
from processors.validator import Validator
from processors.analyst import Analyst
folderNames = ['assessment', 'financial_data']
def main():
# create object instance of DataFrameFile
# have it read in ... |
import numpy as np
import pandas as pd
def merge(path_to_mf_lf_1, path_to_mf_lf_2, path_to_mf_hf_1, path_to_mf_hf_2, path_to_sf,
path_to_mf_lf, path_to_mf_hf, path_to_sf_copy):
"""Merge multi fidelity results to be able to assess differences between scenarios."""
mf_lf = merge_one_case(pd.read_csv(p... |
# Copyright 2016 Oursky Ltd.
#
# 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, ... |
from unittest.case import TestCase
from probability.distributions import Lomax
class TestLomax(TestCase):
def setUp(self) -> None:
pass
def test_fit(self):
for lambda_, alpha in zip(
(1, 2, 4, 6),
(2, 2, 1, 1)
):
lomax_orig = Lomax(lambd... |
from rest_framework import serializers
from books.serializers import UserSerializer, BookSerializer, LibrarySerializer
from waitlist.models import WaitlistItem
class WaitlistItemSerializer(serializers.ModelSerializer):
user = UserSerializer()
library = LibrarySerializer()
book = BookSerializer()
adde... |
"""
This file enumerates JSON-LD Framing options to be used in serialising Irish Spatial Data Exchange metadata objects
"""
from enum import Enum
class JSONLDFraming(Enum):
DATASET_SCHEMA_ORG = {"@context":
{
"@vocab": "https://schema.org/"
},
"@id": None
}
"""
Fram... |
# Compatible with ranger 1.6.0 through ranger 1.7.*
#
# This plugin serves as an example for adding key bindings through a plugin.
# It could replace the ten lines in the rc.conf that create the key bindings
# for the "chmod" command.
import ranger.api
old_hook_init = ranger.api.hook_init
def hook_init(fm):
old_... |
"""
Environments
* Bind names to values, allowing lookup and modification by trampling
* Chain off of one another, allowing lookups and assignments to other
environments
"""
import json
class Environment:
def __init__(self, name = "(?)", upstream = None, default_value = "",
initial_bindings = None):... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from secretpy import ColumnarTransposition
from secretpy import alphabets
import unittest
class TestColumnarTransposition(unittest.TestCase):
alphabet = (
alphabets.ENGLISH,
alphabets.ENGLISH,
alphabets.ENGLISH,
alphabets.GERMAN,
... |
year = 0 # Year 0
tuition = 10000 # Year 1
while tuition < 20000:
year += 1
tuition = tuition * 1.07
print("Tuition will be doubled in", year, "years")
print("Tuition will be $" + format(tuition, ".2f"),
"in", year, "years")
|
#!/usr/bin/python
from __future__ import absolute_import
from roberta.ev3 import Hal
from ev3dev import ev3 as ev3dev
import math
import os
import time
class BreakOutOfALoop(Exception): pass
class ContinueLoop(Exception): pass
_brickConfiguration = {
'wheel-diameter': 5.6,
'track-width': 18.0,
'actors': ... |
"""
Django settings for feder project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import sys
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myf... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
from network.mine import Miner, cite_graph
from sklearn.feature_extraction import text
from utils.lib import O
from collections import OrderedDict
from classify.model import read_pap... |
from collections import Iterable
import numpy as np
def get_item(collection, item_path):
"""Retrieve an item from a component's collection, possibly going through
multiple levels of nesting.
:param collection: the collection where the item resides.
:param item_path: a string with the name of the ite... |
#from decimal import decimal
from django.conf import settings
from django.urls import reverse
from django.shortcuts import render, get_object_or_404
from paypal.standard.forms import PayPalPaymentsForm
from orders.models import Order
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def payment_done(... |
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import pickle
import os
driver = webdriver.Chrome('D:\py\chromedriver_win32\chromedriver.exe')
link_list = []
link_list_v = []
#load profile links from file links.txt
if os.path.getsize('links.txt') > 0:
with open('links.txt', 'rb') as fp:
l... |
import re
pattern = r'(\||#)([A-Za-z]+ *[A-Za-z]+)\1([0-9]{2}\/[0-9]{2}\/[0-9]{2})\1([0-9]+)\1'
text = input()
calories_count = 0
CALORY_FOR_DAY = 2000
matches = re.findall(pattern, text)
days = 0
for match in matches:
if match != []:
food = match[1]
time = match[2]
calories = int(match[3]... |
import pandas as pd
import numpy as np
from itertools import product
from scipy.stats import chisquare
import matplotlib.pyplot as plt
from Bio.Seq import Seq
import logomaker
from scipy.stats import rankdata
window = 30
codons = [''.join(i) for i in product('AGTC', repeat=3)]
context_2 = pd.read_csv("context.tsv",... |
import pytest
from django.core import mail
from grandchallenge.subdomains.utils import reverse
from grandchallenge.participants.models import RegistrationRequest
from tests.factories import UserFactory, RegistrationRequestFactory
from tests.utils import get_view_for_user
@pytest.mark.django_db
@pytest.mark.parametri... |
#!/usr/bin/env python3
import sys
import math
import csv
import itertools
from pprint import pprint
import func
INPUTFILE = './task05.input'
def main():
with open(file=INPUTFILE, mode='r') as fileinput:
lines = list(map(int, fileinput.readlines()))
steps = 0
index = 0
reading ... |
import random
import string
import re
import os.path
import jsonpickle
import getopt
import sys
from models.contact import Contact
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
for o, a in opts:
... |
import datetime
import time
import re
from email.utils import formatdate # rfc822
import markdown
from wmk_utils import slugify
__all__ = [
'date_to_iso',
'date_to_rfc822',
'date',
'date_short',
'date_short_us',
'date_long',
'date_long_us',
'slugify',
'markdownify',
'truncat... |
from .database import db
from .tokens import Tokens
from .user import User
__all__ = [
'db',
'Tokens',
'User'
]
|
"""
An example of mixed python/c code fuzzing. In this case, it is assumed that the Pillow
package in use has been compiled with e.g. afl's llvm_mode..
"""
from cpytraceafl.rewriter import install_rewriter
install_rewriter()
from cpytraceafl import fuzz_from_here, DEFAULT_MAP_SIZE_BITS, get_map_size_bits_env
... |
import base64
import json
import os
import time
import cv2
import numpy as np
import requests
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile
from django.http import HttpResponse
from cv.controllers.log import logger
from cv.models.plant_disease_recognizer import pdr
URL_PORT =... |
import pandas as pd
from ai4netmon.Analysis.bias import generate_distribution_plots as gdp
from matplotlib import pyplot as plt
from matplotlib import cm, colors
AGGREGATE_DATA_FNAME = 'https://raw.githubusercontent.com/sermpezis/ai4netmon/dev/data/aggregate_data/asn_aggregate_data_20211201.csv'
BIAS_DF = './data/bia... |
import os
from Jumpscale import j
from .OauthInstance import OauthClient
JSConfigs = j.baseclasses.object_config_collection
class OauthFactory(JSConfigs):
__jslocation__ = "j.clients.oauth"
_CHILDCLASS = OauthClient
|
from backend.database.models import StaffToken
from backend.site import StaffSite
import cognitojwt
from cryptography.fernet import Fernet
from pyramid.httpexceptions import HTTPBadRequest
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.view import view_config
import datetime
import hashlib
import json
im... |
"""
Here we'll define the dropdown with
all the information options.
"""
from __future__ import unicode_literals
import re
import subprocess
import sys
import click
import isort # noqa: F401
import questionary
# import snoop
from questionary import Separator, Style
subprocess.run(["isort", __file__])
# @snoop
def... |
# Copyright (c) Fahad Ahammed 2021.
|
# -*- encoding:utf-8 -*-
"""
company:IT
author:pengjinfu
project:migu
time:2020.5.4
"""
from info import user, pwd
import requests
import execjs
import asyncio
class Login():
def __init__(self):
self.session = requests.Session()
self.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 1... |
import os
# Build paths (PROJECT_DIR = sandbox and BASE_DIR = root)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
|
import os
from pathlib import Path
import pytest
from pipeline.execution import _patch_subprocess_environment
@pytest.mark.unit
def test_patch_subprocess_environment(monkeypatch):
monkeypatch.setattr(os, "environ", {})
path = Path("C:/dummy_project_directory")
config = {"project_directory": str(path)}
... |
/usr/local/lib/python3.6/copyreg.py |
from fila_da_creche.queries.dt_atualizacao import get_dt_atualizacao
from fila_da_creche.queries.fila_por_escolas import get_fila_por_escolas
from fila_da_creche.queries.espera import get_espera
from rest_framework.response import Response
from rest_framework.views import APIView
from utils.get_raio import get_r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenAppTestapiiSyncModel(object):
def __init__(self):
self._in_1 = None
self._in_2 = None
@property
def in_1(self):
return self._in_1
@in... |
import pandas
import requests
import re
from .utils import \
last_seven_days, get_str_day, \
strip_irc_chars, strip_channel_name, \
get_nick_from_message
# close "A value is trying to be set on a copy of a slice from a DataFrame." warning
pandas.options.mode.chained_assignment = None
def get_log(base_url, channel, d... |
import numpy
import noodles
import time
from copy import copy
@noodles.schedule(call_by_ref=['gobble'])
def mul(x, y, gobble):
return x*y
@noodles.schedule(call_by_ref=['gobble'])
def factorial(x, gobble):
time.sleep(0.1)
if numpy.all(x == 0):
return numpy.ones_like(x)
else:
return mul... |
# power_of_2.py
#
# print a list of powers of 2
# also includes input validation
# CSC 110
# Fall 2011
top = int(input('Enter a value between 1 and 20: '))
# an indefinite loop for input validation
while top < 1 or top > 20:
print('Error. ' + str(top) + ' is not between 1 and 20. Please try again.')
top ... |
# -*- coding: utf-8 -*-
"""
discopy error messages.
"""
IGNORE_WARNINGS = [
"No GPU/TPU found, falling back to CPU.",
"Casting complex values to real discards the imaginary part"]
def empty_name(got):
""" Empty name error. """
return "Expected non-empty name, got {}.".format(repr(got))
def type_er... |
alien_0 = {'color': 'Green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
answer = 17
if answer != 17:
print("error")
else:
print('ok')
|
from ntptime import settime
from micropython import const, alloc_emergency_exception_buf
from uctypes import addressof
from machine import Pin, Timer, I2C, WDT
from gc import collect
from esp32 import RMT
from wifiman import get_connection
import time, dst
disp=const(0)
cyear=const(0)
cmonth=const(1)
cday=const(2)
ch... |
from settings import *
def nearby_cells_count(cells: list, x: int, y: int):
res = []
if (x > 0) and (y > 0) and (x < cell_count-1) and (y < cell_count-1):
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if (i, j) != (x, y):
res.append(cells[... |
# 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 u... |
import json
annotation_filename_1 = 'data/images/annotations/instances.json'
annotation_filename_2 = 'data/images/annotations/instances_remaining.json'
with open(annotation_filename_1,'r') as f:
annotations_1 = json.load(f)
with open(annotation_filename_2,'r') as f:
annotations_2 = json.load(f)
new_imag... |
import pymoo.problems as mop
from pymoo.factory import get_problem
import numpy as np
import time
import math
import mabs.utils.reproblems as reprob
class optimization_test_functions(object):
def __init__(self, test):
self.test_name = test
def predict(self, test_name, x, num_vars=2, num_objs=None... |
PACKAGE_NAME = 'cockroachdb'
SERVICE_NAME = 'cockroachdb'
DEFAULT_TASK_COUNT = 3
DEFAULT_POD_TYPE = 'cockroachdb'
DEFAULT_TASK_NAME = 'node'
|
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
# Create your views here.
from login.models import User
def login(request):
'''显示登录页面'''
# 判断用户是否已经登录
# 获取session
if request.session.has_key(... |
import ijmfttxt
# Initialize and setup Connection to TXT Controller
txt = ijmfttxt.TXT()
# Get Motor connected to Output 1
motor_hl = txt.motor(1)
# Get Motor connected to Output 2
motor_vl = txt.motor(2)
# Get Motor connected to Output 3
motor_vr = txt.motor(3)
# Get Motor connected to Output 4
motor_hr = txt.motor(... |
import os
import json
import codecs
import sys
from keras import layers
from keras import models
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
# This is module with image preprocessing utilities
from keras.applications import VGG16
from keras.callb... |
from settings import TOKEN, headers
import telebot
from telebot import types
import requests
from bs4 import BeautifulSoup
import sqlite3
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=["start"])
def start(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardB... |
# Copyright 2020 Francesco Ceccon
#
# 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 writ... |
from datetime import date, datetime
dateformat = "%b %d %Y %H:%M:%S"
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.strftime(dateformat)
raise TypeError ("Type %s not serializable" % type(obj)) |
from flask import Flask, redirect, render_template, request, url_for
import sys
import os
import helpers
from analyzer import Analyzer
N_TWEETS = 100
app = Flask(__name__)
def get_scores(tweets):
# absolute paths to lists
positives = os.path.join(sys.path[0], "positive-words.txt")
negatives = os.path.j... |
def case_lookup(request):
if request.method == 'POST':
url = reverse('case-details', kwargs={'case_id': request.POST['case-id']})
return redirect(url)
else:
return render(request, 'case_lookup.html')
@login_required
def case_details(request, case_id=None):
'''
Removed from main app because it's n... |
import datetime
from modules.Module import Module
class Date(Module):
def __init__(self, pipe):
super().__init__(self, pipe)
def run(self, command: str, regex) -> str:
try:
now = datetime.datetime.now()
day = self._parse_day(now)
self.say('It is {0:%A} {0:... |
class Region(object):
LEFT = 1
MIDDLE = 2
RIGHT = 3
_names = None
_values = None
@classmethod
def names(cls):
return cls._names
@classmethod
def values(cls):
return cls._values
class Color(object):
OFF = 0
RED = 1
ORANGE = 2
YELLOW = 3
GREEN ... |
f = open('text.txt')
text = f.read()
#Словарь
import pymorphy2
morph = pymorphy2.MorphAnalyzer()
def LEG (word):
p = morph.parse(word)[0]
pp = p.normal_form
return pp
#print(LEG('звери'))
LEG ('звери')
#e = список знаков препинания формат ,"#знак препинания"
e = ",", ".","!","-","?","»","«","—"
for i i... |
#Resolvendo o 060 com Módulo
#Módulo para calcular o fatorial:
from math import factorial
n = int(input('Digite um número para cálculo do fatorial: '))
fatorial = factorial(n)
print('O fatorial do número {}! é: {}'.format(n, fatorial)) |
from .reproducibility import kth_diag_indices, pairwise_distances
from .embedding import PCA, MDS, tSNE, SpectralEmbedding, PHATE
__all__ = ["kth_diag_indices",
"pairwise_distances",
"PCA",
"MDS",
"tSNE",
"SpectralEmbedding",
"PHATE"
]
|
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
"""The rtorrent component."""
|
import collections
import logging
from functools import partial
from Qt import QtWidgets, QtCore
import qtawesome
from bson.objectid import ObjectId
from avalon import io
from openpype import style
from openpype.pipeline import (
HeroVersionType,
update_container,
remove_container,
discover_inventory... |
from tkinter import *
from tkinter import ttk
class Calculator:
calc_value = 0.0
div_trigger = False
mult_trigger = False
add_trigger = False
sub_trigger = False
def button_press(self, value):
if value == "AC":
self.calc_value = 0.0
self.div_trigger = False
... |
# -*- coding: utf-8 -*-
"""Vector classification algorithms, not designed specifically for time series."""
|
# flake8: noqa
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# https://seaborn.pydata.org/generated/seaborn.set_context.html
# https://seaborn.pydata.org/generated/seaborn.set_style.html
sns.set_style("white")
sns.set_context("paper", font_scale=1)
np.random.seed(12345)
from numpy_ml.lda i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.