text
stringlengths
38
1.54M
# -*- coding:utf-8 -*- __Author__ = "KrianJ wj_19" __Time__ = "2020/7/28 19:19" __doc__ = """ 数据清洗用到的配置属性""" MONGO_URI = 'localhost' MONGO_PORT = 27017 MONGO_DB = ['china_tech', 'china_digi']
# coding: utf-8 from django.utils.translation import ugettext_lazy as _ from django.db import models __all__ = ('Log', 'LOG_EXCEPTION','LOG_WARNING','LOG_NOTICE','LOG_STRING') import datetime LOG_EXCEPTION = 1 LOG_WARNING = 2 LOG_NOTICE = 3 LOG_STRING = 4 LOG_TYPE = ( (LOG_EXCEPTION, ...
import sys from .io import read_active_sites, write_clustering, write_mult_clusterings from .cluster import cluster_by_partitioning, cluster_hierarchically, create_similarity_matrix, \ convert_indices_to_active_sites from .compare_clusters import sum_of_distances, rand_index, benchmark_clusters, benchmark_rand,...
{ "targets": [ { "target_name": "structure", "sources": [ "src/structure.cc" ] } ] }
import json import logging import urllib from dojo.models import Finding logger = logging.getLogger(__name__) class SafetyParser(object): def __init__(self, json_output, test): # Grab Safety DB for CVE lookup url = "https://raw.githubusercontent.com/pyupio/safety-db/master/data/insecure_full.jso...
import textwrap from xmldoc.renderer import Renderer class MarkdownRenderer(Renderer): width = 80 def wrap(self, text): return textwrap.fill(text, self.width) def header(self, element): level = int(element.tag[1]) + 1 title = self.inline(element) return self.wrap(("#" *...
import pandas as pd import numpy as np import seaborn as sn import matplotlib.pyplot as plt import time dataset = pd.read_csv('new_appdata10.csv') ## Data Preprocessing response = dataset["enrolled"] dataset = dataset.drop(columns = 'enrolled') from sklearn.model_selection import train_test_split X_tr...
from lxml import etree import requests import re url = "http://www.dxy.cn/bbs/thread/626626#626626" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36' } #获取url的html res = requests.get(url,headers) #用lxml解...
#!/usr/bin/env python3 import sys import os import json import sqlite3 import csvloader import starlight import models from collections import namedtuple, defaultdict import locale locale.setlocale(locale.LC_ALL, "en_US.UTF-8") QUERY_GET_EVENT_STUBS = "SELECT id, name, type, event_start, event_end FROM event_da...
'''文件操作 r读取操作,文件不存在抛异常 w写操作,文件不存在创建,文件存在就覆盖 a写操作,文件不存在创建,文件内容存在就追加 rb以二进制方式打开文件,即序列化 wb ab r+读写操作,写与读不分先后,即随时都可进行读与写,写是追加 w+读写操作,文件不存在创建,存在覆盖,先写后读。保证文件有内容通过移动光标来读自己想要的部分。 a+读写操作,文件不存在创建,存在就追加,任意时刻读写,若刚用‘a+’打开一个文件,则不能立即读,因为此时光标已经是文件末尾,除非你把光标移动到初始位置或任意非末尾的位置。 文件的定位读写 ''' with open("C://software//readme.txt","a+",encoding...
#!/usr/bin/env python import sys import argparse import os.path import os import numpy as np import libtiff as lt from libtiff import TIFF from glob import glob from cvtools import readFlo import cv2 import matplotlib.pyplot as plt import scipy import pylab import scipy.cluster.hierarchy as sch def main():...
__author__ = "Vini Salazar" __license__ = "MIT" __maintainer__ = "Vini Salazar" __url__ = "https://github.com/vinisalazar/bioprov" __version__ = "0.1.24" __doc__ = """ Module for holding preset instances of the Program class. """ from os import path from pathlib import Path from bioprov import File, config from biop...
import redis import time re = redis.Redis(host='localhost', port=6379,db=8, password=12345) #re.set('key_name','value_test') while True: data = re.rpop("parkmsg") print(data) time.sleep(0.5)
import os import numpy as np import pandas as pd import warnings warnings.simplefilter(action='ignore', category=Warning) import matplotlib.pyplot as plt import seaborn as sns def count_sensitive_words(df_, word_list_, str_col='Short_Msg', companies_neg_pos=None): ''' Count number of sensitive words from `word...
#when other servers are down, try&except #when a client send the same message to two dif servers at the same time import asyncio import logging import sys import urllib.parse import time import json from datetime import datetime SERVER_NAME_LIST = {'Alford','Ball','Hamilton','Holiday','Welsh'} SERVER_ADDRESS_LIST = {...
# Copyright (C) 2016 Calvin He # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the ...
import requests from requests.models import HTTPError from systemFunctions import speak, draw_text def weather_data(query): res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=8de0c1d186a15c6c44a58c73ca31e976&units=metric'); # Check if city exists if (res.json()['cod'] == '404'...
import pytest from openapi_core.security.providers import HttpProvider from openapi_core.spec.paths import SpecPath from openapi_core.testing import MockRequest class TestHttpProvider(object): @pytest.fixture def spec(self): return { 'type': 'http', 'scheme': 'bearer', ...
import networkx as nx import numpy as np import dwave_qbsolv as QBSolv import time import statistics from itertools import combinations from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite from matplotlib import pyplot as plt import pandas as pd def I(i, j,...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import struct import sys import time def p16(addr, sign="unsigned"): fmt = "<H" if sign == "signed": fmt = "<h" return struct.pack(fmt, addr) def p32(addr, sign="unsigned"): fmt = "<I" if sign == "signed": fmt = "<i" ...
from visual import * from particula import * def generaColumna(posInicial, masa, nParticulasX, nParticulasY, nParticulasZ, densidad, separacion, vInicial, radio, color): listaParticulas= [] #Calculamos la nueva posicion de la particula separada for k in range(nParticulasZ): #print k ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import numpy as np import torch from PIL import Image from skimage.segmentation import mark_boundaries from skimage.color import rgb2gray from ex_methods.lime import lime_image from ex_m...
# -*- coding: utf-8 -*- """ brickv (Brick Viewer) Copyright (C) 2012, 2014 Roland Dudko <roland.dudko@gmail.com> Copyright (C) 2012, 2014 Marvin Lutz <marvin.lutz.mail@gmail.com> main.py: Main standalone data logger This program is free software; you can redistribute it and/or modify it under the terms of the GNU Gen...
from __future__ import print_function from tensorflow.keras.preprocessing.image import ImageDataGenerator import numpy as np import os import glob import skimage.io as io import skimage.transform as trans import tensorflow as tf from skimage import img_as_ubyte import matplotlib.pyplot as plt import tensorflow.keras as...
# -*- coding: utf-8 -*- import numpy as np from sklearn import cluster from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import pyqtSignal, pyqtSlot try: from .ui_group_tracker_widget import Ui_group_tracker_widget except ImportError: from ui_group_tracker_widget import Ui_group_tracker_widget try:...
################################################### import tensorflow as tf a = [[1,2,3],[4,5,6]] b = [[1,0,3],[1,5,1]] condition1 = [[True,False,False], [False,True,True]] condition2 = [[True,False,False], [False,True,False]] with tf.Session() as sess: print(sess.run(tf.where(condition1...
import math import cv2 import numpy as np def max_dist(x_k, y_k, x, y): return math.sqrt((x - x_k) ** 2 + (y - y_k) ** 2) def seek_chair_contours(rect_dict, x, y, w, h): x_max, y_max = 0, 0 max_len = 0 for x_k, y_k in rect_dict.keys(): curr_max = max_dist(x_k, y_k, x + w / 2, y + h / 2) ...
#!/usr/bin/env python import numpy as np import sys from scipy import stats # I used the lee.cor and similarities0-1.txt files from https://github.com/piskvorky/gensim/tree/develop/gensim/test/test_data sim_matrix_original = np.loadtxt("similarities0-1.txt") gesa_matrix = np.loadtxt(str(sys.argv[1])) sim_matrix_ori...
#!/usr/bin/env python ''' Author : Yi-Ying Lin ''' from __future__ import print_function import rospy import numpy as np import math from math import pi import time from geometry_msgs.msg import Twist, Point, Pose from sensor_msgs.msg import LaserScan from sensor_msgs.msg import Imu from nav_msgs.msg import Odometry ...
# -*- coding: utf-8 -*- import __init__ from abc import ABCMeta from abc import abstractmethod import threading import time from Configure.GetConfigure import GetConfigure class Service(object): __metaclass__ = ABCMeta def __init__(self): self.configures = GetConfigure() self.load_config() ...
import cv2 import numpy as np from PIL import Image import math drawing=True # true if mouse is pressed def input_file(path,pix = 0.388): PIXEL_SIZE = pix def draw_circle(event,former_x,former_y,flags,param): global current_former_x,current_former_y,drawing,distance if event == cv2.EVENT_LBUTTONDBLCLK: cv...
import os from datetime import datetime from tqdm.autonotebook import tqdm import shutil from functools import partial import numpy as np import pickle import tensorflow as tf import tensorflow_datasets as tfds import tensorflow.keras.backend as K from tensorflow.python.keras import metrics from tensorflow import rand...
def read(): with open('A-large.in') as f: return f.readlines() def write(lines): with open('result.txt', 'w') as f: i = 1 for line in lines: f.write('Case #' + str(i) + ': ' + str(line) + '\n') i += 1 def solve(data): res = [] for num in data: s ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # "THE WISKEY-WARE LICENSE": # <utn_kdd@googlegroups.com> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, and you # think this stuff is worth it, you can buy us a WISKEY in return. #==================...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from parts.speaker import Speaker SPEAKER_PIN = 5 # ドレミのメロディ melody = ((262, 1),(294, 1),(330, 1),) # メロディーの値を表示 for value in melody: pitch_name, length = value print('{0}, {1}'.format(pitch_name, length)) # メロディーの再生 speaker = Speaker(SPEAKER_PIN) speaker.play(m...
import socket import time # class for client obj put exception class ClientError(socket.error): pass class Client: def __init__(self, addr, port, timeout=None): self.addr = addr self.port = port try: self.sock = socket.create_connection((self.addr, self.port), timeout) ...
from path_class import * from gibbs_MJPs import sampleUI from gibbs_MJPs import get_likelihood from gibbs_MJPs import FFBS from math import log from numpy import random from scipy.stats import gamma from math import pi from math import sqrt from math import exp from model_parameters import * from gibbs_MJPs import FF f...
from dolfin import * import sys import numpy as np sys.path.append('../') from navier_stokes import * if has_linear_algebra_backend("Epetra"): parameters["linear_algebra_backend"] = "Epetra" # Sub domain for Dirichlet boundary condition #class DirichletBoundary(SubDomain): # def inside(self, x, on_boundary): # ...
# example showing how time series is applied import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime from statsmodels.tsa.seasonal import seasonal_decompose from pandas import Series,DataFrame,DatetimeIndex from statsmodels.tsa.arima_model import ARIMA from pandas.tools.plotting import a...
import numpy import cv2 import matplotlib.pyplot as plt def getPixelValue(padded_img, filter, i, j): f_h, f_w = filter.shape summed = 0 for k in range(f_h): n_j = j for l in range(f_w): summed = summed + (filter[k][l] * padded_img[i][n_j]) n_j = n_j + 1 i = i + 1 return summed def convolution(image, ...
from gevent import os, subprocess import pytest from setuptools import glob from volttron.platform.dbutils.sqlitefuncts import SqlLiteFuncts TOPICS_TABLE = "topics" DATA_TABLE = "data" META_TABLE = "meta" METAMETA_TABLE = "metameta" AGG_TOPICS_TABLE = "aggregate_topics" AGG_META_TABLE = "aggregate_meta" TABLE_PREFI...
from django.core.management.base import BaseCommand from apps.utils.sprinklr import SprinklrService from apps.web.models import Recipe class Command(BaseCommand): help = 'Calls the sprinklr service' def add_arguments(self, parser): parser.add_argument( '--recipe_ratings', acti...
from __future__ import annotations import pytest from hooks.validate_django_model_field_names import boolean_validator @pytest.mark.parametrize( ('field_name', 'expected_is_valid'), [ ('is_accepted', True), ('was_migrated_from_specialties', True), ('has_public_link_access', True), ...
from nose.tools import * from exercises import ex13 def test_max_in_list(): ''' Confirm we are finding the largest number ''' test_max_in_list = ex13.max_in_list([1, 2, 3, 4, 2, 6, 2]) assert_equal(test_max_in_list, 6)
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import os from torchvision import datasets, transforms from torchvision.utils import save_image from models import Gnet, Dnet, Qnet, FrontEnd, weights_init from myUtils import save_checkpoint, load_checkpoint class args: seed = 0...
"""Module that contains BaseModel abstract class""" from abc import ABCMeta, abstractmethod import numpy as np class BaseModel(object): """Abstract class that defines common methods for all models""" __metaclass__ = ABCMeta def __init__(self, configs, score_method, predict_as_probability): self.con...
#!/usr/bin/env python3 __all__ = ["Expense", "BaseExpencesManager", "ExpencesManager"] from collections import defaultdict, namedtuple from operator import itemgetter Expense = namedtuple("Expense", ("category", "amount")) class BaseExpencesManager: expenses = [] def add(self, expense): self.expen...
# metros quadrados para acres m = float(input('Digite o valor em metros quadrados: ')) a = m * 0.000247 print(f'O valor em acres é {a}.')
import sys sys.setrecursionlimit(1 << 20) INF = float('inf') def read_int_list(): return list(map(int, input().split())) def read_ints(): return map(int, input().split()) from collections import deque def mainQ(): S = input() q = deque([S]) cands = ['dream', 'dreamer', 'erase', 'eraser'] ...
import numpy as np from gsm import GameOver, GamePhase, GameActions, GameObject from gsm import tset, tdict, tlist from gsm import SwitchPhase, PhaseComplete from gsm.common import TurnPhase from ..ops import get_next_market class MarketPhase(TurnPhase): def execute(self, C, player=None, action=None): if a...
a = 4 b = 2 c = 1 d = 4 e = 5 f = 6 Comp_var = {a,b,c,d,e,f} # Множество не содержит повторяющиеся элементы print(Comp_var) print(len(Comp_var)) if ( len(Comp_var) == 6 ): print("Все разные") else: print("Есть одинаковые")
import tensorflow as tf import utili.dataset_factory as datasets from modules import resnet_v1 import utili.config as config def cls_score_layer(input): score = tf.keras.layers.Conv2D(18,(1,1),activation=tf.nn.softmax,name="rpn_cls_score")(input) score = tf.reshape(score, [-1, 2]) # -1 means flatten to 1-D ...
import plotly.express as px import pandas as pd import csv df = pd.read_csv('file1.csv') fig = px.scatter(df,x='Temperature',y='Ice-cream Sales( ₹ )') fig.show()
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-12 20:59 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0007_profile_course_combo'), ] op...
#!/usr/bin/env python3 import aerospike def main(): if '__version__' in dir(aerospike): print(("Python client version is %s" % aerospike.__version__)) else: print("don't know what Python client version is") if 'MAP_RETURN_UNORDERED_MAP' in dir(aerospike): print(("Python client su...
# Generated by Django 3.1.1 on 2020-10-01 16:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0002_prices_value'), ] operations = [ migrations.CreateModel( name='clients', ...
# Write a python function to generate # and return the list of all possible sentences created from the given lists of Subject, Verb and Object. # Note: The sentence should contain only one subject, verb and object each. # Sample Input Expected Output # subjects=["I", "You"] # verbs=["Play", "Love"] # objects=["Hockey...
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- import sys from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtQml import QQmlApplicationEngine def main(): app = QApplication(sys.argv) engine = QQmlApplicationEngine() engine.setOfflineStoragePath("./Databases/") eng...
from flask import render_template, redirect, url_for, abort, flash, request, \ current_app, make_response, abort from flask.ext.login import login_required, current_user from flask.ext.sqlalchemy import get_debug_queries from app.decorators import admin_required from . import main from .forms import EditProfileFor...
from Models import Encoder from data_loader import cropus import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import sys import torch.optim as optim import os from visdom import Visdom def get_dev_loss(model,mycropus,dev_data,criterion): #计算开发测试节集损失 dev_loss_list=[] d...
from django.contrib import admin from .models import suggestion # Register your models here. @admin.register(suggestion) class suggestAdmin(admin.ModelAdmin): list_display = ['name1','others']
INF = 1000 def getDigits(n): return set(map(int, list(str(n)))) T = input() for t in range(1, T+1): N = input() if N == 0: res = "INSOMNIA" else: digits = set() for i in range(1, INF): digits.update(getDigits(N*i)) if len(digits) == 10: res = N*i break print "Case #%d: %s" % (t, res)
import os import tensorflow as tf import numpy as np from tensorflow.contrib.tensorboard.plugins import projector import gensim LOGDIR = 'log' N = 3000 D = 300 # load model word2vec = gensim.models.KeyedVectors.load_word2vec_format('filtered.bin', binary=True) vocab = list(word2vec.vocab.keys()) # create a list of ve...
import array import matplotlib.pyplot as plt import skimage.transform as transform import numpy as np import scipy.integrate as spi import scipy.optimize as sopt import warnings import scipy.interpolate as sinterp def get_vanhateren(filename, src_dir): with open(filename, 'rb') as handle: s = handle.read()...
import cv2 camera = cv2.VideoCapture(0) prev_frame = None while camera.isOpened(): success, frame = camera.read() if not success: break frame = cv2.medianBlur(frame, 5) if prev_frame is not None: mask = cv2.absdiff(frame, prev_frame) _, mask = cv2.threshold(mask, 50, 255, cv...
# Copyright (c) 2017-present, yszhu. # # 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 to in w...
import random import os if __name__ == "__main__": # os.rename('./data/plaws.csv', './data/plaws_full.csv') with open("./data/plaws.csv", "rb") as source: lines = [line for line in source] random_choice = random.sample(lines, 200) source.close() with open("./data/plaws.csv", "wb")...
#!/usr/bin/env python3 from caproto import ChannelType from caproto.server import PVGroup, SubGroup, ioc_arg_parser, pvproperty, run class EpicsScalerGroup(PVGroup): count = pvproperty(name=".CNT", dtype=int) count_mode = pvproperty( value="OneShot", name=".CONT", dtype=ChannelType.ENU...
#!/usr/bin/python # -*- coding: utf-8 -*- """Friendly Python SSH2 interface.""" import os import sys import tempfile import paramiko import traceback class Connection(object): """Connects and logs into the specified hostname. Arguments that are not given are guessed from the environment.""" def __init__...
class Stack: def __init__(self, list=None): if list == None: self.items = [] self.len = 0 else: self.items = list self.len = len(list) def push(self, item): self.items.append(item) self.len += 1 def pop(self): self...
""" 模型 Revision ID: e3729b5abc40 Revises: Create Date: 2018-10-27 13:13:38.276381 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e3729b5abc40' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by A...
#!/usr/bin/env python # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import sys from typing import Any, Dict, cast import setuptools def get_version() -> str: onefuzz: Dict[str, Any] = {} with open("onefuzz/__version__.py") as fh: # Exec our own __version__.py to pull out ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """pybej.py Author: William Yao <LNYK@ME.COM> at <LNYK2.COM> Date : 2015.05.27 A very simple script to catalyse your headsets. USE IT UNDER YOUR OWN RISK! """ class Locale(): def __init__(self, lang='en'): self.trans = None zh_CN = {'i.1': u'欢迎使用 p...
import re # print(re.findall(r'paper/\d+/reference','paper/1559136758/reference')) # temp = ' CITATIONS* (1,318)' # # ''' # CITATIONS* (567) # CITATIONS* (1,318) # CITATIONS* (460) # CITATIONS* (481) # CITATIONS* (603) # CITATIONS* (136) # ''' # Citation_...
from django import forms class CtsQueryForm(forms.Form): ctsproductnum = forms.CharField(required=False,max_length=20,widget=forms.TextInput(attrs={'placeholder':'请输入商品编码','class': 'form-control'})) ctssellcountmin = forms.CharField(required=False,max_length=20,widget=forms.TextInput(attrs={'placeholder':'请输入商...
from rest_framework.filters import OrderingFilter from rest_framework_filters.backends import RestFrameworkFilterBackend, ComplexFilterBackend from rest_framework_filters_nkg.filterset import FilterSetNkg from rest_framework_filters_nkg.utils import * parent_fields = ['ForeignField', 'PrimaryKeyRelatedField'] number...
import math import numpy as np from algorithms import center_of_mass def test_center_of_mass_impulse(): image = np.zeros(10) image[4] = 1.0 assert center_of_mass(image) == 4.0 def test_center_of_mass_rect(): image = np.zeros(10) image[4] = 1.0 image[5] = 1.0 assert math.isclose(center_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 27 21:15:04 2018 @author: Iswariya Manivannan """ import sys import os from collections import deque from helper import maze_map_to_tree, write_to_file, assign_character_for_nodes from helper import start_pose, print_maze, clear_screen import time ...
import pymongo from pymongo import Connection connection = Connection() # Удалить БД, если она существует connection.drop_database("server_database") # Выбираем БД db = connection["server_database"] # Удалить коллекцию db.drop_collection('users') # Добавление документов в колекцию 'users' def insert...
from django.conf import settings from rest_framework import serializers from openbook.settings import COLOR_ATTR_MAX_LENGTH from openbook_categories.models import Category from openbook_categories.validators import category_name_exists from openbook_common.serializers import CommonCommunityMembershipSerializer from op...
import socket def get_machine_info(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) print("host name is: \t %s " % host_name) print("This machines IP address is: \t %s" % ip_address) get_machine_info()
import json, os, re, dateutil.parser from nltk.tokenize import word_tokenize import string from nltk.corpus import stopwords import nltk import markdown2 from bs4 import BeautifulSoup nltk.download('punkt') nltk.download('stopwords') repos = ['react', 'angular', 'vue', 'backbone', 'ember.js', 'jquery'] fields = ['tit...
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: C:\ProgramData\Ableton\Live 9.7 Suite\Resources\MIDI Remote Scripts\_NKFW2\ModifierMixin.py # Compiled at: 2017-03-07 13:28:52 from ...
# This sample tests various type checking operations relating to # generator functions that use the "yield from" clause. from typing import Iterator class ClassA: pass class ClassB: def shouldContinue(self): return True class ClassC: pass def generator1() -> Iterator[ClassA]: yield from...
from flask import Flask app = Flask(__name__) @app.route("/") import numpy as np import pandas as pd import matplotlib.pyplot as plt # For this assignment, we need to load in the following modules import requests import StringIO import zipfile import scipy.stats def getZIP(zipFileName): r = requests.get(zipFile...
#============================================================================ #Name : xmlhelper.py #Part of : Helium #Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). #All rights reserved. #This component and the accompanying materials are made available #under the terms of the Li...
''' <21.02.22> made by KH problem number: 2577 source: https://www.acmicpc.net/problem/2577 ''' inputNumber1 = int(input()) inputNumber2 = int(input()) inputNumber3 = int(input()) productNumber = inputNumber1*inputNumber2*inputNumber3 productNumberStr = str(productNumber) for i in range(10): print(productNumbe...
import os import random import numpy as np import scipy.misc as m from PIL import Image from torch.utils import data from torchvision import transforms from dataloaders import custom_transforms as tr from dataloaders.SampleLoader import SampleLoader class KittiSegmentation(data.Dataset): def __init__(self, cfg, s...
from server.util import Plugin # Logs the player into the world messaging system, then allows other users to Private Message the logged in user def pmaccess(player): player.getPA().logIntoPM()
#paper #Reasoning about Entailment with Neural Attention #https://arxiv.org/pdf/1509.06664v1.pdf import tensorflow as tf import numpy as np batch_size = 3 seq_len = 5 dim = 2 # [batch_size x seq_len x dim] -- hidden states Y = tf.constant(np.random.randn(batch_size, seq_len, dim), tf.float32) # [batch_size x dim] ...
from collections import defaultdict from functools import reduce from typing import DefaultDict, Dict, List, Optional, Tuple, TypedDict, cast from sqlalchemy import and_ from sqlalchemy.orm import Session from src.challenges.challenge_event_bus import ChallengeEventBus from src.models.rewards.challenge import Challen...
from django.contrib import admin from .models import Example from django_gaode_maps.widgets import LocationWidget from django_gaode_maps.fields import LocationField @admin.register(Example) class ExampleAdmin(admin.ModelAdmin): fields = ["address", "city", "postal_code", "location"] formfield_overrides = { ...
def print_max(x,y): '''Prints the max of 2 numbers. The two values must be integers.''' #convert to int if possible x = int(x) y = int(y) if x > y: print x, ' is maximum' else: print y, ' is maximum' print_max(3,5) print print_max.__doc__ #docstrings: a multi-line string where the first line starts...
m,p=map(int,input().split()) l2=list(map(int,input().strip().split()))[:m] for i in range(0,m): if(l2[i]==p): print("yes") break else: print("no")
# coding: utf-8 from django.shortcuts import get_object_or_404 from parlaseje.models import * from sklearn.decomposition import PCA from numpy import argpartition import pandas as pd import requests import json from collections import Counter from parlaseje.models import Vote_analysis from parlalize.settings import ...
#Q1 To find area of a circle def SetArea (): radius = int(input('enter the radius')) myarea =3.14*radius** 2 return myarea print(SetArea()) #Q2 Finding perfect number def perfect(x): list=[] for i in range(1,x ):#finding factors except number itself if x % i == 0: list.a...
# encoding: UTF-8 from socketIO_client import SocketIO from EventConstant import * from Config import * from RtConstant import * from RtObject import * import requests import json basetPath = "http://" + host + ":" + str(httpPort) + "/api" class StrategyTemplate: def __init__(self): self.tickIDSet = set...
# stdlib import copy # 3p from mock import Mock from nose.plugins.attrib import attr # project from tests.checks.common import AgentCheckTest INSTANCE = { 'class': 'Win32_PerfFormattedData_PerfProc_Process', 'metrics': [ ['ThreadCount', 'proc.threads.count', 'gauge'], ['IOReadBytesPerSec', 'p...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) email = db.Column(db.String, nullable=False) password = db.Column(db.String, nullable=False) def __in...
# importing flask modules from flask import Flask, render_template, request, redirect, url_for, session, flash from flask_mysqldb import MySQL import MySQLdb.cursors import re import csv import mlmodel import Fake_review_5_Algos import pandas as pd import io import random from flask import Response from matplotlib.back...