text
stringlengths
38
1.54M
try: price=int(input("Enter the price-")) except: print("Invalid Input") else: print("Product added successfully") try: print(2/0) except: print("Zero division error") else: print("Division Successful") finally: print("Perhaps")
#!/usr/bin/env python3 #coding:utf8 import subprocess import re a = ''' docker0 Link encap:Ethernet HWaddr 4A:A3:0C:97:E9:11 inet addr:192.168.42.1 Bcast:0.0.0.0 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 fr...
from AbstractMemoryInstruction import AbstractMemoryInstruction as AMI class POP(AMI): def __init__(self, registry): super(POP, self).__init__(registry) def generate(self): return 'pop %{}'.format(self._value)
from flask import Flask, send_from_directory from config import Config from requests import Session from flask_bootstrap import Bootstrap from pymongo import MongoClient app = Flask(__name__) app.config.from_object(Config) bootstrap = Bootstrap(app) mongo_client = MongoClient(host="localhost", port=27017) db = mongo_c...
import sys if sys.version_info.major != 3: print("Error: You must use python3") exit() import os import pickle as pkl import csv from data_management.read_csv import * from visualization.visualize_frame import VisualizationPlot import main TRAVEL_DIR_LEFT_TO_RIGHT = 2 TRAVEL_DIR_RIGHT_TO_LEFT = 1 LC_LEFT =...
class Solution: def isEscapePossible(self, blocked, source, target): from collections import deque blocked = set(map(tuple, blocked)) def bfs(source, target): queue = deque() queue.appendleft((source[0], source[1], 0)) visited = set() visited....
from django.contrib import admin from juriidilisedjuured.models import Node from juriidilisedjuured.forms import NodeForm class NodeAdmin(admin.ModelAdmin): form = NodeForm admin.site.register(Node, NodeAdmin)
from gnuradio.digital import ofdm_packet_utils as pkt_utils def conv_string_to_1_0_list(s): """ s = 'Hello World!'' """ unpacked_s = pkt_utils.conv_packed_binary_string_to_1_0_string(s) unpacked_s = list(unpacked_s) for i in range(len(unpacked_s)): unpacked_s[i] = int(unpacked_s[i]) ...
import pandas as pd import numpy as np max_len= 10 data = pd.DataFrame(columns=np.arange(max_len)) for i in range(10): reading = pd.DataFrame([np.arange(20)],columns=np.arange(20)) data=data.append(reading, ignore_index=True) remove_cols = [5,6] data=data.drop(columns=remove_cols) print()
import cv2 # 图片读取与显示 src = cv2.imread("./pictures/factory.jpg") cv2.namedWindow("input", cv2.WINDOW_FREERATIO) cv2.imshow("input", src) cv2.waitKey(0) cv2.destroyAllWindows()
from PackagesAndModels.pack import * from PackagesAndModels.method_functions import * from PackagesAndModels.train_val_test_MNIST import * from PackagesAndModels.MNIST_MODELS import * import pickle import timeit criterion = nn.CrossEntropyLoss() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") b...
weight = input('Your weight (kgw): ') height = input('Your height (cm): ') print('Your weight and height are ', weight, height)
from dp.backend.clients import ConfluentClient, KafkaPythonClient from dp.filter_extract import get_filter_func def get_kafka_client(): return KafkaPythonClient() # return ConfluentClient() def get_filtered_kafka_messages(topic, filter_func, expected_count, offset, timeout): client = get_kafka_client() ...
from django.test import TestCase, Client from . import extras # Create your tests here. # these are the tests that show # that the attack no longer works # test that xxs is fixed class XXSTestCase(TestCase): fixtures = ['testdata.json'] def setUp(self): self.client = Client() def testXXS(self): response = ...
# _*_ coding: utf-8 _*_ # author: guoxiaopolu import urllib2 import sys import json from BeautifulSoup import * reload(sys) sys.setdefaultencoding('utf-8') # 传入汽车所属url与所属国家,爬取指定url的汽车信息 def findcar(url, countryname): try: c = urllib2.urlopen(url) except: print "Could not open %s" % url ...
""" Código para raspagem dos resumos submetidos aos Simpósio Nacionais de História da Anpuh entre 2013 e 2019. Autoria: Eric Brasil (IHL-UNILAB, LABHDUFBA) """ from urllib.request import Request, urlopen from bs4 import BeautifulSoup import pandas as pd from datetime import datetime from pprint import pprint dic = {'U...
# -*- coding: utf-8 -*- # jeroen.vanparidon@mpi.nl import os import lzma import argparse import random import itertools from utensils import log_timer import logging logging.basicConfig(format='[{levelname}] {message}', style='{', level=logging.INFO) def get_lines(fhandle): """Removes duplicate lines from a file....
# Generated by Django 3.1.7 on 2021-04-23 17:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mobile', '0002_order_product'), ] operations = [ migrations.CreateModel( name='cart', fields=[ ('id'...
# coding: utf-8 #!/usr/bin/env python from torneira.controller import BaseController, render_to_extension from tornado.web import HTTPError from twittface.models.voto import Voto import tweepy import math import settings import datetime class VotoController(BaseController): CONTEXT = "" def create(self...
import pymongo import sys # establish connection to db connection = pymongo.Connection("mongodb://localhost", safe=True) # handle to students collection db = connection.school students = db.students def delete_lowest_homework_score(): cursor = students.find({}) try: for student in cursor: student_id =...
from aiogram import types from aiogram.dispatcher.filters import Command from loader import dp from utils.db_api.models import User from utils.misc.sentinel import allow_access @allow_access() @dp.message_handler(Command('block_me')) async def block_me(message: types.Message, user: User): await message.answer(f"...
''' Created on Jun 21, 2018 @author: ftd ''' import os import shutil from pathlib import Path from src.main.pydev.com.ftd.generalutilities.metadata.service.base.File_constant import File_constant class File_processor(object): ''' classdocs ''' @staticmethod def get_home_dir(): ret...
# Generated by Django 2.0 on 2017-12-22 06:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('platformes', '0001_initial'), ] operations = [ migrations.AddField( model_name='goods', name='good_url', f...
import requests from .Handlers import ( ApiError as _ApiError, IllegalArgumentError as _IllegalArgumentError, ) ApiError = _ApiError # should silence code analysis warning IllegalArgumentError = _IllegalArgumentError TimeoutError = requests.exceptions.Timeout
# Single Channel Noise Removal using the Subspace Approach # Copyright (C) 2019 Eric Bezzam, Mathieu Lecoq, Gimena Segrelles # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restric...
# -*- coding: utf-8 -*- from good import Schema, All, Required, Optional, Length, Match, Email login_schema = Schema({ Required('login'): unicode, Required('password'): unicode }) signup_schema = Schema({ Required('usern...
# Filename: TaxRate.py import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class TaxRate(QObject): def __init__(self): super(TaxRate, self).__init__() self.__rate = 17.5 def rate(self): return self.__rate def setRate(self, rate): if rate != self._...
lsfrom selenium import webdriver import unittest import sys usingChrome=False class remoteExample(unittest.TestCase): def setUp(self): if(usingChrome): self._driver=webdriver.Remote("http://152.23.23.217:4444/wd/hub", webdriver.DesiredCapabilities.CHROME) else: self._driver=webdriver.Remote("http://152.23....
#!/usr/bin/env python room_grid =\ [ ['*', '8', '-', '1'], ['4', '*', '11', '*'], ['+', '4', '-', '18'], ['22', '-', '9', '*'] ] # Because it's easier to access like (x, y) than [x][y], or at least feels nicer. rooms = {(a, b): room_grid[a][b] for b in range(4) for a in range(4)...
name='ted' for char in name: print(char) shows=['this', 'is', 'list'] for smthn in shows: print(smthn) kor=('this', 'is', 'tuple') for jj in kor: print(jj) people_in_dictionary={'jim': 'BBT', 'brian': 'tyler', ...
import numpy as np from scipy.signal import cont2discrete as c2d import scipy.io as sio class params(object): ## Parameters definition def __init__(self): # model parameters self.m = 1.5 # mass of the quadcopter (Kg) 0.468 self.g = 9.8 # gravity (m/sec^2) self.kx =...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import warnings from pyramid import httpexceptions from sqlalchemy.orm.exc import NoResultFound from ..views import permalinker from ..dynmenu import DynMenu, Label, Link, DynItem from ..psection import PageSections from ..pyramid import viewargs from...
from abc import ABC from typing import List, Dict import torch from torch import Tensor from hana.rindou.poser.v2.poser_gan_loss import PoserGanLoss from hana.rindou.poser.v2.poser_gan_module import PoserGanModule ORIGINAL = 'original' G_OUTPUT = "G_output" KEYPOINT_OUTPUT = "keypoint_output" class K...
import time import chess import chess.pgn import random 'uh oh here here i go again...' GLOBAL_MIN = -1000000 GLOBAL_MAX = 1000000 class engine: def __init__(self, tlim): self.root = None self.layers = 3 self.help = helper() self.start_time = 0 self.tlim = tlim def pla...
from django.db import models from django.contrib.auth.models import User from django_resized import ResizedImageField class MakePost(models.Model): title = models.CharField(max_length=30) content = models.TextField(max_length=500, blank=True) photo = ResizedImageField(size=[500, 300], quality=100, upload_t...
from flask import jsonify from dao.resource import ResourcesDAO class ResourceHandler: def build_resource_dict(self, row): result = {} result['rid'] = row[0] result['sid'] = row[1] result['rname'] = row[2] result['cost'] = row[3] result['resAmount'] = row[4] ...
''' Script for downloading and working with a term programme. ''' import os import sys import traceback from datetime import date import xlsxwriter from docx import Document from docx.enum.section import WD_ORIENT from docx.enum.style import WD_STYLE_TYPE from docx.shared import Cm, Pt from osm import Connection, Man...
def hello_max(): print('Hello Max') def hello(who): print('Hello', who) def greetiong(who, say): print(say, who) def greetiong_default(who, say='Hello'): print(say, who) hello_max() hello('Leo') hello('Max') greetiong('Привет епта', 'Максон') greetiong(say='Hi', who='Lol') greetiong_default(...
# -*- coding: utf-8 -*- """ Created on Fri Sep 6 20:38:51 2019 @author: Administrator """ import torch import yi import math def knn_kdtree(x, y, k): # x: torch.FloatTensor[B, M, 3] # y: torch.FloatTensor[B, N, 3] # output: tuple(torch.FloatTensor[B, N, k], torch.LongTensor[B, N, k])...
import pandas as pd import numpy as np from iexfinance import get_historical_data from datetime import datetime from datetime import timedelta # https://pypi.org/project/iexfinance/ IPOData = pd.read_excel("ipo.xlsx") IPOData_np = np.array(IPOData) def getQuote(index): print("processing " + IPOData_np[index,3] ...
# Copyright (c) Alibaba, Inc. and its affiliates. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class SinusoidalPositionEncoder(nn.Module): def __init__(self, max_len, depth): super(SinusoidalPositionEncoder, self).__init__() self.max_len = max_len ...
#!/usr/env/bin python # # Buttons # # import pygame class Button: def __init__(self, color, coordinates, width, height, text = ''): self.color = pygame.Color(*color) self.x, self.y = coordinates self.width = width self.height = height self.text = text self.active = False def isHover(self, mouse_x, mo...
import numpy class ProportionalControl: def calculatePolarError(states,referencePosition): errorPosition = referencePosition - states[0:2] referenceAngle = numpy.arctan2(errorPosition[1],errorPosition[0]) errorAngle = referenceAngle - states[2] magnitude = numpy.sqrt(errorPosit...
import re from datetime import date from OOP_with_python.utility.My_utility import * class Regex: def __init__(self): self.number = "1122334455" def regex(self, data): # Replace name at every position by user_name replace_name = re.sub('<<name>>', "Akanksha", data) replace_f_n...
# -*- coding: utf-8 -*- # Copyright 2015-2016 Ivan Yelizariev <https://it-projects.info/team/yelizariev> # Copyright 2016 Ilyas Rakhimkulov # Copyright 2017 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr> # Copyright 2016-2018 Dinar Gabbasov <https://it-projects.info/team/GabbasovDinar> # License MIT...
# coding=utf-8 # def add_num(num): # with open('%s.txt'%num, 'w') as fp: # for i in range(1,100): # num += 1 # fp.write(str(num) + '\n') # # add_num(49110000) import os def File_num(path): if os.path.isfile(path): print('file num is 1') return num = 0 fi...
from flask import Flask, render_template from flask_assets import Environment, Bundle app = Flask(__name__) app.config['DEBUG'] = True assets = Environment(app) less = Bundle('styles/app.less', filters='less',depends='styles/less/**/*.less', output='app.css') assets.register('less', less) @app.route('/') def index()...
import os import pandas as pd from utils.PreprocessUtils import clean_text, remove_stopwords, lemmatize_text, tf_idf, export_tfidf_to_dill def files_to_df(): path = '..\\data\\bbc' # path = '..\\data\\bbcSample' df = pd.DataFrame(columns=['id', 'path', 'filename', 'text']) for root, dirs, files in o...
#!/usr/bin/env python #coding:utf-8 '''3 合并排序 基本思想: 获取两个已经排序的列表,然后将他们合并成一个列表, 我们先以非常小的列表开始,然后不断对它们进行合并, 直到最终剩下单个已排序列表为止。''' def merge(left, right): """合并两个数组""" merged = [] i, j = 0, 0 # i, j 分别作为left和right的下标 left_len, right_len = len(left), len(right) while i < left_len and j < right_len: ...
from unittest import mock import pytest from services.translation import ( TranslationConfig, TranslationRequest, TranslationResponse, TranslationService, ) translation_test_data = [ # Test same language returns same string ("google", "Hello test", "en-US", "en-US", "Hello test", None), ("...
import socket import sys import select import upload from encryption import encrypter, decrypter, init_key, init_iv DEFAULT_BUFF = 128 MAX_READ = 112 def ping(): first = "ping\n".encode() first = encrypter(first) connection.sendall(first) while True: line = sys.stdin.readline() encryp...
"""Remove a Few Things Sometimes you need to remove something from a list. beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatles This code will print: ["john","paul","george","ringo"] We create a list called beatles with 5 strings. Then, we remove the first item from beatles that...
#!/usr/bin/python3 import torch.utils.data from typing import List, Tuple from mseg_semantic.utils import dataset, transform, config def create_test_loader(args) -> Tuple[torch.utils.data.dataloader.DataLoader, List[Tuple[str,str]]]: """ Create a Pytorch dataloader from a dataroot and list of relative paths. ...
from django.test import TestCase from .models import * class SmsTestCase(TestCase): def setUp(self): Template.objects.create(label='test', code='test', content='【漫点科技】验证码%s,用于注册登录,请勿泄露') def test_send_sms(self): result = Sms.objects.send_sms('15550001234', 'test', '1234') self.assert...
import os,sys sys.path.append(os.path.dirname(os.path.realpath(""))) from image import * from imgstream import * def test_stereo(): stream = Stream(mode='img',src='stereotest') img1 = stream.get() img2 = stream.get() f = 1000 K = np.zeros((3,3)) K[0,0] = f K[1,1] = f K[2,2] = 1 K[0,2] = img1.shape[0] K[1...
import unittest import calc class CalcultaroTestCase(unittest.TestCase): def test_add(self): self.assertEqual(calc.add(2, 3), 5) def test_sub(self): self.assertEqual(calc.subtract(10, 5), 5) def test_div(self): self.assertEqual(calc.division(10, 2), 5) def test_multiply(self...
# -*- coding: utf-8 -*- import datetime import json from django.http import HttpResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from django.views.g...
#!/usr/bin/env python3 import surfex import sys if __name__ == "__main__": args = surfex.parse_args_gridpp(sys.argv[1:]) surfex.run_gridpp(args)
class Solution: def removeDuplicates(self, nums: List[int]) -> int: if len(nums) < 2: return len(nums) pointer = 0 for i in range(len(nums)): if nums[pointer] != nums[i]: pointer += 1 nums[pointer] = nums[i] return pointer+...
# Generated by Django 2.2.1 on 2019-05-12 07:33 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ...
from flask import render_template, redirect, url_for, request, session, flash from shop import db from . import auth_bp from .forms import RegistrationForm, LoginForm from .models import User @auth_bp.route('/register/', methods=['GET', 'POST']) def register(): form = RegistrationForm(request.form) if request...
__all__ = ('TOUHOU_ACTION_KISS',) from ...image_handling_core import ImageDetail from ...touhou_core.character import freeze from ...touhou_core.characters import KOMEIJI_KOISHI, SCARLET_FLANDRE TOUHOU_ACTION_KISS = [ ImageDetail( 'https://cdn.discordapp.com/attachments/568837922288173058/102327382667246...
# coding: utf-8 from sqlalchemy import Column, Float, Integer, Table, Text from sqlalchemy.sql.sqltypes import NullType from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class BOX(db.Model): __tablename__ = 'BOX' id = db.Column(db.Integer, primary_key=True) movie_key = db.Column(db.Integer, nul...
import unittest import numpy as np import pandas as pd import xarray as xr import stglib class TestUtils(unittest.TestCase): def test_rotate(self): expected = (-np.sqrt(2) / 2, np.sqrt(2) / 2) result = stglib.aqd.aqdutils.rotate(0, 1, -45) np.testing.assert_almost_equal(expected, result)...
import random import time import requests from BeautifulSoup import BeautifulSoup from methods import * from config import endpoints logger = logging.getLogger('incapsula') def _load_encapsula_resource(sess, response): timing = [] start = now_in_seconds() timing.append('s:{}'.format(now_in_seconds() - ...
''' Model baseclass ''' # pylint: disable=no-member import json import os import time import random import sys from collections import Counter import numpy as np from sklearn.model_selection import train_test_split from sklearn.utils import class_weight from tensorflow.keras.optimizers import Adam from tensorflow....
import csv import random from hyperopt import STATUS_OK from timeit import default_timer as timer from hyperopt import hp from hyperopt.pyll.stochastic import sample from sklearn.model_selection import KFold, train_test_split from sklearn.metrics import recall_score, precision_score, accuracy_score from hyperopt import...
#!/usr/bin/env python # -*- coding: utf-8 -*- # explode: 将一行数据展开成多行 # nunique: 去重计数 # replace: 替换df中的值,赋以新的值 import pandas as pd import numpy as np # DataFrame.explode(self, column: Union[str, Tuple]) def l_explode(): id = ['a','b','c'] measurement = [4,6,[2,3,8]] day = [1,1,1] df1 = pd.DataFrame({'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 11 18:21:30 2018 @author: virajdeshwal """ '''Let's start the Natural Language Processing. In the dataset. 1= positive review 0= negetive review''' import pandas as pd #We will use tab seperated Variabel(.tsv) file. #checkout the synt...
from django.shortcuts import render from .models import Person def persons_list(request): persons = Person.objects.all() return render(request, 'person.html', {'person': persons}) # Create your views here.
# Copyright 2019 Balaji Veeramani. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
from margo_parser.exceptions import MargoParseException import json from margo_parser.api import ( MargoBlock, MargoDirective, MargoAssignment, MargoStatementTypes, ) import pytest import yaml def test_parses_empty_margo_block(): block = MargoBlock("") assert block.statements == [] def test_...
# compat2.py # Copyright (c) 2013-2019 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0111,R1717,W0122,W0613 # Standard library imports import re ### # Functions ### def _ex_type_str(exobj): # pragma: no cover """Return a string corresponding to the exception type.""" regexp = re.compile...
import logging log = logging.getLogger(__name__) from functools import partial import operator as op import threading import numpy as np from atom.api import Enum, Bool, Typed, Property from enaml.application import deferred_call from enaml.qt.QtCore import QTimer from enaml.workbench.api import Extension from enaml...
#!/usr/bin/env python3 """Kafka connector """ __author__ = 'Ali Rahim-Taleqani' __copyright__ = 'Copyright 2020, The Insight Data Engineering' __credits__ = [""] __version__ = '0.1' __maintainer__ = 'Ali Rahim-Taleqani' __email__ = 'ali.rahim.taleani@gmail.com' __status__ = 'Development' import argparse import json im...
import requests import json from math import ceil import pandas as pd import os USER = os.environ.get('PELOTON_DISPLAY_NAME') EMAIL = os.environ.get('PELOTON_EMAIL') PWD = os.environ.get('PELOTON_PWD') PAYLOAD = {'username_or_email': EMAIL, 'password':PWD} LOGIN_URL = 'https://api.onepeloton.com/auth/login' USER_URL =...
class Node: def __init__(self, key): self.parent = None self.key = key self.right = None self.left = None self.start = float('-inf') self.end = float('inf') self.intervals = [] def succ(self): tmp=self if tmp.right is not None: ...
from numpy import * from case4 import case4 from scipy.sparse import * import nlopt ppc = case4() bus = ppc["bus"] branch = ppc["branch"] gen = ppc["gen"] baseMVA = ppc["baseMVA"] nb = 4 #number of bus nl = 4 #number of branch ng = 2 #number of generator #calculate Ybus, this part from pypower stat =...
from cs50 import get_int # prompt for height where h is an integer between 1 and 8 while True: h = get_int("Height: ") w = h if h > 0 and h <= 8: break # print # based on input value of h for i in range(1, h + 1): hash = i spaces = w - hash print(" " * spaces, end="") print("#" * ...
from tkinter import * import Pmw def inisialisasi(): #Code tetap, inisialisasi root = Tk() root.title('ElGamal Cryptosystem') Pmw.initialise() # Create and pack the NoteBook. notebook = Pmw.NoteBook(root) #membuat objek notebook notebook.pack(fill = 'both', expand = 1, padx = 10, ...
# Copyright 2016 - Nokia # # 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 writing, sof...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'petro-ew' """ 41. Написать программу, считывающую текстовой файл и выводящую 20 самых часто встречающихся в нем слов. Слово - это последовательность символов, не содержащая разделителей. Разделители - это символы в данной строке: " .,:;-?!\n". ...
""" RF_Train_Test.py date: 25-Jun-2021 author: L.Zhang Contact: leojayak@gmail.com ------------------------------------- Description: """ # libraries import os import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.m...
# this file will automatically be changed, # do not add anything but the version number here! __version__ = "3.7.0a1"
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split import numpy as np class RNN_Transform_Wrap(BaseEstimator, TransformerMixin): """ Wrapper to apply scaling transformation to 3d shaped array required ...
from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.optimizers import Adam from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import regulariz...
# -*- coding: utf-8 -*- """ Created on Mon Dec 21 13:50:05 2020 @author: amsa9 """ from sklearn.metrics import accuracy_score,confusion_matrix import matplotlib.pyplot as plt import itertools import numpy as np classes=['buildings','forest','mountain','sea'] priors=[] covariances=[] means=[] # === likelihood 계산 함수 ...
class RelationClassifier: def isBijection(self, domain, range): d = {} for x in domain: if x in d: return 'Not' d[x] = True d = {} for x in range: if x in d: return 'Not' d[x] = True return 'Bijection'
import datetime class file_system(): def __init__(self, nome): # Inicializa o FileSystem com os arquivos já contidos no disco print("\nSistema de arquivos =>") with open(nome, 'r') as f: lines = [l.strip() for l in f.readlines()] self.num_blocks = int(lines[0]) ...
from django.contrib import admin from clubkit.roster.models import RosterId admin.site.register(RosterId)
""" User input handling """ from pygame import joystick from pygame.locals import * import pygame import logging import functions import Display # Controller sensitivity to axis position changes POS_SENS = 0.2 # Positive sensitivity NEG_SENS = -0.2 # Negative sensitivity HAT_UP = (0, 1) HAT_DOWN = (0, -1) ...
#!/usr/bin/env python import sys import Personis import Personis_base import Personis_a from Personis_util import printcomplist, printjson print "skipping import test. Edit script to test" sys.exit(0) # import a model sub tree from JSON um = Personis_a.Access(model="Alice", modeldir='Tests/Models', user='alice', pa...
import socket import threading import sys import datetime import time import hashlib def packetMaker(packet,i): hash_value = (hashlib.sha1(str(i).zfill(5) + packet).hexdigest())[:10] packet = str(i).zfill(5) + packet + hash_value return packet i = 1 input_file = open("input.txt", "rb") file_array = [] p...
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 14:20:17 2018 @author: Anshu Pandey """ import numpy x=[4,5,6] y=[7,2,9] x+y x=numpy.array([7,4,2,6]) y=numpy.array([2,3,9,8]) type(x) x.size x+y x*y x-y x/y x=numpy.array([[7,4,2,6],[1,2,5,8],[3,6,9,4]]) x.dtype #data type of the elements x...
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def index(): return render_template ("index.html") @app.route("/ninja") def all_ninja(): return render_template ("all_ninjas.html") @app.route("/ninja/<color>") def specific_ninja(color): color = color if color == "blue": r...
""" A collection of handy functions for making python microservices work in the real world """ from os import getpid, getenv from socket import getfqdn, gethostbyname import logging import urllib2 import json import datetime import traceback as tb def send_request_to_bus(input_dict,host,port,topic): """ this is...
__author__ = 'suhas subramanya' import MapReduce import sys import json mr=MapReduce.MapReduce() def mapper(record): mr.emit_intermediate(record[1],('A',record[0],record[2])) mr.emit_intermediate(record[0],('B',record[1],record[2])) def reducer(key,list_of_values): firstMatrix=[] secondMatrix=[] ...
from examples.ramen_rec.tests.conftest import TestRamens from examples.ramen_rec.app.services import GraphRamenQueryService from examples.ramen_rec.app.models import Ramen from frex.services import DomainKgQueryService from frex.stores import LocalGraph def test_get_ramen_by_uri( graph_ramen_query_service: GraphR...
import requests from selenium import webdriver def get_job(): """发送请求获取任务""" return 'josn_dict' def consumer_job(jobs=''): """执行并保存""" driver = webdriver.Chrome() url = 'https://www.facebook.com/701004359919966' driver.get(url) html = driver.page_source with open("temp.html", 'w', enc...
from tkinter import * def print_me(): result = text.get(1.0,END) print(result) def print_me1(): result = text.selection_get() print(result) def position(): result = text.selection_get() pos = text.search(result,0.0,stopindex=END) print(pos) def clearme(): text.delete(1.0,END) root =...