text
stringlengths
8
6.05M
''' This is a script to split sample points into test & training sets, then fit to linear regression. INPUTS (in parameter file: -samplePointsCsv -targetField -predictFields -percentTraining -outputPath OUTPUTS: -csv of results ''' import sys, os, gdal import numpy as np from sklearn import linear...
import argparse import time import numpy as np import collections import torch import torch.nn as nn import torch.optim as optim from tensorboardX import SummaryWriter from trading_session_gym.envs.trading_session_gym import TradingSession MEAN_REWARD_BOUND = 0.95 GAMMA = 0 BATCH_SIZE = 20 REPLAY_SIZE = 100000 LEARN...
import datetime import pickle from flask import Flask, render_template, request, flash import untangle import requests from requests import ConnectTimeout app = Flask(__name__) app.secret_key = 'fjas7df98afh879sfh8' file_name = 'todays-movie-id.txt' history_file_name = 'history.txt' section = 1 http_port = 5000 ple...
# a = ('val1', (1, 2 ), (2.5, 5.6, 8.2)) # print(a) # print(type(a)) # print(a[1][1]) '''b = [['gmc', 'audi', 'bmw', 'ford'], ['saquib', 'ayush', 'dan', 'maniac'], [1, 2, 3, 4], [2.3, 4.6, 8.2, 3.4]] print(b) print(type(b)) print(b[0][-1:-3])''' lst = [1, 1, 2, 3, 3] a = tuple(lst) print(a) b = list(a) print(len(b))...
import unittest import decimal as d import complex as c import math class ComplexDecimalTest(unittest.TestCase): def decimal_almost_equals(self, lhs, rhs, epsilon=7): epsilon = pow(10, -epsilon) if abs(d.Decimal(lhs - rhs)) < epsilon: return True return False def check_ty...
import gdcm import numpy import sys import os from PIL import Image, ImageOps def get_gdcm_to_numpy_typemap(): """Returns the GDCM Pixel Format to numpy array type mapping.""" _gdcm_np = {gdcm.PixelFormat.UINT8 :numpy.uint8, gdcm.PixelFormat.INT8 :numpy.int8, gdcm.PixelForma...
import random def rohanmultiplication(number): wrong = random.randint(1,9) # print(wrong) tabel = [i * number for i in range(1,11)] # print(tabel[wrong]) tabel[wrong] = tabel[wrong]+random.randint(1,8) #print(tabel) return tabel def iscorrect(table,number): for i in range(1,11): ...
# python 2.7.3 import sys import math from collections import deque def first2second(n, magic): isBlack = [[False for x in range(magic)] for y in range(magic)] leftmost, lowest = magic, magic for i in range(n): [x, y] = map(int, sys.stdin.readline().split()) isBlack[x][y] = True if ...
# Generated by Django 2.2 on 2019-03-14 19:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wikiApp', '0006_auto_20190314_1629'), ] operations = [ migrations.RemoveField( model_name='newuse...
import random TOTAL = 1000000 RANGE = 100 def main(): accumulative_count = 0 with open("binary.bin", "w") as file: while accumulative_count < TOTAL: count = random.randrange(min((RANGE, TOTAL - accumulative_count)) + 1) file.write(count * str(random.randrange(2))) ...
"""The Python implementation of the GRPC client.""" from __future__ import print_function import logging import sys import os from concurrent import futures import grpc from grpc_reflection.v1alpha import reflection from keysearch.proto import keysearch_pb2 from typing import Text from keysearch.proto.key...
from yusuan_PO.BasePage.BasePage import * from yusuan_PO.BasePage.logger import * from selenium.webdriver.support.ui import Select class NewProject(Page): all_button_loc = (By.LINK_TEXT, '全部') project_list = (By.CLASS_NAME, 'list-over-effect') # 项目列表 new_button_loc = (By.CLASS_NAME, 'text-effect') # 【新...
from django.urls import path, re_path, include from . import views urlpatterns = [ path('', views.dashboard, name='dashboard'), #path('authmail/', views.auth_mail, name='authmail'), path('settings/', include('apps.users.settingsurls')), path('signup/', views.userSignup, name='usersignup'), path('fblogin/'...
''' This script is intended to iterate over a range of errors in natural frequency to determine the residual vibration amplitude of a boom crane subject to luff Created by: Daniel Newman Date: 01-13-2017 ''' from timeit import default_timer as timer import numpy as np from matplotlib import pyplot as plt import os fr...
# 用于跟python解释器进行交互 import sys # print(sys.argv) # 执行:python sys模块.py post download # 结果:['sys模块.py', 'post', 'download'] def post(): print('post') def download(): print('download') # if sys.argv[1] =='post': # post() # elif sys.argv[1] == 'download': # download() # sys.exit(0) # 0表示正常退出 import time...
""" The following function verifies if, given a 'board' setup, the cell (i, j) is safe - can take a queen which would not be attacked. We should verify: - There exists an integer c for which board[i][c] = 1 ; - There exists an integer l for which board[l][j] = 1 ; - There exists an integer k for which board...
from django.db import models class BlogPost(models.Model): """A topic the user is learning about""" title = models.CharField(max_length=200) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model."""...
print("SCSCSSSKYKYKKK"[input()%7::7])
import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" # Scrapy는 Spider의 start_requests 메소드에 의해 리턴 된 요청 오브젝트를 스케줄링한다. # 각 요청에 대한 response인스턴스를 생성하며 요청에 할당된 콜백함수를 호출한다. def start_requests(self): urls = [ 'https://quotes.toscrape.com/page/1/', 'https://quotes....
from django.shortcuts import render from .models import * from django.db.models import Q # Create your views here. def BootstrapFilterView(request): queryset = Journal.objects.all() categories = Category.objects.all() title_contains_query = request.GET.get("title_contains") id_exact_query = request.G...
from app import hello from flask import Flask from flask.helpers import flash app = Flask(__name__) @app.route('/home/user/<string:username>/posts/<int:id>') def function(username,id): return "Hello,"+username+" You are watching your post which id: "+str(id) @app.route('/onlyget',methods=['GET','POST']) def get_r...
#------------------------ # Romberg Method # # Lucas Motta Freire #------------------------ import numpy as np def trapz(a, b, f, t, i): '''Parameters: a, b : Points Extrems; f : integral function t : Value of T(h_i-1); i : index Return: Value of T(h_i)''' if i==0: ...
# my_str = "blablacarblablacar" # my_symbol = "bla" # # my_symbol_count = my_str.count(my_symbol) # print(my_symbol_count) # res_message = f"{my_symbol}\n" * my_symbol_count # print(res_message.strip()) # for _ in range(my_symbol_count): # print(my_symbol) # print(my_symbol * _ ) # my_str = "bla BLA car" # m...
from ConfigParser import SafeConfigParser ### global variables ### configReader = SafeConfigParser() project_name = '' infile = '' gaincnv_path = '' losscnv_path = '' cancer_type = '' spltbams_path = '' het_path = '' nonhet_path = '' outbamfn = '' results_path='' java_path ='' beagle_path='' samtools_path='' bedtoo...
import numpy as np from collections import namedtuple import os import sys os.chdir(sys.path[0]) import imgLibrary if(len(sys.argv)>1): name=sys.argv[1] image=imgLibrary.readP2(name) smooth=imgLibrary.covolve2D2D(imgLibrary.gaussian2D(3,4),image) edges=imgLibrary.detectEdge(smooth) th...
import glob import os import numpy as np import warnings import matplotlib.pyplot as plt from Image_Analysis import image_analysis, write_asymetry_to_file, write_maxima_to_file, write_maxima_to_file_2, write_detections # from Image_Analysis import detect_star from scipy.optimize import minimize from utils import parall...
from keras import Model, optimizers from keras.layers import Input, Dense from keras.utils import to_categorical from keras.datasets import fashion_mnist import matplotlib.pyplot as plt # パラメータ + ハイパーパラメータ img_shape = (28 * 28, ) hidden_dim = 100 output_dim = 10 batch_size = 128 learning_rate = 0.1 epochs = 15 def bu...
import matplotlib.pyplot as plt import matplotlib.ticker as plticker import sys import argparse try: from PIL import Image from PIL import ExifTags from PIL.ExifTags import TAGS except ImportError: import Image def sizeCanvas(imageHeight,imageWidth,canvasHeight,canvasWidth): if imageHeight < image...
# ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
#!/usr/bin/env python from setuptools import setup import os import springserve dir = os.path.split(os.path.abspath(__file__))[0] DESCRIPTION = "API Library for video.springserve.com" LONG_DESCRIPTION = """Springserve is a video adserver, and this library allows you to interface with its api to do read/write and rep...
#!/usr/bin/python3 for i in list( range(ord('a'), ord('e')) ) + list( range(ord('f'), ord('q')) ) + list( range(ord('r'), ord('z') + 1) ): print('{:c}'.format(i), end="")
# que https://www.hackerrank.com/challenges/string-validators/problem?isFullScreen=true #solution if __name__ == '__main__': s = input() print(any([True for c in s if(c.isalnum())])) print(any([True for c in s if(c.isalpha())])) print(any([True for c in s if(c.isdigit())])) print(any([True for c i...
import heapq import sys #import queue import time from collections import namedtuple import time import threading import dummy_threading import smtplib num_workers = 10 class Empty(Exception): "Exception raised by PriorityQueue.get(block=0)/get_nowait()." pass class Full(Exception): "Exception raised ...
import torch __all__ = [ "RNNTLoss", "rnnt_loss", ] def _rnnt_loss_alphas( logits, targets, logit_lengths, target_lengths, blank=-1, clamp=-1, ): """ Compute alphas for RNN transducer loss. See documentation for RNNTLoss """ targets = targets.to(device=logits.devi...
import asyncio from Utils.Timer import Timer from World.Region.RegionManager import RegionManager from Server.Registry.QueuesRegistry import QueuesRegistry class WorldManager(object): def __init__(self): self.heartbeat = 0.01 self.last_update = None self.region_mgr = RegionManager() ...
pDCount = 9 pDSides = 4 cDCount = 6 cDSides = 6 pSums = dict() for x in range(1,37): pSums[x] = 0 for p in range(pDSides**pDCount): pDice = [(p // (pDSides**i) % pDSides) for i in range(pDCount)] pSums[sum(pDice)+pDCount] += 1 for s in pSums: pSums[s] /= pDSides**pDCount cSums = dict() for x in range(1,37): c...
while True: n=int(input()) if n==0: break while n>9: n=sum(list(map(int,list(str(n))))) print(n)
from omnipytent import * from omnipytent.ext.idan import * from omnipytent.completers import file_completer exe = local['./app'] dub = local['dub']['-q'] @task def compile(ctx): dub['build']['--compiler=dmd'] & ERUN.bang @task def run(ctx): dub['run'] & BANG @task def test(ctx): dub['test']['--compil...
import numpy as np import cv2 import cv2.cv as cv cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_SIMPLEX range_R = np.arange(40,205) range_G = np.arange(70,255) range_B = np.arange(0,60) lower_green = np.array([30,120,120]) upper_green = np.array([100,255,255]) while True: ret, img = cap.read() blur =cv2.Gaussia...
from PIL import Image import sys def main(): for args in sys.argv[1:]: image = Image.open(args) image = image.resize((200,200),Image.ANTIALIAS) image.save(args) if __name__ == "__main__": main()
import sqlalchemy from model import * def test1(): session = getSession() print(ImageList) il = session.query(ImageList).one() if __name__ == "__main__": initDb() session : sqlalchemy.orm.session.Session = getSession() simple = session.query(Simple).filter(Simple.id == 1).one() print(sim...
#-*- coding:utf-8 -*- #官方推荐使用 '''#coding=utf-8'''#不推荐使用 print("the first hello world !") '''这是注释''' """这也是注释"""
''' File name: test_script.py Author: Haoyuan(Steve) Zhang Date created: 9/26/2017 ''' ''' File clarification: Check the accuracy of your algorithm ''' import numpy as np # from est_tps import est_tps # from obtain_morphed_tps import obtain_morphed_tps # from morph_tps import morph_tps from morph_tri imp...
import httplib2 import pprint import time import os import shutil #import urllib2 #libraries for gdrive file upload from apiclient.discovery import build from apiclient.http import MediaFileUpload from oauth2client.client import OAuth2WebServerFlow from apiclient import errors from apiclient import http #libraries for ...
def main(): n = int(input("Insira um numero: ")) adjacente = False while n > 0: num1 = n % 10 n = n // 10 if num1 == n%10: adjacente = True if adjacente: print("sim") else: print("nao") #-------------------------------------------------- if __name__ == '__main__': main()
n = int(input("Digite seu número: ")) nao_primo = 0 numero_atual = 2 while numero_atual < n: if n % numero_atual == 0: nao_primo += 1 numero_atual += 1 if nao_primo == 0: print("É primo.") else: print("Não é primo.")
import subprocess import time import os from operator import itemgetter # -- set update/round time (seconds) period = 5 # -- set sorting order. up = most used first, use either "up" or "down" order = "up" # Inicializar variables de Tiempo Lista de Aplicaciones y Lista de ventanas t, applist, winlist = 0, [], [] # Dire...
# -*- coding: utf-8 -*- """Automatic clustering algorithms.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import os.path as op from collections import defaultdict import numpy as np from ....
a = int(input('Escreva um número: ')) b = int(input('Escreva um número: ')) c = int(input('Escreva um número: ')) if a >= b and a >= c and b >= c: print(f'A ordem decrescente é {a} , {b} e {c}') elif a >= b and a >=c and c >= b: print(f'A ordem decrescente é {a} , {c} e {b}') elif b >= a and b >= c and a >= c:...
from setuptools import setup, find_packages setup( name='django-sabayon', version='0.1.1', packages=find_packages(), author='w0de', author_email='harry@sysop.ooo', description='Django support for https://github.com/dmathieu/sabayon' )
#!/usr/bin/env """ ----------------------------------------------- Bardel Written By: Colton Fetters Version: 1.0 First release: 2017 ----------------------------------------------- """ # Import module import os import re import pymel.core as pm import maya.cmds as cmds import maya.mel as mel # Studio mo...
class PagSeguroPaymentParserData: code = None registrationDate = None def getCode(self): return self.code def setCode(self, code): self.code = code def getRegistrationDate(self): return self.registrationDate def setRegistrationDate(self, registrati...
#!/usr/bin/env python3 import gzip import os import subprocess import sys import tempfile import collections SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) try: AOSP_DIR = os.environ['ANDROID_BUILD_TOP'] except KeyError: print('error: ANDROID_BUILD_TOP environment variable is not set.', f...
''' Created on Sep 15, 2015 @author: Jonathan Yu ''' def repeat(word,number): vowels = ["a", "e", "i", "o", "u"] a = word.lower() if vowels.count(a[0]) != 0: return word if len(a) == 1: return word if len(a) == 2: if vowels.count(a[1]) != 0: a = a * number ...
from functools import cached_property from onegov.core.utils import normalize_for_url from onegov.election_day import _ from onegov.election_day.layouts.detail import DetailLayout from onegov.election_day.utils import pdf_filename from onegov.election_day.utils import svg_filename class VoteLayout(DetailLayout): ...
from config import db import random import web class Question(): def __init__(self, description,answer): self.description=description self.answer=answer def get_obf_dot_number(self): return ((len(self.description) % 10)+2)*2 def get_obf_busted(self): busted='..' for c...
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="magic_config", version="0.1.0", author="mogaiskii", author_email="sani.mog@gmail.com", description="declarative settings with multiple backends", long_description=lo...
import torch import torch.nn as nn import numpy as np '''Q Network''' class ImageConv(nn.Module): def _initialize_weights(self): for module in self.modules(): if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): nn.init.orthogonal_(module.weight, nn.init.calculat...
from julia.core import which pytest_plugins = ["pytester"] def test__using_default_setup(testdir, request): if request.config.getoption("runpytest") != "subprocess": raise ValueError("Need `-p pytester --runpytest=subprocess` options.") # create a temporary conftest.py file testdir.makeini( ...
from flask.ext.mail import Message from loghub import mail def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender = sender, recipients = recipients) msg.body = text_body msg.html = html_body mail.send(msg)
# -*- coding: utf-8 -*- import urllib, urllib2, cookielib, time, socket,gzip,StringIO,zlib,inspect,sys from datetime import datetime, timedelta,tzinfo try: import xml.etree.cElementTree as ElementTree except: from xml.etree import ElementTree from epg import * BASE=[ u'http://supertv.3owl.com/USA.xml', u'htt...
#!/usr/bin/env python3 # # Convert a test specification to command-line options import pscheduler from validate import spec_is_valid spec = pscheduler.json_load(exit_on_error=True, max_schema=1) valid, message = spec_is_valid(spec) if not valid: pscheduler.fail(message) result = pscheduler.speccli_build_args...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from telegram.ext import Updater, CommandHandler from telegram.utils.helpers import escape_markdown from telegram import ParseMode import telegram.constants import configparser import logging import requests import strings import feedparser from sqlalche...
import unittest from mytodo.database import User, Todo, Base, dbdriver from datetime import date from mytodo.mytodo import default_time class DbTestCase(unittest.TestCase): def test_get_todos_month(self): result = self.dbdriver.get_todos("test_user1", date(2021, 6, 11), date(2021, 6, 12)) self.as...
from django import forms from books.models import ClubHouseRoom, Book class ClubHouseRoomForm(forms.ModelForm): class Meta: fields = ['room_name'] model = ClubHouseRoom class BookForm(forms.ModelForm): class Meta: fields = ['author', 'title', 'cover'] model = Book
#!/usr/bin/python # Setup and connect the bot to the server, pass along strings to docbot_core from ircutils3 import bot from docbot_core import response # Settings BOT_NAME = "DR" NETWORK = "irc.gamesurge.net" CHANNELS = ["#thefuture",] class DocBot(bot.SimpleBot): def on_welcome(self, event): for cha...
'''This module extends PTP for Nikon devices. Use it in a master module that determines the vendor and automatically uses its extension. This is why inheritance is not explicit. ''' from ..util import _main_thread_alive from construct import ( Container, PrefixedArray, Struct, ) from contextlib import contextmanage...
#import libs import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(40,GPIO.OUT) #Initiakize PWM servo = GPIO.PWM(40,50) servo.start(0) while True: print("0") servo.ChangeDutyCycle(2.5) time.sleep(1) print("180") servo.ChangeDutyCycle(12.5) time...
# -*- coding: utf-8 -*- """ Created on Wed Nov 6 21:06:25 2013 @author: miguel """ class Simbolo(object): def __init__(self,dato,p): self.simbolo = dato self.probabilidad = p self.codigo = "" self.sucesor = None def getProbabilidad(self): return self....
from django.db import models from account_app.models import Account from product_mgr_app.models import Product, Rating class Recommend(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateTimeField('da...
odometer_seq = [] def odometer_speed(x): x = 100000 while x < 999996: x += 1 odometer_seq.append(str(x)) odometer_speed(1000) four_digit_palindromic = [] five_digit_palindromic = [] middle_four_palindromic = [] six_digit_palindromic = [] def four_digit(zz): for i in zz: if ...
from __future__ import print_function import markovify #import tweepy import random import datetime #from keys import keys from unidecode import unidecode import textwrap from Adafruit_Thermal import * # Starts the api and auth #consumer_key = keys['consumer_key'] #consumer_secret = keys['consumer_secret'] #access_to...
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): # flask app 实例化 app = Flask(__name__, static_folder="../fronted", static_url_path="/html", ) # 加载配置 app.config.from_object("config.Config") ...
pocketMoney=int(input('Enter your pocket money:')) if(pocketMoney>500): print('Ew stitnky rich kid') elif(pocketMoney>100): print('I live life') else: print("im purr ")
#!/usr/bin/python3 """select states module""" from sys import argv import MySQLdb if __name__ == "__main__": db = MySQLdb.connect(host="localhost", port=3306, user=argv[1], password=argv[2], database=argv[3]) c...
# 给一些字符串,然后再给一个,判断这个字符串是不是距离一开始中的 # 任意一个编辑距离为一。构造字典,键为给定的单词,值为它可能改变 # 的样子,用 '_' 填充空位,将要查找的单词修改成可能的样子,检查 # 在不在字典的值中,并且键和给定的单词不相等 class MagicDictionary: def __init__(self): """ Initialize your data structure here. """ self.magic = {} def buildDict(self, words): """ ...
class WindowRendererStratgey: def __init__(self): self.pixels_per_unit = None self.x_tiles = None self.y_tiles = None self.screen_width = None self.screen_height = None def reset(self, x_tiles, y_tiles, screen_width, screen_height): self.x_tiles = x_tiles ...
from pennclubs.settings.base import * # noqa: F401, F403 TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner" TEST_OUTPUT_VERBOSE = 2 TEST_OUTPUT_DIR = "test-results" # Use dummy cache for testing CACHES = {"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"}}
#should REALLY get this commented up import math ffac = 0 sfac = 0 a = int(input("Input the a of the polynomial: ")) b = int(input("Input the b of the polynomial: ")) c = int(input("Input the c of the polynomial: ")) ac = a * c radical = 1 def findgcf(a, b): #returns the greatest common factor of a a...
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def main(): # here we create a file access object fout = open('out.txt', 'at') # 'at' append text 'wt' (over)write text 'xt' exclusive - fails if exists # we can switch the context of our print statement so it output to this file access object print('here is some text', file=fout) fout.close(...
#!/usr/bin/env python import neutronclient.v2_0.client as ntclient from.credentials import get_neutron_credits __author__ = 'Yuvv' cred = get_neutron_credits() neutron = ntclient.Client(**cred) # TODO: ''' >>> ops.neutron.list_networks() {'networks': [{u'status': u'ACTIVE', u'subnets': [u'0050c144-91...
vertices = [] with open('./obj/people.obj','r',encoding='utf-8') as f: for line in f.readlines(): if (line.startswith('v ')): line = line.replace('\n', '') value = line.split(' ') vertices.append(str(round(float(value[1]) * 50, 2) - 17)) vertices.append(str(round(float(value[2]) * 50, 2) ...
# 引用计数的缺陷 class Person(object): def __init__(self, name): self.name = name self.next = None self.pre = None def __del__(self): super() print("%s执行了del函数" % self.name) while True: p1 = Person('p1') p2 = Person('p2') # 循环引用 p1.next = p2 p2.pre = p1 ...
#find the sum of all multiples of 3 or 5 below 1000. import sys; def threefivesum(): multiple = 3 counter = 0 while multiple < 1000: counter += multiple multiple += 3 multiple = 5 while multiple < 1000: counter += multiple multiple += 5 multiple = 15 while mu...
from chess.pieces import Pawn from chess.board import Board import pytest def test_pawn_init(): pawn = Pawn(1, 0, False) assert pawn.row == 1 assert pawn.col == 0 assert pawn.is_white is False assert pawn.first_move is True assert pawn.unit == 'p' assert pawn.name == 'bp' assert pawn...
#find if a node is connected or not #l = [[1, 3], [3, 4], [2, 4], [1, 2], [2, 3], [5, 6] , [5 , 7]] l = [[1, 2], [3 , 4] , [5 , 6]] def isReachable(l , m , s , d): visited = [False] * (len(m)) #print(visited) q = [] q.append(s) visited[m.index(s)] = True while ...
from onegov.chat import Message from onegov.org.models.message import TicketMessageMixin class AgencyMutationMessage(Message, TicketMessageMixin): __mapper_args__ = { 'polymorphic_identity': 'agency_mutation' } @classmethod def create(cls, ticket, request, change): return super().cre...
""" Definitions for model that classifies dispatch messages into 24 categories. """ from functools import partial import re from autocorrect import spell, word from sklearn.base import TransformerMixin, BaseEstimator from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from ...
import random # висновок,що не дуже підходить, бо ти можеш завжди вводити максимально велике число # (або може взагалі не число ввести) # (або можеш ввести більше число ніж комп введе) n1 = random.randint(1, 10) answer = input('Enter some integer: ') answer = int(answer) print(f'You choose {answer}, computer {n1}') i...
#!/usr/bin/python2 # coding=utf-8 import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,requests,mechanize from multiprocessing.pool import ThreadPool from requests.exceptions import ConnectionError from mechanize import Browser reload(sys) sys.setdefaultencoding('utf8') br = mechanize.Bro...
from launch import LaunchDescription import launch_ros.actions def generate_launch_description(): return LaunchDescription([ launch_ros.actions.Node( package='topic_subscriber_pkg', executable='simple_sub_node', output='screen'), ])
from rest_api.app import setup_app from rest_api.config import DebugConfig, ProductionConfig app = setup_app(config=ProductionConfig) if __name__ == "__main__": app = setup_app(config=DebugConfig) app.run(host="localhost", port=5000)
import sys import threading from functools import wraps from typing import Union, Tuple, Callable, Optional, List, Type from bugsnag.configuration import Configuration, RequestConfiguration from bugsnag.event import Event from bugsnag.handlers import BugsnagHandler from bugsnag.sessiontracker import SessionTracker i...
#coding=gbk import zipfile import os def zip_files( files, zip_name ): zip = zipfile.ZipFile( zip_name, 'w', zipfile.ZIP_DEFLATED ) for file in files: print ('compressing', file) zip.write( file ) zip.close() print ('compressing finished') if __name__=='__main__': files = ['a.txt'...
# Setup in PyCharm print("Hello World")
# -*- coding:utf-8 -*- """ 一些工具函数 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf input_key = 'input_img' output_key = 'pred' def save_model(sess, inp_tensor, out_tensor, ...
import bottle import os import hashlib from model import Uporabnik, Dnevnik, seznam_zvrsti, seznam_ocen from datetime import date imenik_s_podatki = 'uporabniki' uporabniki = {} skrivnost = 'TO JE ENA HUDA SKRIVNOST' if not os.path.isdir(imenik_s_podatki): os.mkdir(imenik_s_podatki) for ime_datoteke in os.listd...
import networkx as nx if __name__ == "__main__": G = nx.Graph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_nodes_from([ (4, {"color": "red"}) ]) G.add_edge(1, 2) G.add_edges_from([(2, 3), (1, 3)]) print(G.nodes)
# Author: Zequn Yu # PID: A14712777 from __future__ import division #import pandas as pd import numpy import math # function to help add data to array def add_data(line, data, file): while (line): data.append(line.split()) line = file.readline() # read data from files # to save data from files tr...