text
stringlengths
38
1.54M
from flask import Flask, jsonify, request from flask_pymongo import PyMongo app = Flask(__name__) app.config["MONGO_URI"] = "mongodb://okteto:okteto@mongodb:27017/okteto" mongo = PyMongo(app) @app.route("/", methods=["GET"]) def get_messages(): messages = [] for m in mongo.db.messages.find(): message...
# 主要记录python中的元组类型 # 元组属于不可变数据类型,包含任意数目的各种python对象,使用圆括号()来定义,可以用做字典的key # 元组和列表的比较: # 相同点:都是序列,都可以根据索引访问,都可以存放任何类型数据 # 不同点:list用[]创建,tuple用()创建;list可变,tuple不可变; # python一般分配较大内存块给tuple,因为它不可变,较小内存块给list,因此大量元素时tuple比list快 # 声明一个元祖 tuple_1 = () print(type(tuple_1)) # 元组创建赋值 atuple = (123, 'abc', 3.14, ['alist', 45...
def process(case_num): (candy_bags, kids) = tuple(map(int, input().split())) candies = list(map(int, input().split())) remain = sum(candies) % kids print(f'Case #{case_num}: {remain}') t = int(input()) for i in range(1, t + 1): process(i)
"""The casambi integration.""" # https://developers.home-assistant.io/docs/creating_component_index/ # https://github.com/home-assistant/core/blob/dev/homeassistant/components/unifi/__init__.py # https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_light/ # https://developers.ho...
''' I got issues with overlapping subtitles on .srt files. The extension for chrome browser Substitial does not read them well. So I can edit subs. No more overlapping! ''' from sys import argv def extract_times(line): parts = line.split() current_time_first = parts[0] current_time_last = parts[2] r...
import torch from torch.utils.data import ConcatDataset from dataset.voc_dataset import VOCDataset device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') model_pth = 'pretrained models/vgg_voc_0.0001lr_1.90828loss_0.74948acc.pth' model = torch.load(model_pth).to(device) model.classifier = torch.nn.Seq...
from django.shortcuts import render, redirect from django.contrib.auth.models import User def index_view(request): if not request.user.is_staff: return render(request, 'error.html') user = User.objects.all() return render(request, 'app_admin/index.html', {'user_list': user}) def detail_view(request, use...
from copy import copy, deepcopy from enum import Enum from moves import * import random import collections from monte import GameState, PlayGame, ISMCTS from itertools import chain, combinations import hook import operator import numpy as np VERBOSE_LOG = False def powerset(iterable): """ powerset([1,2,3]) --...
#Encrypted By MAFIA-KILLER #WHATSAPP : +92132197796/DON,T TRY TO EDIT THIS TOOL/ import zlib, base64 exec(zlib.decompress(base64.b64decode("eJztHGtz2kjye6ryH2a36gJcsN684vJtCRAxZUAsCCeO7aIEGkBrPYgkYpzL/ffr0QMkjIAYO7eXyiTYo5npnp5+TU9rsG7ObcdDtptH7gP88HQT55GmejioOaql2WYezVR3ZugjaIBGb+ZgVdOtaR795dpWHi0cw+8c2/adjv3qFHtz1XVf...
""" File: number_of_words.py Name: ------------------------------- This file calculates the number of words in romeojuliet.txt by using word.split() and basic Python list operations """ FILE = 'romeojuliet.txt' def main(): if __name__ == '__main__': main()
from django.test import TestCase from nlpviewer_backend.models import Document, Project class DocumentTestCase(TestCase): def setUp(self): a = Project.objects.create(name="project1", ontology='I am ontology') Document.objects.create(name="doc1", ...
import sys import os sys.path.append(os.getcwd()) from UtilFuncs.screens import Interaction as interact, Authenticate as auth from socket import * from UtilFuncs.User import User import logging import time import os class TCPClient: def __init__(self, protocol="TCP", server_address="127.0.0.1", port=12345) -> Non...
from django.db import models from django.core.exceptions import ValidationError """ DB structure: Game - just id Turn - id, game_id, field_num Most of business-logic is located in Game model - building board - player's turn determination - checking turns (only same field attempts, ...
import numpy as np license=""" Copyright (C) 2014 James Annis This program is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. More to the points- this code is science code: buggy, barel...
# coding=utf-8 from django.contrib import admin from objects.models import * from django import forms class ConfigForm(forms.ModelForm): template = forms.CharField(widget=forms.Textarea) class Meta: model = Config class ConfigAdmin(admin.ModelAdmin): form = ConfigForm readonly_fields = ('p...
import multiprocessing as mp import numpy as np import tensorflow as tf from tensorflow import keras from matplotlib import pyplot as plt import gym from DeepRL.Async_Actor_Critic.Worker import Worker from DeepRL.Async_Actor_Critic.Utilities import create_actor_critic_model, accumulate_gradients class Master: def...
''' Script to estimate probabilistic power spectral densities for one combination of network/station/location/channel/sampling_rate. (https://docs.obspy.org/tutorial/code_snippets/probabilistic_power_spectral_density.html) Calculations are based on the routine used by [McNamara2004]: McNamara, D. E. and Buland, R. P....
import sys from pathlib import Path import librosa import numpy as np import pandas as pd import pytorch_lightning as pl import torch import tqdm.contrib.concurrent from lib import CLIP_LENGTH, MIN_CLIP_LENGTH, get_mel_mat, load_audio, stft EPS = 1e-20 # This is a random list of Common Voice languages. VAL_LANGS = "...
from typing import List from collections import namedtuple, deque import numpy as np ReplayBatch = namedtuple( 'ReplayBatch', ['states_before', 'actions', 'states_after', 'rewards', 'done_flags']) ReplayBatchLong = namedtuple('ReplayBatch', [ 'states_before', 'actions', 'states_after', 'rewards', 'done_fl...
from __future__ import print_function import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously import matplotlib.pyplot as plt import matplotlib as mpl# ; #mpl.use("Qt4Agg") import matplotlib.animation as manimation import torch from torch.autograd import Variable import torch.nn.function...
from setuptools import setup, find_packages import pydht with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='pydht', version=pydht.__version__, description='Python DHT Implementation', long_description=readme, author='Isaac Zafuta', ...
import csv import pycountry from django.core.management.base import BaseCommand from django.utils.text import slugify from artifacts.models import Artifact, ArtifactType, ArtifactMaterial class Command(BaseCommand): help = "Import artifacts from csv." def add_arguments(self, parser): parser.add_arg...
import pandas as pd from tqdm.auto import tqdm class TokenSequenceSegmenter: def __init__( self, segment_length: int = 500 ): self.segment_length = segment_length def whole_df_to_segmented_df( self, df: pd.DataFrame, parsed_col: str, ...
from lark.tree import pydot__tree_to_png from src.loading_rules_to_tree import * from src.functions import * class Rule: def __init__(self, name: str, pos_b: str, pos_a: str, tags_b: Dict[str, str], raw_rules: str): self.name = name self.pos_a = pos_a self.tags_b = dict() ...
#/usr/bin/python import mx.ODBC.unixODBC as odbc import numpy as np # Connect to the database db = odbc.DriverConnect("DSN=ramses17;UID=wsaro;PWD=wsaropw") # Initiate the Cursor cursor = db.cursor() # remove old lasID column cursor.execute("ALTER TABLE cmurray..MGS_contour_tbl DROP COLUMN lasID;") # Add lasID colu...
from asyncio import TimeoutError, sleep from datetime import datetime from os import getcwd from subprocess import getoutput from time import perf_counter from discord import Embed, Colour, errors from discord.ext import commands, tasks from .loader import __version__ class HelpCommand(commands.HelpComm...
import scrapy ''' important notes for usage of the spider: the spider takes two arguments: the category you want to crawl and the label you want to give and the number of pages you want crawled example: scrapy crawl youm -o data.json -a label=0 -a pages=20 -a category=علوم-و-تكنولوجيا/328/ scrapy crawl youm -o data...
import numpy as np input_num = int(input("input data :")) a = 1 b = 2 c = 3 def hanoi(n, a, b, c): if n == 1: print(a, c, sep = " ") else: hanoi(n-1, a, c, b) print(a, c) hanoi(n-1, b, a, c) print(2**input_num-1) if(input_num <= 20): hanoi(input_num, a, b, c) ...
import statsmodels.api as sm from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score import sklearn as sk import pandas as pd import numpy as np import os def get_metrics(y_actual, y_predicted): print("Confusion Matr...
from django.db import models class Article(models.Model): title= models.CharField(max_length=100) author= models.CharField(max_length=100) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
""" IMPORTING LIBS """ import dgl import numpy as np import os import socket import time import random import glob import argparse, json import pickle import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader from tensorboardX import S...
import mol2 import sys print "this file requiers the mol2 libary writen by trent balius and sudipto mukherjee" print "syntex: mol2_removeH.py input_file output_file" infile = sys.argv[1] outfile = sys.argv[2] mol_list = mol2.read_Mol2_file(infile) cmol = mol2.centre_of_mass( mol_list[0] ) print cmol fh = open(outf...
#!/usr/bin/python3 import argparse import os # Import Purity//FB SDK from purity_fb import PurityFb, Bucket, ObjectStoreAccessKey, Reference, rest # Disable warnings related to unsigned SSL certificates. import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def main(): parser = arg...
# -*- coding: utf-8 -*- from arrays import Array class Grid(object): def __init__(self,rows,columns,fillValue=None): self.data=Array(rows)#初始化行 for row in range(rows): self.data[row]=Array(columns,fillValue)#初始化列 def getHeight(self):#获取行数 return len(self.data) def getWidth(self):#获取列数 return len(self.da...
#!/usr/bin/env python -O import argparse import nltk import numpy as np import pytest import re import optimizers import order_problem nltk.download('stopwords', quiet=True) nltk.download('punkt', quiet=True) nltk.download('wordnet', quiet=True) PASSAGE_SEPARATOR = "\n\n" STOPWORDS = set(nltk.corpus.stopwords.words...
#Parameters to be changed ARDUINO_PORT_NAME = 'COM9' #Fixed parameters ARDUINO_SERIAL = 9600 FREQ_COMMANDS = 0.025 FINGER_NAME = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky'] N_SCANSIONI_TRAINING = 5 FINGER_TIP = 3 SERVO_MAX = 180 SERVO_MIN = 0
from sqlalchemy.dialects.postgresql import JSON from sqlalchemy.orm.exc import NoResultFound from time import time from ..config import app, db, FACE_ENGINES class Face(db.Model): __tablename__ = 'face' id = db.Column(db.Integer, primary_key=True) encoding = db.Column(JSON) face_pp_set = db.Column(db.String)...
from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.template import loader from django.urls import reverse from django.views import generic from django.views.decorators.http import require_http_methods from django.utils import ...
import numpy as np import time start = time.time() print("\n(Map) multiplying 32 million elements by 2") dbls=np.arange(32000000)*2 print("(Reduce) sum: %d" % sum(dbls)) end = time.time() print("Total MapReduce time: %f" % (end-start))
#1. We have provided some synthetic (fake, semi-randomly generated) twitter data in a csv file named project_twitter_data. #csv which has the text of a tweet, the number of retweets of that tweet, and the number of replies to that tweet. #We have also words that express positive sentiment and negative sentime...
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm # importing login as auth_login to prevent clashing with inbuilt view from django.contrib.auth import login as auth_login from django.contrib.auth.decorators import login_required from django.cont...
#!BPY # Copyright (C) 2010 Florent Monnier # # This software is provided "AS-IS", without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commerc...
import sys import numpy as np import threading import argparse from fast5_research import Fast5 from tqdm import tqdm import h5py from uuid import uuid4 import matplotlib.pyplot as plt base_dict = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 0, 'c': 1, 'g': 2, 't': 3} class Model: def __init__(self,model_path): f ...
# 2. Написать два алгоритма нахождения i-го по счёту простого числа. # Функция нахождения простого числа должна принимать на вход натуральное и возвращать соответствующее простое число. # Проанализировать скорость и сложность алгоритмов. # Первый — с помощью алгоритма «Решето Эратосфена». # Примечание. Алгоритм «Ре...
class Station: """Class that contains a station""" def __init__(self, name, latitude, longitude, critical): """Args: name (String) : the name of the Station latitude (String) : the latitude of the Station longitude (String) : the longitude of the Station critical (String) : indicates whether a Stat...
class Node: def __init__(self,dataval): self.dataval=dataval self.nextval=None class Linkedlist: def __init__(self): self.headval=None def printval(self): printval=self.headval while printval!=None: print(printval.dataval) printval=printval.nex...
#!/usr/bin/env python import unittest from dominion import Game, Card, Piles import dominion.Card as Card ############################################################################### class Card_Mercenary(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = [Card.CardType.AC...
import cv2 import os inputname='TumeBeach' format = 'mp4' vidcap = cv2.VideoCapture('./input/'+inputname+'.'+format) success,image = vidcap.read() count = 0 directory = './'+inputname if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists(directory+'/people'): os.makedirs(directory+...
from header import * def out_size(l_in, kernel_size, padding=0, dilation=1, stride=1): a = l_in + 2*padding - dilation*(kernel_size - 1) - 1 b = int(a/stride) return b + 1 class cnn_encoder(torch.nn.Module): def __init__(self, params): super(cnn_encoder, self).__init__() self.para...
from math import sin, asin, pi, radians, cos, atan2, exp, tan, acos, atan2 from renmas3.base import Vector3 from .surface import SurfaceShader # latitude - (0 - 360) # longitude - (-90, 90) south to north # sm = standard meridian -- actually time zone number # jd = julian day (1 - 365) # time_of_day (0.0 - 23.99) 14...
# -*- coding: utf-8 -*- """ Created on Thu Sep 9 18:49:21 2021 @author: pc """ #Number of test cases T=int(input()) #Input and computation #Res=list() for i in range(T): num=int(input()) count=0 while num>0: temp=int(num%10) num=num//10 #print("temp: ",temp) if(temp==4): ...
#author : Yuwono Bangun Nagoro (a.k.a SurgicalSteel) from tweepy.streaming import StreamListener from tweepy import Stream import json import tweepy import sys auth = tweepy.OAuthHandler("YOUR-CONSUMER-KEY","YOUR-CONSUMER-SECRET") auth.set_access_token("YOUR-ACCESS-TOKEN","YOUR-TOKEN-SECRET") api = tweepy.API(auth) c...
#!/usb/bin/python import re import time from datetime import datetime # Example line: # Oct 25 07:03:28 localhost nullmailer[2319]: Sending failed: Host not found regex = re.compile('(?P<time>\w{3} \d{1,2} \d\d:\d\d:\d\d) (?P<host>.*?) (?P<rawprocess>(?P<process>.+?)(\[\d+\])?): (?P<message>.*)') def process(data, ...
 import base64 import struct import gnupg import hashlib import otrmanager import otrimplement #import networkmanager #import usermanager # by wrapping with message block, we can add some control message MSG_TYPE_NONE = 0 MSG_TYPE_ENCRYPTED = 1 MSG_TYPE_VERIFY = 2 class MessageBlock : def __init__(self): ...
import importlib import os from arcgis import GeoAccessor from arcgis.geometry import Geometry from requests import post if importlib.util.find_spec("dotenv") is not None: from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) # try to load the placekey_arcgis key from the environment variabl...
class Tree: def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right def __str__(self): return str(self.value) def findMaxPath(test): if test == 1: strTriangle = genFirstTest() elif test == 2: strTriangle = genSecondTest() triangle = genTree(st...
'''parser sintaksnog analizatora''' from sintaksni_analizator import SintaksniAnalizator from leksicka_jedinka import LeksickaJedinka from zajednicki.produkcija import Produkcija from zajednicki.akcija import Akcija class ParserAnalizatora: '''parsira sve upute potrebne sintaksnom analizatoru 1 - tablice...
import sys sys.path.append('/usr/local/lib/python2.7/site-packages') from picamera import PiCamera from bounds_test_copy import * from beacon_manipulation import * from determine_location import * from robs_code import * from pprint import pprint import smbus # Setup Bus bus = smbus.SMBus(1) address = 0x04 usingTer...
#Contribiuted by Shyam Yadav [github/YA12SHYAM] #implementing recusion solution of Tower of Hanoi in python def solve_hanoi(n,from_rod,to_rod,use_rod): if(n==1): print("Move disk 1 from rod {} to_rod {}".format(from_rod,to_rod)) else: #solve top n-1 disc from source rod to auxillary/Using rod solve_han...
# BOJ 10757 큰 수 A+B # https://www.acmicpc.net/problem/10757 import sys a, b = map(int, sys.stdin.readline().split()) print(a+b)
import math import sys # pylint:disable=no-self-use class View: """ This class is responsible for displaying information to the user. """ def __init__(self, terse, reverse, cram): self.terse = terse self.reverse = reverse self.cram = cram def print_question(self, card): fr...
import numpy as np import pandas as pd from matplotlib import pyplot as plt ## Lotus def data(): fluid_df = pd.read_csv('fort.9', delim_whitespace = True, names=["time","CFL","fx1","fy1","m1","p1","fx2","fy2","m2","p2"]) fluid_df.drop(['CFL', 'fy1', 'm1'],axis=1, i...
#파일명: 1pan.py import sys import pandas as pd input_file = sys.argv[1] # 읽어들일 파일을 지정한다 output_file = sys.argv[2] # 저장할 파일이름 지정한다 data_frame = pd.read_csv(input_file) print(data_frame) data_frame.to_csv(output_file, index=False) # pandas 모듈을 이용하면 더 간단하게 코드르 짤 수 있다.
import numpy as np try: from . import data_load except (SystemError, ImportError): import data_load from pathlib import Path from bllipparser import RerankingParser from sklearn import datasets, linear_model import pickle MAX_NUMATTR = 5 def parse(sentence,nbest=MAX_NUMATTR): if 'rrp' not in globals(): global ...
from lib2to3 import fixer_base from lib2to3.fixer_util import Name, BlankLine # whyever this is necessary.. class FixXrange2(fixer_base.BaseFix): PATTERN = "'xrange'" def transform(self, node, results): node.replace(Name('range', prefix=node.prefix))
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-15 09:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cards', '0013_auto_20161013_1200'), ] operations =...
import pandas as pd import dabl titanic = pd.read_csv(dabl.datasets.data_path("titanic.csv")) dabl.plot(titanic, 'survived') # doctest: +SKIP # Expected: ## Target looks like classification ## Linear Discriminant Analysis training set score: 0.578 # import matplotlib.pyplot as plt; plt.show()
#!/usr/bin/env python # coding: utf-8 import pandas as pd app_train = pd.read_csv('/Credit-default-risk/data/application_train.csv') app_test = pd.read_csv('/Credit-default-risk/data/application_test.csv')
if __name__=="__main__": # List of lists board = [["_"]*3 for i in range(3)] board[1][2] = "X" weird_board = [["_"]*3] * 3 weird_board [1][2] = "X" print(board,'\n',weird_board) # More operators
''' scope=session实现driver全局化 结合conftest.py文件执行 结合test_12_fixture_6_2.py文件执行 ''' import pytest from time import sleep # @pytest.mark.usefixtures("driver") # #这种方式是拿不到返回值的,此处并不适用;因此需要返回值时,用autouse的方式,也不适用。 class TestBaiduSearch: def test_search_1(self,driver): # driver=get_driver #直接把conftest.py中的get_driver...
import numpy as np from sklearn.cluster import KMeans X = [ [12, 11], [5, 12], [14, 15], [3, 3], [9, 1], [11, 11], [15, 2], [6, 4], [17, 11], [13, 11], [18, 11], [9, 15], [15, 20], [9, 18], [14, 5] ] kmeans = KMeans(n_clusters=3, init=np.array([[10.33, 8.5],...
# # Copyright 2019-2020 Lukas Schmelzeisen # # 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 agreed t...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(23,GPIO.OUT) GPIO.setup(18,GPIO.OUT) try: while True: GPIO.output(23,GPIO.HIGH) time.sleep(0.1) GPIO.output(23,GPIO.LOW) GPIO.output(18,GPIO.HIGH) time.sleep(0.1) GPIO.ou...
''' Copyright (c) 2015, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaim...
#! /usr/bin/python #Script for extracting a list of files from DPM database #Inspired from original script by Erming Pei, 2009/11/13 #A. Sartirana 2012/02/16, sartiran@llr.in2p3.fr import sys,os import datetime, time import MySQLdb usage= '' helpmsg= """ Script for getting a a filelist in xml format in dpm Usage: ...
# Generated by Django 3.0.3 on 2020-05-12 11:09 import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Member', fields=[ ('id', mo...
''' 12で作ったcol1.txtとcol2.txtを結合し,元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.確認にはpasteコマンドを用いよ. ''' def uni(w_f, txt1, txt2): for line1, line2 in zip(txt1, txt2): line1 = line1.strip() w_f.write('{}\t{}'.format(line1, line2)) if __name__ == '__main__': txt1 = open('col1.txt').readlines() txt2 = open('co...
# Generated by Django 4.1.7 on 2023-04-06 09:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dictionary', '0068_alter_queryparametermultilingual_fieldname'), ] operations = [ migrations.AlterField( model_name='queryparame...
# -*- coding: utf-8 -*- import json, sys from common import connect flickr_url = 'http://api.flickr.com/services/rest/' flickr_key = 'c588daa85452f53eb3babe7a893a359d' base_params = 'method=flickr.photos.search&format=json&nojsoncallback=1&extras=geo,tags,date_taken,description&has_geo=true&api_key={key}'.format(key=f...
from time import time import numpy as np import matplotlib.pyplot as plt from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale import pandas as pd np.random.seed(42) from matplotlib.patches i...
#!/usr/bin/env python3 import math import time import re import signal import sys import praw from praw.handlers import MultiprocessHandler try: from credentials import * # NOQA except ImportError: USERNAME = 'someusername' PASSWORD = 'somepassword' SUBREDDIT = 'somesubreddit' SIDEBAR_TAGS = {'sta...
import enum import itertools class Loadout: def __init__(self, weapon, armor_component, rings): self.weapon = weapon self.armor_component = armor_component self.rings = rings def __str__(self): armor_string = self.armor_component.name if self.armor_component else "No armor" ...
EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.yahoo.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'ubt_0130@yahoo.com' EMAIL_HOST_PASSWORD = 'soccer123'
#!/usr/bin/env python # Created by Jacob Schaible from flask import Flask, render_template, request, redirect, url_for from flask import flash, jsonify, make_response from flask import session as login_session from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import Null...
from django.urls import path from . import views urlpatterns = [ path('',views.home, name="home",), path('about',views.about, name="about",), path('blog',views.blog, name="blog",), ]
Import('env') env.Append(CCFLAGS='-g') #env.Replace(SHOBJSUFFIX='o') sources = [env.Object("./${SOURCE.srcdir}/${SOURCE.filebase}${SHOBJSUFFIX}", s, CPPPATH = ['#/inc']) for s in ['#src/terminal_ui.cpp', 'src/main.cpp',] ] env.Program('test_tui', sources, CPPPATH = ['#/inc'])
import json import xml.etree.ElementTree as ET class Parser(object): def parse(self, content): raise NotImplementedError() class JSONParser(Parser): def parse(self, content): return json.loads(content) class XMLParser(Parser): results = './*' ns = {} def __init__(self, *args, ...
titulo = input("Proporciona el titulo: ") autor = input("Proporciona el autor: ") print(f" {titulo} fue escrito por {autor}")
import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt import ssl ssl._create_default_https_context = ssl._create_unverified_context #wget https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224.h5 -O /Use...
# -*- coding: utf-8 -*- #from __future__ import unicode_literals import matplotlib.pyplot as plt #from matplotlib import rcParams from tests import * #rcParams['text.usetex'] = True #alpha average g's across flows #for i in range(0,9,1): # print np.mean(a.g[i*jump:(i+1)*jump]) p, s, a, _, _ = readAndAverage("tes...
from __future__ import unicode_literals import frappe import verp import unittest from frappe.utils import nowdate, add_months, getdate, add_days from verp.hr.doctype.leave_type.test_leave_type import create_leave_type from verp.hr.doctype.leave_ledger_entry.leave_ledger_entry import process_expired_allocation, expire_...
""" Copyright (C) 2022 SE CookBook - All Rights Reserved You may use, distribute and modify this code under the terms of the MIT license. You should have received a copy of the MIT license with this file. If not, please write to: help.cookbook@gmail.com """ from datetime import datetime from itertools import count i...
import inspect, os frame = inspect.getfile(inspect.currentframe()) exec_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) PROJECT_DIR = ('/').join(exec_path.split('/')[:-2]) PYTHON_APP_DIR = "%s/thisisthebus" % PROJECT_DIR FRONTEND_DIR = "%s/frontend" % PROJECT_DIR FRONTEND_APPS_DIR = ...
""" Правила продолжения остановившегося диалога для чит-чата """ import logging import random from ruchatbot.bot.base_rule_condition import BaseRuleCondition from ruchatbot.utils.constant_replacer import replace_constant from ruchatbot.bot.saying_phrase import SayingPhrase, substitute_bound_variables class Continua...
import time from collections import defaultdict import math def PageRank(G, insinks): """ :param G: a graph stores outlinks :param insinks: a graph stores inlinks :return: """ alpha = 0.85 N = len(G) # number of nodes in G PR = {} # {'node': value} sink = set() # s...
from threading import Thread from time import sleep from PiratesTreasure.ServerPackage import Session import select from PiratesTreasure.ServerPackage import ClientThread class ConnectionsThread(Thread): def __init__(self,val,sock): Thread.__init(self) self.val = val self.Sock = sock d...
import swiftclient import datetime import random def check_file_exists(object_name, container_download, environ): try: swift = swiftclient.Connection( auth_version='2', user=environ['OS_USERNAME'], tenant_name=environ['OS_TENANT_NAME'], key=environ['OS_PASSW...
import asyncio import sqlalchemy as sa from databases import Database metadata = sa.MetaData() tbl = sa.Table( 'tbl', metadata, sa.Column('id', sa.Integer, primary_key=True), sa.Column('val', sa.String(255)), ) async def create_table(conn): await conn.execute('DROP TABLE IF EXISTS tbl') await conn...
# -*- coding: utf-8 -*- """ Created on Wed May 10 11:15:22 2017 @author: lracuna """ from vision.camera import * from vision.plane import Plane from vision.screen import Screen import numpy as np import matplotlib.pyplot as plt from mayavi import mlab import cv2 # import qgis.core from PyQt4 import QtCore, QtGui, ui...
#!/usr/bin/env python def _adjust_for_fips(): ''' Manipulate sys.path if FIPS is enabled. ''' import os, sys FIPS_ENABLED = '/proc/sys/crypto/fips_enabled' SIQHASHLIB = 'siqhashlib' try: with open(FIPS_ENABLED, 'r') as fsin: try: fips_enabled = bool(int(fsin.rea...