content stringlengths 5 1.05M |
|---|
from pyspark.sql import SparkSession
from pyspark.sql.types import Row
# Create the spark session
spark = SparkSession.builder.master("local")\
.appName("count-words-python")\
.getOrCreate()
ip_database = {}
with open("/Users/shad/ip.db") as f:
table = f.read().split("\n")
for row in table:
... |
import os
import json
import jsonpickle
from jsonschema import validate
from http.server import BaseHTTPRequestHandler
from urllib import parse
from plexapi.library import LibrarySection, ShowSection
from plexapi.myplex import MyPlexAccount
from plexapi.server import PlexServer
from plexapi.video import Episode, Show
f... |
def primo(x):
fator = 2
while x%fator !=0 and fator<=x/2:
fator=fator+1
if x%fator==0:
return False
else:
return True
n= int(input("Digite um número prímo: "))
if primo(n):
print("primo")
else:
print("não primo") |
from collections import deque
from utils.args import args
class Dinic:
def __init__(self, ps, es, n):
self.n = n
self.points = ps
self.edges, self.cnt = [], 0
self.head = [-1] * self.n
self.deep = [0] * self.n
self.now = [0] * self.n
self.vis = [False] * self... |
# 2017 JA
import numpy as np
from scipy.linalg import pinv, sqrtm
from .L96_model import lorenz96
def kfs_lor96(x0_t,t,tobs,y,H,R,rho,M,met,lam,loctype):
"""Data assimilation for Lorenz 1996 using Ensemble Kalman Filters.
Inputs: - x0_t, the real initial position
- t, time array of the model (should be ev... |
"""take meta argument and run the injection infrastructure"""
import os, re, time, sys
from subprocess import Popen, PIPE, TimeoutExpired
sys.path.append("..")
from ctest_const import *
from program_input import p_input
from inject import inject_config, clean_conf_file
from parse_output import parse_surefire
import ... |
import yaml
import sys
import urllib.request #for generating words
import random
import unittest
sys.path.append("../")
import praw
class submissionUnitTest(unittest.TestCase):
def login(self):
login_doc='../../credentials.yaml'
with open(login_doc,'r') as stream:
credentials... |
import unittest
import pytest
from proto_lib_fixture import proto_lib
EmptyMessageWithNoFields = None
@pytest.mark.usefixtures('proto_lib')
class EmptyMessageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
global EmptyMessageWithNoFields
from test_message_field_types_proto import... |
"""
Copyright (C) 2007 Google 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 writing, softwa... |
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import load_model, Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping, CSVLogger
from .keras_yolo import preprocess_true_boxes, yolo_body, yolo_eval, yolo... |
"""
LICENSED MATERIALS – PROPERTY OF IBM
Copyright IBM Corp. 2016, 2016
ALL RIGHTS RESERVED
@author: Giorgio Signorello, IBM Research - Zurich
"""
import scipy.io as sio
import numpy as np
#Define the some configuration strings for HP and switching matrix
parameter_analyzer_configuration = 'insert here the configura... |
"""
Tests app.internals.accounting_manager module
:author: Angelo Cutaia
:copyright: Copyright 2021, LINKS Foundation
:version: 1.0.0
..
Copyright 2021 LINKS Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo... |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... |
import sys, os
inputtable = sys.argv[1]
inputzs = sys.argv[2]
outputtable = sys.argv[3]
outrename2 = '/tmp/zs4'
asconf = '/tmp/ascout.conf'
asc = open(asconf,'w')
keys = ['photID','photoz','less045','greater045']
for name in keys:
asc.write('#\nCOL_NAME = ' + name + '\nCOL_TTYPE= FLOAT\nCOL_HTYPE= FLOAT\nCOL_COMM=... |
from __future__ import print_function
# Import the necessary Python modules
import sys
import math
import numpy as np
import time
# rospy - ROS Python API
import rospy
# baxter_interface - Baxter Python API
import baxter_interface
#Message carrying location of target
from geometry_msgs.msg import Point
from std_msg... |
import typing
from typing import Union, Any, Optional
import numpy as np
import wx
from controls import ParamsInstance
from .image import ImageDisplayer, MatrixDisplayer, ArrayDisplayer
if typing.TYPE_CHECKING:
pass
class BaseParameter:
pass
class OutputData:
ARRAYDISPLAYERS = [
ImageDisplaye... |
maior = -99999999999999999999999
menor = 99999999999999999999999
lista = []
for i in range(5):
numero = int(input('Digite um numero: '))
lista.append(numero)
if maior < numero:
maior = numero
if menor > numero:
menor = numero
print(f'o menor numero digitado foi {menor} e ele é o {lista.i... |
from .database import get_database
db = get_database() |
import cupy
def polyvander(x, deg):
"""Computes the Vandermonde matrix of given degree.
Args:
x (cupy.ndarray): array of points
deg (int): degree of the resulting matrix.
Returns:
cupy.ndarray: The Vandermonde matrix
.. seealso:: :func:`numpy.polynomial.polynomial.polyvander... |
import json
import settings
import logging
import traceback
import requests
from wfs_client import WFSClient
"""This is modelled after https://docs.easydb.de/en/technical/plugins/
section "Example (Server Callback)
"""
SERVICER_URL = "http://servicer:5000"
class ServicerClient:
def __init__(self, url):
if... |
import re
from datetime import datetime, timedelta, date
import calendar
def get_sunday(offset_mins):
now = datetime.utcnow() - timedelta(minutes=offset_mins)
sunday = datetime(*now.timetuple()[0:3])
while sunday.weekday() != calendar.SUNDAY:
sunday -= timedelta(days=1)
return sunday
def get_this_week... |
import logging
from typing import Any, Generator
from urllib.parse import urlencode
import scrapy
from burplist.items import ProductLoader
from burplist.utils.const import SKIPPED_ITEMS
from burplist.utils.parsers import parse_brand
logger = logging.getLogger(__name__)
class AlcoholDeliverySpider(scrapy.Spider):
... |
import torch
from torch import Tensor
from torch.nn import functional as F
from semseg.models.base import BaseModel
from semseg.models.heads import LawinHead
class Lawin(BaseModel):
"""
Notes::::: This implementation has larger params and FLOPs than the results reported in the paper.
Will update the code ... |
from anytree import Node, PreOrderIter
from nltk import word_tokenize
from treelib import Node
def is_empty(params):
flag = False
if params:
flag = True
return flag
def build_ast(parent, task):
root = Node(parent)
for key in list(task.keys()):
node_key = Node(key, parent=root)
... |
import os
import socket
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid_beaker import session_factory_from_settings
from social_pyramid.models import init_social
from sqlalchemy import create_en... |
# coding=utf-8
"""Prepare data.
"""
import os
for i in range(1, 1769):
output_dir = 'test_set/{:04}'.format(i)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
file_path = 'test_set/{}.jpg'.format(i)
if not os.path.exists(file_path):
print(file_path)
continue... |
# coding: utf-8
# Copyright (C) zhongjie luo <l.zhjie@qq.com>
from imports import *
from confluent_kafka import Consumer, TopicPartition
from client_kafka import kafka_options
class KafkaConsumer(DbConnection):
def __init__(self, options):
super(KafkaConsumer, self).__init__(options)
sel... |
#task 1: The Greeting Program
name = "Maximilian"
from datetime import date
import calendar
curr_date = date.today()
print("Good day", name, ". Today,", calendar.day_name[curr_date.weekday()], "is a perfect day to learn some Python")
#task 2: Manipulate Strings
first_name = 'Maximilian'
last_name = 'Riesterer'
print... |
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
from .Generaldistribution import General
|
import os
from pathlib import Path
from typing import Dict, List
import torch
from torch import Tensor
from torch.utils.data import TensorDataset, DataLoader
from torch.optim import SGD
from torch.nn.functional import mse_loss
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import Callback
impor... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class LinearRegression:
def __init__(self):
"""
Linear regression
Arguments - alpha (by default .001)
epochs(by default 100)
plot : bool - plot the cost vs epoch graph
fu... |
import json
import os
import datetime
from menu import Requests
from menu import Utility as Util
from datetime import timedelta
import logging
def foods_to_json(food_array, day):
foods = []
for food_name in food_array:
food = {
"name": food_name,
"rating": 0,
"amou... |
from enum import Enum
class AnnulmentVerificationStatus(Enum):
"""Verification status of technial annulment requests"""
NOT_VERIFIABLE = 'NOT_VERIFIABLE'
"""The technical annulment is not verifiable due to client error"""
VERIFICATION_PENDING = 'VERIFICATION_PENDING'
"""The technical annulment is ... |
"""The lightly.models package provides model implementations.
*Note that the high-level building blocks will be deprecated with
lightly version 1.2.0. Instead, use low-level building blocks to build the
models yourself.
Have a look at the benchmark code to see a reference implementation:*
`lightly benchmarks <https:... |
"""Find the Error in Mtomo for many mocks and save the data on an hdf5 file"""
import os
import h5py
from lytomo_watershed import mpi4py_helper
import numpy as np
from scipy.ndimage import gaussian_filter
import importlib
import argparse
def get_id_max_overlap(lmap_mock, lmap_true):
"""Slightly improved compared to... |
from io import StringIO
from opensfm import tracking
from opensfm.test import data_generation
def test_tracks_io():
d = data_generation.CubeDataset(2, 100, 0.0, 0.3)
output = StringIO()
tracks_before = d.tracks
tracking.save_tracks_graph(output, tracks_before)
output.seek(0)
tracks_after = ... |
# -*- coding: utf-8 -*-
"""
Debugging system for Triangulation class. Displays stepwise visual
representation of the algorithm.
This system currently requires pyqtgraph for its visual output.
"""
from __future__ import division
import numpy as np
import time
from ..util.geometry.triangulation import Triangulation
... |
from sqlalchemy.sql import func
from flask_login import UserMixin
from app import db, login_manager
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Database models
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255)... |
import logging, codecs, time
from telegramBot import TelegramBot
from oldMessageDeleter import OldMessageDeleter
MESSAGE_RETAINTION_DURATION = 7*24*60*60 #Retain a week of data
POLL_INTERVAL = 5*60
if __name__ == "__main__":
with open('data/token', 'r') as f:
telegramBot = TelegramBot(codecs.encode(f.read().replac... |
#!/usr/bin/python2.4
# Copyright 2008, Google 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... |
import xml.etree.ElementTree as ET
from os import getcwd
sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
wd = getcwd()
classes = ["no_mask","face","face_mask","nomask","face_nask"]
def convert_annotation(year, image_id, list_file):
in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id),... |
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
from model.utils.config import cfg
from model.roi_layers import nms
from model.rpn.bbox_transform import bbox_transform_inv
from model.rpn.bbox_transform import clip_boxes
import pdb
from detection_metric.utils import *
from detection_metric.... |
class Solution:
def totalNQueens(self, n: int) -> int:
'''Time O(n!) Space O(n)'''
def is_not_under_attack(row, col, cols, hills, dales):
return not (cols[col] or hills[row + col] or dales[row - col])
def place_queen(row, col, cols, hills, dales):
cols[col] =... |
#!/usr/bin/env python
import sys
import dotenv
import os
def valid_env():
env_list = []
env_example_list = []
f = open('.env', 'r')
for i in f.readlines():
env_list.append(i.rstrip().split('=')[0])
f = open('.env_example', 'r')
for i in f.readlines():
value = i.rstrip()
... |
# Copyright 2013-2014 DataStax, 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 writi... |
import json
from django.core.exceptions import ValidationError
from backend.api.models import Proyecto, RolProyecto, Usuario, Miembro
from django import forms
class CreateMiembroForm(forms.Form):
"""
CreateMiembroForm Valida los datos del request.data al crear un miembro
Args:
forms (Form): Form ... |
import numpy as np
def gaussian(x,mu,sigma):
temp = -np.square(x-mu)/(2*sigma)
return np.exp(temp)/(np.sqrt(2.0*np.pi*sigma)) # sigma = sigma^2
def e_step(data, phais, mus, sigmas):
Qs = []
for i in xrange(len(data)):
q = [phai*gaussian(data[i],mu,sigma) for phai,mu,sigma in zip(phais,mus,sigmas... |
# -*- coding: utf-8 -*-
import subprocess
import unittest
from pathlib2 import Path
from mock import Mock
from termius.core.storage import ApplicationStorage
from termius.core.models.terminal import (
Host, Group, PFRule, Identity
)
# inspired from
# https://github.com/lacostej/unity3d-bash-completion
class Compl... |
import builtins
import datetime
from files_sdk.api import Api
from files_sdk.list_obj import ListObj
from files_sdk.exceptions import InvalidParameterError, MissingParameterError, NotImplementedError
class UsageSnapshot:
default_attributes = {
'id': None, # int64 - Site usage ID
'start_at': Non... |
from mp1 import merge
test1 = [2,0,2,4]
test2 = [0,0,2,2]
test3 = [2,2,0,0]
test4 = [2, 2, 2, 2, 2]
test5 = [8, 16, 16, 8]
output1 = [4,4,0,0]
output2 = [4,0,0,0]
output4 = [4, 4, 2, 0, 0]
output5 = [8, 32, 8, 0]
def comp(list1, list2):
for val in list1:
if val not in list2:
return False
... |
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX
# All rights reserved.
from force_bdss.api import (
BaseMCOFactory,
BaseMCOCommunicator,
FixedMCOParameterFactory,
RangedMCOParameterFactory,
RangedVectorMCOParameterFactory,
ListedMCOParameterFactory,
CategoricalMCOParameterFactory,
)... |
#!/usr/bin/env python
# shell14 0.0.1
# Generated by dx-app-wizard.
#
# Basic execution pattern: Your app will run on a single machine from
# beginning to end.
#
# See https://wiki.dnanexus.com/Developer-Portal for documentation and
# tutorials on how to modify this file.
#
# DNAnexus Python Bindings (dxpy) documentati... |
# _*_coding:utf-8_*_
# Author :ories
# File_Name :fishing.py
# Create_Date :2020-02-26 19:31
# Description :wow fishing script
# IDE :PyCharm
import math
import time
import autopy as at
from pykeyboard import PyKeyboard
import pyscreenshot as ImageGrab
import cv2
import numpy as np
from collections impo... |
import uiautomator2
from random import uniform
from dgfbot.utils import COLOR_REPORT, COLOR_ENDC, COLOR_FAIL
from time import sleep
from enum import Enum, unique
from typing import Optional
UI_TIMEOUT_LONG = 5
UI_TIMEOUT_SHORT = 1
class DeviceFacade:
def __init__(self, device, ) -> None:
sel... |
"""
Receive text data from a data server 127.0.0.1:[port number], listening on a TCP socket.Takes in the same port number
as command line argument passed to server2.py script. Run server2.py before executing this script.
Splits each line of text on comma(,).Perform grouping and aggregation on the data and displays the... |
# Generated by Django 2.0.2 on 2018-03-09 19:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('voter', '0008_auto_20180309_1832'),
]
operations = [
migrations.AlterField(
model_name='changet... |
import numpy as np
import networkx as nx
from mesa import Model
from mesa.time import RandomActivation, SimultaneousActivation
from mesa.datacollection import DataCollector
from scseirx.model_SEIRX import *
## data collection functions ##
def count_S_student(model):
S = np.asarray([1 for a in model.schedule.age... |
import mysql.connector
from mysql.connector import errorcode
from discord import Embed, Colour, Guild, TextChannel
from discord.ext import commands, tasks
from discord.utils import get
import re
import json
import random
import time
# Loading config file...
with open("./config.json", "r", encoding="utf-8") as config:... |
import os.path as osp
import multiworld.envs.mujoco as mwmj
import torch.nn.functional as F
import railrl.misc.hyperparameter as hyp
from railrl.launchers.launcher_util import run_experiment
from railrl.launchers.experiments.disentanglement.state_launcher import \
disentangled_her_twin_sac_experiment_v2
from multiw... |
'''Tests for cli implementation.'''
import os
import pytest
import test_util
from goto import cli
from goto import storage
@test_util.custom_home
def test_add():
'''Tests that add works with normal input.'''
here = os.path.abspath('./')
dirname = os.path.basename(here)
cli.handle_add('./')
asse... |
#!/usr/bin/env python
"""
Do nothing, but document it.
Lists of all OpenStack projects are available here:
http://git.openstack.org/cgit/openstack/governance/plain/reference/projects.yaml
"""
import yaml
import requests
import os
"""
DOWNLOAD THE yaml file containing all projects from Governance repo... |
from typing import List
def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> List[int]:
i, j, k = m - 1, n - 1, m + n - 1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[k] = nums1[i]
i -= 1
else:
nums1[k] = nums2[j]
j -= 1
... |
# filter warnings
import warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
# keras imports
from keras.layers.core import Dense, Activation, Dropout
from keras.applications.densenet import DenseNet121, preprocess_input
from keras.preprocessing import image
from keras.models import Model
from keras.... |
import numpy as np
def config_tuning_space(tuning_space_raw):
from hyperopt import hp
from hyperopt.pyll.base import scope
if tuning_space_raw is None:
return None
hyper_obj = {}
if "learning_rate" in tuning_space_raw:
hyper_obj = {**hyper_obj, **{
"learning_rate": hp.... |
"""Test handler classes."""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import factory
reload(factory)
from factory import *
def backport_factory(name=None, setVersion=False, repo='expanse-qt', distribution='trusty', architecture='amd64', packages=[]):
factory = BuildFactory()
for package in packages:
cmd = ["backportpackage... |
import constants
import os
import copy
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def conver_height(Players):
for player in Players:
l_height = player['height'].split()
player['height'] = int(l_height[0])
return Players
def conver_experience(Players):
for player in Players... |
import unittest
import numpy as np
from lyssa.dict_learning.utils import get_class_atoms, init_dictionary
class UtilsTest(unittest.TestCase):
def test_get_class_atoms(self):
n_class_atoms = [2, 3, 5]
cl = 1
self.assertEqual(get_class_atoms(cl, n_class_atoms=n_class_atoms), [2, 3, 4])
... |
# -*- coding: utf-8 -*-
# ------------- Diccionario -------------
#Solo se ermite una llave nula
#Los valores son mutables pero las llaves NO
#No se encuentran ordenados por ser hashmap
elementos = {'Abarrotes': {
'Pan':{},
'Leche':{}
}
... |
from google.oauth2 import id_token
from google.auth.transport import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.goo... |
#!/usr/bin/python3
""" Test .get() and .count() methods
"""
from models import storage
print("All objects: {}".format(storage.count()))
print("State objects: {}".format(storage.count("State")))
first_state_id = list(storage.all("State").values())[0].id
print("First state: {}".format(storage.get("State", first_state_i... |
from .dataset import MegaDepthDataset
from .transform import ISSTransform , ISSTestTransform
from .sampler import DistributedARBatchSampler
from .misc import iss_collate_fn
from .hpatches import HPacthes, HP_INPUTS |
# See FinTS_3.0_Formals_2011-06-14_final_version.pdf
from collections import OrderedDict
from fints3.segments import FinTS3Segment
# See B.5.2
class FinTS3Header(FinTS3Segment):
def __init__(self, version=300):
self.elements = OrderedDict([
('head', OrderedDict([
('identifier', 'HNHBK'),
('counter', 0),
... |
from os import path, getcwd
from openpyxl.utils import get_column_letter
from openpyxl.styles import NamedStyle, Font, Border, Side, Alignment, Fill, PatternFill
def generate_stub(company_name: str, employees: str, deductions: list, period: str, prepared_by: str, ws):
col_per_stub= 10
row_per_stub= 22
# F... |
from __future__ import unicode_literals, print_function, division
import os
from io import open
import torch
from autocomplete.lib.constants import ENCODING
def create_directory_if_not_exists(path):
os.makedirs(path, exist_ok=True)
def read_lines(filename, encoding=ENCODING):
lines = []
with open(filenam... |
import unittest
import unicodedata
from robot.utils import unic, is_jython
from robot.utils.asserts import assert_equals, assert_true
if is_jython:
from java.lang import String
import JavaObject
import UnicodeJavaLibrary
if is_jython:
class TestJavaUnic(unittest.TestCase):
def test_with_java_... |
#!/usr/bin/python
from __future__ import print_function
import os, sys
import platform
import fnmatch
try:
from itertools import izip
except ImportError:
izip = zip
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'helpers')))
from csHelpers import *
CSUPPORT = True
if CSUPPORT... |
from . import auth
from app import get_logger, httpauth, db
from app.models import Auth
from flask import g, request, jsonify
logger = get_logger(__name__)
@httpauth.verify_password
def verify_password(username, password):
# try to authenticate with username/password
auth = Auth.query.filter_by(username=user... |
#!/usr/bin/env python3
import os
import json
import pytest
from elasticsearch import Elasticsearch
# Suggest matplotlib backend that does not need DISPLAY or
# python running as a framework on OS X.
os.environ.setdefault('MPLBACKEND', 'agg')
@pytest.fixture(scope='module')
def es(hosts=None):
e = Elasticsearch... |
"""A module for solving all kinds of equations.
In [3]: solve(x**5+5*x**4+10*x**3+10*x**2+5*x+1,x)
Out[3]: [-1]
"""
from solvers import solve, solve_linear_system, solve_linear_system_LU, \
dsolve, solve_undetermined_coeffs, tsolve, deriv_degree, msolve
from recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve... |
from wtforms.validators import ValidationError
from .models import User
|
import numpy as np
import Mapa as mp
import Ventana as v
# 0 para mapa aleatorio y 1 para mapa de archivo
tipo = 1
ventana = v.Ventana(tipo)
|
from frozendict import frozendict
import re
_VM_KWARGS = (
('ostype', 1),
('ostype_text', 'test'),
('dc_name', 'test'),
('disk_image', 'test'),
('disk_image_abbr', 'test'),
)
VM_KWARGS = frozendict(_VM_KWARGS)
VM_KWARGS_KEYS = tuple(VM_KWARGS.keys())
VM_KWARGS_NIC = frozendict(_VM_KWARGS + (('net... |
""" Model classes for ingesting volumes. """
import os
import uuid
import logging
from io import BytesIO
from mimetypes import guess_type
import httpretty
from stream_unzip import stream_unzip, TruncatedDataError
from boto3 import client
from tablib import Dataset
from django.db import models
from django.conf import se... |
# Third party modules
import numpy as np
import pandas as pd
from scipy.interpolate import CubicSpline # for warping
from transforms3d.axangles import axangle2mat # for rotation
# augmentation of data
def Jitter(X, sigma=0.5):
myNoise = np.random.normal(loc=0, scale=sigma, size=X.shape)
return X + myNoise
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
from payload import payload
def makeSession(payload):
login_url = 'https://aprender.ead.unb.br/login/index.php'
session_requests = requests.session()
result = session_requests.post(
login_url,
data = payload
) ... |
"""
NOTE: this is dead code! do not use!
This file is only present to ensure backwards compatibility
in case someone is importing from here
This is only meant for 3rd party code expecting ovos-core
to be a drop in replacement for mycroft-core
"""
from ovos_plugin_manager.utils.tts_cache import hash_sentence, hash_from_... |
from argparse import ArgumentParser
from painter.painter import invoke
def main():
parser = ArgumentParser(description="Hill Painter")
parser.add_argument(
"--image-path", type=str, default=None, help="Path to the source image")
parser.add_argument(
"--iterations", "-i", type=int, default... |
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
radioitems = dbc.FormGroup(
[
dbc.Label("Choose one"),
dbc.RadioItems(
options=[
{"label": "Option 1", "value": 1},
{"label": "Option 2... |
import sys
a, b, c, d, e, f = map(int, sys.stdin.readline().split())
def main():
w = set()
s = set()
for i in range(0, f + 1, 100 * a):
for j in range(0, f - i + 1, 100 * b):
w.add(i + j)
for i in range(0, f + 1, c):
for j in range(0, f - i + 1, d):
... |
import pandas as pd
def row_i_to_row_j(row_i, row_j):
"""docstring goes here"""
return row_i.corr(row_j)
def row_i_to_all_rows(df, index_i, row_i, metric):
"""docstring goes here"""
for index_j, row_j in df.iterrows():
# use special features of the matrix
if index_j < index_i:
... |
import csv
import pandas as pd
import json
data_source = 'https://raw.githubusercontent.com/washingtonpost/data-police-shootings/master/fatal-police-shootings-data.csv'
report = pd.read_csv(data_source, na_filter='')
fatality = [list(row) for row in report.values]
fatalityDict = {}
for rows in report.values:
key... |
#!/usr/bin/env python3
import os
import sys
import bz2
import numpy as np
import pyopencl as cl # install with `PYOPENCL_CL_PRETEND_VERSION=2.0 pip install pyopencl`
from selfdrive.hardware import PC, TICI
from common.basedir import BASEDIR
from selfdrive.test.openpilotci import BASE_URL, get_url
from selfdrive.vers... |
import dash.dependencies as dep
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from app import app
from components.cards import card
from components.headings import header, subheader
from data_loader import get_country... |
from django.contrib.admin import ModelAdmin
from lazychoices.admin import LazyChoicesFieldListFilter
class BookAdmin(ModelAdmin):
list_filter = [
('category', LazyChoicesFieldListFilter),
('genre', LazyChoicesFieldListFilter),
]
ordering = ['-id']
|
import sys
import unittest
from numba import njit
@njit
def f0(a, b):
return a + b
@njit
def f1(begin1, end1, begin2, end2):
if begin1 > begin2: return f1(begin2, end2, begin1, end1)
return end1 + 1 >= begin2
@njit
def f0_2(a, b):
return a + b
@njit
def f1_2(begin1, end1, begin2, end2):
if ... |
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res, prev = nums[0], nums[0]
for n in nums:
if n < prev:
return n
prev = n
return res
def test_find_min():
s = Solution()
... |
'''
Created on May 6, 2021
@author: Curious Nekomimi
'''
import json
import requests
import os
import uuid
import getpass
from time import strftime
from json_to_html import to_html
aidcat_version = '0.6.4'
class User():
def __init__(self, user=''):
self.user = user
self.access_token = None
... |
import string
import torch
import pandas as pd
from tqdm import tqdm
from transformers.models.t5 import T5ForConditionalGeneration, T5Tokenizer
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = T5ForConditionalGeneration.from_pretrained("NTUYG/SOTitle-Gen-T5")
tokenizer = T5Tokenizer.from_p... |
# coding=utf-8
import json
from math import floor
from pathlib import Path
with (Path(__file__).resolve().parent / "data" / "ideologies.json").open("rt") as ideologiesFile:
IDEOLOGIES = json.load(ideologiesFile)
class Coordinates:
def __init__(self, economic: float, social: float) -> None:
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.