content stringlengths 5 1.05M |
|---|
"""
This script will create a standalone program for a pythonn script using py2exe.
The syntax for running this file is: python deploy.py py2exe
The options, notes etc. for the syntax below can be found at: http://www.py2exe.org/index.cgi/ListOfOptions
Use console to launch this from cmd prompt. Copy mkl_avx2.dll and ... |
# dummy file for django tests
|
"""
Parameter related utils
-----------------------
Contains utils and definitions that are used together with the parameters.
"""
import enum
from aiida.common.extendeddicts import AttributeDict
from aiida.plugins import DataFactory
from aiida_vasp.utils.extended_dicts import update_nested_dict
FUNCTIONAL_PARAMETE... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import nlpaug.augmenter.char as nac
import numpy as np
if __name__ == "__main__":
with open("var.txt") as f:
variables = [line.strip() for line in f.readlines()]
np.random.seed(42)
variables = np.random.choice(variables, 1024)
aug = nac.KeyboardAug(
aug_char_max=1,
include_speci... |
from src.ch3.dictionary_code import lz78_decode, lz78_encode
def test_lz78_encode():
assert lz78_encode("bccbcbacbabcbac") == [
("b", (0, "b")),
("c", (0, "c")),
("cb", (2, "b")),
("cba", (3, "a")),
("cbab", (4, "b")),
("cbac", (4, "c")),
]
assert lz78_enco... |
#!/usr/bin/env python3
# Copyright (c) 2019 SiFive Inc.
# SPDX-License-Identifier: Apache-2.0
from itertools import chain
from pydevicetree.source import grammar
from pydevicetree.ast import *
def transformNode(string, location, tokens):
"""Transforms a ParseResult into a Node"""
properties = [e for e in tok... |
'''Creates sitemap for galleries and images.
# TO DO: Galleries
'''
from django.contrib.sitemaps import Sitemap
from gallery.models import Image
class ImageSitemap(Sitemap):
changefreq = "never"
priority = 0.5
def items(self):
return Image.objects.all()
def lastmod(self, obj):
return... |
import json
import pytest
from aws_cdk import core
from patient_outcome_prediction.patient_outcome_prediction_stack import PatientOutcomePredictionStack
def get_template():
app = core.App()
PatientOutcomePredictionStack(app, "patient-outcome-prediction")
return json.dumps(app.synth().get_stack("patient-o... |
# Generated by Django 3.1.7 on 2021-03-13 13:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CustInfo',
fields=[
('id', models.IntegerFi... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
import argparse
import json
import os
from distutils.util import strtobool
from os.path import join, dirname
import sys
from watercooler_utils import ad_op... |
from setuptools import setup
setup(
name='graypy_gelf_https',
version='1.0.1',
description='graypy extension with GELF HTTPS handler',
license='MIT',
author='Dmitrii Don',
author_email='dondmitriys@gmail.com',
packages=['graypy_gelf_https', ],
url='https://github.com/smpio/graypy-gelf-h... |
#!/usr/bin/env python
import protocols_flavor
class GoRpcProtocolsFlavor(protocols_flavor.ProtocolsFlavor):
"""Overrides to use go rpc everywhere"""
def binlog_player_protocol(self):
return 'gorpc'
def binlog_player_python_protocol(self):
return 'gorpc'
def vtctl_client_protocol(self):
return '... |
"""Support for the Netatmo Weather Service."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import NamedTuple, cast
import pyatmo
from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT,
STATE_CLASS_TOTAL_INCREASING,
SensorEntity,
Senso... |
lang = {
"it": {
"col": {
"hospital_bed_tot": "Totale Posti Letto",
"province": "Provincia",
"region": "Regione",
"population": "Popolazione",
"death_rate_all_rel_freq": "Tasso di Mortalità Complessivo'",
"age": "Eta'",
"gen... |
#
# Execute watson on a session
#
import argparse
from lib import shellcode
__description__ = "Show missing KBs and suggest exploits for priv esc"
__author__ = "@Flangvik, @_RastaMouse"
__type__ = "enumeration"
# identify the task as shellcode execute
USERCD_EXEC_ID = 0x3000
# location of Watson binary
WATSON_BIN ... |
''' generic util functions
'''
import os
import sys
import pdb
import uuid
import shlex
import itertools
import subprocess
import numpy as np
import pickle as pkl
from tqdm import tqdm
from tabulate import tabulate
# Torch imports
import torch
from torch.autograd import Variable
import torch.nn.functional as F
def ch... |
# coding: utf-8
import os
import shutil
import json
import click
from werkzeug.utils import cached_property
class Context(object):
def __init__(self):
self.config_filename = os.environ.get('RIGIDSEARCH_CONFIG')
@cached_property
def app(self):
from rigidsearch.app import create_app
... |
#---------------------------------------
# DUNDERS
#---------------------------------------
__author__ = "Philip Arvidsson <contact@philiparvidsson.com>"
__license__ = "MIT (see LICENSE)"
__version__ = "0.4.7"
#---------------------------------------
# IMPORTS
#---------------------------------------
from pymake3 i... |
"""Next gen sequence alignments with Bowtie2.
http://bowtie-bio.sourceforge.net/bowtie2/index.shtml
"""
import os
import subprocess
from bcbio.pipeline import config_utils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.ngsalign import bowtie
def _bowtie2_arg... |
import cv2
#Create a cascade classifer object
car_cascade = cv2.CascadeClassifier("cascadeclassifiers\\cars.xml")
#start capturing video feed
video_footage = cv2.VideoCapture("SampleVideos\\samplevid.mp4")
while(video_footage.isOpened()):
ret, frame = video_footage.read()
if ret:
#search the... |
"""File containing all definitions and functions for git commands used by pyautogit.
This file should remain separate from the CUI interface.
Author: Jakub Wlodek
Created: 01-Oct-2019
"""
import os
from os import environ
import re
import shutil
import stat
from sys import platform
from subprocess import Popen, PIP... |
"""
Entry point to {{tgi}} features.
"""
import asyncio
import logging
from contextlib import asynccontextmanager
from time import time
from typing import AsyncGenerator
from typing import cast
from typing import List
from typing import Optional
from typing import Union
from pyrogram import Client
from pyrogram import... |
# -*- coding: utf-8 -*-
import psycopg2
from .abstract import Runner
from ..models import Query
class PostgresqlRunner(Runner):
def __init__(self, query: Query):
super().__init__(query)
self._conn = None
def connect(self):
self._conn = psycopg2.connect(
host=self.server... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import numpy as np
from inspect import getsourcefile
from time import time
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers.recurrent import GRU
from casket.experiment import Experiment
def load_data(data, steps=4):
... |
from typing import List, Tuple
import sys
# Constant definitions
sys.setrecursionlimit(10000)
MAZE_PATH = "./week_four/pac_man/maze.txt"
def print_maze():
for row in maze:
for char in row:
print(char, end="")
print()
def find_ghosts(maze: List[List[str]]) -> List[Tuple[int, int]]:
... |
from abaqusConstants import *
class ConstrainedSketcherOptions:
"""The ConstrainedSketcherOptions object is used to store values and attributes which will
be applied to all sketches used in the current session. The ConstrainedSketcherOptions
object has no constructor.
Notes
-----
This objec... |
import sys
sys.path.append('.')
sys.path.append('..')
from models.carlaEmbeddingDataset import CarlaOnlineEmbeddingDataset, PadSequence, CarlaEmbeddingDataset
from models.TemporalEncoder import RNNEncoder, VanillaRNNEncoder, SequenceRNNEncoder
import argparse
import wandb
def train(args):
device = args.device
... |
import unittest
import logging
import numpy as np
from src.boundary_conditions import inlet, outlet, moving_wall, rigid_wall, periodic_with_pressure_variations
from src.lattice_boltzmann_method import equilibrium_distr_func
class TestMassPreservation(unittest.TestCase):
def setUp(self) -> None:
logging.ba... |
import threading
from time import sleep
import serial
#from aruco_calculations import ArucoCalculator
from codeListener import codeListener
from ultraSensor import ultraSensor
# Global variables
condition = threading.Condition()
printSem = threading.Semaphore()
serialSem = threading.Semaphore()
# size in meters of ar... |
# Imports
import numpy as np
import pandas as pd
import os
import time
from itertools import permutations, combinations
from IPython.display import display
# this will display the max column width so we can see the associations involved....
pd.set_option('display.max_colwidth', None)
pd.set_option('display.max_colum... |
from django.http import HttpResponse
from django.template import loader
def customer_weekly(request, site_id):
template = loader.get_template('customer_weekly.html')
context = {
# 'site_id' : site_id,
}
return HttpResponse(template.render(context, request))
def serve_svg(request):
template ... |
"""Sample app."""
from aws_cdk import aws_sns as sns
from aws_cdk import core
class MyStack2(core.Stack): # pylint: disable=too-few-public-methods
"""My stack."""
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
"""Instantiate class."""
super().__init__(scope, id, **kwar... |
"""N-wave component"""
import numpy as np
def MachNumber(v):
'''
Calculate Mach number
Parameters:
----------------
v -- Speed of projectile (float)
Returns:
----------------
M -- Mach number (float)
'''
csnd = 341.0
M = v/csnd
return M
def coneAngle(M):
'''
... |
#!/user/bin/env python
'''ligandInteractionFIngerprint.py
Finds interactions between ligands and polymer chains and maps them onto polymer sequences.
'''
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@gmail.com"
__version__ = "0.2.0"
__status__ = "done"
fro... |
from pathlib import Path
from typing import Optional
from langworld_db_data.adders.adder import Adder, AdderError, AUX_ROW_MARKER, SEPARATOR
from langworld_db_data.constants.paths import FILE_WITH_CATEGORIES, FILE_WITH_NAMES_OF_FEATURES
from langworld_db_data.filetools.csv_xls import read_csv, write_csv
from langworld... |
# coding=utf-8
import os
import base64
import platform
import json
if platform.system() == 'Darwin':
try:
import crypto
import sys
sys.modules['Crypto'] = crypto
except ImportError:
pass
from Crypto.Cipher import AES
# https://github.com/darknessomi/musicbox/wiki/网易云音乐新版WebA... |
import abc
from cosmogrb.lightcurve.light_curve_storage import LightCurveStorage
from cosmogrb.utils.logging import setup_logger
logger = setup_logger(__name__)
class LightCurveAnalyzer(object, metaclass=abc.ABCMeta):
def __init__(self, lightcurve, instrument):
assert isinstance(lightcurve, LightCurveS... |
import os, sys
from map import Map
from window import Window
from geom import newLine
from event_handler import EventHandlerMouse
class Map_editor:
def __init__(self, name_map):
self.window = Window()
self.map = Map(name_map)
self.event_handler = EventHandlerMouse()
self.window.dr... |
# Quick Union (Lazy approach)
# Created by: Mohammed Mounir, Bouhamed
# Date: July 17, 2021
class QuickUnionQU:
def __init__(self, n):
self.id = list(range(n))
def root(self, i):
while self.id[i] != i:
i = self.id[i]
return i
def connected(self, p, q):
return... |
class ConTextGraph:
def __init__(self, remove_overlapping_modifiers=False):
self.targets = []
self.modifiers = []
self.edges = []
self.remove_overlapping_modifiers = remove_overlapping_modifiers
def update_scopes(self):
"""Update the scope of all ConTextModifier.
... |
from django.apps import AppConfig
class PatternForConfig(AppConfig):
name = 'pattern_for'
verbose_name="Настройка разделов для бизнеса , для государства"
verbose_name_plural="Настройка разделов для бизнеса , для государства"
|
#!/usr/bin/env python3
#
## @file setup.py
#
# Copyright (c) 2017 - 2020, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
from setuptools import setup
setup(name='edkrepo',
version='2.0.0',
description='The edkrepo tools',
packages=['edkrepo'... |
# Generated by Django 2.2.7 on 2019-11-20 19:31
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('Pedido', '0042_remove_suporte_data_mensagem'),
]
operations = [
migrations.AddField(
model_name='su... |
"""
This test verifies that vtk's Xdmf reader will read a sampling of small
to moderate size data files that cover a spectrum of file format features.
"""
from __future__ import print_function
import sys
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
smallFiles = [
... |
import json
import sys
import os
def get_index_names_from_stats(stats):
index_names = {}
for k in stats:
if k.startswith(bucket):
iname = k.split(":")[-2]
if iname not in index_names:
index_names[iname] = True
return index_names.keys()
def run(filename, bucket, pstat):
f = open(filename, "r")
i = 0
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# from torch import einsum
# from einops import rearrange, repeat
from PCT_Pytorch.pointnet2_ops_lib.pointnet2_ops import pointnet2_utils
# from pointnet2_ops import pointnet2_utils
def get_activation(activation):
if activation.lower() == 'gelu'... |
def fun(a, b, k=None, *argc, **kwargs):
pass
def fun(a, b, k=None, *argc, fail=failure, **kwargs):
pass
|
#!/usr/bin/env python3
import os
import subprocess
packages = [
"curl",
"default-jdk",
]
SCRIPT_DIR = os.path.realpath(os.path.dirname(__file__))
TOMCAT_DIR = os.path.join('/opt', 'tomcat')
TOMCAT_SERVICE_PATH = os.path.join('/etc', 'systemd', 'system', 'tomcat.service')
DEFAULT_TOMCAT_TAR = "https://archive... |
d = {'k1':[11,12,13],'k2':[21,22,23],'k3':[[311,312,313],32,33]}
for k in d.keys():
print(k)
print(d[k][0])
print(d['k3'][0][2]) |
'''
References:
- Symbolic Logic, Copi, p.33, 396
'''
from typing import List, Tuple, Callable
from .lang import (
PropositionalVariable,
Wff, PropVarWff, ImplWff, ConjWff, DisjWff, NegWff)
from .proof import Inference, Application, Line
def find_proposional_patterns(premises: List[Wff],
... |
#boids.py
"""
Explores flocking behavior of flying "boids" aka "bird android".
Requires Python (www.python.org), my favorite programming language, and
and VPython (www.vpython.org), a fine Python graphics simulation extension for beginners.
Thanks to Conrad Parker conrad@vergenet.net for the boids pseudocode.
... |
from datetime import date, timedelta
import factory
from ..database import db
from ..core.models import Entry, Log
class BaseFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
abstract = True
sqlalchemy_session = db.session
class LogFactory(BaseFactory):
name = factory.Sequence(... |
from unittest import mock
import pytest
from core.config import Configuration
from core.configservice.base import (
ConfigService,
ConfigServiceBootError,
ConfigServiceMode,
)
from core.emulator.enumerations import ConfigDataTypes
from core.errors import CoreCommandError, CoreError
TEMPLATE_TEXT = "echo ... |
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain r... |
import numpy as np
import torch
import anndata
from celligner2.othermodels.trvae.trvae import trVAE
from celligner2.trainers.trvae.unsupervised import trVAETrainer
def trvae_operate(
network: trVAE,
data: anndata,
condition_key: str = None,
size_factor_key: str = None,
n_epoch... |
import autograd.numpy as np
import tensorflow as tf
import torch
import pymanopt
from examples._tools import ExampleRunner
from pymanopt.manifolds import Oblique
from pymanopt.optimizers import TrustRegions
SUPPORTED_BACKENDS = ("autograd", "numpy", "pytorch", "tensorflow")
def create_cost_and_derivates(manifold, ... |
# This is a bare-bones test to ensure that there are no crashes, dead-locks, and to test performance.
# The actual client test suite is language agnostic and available in a different repository.
from nolog.io import NoLog
import time
import gc
import sys
from multiprocessing import Pool
def work(i):
executionBlock1 ... |
import unittest
from app.models import Comment
class TestUsers(unittest.TestCase):
'''
Test class that defines the test cases for the behaviour of the Users class.
Args:
unittest.TestCase: Test case class that helps in creating test cases.
'''
def setUp(self):
'''
Setup meth... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QSizePolicy
class Ui_SerialBox(object):
def setupUi(self, serialBox):
serialBox.setObjectName("serialBox")
self.centralWidget = QtWidgets.QWidget(serialBox)
self.centralWidget.setObjectName("centralWidget")... |
# ---------------------------------------------------------------
# base_caption_head.py
# Set-up time: 2021/1/2 17:05
# Copyright (c) 2020 ICT
# Licensed under The MIT License [see LICENSE for details]
# Written by Kenneth-Wong (Wenbin-Wang) @ VIPL.ICT
# Contact: wenbin.wang@vipl.ict.ac.cn [OR] nkwangwenbin@gmai... |
# -*- coding: utf-8 -*-
"""
Django settings for milmove_admin project.
Generated by 'django-admin startproject' using Django 3.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/r... |
kilometerUnit = 'km'
def milesToKm(miles):
return miles / 0.62137 |
# list performance for all groups
res = client.get_file_systems_groups_performance(file_system_names=["fs1"])
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# list performance for one group
res = client.get_file_systems_groups_performance(file_system_names=["fs1"],
... |
#Python | Messagec using Tkinter
# import tkinter module
from tkinter import *
# import other necessery modules
import random
import time
import datetime
# creating root object
root = Tk()
# defining size of window
root.geometry("1200x6000")
# setting up the title of window
root.title(" Encrypti... |
# 1st solution
# O(n) time | O(1) space
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x, y = 0, 0 # location
dx, dy = 0, 1 # direction
for ch in instructions:
if ch == "G":
x += dx
y += dy
elif ch == "L":
... |
t=int(input())
for i in range(t):
s=input()
ls=s.split("#")
day=0
max=0
for x in ls:
if len(x)>0:
if len(x)>max:
max=len(x)
day=day+1
print(day)
|
import json
import base64
def serialize(value):
return base64.b64encode(json.dumps(value).encode("utf-8")).decode("utf-8")
def deserialize(value):
return json.loads(base64.b64decode(value).decode("utf-8"))
|
class ImproperConfiguredException(Exception):
def __init__(self, key_path):
self.key_path = key_path
super(ImproperConfiguredException, self).__init__()
def __repr__(self):
return "<ImproperConfiguredException: %s>" % self.key_path
def __str__(self):
return "ImproperConfi... |
# pylint: disable=missing-docstring, maya-short-flag, invalid-name, unused-argument
"""Symmetry stuff.
:created: 14/01/2019
:author: Benoit GIELLY <benoit.gielly@gmail.com>
"""
from functools import partial
from PySide2 import QtWidgets
from maya import cmds
import pymel.core as pm
import pymel.core.datatypes as dt
i... |
from .base_element import BaseElement
from .....library.utils.datamodel import Element
class TimeFrame(BaseElement):
def __init__(self, element: Element):
super().__init__(element)
@property
def start(self):
return self._element['start']
@property
def duration(self):
retu... |
from micooc import new_build, build_stats, latest_build_stats
def test_new_build():
service_host = "http://localhost:8123"
engine_host = service_host + "/engine"
api_key = "AK005fca5cbc9779755f"
pid = "PIDc3ac134737084e6596e52b8de1d4be39"
build_version = "5fafc0478af24af2da45fa19ddd06c17dd5d0d45"... |
#!/usr/bin/env python
# -*- coding: windows-1252 -*-
import os
import struct
import array
import mmap
from rhCompression import lzss
PATH_SUBTITLES = "./subtitles/out-ptbr"
PATH_OUTPUT = "./subtitles/ptbr"
def vertical(buffer):
c = ''
for y in range(8)[::-1]:
c += buffer[4*y:4*(y+1)]
return c
d... |
# Generated by Django 3.2 on 2021-04-14 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('arkyris_api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='entry',
name='deleted',
f... |
# Import matplotlib.pyplot with alias plt
import matplotlib.pyplot as plt
# Look at the first few rows of data
print(avocados.head())
# Get the total number of avocados sold of each size
nb_sold_by_size = avocados.groupby('size')['nb_sold'].sum()
# Create a bar plot of the number of avocados sold by size
nb_sold_by_... |
import os
from setuptools import setup
lib_folder = os.path.dirname(os.path.realpath(__file__))
requirementPath = lib_folder + '/requirements.txt'
install_requires = []
if os.path.isfile(requirementPath):
with open(requirementPath) as f:
install_requires = f.read().splitlines()
setup(
name='extract_x... |
# Pandas
from pandas import DataFrame
# Visualization
from altair import Chart
# Local
from .interactive import interactive_tooltip_chart
def create_chart(
dataframe: DataFrame,
y_column: str = "percentage",
color_column: str = None,
stroke_dash: str = None,
interactive: bool = True,
) -> Chart:... |
import torch
from torch import nn
from utils.utils import compute_conv_output_img_dims
def test_compute_conv_dims_out():
for width_img in [63, 64, 65, 66]:
dims_img = (width_img, width_img)
inp = torch.randn((10, 1,) + dims_img)
for padding in [0, 1, 2]:
for dilation in [1, 2,... |
# 2020 Tommaso Ciussani and Giacomo Giuliari
from typing import Tuple, List
from icarus_simulator.strategies.grid.base_grid_strat import BaseGridStrat
from icarus_simulator.strategies.base_strat import BaseStrat
from icarus_simulator.strategies.grid_weight.base_weight_strat import BaseWeightStrat
from icarus_simulat... |
from file_with_function import add_strings
name = add_strings("ajay", "gollapalli")
print(name)
|
"""
Zachary Cook
Helper script for deploying services.
"""
from DeployImplementations import AutoDeploy
from DeployImplementations import BaseDeploy
# Run the program.
if __name__ == '__main__':
# Get the services to deploy.
deployObject = AutoDeploy.getDeploy()
servicesToDeploy = deployObject.getServic... |
import matplotlib.colors as mcolors
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import networkx as nx
from tom.tom import Train, TrainRun
def get_color_for_section(section):
cmap = mcolors.CSS4_COLORS
return cmap.get(section.color,
cmap['black'])
def annotate_train... |
import numpy as np
from scipy.stats import norm
from edge import Simulation
from edge.agent import SafetyLearner
from edge.envs import Hovership
from edge.model.safety_models import SafetyTruth, MaternSafety
from edge.graphics.plotter import SafetyPlotter, DetailedSafetyPlotter
class OptimisticSimulation(Simulation)... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.pyx import pyx
def test_pyx():
"""Test module pyx.py by downloading
pyx.csv and testing shape of
extracted data has 72 rows and 4 columns
... |
from entities.ships.allies.aegis import Aegis
from entities.ships.allies.archer import Archer
from entities.ships.allies.citadel import Citadel
from entities.ships.allies.longsword import Longsword
from entities.ships.enemies.arbitrator import Arbitrator
from entities.ships.enemies.crucible import Crucible
from entitie... |
# Ulab is a numpy-like module for micropython, meant to simplify and speed up common
# mathematical operations on arrays. This basic example shows mean/std on an image.
#
# NOTE: ndarrays cause the heap to be fragmented easily. If you run out of memory,
# there's not much that can be done about it, lowering the resolut... |
from ..completer.websocket_completer import WebSocketCompleter
from ..prompt.prompt import Prompt
from ..runner.websocket import WebSocket
class WebSocketPrompt(Prompt):
def __init__(self, url):
super().__init__(url, WebSocket(url), WebSocketCompleter())
|
import matplotlib.pyplot as plt
import numpy as np
# time domain in which we sample
x = np.linspace(0, 20, 50)
# random function to simulate sampled signal
y = np.sin(x + 1) + np.cos(x ** 2)
# here we can setup baseline position
bottom = -0.1
# True -- hold current axes for further plotting
# False -- opposite. ... |
import pytest
from pathlib import Path
from repo_link import parse, RepoData
@pytest.mark.parametrize(
["link", "data"],
[
(
"https://github.com/erikrose/more-itertools/blob/master/more_itertools/recipes.py#L74",
RepoData(
path="more_itertools/recipes.py",
... |
from .items import Item, ShopItem
from .antiCaptcha import AntiCaptcha
from FoodScan.ShopList.ShoppingLists.BringList import BringList |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
# This turns on e.g. the filename-based detection of which
# platforms to include source files on (e.g. files ending in
# _mac... |
from __future__ import absolute_import, unicode_literals
import celery
import os
from common.helpers import read_dotenv
read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uclapi.settings')
class Celery(celery.Celery):
def on_configur... |
"""Scraper for http://www.football-data.co.uk/data.php."""
import itertools
from pathlib import Path
from typing import List, Optional, Union
import pandas as pd
from ._common import BaseReader, make_game_id
from ._config import DATA_DIR, NOCACHE, NOSTORE, TEAMNAME_REPLACEMENTS
MATCH_HISTORY_DATA_DIR = DATA_DIR / 'M... |
# Exercício 3.6 Escreva uma expressão que será utilizada para decidir se um aluno foi
# ou não aprovado. Para ser aprovado, todas as médias do aluno devem ser maiores
# que 7. Considere que o aluno cursa apenas três matérias, e que a nota de cada uma
# está armazenada nas seguintes variáveis: matéria1, matéria2 e ma... |
from .load import (
load_from_directory,
load_from_paths,
load_original_text_from_directory,
load_transcription_text_from_directory,
)
|
# Generated by Django 3.1.6 on 2021-10-24 03:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jrecomments', '0002_auto_20211023_0142'),
]
operations = [
migrations.AddField(
model_name='comment',
name='name',
... |
from pyspark.sql.functions import col
from sparkdq.analytics.Preconditions import has_column, is_string
from sparkdq.repairs.transformers.filters.Filter import Filter
from sparkdq.structures.ConstrainableDataTypes import ConstrainableDataTypes
from sparkdq.utils.RegularExpressions import FRACTIONAL, INTEGRAL, BOOLEAN
... |
import argparse
import random
# configs
NUM_OF_LEVELS = 1
LEVEL_PREFIX = "lev_"
MIN_NUM_OF_PIECES = 5
MAX_NUM_OF_PIECES = 8
MIN_BOARD_SIZE = 6
MAX_BOARD_SIZE = 8
MIN_PIECE_SIZE = 1
MAX_PIECE_SIZE = 2
MOD_VALUE = 3
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def __st... |
# The MIT License (MIT)
#
# Copyright (c) 2016 Adafruit Industries
#
# 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 the rights
# to use, cop... |
from nn.hh_ensemble_lookup import *
from nn.dictionary_store import *
from ann.hyperplane_hasher import HyperplaneHasher, NORMAL_VECTOR_ID, NUM_NORMAL_VECS_ID, CHAMBER_ID
import unittest, copy, string, numpy as np, random as rd, pandas as pd
RANK = 10
NAME = 'test_HHENL'
METRIC = 'l2'
NNV = 5
NHH = 4
NUM_VECS = 30
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.