content stringlengths 5 1.05M |
|---|
try:
import simplejson as json
print "Using simplejson for faster json parsing"
except ImportError:
import json
import telemetryutils
import jydoop
import sys
python_map = map
def map(uid, line, context):
payload = json.loads(line)
try:
i = payload['info']
channel = i.get('appUpdat... |
import pytest
from stix2.hashes import Hash, check_hash, infer_hash_algorithm
@pytest.mark.parametrize(
"hash_name, expected_alg", [
("md5", Hash.MD5),
("md6", Hash.MD6),
("ripemd160", Hash.RIPEMD160),
("sha1", Hash.SHA1),
("sha224", Hash.SHA224),
("sha256", Hash.S... |
'''
Joe Walter
difficulty: 5%
run time: 0:20
answer: 40730
***
034 Digit Factorials
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
***
O... |
from functools import lru_cache
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
@lru_cache(maxsize = None)
def helper(n):
if n == 1:
return 1
elif n == 2:
return 2
... |
from torch.optim import Optimizer
from vel.api import TrainingInfo, EpochInfo, Learner, Model, Source
class TrainPhase:
""" A single phase of training """
@property
def number_of_epochs(self) -> int:
""" How many epochs does this phase take """
raise NotImplementedError
def set_up_p... |
import os
basedir = os.path.abspath(os.path.dirname(__file__)) # relpath
class Config(object):
MAX_LENGTH = 34
UPLOAD_FOLDER = 'tmp/'
# app.config['DISPLAY_FOLDER'] = 'app/static/'
# app.config['FINAL_FOLDER'] = 'static/'
SECRET_KEY = 'you-will-never-guess'
# SQLALCHEMY_DATABASE_URI = os.envir... |
import re
from django import template
register = template.Library()
@register.filter(name="embedurl")
def get_embed_url_with_parameters(url):
print('we inside this emb')
if "youtube.com" in url or "youtu.be" in url:
regex = r"(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)" # ... |
def register_data(app):
from app.api.data.file import blueprint as data_file
from app.api.data.friend import blueprint as data_friend
from app.api.data.mail import blueprint as data_mail
from app.api.data.post import blueprint as data_post
from app.api.data.server import blueprint as data_server
... |
import numpy as np
import torch
import gym
from PIL import Image
import imageio
from pygifsicle import optimize
import os, sys
root_dir = os.path.dirname(os.path.abspath(__file__))
external_dir = os.path.join(root_dir, 'externals')
sys.path.insert(0, root_dir)
sys.path.insert(1, os.path.join(external_dir, 'pytorch_a2... |
from prompt.prompt.context import Context as BaseContext
class Context(BaseContext):
__slots__ = [
'nvim',
'text',
'caret_locus',
'buffer_number',
'buffer_content',
'buffer_options',
'window_options',
'selected_line',
'selected_indices',
... |
import plugin
import urwid # 1.3.1
class HelloWorld(plugin.BasePlugin):
"""A simple demonstration plugin.
"""
def __init__(self):
super().__init__()
self.main_widget = urwid.Text("Hello World!")
def get_main_widget(self):
return self.main_widget
def new_instance(framework... |
# Copyright (c) 2021. Universidad de Pinar del Rio
# This file is part of SCEIBA (sceiba.cu).
# SCEIBA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
from __future__ import absolute_import, division, print_function
import click... |
Infinity = float('inf')
import op
import iz
class Iterator(object):
def __init__(self, ops):
self.ops = ops
self.index = 0
self.offset = 0
def hasNext(self):
return self.peekLength() < Infinity
def next(self, length=Infinity):
try:
nextOp = self.ops... |
import processout
from processout.errors.notfounderror import NotFoundError
from processout.gatewayrequest import GatewayRequest
def main():
client = processout.ProcessOut("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x",
"key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB")
# Create ... |
import os
from codecs import open
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), "README.md")) as f:
long_description = f.read()
setup(
name = 'electronicscalc',
packages = ['electronicscalc'],
version = '0.5',
license='MIT',
description = 'This is the package t... |
from hashlib import sha1
from time import time
try:
# Due: https://www.python.org/dev/peps/pep-0476
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by defau... |
from collections import Counter
from utils import fileToDict
class Knn:
def __init__(self, nn=2):
self.xtrain = list()
self.ytrain = list()
self.nn = nn
def train(self, x: list, y: list):
self.xtrain += x
self.ytrain += y
def predict(self, xpred: dic... |
from rest_framework import serializers
from .models import DataDogConfiguration
class DataDogConfigurationSerializer(serializers.ModelSerializer):
class Meta:
model = DataDogConfiguration
fields = ("id", "base_url", "api_key")
|
'''https://projecteuler.net/problem=6'''
'''Please see the README document for details'''
import math
def run(limit):
result = 0
print "Way #1"
for outer_counter in range(1, limit+1, 1):
for inner_counter in range(outer_counter+1,limit+1,1):
result = result + 2*outer_counter*inner_counter
print "Difference b... |
#!/usr/bin/env python
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
import copy
import sift
class Blob_Detect:
def __init__(self, image):
self.image = image
self.minThreshold = 1
self.maxThreshold = 2000
# Filter by Area.
self.filter... |
from time import sleep
c=('\033[m', #0 sem cor
'\033[0;30;41m',#1 vermelho
'\033[0;30;42m',#2 verde
'\033[0;30;43m',#3 amarelo
'\033[0;30;44m',#4 azul
'\033[0;30;45m',#5 roxo
'\033[0;30;42m',#6 branco
)
def titulo(txt):
x=len(txt)
print(f'{c[1]}~'* (x +4),f'{c[0]}')
print(f'{c[2]}... |
##
# Copyright © 2020, The Gust Framework Authors. All rights reserved.
#
# The Gust/Elide framework and tools, and all associated source or object computer code, except where otherwise noted,
# are licensed under the Zero Prosperity license, which is enclosed in this repository, in the file LICENSE.txt. Use of
# this ... |
import logging
logging.basicConfig(format="[%(asctime)s] %(message)s", datefmt="%m-%d %H:%M:%S")
import os
import time
import numpy as np
import tensorflow as tf
import core.data.cifar_data as cifar
import core.data.mnist_data as mnist
from network import Network
from statistic import Statistic
import utils as util
... |
import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
tf_ys = tf.placeholder("float", shape=[ None, 1 ])
b = tf.Variable(tf.zeros([ 1 ]))
tf_res = tf.reduce_sum(tf_ys - b)
ops = tf.train.GradientDescentOptimizer(0.4).minimize(tf_res)
tf.train.write_graph(graph.as_graph_def(), '.', 'simple.pbtxt'... |
#!/usr/bin/env python
# coding: utf-8
"""
Copyright (c) 2021 Tatsuya Matsuura
Released under the MIT License.
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 witho... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import hashlib
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE']
app.config['SQLALCHEMY_POOL_RECYCLE'] = 30;
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
use... |
import os
from symbolic import Unreal4Crash
def test_unreal_crash_files(res_path):
path = os.path.join(res_path, 'unreal', 'unreal_crash')
with open(path, mode='rb') as crash_file:
buffer = crash_file.read()
unreal_crash = Unreal4Crash.from_bytes(buffer)
files = list(unreal_crash.files... |
# Generated by Django 4.0.3 on 2022-03-20 20:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
'''
Created on 06 May 2010
@author: EWillemse
'''
import routes_neighbours_IF_all as RN
import time
import transformSolution
import reduceNumberTrips_IF as RED
import refitIFs
import testSolutions
import gen_neighbours_beta1
from copy import deepcopy
#================================================... |
# -*- coding: utf-8 -*-
import platform
import sys
import pytest
LINUX = sys.platform.startswith("linux")
MACOS = sys.platform.startswith("darwin")
WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin")
CPYTHON = platform.python_implementation() == "CPython"
PYPY = platform.python_implementation... |
import argparse
import logging
from typing import Any, Dict
__all__ = ["add_options", "apply_options", "update_config"]
logger = logging.getLogger(__name__)
def add_options(parser: argparse.ArgumentParser) -> None:
"""
Add options to parser.
"""
parser.add_argument(
"opts",
help="mod... |
from model.contact import Contact
from model.group import Group
import random
from fixture.orm import ORMFixture
orm = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
def test_add_contact_to_group(app, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(first_nam... |
# Generated by Django 2.2.1 on 2019-10-14 05:56
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='History',
fields=[
('id', models.AutoField(... |
import os # path
import sys # path
import yaml # safe_load, YAMLError
import glob # glob
import importlib # import_module
import pytest # skip
import warnings # warn
# For type hints only:
from typing import Union
from types import ModuleType
from _pytest.config import C... |
from Statistics.Proportion import proportion
from Calculators.Subtraction import subtraction
from Calculators.Division import division
from Calculators.Multiplication import multiplication
def var_pop_proportion(data):
p = proportion(data)
q = subtraction(1, p)
data = [num for elem in data for num in elem... |
# -*- coding: utf-8 -*-
"""
******* 文档说明 ******
通过 SlideCutWord 脚本 提取的词出现次数统计数据 计算 n_gram 下各个新词的 凝固度、自由度
并通过 p_min(最小概率或频数)、co_min(凝固度)、h_max(自由度) 的设置阈值 找出训练样本中可能性最大的用户词典
Time: 2020/11/26 21:46
Author: ChenXin
Version: V 0.1
File: bulletDensity.py
Describe: Github link: https://github.com/Chen-X666
"""
im... |
import re
# Read the file (using a different, more python 3 way, just for fun!)
with open('../data/blackbirds.txt', 'r') as f:
text = f.read()
# replace \t's and \n's with a spaces:
text = text.replace('\t',' ')
text = text.replace('\n',' ')
# You may want to make other changes to the text.
# In particular, not... |
import datetime
import boto3
import json
import os
# Prefix to give to training jobs, models, and endpoint configs, and endpoint name
MODEL_PREFIX = os.environ['MODEL_PREFIX']
# Name of Parameter Store key corresponding to value of last successful training job date
LAST_TRAIN_PARAM = '/models/{}/train/latest'.format... |
from sqlalchemy import Column, Integer, NVARCHAR, CHAR, DateTime, ForeignKey, NVARCHAR
from sqlalchemy.orm import relationship
from database import Base
class ShopMember(Base):
__tablename__ = 'shop_member'
id = Column(Integer, primary_key=True)
name = Column(NVARCHAR(50))
email = Column(NVARCHAR(200)... |
from unittest.mock import patch
import numpy as np
import pandas as pd
import pytest
import woodwork as ww
from pandas.testing import assert_frame_equal
from woodwork.logical_types import (
Boolean,
Categorical,
Datetime,
Double,
Integer,
)
from rayml.pipelines import TimeSeriesFeaturizer
ROLLING... |
# -*- coding: utf-8 -*-
"""
Module for functional test '22_delete' of gitcache.
Copyright:
2022 by Clemens Rabe <clemens.rabe@clemensrabe.de>
All rights reserved.
This file is part of gitcache (https://github.com/seeraven/gitcache)
and is released under the "BSD 3-Clause License". Please see the ``LI... |
import sys
import urllib2
from PyQt4 import QtCore, QtGui
class DownloadThread(QtCore.QThread):
data_downloaded = QtCore.pyqtSignal(object)
def __init__(self, url):
QtCore.QThread.__init__(self)
self.url = url
def run(self):
info = urllib2.urlopen(self.url).info()
self.... |
##
# Copyright (c) 2007-2013 Apple Inc. 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 l... |
# import modules
from colorexlib.colorex import ColorExGrid
# set tile grid options
options = dict()
options['source'] = ['data\\attendance.csv', 'csv']
options['title'] = 'Student Attendance'
options['subtitle'] = 'Attendance of students per month in 2018'
options['theme'] = 'default'
# create ColorEx o... |
"""Zendown flavored Markdown. It extends Markdown with macros."""
from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, List, NamedTuple, Optional
from mistletoe import block_token, span_token
from mistletoe.block_token import BlockToken, Document, Heading, HTMLBlock, Quote
fr... |
# Practice 01 - Python basics
# The program ask the user to enter a number
# then tell us if the number is pair or impair
def exo01():
while True:
# Catch with the try the possible exceptions that user can enter
try:
# Capture the user input
n = int(input("Enter a number ... |
#
# Copyright 2010-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version... |
#67 Faça um programa que leia um número inteiro e forneça a tabuada, utilizando WHILE.
def Main067():
a = b = 0
while True:
a = int(input('Quer ver a tabuada de que valor? '))
if a <= 0:
break
for b in range (0,11):
print(f'{a} x {b} = {a*b:.0f}')
b +... |
from .config import YamlConfig
def get_yaml_config() -> YamlConfig:
yaml_config = YamlConfig()
yaml_config.load('./test_resources/yaml_config.yaml')
return yaml_config
def test_yaml_config_get_tasks_hello_description():
yaml_config = get_yaml_config()
assert yaml_config.get(['tasks', 'hello', 'd... |
import os
from collections import OrderedDict
from onegov.foundation import BaseTheme
from onegov.core.utils import module_path
HELVETICA = '"Helvetica Neue", Helvetica, Roboto, Arial, sans-serif !default;'
ARIAL = 'Arial, sans-serif !default;'
VERDANA = 'Verdana, Geneva, sans-serif !default;'
COURIER_NEW = '"Courier... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .get_cluster_node_pool import *
from .get_kube... |
'''
Created on Mar 28, 2019
@author: XBBNTNI
'''
#!/usr/bin/env python
import sys
import wx
import wx.stc as stc
# import wx.lib.scrolledpanel as scrolled
from wx.lib.wordwrap import wordwrap
from diffutil import FancySequenceMatcher
FACE1 = FACE2 = FACE3 = "Dejavu Sans Mono"
FACE_SIZE = 10
DEBUG = 1
class Dif... |
#!/usr/bin/python3
import os
import glob
import time
import socket
from config import api_key
from datetime import datetime
import RPi.GPIO as GPIO
from Adafruit_CharLCD import Adafruit_CharLCD
# Initialize LCD (must specify pinout and dimensions)
lcd = Adafruit_CharLCD(rs=26, en=19, d4=13, d5=6, d6=5, d7=11, cols=1... |
wdth=500
hght=500
x1=100
y1=100
x2=250
y2=350
x3=450
y3=100
outsideRadius = 150
insideRadius = 100
c=color(int(random(0,255)),int(random(0,255)),int(random(0,255)),50)
def setup():
size(wdth,hght)
background(205)
x = wdth / 2
y = hght / 2
def draw() :
numPoints = int(map(mouseX, 0, wi... |
'''
Just the setup.
'''
from setuptools import setup, find_packages
def readme():
with open('README.rst') as f:
return f.read()
# Package details
setup(
name='machine-learning-fortune',
version='0.0.1',
author='Will Ballard',
author_email='wballard@mailframe.net',
url='https://github... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, UsernameField
from django.utils.translation import ugettext_lazy as _
from .models import User
class AdminUserCreationForm(UserCreationForm):
"""
Custom ... |
#!/usr/bin/env python
#
# 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 ... |
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.lines import Line2D
import os
import itertools
import pf_dynamic_cart as pfc
import pf_dynamic_sph as pfs
import Grid
from scipy import interpolate
... |
__author__ = 'surya'
from Mysql_queries import MySqlConnection
def getAlldata_fromDatabase(Query,cnx,query_val='Null',append=False):
if not cnx.is_connected():
cnx = MySqlConnection.connectSql()
dic={}
cursor3 = cnx.cursor()
if query_val!="Null":
cursor3.execute(Query,query_val)
e... |
import base64
import csv
import io
from utility import Utility
class Report(object):
"""
We use this class to generate text reports.
Class based on awilson@cloudpassage.com's Report.py class and modified
for this purpose
"""
@classmethod
def create_csv_report(cls, vulnerable_image_check_da... |
"""
Xlink utility methods.
Copyright (C) 2019-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
import logging
from typing import List
from ctypes import *
from ..constants import XLINK_LIB_PATH, SW_DEVICE_ID_PCIE_INTERFACE, SW_DEVICE_ID_INTERFACE_SHIFT, \
SW_DEVICE_ID_INTERFACE_MASK, M... |
import logging
from typing import Optional, Tuple
from snuba.consumers.consumer_builder import ConsumerBuilder
from snuba.stateful_consumer import ConsumerStateData, ConsumerStateCompletionEvent
from snuba.utils.state_machine import State
logger = logging.getLogger('snuba.snapshot-catchup')
class CatchingUpState(St... |
import re
import rethinkdb as r
from repool import ConnectionPool
from rethinkdb.errors import RqlRuntimeError, RqlDriverError, ReqlCursorEmpty
from app.incident import Incident, LIST_FIELDS, CRITICAL_FIELDS
from templates.responses import (
CREATE_INCIDENT_FAILED, SET, GET, GET_LIST, NAG)
class CommanderBase:
... |
import math
import numpy as np
import os
from PIL import Image
import random
import torch
import torch.utils.data as data
import pickle
# import pickle
# with open('x.pkl', 'wb') as file:
# pickle.dump(object, file)
default_data_path = {
"200MB": "/miniscratch/tyz/datasets/CloudCast/200MB/pkls/",
"8GB": "... |
# -*- coding: utf-8 -*-
# encoding: utf-8
'''
Created on 2015年3月1日
@author: kane
'''
import six
from billiards.pay import Pay
import alipay
from billiards.views.transaction import getIdFromTradeNum,\
transactionSuccessNotification, TRANSACTION_TIME_FORMAT
from xml.etree import ElementTree
if six.PY3:
from urll... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Pose estimation of the camera
#
# External dependencies
import pickle
import cv2
import numpy as np
# Calibration pattern size
pattern_size = ( 9, 6 )
# Chessboard pattern
pattern_points = np.zeros( ( np.prod( pattern_size ), 3 ), np.float32 )
pattern_points[ :, :2 ]... |
# Contains code under test for pytest notebook
def add_func(a, b):
return a + b
def prime(a, b):
return a**b
def euclid(p, q):
"""Return the euclidean distance.
Args:
p (list): p vector
q (list): q vector
Returns:
euclidean distance
"""
dist = 0
for p_i, q_i... |
import pytest
from .DirectorRequestBuilder import DirectorRequestBuilder
from .BuilderPointImageryRequest import BuilderPointImageryRequest
from .pointImageryRequest import PointImageryRequest
@pytest.fixture
def testPointRequest():
tempOrder = BuilderPointImageryRequest()
director = DirectorRequestBuilder()... |
import matplotlib.pyplot as plt
import numpy as np
from pymoo.visualization.fitness_landscape import FitnessLandscape
from pymoo.visualization.video.callback_video import AnimationCallback
class TwoVariablesOneObjectiveVisualization(AnimationCallback):
def __init__(self,
n_samples_for_surface=1... |
#! usr/bin/env python3
# -*- coding: utf-8 -*-
'''
This features.py is used to extract audio features based on openSIMLE.
Require: openSMILE-2.2rc1
OpenSMILE only support audios in WAV format,
so before using this script you could
transform MP3s into WAVs by transformat.sh.
'''
__author__ = 'huizhang'
import csv
im... |
from unittest.mock import patch
import miscutils.testing as under_test
class TestPatcher:
# Its tempting to use the utility to test itself...
@patch("miscutils.testing.patch")
def test_creates_relative_patches(self, mock_patch):
mock_patch.return_value = "patch_context"
relative_patch = u... |
import pymongo
import unittest
import pytest
from pymongo import IndexModel
from mongodantic.models import MongoModel
from mongodantic import connect
from mongodantic.exceptions import MongoIndexError
class TestIndexOperation:
def setup(self, drop=False, basic_indexes=True):
connect("mongodb://127.0.0.1:2... |
# Copyright 2020 MONAI Consortium
# 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... |
#Utility routines for HyperDrive and HyperCheck
import numpy as np
import copy
import importlib
from scipy import optimize
big = 1.0e10
small = 1.0e-6
def mac(x):
if x > 0.0: return x
else: return 0.0
def S(x):
if x > 0.0: return 1.0
else: return -1.0
def floor(x):
if x < small: r... |
#!/usr/bin/env python3
##########################################################
## Jose F. Sanchez ##
## Copyright (C) 2019 Lauro Sumoy Lab, IGTP, Spain ##
##########################################################
"""
Generates sample identification using KMA software and MLSTar.
Looks for similar ... |
for i in range (6):
for j in range (7):
if (i==0 and j %3!=0) or (i==1 and j % 3==0) or (i-j==2) or (i+j==8):
print("*",end=" ")
else:
print(end=" ")
print()
|
import torch.utils.data
from datasets.dataset import DatasetFactory
class CustomDatasetDataLoader:
def __init__(self, opt):
self.opt = opt
self.num_threds = opt.n_threads_train
self.create_dataset()
def create_dataset(self):
self.dataset = DatasetFactory.get_by_name(
... |
from kmeans1d.core import cluster, Clustered, __version__
|
from tests.utils import W3CTestCase
class TestAnonymousBoxGeneration(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'anonymous-box-generation-'))
|
import pytest
from numpy import array, log
from pandas import DataFrame
from minecraft_learns.common import *
def test_euclidean_distance():
a = array([[0,1,2,3],[2,0,2,-1]])
b = array([1,3,4,1])
dist = euclidean_distance(a, b)
assert dist.shape == (2,)
def test_mean_zero_normalize():
a = arr... |
import base64
import PySimpleGUI as sg
from sys import platform
import backend
icon = base64.b64encode(open("framework.png", "rb").read())
sg.set_options(font=("Courier New", 12))
backend = backend.Backend()
def LedControl(name):
return [
sg.Input(key="Input " + name, visible=False, enable_events=True,... |
"""
Find the kth largest element in an unsorted array.
Note that it is the kth largest element in the sorted order,
not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's len... |
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
sns.set(style="ticks")
df = pd.read_csv('cardio_train_cleaned.csv', sep=';', nrows=1000)
print(df.describe())
df.plot.scatter(x="ap_hi", y="cardio")
heat_map = sns.heatmap... |
from __future__ import print_function, absolute_import, division
from collections import Counter
import cobrame
from cobrame.util import massbalance
def get_remaining_complex_elements(model, complex, modification_formulas):
tmp_met = cobrame.Metabolite('tmp_met')
mets = model.metabolites
components = c... |
from django.test import TestCase
from rest_framework.test import APIClient
from django.urls import reverse
from faker import Factory
from .models import Produto, Favorito
from clientes.models import Cliente
from usuarios.tests import getApiCliente, criaUsuarios
def criaFavorito() -> object:
"""
param: Non... |
__all__ = (
"AsyncResource",
"IPAddressType",
"IPSockAddrType",
"SocketAttribute",
"SocketStream",
"SocketListener",
"UDPSocket",
"UNIXSocketStream",
"UDPPacketType",
"ConnectedUDPSocket",
"UnreliableObjectReceiveStream",
"UnreliableObjectSendStream",
"UnreliableObjec... |
import time
from ppserver import celery, app
import requests
from random import randint
# from celery import Celery
@celery.task(bind=True)
def long_task(self):
"""My long task."""
c = 0
while c != 100:
c += 1
i = randint(0, 10)
time.sleep(1)
self.update_state(state='PROGRE... |
import numpy as np
from model import create_custom_model
# models
# model = ENGINE + MODEL DEFINITION
# engine is not cofigurable yet
# you can specify your model definition
# MODEL DEFINITION
# 1. states, transtion types, parameters
model_definition = {
# define your model states and transition types
#
... |
from typing import List, Union
import cv2
from pathlib import Path, PosixPath
def make_video(
save_dir: str, img_names: List[Union[str, PosixPath]], width=512, height=512
):
fourcc = cv2.VideoWriter_fourcc("m", "p", "4", "v")
save_name = Path(save_dir).joinpath("result_video.mp4")
video = cv2.VideoWri... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Remove tf error warnings
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras import layers
from tensorflow import keras
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_... |
import requests
from requests import cookies
import logging
import json
from urllib3 import disable_warnings
from urllib3 import exceptions
from singleton_decorator import singleton
from typing import List, Dict
from collections import namedtuple
LOG = logging.getLogger('apic_exporter.exporter')
TIMEOUT = 10
COOKIE_... |
import os
def nyu2_paired_path(nyu2_path):
'''
transform images to list
in the list, the entries are pairs of pathes of images
e.g. (path_train1, path_label1)
'''
paired_path = []
pair = []
jpg_paths, png_paths = [], []
for curDir, dirs, files in os.walk(nyu2_path):
for file... |
"""
servers
"""
import functools
from collections import namedtuple
import pandas as pd
@functools.lru_cache(maxsize=None)
def servers_list():
"""
Download a new server list from awesome-erddap.
If loading the latest one fails it falls back to the default one shipped with the package.
"""
fro... |
import os
import time
for connections in [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75]:
print("=" * 80)
print(f"Iniciando o teste com a quantidade {connections} de conexões")
os.system(
f"python main.py logs/1000-urls-para-testes.log https://new.scielo.br --connections {connections} --d... |
import moviepy.editor as mpy
import moviepy.video.fx.all as vfx
import moviepy.audio.fx.all as afx
import gizeh_title as gt
import os
# get the information to render the final video
videofolder = "/home/joaopedro/Videos/GGTP/Creating Videos/Current_Videos/"
defaultVideos = "/home/joaopedro/Videos/GGTP/Creating Videos/... |
import numpy as np
from nasbench301.surrogate_models.encodings.encodings_nlp import encode_nlp
def encode(arch_strings, data, search_space, nlp_max_nodes, nb101_api):
if search_space == 'nlp':
X = []
epoch = 3
for arch_str in arch_strings:
lc_acc = np.array([100 - loss for los... |
import random
import os
from Crypto.Util.number import getPrime
from const import description, flag, logo
def log(message):
character_color = "\x1b[34m"
reset = "\x1b[0m"
print(f"{character_color}[+] {message}{reset}")
def rsa_0():
while True:
p, q = random.getrandbits(512), random.getrand... |
"""
This function takes in file path of clinical notes and outputs HPO terms that are successfully
mapped to the clinical note text. Unlike the common state-of-the-art, this NLP is not relying on the
Unified Medical Language System (UMLS) and therefore does not require a third-party license. Might still
subject to ... |
"""
实在是莫得法了,用用api
create by judy 2019/09/10
"""
|
import torch
from model import UnStructuredModel
import pandas as pd
from os import listdir, mkdir
from os.path import isfile, join, isdir
files_path = "./data_10K_3K/"
#files_path = "./"
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
files = ["yoy1.csv", "yoy2.csv", "yoy3.csv", "yoy4.csv", "yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.