text
stringlengths
38
1.54M
import os, sys sys.path.append(os.getcwd()) import time import numpy as np import tensorflow as tf import language_helpers import tflib as lib import tflib.ops.linear import tflib.ops.conv1d import tflib.plot from keras.utils import to_categorical import copy import pickle BATCH_SIZE = 64 SEQ_LEN = 33 DIM = 256 ...
import logging import socket import sys import time import threading logging.basicConfig(level=logging.INFO, stream=sys.stdout) logger = logging.getLogger(__name__) class DroneManager(object): def __init__(self, host_ip='192.168.10.2', host_port=8889, drone_ip='192.168.10.1', drone_port=8889): ...
import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure from matplotlib.patches import Rectangle from data_models.object_detection_models import ImageData from settings import MATPLOTLIB_COLORS import cv2 def display_img_data(img_data: ImageData, class_mapping=None): ...
import requests from bs4 import BeautifulSoup def kino(k,i,j): if (j != 'кино'): url = 'http://afisha.ngs.ru/afisha/1/' r = requests.get(url) with open('test.html', 'w') as f: f.write(r.text) j = 'кино' with open('test.html', 'r') as f: soup = BeautifulSou...
import numpy as np import matplotlib.pyplot as plt # • the thermal coupling constant C = 9.96 × 10 6 , # • the emissivity  = 0.62 (corresponding to the fact that a part of the # outgoing radiation is hold back in the atmosphere due to the green- # house effect), # • the Boltzmann constant σ = 5.67 × 10 −8 # • the sola...
""" This ``urls.py`` is only used when running the tests via ``runtests.py``. As you know, every app must be hooked into yout main ``urls.py`` so that you can actually reach the app's views (provided it has any views, of course). """ from django.conf.urls.defaults import include, patterns, url from django.contrib impo...
import random import gym from gym import spaces import numpy as np def tempoIntToStr(tempo): #função para transformar int para horario milesimo = 1000 horas = int(tempo//(3600 * milesimo)) tempo -= horas * (3600 * milesimo) minutos = int(tempo//(60 * milesimo)) tempo -= minutos * (60 * milesimo) ...
p1, s1 = map(int,input().split()) s2, p2 = map(int, input().split()) if p1+p2 > s1+s2: print("Persepolis") elif p1+p2 < s1+s2: print("Esteghlal") elif s1 > p2: print("Esteghlal") elif s1 < p2: print("Persepolis") else: print("Penalty")
"""Process responses for the route functions.""" def okay(obj, filetype, updir="media"): """Return okay python dict.""" d = { "code": 200, "data": [ { "url": "/" + updir + "/" + obj.filename, "message": "OK.", "type": obj.mediaType, ...
from apollo.events.event_handler import EventHandler from kafka import KafkaProducer from apollo.configurations import kafka_bootstrap_server from apollo.monitoring.tracing import print_publish_message import json from datetime import datetime def datetime_handler(x): if isinstance(x, datetime): return x._...
from django.db import models from datetime import datetime, timedelta import re class UserManager(models.Manager): def validator(self, postData): errors = {} if len(postData['first_name'])<2: errors['first_name'] = "First Name must be at least 2 characters." if len(postData['las...
print("Please think of a number between 0 and 100!") low=0 middle=50 high=100 guess=raw_input("Is your number " + str(middle) + "?\nEnter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ") while guess != "c": if guess == "l": ...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import precision_score,f1_score,roc_curve,auc from keras.models import Sequential from keras.layers import Dense, LSTM from keras.layers.embeddings import Embedding...
from ansible.plugins.callback import CallbackBase import os import sys import logging import json import shutil class ResultsCollector(CallbackBase): def __init__(self, *args, **kwargs): super(ResultsCollector, self).__init__(*args, **kwargs) self.host_ok = {} self.host_unreachable = {} ...
""" Lab4: Q1B -Create new security group """ import boto3 from botocore.exceptions import ClientError ec2 = boto3.client('ec2') try: message = ec2.create_security_group(GroupName="TheWizardIsHere",Description="Only level 20 wizards allowed") print("Sucess",message) except ClientError as e: print(e)
from tree import Tree tree = Tree() tree.add_node(1) # root node tree.add_node(2,3) # root node tree.add_node(4,5) # root node tree.add_node(6,7) # root node tree.display(1)
from dcbase.tests.unit import UnitTestCase from django.core.urlresolvers import reverse class TestUserView(UnitTestCase): def setUp(self): super().setUp() self.user = self.createUser() self.url = self._createUrl(self.user.username) self.response = self.client.get(self.url) def...
from flask import Flask from flask import Response, request import json import sys #import file from main path sys.path.insert(0, '/home/pi/Desktop/Flow_sensor') import function import db_connection app = Flask(__name__) @app.route('/') def index(): return 'Flow Sensor API! ' #Get sensor data @app....
from heapq import heappop, heappush w = [ # 顶点间距离, -1表示无穷大 [0, 7, 9, -1, -1, 14], [7, 0, 10, 15, -1, -1], [9, 10, 0, 11, -1, 2], [-1, 15, 11, 0, 6, -1], [-1, -1, -1, 6, 0, 9], [14, -1, 2, -1, 9, 0] ] def dijkstra(start, dest): n = 6 ...
import numpy as np from scipy.interpolate import CubicSpline def DA_Jitter(X, sigma=0.05): myNoise = np.random.normal(loc=0, scale=sigma, size=X.shape) return X+myNoise def DA_Scaling(X, sigma=0.1): scalingFactor = np.random.normal(loc=1.0, scale=sigma, size=(1,X.shape[1])) # shape=(1,3) myNoise = np....
from calcFunctions import * from plot import * from tkinter import * import webbrowser def path(f): #we ask for the shape properties print("Image of a shape: {z=x+iy: x0<x<x1, y=f*(x)}") x0=float(ask('x0=', '0')) x1=float(ask('x1=', '1')) print("Please type in the (real) function for the path of th...
from schematics.types import StringType, IntType, IPv4Type from model import SbbModel class IpAddress(SbbModel): ipaddress = IPv4Type(primary_key=True) status = IntType() #history = Map(Integer, Integer)
#!/usr/bin/env python # -*- coding: utf-8 -*- from controllers.baseengine import RoundGameEngine, readInput from controllers.statsengine import StatsEngine, ParticularStatsEngine from controllers.db import db class Phase10Engine(RoundGameEngine): def __init__(self): super(Phase10Engine, self)._...
#!/usr/bin/env python import sys sys.path.append(".") import numpy import geometry_msgs.msg #from interactive_markers.interactive_marker_server import * #from interactive_markers.menu_handler import * import trajectory_msgs.msg #import moveit_commander import moveit_msgs.srv import rospy import sensor_msgs.msg import ...
""" Classes and functions for adjusting strain data. """ # Copyright (C) 2015 Ben Lackey, Christopher M. Biwer # # 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 3 of the License, ...
"""Implementation of Bayesian Quadrature.""" class BayesianQuadrature: """Bayesian quadrature. Bayesian quadrature methods build a model for the integrand via function evaluations and return a belief over the value of the integral on a given domain with respect to the specified measure. Paramete...
from detectron2.engine import DefaultTrainer from detectron2.evaluation import COCOEvaluator from detectron2 import model_zoo from utils import get_my_cfg from visdrone import register_one_set import os if __name__ == '__main__': train_dataset = "VisDrone2019-DET-train" val_dataset = "VisDrone2019-DET-val" ...
""" This set of functions are various random things needed somewhere in the project. """ import numpy as np from adcsim import transformations as tr def random_dcm(): """ This function generates a random DCM. method: generate a random vector and angle of rotation (PRV attitude coordinates) then calculate...
import qsim.evolution.hamiltonian from qsim.graph_algorithms.graph import line_graph, ring_graph from qsim.tools import tools import numpy as np from scipy import sparse from scipy.sparse.linalg import expm_multiply, eigsh, expm from scipy.special import comb from scipy.special import jv, iv from qsim.codes.quantum_sta...
import csv import json from 臺灣言語工具.解析整理.拆文分析器 import 拆文分析器 from 臺灣言語工具.音標系統.台語 import 新白話字 from 臺灣言語工具.音標系統.閩南語.臺灣閩南語羅馬字拼音 import 臺灣閩南語羅馬字拼音通行韻母表 def _main(): tsuanpooji = set() tsuanpoojitiau = set() for 字物件 in csvtsuliau(): tailo = 新白話字(字物件.型) if ( tailo.音標 is not None and ...
class Config: lr = 1e-4 dropout = 0.2 qs_max_len = 20 qb_max_len = 95 ct_max_len = 150 char_max_len = 16 epochs = 50 batch_size = 30 char_dim = 15 l2_weight = 0 patience = 5 k_fold = 0 categories_num = 2 period = 50 need_punct = False wipe_num = 0 w...
import os.path def load_data(sys_name, file_index): # 텍스트파일로 저장된 filename_list = os.listdir('../data/{0}'.format(sys_name)) if file_index >= len(filename_list): return False elif filename_list[file_index][-3:] != 'txt': return False else: filename = filename_list[file_index...
# Copyright (c) Code Written and Tested by Ahmed Emad in 24/03/2020, 14:36. from rest_framework import permissions from recipes.models import RecipeModel, RecipeImageModel, RecipeReviewModel class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. ""...
#!/usr/bin/env python #-*- coding:utf-8 -*- """ this is a unicode file test """ #this is the code use utf-8 CODEC = 'utf-8' FILE = 'unicode.txt' #this is write the content to the file,then must be encode to the utf-8 hello_out = u'Hello KEL,中文测试\n' bytes_out = hello_out.encode('utf-8') f = open(FILE,'w') f.write(bytes...
# Copyright 2017-2023 Posit Software, PBC # # 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 ...
from random import choice class RandomWalk: """a class to generate random walks""" def __init__(self,num_points = 5000): """init attributes of walk""" self.num_points = num_points #all walks start at (0,0) self.x_values = [0] self.y_values = [0] def f...
from scipy import signal import matplotlib.pyplot as plt r_l = 66 r_h = 1600 c_l, c_h = 1e-6, 1e-6 twof = signal.TransferFunction([1], [0.001, 1]) threec = signal.TransferFunction([r_h * c_h, 0], [r_l * r_h * c_l * c_h, r_l * c_l + r_h * c_h, 1]) w, mag, phase = signal.bode(twof) w2, mag2, phase2 = signal.bode(three...
# Generated by Django 3.0.4 on 2020-06-01 15:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('partage_repas', '0002_profil'), ] operations = [ migrations.AlterModelOptions( name='profil', options={'verbose_name': 'prof...
#!/usr/bin/python3 """ Top ten """ import json import requests def top_ten(subreddit): """ Print the tittles of the first 10 hot posts """ url = 'https://www.reddit.com/r/{}/hot.json?limit=10'.format(subreddit) headers = {'User-Agent': 'My User Agent 1.0'} request = requests.get(url, headers=header...
from http.server import HTTPServer, BaseHTTPRequestHandler from io import BytesIO import socket hostname = socket.gethostname() ip = socket.gethostbyname(hostname) ipBytes = ip.encode() class Handler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) bo...
my_mail = 'vol1@test.test' my_pass = 'vol1' api_key = "5402354a55655803bd34fe6b16344855c6056d34b7746bae11b2e990" #api_key = "" base_url = 'https://petfriends1.herokuapp.com/'
############################################################################## # # Copyright (c) 2000-2009 Jens Vagelpohl and Contributors. All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS S...
# -*- coding: utf-8 -*- import torch import torch.nn as nn from kornia.losses import SSIM from kornia.filters import SpatialGradient from torch.nn import functional as F #def inverse_huber_loss(target, output): # absdiff = torch.abs(output-target) # C = 0.2*torch.max(absdiff).item() # return tor...
import datetime from django.contrib.auth.models import User as admin from django.utils import timezone from django.utils.safestring import mark_safe from djongo import models # Create your models here. class State(models.Model): state_name = models.CharField(max_length=50) def __str__(self): return ...
from modeltranslation.translator import register, TranslationOptions from .models import DayTemplateRule, RuleSet @register(DayTemplateRule) class SimpleRuleTranslation(TranslationOptions): fields = ('name',) @register(RuleSet) class RuleSetTranslation(TranslationOptions): fields = ('name',)
import numpy as np from genetic_algorithm.dna import DNA from scipy.special import softmax class Population: """ Class to generate a population with genes of the type (a, b) """ def __init__(self, max_pop, low, high, fitness_calculator): self.generation = 0 self.best = None se...
import cv2 import numpy as np import json import imutils as iu from imutils.perspective import four_point_transform import time from utils import helper_visuals as iv import utils.plugins.CMT.CMT as CMT from utils import modelio as mio from keras.preprocessing.image import img_to_array # import utils.plugins.CMT.util...
# String converted to binary sequence def str2bin(msg): msg_bin = '' for i in range(0, len(msg)): msg_bin = msg_bin + format(ord(msg[i]),'08b') return msg_bin msg = 'This is a test message' msg_bin = str2bin(msg) print(msg_bin, end = '\n')
def default_special_forms_table(): from anoky.fallback import fallback_import operators = fallback_import("anoky.special_forms.operators") assign = fallback_import("anoky.special_forms.assign") containers = fallback_import("anoky.special_forms.containers") Def = fallback_import("anoky.special_form...
# Resolva o seguinte sistema de equações não-lineares: # 2x - y - e**x = 0 # -x + 2y - e**y = 0
# Python imports. # Other imports. from agents.safe_agent import SafeAgent from constants import * from dynamic_programming import value_iteration class SafeEGreedyAgent(SafeAgent): def __init__(self, actions, states, reward_func, initial_safe_states, initial_safe_actions, similarity_functi...
# -*- coding: utf-8 -*- """ Created on Fri Dec 7 08:20:54 2018 @author: Dorota """ data = open("data.txt").read().split("\n") for i, d in enumerate(data): data[i] = d.split("must be finished before step") data[i][0] = data[i][0].replace(" ","") data[i][0] = data[i][0].replace("Step","") data[i][1] =...
import cv2 import numpy as np MIN_MATCH_COUNT = 10 img1 = cv2.imread('ojota1.jpg') cv2.imshow('img1', img1) gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) img2 = cv2.imread('ojota2.jpg') cv2.imshow('img2', img2) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # Inicializamos el detector y el descriptor sift = cv2.xfe...
# -*- coding: utf-8 -*- """ Created on Sat May 5 23:17:17 2018 @author: 王磊 """ # coding:utf-8 import numpy as np import matplotlib.pyplot as plt def drawHeart(): plt.figure(figsize=(12, 6)) arrayOne = np.linspace(-np.pi/2, np.pi/2, 1000) x = np.cos(arrayOne) y = np.sin(arrayOne)...
# -*- coding: UTF-8 -*- """ PCI math Lib 大整数请用python内建类型int 大浮点数请用decimal.Decimal或sympy.Float,比如Decimal('3.1415926535')或Float('1e-3', 3) """ import PCILib.PCImathLib.analysis as pcianalysis import PCILib.PCImathLib.discrete as pcidiscrete import PCILib.PCImathLib.stat as pcistat __all__=[] class Cartesian(object...
# Made from a copy from channelRoomGUI: import pygame from pygame.locals import * import time import textBox import textBoxList import button import sys import clientContext import channelRoomGUI import waitingRoomWindow def main(threadName, args): if len(args) > 1: connection = args[1] else: ...
# -*- coding: utf-8 -*- from functools import reduce from . import BoxItem, CylinderItem, EnvelopeItem class Package(object): FORMAT_BOX = 1 FORMAT_CYLINDER = 2 FORMAT_ENVELOPE = 3 MIN_WEIGHT = 0.005 MAX_WEIGHT = 30.0 def __init__(self, format = None): self.format = format or s...
from django.contrib import admin from models import * from django.contrib import databrowse from django.forms import ModelForm from django import forms class ItemAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display = ('__unicode__', 'amount_sold', 'amount_on_stock') filter_horizo...
import torch import network from TorchSUL import Model as M import config import numpy as np import util import cv2 import testutil # import visutil2 # from pycocotools.cocoeval import COCOeval # from pycocotools.coco import COCO def vis_skeleton(img, pts): pts = pts[:,:3] # img = visutil2.deprocess(img) # ...
#!/usr/bin/env python #encoding:utf-8 # -*- coding: utf-8 -*- import logging import os import os.path import sys import subprocess import _subprocess import string import logging import time import shutil import codecs import ConfigParser from RenderBase import RenderBase class MayaPre(RenderBase): def __init__(sel...
import csv from collections import defaultdict, Counter import operator lang_info={"NA": 0, "Assembly": 0, "Bash/Shell/PowerShell": 0, "C": 0, "C++": 0, "C#": 0, "Clojure": 0, "Dart": 0, "Elixir": 0, "Erlang": 0, "F#": 0, "Go": 0, "HTML/CSS": 0, "Java": 0, "JavaScript": 0, "Kotlin": 0, "Objective-C": 0, "PHP": 0, "Pyt...
from ajouterWidget import Ui_AjouterWidget from PyQt5.QtCore import pyqtSlot class Ajouter(Ui_AjouterWidget): def __init__(self, centredWidget, db): super(Ajouter, self).__init__() self.setupUi(centredWidget) self.widget.close() self.labelAttention.close() self.pushButtonSauvgarder.setEnabled(False) self...
import numpy as np import pandas as pd from datetime import datetime from pandas_datareader import DataReader rand_array = np.random.rand(3, 3) df = pd.DataFrame(data=rand_array, columns=['a', 'b', 'c']) print(df) # 取得する期間 end = datetime.now() start = datetime(end.year - 1, end.month, end.day) print(end) AAPL = Data...
"""Localhost client mocked components.""" import logging import re from splitio.storage import ImpressionStorage, EventStorage, TelemetryStorage _LEGACY_COMMENT_LINE_RE = re.compile(r'^#.*$') _LEGACY_DEFINITION_LINE_RE = re.compile(r'^(?<![^#])(?P<feature>[\w_-]+)\s+(?P<treatment>[\w_-]+)$') _LOGGER = logging.getLo...
#!/usr/bin/env python import os import sys import json import numpy as np import matplotlib.pyplot as plt from scipy.spatial import ConvexHull import argparse def spcgrp_props(space_group): cst_marker = '.' cst_color = '#000000' cst_marker_size = 2 cst_zorder = 2 cst_fillstyle = 'full' if spa...
localrules: pureclip def make_pureclip_input(): # this expects directories under input/ that contain bed files # in directories named signal and control fns = get_input_dirs() chdir = list(map(lambda fn: fn.replace('input/','output/pureclip/'), fns)) chsuff = list(map(lambda fn: re.sub(r'$', '_pur...
import pandas as pd df = pd.DataFrame({'name':['A','B','C','D','E','F','G','H','I','J','K','L'], 'type':[0,0,1,1,1,2,2,2,2,2,2,3], 'level':[None, None,1,2,3,None, None, None, None, None, None,None], 'pl':[100,150,200,100,300,50,150,-200,100,100,-150,100], ...
import lxml.etree from .h9msg import H9msg class Common(H9msg): def _dump(self, node, res): if isinstance(res, dict): for n in node: if n.tag == 'value': if n.text is None: res[n.attrib['name']] = '' else: ...
#!/usr/bin/env python # -*- coding: utf-8 # # Example of Usage : # If we want to generate 15 imposters of spanish language , we use the next command # python src/imposters_generator.py --lang sp --seed training/ --output esimposters --imposters 15 # # If we want to generate 150 imposters of spanish language , we us...
# get data import functions as f #import cv2 from sklearn.neighbors import KNeighborsClassifier import numpy as np from sklearn import datasets, svm, metrics data = f.get_array_from_images('images_no_copies') dev, test = f.split_data(data, 0.2) training_data, training_labels = f.reshape(dev) test_data, test_labels = f...
# pip install pymongo 安装 from pymongo import MongoClient from bson.objectid import ObjectId import pymongo # 更新文档 # 连接服务器 conn = MongoClient("localhost", 27017) # 连接数据库 数据库的名字是 myDB db = conn.myDB # 得到数据库下面的集合 colletion = db.student #开始操作数控下面的 表(colletion) # 更新文档 #将 name = 基本密码 的数据 中的 age 变为 88 res = colle...
#How to define or create function def greet(): print("Hello , This is my first python function") print("Welcome to python world") greet()
# -*- coding: utf-8 -*- # Игра «Быки и коровы» # https://goo.gl/Go2mb9 from mastermind_engine import get_number, check_number from termcolor import cprint, colored cprint('Загадано четырехзначное число, попробуй отгадать!', color='green') counter = 0 while True: print('Ход', counter + 1) user_number = input...
import random import math class bbplayer: #stats_array = [[0 for x in range(2)] 0 for x in range(9)] #2manystats stats_pts = 0 stats_fga = 0 stats_fgm = 0 stats_3ga = 0 stats_3gm = 0 stats_ass = 0 stats_reb = 0 stats_stl = 0 stats_blk = 0 stats_ofa = 0 stats_ofm = 0 ...
import random from enum import Enum from minesweeper.core.board import GameBoard from datetime import datetime from minesweeper.core.cell import RevealCellResult class GameState(Enum): NEW = 0 STARTED = 1 PAUSE = 2 WIN = 3 LOST = 4 class MinesweeperGame: def __init__(self, rows, cols, mine...
""" Django settings for Easytest project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # ...
import morepath class App(morepath.App): pass @App.path('/welcome') class Welcome(object): pass @App.view(model=Welcome) def root_default(self, request): return "Hello World!" App.commit() main = App()
from django.conf.urls import url from . import views from django.conf.urls import include urlpatterns = [ url(r'^student/(?P<pk>[0-9]+)$', views.Delete_Update_Student.as_view()), url(r'^student/', views.Student.as_view()), ]
import unittest import requests import json import random class TestServer(unittest.TestCase): # Check that the server gives a list of all candidates. def test_gives_list(self): d = requests.get('http://qainterview.cogniance.com/candidates') code = d.status_code obj = json.loads(d.text...
#Uses python3 import functools import sys def compare(x, y): xy = "".join([x,y]) yx = "".join([y,x]) if xy < yx: return -1 elif xy > yx: return 1 else: return 0 def largest_number(A): A.sort(key=functools.cmp_to_key(compare), reverse=True) return "...
class Settings(): """存储外星人入侵的所有设置的类""" def __init__(self): """初始化游戏的设置""" # 屏幕设置 self.screen_width = 1024 self.screen_height = 768 self.bg_color = (30, 144, 255) self.ship_speed_rate = 1.0 # 游戏中子弹的相关参数需要在此设置 self.bullet_speed_rate = 1 ...
import collections import datetime import urllib import pytz from pylons import c, g from pylons.i18n import _, ungettext from r2.lib import filters from r2.lib.pages import Reddit, UserTableItem from r2.lib.menus import NavMenu, NavButton from r2.lib.template_helpers import add_sr from r2.lib.memoize import memoize...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from random import randint import time import sys data = sys.stdin.readlines() # read stdin time.sleep(5) # Stop for a while to simulate some processing obj = {"items": ["a", "b", "c", data], "boolean": True, "integer": 123456, "random": randint(0, ...
""" list four bytes fields """ four_bytes = { "JobId", "LineNumber", "ReelNumber", "order", "TRACE_SEQUENCE_LINE", "TRACE_SEQUENCE_FILE", "FieldRecord", "TraceNumber", "EnergySourcePoint", "CDP", "CDP_TRACE", "offset", "ReceiverGroupElevation", "SourceSurfaceE...
from bs4 import BeautifulSoup as bs import requests import pandas as pd from splinter import Browser from webdriver_manager.chrome import ChromeDriverManager def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {'executable_path': ChromeDriverManager().inst...
''' Clustering example of iris dataset Commented codes display all possible graphs ''' import pandas as pd import matplotlib.pyplot as plt import numpy from sklearn.cluster import KMeans iris = pd.read_csv('C:/Users/jhunjhun/Downloads/iris.csv') iris = iris.iloc[:,[0,1,2,3]] #x = iris.iloc[:,0] #y = iris.iloc[:,1]...
# Generated by Django 2.1.3 on 2018-12-05 19:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('microlly_blog', '0003_auto_20181202_2355'), ] operations = [ migrations.AlterModelOptions( name='post', options={'ve...
from flask import Flask, render_template, url_for,request,jsonify,g,make_response import datetime from flask_cors import CORS import mysql.connector as db from flask_httpauth import HTTPBasicAuth,MultiAuth,HTTPTokenAuth import base64 from flask_mail import Mail,Message import random import string con=None app = Flask...
from pypif import pif from pypif.obj import * chemical_system = ChemicalSystem() chemical_system.chemical_formula = 'MgO2' band_gap = Property() band_gap.name = 'Band gap' band_gap.scalars = 7.8 band_gap.units = 'eV' chemical_system.properties = band_gap print(pif.dumps(chemical_system, indent=4))
import glob import cv2 import matplotlib.pyplot as plt import pandas as pd import numpy as np import math from tqdm import tqdm import os from pathlib import Path from defisheye import Defisheye fov = 180 pfov = 120 dtype = "equalarea" # #"linear","stereographic","orthographic" format_ = "fullframe...
import os import logging # from flask_migrate import Migrate, MigrateCommand # from flask_script import Manager # from webapp import blueprint from app import create_app, db, migrate from loguru import logger import unittest # http://127.0.0.1:5000/api/v1/documentation PROJECT_ROOT = os.path.dirname(os.path.abspath...
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file ex...
""" 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который результат спортсмена составит не менее b километров. Программа должна принимать значения параметр...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
""" Definition of TreeNode: """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class ReturnType: def __init__(self, cur_sum, min_sum,subtree): self.cur_sum = cur_sum self.min_sum = min_sum self.subtree = subtree class Solution...
from django.contrib import admin from .models import Room, Reservation, ReservedRoom, BigText, Schedule, DeletedReservation admin.site.register(Reservation) admin.site.register(DeletedReservation) admin.site.register(Room) admin.site.register(ReservedRoom) admin.site.register(Schedule) admin.site.register(BigText)
from train_and_eval_utils import CNNDailyMailDataset from pytorch_transformers import XLNetTokenizer best_list = [("1a0cb94420e0e1ce99d2e67607175aa067d2adae", "../data/dev_data0-9/dev_data_5"), ("76f3f120cf62c5fc7a0cd0c95d3245775e41834a", "../data/dev_data0-9/dev_data_6"), ("3bb5c44400b711cb4...
from logging import getLogger from unittest import TestCase import requests logger = getLogger(__name__) BASE_URL = "http://calendar:8123" def get_calendar(calendar, **params): # This will insert the number of the calendar into the url url = BASE_URL + "/calendars/{}/dates/".format(calendar) # This wi...
from ..Base.Patch import Patch class LymphNode(Patch): def __init__(self, patch_id, species, loads, position): Patch.__init__(self, patch_id, species, loads, position) def __str__(self): return "LN {0}".format(self.id)
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html # Extracted items -> temporary containers -> then to the csv import scrapy class Scrapy2Item(scrapy.Item): theindex = scrapy.Field() theurl = scrapy.Field() ...