content
stringlengths
0
894k
type
stringclasses
2 values
from pathlib import Path import pytest RESOURCES_DIR = Path(__file__).parent / "resources" @pytest.fixture def users_path(): return RESOURCES_DIR / "test-users.json" @pytest.fixture def tweets_path(): return RESOURCES_DIR / "test-tweets.json"
python
import pandas as pd __all__ = ["calc_embedding_size"] def calc_embedding_size(df: pd.DataFrame) -> int: """ Calculates the appropriate FastText vector size for categoricals in `df`. https://developers.googleblog.com/2017/11/introducing-tensorflow-feature-columns.html Parameters ------...
python
import mailparser import re from nltk.tokenize import word_tokenize from nltk import pos_tag # #### typo_parser def typo_parser(x): """ 1. replace irrelevant symbol "|" or "*" 2. remove extra space " " 3. replace extra \n "\n\n" into "\n" 4. replace "> *>" into ">>" for further analysis @pa...
python
"""API package. Contains controller and model definitions. Modules: models routes views """
python
from transformers import AutoModelForSequenceClassification, Trainer, AutoTokenizer from sklearn.metrics import accuracy_score, precision_recall_fscore_support from datasets import load_from_disk import tarfile import os if len(os.listdir('model')) == 0: with tarfile.open('model.tar.gz') as tar: tar.extrac...
python
""" Visualize ========= pypesto comes with various visualization routines. To use these, import pypesto.visualize. """ from .reference_points import (ReferencePoint, create_references) from .clust_color import (assign_clusters, assign_clustered_colors, ...
python
import boto3 import pytest import uuid acm = boto3.client('acm') @pytest.fixture(scope="module") def certificate(): name = 'test-%s.binx.io' % uuid.uuid4() alt_name = 'test-%s.binx.io' % uuid.uuid4() certificate = acm.request_certificate(DomainName=name, ValidationMethod='DNS', SubjectAlternativeNames=[a...
python
import numpy as np from nlpaug.util import Method from nlpaug import Augmenter class SpectrogramAugmenter(Augmenter): def __init__(self, action, name='Spectrogram_Aug', aug_min=1, aug_p=0.3, verbose=0): super(SpectrogramAugmenter, self).__init__( name=name, method=Method.SPECTROGRAM, action=a...
python
# -*- coding: utf-8 -*- from flask import jsonify, request from pronto import utils from . import bp @bp.route("/<path:accessions>/proteins/") def get_proteins_alt(accessions): accessions = set(utils.split_path(accessions)) try: comment_id = int(request.args["comment"]) except KeyError: ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 8 18:04:51 2021 @author: jm """ # required libraries import pytest import pandas as pd import numpy as np from task1.helpers import Helper # sample rate values for different currencies rates = {'USD': 1.067218} # sample data frame df = pd.DataFr...
python
from ctypes import cdll, c_int, c_size_t my_lib = cdll.LoadLibrary('target/debug/librust_ffi.so') int_array_size = c_size_t(256) int_array = (c_int * int_array_size.value)() my_lib.produce_us_some_numbers(int_array, int_array_size) for i,n in enumerate(int_array): print(str(n) + ' ', end='') if (i + 1) % 16...
python
shapes = [ # Grosses L [ (0, 0, 0), (1, 0, 0), (2, 0, 0), (0, -1, 0) ], # T [ (0, 0, 0), (1, 0, 0), (2, 0, 0), (1, -1, 0) ], # Eck aka kleines L [ (0, 0, 0), (1, 0, 0), (0, -1, 0) ], # Treppe [ (0, 0, 0), (1, 0, 0), (1, 1, 0), (2, 1, 0) ], # Asymmetrische Ecken [ (0, 0, 0), ...
python
import sys import time import datetime lines = open(sys.argv[1], 'r') for line in lines: line = line.replace('\n', '').replace('\r', '') if len(line) > 0: a, b = sorted([datetime.datetime.strptime(x, "%H:%M:%S") for x in line.split(' ')]) hours, remainder = divmod((b - a).seconds, 3600...
python
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at: # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
python
# -*- coding: utf-8 -*- """The multi-process processing engine.""" import abc import ctypes import os import signal import sys import threading import time from plaso.engine import engine from plaso.engine import process_info from plaso.lib import definitions from plaso.multi_process import logger from plaso.multi_pr...
python
#!/usr/local/bin/python2.7 ## # OOIPLACEHOLDER # # Copyright 2014 Raytheon Co. ## from mi.core.versioning import version from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.driver.cg_stc_eng.stc.mopak_o_dcl_common_driver import MopakDriver from mi.dataset.parser.mopak_o_dcl import \ Mopak...
python
# Aula 08 (Usando Módulos do Python) from math import sin, cos, tan, radians # para seno, cosseno e tangente # é preciso converter o ângulo para radians angulo = float(input('Digite um Ângulo qualquer: ')) print('Ângulo: {:.2f}' '\nSeno: {:.2f}' '\nCosseno: {:.2f...
python
from consola import leer_caracter from consola import leer_entrada_completa from consola import obtener_caracter from consola import avanzar_caracter from consola import hay_mas_caracteres from consola import imprimir from consola import cambiar_color_texto min_C3_BAscula = None may_C3_BAscula = None def Buscar_vocal...
python
import os ls=["python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold0_noda.yml", "python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold1_noda.yml", "python main.py --configs configs/train_ricord1a_unetplusplus_timm-regnetx_002_fold2_noda.yml", "python main.py -...
python
nCr = [[0 for j in range(101)] for i in range(101)] for i in range(101): for j in range(i+1): if i==j or j==0: nCr[i][j] = 1 else: nCr[i][j] = nCr[i-1][j-1] + nCr[i-1][j] while True: n,r = list(map(int,input().split())) if n==0 and r==0: break print(str(n...
python
print("hola") kjnkjk
python
from setuptools import setup, find_packages setup( name="django-allmedia", url="http://github.com/suselrd/django-allmedia/", author="Susel Ruiz Duran", author_email="suselrd@gmail.com", version="1.0.20", packages=find_packages(), include_package_data=True, zip_safe=False, descriptio...
python
""" cloudalbum/app.py ~~~~~~~~~~~~~~~~~~~~~~~ AWS Chalice main application module :description: CloudAlbum is a fully featured sample application for 'Moving to AWS serverless' training course :copyright: © 2019 written by Dayoungle Jun, Sungshik Jou. :license: MIT, see LICENSE for more details...
python
# noqa: E501 ported from https://discuss.pytorch.org/t/utility-function-for-calculating-the-shape-of-a-conv-output/11173/7 import math def num2tuple(num): return num if isinstance(num, tuple) else (num, num) def conv2d_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): h_w, kernel_size, stride, ...
python
resposta = 42 print('A resposta para tudo é: ', resposta)
python
# -*- coding: utf8 -*- # # Copyright (c) 2016 Linux Documentation Project from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import unittest import argparse from argparse import Namespace from tldptesttools import TestToolsFilesystem from tldptesttools import CCT...
python
import time from adafruit_servokit import ServoKit kit = ServoKit(channels=16) def mouth(action): if(action == 0): print("openMouth") kit.servo[0].angle = 40 if(action == 1): print("close") kit.servo[0].angle = 180 if(action == 2): print("talk") #kit.servo[0...
python
""" Perceptual decision-making task, loosely based on the random dot motion task. """ import numpy as np from pycog import Model, RNN, tasktools #------------------------------------------------------------------------------- # Network structure #----------------------------------------------------------------------...
python
from OpenGL.GL import * import threading import random import time class Block: """ Block * Base block class """ def __init__(self, name, renderer): """ Block.__init__ :name: name of the block :texture: texture of the block :parent: the parent window ...
python
from django.conf import settings from .filebased import FileBackend from .s3 import S3Backend DEFAULT_CLASS = FileBackend def get_backend_class(): if settings.FILE_STORAGE_BACKEND == "s3": return S3Backend elif settings.FILE_STORAGE_BACKEND == "file": return FileBackend else: ...
python
from setuptools import setup setup(name='data_loader', version='0.1', description='Hackathon data loader', url='https://github.com/snowch-labs/or60-ocado-ibm-hackathon', author='Chris Snow', author_email='chris.snow@uk.ibm.com', license='Apache 2.0', packages=['data_loader'], ...
python
from json import loads from gtts import gTTS import urllib.request import time import random link = "http://suggestqueries.google.com/complete/search?client=firefox&q=" rap = "" def editLinkWithUserInput(link): magicWord = str(input("What do you want your starting words to be? ")) if " " in magicWord: ...
python
import sys import os cur = os.path.dirname(os.path.abspath(__file__)) sys.path.append(cur) sys.path.append(cur+"/..") sys.path.append(cur+"/../common") from SearchRepository import ISearchRepository import unittest from IQRServer import QRContext from IQRRepository import IQRRepository from search_service import * fro...
python
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
python
#!/usr/bin/python from __future__ import division, print_function import multiprocessing from subprocess import call import numpy as np import pandas as pd import numpy.linalg as linalg from math import sqrt import ld.ldscore as ld import ld.parse as ps from ldsc_thin import __filter_bim__ from scipy.stats import norm ...
python
file1=open("./protein1.pdb","r") file2=open("./protein2.pdb","r") from math import * model1=[] model2=[] for line in file1: line=line.rstrip() if "CA" in line: list1=line.split() model1.append([float(list1[6]),float(list1[7]),float(list1[8])]) for line in file2: line=line.rstrip() if "CA" in line: list2=line....
python
""" 关键点解析 链表的基本操作(删除指定节点) 虚拟节点dummy 简化操作 其实设置dummy节点就是为了处理特殊位置(头节点),这这道题就是如果头节点是给定的需要删除的节点呢? 为了保证代码逻辑的一致性,即不需要为头节点特殊定制逻辑,才采用的虚拟节点。 如果连续两个节点都是要删除的节点,这个情况容易被忽略。 eg: // 只有下个节点不是要删除的节点才更新current if (!next || next.val !== val) { current = next; } """ """ Before writing any code, it's good to make a list of edge cases ...
python
""" Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2:...
python
import redis rds=redis.StrictRedis('db', 6379)
python
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.contrib.auth.forms import PasswordChangeForm class CreateProject(forms.Form): projectname = forms.SlugField(label="Enter project name", max_length=50, required=True) helper = FormHelper() ...
python
from JumpScale import j def cb(): from .HttpClient import HttpClient return HttpClient() j.base.loader.makeAvailable(j, 'clients') j.clients._register('http', cb)
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Assumes: Python 3 (>= 3.6) # selenium ($ pip install selenium) # ChromeDriver (http://chromedriver.chromium.org) # Chrome binary (> v61) # __author__ = "Adam Mikeal <adam@tamu.edu>" __version__ = "0.8" import os import sys import logging i...
python
""" Azdevman Consts This module contains constant variables that will not change """ # Environment Variables AZDEVMAN_ENV_PREFIX = "AZDEVMAN_" # Azure Devops AZ_BASE_URL = "https://dev.azure.com/" AZ_DEFAULT_ORG = "ORGANIZATION" AZ_DEFAULT_PAT = "UEFUCg==" AZ_DEFAULT_PROJECT = "PROJECT" # Config file CONFIG_DIR = "...
python
class JintaroException(Exception): """Base class for Jintaro exceptions""" class ConfigError(JintaroException): """Base class for config exceptions""" class UnknownOptionError(ConfigError): """""" class ConfigValueError(ConfigError): """""" class InputListError(JintaroException): """""" cl...
python
#! /usr/bin/env python def read_file(): """Opens Project Euer Name file. Reads names, sorts and converts str into a list object""" a = open('names.txt', 'r') data = a.read() names = data.split(",") a.close() names.sort() return names def name_score(): """Calculates the total nam...
python
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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...
python
#!/usr/bin/env python # J-Y Peterschmitt - LSCE - 09/2011 - pmip2web@lsce.ipsl.fr # Test the use of hatches and patterns in the isofill # and fill area graphics methods # Import some standard modules from os import path # Import what we need from CDAT import cdms2 import vcs # Some data we can plot from the 'sampl...
python
from thresher.scraper import Scraper from thresher.query_share import QueryShare import furl import csv import os from slugify import slugify import wget import json ### Possibly convert this to docopt script in the future ### class Thresher: #assumes that links is a list of dictionaries with the keys as a conten...
python
from hknweb.academics.views.base_viewset import AcademicEntityViewSet from hknweb.academics.models import Instructor from hknweb.academics.serializers import InstructorSerializer class InstructorViewSet(AcademicEntityViewSet): queryset = Instructor.objects.all() serializer_class = InstructorSerializer
python
import sys if len(sys.argv) == 2: print("hello, {}".format(sys.argv[1])) #print("hello,"+(sys.argv[1])) else: print("hello world")
python
import pydot # I like to use the full path for the image as it seems less error prone. # Therefore, first we find the current path of this file and use that to locate the image - assuming the image, # is in the same folder as this file. import pathlib current_path = pathlib.Path(__file__).parent.resolve() # Create t...
python
# -*- coding: utf-8 -*- """ Copyright [2020] [Sinisa Seslak (seslaks@gmail.com) 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/lice...
python
import numpy as np class Kalman(object): DIMENSIONS = 3 MEASUREMENT = 1 def __init__(self, q, r): #initialise self.Q = np.matrix(np.eye(Kalman.DIMENSIONS)*q) self.R = np.matrix(np.eye(Kalman.MEASUREMENT)*r) self.H = np.matrix(np.zeros((Kalman.MEASUREMENT, Kalman.DIMENSIO...
python
# Databricks notebook source # MAGIC %run ./_databricks-academy-helper $lesson="dlt_demo" # COMMAND ---------- try: dbutils.fs.unmount("/mnt/training") except: pass # %run ./mount-datasets # COMMAND ---------- class DataFactory: def __init__(self): self.source = f"{DA.paths.data_source}/tracker/streamin...
python
r""" bilibili_api.live 直播相关 """ import time from enum import Enum import logging import json import struct import base64 import asyncio from typing import List import aiohttp import brotli from aiohttp.client_ws import ClientWebSocketResponse from .utils.Credential import Credential from .utils.ne...
python
import sys import os import torch import librosa import soundfile as sf import numpy as np import tkinter as tk from tkinter import filedialog import openunmix from PySide6 import QtCore class Main(QtCore.QThread): def __init__(self): super(Main, self).__init__() self.global_objects = {} de...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: train-atari.py # Author: Yuxin Wu import numpy as np import sys import os import uuid import argparse import cv2 import tensorflow as tf import six from six.moves import queue from tensorpack import * from tensorpack.tfutils import optimizer from tensorpack.util...
python
#!/usr/bin/env python import os import sys import socket import rospy from robotiq_control.cmodel_urscript import RobotiqCModelURScript from robotiq_msgs.msg import CModelCommand, CModelStatus def mainLoop(urscript_topic): # Gripper is a C-Model that is connected to a UR controller. # Commands should be published...
python
import torch import torch.nn.functional as F class DynamicsModel(torch.nn.Module): # transitioin function def __init__(self, D_in, D_out, hidden_unit_num): print("[DynamicsModel] H =",hidden_unit_num) super(DynamicsModel, self).__init__() # zero hidden layer #self.l1 = torch.nn.Li...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Script to plot storage IO timing usage from profiling data. This script requires the matplotlib and numpy Python modules. """ from __future__ import print_function from __future__ import unicode_literals import argparse import glob import os import sys import numpy ...
python
# -*- coding: utf-8 -*- import datetime from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from taxi_online_example.utils import date_now_or_future_validator, UTC from django.forms.models import model_to_dict class TaxiLocation(models.Model): taxi_id = models.Cha...
python
from get_data import *
python
import os import gzip import shutil import struct import urllib import numpy as np import matplotlib.pyplot as plt import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL']='2' def read_data(filename): """ :param filename :return: array """ text = open(filename, 'r').readlines()...
python
#!/usr/bin/env python """ DBSCAN Project - M2 SSI - Istic, Univ. Rennes 1. Andriamilanto Tompoariniaina <tompo.andri@gmail.com> This module is an implementation of K-mean algorithm to confront it with our implementation of the DBSCAN one. """ # -- Imports import sys import random import operator from pandas import D...
python
import csv from stations import Station, Stations csvfile="./source/stations_aod.csv" def readCSV(csv_file): stations_aod=dict(); with open(csv_file,'rb') as csvfile: spamreader=csv.reader(csvfile,delimiter=",",quotechar='|') for row in spamreader: stations_aod[row[0]]=(row) ...
python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from math import log class Solution: # @param {TreeNode} root # @return {integer[]} def rightSideView(self, root): def df...
python
#Ejercicio 2 - Cuaderno 2 """ Implementa un programa modularizado que, leyendo de teclado los valores necesarios, muestre en pantalla el área de un círculo, un cuadrado y un triángulo. Utiliza el valor 3.1416 como aproximación de П (pi) o importa el valor del módulo “math”. """ import math print ('Círculo') radio= f...
python
import sys def main(): infile=open(sys.argv[1],"r") counter=0 tf="" for l in infile: if (">" in l): s=l.split() if (tf!=""): print(tf+'\t'+str(counter)) counter=0 tf=s[1].upper() elif ("#" not in l): counter+=1 print(tf+'\t'+str(counter)) infile.close() main()
python
# -*- coding: utf-8 -*- """ @author: Hiromasa Kaneko """ import pandas as pd from sklearn.neighbors import NearestNeighbors # k-NN k_in_knn = 5 # k-NN における k rate_of_training_samples_inside_ad = 0.96 # AD 内となるトレーニングデータの割合。AD のしきい値を決めるときに使用 dataset = pd.read_csv('resin.csv', index_col=0, header=0) x_pr...
python
from BogoBogoSort import bogoBogoSort from BogoSort import bogoSort from BozoSort import bozoSort from CommunismSort import communismSort from MiracleSort import miracleSort from StalinSort import stalinSort from SlowSort import slowSort import numpy as np import time import matplotlib import matplotlib.pyplot a...
python
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Django model mixins and utilities.""" class RunTextFieldValidators: """ Mixin to run all field validators on a save method call This mixin should appear BEFORE Model. """ def save(self, *args, **kwargs): """ ...
python
#! python3 # voicechannelcontrol.py """ ============================================================================== MIT License Copyright (c) 2020 Jacob Lee 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...
python
""" Copyright MIT and Harvey Mudd College MIT License Summer 2020 Lab 3B - Depth Camera Cone Parking """ ######################################################################################## # Imports ######################################################################################## import sys import cv2 as...
python
import pytest class RespIs: @staticmethod async def no_content(resp): assert resp.status == 204 @staticmethod async def bad_gateway(resp, message="Bad gateway"): """ Check whether a response object is a valid Virtool ``bad gateway``. """ assert resp.status == 5...
python
""" Some examples playing around with yahoo finance data """ from datetime import datetime from pandas.compat import zip import matplotlib.finance as fin import numpy as np from pylab import show from pandas import Index, DataFrame from pandas.core.datetools import BMonthEnd from pandas import ols startDate = date...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo import torch.autograd as autograd from torch.autograd.variable import Variable from threading import Lock from torch.distributions import Categorical global_lock = Lock() model_urls...
python
from sqlalchemy import Table, Column, Integer, String, ForeignKey from utils import metadata category = Table( "category", metadata, Column("id", Integer, primary_key=True), Column("parent_fk", Integer, ForeignKey("category.id"), nullable=True), Column("label", String(length=60), unique=True, n...
python
import lark from foyer.exceptions import FoyerError GRAMMAR = r""" start: _string // Rules _string: _chain _nonlastbranch* _lastbranch? _chain: atom _chain | atom _nonlastbranch: "(" branch ")" _lastbranch: branch branch: _string atom: ("[" weak_and_expression "]" | atom_symbol) atom_...
python
""" Created on 13-Apr-2018 @author: jdrumgoole """ import unittest import pymongo from dateutil.parser import parse from pymongoimport.audit import Audit class Test_Audit(unittest.TestCase): def setUp(self): self._client = pymongo.MongoClient(host="mongodb://localhost/TEST_AUDIT") self._databa...
python
# search target number in the list. class LinearSearch : def __init__(self,target, data): self.data = data self.target = target print(self.doSearch()) def doSearch(self): for current in self.data : if current == self.target : return "Target Number...
python
import numpy as np from flask import Flask, render_template, request import jinja2 from MBScalc import * #Init Flask App app = Flask(__name__) @app.route('/', methods = ['GET','POST']) def main(): number = int(request.form['number']) if request.method == 'POST': result = number else: result = 0 # mass = float...
python
# -*- coding: utf-8 -*- import logging from random import randint import re import six import os from datetime import datetime __author__ = "Arun KR (kra3) <the1.arun@gmail.com>" __license__ = "Simplified BSD" RE_IP = re.compile(r'^[\d+]{1,3}\.[\d+]{1,3}\.[\d+]{1,3}\.[\d+]{1,3}$', re.I) RE_PRIV_IP = re.compile(r'^(?...
python
from Cimpl import load_image, create_color, set_color, show, Image, save_as, copy from typing import NewType image = load_image('p2-original.jpg') # loads the original colourless picture def createBlue( image ): """ the function createBlue displays the original image, once closed it displays the image with a bl...
python
import os import sys from random import Random import numpy as np from os.path import join import re from gpsr_command_understanding.generator.grammar import tree_printer from gpsr_command_understanding.generator.loading_helpers import load, GRAMMAR_YEAR_TO_MODULE, load_paired from gpsr_command_understanding.generato...
python
#!/usr/bin/env python3 from sys import argv,stderr,exit import json, os, yaml, pynetbox, re, ipaddress from collections import defaultdict from pprint import pprint doc = """ Get config context from netbox for specified device. ## Usage %s "FQDN" """ % (argv[0]) def assume_ip_gateway(network): return str(ipadd...
python
from scipy.optimize import shgo import numpy as np from numpy.linalg import norm class VectorCubicSpline: """ a0, a1, a2, a3 are numpy vectors, they form the spline a0 + a1*s + a2*s^2 + a3*s^3 """ def __init__(self, a0, a1, a2, a3): self.a0 = np.array(a0) self.a1 = np.array(a1) self.a2...
python
class Fonction: def calcul(self, x): pass class Carre(Fonction): def calcul(self, x): return x*x class Cube(Fonction): def calcul(self, x): return x*x*x def calcul_n_valeur (l,f): res = [ f(i) for i in l ] return res l = [0,1,2,3] l1 = calcul_n_valeur(l, Carre().cal...
python
import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests def aggregate_tags_count(new_values, total_sum): return sum(new_values) + (total_sum or 0) def get_sql_context_instance(spark_...
python
""" API serializers """ from rest_framework import serializers from groups.models import CustomUser, Group, Link class CustomUserBaseSerializer(serializers.ModelSerializer): """ CustomUser base serializer """ class Meta: model = CustomUser fields = ('id', 'username', 'email', 'date_jo...
python
import argparse import json from pathlib import Path from typing import Iterable, Set import pandas as pd from hyperstyle.src.python.review.inspectors.inspector_type import InspectorType from hyperstyle.src.python.review.inspectors.issue import BaseIssue, IssueType from hyperstyle.src.python.review.reviewers.utils.pri...
python
""" The STDIO interface for interactive CIS. Authors: Hamed Zamani (hazamani@microsoft.com) """ import time import traceback from macaw import util from macaw.interface.interface import Interface from macaw.core.interaction_handler.msg import Message class StdioInterface(Interface): def __init__(self, params):...
python
from rest_framework import status from webfront.tests.InterproRESTTestCase import InterproRESTTestCase from webfront.models.interpro_new import Release_Note class UtilsAccessionTest(InterproRESTTestCase): def test_can_read_structure_overview(self): response = self.client.get("/api/utils") self.ass...
python
import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" os.environ["CUDA_VISIBLE_DEVICES"] = "3" import warnings warnings.filterwarnings('ignore') import pickle as pickle import numpy as np import datetime from keras import Model import keras import queue from keras.layers import Dense, Activation, Dropout, Layer...
python
boot_list = [ "anklet", "boots", "clogs", "feet", "footguards", "footpads", "footsteps", "footwraps", "greatboots", "greaves", "heels", "sabatons", "sandals", "slippers", "sneakers", "socks", "sprinters", "spurs", "stompers", "treads", "walkers", "warboots", "wraps", "zoomers"] body_list = [ "bande...
python
# -*- coding: utf-8 -*- import cv2 import numpy as np from typing import Tuple, List, Union from image_registration.keypoint_matching.kaze import KAZE from image_registration.exceptions import (CreateExtractorError, NoModuleError, NoEnoughPointsError) class ORB(KAZE): METHOD_NAME = "ORB" def __init__(self, t...
python
""" functions for deterministically preprocessing 2D images (or 3D with color channels) mostly for the consumption of computer vision algorithms """ import math import numpy as np import skimage.transform from .. import utils def _center_coords_for_shape(shape): """ returns the center of an ndimage with a gi...
python
# This file is a part of Arjuna # Copyright 2015-2020 Rahul Verma # Website: www.RahulVerma.net # 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...
python
# Copyright (c) 2019, Ahmed M. Alaa # Licensed under the BSD 3-clause license (see LICENSE.txt) import pandas as pd import numpy as np def draw_ihdp_data(fn_data): # Read the covariates and treatment assignments from the original study # -----------------------------------------------------------------...
python
import numpy as np from numba import njit, prange from SZR_contact_tracing import nb_seed, update_cell, szr_sample, mszr_sample @njit def cluster_size(L: int, seed: int, alpha: float = 0.25, occupancy: float = 1, mszr: bool = True): # Initialize a lattice, run it, and return the cluster size. nb_seed(L) l...
python
"""Constants for the Kostal Plenticore Solar Inverter integration.""" from typing import NamedTuple from homeassistant.components.sensor import ( ATTR_STATE_CLASS, SensorDeviceClass, SensorStateClass, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, ...
python