content
stringlengths
5
1.05M
# coding=utf-8 """Model filter change tests.""" import pytest from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.shortcuts import get_object_or_404 from django.test import TestCase, override_settings f...
"""Tests for JsonFirmwareUpdateProtocol.""" # Copyright 2019 WolkAbout Technology s.r.o. # # 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/LICEN...
# -*- coding: utf-8 -*- import json import gzip import numpy as np import nltk from inferbeddings.nli import util from inferbeddings.models.training.util import make_batches def evaluate(session, eval_path, label_to_index, token_to_index, predictions_op, batch_size, sentence1_ph, sentence2_ph, senten...
import os from JavaPropertiesLibrary.keywords import JavaPropertiesLibrary as jp def test_something(): my_jp = jp() my_jp.get_properties_file_content('./utests/test.properties') assert 1 == 1 def test_get_properties_file_content(): my_jp = jp() prop_path = os.path.abspath('./utests/test.propertie...
import os from OpenSSL import crypto from dotenv import load_dotenv load_dotenv() EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS") COMMON_NAME = os.getenv("COMMON_NAME") COUNTRY_NAME = os.getenv("COUNTRY_NAME") LOCALITY_NAME = os.getenv("CITY_NAME") STATE_OR_PROVINCE_NAME = os.getenv("PROVINCE_NAME") ORGANIZATION_NAME = os....
from pynubank.exception import NuException from pynubank.utils.http import HttpClient DISCOVERY_URL = 'https://prod-s0-webapp-proxy.nubank.com.br/api/discovery' DISCOVERY_APP_URL = 'https://prod-s0-webapp-proxy.nubank.com.br/api/app/discovery' class Discovery: def __init__(self, client: HttpClient): self...
"""Utilities for plotting.""" import numpy as np import warnings try: import matplotlib.pyplot as plt from matplotlib import artist from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d from mpl_toolkits.mplot3d.art3d import Line3D, Text3D, Poly3DCollection, Line3DCo...
import pytest from dagster import PipelineDefinition, execute_pipeline, pipeline, solid from dagster.core.errors import DagsterRunConflict from dagster.core.instance import DagsterInstance from dagster.core.snap.pipeline_snapshot import create_pipeline_snapshot_id from dagster.core.storage.pipeline_run import Pipeline...
#!/usr/bin/env python3 from .parser import Parser from .parser import PcapParser
import torch from hypothesis import given, settings from hypothesis import strategies as st from torch import nn as nn from torchdiffeq import odeint as odeint from dynamics_learning.networks.kalman.ekf import EKFCell from dynamics_learning.networks.models import SimpleODENetConfig from dynamics_learning.utils.net_uti...
import json from urllib.request import urlopen import numpy as np import scipy.optimize as opt def get_json_from_url(url): """Get a json from a URL.""" response = urlopen(url) return json.loads(response.read().decode()) def logistic(x, a, c, d): """Fit a logistic function.""" return a / (1. + ...
from django.test import TestCase from django.core.cache import cache from apps.accounts.models import Account from apps.schedule.models import Lessons, Schedule from apps.university.models import Faculties, Departaments, StudyGroups, Auditories, Disciplines class LessonsTest(TestCase): """Common tests to validat...
import logging import os import pickle import platform import pytest import localpaths # type: ignore from . import serve from .serve import ConfigBuilder, inject_script logger = logging.getLogger() @pytest.mark.skipif(platform.uname()[0] == "Windows", reason="Expected contents are platform-de...
# Copyright (C) 2010-2011 Richard Lincoln # # 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, copy, modify, merge, publish...
import sys import gym import pylab import numpy as np from keras.layers import Dense from keras.models import Sequential from keras.optimizers import Adam class A2CAgent: def __init__(self, state_size, action_size, actor_lr=1e-3, critic_lr=5e-3, discount_factor=0.99): self.state_size = state_size self.action...
# Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number # of sheep present in the array (true means present). # For example, # [True, True, True, False, # True, True, True, True , # True, False, True, False, # True, False, False, True , # True,...
# Copyright (c) 2017-2018 Lenovo Systems, Inc. # # 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 ...
from sopel_help import mixins def test_html_generator_generate_help_commands(): mixin = mixins.HTMLGeneratorMixin() result = list(mixin.generate_help_commands({ 'group_a': ['command_a_a', 'command_a_b'], 'group_c': ['command_c_a', 'command_c_b'], 'group_b': ['command_b_a', 'command_b_...
from .calc_fantasy import calc_match_fantasy
import uuid rand64 = uuid.uuid4().int & (1<<64)-1 print(rand64)
'''entre no sistema com o cumprimento do cateto oposto, cateto adjacente de um triângulo retângulo qualquer calcule e saia com o valor do cumprimento da hipotenusa Matematicamente: hip = (co ** 2 + ca ** 2) / (1 / 2) ''' from math import hypot, pow cores = {'limpa': '\033[m', 'azul': '\033[1;34m'} print('{:-^40}'.forma...
""" test_cors_origin.py Copyright 2012 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the hope...
""" tests for exif2spotlight CLI """ import pathlib import shutil import pytest from click.testing import CliRunner TEST_IMAGES_DIR = "tests/test_images" TEST_FILE_WARNING = "exiftool_warning.heic" TEST_FILE_BADFILE = "badimage.jpeg" TEST_FILE_WRONG_FILETYPE = "not-a-jpeg-really-a-png.jpeg" TEST_FILE_1 = "jackrose.j...
# Generated by Django 2.2.12 on 2020-06-01 12:17 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Dashboard', '0001_initial'), ] operations = [ migrations.AlterField( ...
from tkinter import * window = Tk() menu = Menu(window) window.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New') filemenu.add_command(label='Exit', command=window.quit) helpmenu = Menu(menu) menu.add_cascade(label='Help', menu=helpmenu) helpmenu.add_...
import time import numpy as np import pandas as pd def add_new_category(x): """ Aimed at 'trafficSource.keyword' to tidy things up a little """ x = str(x).lower() if x == 'nan': return 'nan' x = ''.join(x.split()) if r'provided' in x: return 'not_provided' if r'youtube...
import os import json import logging from math import pi from animation import * import tkinter.ttk as ttk from tkinter import filedialog from equation import DiffEqSecKind from tkinter_app_pattern import TkinterApp # Константы: SPRING_SHAPE = 10, 20 # 10 - кол-во витков, 20 - диаметр CUBE_LENGTH = 80 # длина ребра...
from django.shortcuts import render # Create your views here.from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .fo...
# this is the "keep alive" file, # used to keep the replit alive.. # not in use rn from flask import Flask from threading import Thread app = Flask('') @app.route('/') def home(): return"DenzGraphingApiWrapper_Bot is up and running" def run(): app.run(port='8080', host='0.0.0.0') def keep_alive(): ...
from ..models import EvolutionTrackInterpolator, IsochroneInterpolator from .models import MISTIsochroneGrid, MISTBasicIsochroneGrid, MISTEvolutionTrackGrid from .bc import MISTBolometricCorrectionGrid class MIST_Isochrone(IsochroneInterpolator): grid_type = MISTIsochroneGrid bc_type = MISTBolometricCorrectio...
import torch import numpy as np import numbers import quantization import quantization.help_functions as qhf class ScalingFunction(object): ''' This class is there to hold two functions: the scaling function for a tensor, and its inverse. They are budled together in a class because to be able to invert th...
# Exercício 085 numeros = [[], []] for c in range(1, 8): n = int(input(f'Digite o {c}º valor: ')) if n % 2 == 0: numeros[0].append(n) else: numeros[1].append(n) print('=-' * 25) print(f'Os valores pares digitados foram: {sorted(numeros[0])}') print(f'Os valores impares digitados foram: {sor...
"""module for inputname modifier.""" from ..fdef import Fdef, EnumInput from .modifier import Modifier class InputNameModifier(Modifier): """Input name modifier tweaks enum modifier's behavior.""" def define(self, fdef: Fdef) -> None: if fdef.enum_input is None: fdef._enum_input = EnumInp...
''' This module contains functions used to import a csv to pandas DataFrame and to perform ''' import pandas as pd # load csv to data DataFrame def create_dataframe(url): '''Create a DataFrame using csv data online Args: url (str): url that points to a csv data file Return: d_f (pandas D...
# -*- coding: UTF-8 -*- # !/usr/bin/env python ''' author: MRN6 updated: Jul. 18th, 2020 Sat. 03:40PM LICENSE: CC0 ''' import re class QPath: def __init__(self): pass def minimalpair(self, tag, html, position): #最小对称法 check_start_tag='<'+tag check_end_tag='' ...
""" The MIT License (MIT) Copyright (c) 2021 NVIDIA 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, copy, modify, merge, publi...
""" ipcai2016 Copyright (c) German Cancer Research Center, Computer Assisted Interventions. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE for details """ ''' Created on Oct 19, 2015 @au...
## Copyright (c) 2022, Team FirmWire ## SPDX-License-Identifier: BSD-3-Clause from collections import OrderedDict from abc import ABC, abstractmethod class FirmWireSOC(ABC): @property @abstractmethod def peripherals(): pass @property @abstractmethod def name(): pass class SO...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import time import wave import datetime import pyaudio import RPi.GPIO as GPIO import requests from test_nn import AudioNetTester # 録音デバイス番号 DEVICE = 2 # LEDとタクトスイッチのピン SWITCH_PIN = 21 GREEN_PIN = 12 YELLOW_PIN = 16 RED_PIN = 20 ...
import sys import json def read_data(data_filename): with open(data_filename) as data_file: data = json.load(data_file) return data def tree_stats(data): span2counts = {} for instance in data: for question in instance['questions']: support_text = instance['support'][0][...
#Please Don't Forget to read README.md otherwise you will fall in trouble import pyautogui import time X_Axis=int(input("Enter X axis:-")) Y_Axis=int(input("Enter Y axis:-")) print("It Will Start Bombarding in 10sec") print("Clear the place where it wants to click") time.sleep(10) print("u have more 5sec ex...
#!/usr/bin/env python3 # Dependencies from the Python 3 standard library: import os import pickle import shutil from subprocess import call # Dependencies from the Scipy stack https://www.scipy.org/stackspec.html : import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import interpolation, map_coordinat...
import lib.logger as logging from lib.functions import wait_until, r_sleep from lib.game import ui from lib.game.notifications import Notifications logger = logging.get_logger(__name__) class Store(Notifications): class FILTERS: ARTIFACT = ui.STORE_FILTER_ARTIFACT SECOND_LIST = [FILTERS.ARTIFACT.n...
class FSMProxy(object): def __init__(self, cfg): from fysom import Fysom events = set([event['name'] for event in cfg['events']]) cfg['callbacks'] = self.collect_event_listeners(events, cfg['callbacks']) self.fsm = Fysom(cfg) self.attach_proxy_methods(self.fsm, events) ...
import os import sys from pathlib import Path # py.test messes up sys.path, must add manually # (note: do not have __init__.py in project if project and app has same name, python takes "top package" and will # import from project instead of from app) sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from dj...
# Copyright 2017--2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fi...
from unittest import TestCase from copy import deepcopy from numpy import array as np_array from rptools.rpthermo.rpThermo import ( build_stoichio_matrix, get_target_rxn_idx, minimize, remove_compounds, # eQuilibrator, # initThermo, # get_compounds_from_cache ) from brs_utils import ( cr...
from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from django.utils.timezone import now from rest_framework import serializers from rest_framework.exceptions import ValidationError from rest_framework.validators import UniqueTogetherValidator from rest_fra...
from setuptools import setup setup( name='django-pkgconf', version='0.3.0', description='Yet another application settings helper.', url='https://github.com/byashimov/django-pkgconf', author='Murad Byashimov', author_email='byashimov@gmail.com', packages=['pkgconf'], license='BSD', c...
from django.contrib.auth import get_user_model from django.contrib.auth.base_user import (AbstractBaseUser as DjangoAbstractBaseUser, BaseUserManager as DjangoBaseUserManager) from django.db import models from django.utils import timezone from django.utils.translation import ...
import numpy as np import matplotlib.pyplot as plt import random from PIL import Image from matplotlib import gridspec from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle, Circle from matplotlib.pyplot import draw, figure, get_cmap, gray from matplotlib.transforms import Affine2D...
from django.db import models from model_utils.models import TimeStampedModel from companies.models import Company class InterviewStage(TimeStampedModel): name = models.CharField(max_length=100) position = models.IntegerField(null=True) tag = models.CharField(blank=True, max_length=15) company = mod...
#login token for discord token = 'Enter token here' #If you don't have an api_key for LoL, you can get one at https://developer.riotgames.com lol_api_key = 'Enter league of legends api key here' region = 'Enter a region here (na, br, kr, etc.)' #set to true if you want to use lolfantasy enable_fantasy = False #phant...
import math from datetime import datetime from collections import defaultdict import numpy as np import h5py import pandas as pd from exetera.core import exporter, persistence, utils, session, fields from exetera.core.persistence import DataStore from exetera.processing.nat_medicine_model import nature_medicine_model_...
import unittest import sklearn_extra from nlpatl.models.clustering import SkLearnExtraClustering class TestModelClusteringSkLearnExtra(unittest.TestCase): @classmethod def setUpClass(cls): cls.train_features = [ [0, 0], [0, 1], [0, 2], [0, ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2017-08-02 16:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0011_user_name'), ] operations = [ migrations.AddField( ...
from solvers.ea_solver import EASolver from solvers.math import interpolate_signal, ls_fit from solvers.tests.base_test_case import BaseTestCase from solvers.tests.correction_models import linear_correction class TestEASolver(BaseTestCase): def setUp(self): super().setUp() self.solver = EASolver(x...
import numpy as np import scipy.optimize import scipy.special from scipy.interpolate import approximate_taylor_polynomial # ----------------------------------------------------------------------------- class StringPolynomial: ''' Representation of a polynomial using a python string which specifies a numpy fu...
# -*- coding: utf-8 -*- # import json # import csv import unittest from com_lib.file_functions import delete_file class Test(unittest.TestCase): def test_clean_up(self): files = [ "test_data_test_user.json", "test_data_todos.json", "test_data_users.json", "...
#coding: latin1 #< full from algoritmia.problems.knapsack import branch_and_bound_knapsack3 v, w, W = [11, 16, 13, 1, 11], [3, 5, 6, 3, 6], 6 x, score = branch_and_bound_knapsack3(v, w, W) print(x, score) #> full
""" Entradas --> 4 valores int a, b, c y d que vamos a convertir en str a --> str --> a b --> str --> b c --> str --> c d --> str --> d Salidas --> 1 valores int redondeado a su centena mas cercana e --> int --> e """ # Entradas a = str(input("\nEscribe el valor de a ")) b = str(input("Escribe el valor de b ")) c = ...
import transformers from transformers import AutoModelForCausalLM, AutoTokenizer import pickle import torch from GENRE.genre.trie import Trie print("LOAD TRIE") # load the prefix tree (trie) with open("kilt_titles_trie_dict.pkl", "rb") as f: trie = Trie.load_from_dict(pickle.load(f)) print(trie.get("")) device =...
""" Run this script to prepare the train.csv data for analysis in Caffe. Afterwards, run this command to train the model: ../caffe/build/tools/caffe train -solver bnp_paribas/data/caffe/nonlinear_solver.prototxt Based on http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/02-brewing-logreg.ipynb ""...
"""Tests for param_grid """ # Authors: Lyubomir Danov <-> # License: - import pytest from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import ParameterGrid from sklearn.pipeline import Pipeline from sklearn.svm import SVC from ..param_grid import generate_param_grid def get_test_case...
import torch import torch.nn as nn from pytorchBaselines.a2c_ppo_acktr.convgru_model import ConvGRU from pytorchBaselines.a2c_ppo_acktr.distributions import ( Bernoulli, Categorical, DiagGaussian, ) from pytorchBaselines.a2c_ppo_acktr.srnn_model import SRNN class Flatten(nn.Module): def forward(self, ...
""" The MIT License (MIT) Copyright (c) 2017 SML 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, copy, modify, merge, publish,...
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os imp...
# -*- coding: utf-8 -*- """Tests for eccemotus_lib.py.""" import unittest import eccemotus.eccemotus_lib as eccemotus class EccemotusTest(unittest.TestCase): """Tests for eccemotus library.""" def test_CreateGraph(self): """Tests graph creation.""" event = { u'__container_type__': u'event', ...
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
from .LtccPayments import LtccPayments from .LtccPayments import load_ltcc_recipients from .LtccRecipient import LtccRecipient
from ..constants import FORMAT_CHECKS from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES from ..postprocessor import KnowledgePostProcessor class FormatChecks(KnowledgePostProcessor): _registry_keys = [FORMAT_CHECKS] def process(self, kp): headers = kp.headers for fie...
''' Connection_validation protocol ''' class Connection_validation: ''' Connection_validation protocol object ''' def __init__(self): ''' Initialize a Connection_validation object Keyword arguments: self: object ''' self.num_tasks = 100 self.tas...
from django.contrib import admin from .models import DcmToBidsJson from .models import Session from .models import Subject # Register your models here. admin.register(Session, site='bids_tryworks') admin.register(Subject, site='bids_tryworks') admin.register(DcmToBidsJson, site='bids_tryworks')
# ========================================================================= # # Copyright 2018 National Technology & Engineering Solutions of Sandia, # LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, # the U.S. Government retains certain rights in this software. # # Licensed under the Apache...
# Copyright 2019-2020 Axis Communications AB. # # For a full list of individual contributors, please see the commit history. # # 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...
import discord from discord.ext import commands from discord.commands import Option, slash_command import json with open ('././config/guilds.json', 'r') as f: data = json.load(f) guilds = data['guilds'] class NitroView(discord.ui.View): def __init__(self, msg: discord.Message, ctx: commands.Context): super()....
import datetime from asyncio.events import AbstractEventLoop from typing import Generator, List, Union from ..exceptions import VoyagerException from .base import BaseResource __all__ = [ 'FireballResource', ] class FireballRecord(object): __slots__ = [ '_fc', '_date', '_lat', ...
# Run with 'mpirun -n <N CPUs> python run_example.py' from __future__ import division, print_function import numpy as np from parPDE import Simulator2D, LAPLACIAN from BEC2D import BEC2D nx_global = ny_global = 500 x_max_global = y_max_global = 10/np.sqrt(2) simulator = Simulator2D(-x_max_global, x_max_global, -y_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 28 08:38:15 2017 @author: jorgemauricio """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from scipy.interpolate import griddata as gd #%% read csv data1 = pd.read_table('data/d1.tx...
from .abstract_get_api_test import AbstractGetApiTest from .abstract_post_api_test import AbstractPostApiTest
import psycopg2 def drop_table(elephantsql_client, command): '''Drops table included in the input command''' cur = elephantsql_client.cursor() try: cur.execute(command) elephantsql_client.commit() except (Exception, psycopg2.DatabaseError) as error: print("Error: %s" % error) ...
# coding=utf-8 """ update_vagrant_metadata is an Ansible module that allows for updates to a single provider section of a Vagrant metadata.json file describing a box. """ from __future__ import absolute_import, division, print_function, unicode_literals from json import dump, load from ansible.module_utils.basic impo...
import logging, ipaddress import sys base_dir = "/usr/local/fworch" importer_base_dir = base_dir + '/importer' sys.path.append(importer_base_dir) # sys.path.append(importer_base_dir + '/fortimanager5ff') # import common, fwcommon def normalize_nwobjects(full_config, config2import, import_id): nw_objects = [] ...
# Patch the operators in maskrcnn_benchmark import logging logger = logging.getLogger(__name__) try: import siammot.operator_patch.rpn_patch except: logger.info("Error patching RPN operator") try: import siammot.operator_patch.fpn_patch except: logger.info("Error patching FPN operator"...
#validação de dados nome = str(input('Digite seu nome: ')) sexo = str(input('SEXO [M/F] ')).upper()[0].strip() while sexo not in 'MF': sexo = str(input('Resposta invalida! tente novamente \n SEXO [M/F] ')).upper()[0].strip() print('Sexo {} registrado com sucesso'.format(sexo)) idade = int(input('Digite sua idade...
l1 = list(range(100)) new_list = # list comprehension is here filter numbers divisible by 7 #print(l1) #print(new_list) print(sum(new_list))
# -*- coding: utf-8 -*- """ Created on Mon May 31 22:35:08 2021 @author: LENOVO """ import pandas as pd data = pd.read_csv('phpgNaXZe.csv') data.head() #Colocar nombres a las columnas columnas = ['sbp','Tabaco','ldl','Adiposity','Familia','Tipo','Obesidad','Alcohol','Edad','chd'] data.columns=column...
from .base import BaseModel class TransformerSeries(LitBase): """ A Transformer for timeseries data. The standard Trasnsformer encoder layer is based on the paper “Attention Is All You Need”. It implements multi-headed self-attention. The TransformerEncoder stacks the encoder layer and implements ...
from operator import add import numpy as np import digExtractionsClassifier.utility.functions as utility_functions class ClassifyExtractions: def __init__(self, model, classification_field, embeddings, context_range = 5, use_word_in_context = True, use_break_tokens = False): self.model = model sel...
import os print("Hello World") #var1 = input("Enter something please: ") #print(var1) var2 = open("File.txt", "r+") print(var2) print(var2.name) #var2.write("Hello My Name Is Bob") string1 = var2.read(10) print(string1) var2.close() #os.rename("File.txt", "New Name.txt") #os.remove("Filelocation and filename...
import pytest # type: ignore from redicalsearch import CreateFlags, GeoField, IndexExistsError, NumericField, TextField pytestmark = [pytest.mark.integration, pytest.mark.asyncio] async def test_new_index(redical): assert True is await redical.ft.create( 'myindex', TextField('line', TextField.SORTABLE), Tex...
import serial #Write the program name here ProgName = b'TEST' #Write the positions here def Position_List(): positionNoFlag('P1', [426.393,-0.000,460.000,0.000,90.000,-0.000]) positionFlag('P2', [242.630,0.000,685.411,-0.000,52.760,-0.000],[6,0]) #ser = serial.Serial('COM4', 19200, timeout=...
import json def exportImagePath(filepath, listDownload, outpath): imageIds = [] idsDescription = {} idsLinks = {} idsTitles = {} with open(filepath) as f: with open(listDownload, 'w') as fout: with open(outpath, 'w') as fullout: paths = [] f...
#! /usr/bin/python # -*- coding: utf-8 -*- #server #Can only accept one client. # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # #...
token = "1047594455:AAGGblu9FGRNgPkjMEcbX7I5BuwDHUBQqsI" MODULE_NAME = "admin" MESSAGE_AMOUNT = "People registered: " MESSAGE_UNAUTHORIZED = "Unauthorized access attempt. Administrator was notified" MESSAGE_SENT_EVERYBODY = "Message has been sent to everybody" MESSAGE_SENT_PERSONAL = "Message has been sent" MESSAGE_AB...
import time class Mpu6050: ''' Installation: sudo apt install python3-smbus or sudo apt-get install i2c-tools libi2c-dev python-dev python3-dev git clone https://github.com/pimoroni/py-smbus.git cd py-smbus/library python setup.py build sudo python setup.py install pip instal...
import random def start(input_number): if input_number in range(18, 21): print("Minha jogada: 21") print("Você perdeu, playboy!") print("Digite um número, de um a três, para jogar novamente.") elif input_number == 21: print("Você ganhou, espertinho!") print("Digite um número, de um a três, p...
import copy import inspect import operator import warnings from collections import OrderedDict import inflection from django.conf import settings from django.db.models import Manager from django.db.models.fields.related_descriptors import ( ManyToManyDescriptor, ReverseManyToOneDescriptor ) from django.utils i...
from pyspark import SparkContext, SparkConf class Spark(object): def __init__(self, app_name='', master='local', executor_memory='4g'): self.app_name = app_name self.master = master self.executor_memory = executor_memory self.sc = None def context(s...
# read in config from __future__ import absolute_import, print_function, division import configobj import pkg_resources import os import validate def check_user_dir(g, app_name='hfinder'): """ Check directories exist for saving apps/configs etc. Create if not. """ direc = os.path.expanduser('~/.' + ap...