content stringlengths 5 1.05M |
|---|
from __future__ import annotations
from typing import TYPE_CHECKING
import discord
from discord.ext import typed_commands
from .exceptions import NotGuildOwner, OnlyDirectMessage
if TYPE_CHECKING:
from discord.ext.commands import core
def dm_only() -> core._CheckDecorator:
def predicate(ctx: core._CT, /) ... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Recipe for updating the go_deps asset."""
DEPS = [
'checkout',
'infra',
'recipe_engine/context',
'recipe_engine/properties',
'recipe_engine/p... |
import spacy
import numpy as np
import os, shutil, json, sys
import json, argparse, logging
from tqdm import tqdm
import tensorflow as tf
from collections import defaultdict
from MultiHeadAttention import *
class GAN:
def __init__(self, input_shapes, embedding_size, question_padding):
#input shapes is in ... |
"""A Yelp-powered Restaurant Recommendation Program"""
from abstractions import *
from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file
from ucb import main, trace, interact
from utils import distance, mean, zip, enumerate, sample
from visualize import draw_map
##################################
# ... |
import subprocess
import ansiconv
import sys
from django.conf import settings
from django.http import StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.views.generic import View
from fabric_bolt.projects.models import Deployment
from fabric_bolt.projects.signals import deployment_finish... |
import json
import asyncio
import sys
from joplin_api import JoplinApi
from httpx import Response
import pprint
import difflib
import logging
with open('.token','r') as f:
token = f.readline()
joplin = JoplinApi(token)
async def search(query):
res = await joplin.search(query,field_restrictions='title')
lo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 30/11/2021 22:19
# @Author : Mr. Y
# @Site :
# @File : similarity_indicators.py
# @Software: PyCharm
import numpy as np
np.seterr(divide='ignore',invalid='ignore')
import time
import os
from utils import Initialize
os.environ['KMP_DUPLICATE_LIB_OK'] = ... |
"""
"""
try:
from stage_check import Output
except ImportError:
import Output
try:
from stage_check import OutputAssetState
except ImportError:
import OutputAssetState
def create_instance():
return OutputAssetStateText()
class OutputAssetStateText(OutputAssetState.Base, Output.Text):
"""
"... |
import re
from django.urls import re_path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
re_path(r'^$',views.account,name='account'),
re_path(r'^account/',views.account,name='account'),
re_path(r'^home/',views.home,name='home'),
re_path(r... |
# coding: utf-8
# flake8: noqa E266
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from flask_env import MetaFlaskEnv
from celery.schedules import crontab
class base_config(object, metaclass=MetaFlaskEnv):
"""Default configuration options."""
ENV_PREFIX = 'APP_'
SITE_NAME = 'T... |
You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
If the element is even, divide it by 2.
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
If the eleme... |
import pandas as pd
import numpy as np
from unittest import TestCase, mock
from unittest.mock import MagicMock, PropertyMock
from gtfs_kit.feed import Feed
from representation.gtfs_metadata import GtfsMetadata
from representation.gtfs_representation import GtfsRepresentation
from usecase.process_stops_count_by_type_for... |
from cryptography.utils import CryptographyDeprecationWarning
import warnings
warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning)
from qc_qubosolv.solver import Solver
|
from sqlalchemy import create_engine
engine = create_engine('sqlite:///todo.db?check_same_thread=False')
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date
from datetime import datetime
Base = declarative_base()
class task(Base):
__tablename__ = 'task'
... |
n=int(input())
res=""
for i in range(1,n+1):
a,b=map(int, input().split())
if a>=0:
res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2)
elif a<0 and b>=0:
res+="Scenario #"+str(i)+":\n"+str(b*(b+1)//2 + a*(abs(a)+1)//2)
else:
res+="Scenario #"+str(i)+":\n"+str((a+b)*(b-a+1)//2)
... |
import torch
import torch.nn as nn
def FocalLoss(logits, labels, inverse_normed_freqs):
labels = labels.type(torch.float32)
probs = torch.sigmoid(logits)
pt = (1 - labels) * (1 - probs) + labels * probs
log_pt = torch.log(pt)
floss = - (1 - pt)**2 * log_pt
floss_weighted = floss * inverse_norm... |
import sys
import inspect
import torch
#from torch_geometric.utils import scatter_
from torch_scatter import scatter
special_args = [
'edge_index', 'edge_index_i', 'edge_index_j', 'size', 'size_i', 'size_j'
]
__size_error_msg__ = ('All tensors which should get mapped to the same source '
'or... |
from requests import post,get
from requests_oauthlib import OAuth1
from flask import request
from os import path
from json import dumps, loads
from time import sleep
dir_path = path.dirname(path.realpath(__file__))
def read_env(file=".env"):
read_file = open(dir_path + "/" + file, "r")
split_file = [r.strip().... |
import gmaps2geojson
writer = gmaps2geojson.Writer()
writer.query("2131 7th Ave, Seattle, WA 98121", "900 Poplar Pl S, Seattle, WA 98144")
writer.query("900 Poplar Pl S, Seattle, WA 98144", "219 Broadway E, Seattle, WA 98102")
writer.save("example.geojson")
|
"""Этот модуль запускает работу. Работа должна быть асинхронной, модуль запускает и управляет потоками внутри(?)"""
import asyncio
import time
import random
from ss_server_handler import new_order_handler
from PBM_main import TodaysOrders
from controllers_handler import qr_code_alarm, oven_alarm
from settings ... |
import uuid
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field
class UserBase(BaseModel):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
username: str
email: EmailStr
class Config:
arbitrary_types_allowed = True
class UserCreate(UserBase):
register_date: d... |
valores = []
for contador in range(0, 5):
valor = int(input('Digite um valor: '))
if contador == 0 or valor > valores[-1]:
valores.append(valor)
print('Adicionado ao final da lista...')
else:
posicao = 0
while posicao < len(valores):
if valor <= valores[posicao]:
... |
import os,cStringIO
class Image_Fonts():
def Fonts_Defaults(self):
fontlist = [
'/usr/share/fonts/truetype/freefont/FreeSerif.ttf',
'/usr/share/fonts/truetype/freefont/FreeSans.ttf',
'/usr/share/fonts/truetype/freefont/FreeMono.ttf'
]
fontpath = '.'
... |
import itertools
from django.http import HttpRequest, HttpResponse
from django.core.exceptions import PermissionDenied
from django.utils import timezone
from django.utils.text import slugify
from .jalali import Gregorian, datetime_to_str, mounth_number_to_name, en_to_fa_numbers
# create unique slug.
def unique_slug(t... |
from hask.lang import build_instance
from hask.lang import sig
from hask.lang import H
from hask.lang import t
from hask.Control.Applicative import Applicative
from hask.Control.Monad import Monad
from .Foldable import Foldable
from .Functor import Functor
class Traversable(Foldable, Functor):
"""
Functors re... |
from random import choice
from xkcdpass import xkcd_password
class XKCD:
delimiters_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
delimiters_full = ["!", "$", "%", "^", "&", "*", "-", "_", "+", "=",
":", "|", "~", "?", "/", ".", ";"] + delimiters_numbers
def __init__... |
# -*- coding: utf-8 -*-
'''
Created on : Thursday 18 Jun, 2020 : 00:47:36
Last Modified : Sunday 22 Aug, 2021 : 23:52:53
@author : Adapted by Rishabh Joshi from Original ASAP Pooling Code
Institute : Carnegie Mellon University
'''
import torch
import numpy as np
import torch.nn.functional as F
from torch.nn... |
# License: MIT
# Author: Karl Stelzner
import os
import sys
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import numpy as np
from numpy.random import random_integers
from PIL import Image
from torch.utils.data._utils.collate import default_collate
import json
def progres... |
import random
import numpy as np
class Particle():
def __init__(self):
self.position = np.array([(-1) ** (bool(random.getrandbits(1))) * random.random()*50, (-1)**(bool(random.getrandbits(1))) * random.random()*50])
self.pbest_position = self.position
self.pbest_value = float('inf')
... |
import sys
import os
import logging
import shutil
import inspect
from . import config
logger = logging.getLogger('carson')
_init = None
_debug = False
def initLogging(debug=False):
global _init, _debug
if _init is not None:
return
_init = True
_debug = debug
formatter = logging.Format... |
import sys
from distutils.core import setup
from setuptools import find_packages
version = '0.1.1'
install_requires = [
'acme>=0.29.0',
'certbot>=1.1.0',
'azure-mgmt-resource',
'azure-mgmt-network',
'azure-mgmt-dns>=3.0.0',
'PyOpenSSL>=19.1.0',
'setuptools', # pkg_resources
'zope.int... |
import json
import jwt
from fastapi import Depends, HTTPException, Path, Query
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status import HTTP_... |
import time
from itertools import chain
from opentrons import instruments, labware, robot
from opentrons.instruments import pipette_config
def _sleep(seconds):
if not robot.is_simulating():
time.sleep(seconds)
def load_pipettes(protocol_data):
pipettes = protocol_data.get('pipettes', {})
pipette... |
#!/usr/bin/python
import sys
def int2bin(num, width):
spec = '{fill}{align}{width}{type}'.format(
fill='0', align='>', width=width, type='b')
return format(num, spec)
def hex2bin(hex, width):
integer = int(hex, 16)
return int2bin(integer, width)
def sendBinary(send):
binary = '# ' + '\t branch targ... |
"""tests rio_tiler.sentinel2"""
import os
from unittest.mock import patch
import pytest
import rasterio
from rio_tiler.errors import InvalidBandName
from rio_tiler_pds.errors import InvalidMODISProduct
from rio_tiler_pds.modis.aws import MODISASTRAEAReader
MODIS_AST_BUCKET = os.path.join(
os.path.dirname(__file... |
import FWCore.ParameterSet.Config as cms
from RecoTracker.DebugTools.TrackAlgoCompareUtil_cfi import *
|
# -*- coding: utf-8 -*-
# @Time : 2020/1/23 10:10
# @Author : jwh5566
# @Email : jwh5566@aliyun.com
# @File : test1.py
# import sys
# print('参数个数: ', len(sys.argv))
# print('参数列表: ', str(sys.argv))
# a = 10
# if a > 0:
# print(a, "是一个正数")
# print("总是打印这句话")
#
# a = -10
# if a > 0:
# print(a, "是一个正数")
# a = 10... |
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import HtmlXPathSelector
from ..items import NewsItem
from datetime import datetime
import pandas as pd
import re
class SabahSpider(CrawlSpider):
name = "sabah"
allowed_domains = ["sabah.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenAppXwbsssQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenAppXwbsssQueryResponse, self).__init__()
self._a = None
@prop... |
'''
--------------------
standard_parsers.py
--------------------
This module contains a set of commands initializing standard
:py:class:`argparse.ArgumentParser` objects with standard sets of pre-defined
options. The idea here is that I have a standard basic parser with set syntax
but can also have a 'cluster parse... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
def conv(x, out_channel, kernel_size, stride=1, dilation=1):
x = slim.conv2d(x, out_channel, kernel_size, stride, rate=dilation,activation_fn=None)
return x
def global_avg_pool2D(x):
with tf.variable_scope(None, 'global_pool... |
from functools import reduce
from typing import Optional
import numpy as np
def find_common_elements(*indices: np.array) -> np.array:
""" Returns array with unique elements common to *all* indices
or the first index if it's the only one. """
common_elements = reduce(np.intersect1d, indices[1:], indices[0... |
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Skill
from core.models import Location
from core.models import Job
# from core.models import Job
from job import serializers
from djang... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='clus']/h2[@class='nomargin title_sp']",
'price' : "//h2[@class='nomargin']/font",
'category' : "//div[@class='head_t... |
from extractors import archive_extractor, ertflix_extractor, star_extractor, megatv_extractor
from downloaders import m3u8_downloader, alpha_downloader
import sys
if __name__ == "__main__":
url = sys.argv[1]
if "ertflix.gr" in url:
extractor = ertflix_extractor.ErtflixExtractor(url)
stream_dat... |
#!/usr/bin/env python2
# PYTHON_ARGCOMPLETE_OK
import sys
import agoat._config
import agoat.run_disasms
import agoat.indexer
import agoat.diagnostic
import agoat.keywordsearcher
# set up command-line completion, if argcomplete module is installed
try:
import argcomplete
import argparse
parser = argparse... |
import os
import math
import pygame
class Lava(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
"""
Create a platform sprite. Note that these platforms are designed to be very wide and not very tall.
It is required that the width is greater than or equal to the heigh... |
def pal(a):
s=list(str(a))
i=1
w=[]
while i<=len(s):
w.append(s[-i])
i=i+1
if w==s:
print("it is palimdrom")
else:
print("it is not palimdrom")
string=input("enter the string :")
pal(string)
|
from aoc import data
from collections import Counter, defaultdict
parser = int
def part1(inputData, days=80):
fish = Counter(inputData)
for _ in range(days):
newFish = fish.pop(0, 0)
fish = Counter({k-1: v for k, v in fish.items()}) + Counter({6: newFish, 8:newFish})
return sum(fish.values... |
#!/usr/local/bin/python3
import sys
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
def getMNISTData():
print("Preparing data ...")
num_classes = 10
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data... |
# Collection of supporting functions for wrapper functions
__author__ = 'AndrewAnnex'
from ctypes import c_char_p, c_bool, c_int, c_double, c_char, c_void_p, sizeof, \
POINTER, pointer, Array, create_string_buffer, create_unicode_buffer, cast, Structure, \
CFUNCTYPE, string_at
import numpy
from numpy import ct... |
#!/bin/python
if __name__ == "__main__":
from picomc import main
main()
|
import datetime
import logging
import json
import os
import socket
from config import Configuration
from io import StringIO
from loggly.handlers import HTTPSHandler as LogglyHandler
class JSONFormatter(logging.Formatter):
hostname = socket.gethostname()
fqdn = socket.getfqdn()
if len(fqdn) > len(hostname)... |
from genericpath import exists
import os, sys
from os.path import join
import tempfile
import shutil
import json
try:
curr_path = os.path.dirname(os.path.abspath(__file__))
teedoc_project_path = os.path.abspath(os.path.join(curr_path, "..", "..", ".."))
if os.path.basename(teedoc_project_path) == "teedoc":
... |
from .base_settings import *
import os
ALLOWED_HOSTS = ['*']
INSTALLED_APPS += [
'django_prometheus',
'django.contrib.humanize',
'django_user_agents',
'supporttools',
'rc_django',
]
TEMPLATES[0]['OPTIONS']['context_processors'].extend([
'supporttools.context_processors.supportools_globals'
])... |
'''
This script loads an already trained CNN and prepares the Qm.f notation for each layer. Weights and activation are considered.
This distribution is used by net_descriptor to build a new prototxt file to finetune the quantized weights and activations
List of functions, for further details see below
- forward_pa... |
from timemachines.skatertools.evaluation.evaluators import chunk_to_end
def test_chunk_from_end():
ys = [1,2,3,4,5,6,7,8]
chunks = chunk_to_end(ys,5)
assert len(chunks[0])==5
assert len(chunks)==1
assert chunks[0][0]==4 |
from typing import NamedTuple, Optional
class ConnectionProperties(NamedTuple):
origin: str
port: Optional[int]
|
"""cli.py - Command line interface related routines"""
import logging
import os
import pathlib
from itertools import chain
import click
import click_logging
from ocdsextensionregistry import ProfileBuilder
from ocdskit.util import detect_format
from spoonbill import FileAnalyzer, FileFlattener
from spoonbill.common i... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All 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 requir... |
# CSC486 - Spring 2022
# Author: Dr. Patrick Shepherd
# NOTE: This file contains several functions, some of which already do something
# when run, even before you start writing code. For your convenience, in the
# main function, you may want to comment out the functions you are not currently
# using so they are not r... |
import os
from PyQt5.QtCore import QThread, pyqtSignal
from lib.ffmpegRunner import Runner
from lib.logger import Log
class Controller(QThread):
output = pyqtSignal(str)
def __init__(self,):
QThread.__init__(self, parent=None)
self.__runner = None
self.__outputFile = None
def s... |
# https://arcade.academy/examples/array_backed_grid_sprites_1.html#array-backed-grid-sprites-1
"""
Array Backed Grid Shown By Sprites
Show how to use a two-dimensional list/array to back the display of a
grid on-screen.
This version syncs the grid to the sprite list in one go using resync_grid_with_sprites.
If Pytho... |
from datetime import date
def get_count_of_day(year,month,day):
"""
Function that returns the count of day (since the beginning of the year)
for a given year, month and day
Positional argument:
year -- type = integer
month -- type = integer
day -- type = integer
... |
#!/usr/bin/env python3
from gi.repository import Meson
if __name__ == "__main__":
s = Meson.Sample.new("Hello, meson/py!")
s.print_message()
|
import os
import sys
import unittest
import numpy as np
from QGrain.algorithms import *
NORMAL_PARAM_COUNT = 2
WEIBULL_PARAM_COUNT = 2
GENERAL_WEIBULL_PARAM_COUNT = 3
# the component number must be positive int value
class TestCheckComponentNumber(unittest.TestCase):
# valid cases
def test_1_to_100(self):
... |
# Copyright (C) 2020 University of Oxford
#
# 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... |
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
# NOTE: Make sure you've created your secrets.py file before running this example
# https://learn.adafruit.com/adafruit-pyportal/internet-connect#whats-a-secrets-file-17-2
import board
from adafruit_pyporta... |
"""
weasyprint.css.descriptors
--------------------------
Validate descriptors used for some at-rules.
"""
import tinycss2
from ...logger import LOGGER
from ..utils import (
InvalidValues, comma_separated_list, get_custom_ident, get_keyword,
get_single_keyword, get_url, remove_whitespace, single... |
import numpy as np
import pandas as pd
import os
import h5py
from scipy import io
##########################################################
# author: tecwang
# email: tecwang@139.com
# Inspired by https://blog.csdn.net/zebralxr/article/details/78254192
# detail: Transfer mat file into csv file by python
#############... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 23 14:40:10 2017
@author: pudutta
"""
from __future__ import absolute_import, division, print_function
import codecs
import glob
import multiprocessing
import os
import pprint
import re
import nltk
import gensim.models.word2vec as w2v
import math
import ... |
#!/user/bin python
# -*- coding:utf-8 -*-
'''
@Author: xiaodong
@Email: fuxd@jidongnet.com
@DateTime: 2015-11-08 19:06:43
@Description: 提取word文档信息 转换Excel
需求字段 : 姓名,职位,性别,年龄,教育程度,手机号码,邮箱,户籍,简历更新日期,工作经历,项目经历。
'''
from win32com.client import Dispatch, constants
import os,sys
import re
import chardet... |
def my_zip(first,secoud):
first_it=iter(first)
secoud_it=iter(secoud)
while True:
try:
yield (next(first_it),next(secoud_it))
except StopIteration:
return
a=['s','gff x','c']
b=range(15)
m= my_zip(a,b)
for pair in my_zip(a,b):
print(pair)
a,b... |
import sqlite3
def changeDb():
databaseFile = "app/database/alunos.db"
escolha = 0
while escolha != 4:
print("""
1 = Numero para contato
2 = Situação escolar
3 = Documentações pendentes
4 = Sair do menu
""")
escolha... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... |
from confluent_kafka import Producer
import rest
import json
class BusProducer:
def __init__(self):
# Pre-shared credentials
self.credentials = json.load(open('bus_credentials.json'))
# Construct required configuration
self.configuration = {
'client.id': 'bus_producer... |
"""ApacheParser is a member object of the ApacheConfigurator class."""
import fnmatch
import itertools
import logging
import os
import re
import subprocess
from letsencrypt import errors
logger = logging.getLogger(__name__)
class ApacheParser(object):
"""Class handles the fine details of parsing the Apache Con... |
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
__author__ = 'ipetrash'
"""Пример отсылки письма, содержащего обычный текст и html, "самому себе"."""
# http://www.tutorialspoint.com/python/python_sending_email.htm
# https://docs.python.org/3.4/library/email-example... |
#!/usr/bin/env python
import os
import pyfwk
from pyfi.entity.entity.db import EntityDB
# -----------------------------EXCHANGE-MODEL-----------------------------#
class TypeModel(pyfwk.Model):
model = None
dbase = None
table = None
columns = None
@staticmethod
def instance():
if no... |
"""Sensitive Field Type"""
# standard library
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union
# first-party
from tcex.input.field_types.exception import InvalidEmptyValue, InvalidLengthValue, InvalidType
if TYPE_CHECKING: # pragma: no cover
# third-party
from pydantic.fi... |
"""
License
-------
Copyright (C) 2021 - David Fernández Castellanos
You can use this software, redistribute it, and/or modify it under the
terms of the Creative Commons Attribution 4.0 International Public License.
Explanation
---------
This module contains the statistical model of the COVID-19 vaccination ca... |
import torch
import torch.fx.experimental.fx_acc.acc_ops as acc_ops
import torch.nn as nn
from torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec
class TestSizeConverter(AccTestCase):
def test_size(self):
class Size(nn.Module):
def forward(self, x):
bs = ... |
from authlib.oauth2.rfc8414 import AuthorizationServerMetadata
|
# db_util.py
from datetime import datetime
import sqlite3
import os
import inspect
import uuid #uuid4() --> cookie
from utils import err, done,log
try:
# log(os.environ['GATEWAY_INTERFACE'])
if 'cgi' in os.environ['GATEWAY_INTERFACE'].lower():
DATABASE = 'csci4140.db'
else:
DATABASE = "csci4... |
from django.db.models import Choices
class ValueTypes(Choices):
PERCENTAGE = 'percentage'
FIXED_AMOUNT = 'fixed amount'
FREE_SHIPPING = 'free shipping'
|
import logging
from .builder import TargetBuilder
from .config import YAMLParser
from .device import RunnerFactory
from .testcase import TestCaseFactory
class TestsRunner:
"""Class responsible for loading, building and running tests"""
def __init__(self, targets, test_paths, build=True):
self.target... |
from base import PMLM
from models import EDMM, MLMM, MEMM, DCSMM, DEDMM, DKLMM
import utils |
from JumpScale import j
import sys
import fcntl
import os
import time
class Empty():
pass
class AAProcessManagerCmds():
ORDER = 100
def __init__(self, daemon=None):
self._name = "pm"
self.daemon = daemon
self._reloadtime = time.time()
if daemon is not None:
... |
import pandas as pd
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
from matplotlib import style
start = datetime.datetime(2015, 1, 1) #Dato for onsket aksjekurs
end = datetime.datetime.now()
df = web.DataReader("ORK.OL", "yahoo", start, end) # Verdien av Orkla aksjen fra 2015 t... |
"""
Implementation of geo query language
""" |
# 第3章: 正規表現
import json
import gzip
def extract(title):
with gzip.open('jawiki-country.json.gz', 'rt', encoding='utf8') as fin:
for line in fin:
jsd = json.loads(line)
if jsd['title'] == title:
return jsd['text']
return ''
def main():
article = extract('イギリス... |
t = int(input())
for i in range(t):
s = str(input())
w = s.split()
s1 = 'not'
if(s1 in w):
print('Real Fancy')
else:
print("regularly fancy")
|
#!/usr/bin/python3
import pytest
from brownie import network, Contract, Wei, chain, reverts
@pytest.fixture(scope="module")
def requireMainnetFork():
assert (network.show_active() == "mainnet-fork" or network.show_active() == "mainnet-fork-alchemy")
@pytest.fixture(scope="module")
def iUSDC(accounts, LoanTokenL... |
from .database import *
def password_is_valid(password):
if len(password) < 5:
return False
return True
class Login():
def __init__(self, data_set):
self.db = self.db_create(data_set)
def db_create(self, data_set):
db = Database(data_set)
db.up_database()
ret... |
ls = []
for i in range(100):
if i%3==0:
ls.append(i)
print(ls)
ls = [i for i in range(100) if i%3==0] # list comprehension
print(ls)
dict1 = {i:f"item{i}" for i in range(1, 12) if i%2==0} # dictionary comprehension
print(dict1)
dict1 = {value:key for key,value in dict1.items()} # can cha... |
# Copyright 2017 Eun Woo Song
# 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, so... |
import json
import os
import hashlib
import getpass
def main():
FileStructureSetUp().set_up_files()
class ScheduleTable:
# Describes a schedule table
class Row:
def __init__(self, block_type: str = "NA", day: str = "NA", place: str = "NA", time: str = "NA"):
"""
Describes... |
import pytest
import python_jsonschema_objects as pjo
@pytest.fixture
def arrayClass():
schema = {
"title": "ArrayVal",
"type": "object",
"properties": {
"min": {
"type": "array",
"items": {"type": "string"},
"default": [],
... |
import pytesseract
import settings
def img_to_text():
pytesseract.pytesseract.tesseract_cmd = settings.WORKSPACE_DIR + r'/etc/Tesseract-OCR/tesseract.exe'
text = pytesseract.image_to_string(settings.WORKSPACE_DIR + r'/screenshots_temp/screenshot.png', lang=settings.get_language())
text = text.replace("\n"... |
import multiprocessing
import numpy as np
from basetrainer import BaseTrainer
from solvers import LeastSquares
from scorers import MeanAbsolute
from parallelworker import Worker, Task
# Feature selection + linear regression training and validation toolkit
class ParallelTrainer(BaseTrainer):
def __init__(self, x, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.