content stringlengths 5 1.05M |
|---|
#%% Definition of the inputs
'''
Input data definition
'''
#El Espino HI
from core import User, np
User_list = []
#Create new user classes
HI = User("high income",1,3)
User_list.append(HI)
#Appliances
#High-Income
HI_indoor_bulb = HI.Appliance(HI,5,7,2,300,0.2,10)
HI_indoor_bulb.windows([1170,1440],[0,30],0.35)... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon Managed Streaming for Kafka Connect"
prefix = "kafkaconnect"
class Action(BaseAction):
def __init__(self, actio... |
# Copyright 2021 Huawei Technologies Co., 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... |
"""
Defines a type object of from library that can be included in Lemonspotter tests.
"""
import logging
from functools import lru_cache
from typing import TYPE_CHECKING, Mapping, Any, Iterable
from lemonspotter.core.database import Database
from lemonspotter.core.partition import Partition
if TYPE_CHECKING:
fro... |
class SevenDaysHoldException(Exception):
pass
class TooManyRequests(Exception):
pass
class ApiException(Exception):
pass
class LoginRequired(Exception):
pass
class InvalidCredentials(Exception):
pass
class CaptchaRequired(Exception):
pass
class ConfirmationExpected(Exception):
pa... |
from abc import abstractmethod
class BaseDB:
@abstractmethod
def inc_refcount(self, key, value):
raise NotImplementedError
@abstractmethod
def dec_refcount(self, key):
raise NotImplementedError
@abstractmethod
def get(self, key):
raise NotImplementedError
|
"""Fixtures for withings tests."""
import time
from typing import Awaitable, Callable, List
import asynctest
import nokia
import pytest
import homeassistant.components.api as api
import homeassistant.components.http as http
import homeassistant.components.withings.const as const
from homeassistant.components.withings... |
def getPrimes(n):
ret = []
d = [0] * (n + 1)
for i in range(2, n + 1):
if d[i] == 0:
for j in range(2 * i, n, i):
d[j] = 0
ret.append(i)
return ret
def calc(n, p):
ret = 1
r = n
for i in p:
if i * i > n:
return ret * 2
... |
"""Helpers for testing the models directory."""
from microbepy.common import constants as cn
from microbepy.model import binary_tree_model as btm
from microbepy.model import binary_tree_regression as btr
import pandas as pd
import numpy as np
DEPTH = 4
NAMES = ['a', 'b', 'c', 'd', 'e', 'f']
################# HELPER... |
# This is the class created to replace the functionality of PyMPChecker_Brute.py
from __future__ import print_function
import sys
import os
import re
import operator
import ephem # PyEphem module
from multiprocessing import Pool, cpu_count
import pkg_resources
import time
import pandas as pd
import psycopg2
from date... |
import requests
from st2actions.runners import pythonrunner
class GetWorkbookDefinitionAction(pythonrunner.Action):
def run(self, workbook):
url = self._get_api_url('workbooks', workbook)
resp = requests.get(url)
if resp.status_code != 200:
raise Exception(resp.content)
... |
import os
import subprocess
_COB_DEVELOP_MODE = 'COB_DEVELOP'
def is_develop():
return _COB_DEVELOP_MODE in os.environ
def cob_root():
assert is_develop()
returned = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
assert os.path.basename(returned) == 'cob', f'Unable to properly... |
import pytest
from milvus_cloud import ParamError
from factorys import records_factory
dim = 128
nq = 100
class TestGetVectorByID:
def test_get_entity_by_id(self, gcon, gcollection):
vectors = records_factory(128, 1000)
ids = [i for i in range(1000)]
status, ids_out = gcon.insert(collect... |
from .rawdevart_com_old import RawDevArtComOld
class ISekaiScanCom(RawDevArtComOld):
_chapter_selector = r'/(?:chapter-)?(\d+(?:[\a-zA-Z\.-]*?\d+)?(?:-\w+)?)/'
def get_files(self):
parser = self.html_fromstring(self.chapter)
return self._images_helper(parser, '.page-break img.wp-manga-chapter... |
import re
# -*- coding: utf-8 -*-
"""
flask_caching.backends.memcache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The memcache caching backend.
:copyright: (c) 2018 by Peter Justin.
:copyright: (c) 2010 by Thadeus Burgess.
:license: BSD, see LICENSE for more details.
"""
from time import time
from flask... |
from pyperclip import copy
zh_jp = {
'诅': '詛',
'伫': '佇',
'嘟': '篤',
'喔': '哦',
'啪': 'pa',
'嗒': 'da',
'啊': '阿',
'诶': '欸',
'咦': '億',
'哒': '達',
'唧': '喞',
'咧': '禧',
'嘻': '禧',
'噢': '哦',
'哎': '欸',
'啦': '喇',
'哟': '黝',
'呢': '訥',
'吧': '罷',
'跑': '鉋',
... |
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase, Client
from django.utils import translation
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from landpage import views
class LandpageTest(TestCase):
fixtures = [
... |
import logging.config
import pathlib
from django.core.management import CommandParser, BaseCommand
from imagestore.services import fetch_from_local_path
logger = logging.getLogger(__file__)
class Command(BaseCommand):
def add_arguments(self, parser: CommandParser):
parser.add_argument('path', type=pat... |
from assertions import is_any_valid_docker_container_id
def test_is_any_valid_docker_container_id():
assert is_any_valid_docker_container_id("a2b1afc9683c05200b15f0d5f008c27f185503ab1300fd8ce229b107cf460481")
# too short
assert not is_any_valid_docker_container_id("2b1afc9683c05200b15f0d5f008c27f185503ab1... |
import base64
def make_file_from_b64(path: str, b64: str):
with open(path, "wb") as f:
f.write(base64.b64decode(b64))
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 15:08:55 2018
@author: Ryan Clark
Header:
This file defines the class to utilize the ResNet architecture for semantic
segmentation. It currently supports both the 18 and 34 layer architectures.
You can initialize your ResNet with a single param... |
class LinkedinError(Exception):
pass
class LinkedinBadRequestError(LinkedinError):
pass
class LinkedinUnauthorizedError(LinkedinError):
pass
class LinkedinPaymentRequiredError(LinkedinError):
pass
class LinkedinNotFoundError(LinkedinError):
pass
class LinkedinConflictError(LinkedinError):
... |
DEBUG = True
ETL_URL = 'postgresql://localhost/regenesis'
DATA_DIRECTORY = 'exports/'
API_ENDPOINT = 'http://api.regenesis.pudo.org'
CATALOG = {
'regional': {
'title': 'Regionalstatistik',
'url': 'https://www.regionalstatistik.de/',
'username': '',
'password': '',
'export... |
import urllib
import requests
from bs4 import BeautifulSoup
urls = "https://free-proxy-list.net/"
res = requests.get(urls)
soup = BeautifulSoup(res.text,"html.parser")
tbody = soup.find("tbody")
print(tbody.prettify()) |
'''
This code is automatically generated. Never edit it manually.
For details of generating the code see `rubi_parsing_guide.md` in `parsetools`.
'''
from sympy.external import import_module
matchpy = import_module("matchpy")
from sympy.utilities.decorator import doctest_depends_on
if matchpy:
from matchpy import... |
# Copyright (c) 2020 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE
# Generated by Django 2.2.9 on 2020-01-16 06:35
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
depend... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... |
import neurolab.params as P
import params as PP
from .meta import *
config_base_gdes = {}
gdes_fc_on_gdes_layer = {}
gdes_fc_on_gdes_layer_ft = {}
hebb_fc_on_gdes_layer = {}
hebb_fc_on_gdes_layer_ft = {}
prec_on_gdes_layer = {}
prec_on_gdes_layer_ft = {}
knn_on_gdes_layer = {}
knn_on_gdes_layer_ft = {}
svm_on_gdes_l... |
import argparse
from pathlib2 import Path
from awp_processing import read_params
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="", help="Scenario directory")
parser.add_argument("--conf_file", default="param.sh", help="Configuration file")
args = parser.parse_args()
#C = awp.Scenario(mod... |
from typing import List, Sequence
from random import randint, randrange
"""Imagine a robot sitting on the upper left corner of grid with r rows and c
columns. The robot can only move in two directions, right and down, but
certain cells are "off limits" such that the robot cannot step on them.
Design an alg... |
import cv2
import numpy as np
import sys
def main():
if len(sys.argv) == 1: # pass the device number
cap = cv2.VideoCapture(0)
else:
try:
cap = cv2.VideoCapture(int(sys.argv[1]))
except:
cap = cv2.VideoCapture(sys.argv[1])
cap.set(cv2.CAP_PROP_FRAME_WIDTH... |
# -*- encoding:utf-8 -*-
# @Time : 2019/7/6 22:17
# @Author : gfjiang
# @Site :
# @File : __init__.py
# @Software: PyCharm
from .pycocotools import *
from .utils import *
# from .utils.fileio import *
from .utils.evaluation import *
from .label_convert import *
from .label_analysis import *
from .data_augs i... |
import math
import random
import copy
import matplotlib.pyplot as plt
def index_of(a,list): #returns index of "a" in "list" , else "-1"
for i in range(0,len(list)):
if list[i] == a:
return i
return -1
def sort_by_values(front, values):
sorted_list = []
while(len(sorted_list) != len... |
""" An Ambry bundle for building geofile bundles
How to Create a New Geofile Bundle
==================================
Step 1: Setup source.
It's easiest to copy from a similar bundle and edit. You'll need these
sources:
* A dnlpage<year><release> for each year/release. These are URLs to the
download page for the... |
from flask_ckeditor import CKEditorField
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import (BooleanField, PasswordField, StringField, SubmitField,
TextAreaField, ValidationError)
from wtforms.validators import DataRequired, EqualTo, Length
from wtforms.widgets... |
from django.urls import path
from . import views
app_name = 'userclass'
urlpatterns = [
path('details/', views.details, name='details'),
]
|
#! python
import os, sys, glob, time
import threading, queue
import tarfile
import paramiko, socket
import re
import wx
import wx.lib
from wx.lib import intctrl
from watchdog.observers import Observer
from watchdog.events import RegexMatchingEventHandler
from watchdog.events import FileMovedEvent
# Handle file system... |
#
# Copyright John Reid 2006
#
import urllib
import os
# Details of parts of the ensembl url
urlprefix="ftp://ftp.ensembl.org/pub/"
data_dir="/data/fasta/dna/"
file_part=".may.dna.chromosome."
ext=".fa.gz"
# Where the files will be stored
local_dir="c:\\data\\ensembl\\chromosones\\zipped\\"
# Get one file
def get_ch... |
# -*- coding: utf-8 -*-
from returns.functions import identity
def _flatten(container):
"""
Joins two nested containers together.
Please, note that it will not join
two ``Failure`` for ``Result`` case
or two ``Nothing`` for ``Maybe`` case together.
.. code:: python
>>> from returns.c... |
#!/usr/bin/env
## Generate blastn report for Enterococcuss mobile elements
## author: errol strain, estrain@gmail.com
from argparse import (ArgumentParser, FileType)
import sys
import glob
import subprocess
from decimal import Decimal
def parse_args():
"Parse the input arguments, use '-h' for help."
parser = Arg... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
raw corpus를 읽어들여서 vocabulary를 생성합니다.
__author__ = 'Hubert (voidtype@gmail.com)'
__copyright__ = 'Copyright (C) 2017-, grace TEAM. All rights reserved.'
"""
###########
# imports #
###########
import argparse
import logging
import sys
from collections import Counter
... |
"""This file contains decorators used by sitegate."""
from django.shortcuts import redirect
from .signup_flows.modern import ModernSignup
from .signin_flows.modern import ModernSignin
from .utils import DecoratorBuilder
class FlowBuilder(DecoratorBuilder):
def __init__(self, flow_cls, args, kwargs):
sel... |
class Test(object):
def __init__(self, score):
self.score = score
@property
def score(self):
return self.__score
@score.setter
def score(self, value):
if value < 0 or value > 100:
raise Exception('Score out of range')
self.__score = value
class Student(... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(1, 85):
if 168%i == 0:
j = 168 / i
if i> j and (i+j)%2 == 0 and (i-j)%2 == 0:
m = (i+j)/2
n = (i-j)/2
x = n*n - 100
print x |
import sublime
import zlib
try:
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from urllib.request import ProxyHandler
from urllib.request import build_opener
from urllib.request import ins... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2015, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistri... |
from __future__ import absolute_import, unicode_literals, print_function
import pymultinest
import math, os
from fm import *
import pdb
import numpy as np
import pickle
from matplotlib.pyplot import *
if not os.path.exists("chains"): os.mkdir("chains")
xsects=xsects(909,3333) #lower wavenumber, upper wavenumber...to co... |
#!/usr/bin/python
#
# General-purpose Photovoltaic Device Model gpvdm.com - a drift diffusion
# base/Shockley-Read-Hall model for 1st, 2nd and 3rd generation solarcells.
# The model can simulate OLEDs, Perovskite cells, and OFETs.
#
# Copyright 2008-2022 Roderick C. I. MacKenzie https://www.gpvdm.com
# r.c.i.mackenzi... |
from palindrome.doublebase import DoubleBasePalindrome
from random import randint
import unittest
class PalindromeTests(unittest.TestCase):
def test_sum_one_million_palindromes(self):
"""Sum 1 million double base palindromes"""
palindromes = DoubleBasePalindrome()
result = palindromes.sum... |
# 5. Vorlesung 17.10.2020, Skript Python 4 (07_Python_04.pdf)
# Übung 4: GUI Übung 2: Länderflaggen aus Textfeld zeichnen...
from tkinter import *
def updateGui(event):
if textFeld.get() == "Deutschland":
fahneOben.configure(bg="black")
fahneMitte.configure(bg="red")
fahneUnten.configure(b... |
# -*- coding: utf-8 -*-
import pandas as pd
def umi_reads_downsample(seq_df):
"""
:param seq_df:
:return: saturations
"""
saturations = pd.DataFrame(columns=['percent', 'median_gene_num', 'saturation']).set_index('percent')
all_seq_df = seq_df.reset_index().set_index(['Barcode', 'geneID', 'UM... |
import os
import shutil
tmpdir = 'tmp_delete_before_commit'
resfile = 'test_report.txt'
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
try:
os.remove(resfile)
except OSError:
pass |
"""
89 / 89 test cases passed.
Status: Accepted
Runtime: 176 ms
"""
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
sz = len(arr)
if sz < 2:
return sz
ans, l = 0, 0
turbulence = arr[1] > arr[0]
for r in range(1, sz):
current = arr[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from bs4 import BeautifulSoup
import requests
from config import LOGIN, PASSWORD
FORM_DATA = {
'username': LOGIN,
'password': PASSWORD,
}
session = requests.Session()
session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win6... |
import unittest
import numpy.testing as npt
import numpy as np
import freud
import rowan
class TestLocalBondProjection(unittest.TestCase):
def test_nlist(self):
"""Check that the internally generated NeighborList is correct."""
boxlen = 10
N = 500
num_neighbors = 8
r_guess ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
import concurrent.futures
import os
from queue import Queue
from iotfs.filesystem.fs import FileSystemStarter, FileSystem
from iotfs.filesystem.standard_fs import StandardFileSystem
from iotfs.filesystem.producer_fs import ProducerFile... |
import os
import unittest
from mock import patch, call, MagicMock
import charmhelpers.contrib.openstack.templating as templating
from jinja2.exceptions import TemplateNotFound
class FakeContextGenerator(object):
interfaces = None
def set(self, interfaces, context):
self.interfaces = interfaces
... |
# -*- coding: utf-8 -*-
from flask import request
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from purchasing.extensions import admin, db
from purchasing.decorators import AuthMixin, SuperAdminMixin, ConductorAuthMixin
from purchasing.utils import localize_and_strip
from flask_admin.contrib import sql... |
import os
import re
import shutil
import sys
import SQLExtract
import SQLCleanser
import MetricsCalculator
import PLUsedMetrics
import AppNature
import ORM_detector
exclude_list = ["results"]
def get_folder_paths():
if len(sys.argv) <= 1:
print ("Please provide path of the root folder containing projects... |
#-*- coding:utf-8 -*-
from __future__ import print_function
####################### ######################################
import sys
import clr
import System
import System.IO
def getFullNames(dllname):
def getEnvs(envnmame):
tgt1=System.EnvironmentVariableTarget.Machine
tgt2=System.EnvironmentVar... |
import numpy as np
from probatus.utils.tree import TreePathFinder
from probatus.utils.warnings import NotIntendedUseWarning
import pytest
class mock_sub_tree:
"""
Mock.
"""
def __init__(self, node_count, cl, cr, feat, thresh):
"""
Init.
"""
self.node_count = node_count... |
#============================================================================
# An example of a surface domain class.
#
# Author: Johnny Lin.
#
# Copyright (c) 2006-2011 by Johnny Lin. For licensing, distribution
# conditions, contact information, and additional documentation see
# the URL http://www.johnny-lin.com/... |
import time
from multiprocessing import Pipe, Process
def product(pipe):
pipe.send('send product')
def consume(pipe):
time.sleep(2)
print(pipe.recv())
def fe(a):
print('result', a)
# pipe 实现进程间通信
# pipe性能高于queue
if __name__ == "__main__":
# 仅仅适用于两个进程间的通信
rece, send = Pipe()
p = Pr... |
import shutil
import numpy as np
import matplotlib.pyplot as pl
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn.utils.rnn
import pickle
from torch.autograd import Variable
import time
from tqdm import tqdm
import sys
from modules import model_ae as model
import platform
import glob
import os
... |
import torch
import numpy as np
def pad_id_seqs(id_seqs, device, pad_id):
batch_size = len(id_seqs)
max_len = max(len(seq) for seq in id_seqs)
id_seqs_arr = np.ones((batch_size, max_len), dtype=np.int32) * pad_id
attn_mask = np.zeros((batch_size, max_len), dtype=np.float32)
for i, seq in enumerate... |
"""
author: Luke Brandl
project: Implementation of a Newton-Raphson algorithm for maximizing Dirichlet log likelihood
file description: This file is a python script which generates 1000 samples from the Dirichlet distribution with alpha parameter (10,5,15,20,50), then performs a Newton-Raphson algorithm to recover the ... |
# -*- coding: utf-8 -*-
"""
@author; Nobu Kim
"""
import json
import re
import pandas as pd
from dash import Dash, exceptions, no_update, callback_context
from dash.dependencies import Input, Output, State
from dash_utils.Dash_fun import apply_layout_with_auth
import dash_core_components as dcc
import dash_bootstrap_co... |
#!/usr/bin/python -u
# -*- coding: utf-8 -*-
import sqlite3 as sql
def recordUser(ID, name, time, chat_id):
try:
with sql.connect("nis.db") as con:
cur = con.cursor()
query = u"INSERT INTO users (user_id, user_name, last_active, chat_id) VALUES('"
query += str(ID)
... |
'''
BagOfWordsObsModel.py
'''
import numpy as np
import copy
from scipy.special import digamma, gammaln
from ..util import np2flatstr, EPS
from ..distr import BetaDistr
from ObsModel import ObsModel
class BernRelObsModel(ObsModel):
######################################################### Constructors
####... |
import requests
import typing as t
import urllib.parse
from .lexicon import Lex
from .caller import WebCaller
from .objects import (
DTO,
ActDTO,
AccountDTO,
ContentDTO,
ContentItemDTO,
LeaderboardDTO,
LeaderboardIterator,
PlatformDataDTO,
)
class Client(object):
"""Represents a... |
import torchvision.transforms as transforms
mnist_train_transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]
)
|
from django.urls import path
from .views import *
urlpatterns = [
path('', welcome, name = 'welcome'),
path('/dashboard', dashboard, name = 'dashboard'),
path('verify/<uuid:pk>', approve_success, name = 'verify'),
path('decline/<uuid:pk>', decline, name = 'decline'),
path('spam/<uuid:pk>', mark_spa... |
from swissdutch.constants import FloatStatus, Colour, ColourPref
class Player:
def __init__(self, name, rating, title=None, pairing_no=None,
score=0, float_status=FloatStatus.none, opponents=(),
colour_hist=()):
self._name = name
self._rating = rating... |
n=int(input("enter the size"))
a=[]
c=[]
for i in range(n):
b=int(input("enter"))
a.append(b)
x=sorted(a)
if(x.count(0)==len(x)):
print(a[0])
else:
for i in range(len(x)-1,-1,-1):
print(x[i])
|
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
"""server docstring"""
import json
import random
import time
from datetime import datetime
from flask import Flask, Response, render_template, redirect, url_for
from flask_mongoengine import MongoEngine
from sensores.db.models import Sensor, Medition
from sensores.db import util
from .businesslogic import get_sensors... |
from pyrelational.models.ensemble_model import (
GenericEnsembleModel,
LightningEnsembleModel,
)
from pyrelational.models.generic_model import GenericModel
from pyrelational.models.lightning_model import LightningModel
from pyrelational.models.mcdropout_model import (
GenericMCDropoutModel,
LightningMCD... |
'''
This module contains the following:
Sparse Quadric
Max-k-sum-squared
SkewedQuartic
'''
import numpy as np
class SparseQuadric(object):
'''An implementation of the sparse quadric function.'''
def __init__(self, d, s):
self.s = s
self.dim = d
def __call__(self,x):
re... |
import functools
import math
from typing import Dict, Optional, List, Any, Union, Tuple, Callable
import numpy as np
import opensfm.synthetic_data.synthetic_dataset as sd
import opensfm.synthetic_data.synthetic_generator as sg
import opensfm.synthetic_data.synthetic_metrics as sm
from opensfm import pygeometry, types,... |
### The following code implements neural network on MNIST data in pytorch.
### 2 Hidden Layer Feedforward Neural Network (ReLU Activation)
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision
import torchvision.datasets as dsets
import torchvision.transforms as transforms
"""
Step... |
from __future__ import absolute_import
from kafka.producer.kafka import KafkaProducer
from kafka.producer.simple import SimpleProducer
from kafka.producer.keyed import KeyedProducer
__all__ = [
'KafkaProducer',
'SimpleProducer', 'KeyedProducer' # deprecated
]
|
import numpy as np
class PageRank(object):
'''
This class reproduces the PageRank algorithm
'''
def __init__(self, damp = .85):
'''
INPUT: damping factor (discount, how much future clicks are valued)
OUTPUT: None
'''
self.d =... |
import numpy as np
from itertools import combinations
from tabulate import tabulate
from scipy.stats import wilcoxon, ttest_rel, ttest_ind
import matplotlib.pyplot as plt
from tabulate import tabulate
import os
from scipy.ndimage import gaussian_filter1d
from matplotlib import rcParams
from strlearn.utils import scores... |
import os
import numpy as np
import pygfunction as gt
from math import log, pi
from glhe.aggregation.agg_factory import make_agg_method
from glhe.input_processor.component_types import ComponentTypes
from glhe.input_processor.input_processor import InputProcessor
from glhe.interface.entry import SimulationEntryPoint
... |
from flask import request
from flask_restplus import Resource
from ..util.dto import UserDto
from ..helper.token_helper import token_required
from ..service.user_service import save_new_user, get_all_users, get_a_user
api = UserDto.api
_user = UserDto.user
@api.route('/')
@api.param('token', 'Access Token', required... |
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/109... |
# 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... |
#!/usr/bin/python
# Script forked and tweaked from https://github.com/dataJAR/jnuc2016
import CoreFoundation
from sys import argv
if '-h' in argv or len(argv) == 1:
print("")
print("python prefs.py <com.domain.name> <key>")
print("")
exit(0)
script, domain, key = argv
key_value = CoreFoundation.CFP... |
#!/usr/bin/env python3
##
## EPITECH PROJECT, 2021
## plot.py
## File description:
## plot fonc
##
import numpy as np
import matplotlib.pyplot as plt
def plot_fonc() :
plt.style.use('classic')
x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y, marker="x")
plt.show()
from PIL import Image
... |
""" Training and Testing
Author : QiaoTian
Date : 6th Oct 2016
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.ensem... |
import discord
atividades = {
"jogando": [
discord.Game(name="pão para pombos"),
discord.Game(name="minhas esperanças na humanidade"),
discord.Game(name="prefixo: ::"),
discord.Game(name="tralhas fora")
],
}
|
# coding=utf-8
from __future__ import division, absolute_import, print_function, unicode_literals
from enum import Enum
class Side(Enum):
front = 1
back = 2
duplex = 3
class Job(object):
def __init__(self):
self.images = None
self.filename = None
self.side = None
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS231n Convolutional Neural Networks for Visual Recognition
http://cs231n.github.io/
Python Numpy Tutorial
http://cs231n.github.io/python-numpy-tutorial/
Numpy Reference
https://docs.scipy.org/doc/numpy/reference/
 ̄
2019-07-02 (Tue)
"""
# Python Numpy Tutorial > Clas... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import codecs
import json
import logging
import os
import sys
import time
FORMAT = '%(asctime)s - %(levelname)s %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)
class Nefnir(object):
"""
A r... |
# %% REQUIRED LIBRARIES
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
# %% EXAMPLE APPLICATION
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
data = [{'a': 1, 'b': 2... |
import pathlib as path
cwd = path.Path.cwd().parent
features_main = ["type", "game_id", "home_team", "away_team", "week", "season", "home_score", "away_score"]
league = "EPL"
###PATHS FOR SAVE FILE
input_raw = str(cwd) + "/input/" + league + "/01_raw/"
input_team = str(cwd) + "/input/" + league + "/teams/teams.csv"
f... |
import sqlite3
conn = sqlite3.connect('test.db')
print("Opened database successfully");
conn.execute('''DROP TABLE IF EXISTS USER;''')
conn.execute('''DROP TABLE IF EXISTS SERVICE_INFO;''')
conn.execute('''DROP TABLE IF EXISTS MESSAGE;''')
conn.execute('''CREATE TABLE USER
(ID INTEGER PRIMARY KEY autoincrem... |
import datetime as dt
from dateutil.relativedelta import relativedelta
def data_cadastro():
data_cad = dt.datetime.now()
return data_cad.strftime('%d.%m.%Y')
def data_cadastro_month():
data_cad = dt.datetime.now()
return data_cad.strftime('.%m.%Y')
def data_inicio():
data_ini = dt.d... |
import json
from os.path import expanduser, join
from pathlib import Path
import nacl.encoding
__all__ = ['encoder', 'paths', 'Store', 'store']
encoder = nacl.encoding.URLSafeBase64Encoder()
paths = type('paths', (), {})
paths.home = expanduser("~")
paths.config = join(join(paths.home, '.config'), 'salty')
paths.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.
#----------------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.