content
stringlengths
5
1.05M
# Generated by Django 3.1.5 on 2021-05-29 16:07 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('admin', '0001_initial'), ] operations = [ migrations.CreateModel( ...
'''' plot the data from plotter.txt ''' import matplotlib.pyplot as plt import sys from os import path # Check the command line arguments if len(sys.argv) < 2: sys.exit('Usage: %s [plotter.txt location]\nexample: %s ~/plotter.txt' % (sys.argv[0], sys.argv[0])) if not path.exists(sys.argv[1]): sys.exit('ERROR...
import pytest from mspasspy.global_history.ParameterGTree import ParameterGTree, parameter_to_GTree from mspasspy.util.converter import AntelopePf2dict from mspasspy.ccore.utility import MsPASSError, AntelopePf import json import os import yaml import collections from mspasspy.ccore.utility import MsPASSError, Antelope...
#!/usr/bin/python3,3 # -*- coding: utf-8 -*- """py2exe package """ from .version import __version__ from .patch_distutils import patch_distutils patch_distutils()
# Datasaurus dataset # Author: Drishtii import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import pyprobml_utils as pml url = 'https://raw.githubusercontent.com/probml/probml-data/main/data/DatasaurusDozen.tsv' df = pd.read_csv(url, sep='\t' ) df1 = df[df['dataset'] == 'dino'] df2 = df[df['dat...
# example of extrusion primitive # James Gregson (james.gregson@gmail.com), March 2013 # import module import pyPolyCSG as csg # create the poly-line describing the extrusion contour coords = [] coords.append( (0.0, 0.0) ) coords.append( (0.5, 0.5) ) coords.append( (2.0, 1.0) ) coords.append( (2.1, 0.0) ) # extrude ...
# #### 1. 三层简单神经网络 import tensorflow as tf # 1.1 定义变量 w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) # 设置了种子数据后可以保证每次生成的随机数相等 w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1)) x = tf.constant([[0.7, 0.9]]) # 1.2 定义前向传播的神经网络 a = tf.matmul(x, w1) y = tf.matmul(a, w2) # 1.3 调用会话输出结果 sess ...
import datetime import re DEFAULT_IMAGE_PATH='/home/pi/pictures' def eventkey(event): return event['timeofday'] + event['idx'] # Get all the days that this daemonlog has events for. def daemonlog_datelist(daemonlogfile): p = re.compile('([\d]+-[\d]+-[\d]+)-([\d:]+) received message (.*)') dates = set() ...
import json import os from glob import glob import fnmatch from logging import getLogger from chess_zero.config import ResourceConfig logger = getLogger(__name__) def find_pgn_files(directory, pattern='*.pgn'): files = [] for root, dirnames, filenames in os.walk(directory): for filename in fnmatch....
# Copyright (c) 2020 PaddlePaddle Authors. 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 required by appli...
import numpy as np def peak_effects(energies): """ This module checks to see if a given list of peak energies contains any possible single escape peaks, double escape peaks, and sum peaks. """ single_escape_peak = [] single_escape_peak_index = [] double_escape_peak = [] doub...
#%% train sac import os import gym import numpy as np from stable_baselines import SAC from stable_baselines.sac.policies import MlpPolicy from stable_baselines.sac.policies import LnMlpPolicy from stable_baselines.common.noise import NormalActionNoise from stable_baselines.bench import Monitor from stable_baselines.co...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import panel as pn from scipy import stats pn.extension('katex', 'mathjax') # # Tutorial 6 - Tutorial Problems on Flow in Confined/Unconfined Aquifer # # # + **solutions for homework problems 3...
from the_water_project.tags.models import Tag from django.test import TestCase class TestModels(TestCase): def test_tag_models(self): Tag.objects.create(name="water") Tag.objects.create(name="sanitation") self.assertEqual(Tag.objects.count(), 2) self.assertEqual(Tag.objects.get(id=...
import base64 import json import sys from socket import * from blockchain import * from validator import Valid from ast import literal_eval from logging import DEBUG, ERROR, INFO from log import LoggyLogglyMcface from security import * from cryptography.fernet import Fernet from cc_interface import PortugueseCitizenC...
import os import secrets from PIL import Image from django.db import models from django.contrib.auth.models import User, AbstractUser, Group, BaseUserManager from django.utils.translation import gettext_lazy as _ from django.conf import settings from django.utils import timezone from daira.models import Mol7aka def...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import time from django.conf import settings from ralph.util import plugin from ralph_pricing.splunk import Splunk from ralph_p...
import os from setuptools import find_packages, setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-webgate', version='1.0.1', packages=find_packages...
#!/usr/bin/env python3 """ DEVELOPMENT ONLY Serves the site with a development Flask server. """ import flask app = flask.Flask(__name__, static_folder="build/static") @app.route("/") def index(): return flask.send_file("build/index.html") @app.route("/<path:path>") def other(path): return flask.send_fr...
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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 a...
import numpy as np from xplique.features_visualizations.losses import cosine_similarity from ..utils import almost_equal def test_cosine_similarity(): vec = np.array([10.0, 20.0, 30.0])[np.newaxis, :] vec_colinear = np.array([1.0, 2.0, 3.0])[np.newaxis, :] vec_orthogonal = np.array([.0, .0, .0])[np.newax...
""" IO managers for QCodes. IO managers wrap whatever physical storage layer the user wants to use in an interface mimicking the built-in <open> context manager, with some restrictions to minimize the overhead in creating new IO managers. The main thing these managers need to implement is the open context manager: -...
from __future__ import print_function import argparse import torch.backends.cudnn as cudnn # import time,datetime from common import * from dataset_img2vox import * from model import * parser = argparse.ArgumentParser() parser.add_argument('--dataRoot', type=str, default='/data/dudong/ShapeNetCore.v1', help='data root...
from abc import abstractmethod from .module import ModuleProvider from .proto import ProtoShell, ProtoCmd from .config import Config class FolderProvider(ModuleProvider): @abstractmethod def get_name(self): pass @abstractmethod def get_path(self): pass @abstractmethod def is...
"""Copyright 2012 Phidgets Inc. This work is licensed under the Creative Commons Attribution 2.5 Canada License. To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/ """ __author__ = 'Adam Stelmack' __version__ = '2.1.8' __date__ = 'May 17 2010' import threading from ctypes ...
"""Simple URL builder.""" __version__ = "4.0.1" from .builder import BuildURL
import re IP_ADDRESS_RE = re.compile( r"^([1-9]\d{0,2}|0)\.([1-9]\d{0,2}|0)\.([1-9]\d{0,2}|0)\.([1-9]\d{0,2}|0)$") def convert_ip(host): match = IP_ADDRESS_RE.match(host) if not match: raise ValueError( "Ip address string required, got {!r}".format(host)) parts = list(map(int, matc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 2D linear elasticity example Solve the equilibrium equation -\nabla \cdot \sigma(x) = f(x) for x\in\Omega with the strain-displacement equation: \epsilon = 1/2(\nabla u + \nabla u^T) and the constitutive law: \sigma = 2*\mu*\epsilon + \lambda*(\nabla\cdot u)I,...
# from .backbones import * # noqa: F401,F403 from .builder import (DISTILL_LOSSES, CLASSIFIERS, HEADS, build_classifier, build_head, build_distill_losses) from .classifiers import * # noqa: F401,F403 from .heads import * # noqa: F401,F403 from .distillation_losses import * # noqa: F401,F403 ...
# -*- coding: utf-8 -*- """ Conference class - along with its list class """ from plivo.base import PlivoResource, PlivoResourceInterface from plivo.utils import to_param_dict from plivo.utils.validators import * class ConferenceMember(PlivoResource): _name = '' _identifier_string = 'member_id' class Confer...
import abc import typing from typing import ( List, Optional, Tuple, ) from .session import ( Session, ) from .types import ( Label, Number, NumberT, Vector, ) if typing.TYPE_CHECKING: from .ops import ( # noqa: F401 Add, Sub, Mul, Div, ) def ...
"""Plugin that installs a Jinja extension for declaring functions inline.""" __all__ = [ "InlineFunctions", ] from typing import Any from jinja2.ext import Extension from jinja2.nodes import DerivedContextReference # type: ignore from jinja2.nodes import CallBlock, Node from beet import Context, Function fro...
""" Process the data downloaded from original source """ import h5py import os import pickle import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import seaborn as sns sns.set() def process_data(): """ Extracts the SBP and DBP values of 10 seconds long episodes while taking new episodes 5 s...
import pytest from bimini.types import ( ArrayType, BitType, BoolType, ByteType, BytesType, FixedBytesType, ContainerType, ScalarType, OptionalType, TupleType, UnsignedIntegerType, ) from bimini.grammar import parse t_bit = BitType() t_bool = BoolType() t_byte = ByteType() ...
from __future__ import print_function from __future__ import absolute_import from builtins import str from builtins import range import command_line_execution_tools as ce import mermaid.module_parameters as pars import os import shutil def _make_arg_list(args): arg_list = [] for k in args: arg_list...
import datetime import os import sys import click import pandas as pd from copy import deepcopy from collections import defaultdict from planning_system.db import DB from planning_system.api.functions import bulk_insert from planning_system.db.schema.tables.survey import \ SurveyInst, Question, QuestionOption, Resp...
import numpy import plotly.graph_objects as go ee_timings = [] vf_timings = [] with open("ccd-timings.txt", "r") as file: for line in file: stripped_line = line.strip() if stripped_line[:2] == "EE": ee_timings.append(float(stripped_line.split()[1])) elif stripped_line[:2] == "V...
import json import sys import time from datetime import datetime from dataclasses import dataclass, field from dataclasses_json import dataclass_json, config from marshmallow import fields from touchstone_auth import TouchstoneSession from typing import Optional, List def mk_optional_datetime_field(): return field...
# Generated by Django 4.0.2 on 2022-03-07 04:02 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('events', '0001_initial'), migrations.swappable_dependency(setti...
# -------------------------------------------------------- # DaSiamRPN # Licensed under The MIT License # Written by Qiang Wang (wangqiang2015 at ia.ac.cn) # Revised for THOR by Axel Sauer (axel.sauer@tum.de) # -------------------------------------------------------- from yacs.config import CfgNode as CN class Tracker...
import sys from os.path import join, dirname, abspath from unittest import TestCase import phi import phi.vis._vis_base as display from phi.field import Field from phi.math.backend import Backend DEMOS_DIR = join(dirname(dirname(dirname(abspath(__file__)))), 'demos') BACKENDS = list(phi.detect_backends()) BACKENDS = ...
from django.contrib import admin from .models import Profile # Models registration admin.site.register(Profile)
import os import shutil import json from collections import OrderedDict from liquidcss.settings import Settings from liquidcss.utils import create_file_key, create_file_hash class Structure(object): def __init__(self, base_dir, base_folder_name): self.base_folder_name = base_folder_name self.bas...
# imports import sys import argparse from gaevol import gaevol parser = argparse.ArgumentParser(description="Enter string you want to see evolve:") parser.add_argument("string", help="Add string without number and special characters") parser.add_argument("populate", help="Enter poplation of each Generation") parser.ad...
import numpy as np import struct import math # let us use input in python 2.x. try: input = raw_input except NameError: pass # split something into chunks def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] def unpack(buffer): return unpack_buffer(list(chunks(buffer, 2))) def unpack_buffe...
#!/usr/bin/env python """Test fixtures and utilities.""" # Copyright 2016 Vincent Ahrend # 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 ...
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Loading data into array from text file data = np.genfromtxt(path, delimiter=",",skip_header =1) print("\nData: \n\n",data) pr...
import torch from torch.utils.data import DataLoader import argparse import sys, os import numpy as np import main.dataset as dataset import main.wrapper as wrapper from main.myclasses import MODEL, METADATA, DATASET from main.utils import TRAINING_LOSS from main.evaluation import average_precision, NDCG_F from main.z...
from unittest import TestCase from Conundrum.repeated_letters import decrypt, decrypt_try_all encrypted_msg = 'hello world' decrypted_msg = 'helworl' class RepeatedLettersTestCase(TestCase): def test_that_letters_after_repeated_letters_are_removed(self): self.assertEqual(decrypted_msg, decrypt(encrypted...
from pytest import raises from pype.fgir import * one_tree = Flowgraph('test_fgir') test_fgir_A = one_tree.new_node(FGNodeType.unknown, 'x') test_fgir_B = one_tree.new_node(FGNodeType.unknown, 'y') test_fgir_C = one_tree.new_node(FGNodeType.unknown, 'n2') test_fgir_D = one_tree.new_node(FGNodeType.unknown, 'z') test...
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and relat...
import argparse import cv2 import numpy as np from c64_palette import get_palette from c64_palette import palettes from dithering_models import dithering_models from dithering_models import get_dithering_model color_map = [] color2_map = [] def init_colors(palette): print("Initialize colors #1") for y in r...
__author__ = 'Calle' from builtins import bytes, str, filter, map import unittest from zetacrypt import ciphers, utility from zetacrypt.conversions import * from collections import OrderedDict class TestXORFunctions(unittest.TestCase): def test_single_byte_xor(self): plaintext = ascii_to_bytes...
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-11-25 16:14 import os import shutil import sys from collections import defaultdict from os import listdir from os.path import join, isfile from typing import List from phrasetree.tree import Tree from hanlp.components.parsers.conll import read_conll from hanlp.util...
import tensorflow as tf def chamfer_distance(S1, S2, N): S1 = tf.tile(tf.expand_dims(S1, axis=-2), [1, 1, N, 1]) S2 = tf.tile(tf.expand_dims(S2, axis=1), [1, N, 1, 1]) return tf.reduce_sum(tf.reduce_min(tf.reduce_sum(tf.square((tf.subtract(S1, S2))), axis=-1), axis=-1)) def chamfer_loss(Y, Y_cap, N): xy_dis = ch...
#!/usr/bin/env python3 ipchk = input('Apply an IP address: ') # this line now prompts the user for input if ipchk: # if any data is provided, this will test true print('Looks like the IP address was set: ' + ipchk) # indented under if
import sys import math import numpy as np # Determining the velocity: # In the normal case, we use a domain with stretching from 0 to 1 with 256 # cells; this gives a dx = 1. / 256 . We also know that the interval of time # that we allow the cloud to evolve over is dt = 0.25 . Additionally, we can # compute the sound...
""" 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是...
# coding: utf-8 from __future__ import absolute_import from flask import json from six import BytesIO from swagger_server.models.process_response import ProcessResponse # noqa: E501 from swagger_server.models.text import Text # noqa: E501 from swagger_server.models.text_query import TextQuery # noqa: E501 from sw...
# # This file is part of PKPDApp (https://github.com/pkpdapp-team/pkpdapp) which # is released under the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and full license details. # from rest_framework import status from rest_framework.test import APITestCase, APIClient from django.contrib.auth....
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """RESISC45 dataset.""" import os from typing import Callable, Dict, Optional, cast import matplotlib.pyplot as plt import numpy as np from torch import Tensor from .geo import VisionClassificationDataset from .utils impor...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-17 14:06 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('focus', '0005_auto_20171029_2018'), ] operations = [ migrations.RenameField( ...
# Copyright 2014 Dirk Pranke. 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 required by applicable law or a...
# Copyright 2018 The TensorFlow Authors. 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 required by applica...
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.signal import medfilt, savgol_filter import scipy.interpolate from scipy.spatial import distance from librosa.sequence import dtw # only need the 'dtw' function from the librosa...
from car import ElectricCar my_tesla = ElectricCar("Tesla", "modelX", 2020) print(my_tesla.get_describe_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
def reverse(n): rev = 0 while(n > 0): rem = n %10 rev = (rev *10) + rem n = n//10 return rev def palin(n): iterations = 0 s = str(n) while (iterations < 5): n=n+reverse(n) print(n) if s[:1]==s[-1:][::-1]: print(n) return Tr...
from setuptools import setup setup(name='SentiStock', version='0.2', description='Better Stock market recommendation using the Web', author='Mevin Babu', author_email='mevinbabuc@gmail.com', url='http://www.python.org/sigs/distutils-sig/', install_requires=['web.py>=0.36', 'Jinja2','nltk','...
''' The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,...
import pickle import os my_path = os.path.abspath(os.path.dirname(__file__)) data_dir = os.path.join(my_path, 'data_files') x11_path = os.path.join(data_dir, 'x11_colours.pickle') svg_path = os.path.join(data_dir, 'svg_colours.pickle') colour_schemes_path = os.path.join(data_dir, 'colour_schemes.pickle') with open(fil...
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df_gasolina_sp = pd.read_csv('gasolina.csv', sep=',') with sns.axes_style('whitegrid'): grafico = sns.lineplot(data=df_gasolina_sp, x='dia', y='venda', palette='pastel') grafico.set(title='Preço médio gasolina em SP nos 10 primeir...
import argparse import logging import os import torch import torch.distributed as dist import torch.nn.functional as F import torch.utils.data.distributed from torch.nn.utils import clip_grad_norm_ from torch.utils import data import losses from backbones import get_model from dataset import MXFaceDataset, SyntheticDa...
# -*- coding: utf-8 -*- __all__ = ["find_pairs"] import random import itertools import networkx as nx def find_pairs(emails, previous_pairs, shuffle=False, group_map=None): """Find a set of pairings that have not previously been suggested This implementation is based closely on the implementation from the ...
def render_graph_testTAA(): testTAA = RenderGraph("ForwardRenderer") DepthPass = RenderPass("DepthPass", {'depthFormat': ResourceFormat.D32Float}) testTAA.addPass(DepthPass, "DepthPass") SkyBox = RenderPass("SkyBox") testTAA.addPass(SkyBox, "SkyBox") ForwardLightingPass = RenderPass("ForwardLigh...
from dataclasses import dataclass, field as datafield from typing import List, Dict from pal.logger import logger from pal.model.register import Register from pal.model.fieldset import Fieldset from pal.model.access_mechanism import AbstractAccessMechanism @dataclass class IntelRegister(Register): """ Models a r...
""" Atmosphere service compute. """ from threepio import logger from rtwo import settings from rtwo.provider import AWSProvider, EucaProvider, OSProvider from rtwo.driver import EucaDriver, AWSDriver from libcloud.common.types import InvalidCredsError OSProvider.set_meta()
from db.harvest.MsgBase import MsgBase class MsgCANCEL_ASC(MsgBase): """Methods for cancelling AIRMET SIGMET CWA (ASC) messages. """ def __init__(self): """Initialize. """ # All message types must indicate the actual dictionary # 'type' handled super().__init__(['CA...
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Checkbox(Component): """A Checkbox component. Material UI Checkbox component Keyword arguments: - id (string; required): The element's ID. - checked (boolean; default False): Checkbox is ...
from unittest import TestCase import unittest from python_back_end.pipelines_fixture import ToDiscComparer class TriangleTablePipelineTest(TestCase): def testTableTrianglePipeline(self): inputs = [ #Add xls or xlsx example files here ] for in_tup in inputs: ...
from is_isogram import is_isogram import unittest class Test(unittest.TestCase): def test_1(self): result = is_isogram("isogrami") self.assertEqual(result, False) def test_2(self): result = is_isogram("isogram") self.assertEqual(result, True) def test_3(self): res...
import rospy import tf import numpy from sensor_msgs.msg import LaserScan, Image from geometry_msgs.msg import Twist, PoseStamped, Quaternion, Point from nav_msgs.msg import Odometry import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from convert import image_to_numpy from tf.transformations i...
#!/usr/bin/python3 """ GUI program for LSB Steganography in Python 3 Requirements: PyQt5, OpenCV, NumPy, Crypography Author: Suman Adhikari GitHub: https://github.com/int-main """ from PyQt5 import QtCore, QtGui, QtWidgets import lsb_steganography as stego class Ui_MainWindow(object): #Function to display messag...
# coding: utf-8 import pprint import six from enum import Enum class Refund: swagger_types = { 'amount': 'float', 'base_line_items': 'list[LineItem]', 'completion': 'int', 'created_by': 'int', 'created_on': 'datetime', 'environment': 'Environment', 'e...
# Copyright (c) 2020 PaddlePaddle Authors. 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 required by appli...
# Copyright 2019 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import numpy as np def find_triangles_part_1(in_file): # read file f = open(in_file, 'r') lines = [] for l in f: l = l.replace('\n', '') lines.append(l) # remove last blank one if lines[-1] == '': lines = lines[:-1] lines = np.array(lines) possible_total = 0 # to...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name="corpus-sampling", version="1.0.0", description="Corpus sampler", long_description="Corpus sampler", python_requires=">=3.7.0", install_requires=["nltk"], packages=find_packages(), include_package_data=Tru...
from rest_framework.routers import DefaultRouter from accounts.api.views import AccountViewSet accounts_router = DefaultRouter() accounts_router.register( prefix='accounts', basename='accounts', viewset=AccountViewSet )
#!/usr/bin/env python # Light each LED in sequence, and repeat. import fastopc, time import numpy as np import functionLib as lib nStrips = 16 lStrip = 64 client = fastopc.FastOPC('localhost:7890') n = 1 dir = 1 pixels = lib.Pixels(nStrips, lStrip, 20) theoStrip = np.zeros([lStrip*nStrips,3]) color=2 theoStrip[n,...
#!/usr/bin/env python """ This code holds the solution for part 1 of day 9 of the Advent of Code for 2018. """ from collections import defaultdict, deque import sys def play(max_players, max_marbles): circle = deque([0]) player_scores = defaultdict(int) player_num = 0 for marble in xrange(1, max_mar...
import numpy as np import scipy.sparse from scipy.sparse import spmatrix, sputils from .base import _formats from .util import nbytes class hsb_matrix(spmatrix): """Horizontally Stacked Block matrix""" format = 'hsb' def __init__(self, blocks, dtype=None): ns, ms = zip(*[block.shape for...
from collections import Counter, defaultdict class Lanterfish(): def __init__(self, days=8): self.days_till_spawn = days # Days till spawning new lanterfish def spawn(self): if self.days_till_spawn == 0: self.days_till_spawn = 6 return True else: ...
#!/usr/bin/env python3 from build import ninja_common build = ninja_common.Build('vehicle-scripts') build.install("auv-env-set", "vehicle-scripts/auv-env/auv-env-set.sh")
"""final_model_controller controller.""" from math import pi from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import constants from controller import Robot, Motor, PositionSensor signum = lambda x: -1 if x < 0 else 1 # create the Robot instance. robot = Robot() # get...
import os, itertools, math # thanks google: http://christophe-simonis-at-tiny.blogspot.be/2008/08/python-reverse-enumerate.html def reverse_enumerate(it): return itertools.izip(reversed(xrange(len(it))), reversed(it)) def halign(string, width, align = "left", pad_char = " "): def line_halign_left(string, wi...
TOP_PERSON_PROPS_ARRAY_OF_KEY_SQL = """ SELECT groupArray(value) FROM ( SELECT value, {aggregate_operation} as count FROM events e INNER JOIN (SELECT person_id, distinct_id FROM person_distinct_id WHERE team_id = %(team_id)s) as pid ON e.distinct_id = pid.distinct_id INNER JOIN ( ...
import abc import asyncio import logging import logging.config import weakref from aiokts.store import Store class Command: def __init__(self, manager=None): self.logger = logging.getLogger( 'CmdLogger_{}'.format(self.__class__.__name__)) self._manager = weakref.ref(manager) if manage...
# from .base_zpconv import * from .base_so3conv import *
import mysql.connector as mysql from mysql.connector import Error import pandas as pd arquivo = pd.read_csv(r'C:/Users/monitor/Downloads/teste/teste.csv', skiprows=6, sep=';') df = pd.DataFrame(arquivo) try: conexao = mysql.connect(host='localhost', database='db_sm', user='root', password='douglas123') if c...
class Error(Exception): """Base class for exceptions in this module.""" pass class YoutubeIdMalformedError(Error): """Exception raised for errors in the input. Attributes: yt_id -- the malformed id message -- explanation of the error """ def __init__(self, yt_id: str, messag...