content stringlengths 5 1.05M |
|---|
###############################################################################
# Copyright 2018 The AnPyLar Team. All Rights Reserved.
# Use of this source code is governed by an MIT-style license that
# can be found in the LICENSE file at http://anpylar.com/mit-license
################################################... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 Hervé BREDIN
# 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 lim... |
from panda3d.bullet import BulletWorld
from panda3d.core import BitMask32
from panda3d.core import ClockObject
from panda3d.core import CollisionHandlerEvent
from panda3d.core import CollisionTraverser
from panda3d.core import Vec3
from panda3d.physics import PhysicsCollisionHandler
from pandac.PandaModules import loa... |
#!/bin/python
import sys
def print30(*args, **kargs):
sep = kargs.get('sep', ' ')
end = kargs.get('end','\n')
file = kargs.get('file',sys.stdout)
output = ''
first = True
for arg in args:
output += ('' if first else sep) + str(arg)
first = False
file.write(output + end)
|
"""by the given image of the billiard balls need to count them and approximately find their radius. Then compute the variance for the found radiuses."""
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def count_balls(img, method="erode"):
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (7,7... |
import pytest
from django.core.exceptions import ValidationError
from test_plus import TestCase
from maceoutliner.users.validators import validate_usernames_icase
class UserNameValidatorTest(TestCase):
"""
Tests for custom username validators.
"""
def setUp(self):
self.user1 = self.make_user(... |
import os.path
import gi
gi.require_versions({
'Gtk': '3.0',
# 'Pywebkit': '0.1'
})
from gi.repository import Gtk, Gdk, GObject, GLib#, Pywebkit
#from gi.repository.Pywebkit import Webview
from pymtk.WebView import WebView2
from pymtk.future import synced
from pymtk.ui import UI,DirectoryTree,radio_group
fr... |
class BulletParams:
def __init__(self, speed, size, damage):
self.speed = speed
self.size = size
self.damage = damage
@staticmethod
def read_from(stream):
speed = stream.read_double()
size = stream.read_double()
damage = stream.read_int()
return Bullet... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by charlie on 18-4-17
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import os
import random
import pickle
from data_provider.THUMOS14 import THUMOS14
from sklearn.svm import SVR
fr... |
# coding: utf-8
from typing import List, Optional
import pydantic
from pydantic import BaseModel
class Tipe(BaseModel):
name: str
returns: str
origin: Optional[str]
origtype: Optional[str]
desc: List[str]
raises_get: Optional[str]
raises_set: Optional[str]
@pydantic.validator('name', '... |
name = "raspberrypi-uart-logger"
|
from decouple import config
SITE_ID = config('SITE_ID_PRODUCTION')
EMAIL_HOST= "smtp.gmail.com"
EMAIL_HOST_USER= config('EMAIL')
EMAIL_HOST_PASSWORD= config('PASSWORD')
EMAIL_PORT= 587
EMAIL_USE_TLS= True
DEFAULT_FROM_EMAIL= config('EMAIL')
EMAIL_BACKEND = "anymail.backends.mailjet.EmailBackend"
ANYMAIL = {
"MAILJ... |
from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import count
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: mnmcount <file>", file=sys.stderr)
sys.exit(-1)
spark = (SparkSession
.builder
.appNam... |
# Copyright 2014 OpenStack Foundation
# 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 requ... |
# -*-coding:utf8-*-
import requests
import json
import time
import MySQLdb
from multiprocessing.dummy import Pool as ThreadPool
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
urls = []
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.13... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Tools.Logger import logger
from Tools.Config import ROOT_DIR, CONFIG
import json
class ReverseIndex:
def __init__(self):
self.index = {}
self.count_documents_in_word = {}
self.words = []
self.total = None
def create(self, X, ... |
import ast
import operator
from ast import Constant, Num, Str, Bytes, Ellipsis, NameConstant, copy_location
from typing import Iterable, Optional
from compiler.peephole import safe_multiply, safe_power, safe_mod, safe_lshift
from compiler.visitor import ASTRewriter
def is_const(node):
return isinstance(node, (Con... |
import logging
import yagmail
from dredge_logger import generateImages
from dredge_logger.config import config
_logger = logging.getLogger(__name__)
def backup_files(filename, extra_csv=False):
"""This function when called will use the filename of the file to send the files to a list of emails"""
_logger.d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from decimal import Decimal
import model_utils.fields
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depend... |
"""This problem was asked by Facebook.
Given a list of integers L, find the maximum length of a sequence of consecutive
numbers that can be formed using elements from L.
For example, given L = [5, 2, 99, 3, 4, 1, 100], return 5 as we
can build a sequence [1, 2, 3, 4, 5] which has length 5.
""" |
import util
def my_range(start, stop):
if start < stop:
return range(start+1, stop)
else:
return range(start-1, stop, -1)
class matrix():
def __init__(self, filename : str):
self.lines = util.load_str_lines_list(filename)
self.heigth = len(self.lines)
self.width = l... |
from __future__ import print_function
from typing import Sequence, Any, IO
from serversim import *
def print_results(num_users=None, weight1=None, weight2=None, server_range1=None,
server_range2=None, servers=None, grp=None, fi=None):
# type: (int, float, float, Sequence[int], Sequence[int], S... |
import requests
from bs4 import BeautifulSoup
# pull individual items of websites
URL="https://www.amazon.in/Grand-Theft-Auto-V-PC/dp/B00LSBDSYA/ref=sr_1_5?keywords=pc+games&qid=1562758220&s=gateway&sr=8-5"
# product to check
headers= {"User-Agent": " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTM... |
import os
import csv
from flask import flash
def batch_select(csvfile):
# def batch_select(csvfile, user_id, user_name, genome, technology):
"""Opens bed file to load into variants table."""
if os.path.exists(csvfile) and os.path.getsize(csvfile) > 0:
try:
with open(csvfile, 'r') as f:
... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
import os
import sys
sys.path.append(os.path.abspath(r"C:\Users\power\Desktop\Project\Dev\UserDict4Papago"))
import re
from pprint import pprint
import cProfile
import MeCab
from lib.util import *
from lib.convert_dict import ConvertDictionary
from lib.papagopy.papagopy import Papagopy
def main():
# 파파고에서 안 사라지는... |
def mostrar_semillas(imagenC, im_O, im_B):
imagenS = np.zeros(imagenC.shape)
imagenS[:,:,0] = np.maximum(imagenC[:,:,0], im_O*255)
imagenS[:,:,1] = imagenC[:,:,1]
imagenS[:,:,2] = np.maximum(imagenC[:,:,2], im_B*255)
plt.figure(figsize=(7,7))
plt.imshow(imagenS.astype(int))
plt.show()
|
from tkinter import *
from tkinter.ttk import *
class FrameView(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.init_ui()
def init_ui(self):
self.parent.title("Modifying rows")
self.pack(fill = BOTH, expand = True)... |
from unittest import TestCase
from fathomnet import models
from fathomnet.api import geoimages
class TestGeoImagesAPI(TestCase):
def test_find_all(self):
n_images = 5
pageable = models.Pageable(size=n_images)
results = geoimages.find_all(pageable)
self.assertIsNotNone(results)
... |
import os.path
import pickle
import typing as tp
from satella.coding import Monitor
from satella.coding.typing import Number
from smok.exceptions import NotReadedError, OperationFailedError
from smok.pathpoint import PathpointValueType, ValueOrExcept
from .in_memory import InMemoryPathpointDatabase
class PicklingPa... |
import os
import requests
from pymongo import MongoClient
from coin.models import Coin
from multiprocessing import Pool
from coinds.cassandra.coins import Coin as CassandraCoin
BINAN_API_KEY=os.environ.get("BINAN_API_KEY")
BINAN_SECRET_KEY=os.environ.get("BINAN_SECRET_KEY")
BINAN_BASE_URL=os.environ.get("BINAN_BASE_UR... |
class WikiCache(object):
def __init__(self):
self.cache = {}
def __contains__(self, key):
return key in self.cache
def __getitem__(self, key):
return self.cache[key]
|
import asyncio
import statistics
import Battle_Utils
import Config
import math
import discord
import datetime
from discord.ext import commands
import Utils
import random
import time
def get_numbers(number_string):
final_string = ""
for character in number_string:
try:
int(character)
... |
"""Test your system from the command line."""
import getpass
import logging
import sys
from total_connect_client.client import TotalConnectClient
logging.basicConfig(filename="test.log", level=logging.DEBUG)
if len(sys.argv) != 3:
print("usage: username location1=usercode1,location2=usercode2 \n")
sys.exit... |
"""chapter 1 quiz 4 options table
Revision ID: cb9d3f9cc88c
Revises: ecd8e8e98a9b
Create Date: 2022-01-12 10:15:20.368945
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'cb9d3f9cc88c'
down_revision = 'ecd8e8e98a9b'
branch_labels = None
depends_on = None
def ... |
from Socket import Socket
from MiddlewareModule import MiddlewareModule
import threading
class AsyncServer(Socket):
def __init__(self,Port = 25565):
self.Clients = {}
self.Events = [[],[],[],[],[],[]]
self.Thread_Loop = None
super().port = Port
def Use(self,Module = Middlewar... |
from azureml.core import Workspace
from azureml.core.webservice import Webservice
# Requires the config to be downloaded first to the current working directory
ws = Workspace.from_config()
# Set with the deployment name
name = "bank-marketing-endpoint"
# Load existing web service
service = Webservice(name=name, work... |
__all__ = ["const", "eos", "geom", "potentials", "sitemix"]
|
import pytest
import os.path
import yaml
from xxx import Klass
from funcy import silent
from mock_api import mock_function, mock_method, track_function, track_method, same_url, aggregate_same_urls, schema_difference_coefficent, group_equal, parametrize_urls
urlmap = {
'/': 'Root: Str',
'/ciao/': """
Ro... |
import hashlib
import hmac
import bcrypt
# pycryptodome
from Crypto import Random
from Crypto.Cipher import AES
# If you want, you can change this to whatever you want - recommend generating one using -> salt = bcrypt.gensalt(30)
# BEWARE: if you change this, you will need your exact version of Inventus be... |
from pextant.mesh.triangularmesh import TriPolyMesh
from pextant.solvers.astarMesh import MeshSearchElement
ames_em = TriPolyMesh('../../data/maps/Ames/Ames.tif').loadSubSection()
start = MeshSearchElement(ames_em._getMeshElement(10))
#end = MeshSearchElement(ames_em._getMeshElement(10)) |
"""!/usr/bin/env python3"""
import sys
from PyQt5 import QtWidgets
from source.mainWindow import MazeGenApp
def main():
app = QtWidgets.QApplication(sys.argv)
app.setStyle("fusion")
window = MazeGenApp()
window.show()
app.exec_()
if __name__ == "__main__":
main()
|
import torch.nn as nn
import torch
import torch.nn.functional as F
import torchvision.models
import os
import utils.network_utils
from utils.pointnet2_utils import PointNetSetAbstraction,PointNetFeaturePropagation
from models.graphx import PointCloudGraphXDecoder
from losses.earth_mover_distance import EMD
# Set the ... |
import argparse
import datetime
import hashlib
import hmac
from datetime import datetime
from urllib.parse import quote_plus
import boto3
import urllib3
from botocore.exceptions import ClientError
def copy_logs_from_rds_to_s3(rds_instance_name, s3_bucket_name, region, log_prefix="", min_size=0):
"""
Download... |
import sys
sys.dont_write_bytecode = True # No '*.pyc' precompiled files
from rich import print
# print('=', )
from lib_local_various import showvar
from lib_main import combine_dicts
from rich.console import Console
from pyfiglet import figlet_format
from lib_main import negative_console
from lib_main import positi... |
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
"""
This module defines the behaviors of ``RooCurve``.
"""
from __future__ import absolute_import
import numpy
import uproot
import uproot.behaviors.TGraph
# '@fUniqueID', '@fBits', 'fName', 'fTitle', 'fLineColor', 'fLineStyle', 'f... |
from audiomate import annotations
import numpy as np
from evalmate import alignment
from evalmate import evaluator
import pytest
class TestKWSEvaluator:
def test_evaluate_with_two_label_lists(self, kws_ref_and_hyp_label_list):
ll_ref, ll_hyp = kws_ref_and_hyp_label_list
result = evaluator.KWSE... |
import matplotlib.pyplot as plt
import numpy as np
import scipy
import cvxpy as cp
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import pandas as pd
def preprocess():
data = pd.read_csv('weatherAUS.csv')
# Drop certain features any any data with null values
data =... |
# Generates random data in specified shape - Lucas kort (Jun. 23, 2021)
import numpy as np
import pandas as pd
import random as rand
import math
import tkinter as tk #hide tk window
from tkinter import filedialog #get a file dialog window
#Configuração dos dados de saída---------------------------------
record_size =... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Donfig Developers
# Copyright (c) 2014-2018, Anaconda, Inc. and contributors
#
# 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 Soft... |
import logging
import typing
import arrow
import pymongo
import pymongo.errors
from pymongo import MongoClient
class ReceiveDailyAbstract:
DATABASE_NAME = 'ChineseFuturesRaw'
COLLECTION_NAME = None
def __init__(self):
db = MongoClient()[self.DATABASE_NAME]
self.mongo_coll = db[self.COLLE... |
"""
Last Updated : 30/08/19
Purpose: Socket Programming Assignment for Network Fundamentals.
Authors: Jayden Lee, Vivian Huynh, Albert Ferguson
"""
# imports
import socket as sc
from datetime import datetime as dt
def HTTPServer(Port, *args, **kwargs):
"""
Take a given port to bind to an existing IP address. Defa... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-22 12:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20151225_1353'),
]
operations = [
migrations.AlterField(
... |
import moeda
preco = float(input('Informe o preço: R$ '))
print(f'O preço com acréscimo de 10% fica R$ {moeda.aumentar(preco, 10)}')
print(f'O preço com desconto de 10% fica R$ {moeda.diminuir(preco, 10)}')
print(f'O dobro do preço é R$ {moeda.dobro(preco)}')
print(f'A metade do preço é R$ {moeda.metade(preco)}')
|
"""
Copy specific lines of the original csv which contains all data, to
a new csv, which contains only selected classes.
"""
from yaml_util import read_list_yaml
import csv
import os.path
## exp_run_config
# input
original_csv_path = '../data/ucf101.csv'
classes_yaml_path = 'ucf_101_motion_classes.yaml'
key_name = 'cl... |
# encoding: utf-8
"""
Tests of io.base
"""
from __future__ import absolute_import, division
try:
import unittest2 as unittest
except ImportError:
import unittest
from ...core import objectlist
from ...io.baseio import BaseIO
import numpy
class TestIOObjects(unittest.TestCase):
def test__raise_error_... |
from pinto.security import RootACL
class Root(RootACL):
pass
def includeme(config):
config.add_route('category', '/{tag}', factory=Root)
|
# THIS IS THE MAIN CODE
def cal_multiple(a, b):
return int(a) * int(b)
def cal_addition(a, b):
return int(a) + int(b)
if __name__ == '__main__':
print(">>>>> " + str(cal_score(2, 4))) |
from flask import Flask
import os
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello " + os.environ.get("NAME", "you") + "\n"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 3000))
app.run(debug=True,host='0.0.0.0',port=port) |
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# 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 ap... |
import os
import time
import sys
import numpy as np
from glob import glob
import torch
import cv2
from torchvision import transforms
import matplotlib.pyplot as plt
from network_weight import UNet
from network import UNet as HUNet
import argparse
from draw_skeleton import create_colors, draw_skeleton
"""
Height an... |
import array
import async
import binascii
import collections
import hashlib
import os
import random
import shutil
import sqlite3
import struct
import subprocess
import sys
import types
import valtool
deque = collections.deque
_bin2hex = binascii.hexlify
_hex2bin = binascii.unhexlify
def _reiterable(xs):
if type(xs)... |
def copy(source, destination):
f1 = open(source)
f2 = open(destination, 'w')
f2.write(f1.read())
f1.close()
f2.close
|
import os.path
import re
import uuid
from django.conf import settings
from django.db.models import Q, Max
from django.urls import reverse
from django.utils import timezone
import jwt
def some(args):
return any(args) and not all(args)
def get_version_hash() -> str:
return str(uuid.uuid4()).replace("-", "")
... |
from .loader import read_sparse_matrix
from .util import load_gensim_word2vec
import torch
import numpy as np
import scipy.sparse as sparse
import os
from os.path import isfile, join
import pickle
from transformers import BertTokenizer
import time
class Dataset(object):
"""docstring for Dataset"""
def __init... |
# Licensed under a MIT licence - see file `license`
import numpy as np
import astropy.units as u
from .. import fitters
from .. import regions
from ..utils import bool_indarray
def test_image_at_once(example3_3):
psfarray, image = example3_3
class psf(fitters.BasePSFFitter):
regions = regions.image... |
import copy
from typing import List
from typing import Tuple
from data_labeling.labeling_utils import xy_on_interpolated_image_to_raw_xy, xy_on_raw_image_to_xy_on_interpolated_image
class FrameAnnotation:
def __init__(self):
self.accepted = False # whether frame was marked as annotated successfully
... |
"""
Same as monge_array.py but avoiding copying odd and even indices rows into 2 new arrays.
So, instead of passing a list, we will be passing the indices of the initial array in subsequent
recursions using a a range object. This gets rid of additional memory overhead
"""
from monge_array import find_min
def odd_fro... |
import torch.multiprocessing as mp
import pt_rpc_client
import pt_rpc_server
import grpc_client
import grpc_server
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--master_addr", type=str, default="127.0.0.1")
parser.add_argument("--master_port", type=str, default="295... |
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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 re... |
# -*- coding: UTF-8 -*-
from flask import Blueprint, request, jsonify, current_app
from main import db
from main.models.stock import Overview
from crawler.eastmoney.stock.data import get_code_hxtc
bp = Blueprint('stock_overview', __name__)
def get_pagination(model, page, page_size):
pagination = None
data = ... |
import contextlib
from typing import Any, List, Optional, Sequence
import click
from valohai_cli.api import request
from valohai_cli.commands.project.create import create_project
from valohai_cli.consts import yes_option
from valohai_cli.ctx import get_project, set_project_link
from valohai_cli.messages import warn
f... |
import models
import tensorflow as tf
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# todo:学習結果を出力できるよう改造
def gen_image(model, noise, filename="test"):
image = model(noise).numpy()
for i in range(image.shape[0]):
plt.subplot(4, 4, i + 1)
plt.imshow(image... |
import unittest
from talipp.indicators import ATR
from TalippTest import TalippTest
class TestATR(TalippTest):
def setUp(self) -> None:
self.input_values = list(TalippTest.OHLCV_TMPL)
def test_init(self):
ind = ATR(5, self.input_values)
print(ind)
self.assertAlmostEqual(in... |
from typing import Any
from django.db import models
from django.db.models.base import ModelBase
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.validators import MinValueValidator
from django.dispatch import receiver
class DirectReward(models.Model):
na... |
for _ in range(int(input())):
count = 0
n = input()
for i in n:
if i == '4':
count += 1
print(count) |
from ..engine import Box2DEngine
class Box:
""" Represents a box shape for a fixture """
def __init__(self, width=0, height=0):
""" Initialize the Box """
self.width = width
self.height = height
def apply(self, body, fixtureDef):
""" Apply the shape ... |
#q4.Write a program to check whether the input alphabet is vowel or not using if-else.
inp=input("enter a alphabet: ")
if (inp=='a'or inp=='e'or inp=='i'or inp=='o' or inp=='u'):
print('alphabet is vowels')
else:
print("alphabet is consonant") |
from django.db import models
import datetime
FRIDAY = 4
class Todo(models.Model):
done = models.BooleanField(default=False)
description = models.TextField()
def markCompleted(self):
if datetime.datetime.now().weekday() != FRIDAY:
self.done = True
|
import os
from datamanager.project import Project
from datamanager.filemanager import FileManager
from properties import dataFolderPath, always_write_to_disk
class DBManager(FileManager):
"""
Class that implements a DB manager. To use this class, you must first call the method
initialize_write_to_disk, then... |
from flask_restful import Resource, fields, marshal_with, reqparse, request, marshal
from flask_socketio import emit
from core.models.ticket_item import TicketItemModel
from core.models.ticket import TicketModel
from core.views.table import TableDetailById
from core.views.menu import MenuItemById
from core.models.menu... |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <[email protected]>"
"""
"""
from sweetrpg_api_core.data import APIData
from unittest.mock import patch, Mock
from flask_rest_jsonapi.querystring import QueryStringManager
from bson.objectid import ObjectId
import datetime
import json
class TestModel(object):
d... |
#!/usr/bin/env python3
import os
from subprocess import call
import argparse
import multiprocessing
def run_unit_tests(octopus_build_dir, use_verbose_output):
octopus_test_dir = octopus_build_dir + "/test"
os.chdir(octopus_test_dir)
ctest_options = []
if use_verbose_output:
ctest_options.appen... |
from lib.utils.evaluation_metrics.AverageSumErrorEvaluationMetric import AverageSumErrorEvaluationMetric
from lib.utils.evaluation_metrics.SumErrorEvaluationMetric import SumErrorEvaluationMetric
from lib.utils.evaluation_metrics.ClassificationEvaluationMetric import ClassificationEvaluationMetric
from lib.NeuralNetwor... |
from BlochSolver.SolversManager import solvers_manager
from BlochSolver.Plotter import bloch_plotter as bs
from BlochSolver.Perturbations.filters import Filters
from BlochSolver.QuantumSolvers.rotations import rotation_handler
from BlochSolver.QuantumSolvers.numerics import numerical_methods
from BlochSolver.Utils.util... |
from datetime import date
print('Maioridade!!!')
print('=-=' * 15)
maior = menor = 0
data = date.today().year
for c in range(1, 8):
n = int(input(f'Ano de nascimento da {c} pessoa: '))
if data - n >= 18:
maior += 1
else:
menor += 1
print('=-=' * 15)
print(f'{maior} Pessoas cadastradas são ma... |
__author__ = "Mohammad Dabiri"
__copyright__ = "Free to use, copy and modify"
__credits__ = ["Mohammad Dabiri"]
__license__ = "MIT Licence"
__version__ = "0.0.1"
__maintainer__ = "Mohammad Dabiri"
__email__ = "[email protected]"
def check_none(**kwargs):
for [argName, value] in kwargs.items():
if (value... |
from itertools import chain
def foo_yield(x):
i = 1
while i <= x:
yield range(0, i)
i += 1
'''
if you call foo_yield(4)
you will get a generator object
then you can call
for i in chain.from_iterable(foo_yield(4)):
print(i)
and you will get evaluated result below:
0
0
1
0
1
2
0
1
2
3
'''
''... |
import torch
from torch import nn
import torch.nn.functional as F
from collections import OrderedDict
import torch.utils.model_zoo as model_zoo
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
... |
from django.core.management.commands.compilemessages import Command as CompileMessagesCommand
class Command(CompileMessagesCommand):
program_options = [option for option in CompileMessagesCommand.program_options if option != '--check-format']
def add_arguments(self, parser):
super().add_arguments(par... |
"""
Module for helper functions regarding images.
"""
import cv2
import numpy as np
def get_image(file_path):
"""
Reads image and returns array of pixels.
"""
return cv2.imread(file_path)
def get_grayscale_image(image):
"""
Reads image and returns grayscale array of pixels.
"""
retu... |
# Python Substrate Interface Library
#
# Copyright 2018-2020 Stichting Polkascan (Polkascan Foundation).
#
# 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/LIC... |
from django import forms
from adminarea.models import AppIntegration, APP_INTEGRATIONS
class AppIntegrationForm(forms.ModelForm):
class Meta:
fields = ("platform", "display_name")
model = AppIntegration
|
import asyncio
from pyrocketjoe.celery import Celery
from pyrocketjoe.celery.apps import Worker
app = Celery()
worker = Worker(app)
@app.task()
def hello_world(a: int, b: int) -> None:
print('Hello, World!')
return a + b
result = hello_world.apply_async(40, 2)
async def main() -> None:
await worker... |
#!/usr/bin/env python
from __future__ import print_function
import zmq
import sys
import json
def save(filename, contents):
with open(filename + '_versions.json', 'a+') as f:
# Read the old versions.
f.seek(0)
try:
versions = json.load(f)
except ValueError:
v... |
# Generated by Django 2.2.16 on 2022-04-24 07:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sales_backend', '0003_auto_20220423_1218'),
]
operations = [
migrations.CreateModel(
name='Rat... |
import _dk_core as core
LinearTransform2 = core.LinearTransform2
AffineTransform2 = core.AffineTransform2
LinearTransform3 = core.LinearTransform3
AffineTransform3 = core.AffineTransform3
TransformUnit = core.TransformUnit
USTransform = core.USTransform
NSTransform = core.NSTransform
|
# coding: utf-8
try:
import os
import sqlite3
except ImportError:
pass
from modules.windows.chromium.chromium_module import ChromiumModule
from internal import data_type
from api.windows import format
class WindowsChromiumDownload(ChromiumModule):
def __init__(self):
ChromiumModule.__init__(
self,
name=... |
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.