content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import matplotlib.pyplot as plt
from simple import load_training_data as simple_h
from LeNet import load_training_data as LeNet_h
def comparison_plot(simple_history, lenet_history):
"""
:param simple_history: training data (dict)
:param lenet_history: training data (dict)
:return: matplotlib-... | python |
"""------------------------------------------------------------------------------------------------
Program: registry.py
Security: NONE
Purpose: This module provides a simple interface to the Windows
registry. It contains a Registry class that can be used
to interact with the re... | python |
from lltk.imports import *
class TextNewCorpus(Text):
def text_plain(self,*x,**y):
# By default will load from file
txt=super().text_plain(*x,**y)
# Any last minute fixes here?
# txt = ...
return txt
def xml2txt(xml_txt_or_fn,*x,**y):
return default_xml2txt(xml_txt_or_fn,*x,**y)
class NewCorpus(Corpu... | python |
import networkx as nx
from api.models import Person, Photo
import itertools
def build_social_graph():
G = nx.Graph()
people = Person.objects.all()
person_names = [person.name for person in people]
photos = Photo.objects.all()
G.add_nodes_from(person_names)
name_sets = []
for photo in photos:
names = []
... | python |
import math
import re
def percentile(values, percent, key=lambda x: x):
"""
Find the percentile of a list of values.
Params:
values (list): Sorted list of values.
percent (float): A value from 0.0 to 1.0.
key (function): Optional key function to compute value from each value on li... | python |
l=sorted(map(int,input().split()))
a=2*l[2]-l[1]-l[0]
print((a+3)//2 if a%2 else a//2) | python |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... | python |
import os
import sys
from jk_hwriter import HWriter
from .HAbstractElement import HAbstractElement
from .HAttribute import HAttribute
from .HAttributeList import HAttributeList
from .HText import HText
from .HElement_HAbstractElementList import HElement, HAbstractElementList
class HToolkit_Write_Dump(object):
... | python |
# -*- coding: UTF-8 -*-
import base64
import os
from aliyun_encryption_sdk.cache.local import LocalDataKeyMaterialCache
from aliyun_encryption_sdk.ckm.cache import CachingCryptoKeyManager
from aliyun_encryption_sdk.client import AliyunCrypto
from aliyun_encryption_sdk.kms import AliyunConfig
from aliyun_encryption_sd... | python |
from flask_classful import FlaskView
from flask import render_template
class TestClass(FlaskView):
def index(self):
return "<h1>This is my index page</h1>"
def welcome(self): #/welcome
return "<h1>This is my Welcome page</h1>"
def ariwelcome(self):
return render_template('index_o... | python |
##########################################
## Author: Piotr Szczypta ##
## Lidar L515 distance on image ##
## Company: A4BEE ##
##########################################
import cv2 as cv
import pyrealsense2 as rs
import numpy as np
import json
# Some of the para... | python |
import json
import uuid
from typing import Optional
import requests
from ravendb.http.misc import ClusterTopologyResponse
from ravendb.http.raven_command import RavenCommand
from ravendb.http.server_node import ServerNode
from ravendb.http.topology import Topology
from ravendb.tools.utils import Utils
class GetData... | python |
from bullet import Bullet
from pixels_manager import PixelsManager
from player import Player
class Shooter:
@staticmethod
def can_spawn_bullet(direction):
if Player.get_instance().get_health() <= 1:
return False
return direction == direction.LEFT and Player.get_instance().get_curr... | python |
#!/usr/bin/env python3
import os
import argparse
import numpy as np
import torch
from collections import OrderedDict
from xfr import xfr_root
from xfr import inpaintgame_saliencymaps_dir
from xfr.inpainting_game.plot_inpainting_game import make_inpaintinggame_plots
from create_wbnet import create_wbnet
human_net_la... | python |
import os
def is_running_locally():
"""
Tells if an experiment is running on a local machine or not
:return:
"""
local = False
if "POLYAXON_NO_OP" in os.environ:
local = True
return local
def get_username():
username = os.getlogin()
return username | python |
#encoding=utf8
'''
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
'''
import os
import sys
import argparse
import numpy as np
import cv2
from PIL import Image, ImageDraw
# Make sure that caffe is on the python path:
caffe_root = '../../../../caffe_train/'
sys.path.insert(0, ... | python |
#!/usr/bin/python
import os
import time
import sys
import re
import globus_sdk
from datetime import datetime
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
import ast
import ConfigParser
from optparse import OptionParser
args=None
parser = OptionParser()
parser.add_option("--transfer-i... | python |
from collections import deque
from random import randint
from threading import local
def expose(func):
func.exposed = True
return func
class flattener(object):
def __init__(self, iterator):
while type(iterator) == flattener:
iterator = iterator.iterator
self.iterator = iterat... | python |
import tensorflow as tf
import numpy as np
test_arr = [[np.zeros(shape=(2, 2), dtype="float32"), 0], [np.ones(shape=(2, 2), dtype="float32"), 1]]
def input_gen():
for i in range(len(test_arr)):
label = test_arr[i][1]
features = test_arr[i][0]
yield label, features
dataset = tf.data.Data... | python |
# ----------------------------------------------------------------------
# Auth Profile Loader
# ----------------------------------------------------------------------
# Copyright (C) 2007-2016 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC modu... | python |
"""
Write a function to compute 5/0 and use try/except
to catch the exceptions.
Hints : try/except to catch exceptions.
"""
# Solution :
def throw():
return 5 / 0
try:
throw()
except ZeroDivisionError:
print("Division by zero")
except Exception:
print("Caught an exception")
finally:
... | python |
from parsedatetime.pdt_locales import (
de_DE, en_AU, en_US,
es, nl_NL, pt_BR,
ru_RU, fr_FR)
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
QAction, QFileDialog, QApplication, QWidget, QLabel,
QComboBox, QHBoxLayout, QVBoxLayout, QPushButton,
QTableWidget,QTableWidgetItem, QGridLayout,... | python |
import sys
sys.path.append("${CMAKE_BINARY_DIR}")
import os
import pickle
import tempfile
import unittest
import math
import pyrfr.regression as reg
class TestBinaryRssRegressionForest(unittest.TestCase):
def setUp(self):
data_set_prefix = '${CMAKE_SOURCE_DIR}/test_data_sets/'
self.data = reg.default_data_con... | python |
# Virtualized High Performance Computing Toolkit
#
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the
# "License"). You may not use this product except in compliance with the
# Apache 2.0 License. This product may include a number of subcomp... | python |
# -*- coding: utf-8 -*-
"""Source code for abstract observation noise.
Author: Yoshinari Motokawa <yoshinari.moto@fuji.waseda.jp>
"""
from abc import ABC, abstractmethod
from typing import List
from core.worlds.abstract_world import AbstractWorld
from omegaconf import DictConfig
class AbstractObservationNoise(ABC... | python |
import Item
def setter():
x = Item.weaponItem('Iron Sword',1,0,10,"Swing")
return x
| python |
import itertools as it
LOW = 172851
HIGH = 675869
doubles = set()
for i in range(10):
doubles.add(str(i)*2)
triples = set()
for i in range(10):
triples.add(str(i)*3)
def main():
score = 0
for i in range(LOW, HIGH +1):
flag = True
s = str(i)
s_list = list(s)
s_list_s... | python |
def apply_async(func, args, *, callback):
result = func(*args)
callback(result)
def print_result(result):
print('Got:', result)
def add(x, y):
return x + y
apply_async(add, (2, 3), callback=print_result)
# Got: 5
apply_async(add, ("hello", "world"), callback=print_result)
# Got: helloworld
cla... | python |
# Copyright 2020 Makani Technologies LLC
#
# 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... | python |
import pytest
from bmipy import Bmi
class EmptyBmi(Bmi):
def __init__(self):
pass
def initialize(self, config_file):
pass
def update(self):
pass
def update_until(self, then):
pass
def finalize(self):
pass
def get_var_type(self, var_name):
p... | python |
# Natural Language Toolkit: Word Sense Disambiguation Algorithms
#
# Authors: Liling Tan <alvations@gmail.com>,
# Dmitrijs Milajevs <dimazest@gmail.com>
#
# Copyright (C) 2001-2015 NLTK Project
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from nltk.corpus import wordnet
def lesk(cont... | python |
from ...gpstime import GPSTime
from ..utils import Enums, TestCaseFailure
from .standby import DualSatStandbyCase
from .utils import log_fc_data, log_psim_data
class DualSatFarFieldCase(DualSatStandbyCase):
def post_boot(self):
"""To put us in fair field, we need to be able to initialize each
sat... | python |
#!/usr/bin/env python
from methods import (
PlanToConfigurationTest,
PlanToConfigurationStraightLineTest,
PlanToConfigurationCompleteTest,
PlanToEndEffectorPoseTest,
PlanToEndEffectorOffsetTest,
)
from planning_helpers import BasePlannerTest
from prpy.planning.cbirrt import CBiRRTPlanner
from unitte... | python |
import MySQLdb
db_connection = MySQLdb.connect(
host="localhost",
user="tycho_dev",
passwd="dev123",
db="tycho"
)
def fatality_data():
cursor = db_connection.cursor()
cursor.execute("SELECT AVG(CountValue) FROM noncumulative_all_conditions WHERE Fatalities = 1;")
average_fatalities = curs... | python |
# -*- coding: utf-8 -*-
"""Tests for Predicates, mostly took from repoze.what test suite"""
##############################################################################
#
# Copyright (c) 2007, Agendaless Consulting and Contributors.
# Copyright (c) 2008, Florent Aide <florent.aide@gmail.com>.
# Copyright (c) 2008-20... | python |
from pathlib import Path
import shutil
import re
import nbformat as nbf
from wrap_notebook_lines import find_links
from link_fix import markdown_cells
input_nb_pattern = r'0[0123].*.ipynb'
p = Path('.')
(p / 'converted').mkdir(exist_ok=True)
input_notebooks = p.glob(input_nb_pattern)
def nuke_dir_tree(top):
s... | python |
from openvino.inference_engine import IENetwork, IEPlugin
from argparse import ArgumentParser
from PIL import Image, ImageDraw
import logging as log
import numpy as np
import time
import cv2
import sys
import os
def build_argparser():
parser = ArgumentParser()
parser.add_argument("-m", "--model", help="Path to an .x... | python |
# -*- coding: utf-8 -*-
__version__ = '0.0.0'
__author__ = 'Mike Bland'
__license__ = "CC0-1.0"
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 13:10:48 2018
@author: kazuki.onodera
"""
import gc, os
from tqdm import tqdm
import pandas as pd
import numpy as np
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from... | python |
from io import StringIO
from django.apps import apps
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connection
from ....account.utils import create_superuser, create_user
from ...utils.random_data import (
add_address_to_admin
)
class Co... | python |
from numpy import genfromtxt
import numpy as np
from time import sleep
from sklearn.datasets import make_regression as mr
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
class WML(object):
'''
Class to solve a linear regression problem using
calculating the maximum likelihood and solv... | python |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Link CornerPin
# COLOR: #5a892b
# TEXTCOLOR: #ffffff
#
#------------------------------------------------------------------------------------------... | python |
import numpy as np
import cv2
import staple
from sklearn.metrics import jaccard_score
import SimpleITK as sitk
from LabelFusion.wrapper import fuse_images
from skimage.filters import threshold_otsu
def to3(src, axis=2):
return np.stack((np.zeros_like(src), src.max() - src, src), axis=axis)
def get_majority_vote... | python |
import paramiko
import tarfile
import sys
import socket
import nmap
import os
import sys
import struct
import fcntl
import netifaces
import urllib
import shutil
from subprocess import call
# Make a list of credentials
login_list= [('this', 'one?'),
("hell0", "Adel3"),
('admin', 'admin'),
('root', '94849390')
]
#This ... | python |
"""The top level of the package contains functions to load and save
data, display rendered scores, and functions to estimate pitch
spelling, voice assignment, and key signature.
"""
import pkg_resources
from .io.musescore import load_via_musescore
from .io.importmusicxml import load_musicxml, musicxml_to_notearray
f... | python |
#!/usr/bin/env python
# coding: utf-8
#
# Get key to relevant CARD products in CREODIAS catalog
# Version 1.3 - 2020-05-14
# - Make end date inclusive
#
# Version 1.2 - 2020-04-14
# - Changed to JSON format parsing
# - added s1 selection
#
# Version 1.1 - 2020-03-24
# - Include intersection calculation
#
import reque... | python |
#
# テンプレート構成
#
from typing import List, Optional
from .argument import Argument
from .content import Content
class Config:
"""パッケージテンプレートの構成.
"""
def __init__(self,
name: str,
args: List[Argument],
contents: List[Content],
args_handler... | python |
import jwt
from flask import current_app
from datetime import datetime, date, timedelta
from marshmallow import Schema, fields, validate, validates, ValidationError
from werkzeug.security import generate_password_hash, check_password_hash
from book_library_app import db
class Author(db.Model):
__tablename__ = '... | python |
import json
import inspect
from datetime import datetime
import itertools
import requests
##########################################
# Utility functions
#
def _str_or_none(value: any) -> any:
"""will convert any value to string, except None stays None"""
return None if value is None else str(value)
#######... | python |
import compute_merw as merw
import scipy.sparse as sparse
import metrics
import dataset
def print_similarity_matrix(S):
if not sparse.issparse(S):
S = sparse.csr_matrix(S)
n, m = S.get_shape()
for row in range(n):
print('[', end='')
for col in range(m):
print('{:6.3f} '... | python |
# Generated by Django 3.1 on 2021-01-02 12:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('chat', '0006_message'),
]
operations = [
migrations.RemoveField(
model_name='room',
name='staff_only',
),
]
| python |
"""
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from... | python |
"""
Parse a Canadian Census XML document (in SDMX format) and yield a CSV with the
same data. The data will be Tidy (http://vita.had.co.nz/papers/tidy-data.pdf).
However, all the column names and concept values will remain as they appear in
the SDMX file -- which is to say, not very human-readable. See the other scrip... | python |
"""Class that represents the network to be evolved."""
import random
import logging
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
class Network():
"""Represent a netwo... | python |
'''
Created on 2015年12月10日
@warning: 请务必在命令行添加选项参数,以支持不同方法的处理流程
@summary: 初始化工作,将文件的内容写入数据库
@author: suemi
'''
import sys,os
sys.path.append(".")
from optparse import OptionParser
from utils.DBUtil import DBUtil
option_0 = { 'name' : ('-s', '--start'), 'help' : '选择处理的起始位置', 'nargs' : 1 }
option_1 = { 'name' : ('-e','... | python |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
class AnswerForm(forms.Form):
content = forms.CharField(label='Answer content', max_length=2048)
class _EmailForm(forms.ModelForm):
... | python |
from pget import Downloader
def sha1sum(file_name):
import hashlib
BUF_SIZE = 65536
sha1 = hashlib.sha1()
with open(file_name, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data)
return sha1.hexdigest()... | python |
import setuptools
# Open the requirements file and dump them
with open("requirements.txt") as file:
requirements = file.read().splitlines()
# Do the same with the dev requirements
with open("requirements-dev.txt") as file:
extras = {"dev": file.read().splitlines()}
setuptools.setup(
name="tokki",
ver... | python |
import threading
import websocket, json, time
class CoinbaseWebsocket(threading.Thread):
def __init__(self):
# websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("wss://ws-feed.exchange.coinbase.com",
on_message = self.on_message,
... | python |
from ipywidgets import register, Widget, DOMWidget, widget_serialization
from traitlets import (
default, TraitError,
Bool, Int, Unicode, Enum, Tuple, Instance
)
import uuid
from ._version import __version__
def id_gen():
return uuid.uuid4().urn[9:]
@register
class Node(Widget):
""" The node widget ... | python |
# test resources manager - parser (PM)
# test resources loader
# test Music / SOund / Font classes.
import os
import pytest
from laylib import resources as rc
@pytest.fixture
def class_resources(scope='module'):
res_class = rc.Resources('examples/data')
yield res_class
@pytest.fixture
def folder_data(scope... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import cos,sin,diff,integrate,simplify,limit,solve,Symbol
x = Symbol('x')
y = Symbol('y')
# Algebraic computation
print(2*x + 3*x - y)
# Differentiates x**2 wrt. x
print(diff(x**2, x))
# differentiates cos(x) and sin(x) wrt. x
print(... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'AzureSkuName',
'AzureSkuTier',
]
class AzureSkuName(str, Enum):
"""
SKU name
"""
S1 = "S1... | python |
from chemreps.coulomb_matrix import coulomb_matrix
import numpy as np
import pytest as pt
def test_cm():
cm_true = np.array([36.84, 23.33, 36.84, 23.38, 14.15, 36.84, 14.15,
23.38, 9.195, 36.84, 5.492, 2.762, 2.775, 2.162,
0.5, 5.492, 2.762, 2.775, 2.162, ... | python |
from __future__ import unicode_literals
import re
import time
from ncclient import manager
import paramiko
import xmltodict
CONNECT_TIMEOUT = 5 # seconds
class RPCClient(object):
def __init__(self, device, username='', password=''):
self.username = username
self.password = password
tr... | python |
from django.urls import path
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from . import views
from .viewsets import MaskDetectorViewSet
# app_name = 'api'
# router = routers.DefaultRouter()
# router.register('', MaskDetectorViewSet, basename='predict')
urlpatt... | python |
from abc import abstractmethod
from typing import Any, Optional, Union
from PySide6.QtWidgets import QCheckBox, QDoubleSpinBox, QHBoxLayout, QLabel, QSpinBox
from cilissa_gui.widgets.inputs.base import (
MAX_NEG_INTEGER,
MAX_POS_INTEGER,
CQInputWidget,
)
class CQNumberInputWidget(CQInputWidget):
sb:... | python |
#!/usr/bin/env python -O
"""
This is the test class for testing Display module algorithms and models.
"""
# -*- coding: utf-8 -*-
#
# tests.unit.TestDisplay.py is part of The RTK Project
#
# All rights reserved.
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(dirname(__file__))) + "/r... | python |
import tropomi_tools as tt
import letkf_utils as lu
from datetime import datetime
timeperiod = [datetime.strptime('2019-01-01 00:00', '%Y-%m-%d %H:%M'), datetime.strptime('2019-01-02 23:59', '%Y-%m-%d %H:%M')]
histens = lu.HIST_Ens('20190102_0000',True)
histens.getLocObsMeanPertDiff(0,0)
trans = tt.TROPOMI_Translato... | python |
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from ohjelma.models import Song
from ohjelma.models import Track
import json
impo... | python |
import glob
import os
import shutil
import base64
from subprocess import Popen, PIPE
import io
import matplotlib
import imageio
from ..config import Configuration
class FrameWriter(object):
'''A writer of frames from Matplotlib figures.
This class writes out individual frames to the specified directory. No
anima... | python |
from wtforms import PasswordField, StringField, SelectField
from wtforms.fields.html5 import EmailField
from wtforms.validators import InputRequired
from CTFd.forms import BaseForm
from CTFd.forms.fields import SubmitField
from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields
def Registrat... | python |
# Command line tool for dealing with file attachments
import os
#import sys
#sys.path.append(os.path.abspath(".."))
from common_utils import *
from items_in_collection import *
# Main to accept command line and do the operation on images.
if __name__ == '__main__':
# get the command line arguments
if len(sys.a... | python |
def calcular_precio_producto(coste_producto):
"""
num -> num
se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste
:param coste_producto: valor numerico del coste
:return: precio del producto
>>> calcular_precio_producto(1000)
1500.0
>>> calcular_precio_... | python |
from django.contrib import admin
from .models import News
class NewsAdmin(admin.ModelAdmin):
date_hierarchy = 'date'
list_display = ('title', 'author', 'club', 'date')
list_filter = ('date',)
class Meta:
model = News
admin.site.register(News, NewsAdmin)
| python |
import chainer
import chainer.functions as F
import chainer.links as L
import numpy
from tgan2.utils import make_batch_normalization
class GeneratorConv3D(chainer.Chain):
def __init__(self, n_frames=16, z_slow_dim=256, out_channels=3):
self.n_frames = n_frames
self.z_slow_dim = z_slow_dim
... | python |
from werkzeug.serving import run_simple
import tuber
import sys
from .backgroundjobs import AsyncMiddleware
tuber.database.migrate()
app = tuber.app | python |
from django.apps import AppConfig
class SeliaMapsConfig(AppConfig):
name = 'selia_maps'
| python |
import os
import random
import numpy as np
from tqdm import tqdm
def self_play_history(env, agent, turn, gamma=1.0, all_purple=False):
env = env()
if all_purple:
obsv = env.update('14U24U34U44U15U25U35U45U41u31u21u11u40u30u20u10u')
else:
obsv = env.reset(agent.init_red(), agent.init_red()... | python |
import RPi.GPIO as GPIO
import dht11
import time
import datetime
import sys
import os
import serial
#import serialget
sys.path.append('/home/pi/proj/Adafruit_CharLCD')
from Adafruit_CharLCD import Adafruit_CharLCD
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
lcd = Adafruit_CharLCD(rs... | python |
"""
Packages required
terminaltables
colorclass
"""
from schema_validation import CheckGrants as CG
from schema_validation import CheckJSON as CJ
from schema_validation import CheckTable as CT
from schema_validation import OrderFiles as OF
import os
import re
from terminaltables import SingleTable, AsciiTa... | python |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/1222
#!/usr/bin/env python2.7
# -*- coding : utf-8 -*-
while True:
try:
a,b,c = [int(i) for i in raw_input().split()]
except EOFError:
break
entrada = raw_input().split()
paginas = 1
linha_da_vez = []
linhas = 1
for palavra i... | python |
import os
import shutil
from typing import Optional
import pytest
from pandas._testing import assert_frame_equal
import pandas as pd
from numpy import nan
import datacode as dc
import datacode.hooks as dc_hooks
from datacode import Variable
from tests.pipeline.base import PipelineTest, EXPECT_GENERATED_DF
from tests... | python |
#-*- coding: utf-8 -*-
from privtext.env import _PY_V
from random import randint
def cross_input():
if _PY_V == 2:
return raw_input()
return input()
def cross_encode(s):
if _PY_V == 2:
return s
return s.encode('utf-8')
def cross_decode(s):
if _PY_V == 2:
return s
return s.decode('utf-8')
# ... | python |
#!/usr/bin/env python
import os
import re
import shlex
import sys
from distutils.dep_util import newer
from shutil import which
from cx_Freeze import setup, Executable
import jinja2
#import setuptools
from setuptools import Command, find_packages
PO_FILES = 'po/*/messages.po'
class CleanCommand(Command):
"""
... | python |
"""Collection of nodes used in unittests.
PYTHONPATH will be automatically set so Python can find this package.
"""
import sys
import argparse
def main(argv):
parser = argparse.ArgumentParser("hello")
parser.add_argument("name", type=str, help="your name")
args = parser.parse_args(argv[1:])
print(f"... | python |
from nose.tools import raises
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from menpo.math import dot_inplace_left, dot_inplace_right
n_big = 9182
k = 100
n_small = 99
a_l = np.random.rand(n_big, k)
b_l = np.random.rand(k, n_small)
a_r = np.ascontiguousarray(b_l.T)
b_r = np.ascontiguousa... | python |
from laptimize.solver import Solver
'''
Source : A global optimization method for non convex separable programming problems,
European Journal of Operational Research 117 (1999) 275±292
Authors : Han-Lin Li, Chian-Son Yu
Minimize : F0(x1) = 40*x1 + 5*(|x1-10| + x1-10) - 5*(|x1-12| + x1-12)
F0(x2) =... | python |
#!/usr/bin/python3.9
# Copyright (c) 2021 MobileCoin Inc.
# Copyright (c) 2021 The Forest Team
from forest.core import Bot, Message, run_bot
class TemplateBot(Bot):
async def do_template(self, _: Message) -> str:
"""
A template you can fill in to make your own bot. Anything after do_ is a / comma... | python |
#!/usr/bin/env python
import rospy
import sys
sys.path.append("../../")
import configparser
import numpy as np
import time
import tf
import actionlib
import signal
import std_msgs.msg
import geometry_msgs.msg
import sensor_msgs.msg
from geometry_msgs.msg import Pose
from std_msgs.msg import Float32MultiArray
from co... | python |
import numpy as np
import math
c = 2.9979 * pow(10,8)
#Practice test question 2 Type
def MagneticField():
ElecMax = float(input("Input the Emax (V/m): "))
angularVelocity = float(input("Input (x10^6 Rad/s): ")) * pow(10,6)
magneticField = (ElecMax/c) * pow(10,9)
print("Magnetic Field:" ... | python |
import pygame, sys, random
def draw_floor():
screen.blit(floor_surface, (floor_x_pos, 900))
screen.blit(floor_surface, (floor_x_pos+576, 900))
def create_pipe():
random_pipe_pos = random.choice(pipe_height)
bottom_pipe = pipe_surface.get_rect(midtop=(700, random_pipe_pos))
top_pipe = pipe_surface.... | python |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
This implementation is based on the blog post at
https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html
"""... | python |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 2 of the License, or
# (at your o... | python |
import FWCore.ParameterSet.Config as cms
ct2ct = cms.EDProducer("CaloTowersReCreator",
# Weighting factor for EB
EBWeight = cms.double(1.0),
HBGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0,
20.0, 30.0, 50.0, 100.0, 1000.0),
# energy scale for each subdetector (only Eb-Ee-Hb-He interpolations a... | python |
import simulator
BCM = 0
IN = 0
OUT = 1
PUD_DOWN = 0
RISING = 0
def setmode(mode):
pass
def setup(pin, direction, pull_up_down=PUD_DOWN):
if direction == IN:
print("New button @pin{}".format(pin))
def add_event_detect(pin, on, callback):
print("Callback @pin{}".format(pin))
simulator.buttons... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 15:21:32 2020
@author: daniel
"""
import numpy as np
from cmath import sqrt
from scipy.special import sph_harm
from numpy.linalg import pinv
from matplotlib import pyplot as plt
#import shtns
class spherical:
def __init__(self, lmax):
... | python |
import numpy as np
import xpart as xp
import xobjects as xo
def test_basics():
for context in xo.context.get_test_contexts():
print(f"Test {context.__class__}")
particles = xp.Particles(_context=context,
mass0=xp.PROTON_MASS_EV, q0=1, p0c=7e12, # 7 TeV
x=[1e-3, 0], ... | python |
from __future__ import print_function
# OneWire part
try:
import ow
onewire = True
owsensorlist = []
except:
print("Onewire package not available")
onewire = False
import sys, time, os, socket
import struct, binascii, re, csv
from datetime import datetime, timedelta
# Twisted
from twisted.protocol... | python |
from concurrent import futures
from datetime import datetime
from typing import Tuple, Dict, List
from zipfile import ZipFile
from io import BytesIO
from collections import defaultdict
from utils.github import get_github_metadata, get_artifact
from utils.pypi import query_pypi, get_plugin_pypi_metadata
from api.s3 imp... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.