text
stringlengths
38
1.54M
#!/usr/local/bin/python3 from node import BinaryTreeNode def is_symmetric(tree): def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_0 and subtree_1: return (subtree_0.data == subtree_1.data and check_s...
a = [1,2,3,4,5] print(a) oddnum=[1,3,5,7,9] evennum=[2,4,6,8,10] allnum=oddnum + evennum print(allnum) number=1*3/3 print(number) remainder=11%3 print(remainder) squared= 7**2 print(squared) cubed= 2**3 print(cubed) lotsofhello="hello "*10 print(lotsofhello) helloworld="hello" + " " +"world" print(helloworld) ...
import numpy as np import matplotlib.pyplot as plt import cmath from lab2_part3a import RDFcacl, get_Pk, get_Sk, get_k #TODO: include plt.grid(1) for all plots def get_k_subsample(factor): return get_k()[::factor] # get every 2nd (or 4th or 6th) value of the array def RDFcacl_p7(S, dk, rho): k = get_k_subs...
import discord import datetime from discord.ext import commands class Starboard(commands.Cog): """Starboard module""" def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_reaction_add(self, reaction, member): schannel = self.bot.get_channel(320878957...
from p2pnetwork.node import Node class nodo(Node): archivo = open("numeros_1.txt","w")#Creando txt para los numeros a guardar archivo.close() archivo = open("numeros.txt","w")#Creando txt para los numeros a guardar archivo.close() #Constructor def __init__(self, host, port): super(nodo,...
# 한줄 주석 처리 """ 여러줄 주석처리 - 문자열을 표현하는 방식이나 변수에 담지 않으면 주석처럼 사용 가능 클래스의 설명 주석등으로 사용 가능함 """ ''' 여러줄 주석처리 - 문자열을 표현하는 방식이나 변수에 담지 않으면 주석처럼 사용 가능 클래스의 설명 주석등으로 사용 가능함 ''' print("a") # 화면에 a를 출력합니다. end 와 함께 사용하지 않은 경우 다음 내용이 자동 줄넘김이 되어 출력됩니다. print("b")
import math a=float(input("Enter the value of a")) b=float(input("Enter the value of b")) c=float(input("Enter the value of c")) D=(b*b-4*a*c) print("The values of D is",D) if(D<0): print("Roots are Imaginary") elif(D==0): x1=(-b+math.sqrt(D))//2*a print("Roots are real and equals",x1) elif(D>0): x1=(-b+math.sqr...
import codecs import sys import re def make_sentence(input_file, output_file): '''将语料提取成完整句子,供海量分词使用''' input_data = codecs.open(input_file, 'r', 'utf-8') output_data = codecs.open(output_file,'w', 'utf-8') is_pinyin_line = False for line in input_data.readlines(): if is_pinyin_line: ...
''' Created on 2013-5-19 @author: kfirst ''' import multiprocessing import base64 from flex.network.connection import Connection from flex.base.exception import ConnectFailException import time class Sender(object): EOL = b'#' def __init__(self, logger, buffer_size): self._logger = logger ...
# 1-Addr(非表号) 2-Tag 3..-可选自定义列\ meter_list_str = ''' 010128318569 表1 001522454104 表2 # 000080853040 表3 ''' from forked import dlt645 chn=dlt645.Channel(port_id = '/dev/ttyUSB1', tmo_cnt = 10, wait_for_read = 0.5) # [可选] influxdb (OSS V2.0 tested) influxdb_url="http://192.168.1.72:8086" influxdb_token = "" influxd...
def congruencia (a, b, n): if (a - b) % n is 0: print ("a y b son congruentes mod n") else: raise Exception("Elementos no congruentes mod n") congruencia (8,4,2)
import pytz from datetime import datetime, timedelta autumn_sounds = 'spotify:user:spotify:playlist:37i9dQZF1DX4H7FFUM2osB' autumn_chill = 'spotify:user:mariokristian:playlist:7G8qKmsQOGyguhiEo2o8bl' sleep_tight = 'spotify:user:spotify:playlist:37i9dQZF1DWZd79rJ...
# -*- coding: utf-8 -*- """Example of using Cluster-based Local Outlier Factor (CBLOF) for outlier detection """ # Author: Yue Zhao <yuezhao@cs.toronto.edu> # License: BSD 2 clause from __future__ import division from __future__ import print_function import os import sys # temporary solution for relative imports in ...
# -*- coding:utf-8 -*- from .mytypings import DataFrame, pd def get_head_and_tail(df: DataFrame, n: int = 5): return pd.concat([df.head(n), df.tail(n)])
#!/usr/bin/python import xml.etree.ElementTree as ET import sys if __name__ == '__main__': if len(sys.argv) != 2: raise Exception('Must specify ivy report file') tree = ET.parse(sys.argv[1]) for module in tree.getroot().iter('module'): groupId = module.get('organisation') artifactId = module.get('n...
import objc from PyObjCTools.TestSupport import TestCase class TestFramework(TestCase): def test_normal_lib(self): self.assertIsNone(objc.infoForFramework("/usr/lib/libSystem.dylib")) self.assertIsNone(objc.infoForFramework("/usr/lib/libSystem.B.dylib")) self.assertIsNone(objc.infoForFrame...
""" rllib - Reinforcement Learning Library Unit tests for q_learning module. Goker Erdogan https://github.com/gokererdogan/ """ import sys import numpy as np import unittest from rllib.examples.two_state_world import TwoStateFiniteWorldEnvironment, TwoStateInfiniteWorldEnvironment, \ TwoStateActionSpace from rll...
""" Ejemplo de funciones lambdata @royerjmasache """ lista = [10, 2, 3, 5] print(min(lista, key=lambda a: a))
import numpy as np import numpy.random as npr import tensorflow as tf from tqdm import tqdm import matplotlib.pyplot as plt import time from scipy.integrate import ode keras = tf.keras from sklearn.preprocessing import MinMaxScaler, StandardScaler from tensorflow.keras.models import Sequential from tensorflow.keras.lay...
# -*- coding: utf-8 -*- # code by sil3nt-city # Email : sil3nt.city@gmail.com ############ import urllib2 from BeautifulSoup import BeautifulSoup list=open ('list.txt', 'r') for line in list.readlines(): source = line.strip('\n') try: soup = BeautifulSoup(urllib2.urlopen(source)) print soup.title.string ...
# Copyright 2022 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.txt" file accom...
### Author: EMF Badge team ### Description: Change your name ### Category: Settings ### License: MIT ### Appname : Change name import pyb from dialogs import * from database import * timer = pyb.Timer(3) timer.init(freq=60) timer.callback(lambda t:ugfx.poll()) name = database_get("display-name", "") name_new = prom...
from rest_framework import serializers from . models import Teacher, Student from django.contrib.auth import get_user_model User = get_user_model() #employee serialiser class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ['id','name','phone',] def update(self, inst...
import os, sys lib_path = os.path.abspath('../../classes/') print lib_path sys.path.append(lib_path) # import mymodule # import sys # print sys.path # directory = sys.path[0] # index = directory.rfind('code') # directory = directory[0:index] # directory += "classes" # sys.path.insert(0,directory) from...
from __future__ import print_function import sys, os import getpass import subprocess import shutil from crontab import CronTab def prompt(helper=''): if sys.version_info.major == 2: return raw_input(helper) else: return input(helper) def is_raspberry(): try: return os.uname()[1] == 'raspberrypi' except:...
import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import arcpy import statistics import csv class DistrictStats: def __init__(self, shapefile): self.shapefile = shapefile def summary(self, field, dist_id=None): return Summary(self.shapefile, field, dist_id=dist_...
# © 2019 Nedas Žilinskas <nedas.zilinskas@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from awkhad.http import Controller, route from awkhad.addons.web.controllers.main import Binary class WebsiteSnippet(Controller): @route( '/website_snippet/thumbnail/<int:sid>', ...
# Generated by Django 2.1.4 on 2019-02-07 10:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projectx_app', '0089_auto_20190207_0943'), ] operations = [ migrations.AddField( model_name='myrequesttasksinfo', na...
from typing import List import pymysql from dio_core.utils import json_util from DioTest.DS.DBUtil import SSH def printTable(appIds): with SSH() as server: selectTable(appIds) def selectTable(appIds: List[int]): conn = pymysql.connect("127.0.0.1", "rhino", ...
import multiprocessing import time # 多线程 class A(multiprocessing.Process): # 使用threading.Thread 类创建好 def __init__(self, n): # 使用父类进行初始化 multiprocessing.Process.__init__(self) self._n = n # 定义一个run方法, thread的主方法 def run(self): while True: print("this i...
# Generated by Django 3.1.6 on 2021-06-05 05:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('form', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='details', name='name', ), ...
from flask import send_from_directory, Blueprint aiolia_route = Blueprint("aiolia", __name__) @aiolia_route.route("/<path>") def send_aiolia_page(path): return send_from_directory("aiolia/0.3.1/docs/html", path) @aiolia_route.route("/_static/<path>") def send_aiolia_static_stuff(path): return send_from_dir...
import click import datetime import calendar import os import requests from bs4 import BeautifulSoup import lxml import re def make_url(month, year): url = 'https://www.smashingmagazine.com/{}/{:02d}/desktop-wallpaper-calendars-{}-{}/' new_year = year new_month = month - 1 month_name = calendar.month...
import pj2_clfs_zhihu.config as conf import numpy as np import word2vec def emb2npz(emb_file_path, emb_dict_path): """将txt格式的embedding转为字典格式, 并将<PAD>和<UNK>加入""" emb = word2vec.load(emb_file_path) vec = emb.vectors word2id = emb.vocab_hash word2id['<PAD>'] = len(word2id) pad_row = [0] * vec.sh...
def count_vowels(text, a, b): i = a count = 0 while i <= b: char = text[i] if (char == 'a') or (char == 'e') or (char == 'i') or (char == 'o') or (char == 'u'): count += 1 i+= 1 return count print(count_vowels('one fish wasifeee two fish', 1, 20))
import xml.etree.ElementTree as ET import sys class ScannerConfigLoader(): def __init__(self, configFile): self.config = {} tree = ET.parse(configFile) root = tree.getroot() for child in root: if child.tag == "Channels": self.config['Channels'] = [] for element in child: self.config['Channels...
buffer = [0] steps = 349 #number of steps to take each cycle cycles = 100000 #number of cycles to take position = 0 tracker = [] #keeps track of iterations that give position 1 #def spinlock(list, position, tracker): # #adds a number to a list according to the spinlock instructions # #returns list and new po...
# -*- coding: utf-8 -*- import re import pytest import mimesis from mimesis.data import CURRENCIES, CURRENCY_SYMBOLS from . import _patterns as p @pytest.fixture() def _business(): return mimesis.Business() def test_str(business): assert re.match(p.STR_REGEX, str(business)) def test_copyright(business)...
""" BSD 3-Clause License Copyright (c) 2019, Andrew Riha 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 the above copyright notice, this list of condit...
# -*- coding: utf-8 -*- # Copyright 2012 UNED # # 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 agree...
#!/usr/bin/env python # encoding: utf-8 name = "Intra_Diels_alder_monocyclic/groups" shortDesc = u"Intramolecular ring-closure by concerted addition of two alkene end groups in a 6-membered conjugated backbone (C=C-C=C-C=C) to an unsaturated cyclohexane product" longDesc = u""" """ template(reactants=["1_3_5_unsatu...
import os from tools_lib.lib.os_platform.os_platform import OSPlatform def energenie_control(sleep, cmd, socket): cmd = f"python3 $HOME/rpi_styra/services/energenie/py/{cmd}-{socket}.py" if OSPlatform.is_linux(): os.system(cmd) print(f"cmd: {cmd}")
import numpy as np max_interval_s = 60*60*24 min_interval_s = 30 def new_interval(current): new_interval_s = current * 1.2 if new_interval_s > max_interval_s: return max_interval_s elif new_interval_s < min_interval_s: return min_interval_s else: return new_interval_s interva...
import numpy from obs80 import obscode from obs80 import obs80 from obs80 import leapsec from obs80 import obs80hc def test_hc(): hc = obs80hc.HCAnnotator( obscode.siteXYZ(obscode.read5c('obscode.dat')), leapsec.LeapSeconds('leap-seconds.list')) o = obs80.parseOpt('00433 2C2012 05 02.13...
# -*- coding: utf-8 -*- """ Projeto disciplina PCS5031 - Introdução à Ciência dos Dados @author: Rodrigo Müller de Carvalho @author: Eduardo Dias Filho """ class CountryInfo: def __init__(self, country_data): """ country_data is an array containing the info about a country. """ ...
# Import pandas import pandas as pd def open_excel(path_to_excel): print("="*67) print("=== Reading file at '{}' with pandas library\t===".format(path_to_excel)) file = path_to_excel xl = pd.ExcelFile(file) main_sheet = xl.sheet_names[0] df = xl.parse(main_sheet) print("=== Success! Loaded...
#!/usr/bin/env python # coding: utf-8 # ### Grouping # - 참고 : https://pandas.pydata.org/docs/reference/api/pandas.date_range.html # In[1]: import numpy as np import pandas as pd # In[3]: df = pd.DataFrame({ 'A' : ['cho1', 'young1', 'cho1', 'young1', 'cho1', 'young1', 'cho1', 'young1'], 'B' : ['one', 'tw...
#!/usr/bin/python # -*- coding: utf-8 -*- #from __future__ import print_function from datetime import date, datetime, timedelta import MySQLdb import SocketServer from socket import * import thread #import mysql.connector #from mysql.connector.constants import ClientFlag import sys #sys.path.insert(0, 'python{0}/'.form...
from django.db import models from django.contrib.auth.models import User class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Product(models.Model): name = models.CharField(max_length=50) price = models.DecimalField(decimal_pla...
from array_binary_search import binary_search def test_one(): expected = 2 actual = binary_search([4, 8, 15, 16, 23, 44], 15) assert expected == actual def test_two(): expected = -1 actual = binary_search([4, 8, 15, 16, 23, 44], 30) assert expected == actual def test_three(): expected = -...
#!/usr/bin/env python """ CIJOE test extractor """ from __future__ import print_function import argparse import sys import os import cij.extractor import cij.runner import cij.util import cij def parse_args(): """Parse command-line arguments for cij_extractor""" # Parse the Command-Line prsr = argparse...
from app import db class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(50), unique=False, nullable=False) last_name = db.Column(db.String(50), unique=False, nullable=False) address = db.Column(db.String(120), unique=False, null...
# https://programmers.co.kr/learn/courses/30/lessons/43163 # 단어 변환 # 걸린 시간 0:10 def is_near(wordA, wordB): diff = False for i in range(len(wordA)): if wordA[i] != wordB[i]: if not diff: diff = True else: return False return True from collecti...
# Parameters for dataset and data loader data_root = 'data' batch_size = 128 image_size = 28 # Parameters for optimizing models lr_src_enc = 0.0001 lr_tgt_enc = 0.00005 lr_dis = 0.001 beta1 = 0.5 beta2 = 0.9 # Parameters for training models model_root = 'backup' epochs_pre = 20 test_step_pre = 10 save_step_pre = 10 ...
##\package buildingGen.utils.utils_OBJ # Object utilities import bpy import math from . import utils_GLO from .utils_GLO import print_debug ##\brief Duplicates a mesh. #\returns (Mesh) The duplicated mesh. #\param copymesh (Mesh) The mesh to be duplicated. def duplicateMesh(copymesh): mesh_new = bpy.data.mesh...
# import requests # print(requests.get("http://sz.ganji.com/shouji/o1/%E5%BE%AE%E6%B3%A2%E7%82%89/").content.decode("utf-8"))
import unittest from selenium import webdriver from pages.main_page import MainPage class BaseTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://dopoznania.pl/') self.driver.maximize_window() MainPage(self.driver).wait_for_page_to...
import json from django.test import TestCase from main.export import export from main.models import Comment from test082018.local_storage import storage class ExportTestCase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() storage.set_user_id(100) for idx in range(10...
"""Argparser module for pinging""" from jina.parsers.base import set_base_parser def set_ping_parser(parser=None): """Set the parser for `ping` :param parser: an existing parser to build upon :return: the parser """ if not parser: parser = set_base_parser() parser.add_argument( ...
# Copyright (c) 2015 # # All rights reserved. # # This file is distributed under the Clear BSD license. # The full text can be found in LICENSE in the root directory. #!/usr/bin/env python import re try: from urllib.request import urlopen except: from urllib2 import urlopen class TestsuiteConfigReader(object...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Support module generated by PAGE version 5.4 # in conjunction with Tcl version 8.6 # Aug 27, 2020 09:17:14 PM CEST platform: Windows NT import sys try: import Tkinter as tk except ImportError: import tkinter as tk try: import ttk ...
# -*- coding:utf-8 -*- from eagleEye.exts import db, Model, FlagStatus class Cinema(db.Model, Model): __tablename__ = "cinemas" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) city = db.Column(db.String(32)) district = db.Column(db.String(32)) address = db....
import pandas as pd import matplotlib.pyplot as plt import matplotlib from pandas.tools.plotting import andrews_curves plt.style.use('ggplot') df = pd.read_csv('Datasets/wheat.data') #df = df.drop(labels=['id', 'area', 'perimeter'], axis=1) plt.figure() andrews_curves(df, 'wheat_type') plt.show()
from graphql import GraphQLError from graphene import ObjectType, Mutation, Boolean, Int, String, Field from opcuautils import getServer, getServers, setupServers from graphene_schema.query import OPCUAVariable from graphene_schema.scalars import OPCUADataVariable import graphene_schema.descriptions as d import os impo...
import happybase as hb connection = hb.Connection('localhost') connection.open() print connection.tables()
from flask import request from . import api from ..models import db, Credential from ..decorators import json, collection, cors @api.route('/token/', methods=['POST']) @cors @json() def new_token(): pass @api.route('/credentials/', methods=['GET']) @cors @json() @collection(Credential) def get_credentials(): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) logging.basicConfig() logger.setLevel(logging.DEBUG) def obtain_python_version(): import sys python_version = sys.version logger.debug('python version %s' % python_version) return python_version def o...
# coding: utf-8 # In[1]: import sysconfig import os import numpy as np import pandas as pd import json import distutils import scrapy import requests import json import logging import string import re from scrapy.crawler import CrawlerProcess from scrapy.selector import Selector from requests import Request from ma...
import requests from typing import Any, Dict, List from strava_flow.api.strava.credentials import StravaCredentialsService class StravaHttpClient: _URL = 'https://www.strava.com/api' _PER_PAGE_DEFAULT = 30 _GET = 'get' _POST = 'post' _PUT = 'put' def __init__(self, credentials_service: Strav...
# JUNGLE : KHRYSTYNA OLIYNYK import pickle f=open("hero.dat", "rb+") hero=pickle.load(f) #Description of the setting print("""\n\nAfter getting to the island the hero was wandering around, became hungry and decided to go in the direction of the high and wonderful looking trees where she hoped to find s...
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # © 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Skarphed. # # Skarphed is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as ...
#Exercício Python 059: Crie um programa que leia dois valores e mostre um menu na tela: #[ 1 ] somar #[ 2 ] multiplicar #[ 3 ] maior #[ 4 ] novos números #[ 5 ] sair do programa #Seu programa deverá realizar a operação solicitada em cada caso. c = True x = float(input("Primeiro valor: ")) y = float(input("Segundo valo...
rule earth: shell: 'echo "hello earthling"' rule space: resources: alien=1, shell: """ echo 'hello alien number {resources.alien}' """
# def exibir(a, b, c): # print(a, b, c) # # # # fixa o valor de a # def exibir5(b, c): # exibir(5, b, c) # # # # fixa o valor de c # def exibir54(c): # exibir5(4, c) # # # # chama # exibir54(2) # ------------------------------------------------------------------------------ # def equacao_terceiro_grau(a, ...
def sumar(a , b): c = a + b return c def restar(a , b): c = a - b return c def multiplicar(a , b): c = a * b return c def dividir(a , b): c = a / b return c def resto(a , b): c = a % b return c def elevar(a , b): c = a ** b return c #continua en el bloque siguiente -> if __name__ == "__main__": numero_1=1...
#!/usr/bin/env python3 import sys, argparse, os import pandas as pd try: from lib import combine_methods as cm except: import combine_methods as cm try: from joblib import Parallel, delayed import multiprocessing except: print("No MultiThreading available, running on single threadself.") def get_a...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) """Weak-reference support module.""" from builtins import _index from _builtins import ( _builtin, _property, _type, _unimplemented, _weakref_callback, _weakref_check, _weakref_guard, _w...
#coding=utf-8 import sys sys.path.append('../../../lib/dm/spider') import urllib from minisb import MiniSpider seeds = [] tag_list = open(sys.argv[1]).readlines() for tag in tag_list: url = 'https://search.yahoo.com/search?p=%s' % tag url += '+filetype%3apdf' url_req = urllib.parse.quote(url, safe=':/?=%+') seeds...
import sys import termios import time import tty def read_key(): ''' Read a single key from stdin ''' try: fd = sys.stdin.fileno() tty_settings = termios.tcgetattr(fd) tty.setraw(fd) key = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, ...
from django.conf.urls import url, include from .views import CategoryList, MainView, ItemDetail, CreateItem, CategotyView, CategoryViewSet, ItemViewSet, \ DetailView, CreateItemView from rest_framework.urlpatterns import format_suffix_patterns from rest_framework import routers router = routers.DefaultRouter() ro...
#Author: kobe www.cnblogs.com/alex3714/articles/5465198.html type(2**32) #整型int 32位机器 -2**31--2**31-1 64位机器 -2**63--2**63-1 #浮点型 E表示10的幂,52.3E-4表示52.3*10**-4 科学计数法 #布尔值 真或假 1或0 >>> a=0 >>> if a :print("a") ... >>> a=1 >>> if a:print("a") ... a >>> ##三元运算 >>> a,b,c = 1,3,5 >>> d = a if a>b else c >>> d 5 >>> #...
from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: ans = {} for i in range(len(board)): for j in range(len(board)): if board[i][j].isdigit(): n = int(board[i][j]) if not self.isValid(n, i, ans): return False if no...
from django.db import models from django.utils.translation import gettext_lazy as _ class Contact(models.Model): name = models.CharField(verbose_name=_('Name'), max_length=200) email = models.EmailField(verbose_name=_('Email')) phone_number = models.CharField(verbose_name=_('Phone Number'), max_len...
from astropy.units import Quantity class Catalog(object): def __init__(self,label,table,filters,columns_2_filters,columns_2_position): self.label = label self.table = table self.photo = filters self._MAPS = columns_2_filters self._MPOS = columns_2_position def __str__(s...
# custom_storages.py from storages.backends.s3boto import S3BotoStorage from django.conf import settings class StaticStorage(S3BotoStorage): location = settings.STATICFILES_LOCATION
import re import sys filename = "maillog" the_regex = "(([A-Z][a-z][a-z]{1})([\s]*[1]{1}[\s]*)..:([0-5][0-9]):([0-5][0-9])).[a][v][a][s].[p][o][s][t][f][i][x].{14}[a-z]{7}.{6}[a-z]*[[]([0-9.]*)]" pattern = re.compile("%s" % the_regex, re.I) open("log2","w").close() file = open(filename,"r") mydict = {} mydict2 = {} loo...
from io import StringIO import sys class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().split()) sys.stdout = self._stdout
import unittest import pyglet import pywavefront.texture class TestTexture(unittest.TestCase): def setUp(self): pyglet.resource.path.append('@' + __name__) pyglet.resource.reindex() def testPathedImageName(self): "For Texture objects, the image name should be the last component of th...
import re def valid(pin): if len(pin) == 4 or len(pin) == 6: match = re.search(r'\D', pin) if match: return False else: return True else: return False
""" ЗАДАНИЕ -------------------------------------------------------------------------------- На сервере хранятся данные пользователя. Пользователь решил очистить список своих номеров. Написать функцию clear_list, которая будет очищать переданный список. ПРИМЕРЫ --------------------------------------------------------...
# Brooks Brickley & Hector Hernandez CC: 2019 from statistics import mean from math import sqrt before = input('What is the name of the before file? : ') + '.csv' after = input('What is the name of the after file? : ') + '.csv' beforeID = open(before, 'r') data = [] firstline = beforeID.readline() nextline = beforeID...
from __future__ import print_function from __future__ import absolute_import import numpy as np from . import annsa as an from scipy.interpolate import griddata background_locations = ['albuquerque', 'chicago', 'denver', 'losalamos', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'tclh123' import os import urllib import core import models import util import webapp2 import jinja2 import logging from google.appengine.ext import db jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)+'/te...
# File: Grid.py # Description: Recursion # Student Name: Andrew Chen # Student UT EID: ac68644 # Partner Name: Saaketh Palchuru # Partner UT EID: srp2992 # Course Name: CS 313E # Unique Number: 50210 # Date Created: 10/10/19 # Date Last Modified: 10/12/19 # counts all the possi...
# # @lc app=leetcode id=53 lang=python3 # # [53] Maximum Subarray # # @lc code=start class Solution: def maxSubArray(self, nums: List[int]) -> int: currentMaxes = [0] * len(nums) currentMaxes[0] = nums[0] result = currentMaxes[0] for i in range(1, len(nums)): currentMaxe...
from django.urls import path,re_path from blog.views import (blog_post_details_view, blog_post_list_view, blog_post_update_view, blog_post_delete_view ) urlpatterns = [ path('', blog_post_list_view), path('<str:slug...
#Diego Aspinwall #9-26-17 #graphAPoint.py from ggame import * red = Color(0xFF0000,1) black = Color(0x000000,1) blackOutline = LineStyle(1,black) blackLinex = LineAsset(0,400,blackOutline) blackLiney = LineAsset(400,0,blackOutline) xt = LineAsset(0,10,blackOutline) yt = LineAsset(10,0,blackOutline) xpt = float(inp...
"""Perform all analyses. """ from os import makedirs from os.path import exists from time import time from models import fit_model, modela, modelb from figures import fig12, fig3, fig4 from tables import table2, table3 def main(): print("performing all analyses for the 'perceptual anchors' paper") started ...
import torch import torch.nn as nn import torch.nn.functional as F class Encoder(nn.Module): def __init__(self, config, vocab): super(Encoder, self).__init__() self.bi = config.bi self.embed_size = config.embed_size self.batch_size = config.batch_size self.recuda = config...
# Copyright 2020 ArcTouch LLC (authored by Thiago Werner at ArcTouch) # # 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 us...