text
stringlengths
38
1.54M
import math import time from array import array import x86 from ..core import Vector3 from .bbox import BBox import renmas2.switch as proc def clamp(x, minimum, maximum): return max(minimum, min(maximum, x)) class Grid: def __init__(self): pass def _bbox(self, shapes): p0 = Vector3(99999...
import math import time start = time.time() # fairly verbose solution def extract_digits(n): digits = [n%10] while n//10 != 0 : n = n//10 digits.append(n%10) return digits def factors(n): result = [] for i in range(2,(n//2)+1): if i in result: break if n%i == 0: result.extend((i,(n/i))) # res...
from sklearn.preprocessing import OrdinalEncoder import category_encoders as ce import pandas as pd def encode(train, test): ''' This function has 2 parts: encoding ordinal and nominal categories. ''' # Joining both data frames. Have to remove SalePrice from the train df because it is not in the t...
# -*- coding: utf-8 -*- from project.api.mixins import PaginateMixin, UserAccessMixin from project.apps.search.models import Page from rest_framework import mixins, viewsets from .serializers import PageSerializer, PageDetailSerializer class PageViewSet( UserAccessMixin, PaginateMixin, mixins.ListModelMix...
import jpype # Start up the JVM with coverage instrumentation jpype.startJVM("-javaagent:project/coverage/org.jacoco.agent-0.8.5-runtime.jar=destfile=jacoco.exec,includes=org.jpype.*:jpype.*,classdumpdir=dump", classpath=["native/org.jpype.jar", "test/classes/"]) # Execute some paths print(jpype.JStrin...
""" A gui tool for editing. Originally was a basic proof-of-concept and a test of the Python API: The qt integration for ui together with the manually wrapped entity-component data API and the viewer non-qt event system for mouse events thru the py plugin system. Later has been developed to be an actually usable edi...
from nltk.tokenize import word_tokenize as wt from nltk.tokenize import sent_tokenize as st from nltk.util import ngrams from nltk.tokenize import RegexpTokenizer as rt text = "Hi Mr. Smith! I'm going to buy some vegetables (tomatoes and cucumbers). From the store, you know?" #print(wt(text)) #print(st(text)) ''' ...
#!/usr/bin/env python # encoding: utf-8 from __future__ import division import sys #sys.path.insert(0, __file__+'/pyBusPirateLite') sys.path.insert(0, './nfc/pyBusPirateLite') from pyBusPirateLite.I2C import * #[0x78 0x0 0xae] [0x78 0 0xd5 0x80] [0x78 0 0x3f] [0x78 0 0xd3 0] [0x78 0 0x40] [0x78 0 0x8d 0x14] [0x78 0 ...
from core.queries.sql import ( transform_table_dim_artists, transform_table_dim_songs, transform_table_dim_time, transform_table_dim_users, transform_table_fact_songplays, ) from settings.envs import ( DWH_DB_PUBLIC_VAULT, DWH_DB_RAW_VAULT, ) transform_data = [ { "query": trans...
import unittest import main class TestGame(unittest.TestCase): def test_input(self): guess = 5 answer = 5 result = main.run_guess(5, 5) self.assertTrue(result) if __name__ == '__main__': unittest.main()
#!/usr/bin/python # # Parser for token and entropy files. # Looks up and records tokens and entropies. # # Lance Simmons, November 2016 import csv import errno import fnmatch import os import random import sys import time # Seed rng random.seed() def createDirectory(path): try: os.makedirs(path) e...
from sklearn.ensemble import AdaBoostClassifier ''' pruning ''' class Boosting: def __init__(self): self.clfs = [] def get_classifer(self, x, y): b = AdaBoostClassifier( base_estimator=None, n_estimators=50, learning_rate=0.5, algorithm='SAMME...
#收集主机mac地址。提示使用tcpdump -nn -i eth0 port 68 -l #应用环境,在kickstart集中部署时使用 #coding:UTF8 from subprocess import Popen,PIPE import time import sys import os def get_data(): # p = Popen('ping 192.168.88.1 -n 10',stdin=PIPE,stdout=PIPE,shell=True) p = Popen('tcpdump -c1000 -nn -i br0 port 68 -l',stdin=PIPE,stdou...
"""Test the links.streams module.""" # Builtins # Packages from phylline.links.streams import StreamLink LOWER_EVENTS = ['foo,', 'bar,', 'foobar!'] LOWER_BUFFERS = [event.encode('utf-8') for event in LOWER_EVENTS] HIGHER_EVENTS = ['Hello,', 'world!'] HIGHER_BUFFERS = [event.encode('utf-8') for event in HIGHER_EVEN...
from glob import glob from pathlib import Path import numpy as np import SimpleITK as sitk import snorkel from skimage import io from skimage.filters import (threshold_li, threshold_otsu, threshold_sauvola, threshold_yen) from skimage.measure import label, regionprops from skimage.morpholo...
from django.urls import path from .views import GroupView, GetGroupView urlpatterns = [ path('group', GroupView.as_view()), path('group/<str:screen_name>', GetGroupView.as_view()), ]
import random def verify_conditions(participants, outcome): for o in outcome: participant = o[0] assignee = o[1] participant_partner = participants[participant] # participant does not get themselves nor their partners if participant == assignee or participant_partner == as...
''' This is called doc string Created on May 23, 2020 @author: Admin_2 ''' #========================================================================= # There are 3 types of methods in python # 1. instance method - are object related methods # 2. static method - are general utility methods # 3. class method - are class ...
# 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...
# Exercise 8 # Make a two player Rock, Paper, Scissors game import random print("Rock, Paper,Scissors") loop = True move = ["rock", "paper", "scissors"] while loop: bot = random.choice(move) p1 = input("What do you choose\n") p1 = p1.lower() if p1 == bot: print("Tie") ...
# coding=utf8 ''' Given two integer arrays sorted in ascending order and an integer k. Define sum = a + b, where a is an element from the first array and b is an element from the second one. Find the kth smallest sum out of all possible sums. Example Given [1, 7, 11] and [2, 4, 6]. For k = 3, return 7. For k = 4...
#coding=utf-8 # @Author: yangenneng # @Time: 2018-05-09 21:17 # @Abstract:Wolfe Line Search method from LinearSearchMethods.StepSize.Zoom import zoom from LinearSearchMethods.StepSize.Interpolation import * def f(x): return (x-3)*(x-3) def f_grad(x): return 2 * (x - 3) def f_grad_2(x): return 2 def Wol...
class Create_mail: expected_name = "alex2019hillel@ukr.net" create_button = "//div[@id='content']/aside/button" fild_input = "//input[@name='toFieldInput']" fild_subject = "//input[@name='subject']" submit_button = "//div[@id='screens']/div/div/div/button"
import pandas as pd from bokeh.plotting import figure, output_file, show from bokeh.models import Title # Source https://bokeh.pydata.org/en/latest/docs/gallery/color_scatter.html cardata = pd.read_csv('cars-sample.csv') TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_se...
from django.core.management.base import BaseCommand, CommandError from polls.models import Poll from django.utils import timezone class Command(BaseCommand): args = '<question question ...>' help = 'Adds a poll with the specified question(s)' def handle(self, *args, **options): for question in arg...
#coding=utf-8 from django.db import models class Tag(models.Model): tag_name = models.CharField(max_length=20) create_time = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.tag_name class BlogPost(models.Model): title = models.CharField(max_length=150) author ...
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_snmp_agent_cfg from ydk.providers import NetconfServiceProvider from ydk.models.ietf import ietf_interfaces from ydk.services import CRUDService from ydk.services import NetconfService, Datastore if __name__ == '__main__': sp_instance = NetconfServiceProvider(addre...
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from asset.models import * from asset.forms import * from django.conf import settings from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required @login_re...
from django.db import models from django.contrib.auth import get_user_model from common.choices import AdvertisementStatus, AdvertisementType from address.models import AddressField from django.core.exceptions import ValidationError class LandlordUser(get_user_model()): phone_number = models.CharField(max_length=2...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2015-12-23 16:29:55 # @Author : killingwolf (killingwolf@qq.com) import re if __name__ == '__main__': # 15-1 p151 = r'[bh][aiu]t,?' print re.search(p151, 'hut').group() # 15-2 p152 = r'\w+ \w+' print re.search(p152, 'abc cba').group() ...
import numpy as np import pandas as pd from matplotlib import pyplot as plt import umap from embeddings.embedding_manager import EmbeddingMan, GloveEmbeddings, BPEmbeddings, CombinedEmbeddings from dataset import Document, DataSet from flair.embeddings import WordEmbeddings, FlairEmbeddings, StackedEmbeddings, BertEm...
import sys import re from utils.log import log puzzle_input = [x for x in sys.stdin.read().split('\n')] regex = re.compile(r'(\d+)-(\d+)\s([a-z]):\s([a-z]+)') def count_letter(l, s): num = 0 for c in s: if c == l: num += 1 return num @log def a(puzzle_input): valid_pws = 0 ...
# pylint: skip-file """ Fix missing anchors from timestamp and date nodes. This must be removed once incorporated into ruamel.yaml, likely at version 0.17.22. Source: https://sourceforge.net/p/ruamel-yaml/tickets/440/ Copyright 2022 Anthon van der Neut, William W. Kimball Jr. MBA MSIS """ import ruamel.yaml from ruam...
import random import numpy as np import pandas as pd import pytest from mizarlabs.static import CLOSE from mizarlabs.transformers.sample_weights import SampleWeightsByReturns from mizarlabs.transformers.sample_weights import SampleWeightsByTimeDecay from mizarlabs.transformers.targets.labeling import EVENT_END_TIME ...
import math def find_first(fn, arr): for item in arr: if fn(item): return item return None def arr_from(arr, size, padding): if len(arr) >= size: return arr[:size] return arr + ([padding] * (size - len(arr))) def kfold(x, y, partitions=5): def to_partition(coll): sz = m...
import logging import os import shutil import numpy as np from lt_sdk.common import py_file_utils from lt_sdk.graph import full_graph_pipeline, lgf_graph from lt_sdk.graph.graph_collections import graph_collection from lt_sdk.graph.import_graph import graph_importer_map from lt_sdk.graph.run_graph import graph_runner...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: kidjourney # @Date: 2015-06-17 22:30:53 # @Last Modified by: kidjourney # @Last Modified time: 2015-06-17 22:35:01 class Solution: # @param s, a string # @return a string def reverseWords(self, s): s = s.strip().split()[::-1] s = "...
import angr import logging logger = logging.getLogger('Concretizer') class Concretizer(angr.exploration_techniques.ExplorationTechnique): def __init__(self, addrs): super(Concretizer, self).__init__() self.addrs = addrs def step(self, simgr, stash, **kwargs): for addr in self.addrs: ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('matching', '0004_auto_20150407_0933'), ] operations = [ migrations.AddField( model_name='beach', nam...
{ 'variables': { 'component%': 'static_library', 'visibility%': 'hidden', 'library%': 'static_library', }, 'conditions': [ ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris" \ or OS=="netbsd" or OS=="android"', { 'target_defaults': { 'cflags': [ '-pthread' ], ...
from weapon_selector_screen import WeaponSelectorScreen from credits_screen import CreditsScreen from main_menu_screen import MainMenuScreen from pygame import QUIT, Surface from guns import Weapon class MainMenu: def __init__(self, screen: Surface): self.state = 'MENU' self.main_menu_screen ...
dp = [[0 for _ in range(1000)] for _ in range(1001)] def sumOfProduct(arr,n,k): # filling last column : n-1 th element for r in range(k+1): dp[r][n-1]=0 # filling row 1: dp[1][n-1]=arr[n-1] for c in range(n-2,-1,-1): dp[1][c] = ( dp[1][c+1] + arr[c] ) % 1000000007 for ...
# -*- coding:utf-8 -*- import urllib import xlrd import time from urllib import request, parse import json from xlutils.copy import copy import threading def start(): source_workbook = xlrd.open_workbook('E:/song_singer.xls', formatting_info=True) result_workbook = copy(source_workbook) source_sheet = sou...
import csv from keboola import docker class App: def run(self): # initialize KBC configuration cfg = docker.Config() # validate application parameters parameters = cfg.get_parameters() text_max = parameters.get('max') text_min = parameters.get('min') ...
import math # import random as random from random import random from random import randint from random import sample class NQueen(object): def __init__(self, N): self.N = N self.table = [[0] * N for _ in range(N)] def print_table(self): print("-------------") ...
#!python import unittest import ast from py2lisp import translate, translate_literal class TestLiterals(unittest.TestCase): function = staticmethod(translate_literal) def test_string(self): self.assertEqual("#()", self.function("")) self.assertEqual("#(0 0 0 97)", self.function("a")) ...
print('------ Bem vindo ao exercicio 62 ----------') print('\033[31m Melhore o desafio 61, perguntando para o usuario se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar os termos') primeiro = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) termo = primeiro c = ...
import FWCore.ParameterSet.Config as cms apvshotsfilter = cms.EDFilter('APVShotsFilter', digiCollection = cms.InputTag("siStripDigis","ZeroSuppressed"), historyProduct = cms.InputTag("consecutiveHEs"), apvPhaseCollection = cms.InputTag("APVPhases"), zeroSuppressed = cms.untracked.bool(T...
INSTALLED_APPS += ( # CMS parts 'fluent_blogs', 'fluent_blogs.pagetypes.blogpage', 'fluent_pages', 'fluent_pages.pagetypes.fluentpage', 'fluent_pages.pagetypes.flatpage', 'fluent_pages.pagetypes.redirectnode', 'fluent_comments', 'fluent_contents', 'fluent_contents.plugins.code', ...
"""alteracoes Revision ID: e2d92519c296 Revises: ec8ee485b2bd Create Date: 2020-09-20 15:33:06.633473 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e2d92519c296' down_revision = 'ec8ee485b2bd' branch_labels = None depends_on = None def upgrade(): # ###...
import translationstring import colander from ..models import Emails from ..models import Users _ = translationstring.TranslationStringFactory('PhotoViewerExpress') class DBEmail(colander.Email): def __init__(self, msg=None): colander.Email.__init__(self, msg) def __call__(self, node, value): ...
from django.contrib import admin from .models import Player, PlayerTurn admin.site.register(Player) admin.site.register(PlayerTurn)
import csv from collections import defaultdict, Counter from pathlib import Path from itertools import combinations import pytest class Solution: def fourSum(self, nums: list[int], target: int) -> list[list[int]]: count_nums: Counter = Counter(nums) nums = [val for val, val_count in count_n...
numero1=int(input("ingrese el primer numero: ")) numero2=int(input("ingrese el 2 numero: ")) if numero2>numero1: print("el numero mayor es: ", numero2) elif numero1>numero2: print("el numero mayor es: ",numero1) else: print ("no hay numero mayor, los numeros son iguales")
import os import logging import airflow import pendulum from airflow import DAG from airflow.utils import dates as date from datetime import timedelta, datetime from airflow.models import BaseOperator, Pool from airflow.operators.bash_operator import BashOperator from airflow.utils.trigger_rule import TriggerRule from ...
import json import pytest from rest_framework import status from sme_uniforme_apps.core.models import Uniforme pytestmark = pytest.mark.django_db def test_uniformes_api_get_categorias(client, uniforme_meias, uniforme_tenis): response = client.get('/uniformes/categorias/', content_type='application/json') r...
import AuthenticationServices from PyObjCTools.TestSupport import TestCase, min_os_level, min_sdk_level class TestASAuthorizationProvider(TestCase): @min_sdk_level("10.15") def test_protocols(self): self.assertProtocolExists("ASAuthorizationProvider") @min_os_level("10.15") def test_methods10...
#!/usr/bin/python from setuptools import setup install_requires = [i.strip() for i in open("requirements.txt").readlines()] entry_points = """ [console_scripts] manage = manage:manager.run webapp = infopub.webapp:main """ setup( name="cn486", version="1.0", url='http://www.jcing.com', license='Priva...
import torch import numpy as np import torch.nn.functional as F from collections import OrderedDict from torchvision.models import alexnet from torch.autograd import Variable from torch import nn from .config import config # from pose.models.pose_resnet import get_pose_net from .cpm import CPM class SiameseAlexNet(n...
import sys import csv from collections import defaultdict def main(non_canonical_final_table, final_table, SJ_introns, reads_tags): csv.field_size_limit(1000000000) reader1 = csv.reader(open(non_canonical_final_table), delimiter = ' ') reader2 = csv.reader(open(final_table), delimiter = ' ') reader3 = csv.reader...
import matplotlib.pyplot as plt import numpy as np import os import csv from collections import namedtuple os.system("") plt.rcdefaults() filename = 'benchmarks-iterators-{}.png' def get_cpu_caches(bench_file): cpu_caches = ['L0', 'L1', 'L2', 'L3', 'L4'] benchmark_names = '\n'.join(row[0].strip(...
# Count the number of even and odd numbers from a series of numbers numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) #initialise the variables (to count the number of even and odd numbers) to zero count_odd = 0 count_even = 0 #An if-else loop nested in a for loop to count the number of even and odd numbers for x in numbers: ...
#!/usr/bin/python3 import json def save_to_json_file(my_obj, filename): """writes an object to a text file in JSON representation""" if not isinstance(filename, str): raise TypeError("filename must be a string") with open(filename, mode="w", encoding="utf-8") as writeFile: json.dump(my_obj...
""" Gene Analysis project """ # import file_in # import modify_dataframes # import Visualization.heatmap as heatmap # import Visualization.volcano as volcano # import matplotlib.pyplot as plt # import os # import ntpath # def make_a_heatmap(): # dfs = list() # paths = [os.path.join("/Users/coltongarelli/Drop...
def insertion_sort(data): n = len(data) for i in range(1, n): item = data[i] j = i - 1 while j>=0 and data[j] < item: # temp = data[j] # data[j] = data[j + 1] # data[j + 1] = temp [data[j], data[j + 1]] = [data[j +1], data[j]] ...
import json def add(event, context): inputDoc = json.loads(event['body']) sum = str(inputDoc['value1'] + inputDoc['value2']) result = json.dumps("{'sum':" + sum + "}") return { "statusCode": 200, "body": result }
from unittest import TestCase from nose.plugins.attrib import attr from shiftschema.result import Error, Result from shiftschema import exceptions as x from pprint import pprint as pp @attr('result', 'result') class ResultTest(TestCase): # ------------------------------------------------------------------------...
# -*- coding: utf-8 -*- # @Time : 2020/10/28 9:22 # @Author : zls # @File : 120ask_spider.py from pyquery import PyQuery as pq from openpyxl import Workbook import requests headers = {'Content-Encoding': 'gzip', 'Content-Type': 'text/html; charset=UTF-8', 'Date': 'Wed, 28 Oct 2020 01:22:31 GMT',...
import os import pistis import unittest import tempfile import json import shutil class ApiTestCase(unittest.TestCase): maxDiff = None def setUp(self): self.client = pistis.app.test_client() def tearDown(self): pass def test_add_manifest(self): def req(*args, **kwargs): ...
from django.contrib import admin from myapp.models import Articles, Comments, CommentToComment class ArticleInLine(admin.StackedInline): model = Comments extra = 1 class ArticleAdmin(admin.ModelAdmin): fields = ['title', 'text'] inlines = [ArticleInLine] admin.site.register(Articles, ArticleAdmin) ...
from django.conf.urls import patterns, url urlpatterns = patterns('users.views', url(r'^signup/$', 'signup', name='signup'), )
# Generated by Django 2.2.6 on 2019-11-23 13:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mobile', '0023_auto_20191123_1047'), ] operations = [ migrations.AlterField( model_name='mobil', name='defect', ...
import os import json class DataLogger(object): def __init__(self, folder_name, log_freq=10, test_freq=100): """ folder_name: (str) The name of the log folder """ self.folder_name = folder_name if not folder_name is None: if not os.path.exists(folder_name): ...
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from django.core.exceptions import ObjectDoesNotExist from gridsingularity.utils import sim from gridsingularity.exceptions.exceptions import NotFoundException from .models import SimulationResult fr...
#!/bin/python3 import sys from collections import defaultdict class Graph(object): def __init__(self,vertices): self.vertices = vertices self.graph = defaultdict(list) self.paths = set() def set_positions(self, u=None, v=None, w=None): self.u = None self.v = None ...
# -*- conding:utf-8 -*- # 文件就是用来持久化数据(把数据 保存到硬盘) # 文件基础操作 # 1 打开文件 2 关闭 # 文件操作模式 : w:write写入 r:写入 # 1.打开文件 # f = open('123.txt', 'w') # 用w模式 如果文件不存在,会自动创建此文件,如果存在会覆盖里面的内容 # # 2.写入数据 # f.write('hello') # 3.关闭文件 不关闭会 内存泄露 应该要释放的内存无法释放 # f.close() """文件操作的推荐方式""" with open('123.txt', 'w') as f: f.write('python ...
# -*- encoding:utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import unittest import pyparsing from mysqlparse.grammar.data_type import data_type_syntax class DataTypeSyntaxTest(unittest.TestCase): def test_bit(self): self.assertEquals(data_type_syntax.par...
import os import sys from pandac.PandaModules import WindowProperties import pandac.PandaModules # from panda3d.core import Shader from direct.showbase.ShowBase import ShowBase from direct.task import Task import numpy as np from scipy.ndimage.filters import gaussian_filter # pandac.PandaModules.loadPrcFileD...
import sys, os import random import numpy as np import bz2 sys.path.append(os.getcwd()) from nltk.stem import WordNetLemmatizer from visual_embeddings_reader import VisualEmbeddingsReader class Batcher: def __init__(self, captions_file, visual_file, we_dim, ...
import os import numpy as np import pickle as pkl from skimage import io,transform import random import math # read and reshape the samples' images and save their gray values as features, meanwhile, give each of them a label def get_img_features(path,label): img_feature=list() label_list=list() time=1 ...
from segments.errors import replace class TreeNode(object): """ Private class that creates the tree data structure from the orthography profile for parsing. """ def __init__(self, char, sentinel=False): self.char = char self.children = {} self.sentinel = sentinel class T...
from django.conf.urls import url from views import * urlpatterns = [ url(r'^$', index, name = 'my_index'), url(r'^newword$', newword ), url(r'^clearsession', clearsession) ]
""" Handle API response data. """ import re from miner_manager.models import Gas class InvalidRecord(Exception): pass class ResponseHandler: def __init__(self, response) -> None: self.response = response self.excluded = ['gasPriceRange'] self.transform_fields = ['fast', 'fastest...
import pytest @pytest.fixture(scope='function') def environ(request, monkeypatch): """ Fixture to define environment variables before Sphinx App is created. The test case needs to be marked as ``@pytest.mark.environ(VARIABLE='value')`` with all the environment variables wanted to define. Also, th...
import json import time from collections import defaultdict, deque from typing import Optional, Iterable, List if hasattr(time, "monotonic"): get_time = time.monotonic else: # Python2 just won't have accurate time durations # during clock adjustments, like leap year, etc. get_time = time.time from src...
import willie import random citations = [ 'http://en.wikipedia.org/wiki/Cessna_Citation', 'http://en.wikipedia.org/wiki/Chevrolet_Citation', 'http://en.wikipedia.org/wiki/Edsel_Citation', 'http://en.wikipedia.org/wiki/Citation_(horse)', 'http://en.wikipedia.org/wiki/Gibson_Citation', 'http://en.wikipedia.o...
import pytest from bravado.swagger_model import load_file from bravado.client import SwaggerClient, RequestsClient from requests.utils import parse_header_links import urlparse class Client(object): config = { 'also_return_response': True, 'validate_responses': True, 'validate_requests': F...
# Generated by Django 2.2.6 on 2019-10-07 00:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('agents', '0008_auto_20191006_2337'), ] operations = [ migrations.AddField( model_name='requestdetail', name='send', ...
def concreta_busqueda(nombre, dic): elemento = '' elemento = ''.join(map(str, nombre)) valor = dic.get(elemento) if(valor): print('{}={}'.format(elemento, valor)) else: print('Not found') n = int(input()) dic = {} busqueda = [] for x in range(n): arr = list(input().rstrip().spl...
# Define name for the player name = str(input("What is your name? ")) hasKey = False hasUniform = False onQuest = False hasToothbrush = False hasTeddy = False # This is to define the talk functions and dialogue for each NPC def beardedprisoner1(name): print("You approach the bearded prisoner") print("The bea...
import unittest from model.project import project class test_project(unittest.TestCase): def test_it_has_a_name(self): self.assertTrue(type(project.name()) == str) self.assertTrue(len(project.name()) > 0)
flowers = [ "Daffodil", "Evening Primrose", "Hydrangea", "Iris", "Lavender", "Sunflower", "Tiger Lily", ] # for flower in flowers: # print(flower) separator = ", " output = separator.join(flowers)# .join() is iterating over the list for us w/o a for loop print(output) ...
import unittest import Queue import cProfile def chapter_four_problem_seven(projects, dependencies): if not projects: return "Error" if check_for_circular_dependency(dependencies): return "No build case" build_order = [] while len(projects) != len(build_order): for p in project...
import requests from bs4 import BeautifulSoup import urllib.request as urllib2 import re def count_words(url, the_word): print(url, the_word) r = urllib2.urlopen(url) return str(r.read()).count(the_word) soup = BeautifulSoup(r.read(), 'lxml') words = soup.find(text=lambda text: text a...
import corner import matplotlib.pyplot as plt import numpy as np import pandas as pd from astropy import constants from matplotlib import rcParams rcParams["text.usetex"] = False outdir = "disk/" deg = np.pi / 180.0 # radians / degree yr = 365.25 # days / year au_to_R_sun = (constants.au / constants.R_sun).value...
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib.request import sys def download(url, title): """download video from specific url""" urllib.request.urlretrieve(url, title) if __name__ == "__main__": download("http://www.dygod.net/", "test.html")
""" This test batch makes sure the Flask API works as expected. """ import sys sys.path.append('./') from time import sleep import io import pytest import app from misc.env_vars import * valid_job_id: str @pytest.fixture def client(): app.app.config['TESTING'] = True with app.app.test_client() as client: ...
from flask import Flask,request,jsonify from sentence_transformers import SentenceTransformer import scipy import json from numpyencoder import NumpyEncoder embedder = SentenceTransformer('bert-base-nli-mean-tokens') app = Flask(__name__) baseUrl ="/sentenceTransformers" corpus = ['A man is eating food.', ...
# -*- coding: utf-8 -*- import sys import requests import subprocess from os.path import join, exists, isdir, basename, dirname from os import environ, makedirs, listdir, replace, remove, sep, getenv, chdir from time import sleep import site from shutil import rmtree from msvcrt import getwch from os import sep, startf...
# -*- coding: utf-8 -*- from decorated.base.function import Function from metaweb.errors import ValidationError import doctest import re class Validator(Function): def _call(self, *args, **kw): value = self._evaluate_expression(self._param, *args, **kw) error = self._validate(value) if erro...