text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- """ Created on Mon Apr 5 17:13:17 2021 @author: vedhs """ from shutil import copyfile import os import random def splitSets(fromPath,trainPath,validPath,ratio=0.75,print_status=True): plants=list(os.walk(fromPath))[0][1] for plant in plants: diseases=list(os.wal...
# Here are the test scores of 10 students in physics and history: # # Physics Scores 15 12 8 8 7 7 7 6 5 3 # History Scores 10 25 17 11 13 17 20 13 9 15 # Compute the slope of the line of regression obtained while treating Physics as # the independent variable. Compute the answer correct to ...
N = int(input()) XYZ = [] for _ in range(N): XYZ.append(list(map(int, input().split()))) cost = [[float('inf') for i in range(N)] for j in range(N)] # コストをsakuseisuru for i in range(N): for j in range(i, N): cost[i][j] = abs(XYZ[i][0] - XYZ[j][0]) + abs(XYZ[i][1] - XYZ[j][1]) + max(0, XYZ[j][2] - XYZ[...
""" Program: Warehouse management system Author: Wes Ray Description: Description: 1 - Register new item id (auto generated) title (str) category (str) stock (int) price (float) 2 - Display Catalog 3 - Up...
from config import *; from HMMCluster import *; import time; import matplotlib.pyplot as plt; from contraint import compute_PMI_of_HMM_Clusters def try_different_hmm_cluster_nums(o_sequence_List,M): # 实验配置值 N_start = 2; N_end = 7; N_list = []; pmi_list = []; for N in range(N_start, N_end + 1):...
# -*- coding: utf-8 -*- import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence def argmax(vec): # return the argmax as a python int _, idx = torch.max(vec, 1) return idx.item() # Compute log sum exp in a numerically stable way for the forward algorit...
__author__ = 'jason' from enum import Enum from system.actors import Actor, ActorMessages class Directory: def __init__(self): self.actors = {} def add_actor(self, name, actor): self.actors[name] = actor def get_actor(self, name): if name in self.actors: return self...
from django.core.mail import send_mail from django.conf import settings def send_email(subject, message, recepient): return send_mail(subject, message, settings.EMAIL_HOST_USER, [recepient],fail_silently = False)
from __future__ import unicode_literals from django.db import models from django.db.models.signals import pre_delete from scrapy_djangoitem import DjangoItem from dynamic_scraper.models import Scraper, SchedulerRuntime from django.dispatch import receiver # Create your models here. class NewsWebsite(models.Model):...
__author__ = 'fernando.ormonde' import numpy as np import math as math from random import normalvariate from collections import Counter import gc; gc.collect() def gerar_pontuacao_2(): d = [] lista = [] for i in range(100): x = np.random.uniform(0, 1.7) y = 1.6 xy = x, y ...
from subprocess import call from tasks import runMsh import sys from celery import group from data import * from startserver import * import time def splitTasks(angle_start, angle_stop, n_angles, n_nodes , n_levels, speed , NumOfWorkers): jobs=[] jobsArgs=[] finalResults=[] totalWorkItems = 0 anglediff= (angle...
"""All things related to sending emails""" import premailer from html2text import html2text from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string as django_render_to_string from django.contrib.sites.models import RequestSite from django.core.urlresolvers import revers...
from django.http import HttpResponse from django.template import loader,RequestContext from django.shortcuts import render def my_render(request,template_path,context_dict={}): t = loader.get_template(template_path) context = RequestContext(request,context_dict) res_html = t.render() return Htt...
import player import boardV2 import brainV2 import display b = 8 print("\n################### Start Jasmine.py ###################\n") legalMoves = ['L', 'F', 'R'] offensiveStrategy1 = [player.aboutToWin, player.aboutToLose, player.offensiveHeuristic] defensiveStrategy1 = [player.aboutToWin, player.aboutToLose, play...
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # 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 applicab...
from rest_framework import serializers from .models import Board, Card, CardList, User # USER SERIALIZERS class UserSerializer(serializers.ModelSerializer): boards = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = User fields = ('pk', 'firebase_uid', 'boards...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import scipy as sp from scipy.linalg import sqrtm import matplotlib.pyplot as plt import matplotlib.ticker as ticker import time import pickle from Optimization.RBCD_IBPde import RiemannianBlockCoordinateDescentIBP from Optimization.RGA_IBP import Riem...
""" Copyright 2015 Rackspace 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, software dist...
import time class EncryptionParameters: @property def salt(self): return time.time()
# Generated by Django 3.1.4 on 2020-12-24 11:47 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [("topic", "0001_initial")] operations = [ migrations.AlterField( model_name="topic", ...
import numpy as np from PIL import Image from matplotlib import pyplot as plt from 数字图像处理.图像几何变换and插值算法.插值算法 import * from 数字图像处理.仿射变换与透视变换.透视变换 import * im = Image.open('./../image/test01.jpg') print(im.size) img = np.array(im) # image类 转 numpy plt.imshow(img) plt.show() # exit() print(img.shape) img = img...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 27 20:28:33 2018 @author: miaoyufei """ import networkx as nx import numpy as np import random import matplotlib.pyplot as plt import json from construct_network import intersections from construct_network import intersections_and_bridges from cons...
salario = int(input('salario: ')) porcetagem = 15 soma = salario +(salario * porcetagem / 100) print(f'{soma}')
from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework import routers from initiativeTrackerApi.views import login_user, register_user, apiScrapper from initiativeTrackerApi.views import Encounters, PlayerCharacterView, MonsterView, EncounterPairViews, Ca...
import os import sys import time import webbrowser import pylast from scrobbler import Scrobbler def main(): try: lastfm_api_key = os.environ.get("LASTFM_API_KEY") lastfm_secret = os.environ.get("LASTFM_SECRET") lastfm_network = pylast.LastFMNetwork(api_key=lastfm_api_key, api_secret=las...
def get_stream(filename): with open(filename, 'r') as fp: char = fp.read(1) while char != '\n': yield char char = fp.read(1) raise StopIteration def process_stream(stream): garbage_count = 0 try: char = stream.next() while(True): ...
from django.contrib.auth import admin from django.urls import path, re_path from . import views urlpatterns = [ re_path(r'^$', views.index, name='index'), path('impact', views.impact, name='impact'), path('state', views.state, name='state'), path('about-fb', views.about_facebook, name='about-fb'), ...
from django.shortcuts import render, get_object_or_404 from django.views.generic import DetailView from django.http import HttpResponse from .models import Photo # Create your views here. def detail(request, pk): photo = get_object_or_404(Photo, pk=pk) messages = ( '<p>{pk}번 사진 보여줄게요</p>'.format(pk...
import pandas as pd import numpy as np import matplotlib.pyplot as plt datos = pd.read_csv('USArrests.csv') columnas = ['Murder', 'Assault', 'UrbanPop','Rape'] datos2 = datos[columnas] datos2 = (datos2 - datos2.mean())/datos2.std() cov_matrix = np.cov(datos2.T) values, vectors = np.linalg.eig(cov_matrix) vector_A =...
from nixnet_custom import nixnet from Enet_params import nxEptRxFilter_Element_t from ctypes import * import time Eth_port = 'ENET3' VID = 2 priority = 3 enet_session = nixnet('ENET') enet_session.create_frame_input_session(Eth_port) enet_session.set_rx_filter(VID, priority) ...
""" Markdown validation report builder Produces a human friendly markdown based validation report Extends kf_lib_data_ingest.validation.reporting.base.AbstractReportBuilder """ import os import re from collections import defaultdict import pandas from kf_lib_data_ingest.validation.reporting.base import ( FAILED, ...
# -*- coding: utf-8 -*- """Tests for pybaselines.smooth. @author: Donald Erb Created on March 20, 2021 """ from numpy.testing import assert_allclose import pytest from pybaselines import smooth from pybaselines.utils import ParameterWarning from .conftest import BaseTester class SmoothTester(BaseTester): """...
import pyspark from pyspark.mllib.linalg import * import numpy as np from pandas import Series,DataFrame import random from pyspark import SparkConf,SparkContext from pyspark.sql import SQLContext def get_dist_single(ele, centroid): #conpute point-wise distance with index # cls = clusters M = b_met.val...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("file:///C:/User...
# -*- coding:utf-8 -*- """ # @Time :2020/8/2 15:00 #@Author :Wesley #@File :图像阈值.py #@IDE :PyCharm #@Email :984@qq.com """ import cv2 import matplotlib.pyplot as plt img = cv2.imread('cat.jpg', 0) ret, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret, dst2 = cv2.threshold(img, 127, 255, cv2.THRESH_B...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from sklearn import datasets features = datasets.load_iris().data # 导入iris特征 labels = datasets.load_iris().target # 导入iris标签 # 随机打乱数据 np.random.seed(110) np.random.shuffle(features) np.random.seed(110) np.random.shuffle(labels) tf.random.set...
""" https://www.careercup.com/question?id=6321181669982208 Given a number N, write a program that returns all possible combinations of numbers that add up to N, as lists. (Exclude the N+0=N) For example, if N=4 return {{1,1,1,1},{1,1,2},{2,2},{1,3}} This can also be done using the dp approach let n = 4 1 11 111, ...
from nltk import PorterStemmer, LancasterStemmer import nltk tokens = nltk.corpus.brown.words(categories=['romance']) # off the shelf stemmers # The Porter Stemmer is a good choice if you are indexing some texts and want to support search using alternative forms # of words porter = PorterStemmer() # stem() functio...
# 復習課題 7-5 # 新しいスタイルの書式指定を使って定型書簡を作りたい。次の文字列をletterという変数に保存しよう(次の問題で使う)。 "Dear {salutation} {name},\ \ Thank you for your letter. We are sorry that our {product} {verbed} in your\ {room}. Please note that it should never be used in a {room}, especially\ near any {animals}.\ \ Send us your receipt and {amount} for ship...
import pandas as pd # read text file and use '|' as separator auto = pd.read_table('../data/auto_mpg.txt', sep='|') print(auto.shape) print(auto.columns) print(auto.info()) print(auto.describe()) print(auto.min(numeric_only=True)) print(auto.max(numeric_only=True)) # range print(auto.max(numeric_only=True) - auto.m...
from .callback import CallbackHook from .custom_summary_saver import CustomSummarySaverHook from .tqdm import TqdmWrapper, TqdmHook from .eval_callback import EvalCallbackHook
from kubernetes import client, config from kubernetes.client.rest import ApiException import json import re import os type_map = {'kubernetes.client.models.v1_replication_controller.V1ReplicationController': 'ReplicationController', 'kubernetes.client.models.v1_limit_range.V1LimitRange': 'LimitRange', 'kubernetes.clie...
import os from base64 import b64decode, b64encode from io import BytesIO, StringIO from pathlib import Path import pytest from panel.pane import ( GIF, ICO, JPG, PDF, PNG, SVG, ) from panel.pane.markup import escape JPG_FILE = 'https://assets.holoviz.org/panel/samples/jpg_sample.jpg' JPEG_FILE = 'https://assets...
import os, re, sys import glob from jinja2 import Environment, FileSystemLoader, select_autoescape """ Apply Default Values to Captain Hook Jinja Templates This script applies default values to templates in this folder. The templates are used by Ansible, but this script uses the same template engine as Ansible to...
# -*- coding: utf-8 -*- """ Created on Mon May 14 14:15:52 2012 Plot mit TeX-Formatierung der Labels (LaTeX muss auf dem Rechner installiert sein) """ import numpy as np from matplotlib import rc import matplotlib.pyplot as plt rc('text', usetex=True) plt.figure(1) ax = plt.axes([0.1, 0.1, 0.8, 0.7]) ...
import json import random import re import time from datetime import datetime from threading import Timer from selenium import webdriver from selenium.common import exceptions from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui...
import random import numpy import matplotlib.pyplot as plt import math """Function to calculate the area under a function with the Monte Carlo mathod and plot the graph Script takes a lot of time if the plot is made. To speed up the script increase the Xstept function Casper Van der Vliet 11052953 """ global Xstep...
# -*- coding: utf-8 -*- """ Created on Thu Sep 3 16:34:12 2020 Data class for back testing purpose @author: yello """ from get_data import GetData, Get_SP500 import pandas as pd class Data: def __init__(self, universe, price_to_use='Adj Close'): # get data self.data_raw = GetData(names=univers...
from sklearn.externals import joblib import requests import json import pyrebase import numpy as np import xlwt # Path of image (jpg/jpeg/png) file = r'C:\Users\MARK\Desktop\AI HACKATHON\datasets\occupied.jpg' # url name url = "https://lpr.recoqnitics.com/detect" accessKey = "c4ba17f0e24772ba71d2" secretKey = "3b3c3...
basket = {'apple', 'orage', 'apple', 'pear', 'orange', 'banana'} print(basket) # {'banana', 'pear', 'apple', 'orage', 'orange'} print('orange' in basket) # 高速な存在判定 # True print('crabgrass' in basket) # False # 2つの単語からユニークな文字をとって集合演算 a = set('abracadabra') b = set('alacazam') # aのユニーク文字 print(a) # {'r', 'a', 'c', 'b'...
import re import json import psycopg2 import string import random from urllib.parse import urlparse from datetime import datetime REGEX_EMAIL = "^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" class DB_API(object): def __init__(self, host, database, user, password): self.con = psycopg2.connect( ...
PASSWORD_ERROR_MESSAGE = 'Username or Password incorrect' USERNAME_ERROR_MESSAGE = "Username does not exist"
# -*- coding: utf-8 -*- """ Created on Mon Oct 23 14:59:51 2017 @author: kading """ ## Change the working directory to be main folder. import sys import time import os, shutil sys.path.insert(0, os.path.abspath(os.curdir)) from src_pkg.generate import * # Provide the path to the schema. rootpath = os.path.dirname(set...
#!/usr/bin/python3 """ Creates the DBStorage class """ import models from models.user import Base from os import getenv from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlite3 import dbapi2 as sqlite from math import cos, acos, sin, radians class DBStorage(...
# -*- coding: utf-8 -*- import pytest from etg import Response from etg.exceptions import ( ETGException, BadRequestException, AuthErrorException ) from .utils import load_response class TestClientResponse: @pytest.mark.parametrize( 'exception, fn', ( (AuthErrorException, 'error_incorrec...
import turtle import math n = 50 d = 50 turtle.left(90) for k in range (10): for i in range(n): x = 10/n turtle.forward(d*math.sin(math.pi/n)) turtle.left(360/n) d += x
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
from odoo import models, fields, api # from odoo.exceptions import ValidationError # class hms section class patient_mainscreen_inherit(models.Model): _inherit = 'medical.patient' # _rec_name = 'full_name' patient_id = fields.Many2one('res.partner', domain=[('is_patient', '=', True)], string="Patient fi...
# Generated by Django 2.1 on 2018-08-27 02:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_web', '0003_auto_20180827_0128'), ] operations = [ migrations.RenameField( model_name='blogpost', old_name='pos...
# outer() 외부함수 inner() 내부함수 def outer(): def inner(): print("inner") return inner f = outer() f() # 위 코드가 수행되는 과정을 그림으로 그려보면 다음과 같습니다. 개념이 어려울 때 그림으로 그려보고 이해하는 것이 좋습니다. # 앞서 함수 이름은 함수 객체를 바인딩하는 변수라고 했습니다. 즉, outer는 외부 함수 객체를 바인딩합니다. # 함수 이름에 ( ) 를 붙이면 해당 함수 코드가 실행되었죠? # outer 함수가 실행되면 outer에 정...
import boto3 import typing from botocore.client import Config def get_boto3_client( *, aws_lambda_mode: bool, service_name: str, profile_name: str = 'kreodont', ) -> typing.Optional[boto3.client]: known_services = ['translate', 'dynamodb', 's3'] if service_name not in known_se...
#here we have to convert string1 to string2 in minimum number of operations def calc(s1,s2,m,n): if m==0: return n if n==0: return m if s1[m-1]==s2[n-1]: return calc(s1,s2,m-1,n-1) else: return 1+min(calc(s1,s2,m-1,n),calc(s1,s2,m,n-1),calc(s1,s2,m-1,n-1)) a="amnafkjhjn...
from django.conf.urls import url, include from wallet import views urlpatterns = [ url( r'^deposit/(?P<option_id>\d+)/return/(?P<invoice_id>\d+)/$', views.deposit_return, name='deposit_return', ), url( r'^deposit/(?P<option_id>\d+)/return/(?P<invoice_id>\d+)/cancel/$', ...
import argparse import pickle from tqdm import tqdm import sys sys.path.extend(['../']) from data_gen.preprocess import pre_normalization max_body_true = 1 num_joint = 20 max_frame = 16 import os import pandas as pd import numpy as np from collections import defaultdict, Counter import math def aug(args): all_d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 22 12:43:55 2020 @author: lily """ import matplotlib.pyplot as plt history ={'loss': [0.6135852062225342, 0.4178453644330303, 0.36323275737166405, 0.3319740912725528, 0.3051732963959376, 0.2853314482957125, 0.26925592600057524, 0.2600...
# Generated by Django 3.1.2 on 2021-05-28 13:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('school', '0003_auto_20210528_1423'), ] operations = [ migrations.AlterModelOptions( name='student', options={'ordering': ['g...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('grumblr', '0004_auto_20151007_1845'), ] operations = [ migrations.RemoveField( model_name='user_photo', ...
found = False print('searching...') for value in [5,3,8,3,8,6,9,5,7,4,1]: if value == 6: found = True yeah = value print(found, yeah) else: found = False print(found, value) print('yeah we found it and its',yeah)
# Copyright 2023 Touca, Inc. Subject to Apache-2.0 License. import logging import sys from argparse import SUPPRESS, ArgumentParser from typing import List from rich.logging import RichHandler from touca import __version__ from touca.cli.check import CheckCommand from touca.cli.common import CliCommand from touca.cli...
from argparse import ArgumentParser import random import json random.seed(27) def create_pairwise_sampled_dict(n_scenes, imgs_per_scene): intra_pairs_sampled = {} intra_pairs_sampled_inv = {0: []} for scene in range(n_scenes): for img1 in range(imgs_per_scene - 1): for img2 in range(i...
class Solution(object): def numberOfPatterns(self, m, n): """ :type m: int :type n: int :rtype: int """ block_relations = { 2: [(1,3)], 4: [(1,7)], 5: [(1,9),(2,8),(3,7),(4,6)], 6: [(3,9)], 8: [(7,9)], ...
""" Creates on output of the Sellar problem using XDSMjs. """ import numpy as np import openmdao.api as om from openmdao.test_suite.components.sellar import SellarNoDerivatives from omxdsm import write_xdsm if __name__ == '__main__': prob = om.Problem() prob.model = model = SellarNoDerivatives() model.add...
import numpy as np def calculate(list): try: lst = np.reshape(np.array(list), (3, 3)) except: raise ValueError('List must contain nine numbers.') calculations = {} calculations['mean'] = [lst.mean(axis = 0).tolist(), lst.mean(axis = 1).tolist(), lst.mean()] calculations['variance'] = [lst.var(ax...
from sympy import * from se3 import * from matrix_utils import * class Manipulator: def __init__(self,joints_list): self.joints = joints_list def forward_kinematics(self): n = len(self.joints) j1 = self.joints[0] t = j1.transform() for i in range(1,n): nj = ...
import json from marshmallow import Schema, fields from typing import List mapping = { 'string': fields.String, 'integer': fields.Integer, 'boolean': fields.Boolean, 'number': fields.Float, 'null': fields.Field, # todo: see if there is a better solution for this } class UnionField(fields.Field)...
from itertools import product def solution(numbers, target): answer = 0 for pro in product([1,-1],repeat=len(numbers)): if sum([pro[i]*numbers[i] for i in range(len(numbers))])==target: answer+=1 return answer
import random num = 0 secret = random.randint(1,10) while num != secret: num = int(input('enter number: ')) if num > secret: print('number too high') elif num < secret: print('num is too low') else: print(f'correct number was {num}')
""" A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID. Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordinat...
''' Author: Justin Soderstrom Date: 5/22/2016 Description: My solution to Practice Python Character Input problem. Includes extras. http://www.practicepython.org/exercise/2014/01/29/01-character-input.html ''' from datetime import date def solution(name, age, copys): year = dat...
from django.conf.urls import patterns, url from django.contrib import admin admin.autodiscover() import views urlpatterns = patterns('', # Examples: # url(r'^$', 'ADALibras.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^anexar/$', views.anexar, name='anexar'), url(r'^(?P...
#!/usr/bin/env python # -*- coding: utf8 -*- """ Usage: translit_location.py INCOLUMN [--lang LANG] [--reverse] [--minlen MINLEN] INFILE... Options: INCOLUMN The number of the INCOLUMN to use, 1 based (A=1). OUTCOLUMN The number of the OUTCOLUMN to put the result in (WILL OVERWRITE ALL VALUES), 1 ...
from .structure import Structure from .interpolate import interpolate from .randomu import randomu from .file_search import file_search from .idlSpawn import IDLJob, IDLAsyncQueue from .time.make_time import make_time from .time.julday import julday, julday_no_leap from .time.jtime import JTime
import os # logging settings MAX_LENGTH = 5 * 1024 * 1024 # 50 MB MAX_FILES = 10 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s', 'datefmt': "%d/%b/%Y %H:%M...
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # Time - O(numCourses + len(prerequisites)) # Space - O(numCourses + len(prerequisites)) if numCourses == 1: return True adj_list = {} # To build a graph data structure from the...
# coding:utf-8 ''' A simple colorful logging module for console or terminal output. Similar, but not fully compatible with official 'logging.__init__' module. ''' import sys, os, time, traceback from encodings import search_function as searchCodecInfo from codecs import CodecInfo from .common.decorator import make_loc...
#!/usr/bin/env python # coding: utf-8 from __future__ import division #Ezelőttieket ne változtassuk a=7 print a print 7/3 # Íme, most nem egész az eredmény (3. sor eredménye) a=2 while a < 30: a = 2*a print a ##################### # Vezérlőszerkezetek ##################### # if a<4: # <valami> # elif a<...
import sys import unittest def run(*classes): suite = unittest.TestSuite() for cls in classes: suite.addTest(unittest.makeSuite(cls)) if '-v' in sys.argv: verbosity = 1 elif '-vv' in sys.argv: verbosity = 2 else: verbosity = 0 runner = unittest.TextTestRunner(s...
__author__ = 'dgraziotin' """ This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING...
studentencijfers = [ [95, 92, 86],[66, 75, 54],[89, 72, 100],[34, 0, 0] ] def gemiddelde_per_student(studentencijfers): gemiddeldps= [] for s in studentencijfers: gemiddeldps.append(sum(s)/len(s)) return gemiddeldps def gemiddelde_van_alle_studenten(studentencijfers): gemiddeld = 0 ...
import csv import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.feature_extraction import DictVectorizer from sklearn.cross_validation import train_test_split from sklearn import cross_validation from sklearn.model_selection import cross_val_predict from sklearn import tree from sklear...
#Load Data InputFileName = "a1" OutputFileName = InputFileName + "_out" suffix = ".txt" Fin = open(InputFileName+suffix,"rb") Fout = open(OutputFileName+suffix,"wb") points = [] for line in Fin.readlines(): data = line.split() if len(data)==2: a = int(data[0]) b = int(data[1]) points.a...
import time import threading from socketConnect import * from lora_gw import lora_gw from libloragw_enums import * solenoid_flag = False flagIsSet = False class Main(threading.Thread): gwID = '0x99' Freq = [867300000, 867500000, 867700000, 867900000, 868100000, 868300000, 868500000, 868700000, 868900000] ...
import random import pandas as pd import numpy as np class TemporalWindowsCreation: def __init__(self, _window_size, _prediction_period, _overlap_size, _input_path, _output_path, StudyDesign, positiveNegativeRatio, casePositive, caseNegative = 0, controlNegative = 0): self.window_size = int(_window_siz...
from .utils import (_stringToList, _variable_safe_name, _safe_filename, deprecate_async) from .templates import * from .component import VeneerComponentModelActions import os import pandas as pd import json NODE_TYPES = { 'inflow': 'RiverSystem.Nodes.Inflow.InjectedFlow', 'gauge': 'RiverS...
################################################################################ # Logging logic, must come first SAFE_MODE = False from tools.logger import configure_logging configure_logging(SAFE_MODE) ################################################################################ from typing import Dict import n...
import random from Board import Board class TwoPlayers: @staticmethod def game(pl_map): board, winner, counter = Board(), 0, 0 board.reset_board() marks_map = {1: "X", 2: "O"} turn = random.randint(1, 2) while not winner: board.choose_place(pl_map[marks_map...
import numpy as np from scipy.cluster import vq import matplotlib.pyplot as plt # Creating data c1 = np.random.randn(100, 2) + 5 c2 = np.random.randn(30, 2) - 5 c3 = np.random.randn(50, 2) # Pooling all the data into one 150 x 2 array data = np.vstack([c1, c2, c3]) # Calculating the cluster centriods and...
import argparse def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeEror('Boolean value expected') parser = argparse.ArgumentParser() # Hyper-parameters for pr...
# from experiments_common import * # from pykdtree.kdtree import KDTree as pyKDTree from segtools import scores_dense import numpy as np from numpy import r_,s_ import torch import torch.nn.functional as F import denoise_utils from enum import Enum,IntEnum from types import SimpleNamespace import augmend from augmend...
#!/usr/bin/env python """Publish one or more label files to the database.""" import os import sys # Hack: append common/ to sys.path sys.path.append("../common") from db import get_database_connection CREATE_SQL = """ DROP TABLE IF EXISTS revised_labels; CREATE TABLE revised_labels(id INT, label VARCHAR(1), PRIM...