text stringlengths 2 999k |
|---|
"""
MIT License
Copyright (c) 2020-present shay (shayypy)
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
to use, copy, modify, merge,... |
#!/usr/bin/env python
# coding=utf-8
import logging
from typing import NamedTuple, List
from dataclasses import dataclass
from collections import OrderedDict as odict, defaultdict
import numpy as np
from ioos_qc.qartod import QartodFlags
L = logging.getLogger(__name__) # noqa
class CallResult(NamedTuple):
pack... |
from bs4 import BeautifulSoup as bs
import requests
from urllib.request import urlopen
from urllib.parse import quote
import re
import time
def getProductInfo(productNameIndex):
headers = {"User-Agent": "Mozilla/5.0"}
color = []
size = []
price = ""
instruction = ""
sizeGuide = ""
category... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import git
import os
import re
import sys
import toml
from pathlib import Path
from alchemist_py.brokergen import createProject
from alchemist_py.deviceinfo import searchDevice
from alchemist_py.plugin_manager import PluginManager
class Manager(object):
def __init_... |
import pymongo
from bson import ObjectId
from src.services import config
collection = config.db.incomes
def search_by_user_email(user_email, itype):
return collection.find({"user_email": user_email, "itype": itype})
def sum_amounts_by_user(user_email, itype):
pipeline = [{"$match": {"user_email": user_ema... |
def SC_DFA(y):
N = len(y)
tau = int(np.floor(N/2))
y = y - np.mean(y)
x = np.cumsum(y)
taus = np.arange(5,tau+1)
ntau = len(taus)
F = np.zeros(ntau)
for i in range(ntau):
t = int(taus[i])
x_buff = x[:N - N % t]
x_buff = x_buff.reshape((int(N / t),t))
... |
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Automatically fixes formatting issues and reports any other linting errors"
def handle(self, *args, **options):
subprocess.run(["isort", "--apply", "--quiet"], c... |
"""
WSGI config for template_extends project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJ... |
#
# Copyright 2015 Quantopian, Inc.
#
# 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 wr... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allfeed.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are ... |
#!/usr/bin/env python
__author__ = "Amir Savvy"
__copyright__ = "Copyright 2021, MVP Vending Machine Project"
__credits__ = ["amir savvy"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Amir Savvy"
__email__ = "mianamirlahore@gmail.com"
__status__ = "Production"
# User info
TEST_NORMAL_USER_EMAIL = f"n... |
"""
This module is mainly used to conduct feature engineering for predicting air quality index model
"""
import warnings
import helpers
warnings.filterwarnings('ignore')
if __name__ == '__main__':
PATH = r'air_pollution_death_rate_related/data/data_air_raw/daily_aqi_by_county_'
### use most recent 3 years to ... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2019, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
from lxml.builder import ElementMaker
from moai.metadata.mods import NL_MODS, XSI_NS
class DIDL(object):
"""A metadata prefix implementing the DARE DIDL metadata format
this format is registered under the name "didl"
Note that this format re-uses oai_dc and mods formats that come with
MOAI b... |
# -*- coding: utf-8 -*-
import sys
from os.path import dirname, abspath, normpath, join, realpath
from os import listdir, remove, system
import json
from datetime import datetime
begin = len(normpath(abspath(join(dirname(__file__), "../.."))))
end = len(normpath(abspath(join(dirname(__file__), ".."))))
MAIN_DIR = dir... |
file=open("sample.txt","r")
d=dict()
for lines in file:
lines=lines.strip()
lines=lines.lower()
words=lines.split(" ")
for word in words:
if word in d:
d[word]=d[word]+1
else:
d[word]=1
find=str(input("enter the word to count: "))
find=find.lower()... |
#
# Class for full thermal submodel
#
import pybamm
from .base_x_full import BaseModel
class NoCurrentCollector(BaseModel):
"""Class for full x-direction thermal submodel without current collectors
Parameters
----------
param : parameter class
The parameters to use for this submodel
**... |
""" Summary
"""
class Solution(object):
"""
Problem:
https://leetcode.com/problems/combination-sum/
Example:
given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
"""
def combinationSum(self, candidates, t... |
import pandas as pd
import youtube_api_comments_to_mongodb as ym
import text_classification_and_sentiment_analysis as ta
dbpw = 'kpop'
collection_name = 'comments'
data = ym.mongo_to_dataframe(dbpw, collection_name)
allcomments, englishcomments = ta.dataframe_preparation(data)
tt_set, englishcomments =... |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "{" + self.name + " " + str(self.age) + "}"
p1 = Person("John", 36)
print(p1) |
import logging
import random
from typing import List, Tuple
import numpy as np
from skimage.transform import resize
from scipy.ndimage import zoom
from toolbox import images
from toolbox.images import crop, mask_bbox
from .poisson_disk import sample_poisson_uniform
logger = logging.getLogger(__name__)
class PatchT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 7 12:02:50 2021
@author: ministudio
"""
from datetime import datetime, timezone
import pandas as pd
import numpy as np
from alive_progress import alive_bar
def get_all_futures(ftx_client):
tickers = ftx_client.fetchMarkets()
list_perp =[... |
HTTP_OK = 200
HTTP_CREATED = 201
HTTP_NO_CONTENT = 204
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_NOT_FOUND = 404
HTTP_CONFLICT = 409
|
#!/usr/bin/python
# coding=utf-8
#
# <bitbar.title>Dashcoin Ticker (ยฃ1GBP)</bitbar.title>
# <bitbar.version>v1.0</bitbar.version>
# <bitbar.author>impshum</bitbar.author>
# <bitbar.author.github>impshum</bitbar.author.github>
# <bitbar.desc>Displays current Dashcoin price for ยฃ1 from Coinmarketcap</bitbar.desc>
# <bitb... |
#Tests proper handling of Verifications with Transactions which don't exist.
from typing import Dict, List, Any
import json
from pytest import raises
from e2e.Libs.Minisketch import Sketch
from e2e.Classes.Merit.Block import Block
from e2e.Classes.Merit.Merit import Merit
from e2e.Classes.Consensus.VerificationPack... |
B_4002_10 = {0: {'A': 0.22337100816803507, 'C': -0.08721732138853625, 'E': -0.05776024940539231, 'D': -0.8062336491499029, 'G': -0.22235775138309136, 'F': 0.41616940014979253, 'I': -0.2625598958640791, 'H': -0.2842266678402531, 'K': -0.11806916630138095, 'M': 0.3503963704784862, 'L': -0.11175681610077592, 'N': -0.65597... |
import sys
from ingenialink.ethercat.network import EthercatNetwork
def connect_slave():
net = EthercatNetwork("\\Device\\NPF_{192D1D2F-C684-467D-A637-EC07BD434A63}")
servo = net.connect_to_slave(
target=1,
dictionary='../../resources/dictionaries/cap-net-e_eoe_0.7.1.xdf')
return servo, n... |
# -*- Python -*-
# This file is licensed under a pytorch-style license
# See LICENSE.pytorch for license information.
from torch_mlir.dialects.torch.importer.jit_ir import ModuleBuilder
from utils import create_script_function
# RUN: %PYTHON %s | torch-mlir-opt | FileCheck %s
mb = ModuleBuilder()
# CHECK-LABEL: ... |
#Program to find the rank of a matrix.
#Developed by: SRIJITH R
#RegisterNumber: 21004191
import numpy as np
A=np.array([[5,-3,-10],[2,2,-3],[-3,-1,5]])
val=np.linalg.matrix_rank(A)
print(val) |
"""
File upload page using a png file
"""
from selenium.webdriver.common.by import By
from pages.base_page import BasePage
class FileUpload(BasePage):
FILE_UP = (By.ID, 'file-upload-field')
def upload_file(self):
file_up = self.driver.find_element(*self.FILE_UP)
file_up.send_keys('C:/Users/a... |
import os
import re
import sys
import time
import datetime
from .MiscUtils import commands_get_status_output
try:
long()
except Exception:
long = int
from . import PLogger
from .LocalJobSpec import LocalJobSpec
from .LocalJobsetSpec import LocalJobsetSpec
class PdbProxy:
# constructor
def __init__(se... |
r"""
Gnomonic
========
The point of perspective of the gnomonic projection lies at the center of the
earth. As a consequence great circles (orthodromes) on the surface of the Earth
are displayed as straight lines, which makes it suitable for distance
estimation for navigational purposes. It is neither conformal nor eq... |
import flask
from flask import Flask,jsonify,request
import json
from data_input import data_in
import numpy as np
import pickle
def load_models():
file_name = './models/model_file.p'
with open(file_name,'rb') as pickled:
data = pickle.load(pickled)
model = data['model']
return model
app = Flask(__name__)
@... |
import os
import pytest
from sap.aibus.dar.client.data_manager_client import DataManagerClient
from sap.aibus.dar.client.inference_client import InferenceClient
from sap.aibus.dar.client.model_manager_client import ModelManagerClient
from sap.aibus.dar.client.util.credentials import OnlineCredentialsSource
from sap.a... |
import json
import os
import sys
from datetime import datetime
import numpy as np
import pandas as pd
from objects.task import Task
from objects.workflow import Workflow
from objects.workload import Workload
pd.set_option('display.max_columns', None)
USAGE = 'Usage: python(3) ./galaxy_to_parquet.py galaxy_folder'
N... |
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import numpy as np
import cv2
from .cam import GradCAM
# def load_gradcam(images, labels, model, device, target_layers):
def load_gradcam(test, model, device, target_layers,size = 25,classified = True):
_images = []
_target = []
_pred = [... |
"""Factory classes for easily generating test objects."""
from .activation import Activation
from .annotation import Annotation
from .annotation_moderation import AnnotationModeration
from .auth_client import AuthClient, ConfidentialAuthClient
from .auth_ticket import AuthTicket
from .authz_code import AuthzCode
from .... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import msr... |
import os
import nltk
import re
from gensim import corpora, models, similarities
from cleaning import clean
def train():
#Loads the data from the local storage
synopses = []
for filename in os.listdir('cnn-stories'):
with open('cnn-stories/' + filename, 'r') as infile:
synopses.append(infile.read())
#Cleans ... |
# -*- coding: utf-8 -*-
# Copyright 2022 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... |
# Base path for log files and sessions
base_path = '~/.weevely/'
# History path
history_path = '~/.weevely/history'
# Session path
sessions_path = '~/.weevely/sessions/'
sessions_ext = '.session'
# Supported Channels
channels = [
# Obfuscated channel inside POST requests introduced
# in Weevely 3.6
'Obf... |
# -*- coding: utf-8 -*-
# file: train_text_classification_bert.py
# time: 2021/8/5
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
from pyabsa import TextClassificationTrainer, ClassificationConfigManager, ClassificationDatasetList
... |
# Copyright 2018 The Cornac Authors. 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 required by applicable ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 15:37:43 2020
@author: moder
"""
import os
from datetime import datetime
import pandas as pd
import urllib.request
from bs4 import BeautifulSoup
user_agent = "user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)"
def scrap_wikipedia_text(url):
request = urllib... |
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
LAMBDA_COORD = 5
LAMBDA_NOOBJ = 0.5
def calc_loss(inp , target, opt):
if inp.size(0) != target.size(0):
raise Exception("Batch size does not match")
total_loss = torch.tensor(0.0)
#total_loss = total_loss.dtype(te... |
from django.apps import AppConfig
class BasicApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'basic_api'
|
# coding: utf-8
"""
Definition of the job dashboard interface.
"""
__all__ = ["BaseJobDashboard", "NoJobDashboard", "cache_by_status"]
import time
import functools
from contextlib import contextmanager
from abc import ABCMeta, abstractmethod
import six
def cache_by_status(func):
"""
Decorator for :py:me... |
"""Output formatters."""
import os
from pathlib import Path
from typing import TYPE_CHECKING, Generic, TypeVar, Union
import rich
if TYPE_CHECKING:
from ansiblelint.errors import MatchError
T = TypeVar('T', bound='BaseFormatter')
class BaseFormatter(Generic[T]):
"""Formatter of ansible-lint output.
Ba... |
import pytest
from pytest import approx
from math import radians, inf
import pymap3d as pm
@pytest.mark.parametrize(
"geodetic_lat,alt_m,geocentric_lat",
[(0, 0, 0), (90, 0, 90), (-90, 0, -90), (45, 0, 44.80757678), (-45, 0, -44.80757678)],
)
def test_geodetic_alt_geocentric(geodetic_lat, alt_m, geocentric_l... |
"""An Abstract Base Class for Managers
"""
import abc
from py2c.utils import verify_attribute
__all__ = ["Manager"]
class Manager(object, metaclass=abc.ABCMeta):
"""Base class of all managers
"""
def __init__(self):
super().__init__()
verify_attribute(self, "options", dict)
@abc.a... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/022_data.mixed.ipynb (unless otherwise specified).
__all__ = ['MixedDataLoader', 'MixedDataLoaders', 'get_mixed_dls']
# Cell
from ..imports import *
# Cell
# This implementation of a mixed dataloader is based on a great implementation created by Zach Mueller in this fa... |
"""
GENERATED FILE - DO NOT EDIT (created via @build_stack_rules_proto//cmd/depsgen)
"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def _maybe(repo_rule, name, **kwargs):
if name not in native.existing_rules():
repo_rule(name = name, **kwargs)
def prebuilt_protoc_deps():
pre... |
'''
Timings Class
Arrival and departure times for all Route Sections on a Route on a particular
schedule and shows the time into a section and the time out of a section
Model Operations Processing System. Copyright Brian Fairbairn 2009-2010. Licenced under the EUPL.
You may not use this work except in complia... |
import numpy as np
from graphidx.idx import BiAdjacent
def square():
head = np.array([0, 0, 1, 2])
tail = np.array([1, 2, 3, 3])
return BiAdjacent(head, tail)
def test_sqare():
neigh = square()
assert repr(neigh) == "BiAdjacent[m = 4, n = 4]"
assert set(neigh[0]) == {1, 2}
assert set(nei... |
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this
# distribution.
# THIS SOFTWARE IS PROVIDED "AS ... |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
try:
import unittest.mock as mock
except ImportError:
import mock
from gunicorn import sock
@mock.patch('os.stat')
def test_create_sockets_unix_bytes(stat):
conf = mock.Mock(add... |
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
import json
import os
from tempfile import mkstemp
import pytest
from guillotina import testing
from guillotina.commands import get_settings
from guillotina.commands.run import RunCommand
DATABASE = os.environ.get('DATABASE', 'DUMMY')
def test_run_command(command_arguments):
_, filepath = mkstemp(suffix='.py')... |
import torch
import torch.nn as nn
import torch.nn.quantized as nnq
from torch.quantization import QuantStub, DeQuantStub
import torchvision
import unittest
import os
from neural_compressor.adaptor import FRAMEWORKS
from neural_compressor.model import MODELS
from neural_compressor.adaptor.pytorch import PyTorchVersionM... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 16:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Lekars... |
from resources import relu, learnFunc, dot
class HiddenBlock:
def __init__(self, weights, bias):
self.weights = weights
self.bias = bias
def feedForward(self, hidden_inputs):
output = [
relu(
dot(hidden_inputs, weights) + self.bias
)
for... |
# pep8: disable=E501
from __future__ import print_function
import collections
import os
import pandas
import shutil
import unittest
import pandas as pd
import sklearn.datasets as datasets
import tensorflow as tf
from mlflow import tensorflow, pyfunc
from mlflow import tracking
from mlflow.utils.file_utils import Te... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Refnet Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the behavior of RPC importprivkey on set and unset labels of
addresses.
It tests different cases in whi... |
from matplotlib import cm, rcParams
import matplotlib.pyplot as plt
import numpy as np
import math as math
import random as rand
""" G(phi) function in Rinzel & Lewis' article (2003) under weak coupling """
""" This is under weak coupling theory, although one can note that gamma only serves to scale the function """
... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["StarryBaseOp"]
import pkg_resources
from theano import gof
from ..build_utils import get_compile_args, get_cache_version
class StarryBaseOp(gof.COp):
__props__ = ()
func_file = None
func_name = None
def __init__... |
from tkinter import *
from tkinter.filedialog import askopenfilename
import time
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
time.sleep(1)
|
# Filename: analyst.py
"""Analyst is a tool to look up (and export selected) data and insights
from exported data from chats and channels in Telegram
using Python and PyQt5."""
import sys
import pandas as pd
from pathlib import Path
from PyQt5 import QtWidgets, QtCore
from PyQt5 import uic
from backend import (
... |
###############################################################
# pytest -v --capture=no tests/1_local/test_name.py
# pytest -v tests/1_local/test_name.py
# pytest -v --capture=no tests/1_local/test_name.py:Test_name.<METHIDNAME>
###############################################################
import pytest
from clou... |
import tensorflow as tf
from networks.network import Network
#define
n_classes = 21
_feat_stride = [16,]
anchor_scales = [8, 16, 32]
class VGGnet_train(Network):
def __init__(self, trainable=True):
self.inputs = []
self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3])
#self... |
"""
KMP pattern matching algorithm.
Finds matching patterns in text in linear time.
Text: A longer string of length n. (n > m)
Pattern: Substring to be searched for of length m.
Works by precompiling the pattern string to create a LPS string array.
LPS: Longest Proper Prefix. Longest prefix string that is also a suffix... |
class HTTPException(Exception):
"""
Exception which happens when HTTP status code is not 200 (OK).
"""
def __init__(self, code, url) -> None:
self.error = f"While requesting to {url}, request returned status {code}."
def __str__(self) -> str:
return self.error
class NoCatalogResu... |
# Copyright 2013-2014 MongoDB, Inc.
#
# 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 writin... |
"""
mcpython - a minecraft clone written in python licenced under the MIT-licence
(https://github.com/mcpython4-coding/core)
Contributors: uuk, xkcdjerry (inactive)
Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence
Original game "minecraft" by Mojang Studios (www.m... |
#! /usr/bin/env python
# Copyright 2010, 2011 Martin C. Frith
import fileinput, itertools, optparse, os, signal, sys
def batches(lines):
for line in lines:
if line.startswith("# batch"):
yield line
else:
print line,
while True:
yield None
def lastMergeBatches(... |
# Copyright 2021, joshiayus Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
"""distutils.command.config
Implements the Distutils 'config' command, a (mostly) empty command class
that exists mainly to be sub-classed by specific module distributions and
applications. The idea is that while every "config" command is different,
at least they're all named the same, and users always see "config" i... |
import _plotly_utils.basevalidators
class HoverinfosrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="hoverinfosrc", parent_name="splom", **kwargs):
super(HoverinfosrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from PIL import Image
from datetime import datetime
import sys
import base64
from io import BytesIO
import platform
import urllib.parse
IMG_FOLDER = ''
if platform.system() == 'Linux':
IMG_FOLDER = 'images/'
elif platform.system() == 'Windows':
IMG_FOLDER = '.\\images\\'
def get_base64_image(filename: str = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# Date: 2021/01/06
# Author: Shaun
# ๆชๆกๅ่ฝๆ่ฟฐ:
# ่ชๅๆๅๆฉๅฐ็ๆ
๏ผๆดๆฐ่ณๆๅบซ๏ผ้
ๅbash่
ณๆฌ๏ผๅฏซๅ
ฅ็ณป็ตฑๆ็จcrontab -e
# -------------------------------------------------------------------
import socket
# import pymysql
... |
"""
Package defining various dynamic forward models as well as convenience methods to generate the
right hand sides (RHS) of the related partial differential equations.
Currently, the following forward models are implemented:
#. An advection equation for images
#. An advection equation for maps
#. The EPDi... |
from collections.abc import Mapping
from datetime import datetime
import logging
from typing import Optional
from stackdriver_log_formatter.serializer import DefaultFunc, dumps
class StackdriverLogFormatter(logging.Formatter):
"""Log formatter suitable for Stackdriver Logging.
This formatter print log as a ... |
# Copyright 2018 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, s... |
#import libraries of python opencv
import cv2
# capture video/ video path
cap = cv2.VideoCapture('cars.mp4')
#use trained cars XML classifiers
car_cascade = cv2.CascadeClassifier('haarcascade_cars.xml')
#read until video is completed
while True:
#capture frame by frame
ret, frame = cap.read()
#convert ... |
"""
A WebSub Hub is an implementation that handles subscription requests and distributes
the content to subscribers when the corresponding topic URL has been updated. Hubs
MUST support subscription requests with a secret and deliver
[authenticated requests](https://www.w3.org/TR/websub/#authenticated-content-distributi... |
#!/usr/bin/env python
import os
import os.path
import re
import sys
import time
import json
import random
from subprocess import check_call, call, check_output, Popen, PIPE, CalledProcessError
netmask = ('127.0.0.1', '127.0.0.0')
rpc_param = {
'target_ip': '127.0.0.1',
'port': 3260,
'initiator_name': 'AN... |
# Copyright (c) 2019-2021 Micro Focus or one of its affiliates.
#
# 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 applic... |
import operator
class SegmentTree(object):
def __init__(self, capacity, operation, neutral_element):
"""Build a Segment Tree data structure.
https://en.wikipedia.org/wiki/Segment_tree
Can be used as regular array, but with two
important differences:
a) setting item's va... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class BucketTestCase(Integratio... |
import numpy as np
# This class generating new list item given first of list item row and second of list item row
class Crossover:
@staticmethod
def crossover(best):
row_begin_index = 0
row_half = 2
cross_list = []
for i in range(len(best) - 1):
first_part1 = best... |
from typing import Dict, Any
from telegram import Update, ParseMode
from telegram.ext import CallbackContext
from config.constants import (
USER_DATA_V1_SETTINGS_CAMPUS,
USER_DATA_V1_SETTINGS_ONLINE,
USER_DATA_V1_INTRA_LOGIN,
USER_DATA_V1_INTRA_CAMPUS,
USER_DATA_V1_SETTINGS_ACTIVE,
USER_DATA_V... |
import logging
import os
import re
import sys
from typing import Any, Dict
import PySimpleGUI as sg # type: ignore
from PySimpleGUI.PySimpleGUI import Column # type: ignore
from .utils.encryption import encrypt_password, generate_key
logger = logging.getLogger(__name__)
def login_gui() -> Dict[str, Any]:
sg.... |
from random import shuffle
class Deck(object):
CARD_VALUES = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
CARD_SUITS = ['H', 'D', 'S', 'C']
@staticmethod
def get_shuffled_deck():
deck = Deck()
deck.shuffle()
return deck
def __init__(self):
se... |
# Copyright 2020 The TensorFlow Authors. 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 required by applica... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from ax.modelbridge.array import ArrayModelBridge
from ax.models.numpy_base import NumpyMode... |
# Copyright 2020 The HuggingFace Team. 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 required by applicabl... |
# coding: utf-8
"""
Influx API Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class Vari... |
pkgname = "zlib"
version = "1.2.11"
revision = 0
build_style = "configure"
short_desc = "Compression/decompression Library"
maintainer = "q66 <q66@chimera-linux.org>"
license = "Zlib"
homepage = "http://www.zlib.net"
distfiles = [f"{homepage}/{pkgname}-{version}.tar.gz"]
checksum = ["c3e5e9fdd5004dcb542feda5ee4f0ff0744... |
from nba_py import shotchart
from nba_py.player import get_player
def test():
pid = get_player('Kevin', 'Durant')
assert shotchart.ShotChart(pid) |
from __future__ import unicode_literals
import unittest
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.utils import six
from wagtail.tests.utils import WagtailTestUtils
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.