content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import Carbs, Drinks, Fats, Meals, Proteins, User, Weekly
def index(request):
if request.u... | python |
# This file is part of the Reproducible and Reusable Data Analysis Workflow
# Server (flowServ).
#
# Copyright (C) 2019-2021 NYU.
#
# flowServ is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Unit tests for helper methods of the stor... | python |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
"""Tests using pytest_resilient_circuits"""
from __future__ import print_function
import pytest
from mock import patch
from resilient_circuits.util import get_function_definition
fro... | python |
# -*- coding: utf-8 -*-
from helper import *
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
ROOT_DIR = g.ROOT_DIR
raw_data_dir = g.raw_data_dir
processed_data_dir = g.processed_data_dir
print(f"ROOT DIR = {ROOT_DIR}")
data_directory = ROOT_DIR+"/data/raw/"
@click.command()
@click.option('--data_dir', default=ROOT_DIR+"/d... | python |
# read from HDF5 generated by ../bgen2hdf5/geno_hdf5.py
import h5py
import numpy as np
import pandas as pd
def get_individual_list(hdf5):
with h5py.File(hdf5, 'r') as f:
indiv = f['samples'][:].astype(str)
return indiv
def get_position_list(hdf5):
with h5py.File(hdf5, 'r') as f:
pos = f['... | python |
#
# File comparison - Compare contents of two files
#
# Copyright (c) 2018, Nobutaka Mantani
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must ret... | python |
#!/usr/bin/python
from __future__ import division
# example virtual base jump
import math
from lxml import etree
from pykml.parser import Schema
from pykml.factory import KML_ElementMaker as kml
from pykml.factory import ATOM_ElementMaker as atom
from pykml.factory import GX_ElementMaker as gx
GX_ns = "{http://www.go... | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | python |
import pandas as pd
import torch
from sentence_transformers import SentenceTransformer
df = pd.read_json('data/Movies_and_TV_5.json', lines=True)
df = df[['reviewText']]
df = df.rename(columns={'reviewText': 'review'})
index = pd.read_json('data/amt_train.json').index
df = df.loc[index]
df.to_json('data/review.json')... | python |
#!/usr/bin/env python
count = 1
count2 = 16
for i in range(1,10):
for j in range(count,10):
if i == 1:
print("%d * %d = %d" % (i,j,i*j),end="\t")
else:
if i == j:
print(" "*count2*(i-1),end="")
print("{} * {} = {}".format(i,j,i*j),end="\t")
... | python |
# Crie um programa que gere uma página html com links para todos os arquivos jpg e png encontrados a partir de um
# diretório informado na linha de comando
import sys
import os.path
import urllib.request
if len(sys.argv) < 2:
print('\n\nDigite o nome do diretório para coletar os arquivos jpg e png!')
print('U... | python |
import pytorch_lightning as pl
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms, models
IMAGENET_CLASS_COUNT = 1001
class SimpleCNN(pl.LightningModule):
def __init__(self):
super().__init__()
# TODO: torchserve does this processing, but maybe ... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 Ahmet Bakan
#
# This program 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, eith... | python |
import os
import configparser
QUICKIE_CONFIG_FILE = '.quickieconfig'
def find_quickieconfig():
current_dir = os.getcwd()
while not os.path.isfile(os.path.join(current_dir, QUICKIE_CONFIG_FILE)):
parent_dir = os.path.dirname(current_dir)
if current_dir == parent_dir:
raise... | python |
import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.tree import export_graphviz
... | python |
from django.conf.urls import url
from . import views
from . import api_v1
app_name = 'users'
urlpatterns = [
url(
regex=r'^$',
view=views.UserListView.as_view(),
name='list'
),
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redir... | python |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import re
import time
import json
import pprint
import logging
import base64
import pykd
import util.common
import log
import breakpoints
class PyKdDebugger(pykd.eventHandler):
def __init__(self, executable_path = ... | python |
'''
@jacksontenorio8
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que
é a condição de parada. No final, mostre quantos números foram
digitados e qual foi a soma entre eles (desconsiderando o flag)
'''
num = i = s = 0
num = int(input('Digit... | python |
"""
EXERCÍCIO 059: Criando um Menu de Opções
Crie um programa que leia dois valores e mostre um menu como o abaixo na tela:
[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos Números
[ 5 ] Sair do Programa
Seu programa deverá realizar a operação solicitada em cada caso.
"""
from time import sleep
n1 = int(input('... | python |
from models.user import UserModel
from conftest import is_valid, log
from freezegun import freeze_time
from models.user import RoleEnum
def test_user_auth(client, test_database, admin_user):
login_response = client.post("/api/login", json={
"email": admin_user.email,
"password": admin_user.password... | python |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="datadock",
version="0.0.1",
author="Andrew Hannigan",
author_email="andrew.s.hannigan@gmail.com",
description="Data blending utility",
long_description=long_descripti... | python |
__project__ = "SteamGuard"
__author__ = "Tygon"
__version__ = "1.0.0"
__license__ = "MIT" | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gupiao3.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import db_mysql
class Ui_Stock(object):
def setupUi(self, Stock):
... | python |
import requests
from lxml import html
import time
import praw
def sort(inputList):
isSorted=False;
while(isSorted==False):
isSorted=True
for i in range(len(inputList)-1):
if(inputList[i].score > inputList[i+1].score):
inputList[i], inputList[i+1] = inputList[i+1], inputList[i]
isSorted=False
return... | python |
# Not sure these functions are needed now
def createFileStructure(file_id, fileList=[], folderList=[], filePath=LOCAL_TARGET_DIR):
contents = searchChildrenByParent(file_id)
# Can probably refactor this loop to handle .DS_Store files more elegantly
for item in contents:
newPath = filePath+SLASH+item['name']
... | python |
"""
The MerossIot library is a low-level python library which interacts with the Meross Cloud
backend systems in order to control Meross devices. You can consider it as a library
upon which you can build automation scripts.
"""
name = "meross_iot"
| python |
# -*- coding: utf-8 -*-
from ctypes import (
Structure, byref, create_unicode_buffer, c_ubyte, c_ulong,
c_ulonglong, c_ushort, sizeof, windll
)
from enum import IntEnum
class GUID(Structure):
_fields_ = [
('Data1', c_ulong),
('Data2', c_ushort),
('Data3', c_ushort),
('Dat... | python |
import torch
import matplotlib.pyplot as plt
#################
# Fashion-MNist #
#################
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = [
't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt',
'sneaker', 'bag... | python |
with open("output.csv", "w") as output:
clusters = []
for i in range(0, 50):
clusters.append( [] )
with open("centroids2.csv", "r") as fd:
for line in fd:
elements = line.split(",")
for x in range(0, 50):
clusters[x].append( elements[x].rstrip() )
output.write("clusterID\t")
for i in r... | python |
from .web_gui import * | python |
import torch
a = torch.Tensor([[1, 2], [3, 4]])
print(a)
print(a.type())
a = torch.Tensor(2, 3)
print(a)
print(a.type())
a = torch.ones(2, 2)
print(a)
print(a.type())
# 对角线
a = torch.eye(2, 2)
print(a)
print(a.type())
a = torch.zeros(2, 2)
print(a)
print(a.type())
b = torch.Tensor(2, 3)
b = torch.zeros_like(b)
pr... | python |
def solve(arr: list) -> int:
""" This function returns the difference between the count of even numbers and the count of odd numbers. """
even = []
odd = []
for item in arr:
if str(item).isdigit():
if item % 2 == 0:
even.append(item)
else:
... | python |
from setuptools import setup, find_packages
setup(
name='ubuntunews',
version='1.0',
author='Isaac Atia',
author_email='atiaisaac007@gmail.com',
description='Ubuntu News from omgubuntu site',
long_description='Web scraping omgubuntu.co.uk to get latest news about my favourite \
linux distr... | python |
r=10**9
p=r
c=0
s=0
for i in range(2,int(p/3)+1):
k=0
for j in [i-1,i+1]:
p=2*i+j
if p>10**9:
k=1
if ((p**.5)%10)%2==0:
if ((4*i*i-j*j)**.5)%4==0 and p<r:
print(i,i,j,p)
s+=p
c+=1
if k==1:
... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
comment.py
Created by Benjamin Fields on 2014-02-11.
Copyright (c) 2014 . All rights reserved.
"""
import sys
import os
import unittest
import requests
import re
from bs4 import BeautifulSoup
class comment(object):
def __init__(self, rg_id=None, text=None, links=[], ... | python |
import glob
import io
import re
import subprocess
import sys
from enum import Enum
from typing import Tuple
__version__ = '0.2.0'
def get_output(*args):
return subprocess.check_output(args, universal_newlines=True).strip()
def sh(*args):
return subprocess.check_call(args)
def compile_string_decl_regex(va... | python |
#!/usr/bin/env python
# encoding=utf-8
"""
Copyright (c) 2021 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFT... | python |
"""
create_yaml module
This module provide a create_yaml function to interface the efficientdet-configuration file
"""
import yaml
def create_yaml(list_classes, path_output, autoaugment_policy, sample_image_path=None):
"""create_yaml function
This function has the efficientdet hyper-parameters
Args:
lis... | python |
from datetime import datetime
import logging
import urllib2
from django.conf import settings
from django.http import HttpResponse
import jsonpickle
from datawinners.common.authorization import httpbasic, is_not_datasender
from datawinners.main.database import get_database_manager
from datawinners.dataextraction.helpe... | python |
from restart_datasets.core import DataLoader, LocalDataLoader
data = DataLoader()
local_data = LocalDataLoader()
__version__ = "0.6"
| python |
from CoinInfo import CoinInfo
scrapper = CoinInfo()
num = 1
for i in scrapper.get_paragraphs('bitcoin'):
print(str(num) + ") Title : " + i['title'] + ".\n Link: "+ i['link'])
print("Briefly: " + i['body'])
print("##############################################################################... | python |
import argparse
from .molecularflow import runSimulation
parser = argparse.ArgumentParser(
prog='python -m molecularflow',
description='Compute molecular flow particle densities in an elbow tube',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('A', type=float, help='Tube dimen... | python |
#!/usr/bin/env python3
def welcome():
print("Welcome")
def hi(name):
print("Hi " + name + "!")
welcome()
username = input("Who are there? ")
hi(name=username)
hi(username)
| python |
from hashlib import md5
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_str
from django.utils.importlib import import_module
from static_precompiler.settings import MTIME_DELAY, POSIX_COMPATIBLE, STATIC_URL, \
COMPILERS
import os
im... | python |
from setuptools import setup, find_packages
setup(
name="pyti",
version='0.2.2',
description='Technical Indicator Library',
long_description="This library contains various financial technical "
"indicators that can be used to analyze financial data.",
url='https://github.co... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2022 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... | python |
"""Submodule providing tensorflow layers."""
from embiggen.layers.tensorflow.graph_convolution_layer import GraphConvolution
from embiggen.layers.tensorflow.noise_contrastive_estimation import NoiseContrastiveEstimation
from embiggen.layers.tensorflow.sampled_softmax import SampledSoftmax
from embiggen.layers.tensorflo... | python |
from unittest import TestCase
from unittest.mock import Mock, patch
from guet.settings.settings import Settings
from guet.commands.decorators.local_decorator import LocalDecorator
class LocalDecoratorTest(TestCase):
def test_calls_build_on_decorated_when_local_flag_not_in_args(self):
mock_factory = Moc... | python |
import math
import os
import random
import numpy as np
from gym_duckietown.envs import DuckietownEnv
from gym_duckietown.simulator import AGENT_SAFETY_RAD
POSITION_THRESHOLD = 0.04
REF_VELOCITY = 0.7
FOLLOWING_DISTANCE = 0.24
AGENT_SAFETY_GAIN = 1.15
class PurePursuitPolicy:
"""
A Pure Pusuit controller cl... | python |
# -*- coding: utf-8 -*-
# file: train_atepc_based_on_checkpoint.py
# time: 2021/7/27
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
from pyabsa import ATEPCCheckpointManager
from pyabsa.functional import ATEPCModelList
from pyabsa.functiona... | python |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import numpy as np
# Create Map
cm = plt.get_cmap("RdYlGn")
x = np.random.rand(30)
y = np.random.rand(30)
z = np.random.rand(30)
col = np.arange(30)
# # 2D Plot
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.sca... | python |
import math
import datetime
import pyximport; pyximport.install()
from mgf_filter.cython.mat import pow
def calculate_Resolution_based_MZ(mz):
"""
based on MZ calculates resolution
provided by a LR
"""
return math.pow(10, 5.847 + math.log10(mz) * (-0.546))
def calculate_Delta_based_MZ(mz, numSig... | python |
from configparser import ConfigParser
from importlib import import_module
from os import listdir
from sys import path
from plugins.plugin import Plugin
class Calculator(object):
@staticmethod
def __get_plugins():
config_parser = ConfigParser()
config_parser.read('properties.ini')
plug... | python |
#load libs
from wx.lib.embeddedimage import PyEmbeddedImage
#----------------------------------------------------------------------
AppIcon16 = PyEmbeddedImage(
b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC6klEQVR42pWTXUySURjH/3wo'
b'OBCQj7JNAxUJDJmseRGaN165hWbl0r5cLe3D1WWbm5deue6aX5mZMz+aF25h88obKrbmjEa... | python |
import sys
import requests
if __name__ == '__main__':
payload = {'access_key': '45a70dc23344db4c80691df95b90f8df'}
response = requests.get(
'http://api.exchangeratesapi.io/v1/latest',
params=payload
)
if response.status_code != 200:
sys.stderr.write(f"Error: Response: {respons... | python |
import argparse
import os
import numpy as np
from glob import glob
from PIL import Image
from tqdm import tqdm
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert png images to single .npy file')
parser.add_argument('--png_dir', type=str,
default='../ntire2021/data/sou... | python |
class Sample():
"""
A sample for a song, composed of slices (parts).
"""
def __init__(self, slices, song, size, index):
self.slices = slices
self.song = song
self.size = size
self.index = index
class Slice():
"""
A sample of the smallest size, used to construct
... | python |
# -*- coding: utf-8 -*-
# code for console Encoding difference. Dont' mind on it
import sys
import imp
import random
imp.reload(sys)
try:
sys.setdefaultencoding('UTF8')
except Exception as E:
pass
try:
import unittest2 as unittest
except ImportError:
import unittest
from datetime import datetime
from ... | python |
# Copyright 2016 OpenStack 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/LICENSE-2.0
#
# Unless required by applicable law ... | python |
"""
:author: Nicolas Strike
:date: Mid 2019
"""
from src.Panel import Panel
from src.VariableGroup import VariableGroup
class VariableGroupIceMP(VariableGroup):
"""
"""
def __init__(self, case, clubb_datasets=None, sam_benchmark_dataset=None, sam_datasets=None, coamps_benchmark_dataset=None,
... | python |
import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def num_digits(n)... | python |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, ... | python |
# This file was generated automatically by generate_protocols.py
from nintendo.nex import common, streams
import logging
logger = logging.getLogger(__name__)
class NintendoNotificationType:
LOGOUT = 10
PRESENCE_CHANGE = 24
UNFRIENDED = 26
FRIENDED = 30
STATUS_CHANGE = 33
class NotificationEvent(common.Struc... | python |
from django.shortcuts import render
from django.views.generic.base import View
from django.conf import settings
class HelpView(View):
def get(self, request):
return render(request, 'student_app/help.html', {'email': settings.DEFAULT_FROM_EMAIL})
| python |
"""
_ _ _ __
| | __ _| |__/ |/ \.
| |__/ _` | '_ \ | () |
|____\__,_|_.__/_|\__/
Este archivo es 'guia', ustedes tienen que ver la manera de convertir
este algoritmo en un formato compatible con MapReduce: una funcion map y
una funcion reduce.
NOTA: Esta es una manera muy ineficien... | python |
def append_all_custom_variants(base_function, custom_boolean_testers, custom_failure_raisers, dest_list):
"""
Utility method used by the tests
:param base_function:
:param custom_boolean_testers:
:param custom_failure_raisers:
:param dest_list:
:return:
"""
if 'custom_boolean' in ba... | python |
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.homepage,name='home'),
path('colleges/',views.college_list,name='colleges'),
path('college/<str:pk>/',views.college_branch,name='college_branch'),
path('college/<str:pk1>/<str:pk2>',views.college_branch_student,name='cbs'),
] | python |
# utils functions
import numpy as np
import random
import os
from time import time
import pickle
import pdb
import json
import torch
import logging
def setup_seed(seed):
'''
seed: the input random seed
'''
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random... | python |
# ! BE AWARE !
# Module section for Library Management System (LMS)
# Don't change anything if not known what is going to do.
class Library:
# Instances
library_instances = []
# some pre-defined books in this Library for future use
# library_catalog = {
# "Adventure": "Chander Pahar",
# ... | python |
import pygame
class Assasin():
def __init__(self,ai_settings, screen):
"""Initialize the Assasin and set its starting position."""
self.screen = screen
self.ai_settings = ai_settings
# Load the Assasin image and get its rect.
self.image = pygame.image.load('image/warrior_mo... | python |
"""
Original NGSI data example can be found from here:
https://github.com/Fiware/dataModels/blob/master/specs/Environment/AirQualityObserved/doc/spec.md#key-value-pairs-example
Below is reduced and modified version, e.g. PM values added.
See also https://github.com/Fiware/dataModels/issues/292
{
'pm25min': 0.3, 'pm2... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, CETI and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import datetime
class Device(Document):
def autoname(self):... | python |
'''
非同步聽牌機實驗程式
SKCOM.dll 已知狀況:
1. SKCenterLib_Login() 只能在 main thread 執行
2. SKCenterLib_Login() 執行第二次時, 會回傳錯誤 2003, 表示已登入
3. signal.signal() 只能在 main thread 執行
4. SKQuoteLib_EnterMonitor() 可以在 child thread 執行
5. SKQuoteLib_EnterMonitor() 失敗後執行第二次時, skcom.dll 需要 2.13.29.0 才有作用
6. SKQuoteLib_EnterMonitor() 成功後執... | python |
from scene import Scene
import objects
import euclid
from camera import Camera
import time
import sys
if __name__=="__main__":
#import rpdb2; rpdb2.start_embedded_debugger('1234')
# do raycaster things
objectlist = [objects.CollidableSphere(position=euclid.Point3(10.,-5.,5.), radius=3.,
... | python |
from .dataset import *
from .transforms import *
| python |
# coding=utf-8
from mock import patch, call, MagicMock
from django.conf import settings
from django.test import TestCase
from algoliasearch_django import AlgoliaIndex
from algoliasearch_django import algolia_engine
from algoliasearch_django.models import AlgoliaIndexError
from .models import User, Website, Example
... | python |
import flask
import simplejson as json
import api
import server
API_RESPONSE_HEADER = {
'Content-Type': 'application/json'
}
def assign_routes(app):
@app.route('/api/stock/<string:stock_symbol>', methods=['GET'])
def get_stock_realtime(stock_symbol):
try:
stock_data = api.get_stock_... | python |
# -*- coding: utf-8 -*-
###############################################################################
#
# ListYourIssues
# Lists all issues associated with the provided access token.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
... | python |
import numpy as np
from scipy import spatial
from datetime import datetime
import pandas as pd
import os
import copy
max_doc_len = 500
glove_embeddings = {}
embeds_file = open('glove/glove.840B.300d.txt', 'r')
for line in embeds_file:
try:
splitLines = line.split()
word = splitLines[0]
vec... | python |
from ..config import MENU_WIDTH
from ..transform import translate
tooltip = 'Delete Stockpile'
inactive_icon_clip = (192, 16, 16, 16)
active_icon_clip = (192, 32, 16, 16)
_block_origin = None
def start_on_tile(pos, stage, player_team):
# Delete the chosen stockpile
for stock in player_team.stockpiles:
... | python |
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis
from pprint import pprint
from scipy.spatial import ConvexHull
import csv
import pickle
PI = 3.14159265358979323846264338327950288... | python |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RRocr(RPackage):
"""Visualizing the Performance of Scoring Classifiers.
ROC g... | python |
# -*- coding: UTF-8 -*-
def ensure_iterable(v):
if hasattr(v, '__iter__'):
return v
else:
return [v]
| python |
from django.db import models
# Create your models here
class Tweet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
tweet = models.TextField(default='')
class Meta:
ordering = ('created',)
| python |
#!/usr/bin/env python
import queue
import subprocess
from threading import Thread
class SubprocSession(object):
""" An interactive session with a specificed subprocess.
Input may be passed to, and feedback received from, the suborocess.
To close the session, call SubproceSession.close().
"""
... | python |
# -*- coding: utf-8 -*-
import glob
import os
import six
import pytest
from html_text import (extract_text, parse_html, cleaned_selector,
etree_to_text, cleaner, selector_to_text, NEWLINE_TAGS,
DOUBLE_NEWLINE_TAGS)
ROOT = os.path.dirname(os.path.abspath(__file__))
@py... | python |
# Copyright (c) 2020
# [This program is licensed under the "MIT License"]
# Please see the file LICENSE in the source
# distribution of this software for license terms.
import pygame as pg
from os import path
from random import uniform, choice, random
import pytweening as tween
from src.sprites.mob import Mob
vec = ... | python |
# Setup #
import preprocessing
# import multiprocessing
# import re
import requests
import pandas as pd
# import json
import ftfy
# import argparse
from lxml import html # , etree
from dateutil.parser import parse as dateParse
import csv
import os
import time
import sys
import importlib
from selenium import webdrive... | python |
import numpy as np
from scipy.stats import norm
from .base import TimeSeries
class GaussianModel(TimeSeries):
"""
Class defines a collection of dynamic trajectories with a gaussian model fit to them.
Attributes:
norm (scipy.stats.norm) - gaussian fit to dynamic trajectories
bandwidth ... | python |
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import awrams.utils.datetools as dt
from awrams.utils.metatypes import ObjectDict,New
from .stats import build_stats_df,standard_percentiles
from .utils import valid_only,infer_freq,resample_to_months_df,resample_to_years_df
from .model import Sele... | python |
import pytest
import redis
import requests
from fastapi import status
from fastapi.encoders import jsonable_encoder
from app import celerytasks, schemas
class TestCeleryTasks:
@pytest.mark.ext
def test_update_rates__integration_test(self, mocker):
mocker.patch("app.celerytasks._update_cache")
... | python |
import numpy as np
from numpy.random import randint, randn, choice, random
import viznet
from scipy.sparse.csgraph import minimum_spanning_tree
def logo1():
with viznet.DynamicShow(figsize=(4,4), filename='_logo1.png') as ds:
n1 = viznet.NodeBrush('tn.dia', color='#CC3333') >> (0, 0)
n2 = viznet.Nod... | python |
from random import shuffle
def get_team_color(team_colors, click_colors):
team_colors = list(map(lambda x: x.upper(), team_colors.split(" / ")))
shuffle(team_colors)
for c in team_colors:
if c in click_colors:
return c.lower()
return False
| python |
import re
import time
from selenium.webdriver.common.by import By
from helpers import auditchecker
from view_models import sidebar as sidebar_constants, keys_and_certificates_table as keyscertificates_constants, \
popups, log_constants, messages
from view_models.keys_and_certificates_table import DETAILS_BTN_ID
... | python |
# coding: utf8
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
from popups import StudentPopupLayout
from datetime import datetime
class BehaviourContent(FloatLayout):
name = StringProperty('Comportement')
active_student = StringProperty... | python |
from payu.schedulers.pbs import PBS
from payu.schedulers.slurm import Slurm
from payu.schedulers.scheduler import Scheduler
index = {
'pbs': PBS,
'slurm': Slurm,
}
| python |
import unittest
from database import *
class TestCategoryCollection(unittest.TestCase):
def test_get_all_unique_registered_categories(self):
registered_categories = get_all_unique_registered_categories()
registered_categories = sorted(registered_categories)
expected_registed_categories = [
["Cell Phones & ... | python |
from datetime import date
atual = date.today().year
ano = int(input('Digite o ano do nascimento: '))
idade = atual - ano
print('O atleta tem {} anos.'.format(idade))
if idade <= 9:
print('Categoria Mirim')
elif idade <=14:
print('Categoria Infantil')
elif idade <=19:
print('Categoria Junior')
elif idade <=2... | python |
# ---------------------------------------------------------------------
# Zyxel.ZyNOS.get_copper_tdr_diag
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
#... | python |
# Создание и запуск приложения, программирование интерфейса экранов и действий на них
#Hello world
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import Sc... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.