text
stringlengths
38
1.54M
from . import admin from flask import render_template,redirect,url_for,flash,session,request from app.admin.forms import LoginForm,TagForm from app.models import Admin,Tag from functools import wraps from app import db def admin_login_req(f): @wraps(f) def decorate_function(*args,**kwargs): if "admin" ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier #TODO #from sklearn.datasets import load_iris # Load dataset traindata = pd.read_csv('./Datasets/iris/iris.csv') # Change string value to numeric traindata.set_value(traindata['species'] == 'Iris-...
from django.shortcuts import render from django.http import HttpResponse import requests # Create your views here. def test(request): response = requests.get('http://192.168.198.140:5555/images/json') data = response.json() return render(request, 'ssh/base.html', { 'Id': data['Id'], 'RepoT...
from logging import debug import os from flask_socketio import SocketIO from app import create_app, wss from flask_admin import Admin config_name = os.getenv('FLASK_CONFIG') app = create_app(config_name) wss.init_app(app) if __name__ == '__main__': wss.run(app, debug=True)
# 1 Что бы решить проблему в '01_problem_demo.py', необходимо read_ints запустить в новом потоке. import threading import time from multithreading.count_three_sum import count_three_sum, read_ints if __name__ == '__main__': print('Started main.') ints = read_ints('../data/1Kints.txt') t1 = threading.Thre...
from django.contrib import admin from django.conf import settings from api.models import Comment, Follower, Like, Post, PostMeta, Relation, RelationMeta, User, UserMeta class CommentAdmin(admin.ModelAdmin): actions = ['make_inactive', 'make_active'] def make_inactive(self, request, queryset): querys...
def pred_clean(string): # bibliotecas padrões import pandas as pd import numpy as np # bibliotecas para NLP from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer import re from unidecode import unidecode from sklearn.feature_extraction.text import TfidfVect...
#!/usr/bin/env python # -*- coding:utf-8 -*- from bin.base.sys import PR from bin.base.db.MongoEng import MongoEng from bin.base.sys.Bean import Bean from mongoengine import Q from bin import init # 查询默认最大值 DEFAULT_SEARCH_MAX_SIZE = 10000 class SingleTableOpt(object): def __init__(self, ds, bo, data): s...
# coding=UTF-8 def read_dict(dict_file): set_dict = set() in_file = open(dict_file, 'r') for line in in_file: set_dict.add(line.rstrip()) return set_dict def read_dict_map(dict_file): kv_dict = dict() in_file = open(dict_file, 'r') for line in in_file: toks = line.rstrip...
from abc import ABC, abstractmethod class StateManager(ABC): """ ABSTRACT CLASS FOR STATE MANAGER Class uses internal representation of state ([int], bool) to make computations. All communication with the outside is done with string representations """ @staticmethod @abstractmethod de...
import pandas as pd from valid_headers import column_names def check_columns(df,filename): headers = column_names[filename] cur_headers = [str(key) for key in df.keys()] if headers != cur_headers: return False else: return True def check_filename(filename): try: col...
from django.forms import ModelForm from django.forms.models import fields_for_model from .models import * class ProjectForm(ModelForm): class Meta: model = Project fields = ['name','descrp'] class TaskForm(ModelForm): class Meta: model = Task fields = ['name','descr']
"""Defines URL patterns for ians_py_page.""" from django.urls import path from . import views app_name = 'ians_py_page' urlpatterns = [ #Home page path('', views.index, name='index'), ]
from unittest import mock import pytest from sqlalchemy import create_engine from sqlalchemy import func from sqlalchemy import MetaData from sqlalchemy import select from sqlalchemy import Table from ....fakes import FakeAdapter from ....fakes import FakeEntryPoint from shillelagh.backends.apsw.dialects.base import ...
import mxnet as mx if __name__ == '__main__': data = mx.sym.Variable('data') fc1 = mx.sym.FullyConnected(data, name='fc1', num_hidden=128) act1 = mx.sym.Activation(fc1, name='relu1', act_type="relu") fc2 = mx.sym.FullyConnected(act1, name='fc2', num_hidden=10) out = mx.sym.SoftmaxOutput(fc2, name...
import numpy as np import pygame as pg class Graph(dict): graph = {} def __init__(self): self = dict() def add_vertex(self, key, edges=None): if edges is None: edges = [] self[key]=edges def add_edge(self, key, edge=None): self[key].append(edge) def ...
from django.conf import settings from storages.backends.s3boto import S3BotoStorage class S3MediaStorage(S3BotoStorage): def __init__(self, **kwargs): kwargs['location'] = kwargs.get('location', settings.MEDIA_ROOT.replace('/', '')) super(S3MediaStorage, self).__init__(**kwargs) class...
from pkg_ml_prod.preprocessing import drop_na, train_test_split from pkg_ml_prod import get_data, preprocessing, pipeline, model df = get_data.get_data() df = preprocessing.drop_na(df) X_train, X_test, y_train, y_test = preprocessing.split(df) pipe = pipeline.create_pipeline() best_model = model.create_model(pipe...
# 셀프 넘버 # for i in range(1,100): # for j in range(1,100): # A = i # B = j # # AB = 10 * A + B # str_AB = str(A)+str(B) # AB = int(str_AB) # if 100 - (A+B) == AB: # print(A) # print(B) li = list(range(1,100)) n_list = [] for n in range(1,100):...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 3 09:08:33 2017 @author: Charles """ from bisip.models import mcmcinv
# Generated by Django 3.2.7 on 2021-11-10 02:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('helloworld', '0003_auto_20211109_2253'), ] operations = [ migrations.AlterField( model_name='disciplina', name='nome...
# -*- coding: utf-8 -*- """ 列表基本操作知识点(五大基本操作): 1、访问列表元素 2、 添加列表元素 2、补充知识点:从空列表构建新列表 3、修改列表元素 4、删除列表元素 5、列表排序及其他 """ # 定义列表 -- Python实战圈成员列表 names_python_pc = ['陈升','刘德华','杨幂','TFboys'] ''' 1、访问列表元素 ''' # 根据索引访问列表元素--访问杨幂 yangmi = names_python_pc[2] print('Python实战圈成员列表种第三个是:',yangmi) # 两种方法...
#!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen from super_spider import app """ @author: peimingyuan created on 2017/9/9 下午5:53 """ config = app.config def runserver(debug, port): debug = debug or config.get("DEBUG") if debug: app.run( host="0.0.0.0", ...
def returnFloat(): x=input("Please enter an number") return(float(x)) def returnInt(): x=input() print(bool(x)) def PrintFlote(): x=input(float) print(round(x)) PrintFlote()
import yaml import collections # For creating ordered dictionary import json # For creating json data import os from pathlib import Path from datetime import datetime, date from pytz import timezone import calendar import random import names import Database_Ble #----------newly added---- import p...
from django.urls import include, path # from django.conf.urls import url from . import views urlpatterns = [ path('create_user/', views.CreateUserView.as_view(), name='create_user'), path('change_user/<int:user_id>/', views.ChangeUserView.as_view(), name='change_user'), path('users/<int:user_id>/', views.S...
#!/usr/bin/env python ##----------------------------- """Loops over events in the data file, gets calibrated n-d array for cspad, evaluates n-d arrays for averaged and maximum values Usage:: python ex_nda_average.py bsub -q psfehq -o log-r0092.log python ex_nda_average.py """ from __future__ import pr...
# Generated by Django 2.0 on 2019-08-13 10:15 from django.db import migrations, models import django.db.models.deletion import django.db.models.manager import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateMode...
from sklearn.ensemble import RandomForestRegressor import numpy as np from sklearn.metrics import mean_squared_error, mean_absolute_error from sklearn.metrics import r2_score import matplotlib.pyplot as plt f = open("train_data_f_pro.csv") f2 = open("test_data_f_pro.csv") data = np.loadtxt(f,delimiter=",") data2 = np...
# Generated by Django 2.1 on 2018-08-12 19:14 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='EData', fields=[ ('id', models.AutoField(auto...
import time start = time.process_time() slownik = {} slownik['Masło'] = 2.3 slownik['Mleko'] = 1.5 slownik['Chleb'] = 5.2 slownik['Jajka'] = 3.0 slownik['Bulki'] = 0.3 slownik['Banany'] = 2.3 slownik['Jablka'] = 1.4 slownik['Zioło'] = 30.5 slownik['Kasztelan'] = 2.3 slownik['Ksiazece'] = 4.5 # Suma elementów s = su...
fasta_file = input("Enter input file: ") fasta_output = input("Enter output file: ") print("Option-1) Read a FASTA format DNA sequence file and make a reverse sequence file.") print("Option-2) Read a FASTA format DNA sequence file and make a reverse complement sequence file.") print("Option-3) Convert GenBank format f...
def change(amount): if amount == 24: return [5, 5, 7, 7] if amount == 25: return [5, 5, 5, 5, 5] if amount == 26: return [5, 7, 7, 7] if amount == 27: return [5, 5, 5, 5, 7] if amount == 28: return [7, 7, 7, 7] coins = change(amount - 5) coins.app...
# -*- coding: utf-8 -*- import json import re import scrapy from urllib.parse import urlencode from copy import deepcopy from scrapy.http import HtmlResponse from instagram_parser.items import UserItem, FollowingItem class InstagramSpider(scrapy.Spider): name = 'instagram' allowed_domains = ['instagram.com'] ...
import cv2 import numpy as np img = cv2.imread('..\\MasterOpenCV\\images\\IMG_7539.jpg') image = cv2.resize(img,(960,540)) height,width = image.shape[:2] start_row,start_col = int(height*.25),int(width*.25) end_row,end_col = int(height*.75),int(width*.75) corpped = image[start_row:end_row,start_col:end_col] cv2.im...
import numpy as np import matplotlib.pyplot as plt def convolve(x,h): y=[] b=(len(x)+len(h)-1) for n in range(b): s=0 for k in range(len(x)): if n-k<len(h) and n-k>=0: s=s+(x[k]*h[n-k]) y=np.append(y,s) return(y) def timerev(x): lnx=len(x) y=np.zeros(lnx) for i in range(lnx): if lnx-i>=0 and lnx-i...
a,b,x,y=[int(i)for i in input().split()] while 1: p="" if y<b:y+=1;p="S" if y>b:y-=1;p="N" if x<a:x+=1;p+="E" if x>a:x-=1;p+="W" print(p)
from .template import Element, element @element() class h1(Element): ... @element() class b(Element): ... @element() class i(Element): ... @element() class span(Element): ...
import multiprocessing import cv2 import dlib import time import threading import numpy as np from skimage import io from sklearn.externals import joblib import datetime import glob import os import time import MySQLdb import redis redisdb = redis.Redis(host='localhost', port=6379, db=1) mysqldb = MySQLdb.connect("loc...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^faq/$', views.faq, name='faq'), url(r'^start/$', views.start, name='start'), url(r'^profile/(?P<user_pk>\d+)/$', views.profile, name='profile'), url(r'^faq/1/$', views.faq_detail1, name='faq_detail1'), url(r'^faq/2/$', view...
"""Generator Comprehensions * Similar syntax to list comprehensions * Create a generator object * Concise * Lazy evaluation """ from utils import * def is_odd(x): return x % 2 == 1 def main(): hrule("Create a generator comprehension") million_squares = (x*x for x in range(1, 1000001)) ...
import newspaper from newspaper import Article import time import nltk import json import requests from bs4 import BeautifulSoup as soup from requests_oauthlib import OAuth1 import secrets CACHE_FILENAME = "twitter_cache.json" CACHE_DICT = {} client_key = secrets.TWITTER_API_KEY client_secret = secrets.TWITTER_API_SE...
// https://leetcode.com/problems/binary-tree-preorder-traversal # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def preorderTraversal(self, root): st = list() lt = li...
#encoding=UTF-8 ''' 匿名函数: lambda 参数1,参数2,参数3:表达式 特点: 使用lambda创建函数 没有名称 匿名函数冒号后面的表达式有且只有一个,是表达式,不是语句!!!! 匿名函数自带return,返回的 结果就是表达式计算后的结果 ''' def sum(x,y): ''' 求和 :param x: :param y: :return: ''' return x+y pass print(sum(10,2)) M = lambda x,y:x+y print(M(1,2)) a...
import requests import re url_1 = 'https://stepic.org/media/attachments/lesson/24472/sample0.html' url_2 = 'https://stepic.org/media/attachments/lesson/24472/sample2.html' pattern = r'<a\s+(?:[^>]*?\s+)?href="([^"]*)"' urls = [] answer = 'No' for x in range(2): urls.append(input().rstrip()) res = requests.get(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for generated bridges """ import sys from attr.setters import convert sys.path.insert(0, '../..') import pytest from sim import Simulator, CliArgs, path_join, parent_dir import corsair TEST_DIR = parent_dir(__file__) def gen_bridge(tmpdir, bridge, reset): ...
import json from subprocess import PIPE,Popen s = Popen("ruby ast.rb /home/aiyanxu/study/diff++/test/test1.rb", shell=True, stdout=PIPE).stdout.read() h = json.loads(s) print h.get('type')
from unityagents import UnityEnvironment import numpy as np class EnvWrapper(): """ Wrapper for unity framework to match OpenAI environment interface """ def __init__(self, filename): self.env = UnityEnvironment(file_name=filename) self.brain_name = self.env.brain_names[0] ...
import pytest from werkzeug.exceptions import Forbidden from flask_allows import Allows, Permission def test_Permission_provide_ident(app, member, ismember): Allows(app=app) p = Permission(ismember, identity=member) assert p.identity is member def test_Permission_as_bool(app, member, always): All...
#!/usr/bin/env python3 import argparse import re import sys from typing import List # TODO extract into utils module def yes_no_prompt(prompt_msg: str) -> bool: return input(prompt_msg + " [Y/n] ") in ["Y", "y", ""] # TODO extract into utils module def is_timecode_line(line: str) -> bool: timecode_line_pat...
# -*- coding: utf-8 -*- from rest_framework import serializers from . import models class JobSerializer(serializers.ModelSerializer): class Meta: model = models.Job read_only_fields = ('state',) class ImageInfoSerializer(serializers.ModelSerializer): width = serializers.IntegerField() ...
import sys import os from PyQt5 import Qt from settingsController import SettingsController from gitController import GitController from projectController import ProjectController def main(argv): settingsController = SettingsController() prefs = settingsController.loadPrefs() prefs['credentials']['passwor...
#dp[i]=min(dp[i-1],dp[i-2])+cost[i-2] #表示最后一阶必须要走过时的最小的花费 #最后结果从倒数第一个与倒数第二个选一个 from typing import List class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: cur,pre=0,0 for i in range(len(cost)): cur,pre=min(cur,pre)+cost[i],cur return min(cur,pre)
import numpy as np # initialize parameters of LDA model # # input: # - num_words: number of words # - num_docs: number of documents # - num_topics: number of topics # # output (tuple of length 2): # [0] (array shape(num_topics, num_docs)): topic distribution for each doc # [1] (array shape(num_wo...
import os, sys, pygame BASE_DIR = os.path.abspath('') IMAGE_PATH = 'assets/1x/bomb50.png' class Enemy(pygame.sprite.Sprite): """ # use os.path.join to load files from subdirectories for portability # image.load returns a surface object """ def __init__(self, screen_dims): self.surfa...
#!/usr/bin/env python from glob import glob import os from setuptools import setup PACKAGE_NAME = "osm_cartography" SHARE_DIR = os.path.join("share", PACKAGE_NAME) setup( name=PACKAGE_NAME, version='0.2.5', packages=["osm_cartography", "osm_cartography.nodes"], data_files=[ ('share/ament_inde...
from PIL import Image import re src_x = 800 src_y = 800 img = Image.new('RGB', (src_x , src_y), 'black') pixels = img.load() color = (255, 255, 255) #loading obj file which has vertex coords with open('model.obj', 'r') as f: lines = f.read().splitlines() for line in lines: try: v, x, y, z = line.s...
# MIT License # # Copyright (c) 2021 The Anvil Extras project team members listed at # https://github.com/anvilistas/anvil-extras/graphs/contributors # # 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 ...
import re # s = 'A8C3721D86' # # # def convert(value): # matched = value.group() # if int(matched) >= 6: # return '9' # else: # return '0' # # # r = re.sub('\d', convert, s) # print(r) s = 'A83C72D1D8E67' def convert(value): matched = value.group() if int(matched) >= 50: r...
from tdasm import Runtime import renmas3.osl from renmas3.osl import create_shader, create_argument, create_struct_argument from renmas3.core import Vector3 a1 = create_argument('p1', 2) a2 = create_argument('p2', 1) a3 = create_argument('p3', 5.0) #a4 = create_argument('p4', Vector3(2,5,6)) a4 = create_argument('p4...
### MODELS import numpy as np from keras.layers import Dense, GlobalMaxPool2D, BatchNormalization, Dropout from keras.applications import ResNet50, VGG16 from keras.models import Model, Sequential def R50_mod(seed=0): """ Create a new feature extractor based on the pretrained ResNet50 model: The model is ...
# -*- coding: utf-8 -*- # Copyright notice # -------------------------------------------------------------------- # Copyright (C) 2019 Deltares # Rob Rikken # Rob.Rikken@deltares.nl # # # This library is free software: you can redistribute it and/or modify # it under the terms of th...
from flask import Flask, jsonify from app.newspaper import Newspaper from os.path import abspath import json import time app = Flask(__name__) languages = ['pt', 'en'] categories = ['last_news','sports', 'economy', 'health', 'tech'] f = open(abspath('./app/sources.json'), 'r') sources = json.loads(f....
from config import Key from pong_game.paddle import State as PState from pong_game.pong_game import PongGame, State from system_manager import SystemManager sys_manager = SystemManager.get_instance() class SoloMode(PongGame): init_score = 0 def __init__(self): super().__init__() self.update...
from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages from django.contrib.auth.forms import UserCreationForm import json from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from Apps.Notes import views as views_notas # Create your vi...
#============================================================================= # # ALLSorts v2 - Feature Creation Stage # Author: Breon Schmidt # License: MIT # #============================================================================= ''' ---------------------------------------------------------------------...
# Created by Dayu Wang (dwang@stchas.edu) on 01-30-19. # Last updated by Dayu Wang (dwang@stchas.edu) on 01-30-19. # Let the user enter the dimensions of the rectangle. width = int(input('Width: ')) height = int(input('Height: ')) area = width * height print('The area is:', area)
def div_mod(x, y): if x is not None and y is not None: reminder = x % y quotient = int(x / y) # comma seperated values create a tuple. following is a tuple. braces are not required # interestingly we can return multiple values in this approach assuming they are part of a tuple ...
from unittest import TestCase from mock import MagicMock from pushbullet import PushBullet from graphitepager.description import Description from graphitepager.notifiers.pushbullet_notifier import PushBulletNotifier from graphitepager.redis_storage import RedisStorage from graphitepager.alerts import Alert from grap...
from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime @login_manager.user_loader def load_user(user_id): return PatientUser.query.get(int(user_id)) class Admin(UserMixin, db.Model): __tab...
# PyTorch import torch from torch.utils.data import Dataset, DataLoader from torch.autograd import Variable import torchvision.transforms as tr import torch.nn.functional as F from torch.nn import Sequential # Models from unet import Unet from siamunet_conc import SiamUnet_conc from SiamUnet_conc import SiamUnet_conc f...
n = int (input ("Moi ban 1 so tu nhien bat ky: ")) tong = 1 for i in range( 1, n+1 ): tong = tong * i print ("Tong la", tong)
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class FQExtendParams(object): def __init__(self): self._fq_number = None self._fq_seller_percent = None @property def fq_number(self): return self._fq_number @fq_n...
import datetime from datetime import date from dateutil.relativedelta import relativedelta def lifetime(): now = datetime.datetime.now() end_date=date(2011,07,9) rdelta = relativedelta(now, end_date) if rdelta.years >0 and rdelta.months >0 and rdelta.days>0: return str(rdelta.years)+' years '...
# coding:utf-8 ''' @Copyright:LintCode @Author: ultimate010 @Problem: http://www.lintcode.com/problem/reverse-linked-list @Language: Python @Datetime: 16-06-10 10:06 ''' """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = nex...
# Copyright (c) 2020 the original author or authors # # 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 applicabl...
#%% Part 1 import re mask_regex = re.compile(r"^mask\s+=\s+([X10]+)") mem_regex = re.compile(r"^mem\[(\d+)\]\s=\s(\d+)") result = {} with open("day_14_input.txt") as input_data: for line in input_data: if mask_match := mask_regex.match(line): and_pattern = int(mask_match.group(1).replace("1", ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Edoardo Lenzi' __version__ = '1.0' __license__ = 'WTFPL2.0' # load .env configs from knights_tour.utils.env import Env Env.load() # load tests/ import unittest from tests import CliTest '''Run all tests in tests/''' unittest.main()
import datetime import os import random import sys import tempfile import numpy as np import pytest import ray from ray import cloudpickle as pickle from ray._private import ray_constants from ray._private.test_utils import ( client_test_enabled, wait_for_condition, wait_for_pid_to_exit, ) from ray.actor ...
print("----------------------------------") print("Practica 05_calculator.py") print("----------------------------------") print("Introduce el primer Número: ") num1=int(input()) print("Introduce el Segundo Número: ") num2=int(input()) def suma(): return num1 + num2 def resta(): return num1 - nu...
from rest_framework import status, viewsets from rest_framework.authentication import TokenAuthentication from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import filters from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings impor...
import datetime from django.db import models try: from datatype_tools.lib import * # noqa datatype_tools = True except ImportError as e: datatype_tools = False from django_dunder import app_settings from django_dunder.mixins import DunderModel from django_dunder._formatter import _get_one_invoke from dj...
import random #-*- coding: ascii -* import os, sys print "Exercise 94:Random Password" print "Write a function that generates a random password. The password should have a random length of between 7 and 10 characters. Each character should be randomly selected from positions 33 to 126 in the ASCII table. Your function...
import random def generateAgent(): m5 = ["Mozilla/5.0"] m4 = ["Mozilla/4.0"] mozillaList = m5*4 + m4*2 mozillaFinal = random.choice(mozillaList) win = "(Windows NT " + str(random.randint(3,10)) + "." + str(random.randint(3,10)) + "; Win64; x64)" mac = "(Macintosh; Intel Mac OS X " + str(random...
from django.db import models from alumnos.models import AlumnoCurso # Create your models here. class Asistencia(models.Model): fecha = models.DateField(blank=True) asistio = models.FloatField(blank=True) descripcion = models.CharField(max_length=150, blank=True, null=True) fecha_creacion = models.DateT...
#CSci 127 Teaching Staff #January 2021 #A template for a program that draws nested polygons #Modified by: --- Your Name Here! --- #Email: --- Your Email Here! --- import turtle def setUp(t, dist, col): """ Takes three parameters, a turtle, t, the distance, dist, to move the turtle and a color, c...
#_*_ coding: utf-8 _*_ import re import lxml.html def parse_login_form(page_src): """ parse login form infos from the login page src return the form action and the values list """ page = lxml.html.fromstring(page_src) form = page.forms[0] return form.action, form.form_values() def update_...
#!/usr/bin/env python # by Cameron Po-Hsuan Chen @ Princeton import numpy as np, scipy, random, sys, math, os import scipy.io from scipy import stats sys.path.append('/Users/ChimatChen/anaconda/python.app/Contents/lib/python2.7/site-packages/') from libsvm.svmutil import * from scikits.learn.svm import NuSVC impor...
import os import json import numpy as np import pandas as pd import tensorflow as tf #from tf.keras.models import Sequential #from keras.layers import LSTM, Dropout, TimeDistributed, Dense, Activation, Embedding #from keras.callbacks import ModelCheckpoint #from keras.utils import * from music21 import * from tensorf...
"""Celery background task to start workflow run.""" from _io import TextIOWrapper import logging import re import subprocess from typing import (Dict, List, Optional, Tuple) from pro_wes.celery_worker import celery # Get logger instance logger = logging.getLogger(__name__) @celery.task( name='tasks.run_workfl...
import cv2 image = cv2.imread("C:\\sample.jpg") img = cv2.resize(myImage,(640,480)) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(gray,cv2.cv.CV_HOUGH_GRADIENT,1,10, param1=50,param2=35,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # dra...
import os import sys import datetime import whois import requests def load_urls4check(path): with open(path, "r", encoding="utf-8") as file_with_urls: url_list = file_with_urls.read().split() return url_list def is_server_respond_ok(url): try: response_from_url = reque...
# -*- coding: utf-8 -*- from datetime import datetime from django.contrib.contenttypes import generic from taggit.managers import TaggableManager from proj.core.models import User from proj.core.comment.models import Comment from .managers import * PROJECT_STATUSES = ( ('open', u'Открыт'), ('closed', u'Закрыт...
# Generated by Django 3.2.3 on 2021-05-28 18:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web_app', '0003_room_marked_for_housekeep'), ] operations = [ migrations.CreateModel( name='Amenity', fields=[ ...
class Human: def __init__(self, name, params): self.name = name def do_action(self, observation): if observation['event_name'] == 'GameStart': print(observation) elif observation['event_name'] == 'NewRound': print(observation) elif observation['event_name...
from aiogram import Bot, Dispatcher, executor, types #Бот слит в телеграм канале @slivmenss # Клавиатура menu = types.ReplyKeyboardMarkup(resize_keyboard=True) menu.add( types.KeyboardButton('👤 Баланс'), types.KeyboardButton('💸 Клик'), types.KeyboardButton('🎰 Вывод') )#Бот слит в телеграм канале @slivmenss pay...
from django.shortcuts import render # Create your views here. from .models import CharApp from web.chargen.forms import AppForm from django.http import HttpResponseRedirect from datetime import datetime from evennia.objects.models import ObjectDB from django.conf import settings from evennia.utils import create def ...
#!/usr/bin/env python import os import sys if __name__ == "__main__": # The setting file path is set from the virtual environment varialbles, so the following line is not needed. # When deployed to Heroku, a corresponding environment variable on Heroku should be set. # os.environ.setdefault("DJANGO_SETTI...
import os from rsf.proj import * ######################################################################## # RETRIEVE DATA ######################################################################## # Define SLIM FTP server information FTPserver = { 'server': 'ftp.slim.gatech.edu', 'login': 'ftp', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net> import time import logging import hashlib import os import serial # -*- coding: utf-8 -*- # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net> from .utils import default_port from .luacode import D...