content stringlengths 5 1.05M |
|---|
import random
import collections
import typing as t
import datetime as dt
import pytz
import peewee as pw
from playhouse.postgres_ext import DateTimeTZField, BinaryJSONField
class Counter(collections.Counter):
def inc(self, element: str) -> int:
self.update(**{element: 1})
return self[element]
... |
print("Challenge 30: WAF program to find the digits which are absent in a given mobile number.")
mobile = input('Please enter a mobile number: ' )
all = '0123456789'
print('missing digits are ', set(all) - set(mobile)) |
# Generated by Django 2.0.9 on 2018-11-28 02:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0009_aboutmembers_team_department'),
]
operations = [
migrations.AlterField(
model_name='aboutmembers',
na... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
class UnknownObjectType(Exception):
pass
def get_class_for_object_type(object_type):
return _OBJ_META.get_class_for_object_type(object_type)
class _ObjectType(object):
def __init__(self, name, api_... |
# Copyright 2019 CNIT, Francesco Lombardo, Matteo Pergolesi
#
# 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 app... |
"""
Units data for test cases
Data is obtained from
http://motor.ece.iit.edu/data/
"""
from numpy import array
# Transmission line data format
F_BUS = 0
T_BUS = 1
BR_X = 2
RATE_A = 3
# Generator format
GEN_BUS = 0
COST_C = 1
COST_B = 2
COST_A = 3
PG_MAX = 4
PG_MIN = 5
I0 = 6
MIN_DOWN = 7
MIN_UP = 8
RUG = 9
RDG = 10
C... |
# /usr/bin/env python3
# SPDX-FileCopyrightText: Volker Mische <volker.mische@gmail.com>
# SPDX-License-Identifier: MIT
# This script takes a template and some data and creates individual files.
# The files are created in a directory called `md`, each file is named
# with the pretalx ID.
import argparse
import json
... |
# Imports from your apps
from usaspending_api.common.helpers.business_categories_helper import (
BUSINESS_CATEGORIES_LOOKUP_DICT,
get_business_category_display_names,
)
def _get_all_business_category_field_names():
return list(BUSINESS_CATEGORIES_LOOKUP_DICT.keys())
def _get_first_ten_business_category_... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
"""
hbmqtt_sub - MQTT 3.1.1 publisher
Usage:
hbmqtt_sub --version
hbmqtt_sub (-h | --help)
hbmqtt_sub --url BROKER_URL -t TOPIC... [-n COUNT] [-c CONFIG_FILE] [-i CLIENT_ID] [-q | --qos QOS] [-d] [-k KEEP_ALIVE] [--cl... |
#!/usr/bin/env python
"""
Script of word embedding model with Character-level RNN information.
The character-level RNN is similar to the character model for machine traslation.
<Achieving Open Vocabulary Neural Machine Translation with Hybrid Word-Character Models>
https://pdfs.semanticscholar.org/0126/72696e5c1a1b06a... |
'''for c in range(0, 7, 2):
print(c)
print ('FIM')'''
'''n = int(input('Digite um número'))
for c in range(0,n+1):
print(c)
print('FIM')'''
'''i = int(input('INICIO'))
f = int(input('FIM'))
p = int(input('Passo'))
for c in range (i, f+1, p):
print(c)
print('FIM)')'''
for c in range(0,3):
n= int(input... |
def _yq_replace_impl(ctx):
if ctx.toolchains["@rules_yq//yq:toolchain"].os == "windows":
fail("windows is not supported.")
yq = ctx.toolchains["@rules_yq//yq:toolchain"].yq
src_paths = []
for src in ctx.files.srcs:
src_paths.append(src.path)
exec_file = ctx.actions.declare_file(ctx.l... |
# 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 rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
# DFS or BFS
... |
import discord
from discord.ext import commands
class Owner(commands.Cog):
"""Only DvH can use it"""
emoji = "👑"
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
return await self.bot.is_owner(ctx.author)
@commands.command(help="Load a cog")
async def... |
from database.database import db
import json
from flask import jsonify
from sqlalchemy import Column, Integer, String, DateTime, Date, and_
from pprint import pprint
from datetime import datetime
class OutputNews(db.Model):
__tablename__ = "output_news"
id = db.Column(db.Integer, primary_key=True)
news_title = db.C... |
from functional_tests import graphql_utils
LOG_IN_MUTATION = """
mutation LogInMutation($email: String!, $password: String!) {
logIn(email: $email, password: $password) {
user {
id
name
}
}
}
"""
def test_log_in(api_client, user_factory):
"""
Users should be able to log in by providin... |
#!/usr/bin/python3
## MODULES ##
## Data analysis and plotting packages
import numpy as np
# Matplotlib Modules
from matplotlib.ticker import MultipleLocator
# Tkinter Modules
from tkinter import Toplevel
## FELion modules
from FELion_normline import norm_line_felix, felix_binning
from FELion_definitions import Sh... |
from __future__ import print_function
# class Solution:
# # @param n, an integer
# # @return an integer
# def reverseBits(self, n):
# result = 0
# for i in range(32):
# result <<= 1
# result |= n & 1
# n >>= 1
# return result
if __name__ == '__main__':
print(0<<2)
... |
# -*- coding: utf-8 -*-
import serial
import time
from flask import request
from flask import jsonify
import os
from flaskext.mysql import MySQL
import subprocess
import hashlib
import pyglet
import time
import json as JSON
from subprocess import Popen, PIPE, STDOUT
import collections
import datetime
import locale
im... |
from core.templatetags import register
import re
@register.simple_tag
def reg_exp(regex, str):
"""
Does a regexp match on the given string and returns the match
"""
return re.match(regex, str)
|
# Generated by Django 2.2.10 on 2020-04-30 18:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("ui", "0028_add_edx_endpoint_models"),
]
operations = [
migrations.AddField(
model_name="collection",
name="is_logge... |
# Implicit.py
# Represents MNPP domains implicity by a sequence of "snakes"
# Equivalent to a wiring diagram (AKA pseudoline arrangement)
# ImplGraph.explicit() turns an implicit domain into a rhombus tiling (see Graph.py)
from Graph import *
class ImplGraph:
def __init__(self):
self.d = 0
self.outcomes = [... |
from setuptools import setup, find_packages
package_name = 'cloudwatch_robot'
setup(
name=package_name,
version='2.0.0',
package_dir={'': 'src'},
packages=find_packages(where='src'),
data_files=[
('share/' + package_name + '/launch', ['launch/await_commands.launch.py']),
('share/' ... |
from selenium import webdriver
DIRECTORY = 'reports'
NAME = 'IPHONE'
CURRENCY = '₹'
MIN_PRICE = '70000'
MAX_PRICE = '80000'
FILTERS = {
'min': MIN_PRICE,
'max': MAX_PRICE
}
BASE_URL = "https://www.amazon.in/"
def get_chrome_web_driver(options):
return webdriver.Chrome('./chromedriver.exe',... |
# ========================================================
# CTEC 121 - Final Project - Sliding Puzzel
# ========================================================
# File: tileboard.py
# Description: This file implements the GameBoard class
# Author: Robin Murray
# ==================================================... |
from distutils.core import Extension
import os
import pytest
import pkgconfig
os.environ['PKG_CONFIG_PATH'] = os.path.abspath('./data')
PACKAGE_NAME = 'fake-gtk+-3.0'
def test_exists():
assert pkgconfig.exists(PACKAGE_NAME)
assert pkgconfig.exists('fake-openssl')
@pytest.mark.parametrize("version,expected"... |
"""
datazen - An interface for managing on-disk data by loading it and making
discrete changes.
"""
# built-in
from contextlib import contextmanager
import logging
import os
import threading
from typing import Iterator
# third-party
import git
# internal
from datazen.compile import write_dir
from datazen.l... |
import numpy as np
import os
import json
import cv2
import sys
np.random.seed(2020) # to ensure you always get the same train/test split
data_path = '../data/RedLights2011_Medium'
gts_path = '../data/hw02_annotations'
split_path = '../data/hw02_splits'
os.makedirs(split_path, exist_ok=True) # create directory if nee... |
__version__ = "0.3.4"
from .score import *
from .scorer import *
|
import getpass
import os
from urllib.parse import urlsplit
import psycopg2
import pytest
import sql
from IPython import get_ipython
# If this fixture becomes too slow, we can setup the database once, and run each test in a transaction.
@pytest.fixture()
def db():
# This can't be named DATABASE_URL, because ipyth... |
from tau.core.forms import CustomAuthenticationForm
from django.conf import settings
from django.urls import path, re_path, include, reverse_lazy
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.views.generic.base import Redirect... |
# Functions from the following NumPy document
# http://docs.scipy.org/doc/numpy/reference/routines.indexing.html
# "NOQA" to suppress flake8 warning
from clpy.indexing import generate # NOQA
from clpy.indexing import indexing # NOQA
from clpy.indexing import insert # NOQA
|
from typing import NamedTuple, Optional, Dict
from enum import Enum
import re
from ..core.utils import parse_params
# https://tools.ietf.org/html/rfc2045#section-5.1
# https://tools.ietf.org/html/rfc7231#section-3.1.1.1
class MediaTypes(str, Enum):
application = 'application'
audio = 'audio'
chemi... |
import json
import datetime
from user import User
class UserEncoder(json.JSONEncoder):
def default(self, u):
if isinstance(u, User):
dict = {
"id": u.id,
"name": u.name,
"birthdate": u.birthdate.strftime("%d %b %y")
}
return dict
else:
type_name = u.__class__.__name__
raise TypeError(... |
L = ["katak", "burung", "ayam", "ibu", "dia"]
input_user = int(input("Karakter huruf : "))
for i in range(len(L)):
if input_user == len(L[i]):
print(L[i], end=" ") |
from igf_data.igfdb.pipelineadaptor import PipelineAdaptor
from ehive.runnable.IGFBaseProcess import IGFBaseProcess
class ChangePipelineSeedStatus(IGFBaseProcess):
def param_defaults(self):
params_dict=super(ChangePipelineSeedStatus,self).param_defaults()
return params_dict
def run(self):
try:
... |
from .itm_framer import ITMOpcode
from .itm_framer import build_value
from .itm_framer import ITMStimulusPort
from .itm_framer import ITMFramer
from .itm_framer import MAX_ITM_FRAME_SIZE |
# the inclusion of the tests module is not meant to offer best practices for
# testing in general, but rather to support the `find_packages` example in
# setup.py that excludes installing the "tests" package
import unittest
import polar_bear as pb
import pandas as pd
class TestPolarBear(unittest.TestCase):
maxDif... |
"""
This file is part of hybridbox-api
:copyright: (c) 2018 by Jakob Schreiner.
:license: BSD, see LICENSE for more details.
"""
import requests
import base64
import hashlib
import re
import json
class Session(object):
"""The origin of everything you want to do with the hybridbox-api.
Configurat... |
from datetime import date
import pytest
from allocation import bootstrap, views
from allocation.domain import commands
from allocation.service_layer import unit_of_work
today = date.today()
@pytest.fixture
def messagebus(session_factory):
bus = bootstrap.bootstrap(
start_orm=False,
uow=unit_of_w... |
# Author: Andreas Christian Mueller <amueller@ais.uni-bonn.de>
# (c) 2012
# Modified by: Paul Nechifor <paul@nechifor.net>
# License: MIT
#Modified by jack wu
import random
import os
import numpy as np
import math
import imp
try:
imp.find_module('PIL')
found = True
except ImportError:
found = False
if fo... |
from django.apps import AppConfig
from connections.utils import create_elastic_connection
class ConnectionsConfig(AppConfig):
name = "connections"
def ready(self):
create_elastic_connection()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: pedroaugustofreitasdearaujo
"""
import os
import pandas as pd
'''Special case handling to address the lack of a std data format. If you wish to use those
discardd files add your changes here'''
def _handleLackOfGeometricData(filename,verbose):
... |
import http_helper
import convert
import sys
if len(sys.argv)==5:
latrange1 = float(sys.argv[1])
latrange2 = float(sys.argv[2])
longrange1 = float(sys.argv[3])
longrange2 = float(sys.argv[4])
http_client = http_helper.HTTP_Helper("credentials.txt")
content=http_client.GetListOfWiFi(latrange1,la... |
import os
import sys
import argparse
import mmutil
sys.path.insert(1, os.path.dirname(__file__))
from .util import *
###################
# local libraries #
###################
sys.path.insert(1, os.path.dirname(__file__))
def call_nb_vae(args) :
import vae_nb
if args.data is None:
_log_msg("Need... |
import numpy as np
import random
from GlobalConstants import TUPLE_SIZE
class ExperienceBuffer(object):
def __init__(self, buffer_size=100000):
self.buffer = []
self.buffer_size = buffer_size
def add(self, experience):
if len(self.buffer) >= self.buffer_size:
self.buffer... |
import mal_types as mal
class MalEnv():
"""Mal environment class.
An environment mapping symbols to Mal objects. Note that the symbols should
be strings, not Mal objects, although the initializer accepts both strings
naming symbols and mal_types.Symbol.
"""
def __init__(self, outer=None, da... |
n , k =list(map(int , input().split()))
string = input()
k = input().split()
substr=0
flag =0
for idx in range(n):
if string[idx] in k:
if flag==1:
substr+=idx+1
else:#flag ==0
substr+=1
flag =1
else:
flag =0
print(substr) |
#!/usr/bin/env python3
import sys
import json
import urllib3
url = "https://nekos.life/api/v2/img/"
options = ["cum", "les", "meow", "tickle", "lewd", "feed", "bj",
"nsfw_neko_gif", "poke", "anal", "slap", "avatar", "pussy",
"lizard", "classic", "kuni", "pat", "kiss", "neko", "cuddle",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MaintainBizOrderServer(object):
def __init__(self):
self._order_server_id = None
self._origin_cost = None
self._out_product_id = None
self._real_cost = None
... |
from precise.skaters.covariance.ewaempfactory import ema_scov
from precise.skaters.covarianceutil.covfunctions import grand_mean, grand_shrink
from sklearn.covariance._shrunk_covariance import ledoit_wolf_shrinkage
import numpy as np
# EWALD short for "Exp Weight Avg" Ledoit-Wolf
# ----------------------------------... |
from screws.freeze.base import FrozenOnly
from objects.CSCG._2d.forms.standard.base.dofs.dof.visualize import _2dCSCG_SF_DOF_VIS
class _2dCSCG_SF_DOF(FrozenOnly):
""""""
def __init__(self, dofs, i):
""" I am the #i global dof of a standard 2d CSCG form.
:param dofs:
:param i:
... |
import os
import requests
import time
def consultar():
os.system('clear')
cep = input('\033[1;36mDigite o CEP pata consultar:\033[1;92m ')
api = requests.get(f'https://viacep.com.br/ws/{cep}/json/').json()
if 'message' not in api:
os.system('clear')
print('\033[1;97mCEP: {}'.format(a... |
import abc
import math
from typing import Dict, Tuple, List
import copy
import torch
import torch.nn as nn
from habitat_baselines.common.baseline_registry import baseline_registry
from habitat_baselines.rl.ppo.policy import (
CriticHead, CategoricalNet
)
from habitat_baselines.rl.ppo.belief_policy import (
Be... |
from tkinter import *
from subprocess import call
import webbrowser
def News():
root.destroy()
call(['python', '/home/pi/std_googleAssistant/GUI/Codes/BabyG/NewsBabyG.py'])
def Calculator():
root.destroy()
call(['python', '/home/pi/std_googleAssistant/GUI/Codes/BabyG/CalculatorBabyG.py'])
def Remind(... |
import sqlalchemy as sa
def execute_sql_string(connection_manager, raw_sql_string):
'''
This function can execute multiple SQL statements.
The output is a list of a list of tuples. e.g. [ [ (one, two), (three, four) ], [ (1,2), (3,4) ] ]
The first tuple in the inner list is the headers.
'''
... |
from __future__ import absolute_import
import random
from copy import copy
from random import Random
from zlib import compress, decompress
import logging
import uuid
from fnmatch import fnmatch
from datetime import datetime, timedelta
import six
from jsonpickle import encode, decode
from parse import compile # pylint... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score
from utils import plot_decision_regions
from O3 import prepare_data
X, Y = ... |
import math
import torch
from torch import nn
from torch.nn import functional as F
import torch.utils.model_zoo as model_zoo
class _NonLocalBlockND(nn.Module):
def __init__(self,
in_channels,
inter_channels=None,
dimension=3,
mode='embedded_gaus... |
class PerformanceCounterCategoryType(Enum, IComparable, IFormattable, IConvertible):
"""
Indicates whether the performance counter category can have multiple instances.
enum PerformanceCounterCategoryType,values: MultiInstance (1),SingleInstance (0),Unknown (-1)
"""
def __eq__(self, *args):
... |
import numpy as np
import gym
from gym import spaces
import tensorflow as tf
from random import random, randint
from tensorforce.environments import Environment
from tensorforce.agents import Agent
from tensorforce.execution import Runner
from heapq import nlargest
import matplotlib.pyplot as plt
import numpy as np
fr... |
def fWord(file):
wordCount = 0
letterCount = 0
minLetter = ''
characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','t','u','v','w','x','y','z']
minn = 99999
letterDict = dict()
file.seek(0)
for line in file:
for letter in line:
if let... |
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return str(self.score)
def comparator(a, b):
if (a.score != b.score):
return (int(b.score) - int(a.score))
else:
... |
import os, math, sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import unwrap
import scipy.constants as constants
from ott_plotti... |
import pickle
import numpy as np
import cv2
import math
import glob, os
from VIF.HornSchunck import HornSchunck
class VIF:
def __init__(self):
self.subSampling = 3
self.rows = 100
self.cols = 134
self.hs = HornSchunck()
self.clf = pickle.load(open(os.path.dirname(os.path... |
from __future__ import absolute_import
import abc
import math
import os
import socket
import struct
from future.utils import with_metaclass
from boofuzz.connections import itarget_connection
def _seconds_to_sockopt_format(seconds):
"""Convert floating point seconds value to second/useconds struct used by UNIX ... |
#from http://rosettacode.org/wiki/Hailstone_sequence#Python
#pythran export hailstone(int)
#runas hailstone(27)
#runas max((len(hailstone(i)), i) for i in range(1,100000))
def hailstone(n):
seq = [n]
while n>1:
n = 3*n + 1 if n & 1 else n//2
seq.append(n)
return seq
|
import json
import os
import pytest
from newsweec.database.news_db import NewsDb
@pytest.fixture()
def news_db_file():
with open("test-news.json", "w") as f:
test_data = {
"topic1": [
{"hello": "link to hello",
"bye": "link to hello"}
],
... |
import os
import pytest
from jina import Flow
from jina.executors import BaseExecutor
@pytest.mark.skipif(
'GITHUB_WORKFLOW' in os.environ,
reason='skip the test on github as it will hang the whole CI, locally is fine',
)
def test_flow_simple_reload(mocker):
mock = mocker.Mock()
class DummyExecutor... |
from dataclasses import dataclass
from bindings.csw.covariance_element_type import CovarianceElementType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class IncludesElement(CovarianceElementType):
class Meta:
name = "includesElement"
namespace = "http://www.opengis.net/gml"
|
#!/usr/bin/env python
# encoding: utf-8
'''
eval.slashtags_eval -- pos tag evaluator
eval.slashtags_eval is a script to evaluate pos-tagged files.
It defines a main method that scores tag accuracy.
'''
# Global imports ---------------------------------------------------------------
import sys, os, re
from argparse ... |
#importando módulo para pegar número aleatório
import random
#continuar jogando, por padrão é 1 (True)
cj = 1
#pontuação (por padrão, 0)
carap1 = coroap1 = carap2 = coroap2 = vp1 = vp2 = cdp = 0
#definindo os players
p1 = input("Nome do player 1: ")
p2 = input("Nome do player 2: ")
#enquanto continuar jogando = 1 (... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of class psychopy.visual.BufferImageStim()
- take a snapshot of a multi-item screen image
- save and draw as a BufferImageStim
- report speed of BufferImageStim to speed of drawing each item separately
"""
from __future__ import division
from __future__ import p... |
"""Concrete implementation of Credential Wrapper providing
a wrapper that uses AES to wrap the credential source
Classes:
* :class:`AESCredentialWrapper`
"""
"""
© Copyright 2020-2021 University of Surrey
Redistribution and use in source and binary forms, with or without
modification, are permitted provided tha... |
import requests
import datetime
class Session:
def __init__(self):
super().__init__()
self.s = requests.Session()
def _get(self):
pass
def _post(self):
pass
class RequestError(Exception):
def __init__(self, status, message=None):
self.status = status
... |
from scrape_website import ScrapeWebsite
from datetime import datetime
class ScrapeMicrocenter(ScrapeWebsite):
"""
Define the ScrapeMicrocenter object which inherits from ScrapeWebsite object
"""
def __init__(self, search_local=False):
"""
Initialize WebScrape object with the base url ... |
from deadshot.configurations.api_server_config_data import config_map
from flask import Flask
import os
'''
Method to initiate the Flask API server
'''
def create_app(config_object_name=None,
config_dict=None,
**kwargs):
app = Flask(__name__)
if config_object_name is None:
... |
import os
import re
import sys
import glob
import json
import validate
import cairosvg
import subprocess
def guard(result, message, metadata = None):
"""Make sure the result is a positive result. Exit otherwise.
Args:
result (bool): A boolean indicating a positive or negative result.
m... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2019-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 typing import Any, Callable, Dict, List, Optional
import attr
from ..types import UNSET
from ..util.serialization import is_not_none
@attr.s(auto_attribs=True)
class Filter:
"""A string conforming to a *limited* set of the filtering operations described in [Google AIP 160](https://google.aip.dev/160).
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import... |
from re import sub
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from nltk import word_tokenize, tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import spacy
from gensim.parsing.preprocessing import remove_stopwords
import pkg_resources
from symspellpy import SymSpell... |
from dotenv import load_dotenv
import os
load_dotenv()
print(os.getenv("MY_VAR"))
print(os.getenv("PATH"))
|
#!/usr/bin/env python3
# coding: utf-8
""" pyconsole - interactive console on Python """
import argparse
from client import main_client
from daemon import main_daemon
__version__ = "0.0"
def parse_commandline_arguments():
"""
A function that parses command line arguments.
"""
formatter_class = ... |
import pyaudio
import time
import numpy as np
import pygame
import math
from scipy.ndimage import gaussian_filter1d
from scipy.special import softmax
from dfts import do_dfts
from util import *
samplerate = 44100
n_samples = 1024
bin_width = samplerate / n_samples
# Setup pygame
pygame.init()
window_w = 865
window_... |
"""
Calculate the length of the sides that fit into the limited volume
"""
__version__ = "1.0.0"
from fitrate import utils
from fitrate._fit import contain, scale_down
|
import copy
import cv2 as cv
from .options import OPTIONS
class CAMERA:
cap_device = OPTIONS.device
cap_width = OPTIONS.width
cap_height = OPTIONS.height
cap = cv.VideoCapture(cap_device)
use_brect = True
def __init__(self):
self.prep()
# pass
def prep(self):
se... |
from math import hypot
'''
Maneira matemática (sem importações)
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hip = (co ** 2 + ca ** 2) ** (1/2)
print('A hipotenusa vai medir {:.2f}'.format(hip))
'''
# Usando biblioteca math
co = float(input('Comprimento d... |
import cv2
import os.path
# 使用opencv按一定间隔截取视频帧,并保存为图片
filepath = r'G:/1116_3/' # 视频所在文件夹
pathDir = os.listdir(filepath)
# a = 1 # 图片计数
for allDir in pathDir:
# a = 1
videopath = r'G:/1116_3/' + allDir
print(videopath)
vc = cv2.VideoCapture(videopath) # 读入视频文件
# vc = cv2.VideoCaptu... |
from .cli import main
from .web import create_app
__all__ = ['main', 'create_app']
|
from click.testing import CliRunner
from resolos.interface import (
res_remote_add,
res_remote_remove,
res_init,
res_sync,
res
)
from resolos.remote import read_remote_db, list_remote_ids, delete_remote
from tests.common import verify_result
import logging
from pathlib import Path
import os
log... |
from __future__ import print_function
import sys, os, subprocess
import requests
import json
import argparse
import yaml
api_url = 'https://api.jarvice.com/jarvice'
# ssh_path = '/usr/bin/ssh'
with open('nimbix.yaml', 'r') as f:
config = yaml.load(f)
instancetype = None
if len(sys.argv) > 2:
parser = argparse.... |
#!/usr/bin/env python
import os
import sys
import subprocess
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.install import install as _install
topdir = os.path.abspath(os.path.dirname(__file__))
# ----------------------------------------------
# Met... |
from django.conf.urls import * # NOQA
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', # NOQA
url(r'^admin/', include(admin.site.urls)),
url(r'^captcha/', include('captcha.urls')),
url(r'^feedback/', include('cmsplugin_feedback.urls')),
url(r'^', include('cms.urls')),... |
section = 1
rules = []
my_ticket = []
nearby_tickets = []
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
line = line.strip()
if section == 1:
if line != "":
rules.append(line.split(": "))
elif section == 2:
if "ticket" not in li... |
import re
from markdown_it import MarkdownIt
def is_md_equal(md1: str, md2: str) -> bool:
"""Check if two Markdown produce the same HTML.
Renders HTML from both Markdown strings, strips whitespace and
checks equality. Note that this is not a perfect solution, as there
can be meaningful whitespace in... |
#----------------------------------------------------------------------
# Libraries
from .dimensionalEnv import *
from .pertGraph import Graph
from .qtUtils import *
from .utils import *
from .dialog import *
#----------------------------------------------------------------------
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Neural_Network(object):
#def __init__(self, W1 = np.array([None]), W2 = np.array([None]), W3 = np.array([None]), W4 = np.array([None]), b1 = np.array([None]), b2 = np.array([None]), b3 = np.array([None])):
def __init__(self, W1 = np.... |
# handlers for the user-facing website
import urllib.parse
import github_collections
import json_api
from article_helpers import *
from base_handler import *
from user_account_helpers import *
from websockets import convert
class MainHandler(BaseHandler):
""" The front page of Brainspell. """
route = ""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.