text
stringlengths
8
6.05M
# Generated by Django 2.2.4 on 2020-01-16 20:19 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0006_product_likes'), ] operations = [ migrations.AlterField( model_name='product', ...
import sys def cnt (A, X, R, L): # Write your code here out = [] for (l,r,x) in zip (L, R, X): t = 0 for i in range (l-1, r): if x % A[i] == 0: t += 1 out.append (t) return out # N = int(input()) # A = list(map(int, input().split())) # Q = int(inpu...
# 题目 暂停一秒输出。 # 程序分析 使用 time 模块的 sleep() 函数。 # Python 编程中使用 time 模块可以让程序休眠, # 具体方法是time.sleep(秒数),其中"秒数"以秒为单位,可以是小数,0.1秒则代表休眠100毫秒。 import time for i in range(4): print(str(int(time.time()))[-2:]) time.sleep(1)
#!/usr/bin/python if __name__ == '__main__': N = int(raw_input()) numbers = [] for i in range(0, N): tmp = raw_input() command, value = tmp.split(' ') if command == 'a': numbers.append(int(value)) else: try: numbers.remove(int(value...
import configparser import os def get_creds(collection: str, database="SpotiBot"): config = configparser.ConfigParser() config.read(os.path.join(os.getcwd(), "mongo_creds.cfg")) conn_str = ( f"mongodb+srv://{config.get('mongo', 'USERNAME')}:" f"{config.get('mongo', 'PASSWORD')...
import sys, os, shutil from datetime import date from pyspark.sql import SparkSession from pyspark.sql.functions import to_date from pyspark.sql.types import StructType, StructField, StringType, IntegerType, TimestampType, DoubleType test_data = "C:\\Telco Relax\\Input_test\\" prod_data = "C:\\Telco Relax\\Input\\" ...
# ДЗ: # 1. Создать функцию, которая выводит на экран цифру, введенную пользоватлем в консоли. # 2. Написать программу, которая считает 5 значений, введенных пользователем из консоли, сохранит их в список # затем передаст значения в фукцию, которая выводит на экран сумму значений списка. # 3. Написать программу, ...
import datetime pessoa = dict() ano_atual = datetime.datetime.now().year pessoa['nome'] = str(input('Nome: ')) pessoa['idade'] = ano_atual-int(input('Ano de nascimento: ')) pessoa['ctps'] = int(input('Carteira de trabalho (0 não tem): ')) if((pessoa['ctps']) != 0): pessoa['contratado'] = int(input('Ano de contra...
# -*- coding: UTF-8 -*- import sys from System import * from collections import deque from System.Math import * from processing.classification.types import * from processing.segmentation.connected import * from processing.contours.psweeping import * def check_for_circle(segments, cmask, cline, sline, info, window = 3,...
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Code Jam 2021 Round 1C - Problem A. Closest Pick # https://codingcompetitions.withgoogle.com/codejam/round/00000000004362d7/00000000007c0f00 # # Time: O(NlogN) # Space: O(N) # def closest_pick(): N, K = map(int, raw_input().strip().split()) P = sorte...
from flask import render_template, flash, url_for, redirect, request, session from .. import db, bcrypt from ..models import User #from app.user.forms import AjouteruserForm, PassuserForm, EditeruserForm from flask_login import login_user, current_user, logout_user, login_required from . import main @main.route('/adm...
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): name = models.CharField('이름', max_length=100) class Todo(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=200) title = models.TextField(max_le...
#!/usr/bin/python # -*- coding: utf-8 -*- # File: w2v_to_numpy.py # Convert binary W2V file to import sys, struct, re import cPickle, gzip import numpy as np from w2v_to_numpy import W2VLoader def listFromFile(fname): ret = [] f = open(fname, 'r') for l in f: l = l.decode('utf-8').strip() r...
from phantomjs import phantomjs import logging import io import flask # Flash application context app = flask.Flask(__name__) # Setup logging logging.getLogger().setLevel(logging.INFO) @app.route('/') def welcome(): """ :return: The Wrender homepage """ return 'Wrender' @app.route('/ping') def ping...
__version__ = "0.1.0" # Submodule imports from . import isis_serial_number from . import io_controlnetwork from . import io_gdal from . import io_json from . import io_yaml from . import io_db from . import io_hdf from . import utils from . import examples from . import data
def solve(a,b): return [a.count(y) for y in b] ''' Given two arrays of strings, return the number of times each string of the second array appears in the first array. Example array1 = ['abc', 'abc', 'xyz', 'cde', 'uvw'] array2 = ['abc', 'cde', 'uap'] How many times do the elements in array2 appear in array1? ...
import math import logging import pylo tilt_corrector = None tilt_corrector_reset_event_id = "tilt_corrector_reset" tilt_corrector_correct_tilt_event_id = "tilt_corrector_correct_tilt" tilt_corrector_create_event_id = "tilt_corrector_create" def create_tilt_corrector(controller): global tilt_corrector, tilt_corr...
import boto3 import botocore import threading from django.http import HttpResponse from django.core import serializers from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist, PermissionDenied from django.shortcuts import render from django.contrib.auth.models import User from api.models import Video,...
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from datetime import datetime from logging import Logger from os import PathLike import sys from typing import ( AbstractSet, Any, ...
#Claire Yegian and Lea Adams-Blackmore #4/30/18 #strategy5.py - finds exact value for S and D and creates simulation for strategy 5 (pay S above D) from random import randint #Exact value N = int(input('Enter the number of marbles: ')) W = int(input('Enter the monetary prize: ')) marbleList = [] runs = 0 while runs <...
import netCDF3, glob, numpy for file in glob.glob("*.nc"): nc = netCDF3.Dataset(file, 'r') print file, numpy.sum( nc.variables['pr'][:] ) nc.close()
import torch import numpy if __name__ == '__main__': x = torch.tensor([ [1., 2., 3.], [4., 5., 6.] ]) print('x:') print(x) print('------------------------------------------------') # x.data print('x.data:') print(x.data) print('--------------------------------------...
from SPARQLWrapper import SPARQLWrapper, XML, JSON sparql = SPARQLWrapper("") queryString = "" sparql.setQuery(queryString) sparql.setReturnFormat(JSON) # OR XML, OR RDF etc. # return the spqarl object containing bound results results = sparql.query().convert() for result in results: print(result)
# -*- coding: utf-8 -*- """Configuration. This module contains flags to turn on and off optional modules. """ from importlib import util cupy_enabled = util.find_spec("cupy") is not None if cupy_enabled: # pragma: no cover cudnn_enabled = util.find_spec("cupy.cuda.cudnn") is not None nccl_enabled = util.fin...
import mxnet as mx import cv2 import numpy as np from os.path import join import os from logger import logger os.environ["MXNET_CPU_WORKER_NTHREADS"] = "4" def eval_res(class_id,num_id,eval_epoch,root_dir = '/home/lhw/face/faceRec'): print(class_id,num_id,eval_epoch) batch_size = 512 val_label = None im...
import numpy as np import imageio import Poisson as poi import matplotlib.pyplot as plt from scipy import ndimage iter = 20 img = imageio.imread('../hdr-bilder/Bonita/Bonita_00512.png') print(img.shape) mosaic = np.zeros(img.shape[:2]) mosaic[::2, ::2] = img[::2, ::2, 0] mosaic[1::2, ::2] = img[1::2, ::2, 1] mosaic[...
import csv import pdb from sklearn.metrics import accuracy_score, precision_score, recall_score, classification_report, confusion_matrix import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): ...
# Generated by Django 2.2.1 on 2019-05-19 00:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0006_auto_20190519_0006'), ] operations = [ migrations.AlterField( model_name='post', name='header_title', ...
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType from pyasn1.type.namedval import NamedValues from asn1PERser.classes.data.builtin import * from asn1PERser.classes.types.type import AdditiveNamedTypes from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E...
# coding: utf-8 """Utility functions for MDN parsing.""" from __future__ import unicode_literals from django.utils.six import text_type import string def date_to_iso(date): """Convert a datetime.Date to the ISO 8601 format, or None.""" if date: return date.isoformat() else: return None ...
# ''' # \d 可以匹配一个数字 # \w 可以匹配一个字母 # . 可以匹配任何字符 # * 表示任意个字符 # + 表示至少一个字符 # ? 表示1个或者0个字符 # {n} 表示n个字符 # {n,m} 表示n-m个字符 # \s 表示一个空格 # 如果出现特殊字符需要用 \ 进行转义 # 如- 在正则表达式中表示为\- # ''' # ''' # 例子: # \d{3}\s+\d{3,8} # \d{3}表示匹配3个数字,例如'010'; # \s可以匹配一个空格(也包括Tab等空白符),所以\s+表示至少有一个空格,例如匹配' ',' '等; #...
class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dum = head cnt = 0 while dum: dum = dum.next cnt += 1 prev, cur = None, head cnt -= n while cnt > 0: prev = cur cur = c...
# -*- coding: utf-8 -*- import scrapy from qsbk.items import QsbkItem from scrapy.http.response.html import HtmlResponse from scrapy.selector.unified import SelectorList class QsbkSpiderSpider(scrapy.Spider): name = 'qsbk_spider' allowed_domains = ['qiushibaike.com'] start_urls = ['https://www.qiushibaike....
from settings.development import *
import logging from assertion import Assertion logger = logging.getLogger( "TakenAssertion" ) CELL_DOMAIN = "cell" # ROW_DOMAIN = "possibilities" class TakenAssertion(Assertion): def __init__(self): super( TakenAssertion, self ).__init__() def assertTuple(self, tuple): #self.csp.domains[ CELL_DOMAIN ].taken.a...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''lisnp Usage: lisnp mm2yaml <file_name>... lisnp yaml2mm <file_name>... lisnp -h | --help lisnp --version Options: -h --help Show this screen. --version Show version. ''' from __future__ import unicode_literals, print_function ...
from config import * import random import string def generate(): link = ''.join(random.choice(string.uppercase+string.lowercase+string.digits) for x in range(5)) while db.webm.find_one({"short":link}): link = ''.join(random.choice(string.uppercase+string.lowercase+string.digits) for x in range(5)) retu...
from meterbus.meterbus import meterbus import logging __name__ = 'meterbus api' __version__ = '0.1'
from django.contrib.auth.models import User from django.db import models from quizApp.models import Quiz class Attempted(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) got = models.IntegerField() created = models.DateTi...
import pytest from elections.tests.factories import ElectedRoleFactory from elections.utils import ElectionBuilder from organisations.tests.factories import ( OrganisationDivisionFactory, OrganisationDivisionSetFactory, ) def test_division_set_by_date(db): """ Test that we can get a division set by a ...
from enum import Enum class Const(Enum): CommonPhrasesContainer = '29914481-fef8-4e62-b774-f5dc31fff4d2'
from django.conf.urls import url from views import * urlpatterns = [ #resource lists url(r'^$', home, name = 'home'), url(r'search_types$', search_types, name = 'search_types'), url(r'resource_type/(?P<resource_type_id>\d+)$', resource_type, name = 'resource_type'), url(r'resource_list$', resource_...
import numpy as np import pandas as pd from sklearn.base import TransformerMixin from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.preprocessing import StandardScaler from nltk.corpus import stopwords from nltk.stem import PorterStemmer, SnowballStemmer, WordNetLemmatizer from sklearn.linear_model import...
# encoding:utf-8 from __future__ import unicode_literals from django.contrib import admin from helpers.director.shortcut import TablePage,ModelTable,page_dc,FormPage,ModelFields,model_dc,\ regist_director,TabGroup,RowFilter,permit_list,has_permit from .models import JianFangInfo,CunWei,Policy,ApplyTable,YinJiZhen...
from tkinter import * from tkinter.dialog import * from tkinter.messagebox import * from tkinter.ttk import * # 第一个窗口 ''' def xinlabel(event): global xin s = Label(xin, text = "我爱Python") s.pack() xin = Tk() #b1 = Button(xin, text = "Click Me", command = xinlabel) b1 = Button(xin, text = "Click Me") b1.bi...
import psycopg2 from app import config class MasterDAO: """ Master DAO class from which all DAO classes inherit their connection to the PostgresSQL database using psycopg2. """ def __init__(self): """ Initializes the MasterDAO object. Used to give the inheriting classes their...
""" tests for the multiprocess """ from typing import Optional, Any, List import pandas as pd import pytest import replicators.multiprocess as mult TESTDATA = [pd.DataFrame( columns=["This", "is", "a", "test", "to", "check", "a_functio...
from django.db import models from myutils.models import JSONField from myutils.models import RichTextField from myutils.constants import Choices from account.models import User from contest.models import Contest # Create your models here. class ProblemTag(models.Model): name = models.TextField() class Meta...
from glob import glob from PIL import Image import numpy as np import os import pickle def valid(path): depth_path = path.replace('col', 'up_png') depth_path = depth_path.replace('_c', '_ud') exists = os.path.isfile(depth_path) if not exists: return False return True test_color_paths = ...
# Generated by Django 3.2 on 2021-08-22 15:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authors', '0003_author_middlename'), ] operations = [ migrations.AddField( model_name='author', name='image', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from .views import ( CreateAlbumView, AlbumsListView, AlbumImagesView, AlbumImportView, ) urlpatterns = [ url(r'^$', AlbumsListView.as_view(), name='album-list'), url(r'^album/create/', CreateAlbumView...
#!/usr/bin/env /proj/sot/ska/bin/python ################################################################################################# # # # acis_cti_trend_dom.py: computing trend line with dom ...
# Using curl or similarr provide a script that monitors the stub_status endpoint created in the Nginx section. Can you parse the "Active connections" and get the value? import requests response = requests.get('http://localhost/basic_status') # [0] to get the first line [1] to get the second part of the string after t...
import numpy as np import cv2 from matplotlib import pyplot as plt def open(img): cv2.imshow('d',img) cv2.waitKey(0 ) cv2.destroyAllWindows() img = cv2.imread('digits.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Now we split the image to 5000 cells, each 20x20 size cells = [np.hsplit(...
from os.path import dirname, realpath, exists import ctypes import sys import os import math import logging import pprint import random class UControllersError(Exception): def __init__(self, message, ucontroller_name=""): super().__init__(message) self.ucontroller_name = ucontroller_name class UC...
a = 26 b= 11.3 c=5 d= 3.5 #suma print a," +",b,"=", a+b #resta print b," +",a,"=",c-a #multiplicacion print d,"*",a ,"=" ,d*a #exponente print c,"^",2 ,"=",c**2 #division print c,"/",2 ,"=",c/2 #division ... print float(c),"/",2 ,"=", float(c)/2 #modulo ... print 7,"%",3 ,"=", 7%3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print("hello") hello >>> print('hello') hello >>> a="hello" >>> print(a) hello >>> a = """Python is a popular programming language. It was created by Guido ...
# @Time :2019/7/13 0:15 # @Author :jinbiao
#encoding: utf-8 edad=100 if edad >= 0 and edad < 18: print "eres un niño" elif edad >= 18 and edad < 27: print "eres un joven" elif edad>= 27 and 60 >edad: print "eres adulto" else: print "eres de la tercera edad"
import unittest #suite = unittest.TestLoader().loadTestsFromModule(test) #unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python """This script subscribes to a topic and logs the ExampleMessage objects read""" import rospy from example.msg import ExampleMessage NODE_NAME = 'topic_subscriber' TOPIC_NAME = 'topic' def topic_callback(data): rospy.loginfo('{} - {}'.format( rospy.get_caller_id(), data ...
#!/usr/bin/env python3 # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. """This module generates Dart APIs from the IDL database.""" import emitter import ...
from Tested_Method.MethodToTest import Add def test_Add_2_and_2_return_4(): #given x = 2 y = 2 #when result = Add(x,y) #then assert result == 4
class Camera: def __init__(self, brand, model, price, format): self.brand = brand self.model = model self.price = price self.setFormat(format) def getBrand(self): return self.brand def getModel(self): return self.model def getPrice(self): retur...
print("Arecursive program........") def fun(val): #if val <=1: if (val == 0): return 1 #print (val,end = " ") fun(val - 1) print (val, end = " ") def main(): no = int(input("Enter number:")) fun(no) if __name__ == "__main__": main()
from random import randrange as rnd, choice import tkinter as tk from tkinter import* import math import time root = tk.Tk() root.geometry('885x558') cosmos=Canvas(root, width=885,height=558,) fon = PhotoImage(file="cosmos.png") id_img= cosmos.create_image(0,0,anchor=NW,image=fon) cosmos.pack() ang...
class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ count,ct = 0,0 len1,len2 = len(nums1),len(nums2) i,j = len1-1,len2-1 lst = [] midnum = (len1+len2+1)/2 ...
a=int(input("Give me one number: ")) b=int(input("Give me another number: ")) print("If you sum those numbers, the values is: ",a+b); print("If you rest those numbers, the values is: ",a-b); print("If you multiply those numbers, the values is: ",a*b); print("If you raise the first number to a power of the second number...
input = [] with open('data/02.txt') as f: for line in f: line = line.replace(':', '').strip().split(' ') line[0] = line[0].split('-') line[0] = [int(x) for x in line[0]] input.append(line) valid = 0 for p in input: a = p[0][0]-1 b = p[0][1]-1 x = p[2][a] y = p[2][b] ...
import threading import time import queue import socket import select from pifighterinit import * ''' def UDPSendToServer(SendStr): try: # Open socket and send data - Open it each time as there were problems when comms wasn't great. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as Serve...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from app.core.flags import CATEGORY_CHOICES class Fleet(models.Model): class Meta: app_label = u'fleet' verbose_name = 'Frota' verbose_name_plural = 'Frotas' vehicle_name = models.CharField...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time #driver = webdriver.Firefox(executable_path="D:\SeleniumProject\Web_drivers\geckodriver.exe") driver = webdriver.Chrome(executable_path="C:\Drivers\chromedriver") #driver = webdriver.Ie(executable_path="D:\SeleniumProject\Web_dr...
# Configuration File for Embedded libpath = '../lib' cCompBoxFill = 'grey80' # larger number means lighter grey cCompBoxOutline = 'grey60' cConnectFill = 'grey90' cConnectOutline = 'grey70' xdefault = '0' ydefault = '0' zdefault = '0' gdefault = '2' ratio = 1 width = 1280*ratio # de...
from . import proprioceptive_humanoid_env import numpy as np # All obs but xy but yaw and z use integrals class LowlevelProprioceptiveHumanoidEnv(proprioceptive_humanoid_env.BaseProprioceptiveHumanoidEnv): # Initialize environment def __init__(self): super(LowlevelProprioceptiveHumanoidEnv, self).__ini...
# В этом упражнении необходимо выполнить задание из нескольких шагов для практики использования регулярных # выражений и реализации нескольких полезных функций. Следуйте алгоритму: # 1. Получите текст из файла. # 2. Разбейте полученный текст на предложения. # Примечание: Напоминаем, что в русском языке предложения зака...
STATUS = { "Suspend": "Suspended", "Completed": "Completed", "Canceled": "Canceled", "Sent": "Requested", "Discontinued": "Aborted", "Denied Approval": "Rejected", "Verified": "Verified", "Pending": "Received", "Resulted": "Completed", "Dispensed": "Active", "Pending Verify":...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that setting SDKROOT works. """ import TestGyp import os import subprocess import sys if sys.platform == 'darwin': print ...
#!/usr/bin/env python import re import nltk import string from tika import parser def ocr_cleaner(text): """This function takes in input text, performs various regex and non-regex based substitutions and then returns a line-by-line representation of each sentence extracted from raw OCR data.""" text = te...
def square_list(start,end): L=[] while start**2<=end**2: L.append(start**2) start+=1 return L x=int(input("Please enter a number you want to begin with:")) y=int(input("Please enter an ending number:")) print(square_list(x,y)) print(square_list(1,100))
import airflow from airflow.models import DAG from datetime import datetime from airflow.hooks.postgres_hook import PostgresHook from airflow.utils.decorators import apply_defaults from airflow.contrib.operators.postgres_to_gcs_operator import PostgresToGoogleCloudStorageOperator from airflow_training.operators.http_to...
import os def rename_files(): file_list = os.listdir(r"/Users/Angadlamba21/Documents/Myprojects/python/udacity/prank") print file_list saved_path = os.getcwd() os.chdir(r"/Users/Angadlamba21/Documents/Myprojects/python/udacity/prank") for file_name in file_list: os.renames(file_name, file_name.translate(None, ...
import requests image_url = "https://ajeas.godohosting.com/img/F19082100001_02.jpg" headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Accept':'text/html,application/xhtml+xml,applicpipation/xml;q=0.9,*/*;q=0.8','Accept-Encoding':'g...
""" curves @ utils parses paths to curve.mb's from assets/crvSrc folder EXAMPLES: #imports the first curve in crvSrc folder mc.file(rigLib.utils.curves.curvesList[0], i=1) #prints a list of curves in crvSrc folder print rigLib.utils.curves.curvesList """ import maya.cmds as mc import glob from rigLi...
import matplotlib.pyplot as plt import numpy as np u=np.linspace(-2,2,200) v=np.linspace(-1,1,100) X,Y=np.meshgrid(u,v) z=X**2/25+Y**2/4 plt.pcolor(z)#for pseudocolor plt.colorbar() plt.show() plt.pcolor(z, cmap='gray') plt.colorbar() plt.show() plt.pcolor(z, cmap='autumn') plt.colorbar() plt.show() pl...
#-*- coding=utf-8 -*- import requests from hashlib import md5 import copy from config import * url = 'https://payjs.cn/api/native' data = {'mchid': PAYJS_ID, 'total_fee': '1', 'out_trade_no': '2017122712581', 'body': 'test'} def get_sign(data): str_d = sorted(['='.join(i) for i in data....
class Solution: # @param A : list of integers # @param B : integer # @return a list of list of integers def combinationSum(self, A, B): """ This wss one of those ones where I do a first solution to check for correctness, expecting that InterviewBit will fail it for efficiency, an...
""" Tests for cinder api """ from __future__ import absolute_import, division, unicode_literals from twisted.trial.unittest import SynchronousTestCase from mimic.test.helpers import json_request from mimic.rest.cinder_api import CinderApi from mimic.test.fixtures import APIMockHelper class CinderTests(SynchronousTes...
# -*- coding: utf-8 -*- """ Main script to train and export NN Inverse models for the Holzapfel Material. Input: Stress (kPa) - Strain curves + cube dimensions + fiber orientation Output: Material parameters """ import numpy as np from random import seed import torch from sklearn.preprocessing import StandardScaler im...
import sys from time import sleep import pytest # sys.path.append("E:\College\SPRING 2021\\CMPN203\\" # "project\\Flickr-Photos\\Flickr-Photos\\Testing\\Web") from common.sel_helper import SelHelper from pageobject.explore.explore import ExploreLocator, Explore from pageobject.generalmethods.general_m...
import numpy as np file = "Day3/inputnaomi.txt" with open(file,'r') as f: wires = [row.split(',') for row in f.readlines()] f.close() def intersection_present(start1, finish1, start2, finish2): xint, yint = 0,0 if start1[0]==finish1[0]: if start2[0]==finish2[0]: return False, [xin...
# This file will draw all bounding boxes picked up by the frontal_face classifier using your webcam. # It will draw the average bounding box in red if multiple are clustered close enoughtogether. import numpy as np import cv2 # Global Varibules res = [1280, 720] # Recording resolution eps = 1.5 ...
#!/usr/bin/env python import pika import iptc connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.20.10')) channel = connection.channel() channel.exchange_declare(exchange='ip', type='fanout') result = channel.queue_declare(exclusive=True) queue_name = result.method.queue channel.queue_bind(e...
from sklearn.neural_network import MLPClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import plot_confusion_matrix from mnist import MNIST import gzip import numpy as np import matplotlib.pyplot as plt mndata = MNIST('data') np.set_printo...
from flask import Flask, render_template import pandas as pd import requests from bs4 import BeautifulSoup from io import BytesIO import base64 import matplotlib.pyplot as plt app = Flask(__name__) def scrap(url): #This is fuction for scrapping url_get = requests.get(url) soup = BeautifulSoup(url_get.co...
''' A set of utilities to aid in easy and consistent playblasts ''' from maya import cmds import pymel.core as pm import pymel.core.uitypes as pmui import os from maya import mel import maya.OpenMayaAnim as oma import glob def clean_hud(): hud_menu = pm.melGlobals['gHeadsUpDisplayMenu'] menuitems = cmds.menu(...
#!/usr/bin/env python """ Implementation of the conversion from infix to postfix notation using a stack. """ from pythonds.basic.stack import Stack def convert(expression: str) -> str: expression = list(expression) output = [] opstack = Stack() precedence = {"(": 1, "-": 2, "+": 2, "/": 3, "*": 3} ...
''' Created on Jul 5, 2011 :authors: Gary belvin ''' from charm.toolbox.conversion import Conversion import unittest class ConversionTest(unittest.TestCase): def testOS2IP(self): #9,202,000 = (0x)8c 69 50. i = Conversion.OS2IP(b'\x8c\x69\x50') self.assertEqual(i, 9202000) ...
#!/usr/bin/env python3 import re import sys def main(filename): with open(filename) as rd: raw, mine, near = rd.read().split("\n\n") my_ticket = [int(x) for x in mine.splitlines()[-1].split(",")] nearby = [[int(y) for y in x.split(",")] for x in near.splitlines()[1:]] parsed = re.findall(r'(....
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Test cases when multiple targets in different directories have the same name. """ import TestGyp test = TestGyp.TestGyp(formats=['ninj...
class Inside(): pass class Outside(): pass class Header(): pass class NoHeader(): pass def check(x): a = x[0] b = x[1] #print(a) #print(b) assert(type(b) == int) assert(b >= 0) if isinstance(a, Header): if b == 0: exit("error 4") else: return(a, b) elif isinstance(a, NoHeader): if b == 0: retu...