text
stringlengths
38
1.54M
''' Created on Oct 11, 2014 @author: Jake Adapted from Eli Benersky's blog on generating sentences from a CFG http://eli.thegreenplace.net/2010/01/28/generating-random-sentences-from-a-context-free-grammar/ ''' # -*- coding: utf-8 -*- from collections import defaultdict import random, copy class CFG: ''' A CF...
import gin import logging import absl import tensorflow as tf from tensorflow.python.util.deprecation import _PRINT_DEPRECATION_WARNINGS import pathlib import shutil from tune import hyperparameter_tuning from train import Trainer from input_pipeline.dataset_loader import DatasetLoader from utils import utils_params,...
''' 1、确保一个类只有一个对象 2、提供一个访问该实例的全局访问点 ''' class MySingleton: __obj = None __init_flag = True def __new__(cls, *args, **kwargs): if cls.__obj == None: cls.__obj = object.__new__(cls) return cls.__obj def __init__(self, name): if MySingleton.__init_flag ==...
# change hosts_temp to hosts_temp in line 29 and 37 to start blocking import time from datetime import datetime as dt hosts_temp = "hosts" # For testing hosts_path = r"C:\Windows\System32\drivers\etc\hosts" redirect = "127.0.0.1" website_list = ["www.facebook.com", "facebook.com", "www.youtube.com", "youtube.com"] ...
from flask import Flask from flask_restful import Api, Resource, reqparse from globalterrorism import GTData #import parser #from csvtojson import convertCSVtoJSON #convertCSVtoJSON() app = Flask(__name__) api = Api(app) api.add_resource(GTData, "/gt/<string:eventid>") app.run(debug=True)
# -*- coding: utf-8 -*- """ Created on Fri May 29 10:08:11 2020 @author: pravesh """ import cv2 import numpy as np import os from os import listdir from os.path import isfile,join import random cap = cv2.VideoCapture(0) ret,frame1 = cap.read() ret,frame2 = cap.read() while cap.isOpened(): d...
# -*- coding: utf-8 -*- import datetime import os import sys import dash from dash import dcc from dash import dash_table as dt from dash import html import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go from awscostparser import AWSCostParser if not os.environ.get("AWS_PR...
# -*- coding: utf-8 -*- """ Created on Sun Jun 21 11:57:09 2020 @author: Dogancan Torun """ #Subject:Set Operations-Methods and Frozenset #Set definition s={10,20,30,'ali',(1,2,3)} s2=set([20,60,30,'mehmet',(9,0,8)]) #another definition set #print(s[0]) not get any member of set print(20 in s) #member control ...
""" DeepLabCut2.0 Toolbox (deeplabcut.org) © A. & M. Mathis Labs https://github.com/AlexEMG/DeepLabCut Please see AUTHORS for contributors. https://github.com/AlexEMG/DeepLabCut/blob/master/AUTHORS Licensed under GNU Lesser General Public License v3.0 """ from __future__ import print_function import wx import cv2 imp...
from docx import Document import tempfile class SummaryWriter: def __init__(self, summaries): self.summaries = summaries def write_docx(self, destination_path): """ Writes summaries to given file in docx format. :return: """ document = Document() for fi...
import glob import itertools import os import sys import cv2 from socialresearchcv.processing.CONFIG import CONFIG import json import pyrealsense2 as rs from socialresearchcv.processing.CSVWriter import CSVWriter from socialresearchcv.processing.ImageSet import ImageSet from socialresearchcv.processing.Keypoint impor...
import pandas as pd import plotly.figure_factory as ff import csv import random import plotly.graph_objects as go import statistics df = pd.read_csv('studentMarks.csv') data = df['Math_score'].tolist() mean_population = statistics.mean(data) std_deviation_population = statistics.stdev(data) # fig = ff.create_distpl...
import FWCore.ParameterSet.Config as cms from FastSimulation.Event.ParticleFilter_cfi import ParticleFilterBlock from FastSimulation.SimplifiedGeometryPropagator.TrackerMaterial_cfi import TrackerMaterialBlock fastSimProducer = cms.EDProducer( "FastSimProducer", src = cms.InputTag("generatorSmeared"), pa...
#_*_ coding:utf-8_*_ ''' 1. using RNN to train poems 2. support checkpoint support 3. support specify the first word of poem when doing inference 4. need begin and stop token for each sentences, why? 5. try using <UNK> token? 6. only need to unpack the lastone by using split(':') 7. reshape((,-1)) 's method ''' import...
""" <Program Name> storage.py <Author> Joshua Lock <jlock@vmware.com> <Started> April 9, 2020 <Copyright> See LICENSE for licensing information. <Purpose> Provides an interface for filesystem interactions, StorageBackendInterface. """ import errno import logging import os import shutil import stat from a...
from unittest import TestCase,main from vector3d import Vector3D from .rect import Rect class TestRect(TestCase): def test1(self): rect=Rect(Vector3D(0,0),1,1) self.assertTrue(Vector3D(0,0) in rect) self.assertTrue(Vector3D(1, 1) in rect) self.assertFalse(Vector3D(0, 1.1) in re...
from argparse import ArgumentParser import tensorflow as tf import tensorflow.keras as keras import matplotlib.pyplot as plt import numpy as np from functools import partial import os from os import makedirs import time from IPython import display from model import Encoder, Generator, Critic from loss import W_loss fr...
# Copyright 2018 Regents of the University of Colorado. All Rights Reserved. # Released under the MIT license. # This software was developed at the University of Colorado's Laboratory for Atmospheric and Space Physics. # Verify current version before use at: https://github.com/MAVENSDC/Pytplot import pytplot import co...
# File: sshcustodian/sshcustodian.py # -*- coding: utf-8 -*- # Python 2/3 Compatibility from __future__ import (unicode_literals, division, absolute_import, print_function) from six.moves import filterfalse """ This module creates a subclass of the main Custodian class in the Custodian project ...
from django.contrib.auth.models import User from django.db import models class Category(models.Model): category = models.TextField() created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True)
#!/bin/python3 import os import sys # # Complete the diagonalDifference function below. # def diagonalDifference(a): i=0 n=len(a) d1,d2=0,0 diff=0 for j in range(n): d1+=a[j][j] d2+=a[i+j][n-1-j] diff=abs(d2-d1) return diff if __name__ == '__main__': f = open(os.en...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 8 09:27:37 2019 @author: arthurmendes """ from sklearn.ensemble import RandomForestClassifier import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import classification_rep...
#!/usr/bin/env python3 from env import env from run_common import AWSCli aws_cli = AWSCli() def describe_default_lambda(func_info): for el in env['lambda']: if func_info['FunctionName'] == el['NAME'] and el['TYPE'] == 'cron': return True return False def describe_cron_lambda(func_info)...
# Generated by Django 2.2.10 on 2020-03-05 15:30 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("contenttypes", "0002_remove_content_type_name"), ("gdpr_helpers", "0001_initial"), ] operations = [ ...
from . import work_learn_problem as wlp _actions = wlp.actions_all( n_skills=1, n_question_types=1, tell=False, exp=False, ) _observations = wlp.observations( n_question_types=1, ) WORK = _actions.index(wlp.Action('ask')) TEST = _actions.index(wlp.Action('ask', 0)) BOOT = _actions.index(wlp.Action...
#!/usr/bin/python import socket import os #Enter the path to the server root directory path = "srv/" #Enter the path to the log file log = "log/" #Enter the IP address to listen on listen = "127.0.0.1" restrict_ip = True approved_ip = ["127.0.0.5"] print ''' --------------------------------------------------------...
inp = input("Enter the numbers to be added separated by spaces : ") operands = inp.split(' ') sum = 0.0 for i in operands: sum += int(i) print (i + ' + ', end='') print (' = %.3f' %sum)
# import sys # sys.path.append('..') # from util.mlflow_util import load_uri, get_prev_run from .mlflow_util import load_uri, get_prev_run import numpy as np import scipy.sparse as sps import scipy.linalg as sla import os import mlflow from sklearn.neighbors import NearestNeighbors METRICS = ['euclidean', 'cosine'] c...
from ..heaps import * # 10.1 Merge sorted array # pytest -s EPI\tests\test_heaps.py::test_merge_sorted_array def test_merge_sorted_array(): res = merge_sorted_array([[2, 20, 200], [3, 30, 300], [4, 40, 400]]) assert res[0] == 2 assert res[-1:] == [400] # 10.2 Sort K ascending and descending # pytest -s ...
from django.urls import path from main import views urlpatterns = [ path('', views.StoryListView.as_view(), name='story_list'), path('create/', views.StoryCreateView.as_view(), name='story_create'), path('<slug:slug>/', views.StoryDetailView.as_view(), name='story_detail'), # URLs for endpoints p...
""" compare coeffs change name1, name2 to compare coeffs between different tasks """ #%% from numpy import * import torch import matplotlib.pyplot as plt import conf name1 = 'burgers-2-upwind-sparse0-noise0.001-block6' name2 = 'burgers-2-upwind-sparse0.005-noise0.001-block6' D = [] D.append(torch.load('coeffs/burgers/'...
# -*- coding: utf-8 -* ''' 判断输入年份是不是闰年 ''' year = int(input('年份 = ')) is_leapYear = (year % 4 == 0 and year % 100 != 0 or year % 400 == 0) print(is_leapYear)
#!/usr/bin/python #-*- coding:utf-8 -*- # 1.09 Finding Commonalities in Two Dictionaries a = { 'x' : 1, 'y' : 2, 'z' : 3 } b = { 'w' : 10, 'x' : 11, 'y' : 2 } # Find key in common print(a.keys() & b.keys()) # Find keys in a that are not in b print(a.keys() - b.keys()) # Find (key,value) pairs in common print(type...
import os,sys import numpy import glob indir='outputs_fiml' infiles=glob.glob(os.path.join(indir,'*')) infiles.sort() outfile=indir+'.txt' assert not os.path.exists(outfile) f=open(outfile,'w') for i in infiles: l=[x.strip() for x in open(i).readlines()] f.write('%s\n'%'\t'.join(l)) f.close()
class Solution: def isValid(self, s: str) -> bool: valids = { "(" : ")", "{" : "}", "[" : "]" } stack = Stack() for ch in s: if ch in valids: stack.push(valids[ch]) else: if stack.isEmpty(): ...
import sys rid=sys.argv[1] title=sys.argv[2] body=sys.argv[3] # Send to single device. from pyfcm import FCMNotification push_service = FCMNotification(api_key="AIzaSyA3hfQjZ3xn2a_4KKA3rKaPCaP_71B7CCQ") # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmess...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' def tax(bill): bill *= 1.08 print "With tax: %f" % bill return bill def tip(bill): bill *= 1.15 print "With tip: %f" % bill return bill meal_cost = 100 meal_with_tax = tax(meal_cost) meal_with_tip = tip(meal_with_tax) ''' def one(n): ...
import pytest import sys, time from .timer import PerpetualTimer def test_timer(): def timer_func(results): results.append(0) nums = [] t = PerpetualTimer(0.01, timer_func, args=(nums,)) assert not t._should_continue assert t.thread is None t.cancel() assert not t._should_continu...
import re DOMAIN_PATTERN = re.compile( r'^(?:[a-z\d\-_]{1,62}\.){0,125}' r'(?:[a-z\d](?:\-(?=\-*[a-z\d])|[a-z]|\d){0,62}\.)' r'[a-z\d]{1,63}$' ) # The srcset width tolerance dictates the _maximum tolerated size_ # difference between an image's downloaded size and its render...
# 简单递归 def countNodes(root): if not root: return 0 return self.countNodes(root.left) + self.countNodes(root.right) + 1 # 利用完全二叉树的性质 class Solution { public int countNodes(TreeNode root) { /** 完全二叉树的高度可以直接通过不断地访问左子树就可以获取 判断左右子树的高度: 如果相等说明左子树是满二叉树, 然后进一步判断右子树的节点数(最后一层...
#!/usr/bin/env python3 # # Maxwell coil plot example # import math import loopfield as lf import loopfield.plot as lfp # field object field = lf.Field(length_units = lf.cm, current_units = lf.A, field_units = lf.uT) # Maxwell coil model with single current loops R = 10 # center ...
##---to import line_table as pandas dataframe, apply detection criteria, and pump out latex tables----## ##----by Ayan-------## import numpy as np import pandas as pd pd.set_option('display.max_rows', 50) pd.set_option('display.max_columns', 50) pd.set_option('display.width', 1000) import argparse as ap import os HOME...
def shuffle(nums, n): l1 = nums[:n] l2 = nums[n:] print(l1) print(l2) print(shuffle([1, 2, 3, 4], 2))
import unittest class MyDict(object): pass class TestMydDict(unittest.TestCase): def test_init(self): print("测试前准备") def tearDown(self): print("测试后准备") def test_init(self): md = MyDict(one = 1, two = 2) self.assertEqual(md['one'],1) self.assertEqual(md['two'],2) def test_nothing(self): pass ...
import pandas as pd import numpy as np from pandas import Series, DataFrame #d = {'one': Series([1., 2., 3.], index=['a', 'b', 'c']), 'two': Series([1., 2., 3., 4.], index=['a','b', 'c', 'd'])} #df = DataFrame(d, index=['r', 'd', 'a'], columns=['two', 'three']) #df = DataFrame(d) #print df.index #print df.columns #prin...
# -*- coding: utf-8 -*- """ Simrel is a package for simulating linear model data .. moduleauthor:: Raju Rimal <raju.rimal@nmbu.no> """ # Import built-in modules first, followed by third-party modules, # followed by any changes to the path and your own modules. from .version import __version__ from .utilities imp...
#!/usr/bin/env python3 filename = 'example.txt' filename = 'input.txt' tiles = open(filename).read().splitlines() width = len(tiles[0]) height = len(tiles) def count_trees(dx, dy): x = 0 y = 0 count = 0 while y < height - 1: x += dx y += dy tx = x % width ty = y ...
#Import objects import os import csv #Set the path for the csv file file_path = os.path.join('..', 'Resources', 'election_data.csv') #Initiate dicitionary votes=[] candidates=[] #Initiate variables winning_votes = 0 winner = '' #Created function to calculate the total votes for a given candidate and to return that ...
# O(a) -> O(n) def example_1(a_list): for a in a_list: print(a) # O(a * a) -> O(a^2) -> O(n^2) def example_2(a_list): for x in a_list: for y in a_list: print(x, y) # O(a + a) -> O(2a) -> O(a) -> O(n) def example_3(a_list): # O(a) for x in a_list: print(x) # O(a) for y in a_list: print(y) # O(a) +...
import time import sys import ibmiotf.application import ibmiotf.device import random import requests organization = "00dxkm" deviceType = "raspberrypi" deviceId = "123456" authMethod = "token" authToken = "12345678" def myCommandCallback(cmd): print("Command received: %s" % cmd.data) try: devi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ `run_tests` module is responsible for running all tests """ # /////////////////////////////////////////////////////////// # ----------------------------------------------------------- # File: run_tests.py # Author: Andreas Ntalakas <antalakas> # --------------------...
import FWCore.ParameterSet.Config as cms hemispheres = cms.EDFilter( "HLTRHemisphere", inputTag = cms.InputTag("ak4PFJetsCHS"), minJetPt = cms.double(40), maxEta = cms.double(3.0), maxNJ = cms.int32(9) ) caloHemispheres = cms.EDFilter( "HLTRHemisphere", inputTag = cms.InputTag("ak4CaloJets...
H, W = map(int, input().split()) C = [input().split() for _ in range(H)] print('\n\n') for i in range(H): print(C[i][0], C[i][0], sep="\n")
from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock from kivy.properties import ObjectProperty from random import randint class PageOne(Widget): pass class UpdateLeds(Widget): led = [] interval = None def schedule(self): self.led ...
from django.contrib import admin from .models import Seeker,Education,Experience,Skill,Provider,Company,Job,Resumee,Application,Identity,CustomJobApplication admin.site.register(Seeker) admin.site.register(Education) admin.site.register(Experience) admin.site.register(Provider) admin.site.register(Company) admin.site....
# -*- coding:utf-8 -*- import cv2 as cv import numpy as np import sys if __name__ == '__main__': # 创建矩阵,用于求像素之间的距离 array = np.array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], dty...
from __future__ import unicode_literals from ..login_reg_app.models import User from django.db import models class Food(models.Model): food = models.CharField(max_length=255) quantity = models.DecimalField(default=1, max_digits=4, decimal_places=2) calories = models.DecimalField(default=0, max_digits=7, decimal_pla...
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-12-15 22:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dataentry', '0209_auto_20211215_2211'), ] operations = [ migrations.RunSQL("insert...
l = list(input().split()) c = ['i', 'pa', 'te', 'ni', 'niti', 'a', 'ali', 'nego', 'no', 'ili'] for s in l: if(s not in c or s is l[0]): print(s[0].upper(),end='')
# -*- coding=utf-8 -*- from flask import url_for, render_template, redirect from datetime import datetime from . import main @main.route('/') def index(): return render_template('index.html') @main.route('/index') def index_(): print url_for('index') return redirect(url_for('index'))
#!/usr/bin/env python from setuptools import setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = "" packages = [ 'requests_respectful', ] requires = [ 'requests>=2.0.0', 'redis>=2.10.3', 'PyYaml', ] setup( ...
# Generated by Django 3.2.5 on 2021-08-16 14:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sub_part', '0017_quo_add_database'), ] operations = [ migrations.CreateModel( name='purchase_add_database', fields=[...
# coding=utf-8 """ 字典类转换工具 """ # TODO 从list文件中读取信息然后拼装成map list(map(lambda x: x['item_id'], sku_data)) list(set(item_ids)) # TODO 保存一些常见的枚举类信息 json.dumps(spu_draft_data, cls=bm.ExtendJSONEncoder) # TODO 直接从数据库读取注释信息 拼接成map # TODO 直接从代码中读取map # TODO 什么是迭代器?什么是生成器?
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ****************************************************************************** # # Project: GDAL utils.auxiliary # Purpose: gdal utility functions # Author: Even Rouault <even.rouault at spatialys.com> # Author: Idan Miara <idan@miara.com> # # *****************...
stops = input() data = input() while not data == "Travel": line = data.split(":") command = line[0] if command == "Add Stop": index = int(line[1]) string_to_insert = line[2] if index in range(len(stops)): first_half = stops[:index] second_half = ...
# Generated by Django 3.1.5 on 2021-01-18 14:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shortcode', '0003_auto_20210115_1141'), ] operations = [ migrations.AddConstraint( model_name='shortcode', constrain...
import time import RPi.GPIO as GPIO import random GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.OUT) p = GPIO.PWM(5, 50) # GPIO pin=18 frequency=50Hz p.start(0) try: while 1: for dc in range(0, 101): p.ChangeDutyCycle(int(random.random() * 100)) time.sleep(1) for dc in range(10...
import os import sys BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from pytorch_transformers.modeling_TSbert_v3 import BertForSequenceClassificationTSv3 from pytorch_transformers.tokenization_bert import BertTokenizer from pytorch_transformers.configuration_bert import B...
from BiTree import BiTNode, Arr2Tree, InOrder from Array import RandArr def CopyTree(root: BiTNode): if root is None: return None node = BiTNode() node.data = root.data node.lchild = CopyTree(root.lchild) node.rchild = CopyTree(root.rchild) return node if __name__ == '__main__': ...
import tensorflow as tf import os import cv2 import numpy as np import random import datasets.preprocessing as preprocessing __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def...
# Copyright (c) 2021 Philip May # This software is distributed under the terms of the MIT license # which is available at https://opensource.org/licenses/MIT """Util functionality and tools.""" import logging import warnings from typing import Callable _logger = logging.getLogger(__name__) def func_no_exception_...
# test delay of "for loop" and lazy computation # # import time def generated_list(): i = 0 while True: i += 1 print("i in generateor:", i) yield i if __name__ == "__main__": generated = generated_list() for i in generated: print("i in main", i) time.sleep(1...
# # num = 45 # # print(type(num)) # # name = 'It Education' # # print(type(name)) # # floating = 879.548 # # print(type(floating)) # num1 = 87 # num2 = 45 # var = "Youtube" # print(num1+ float(num2)) # num3 = 548.48 # print(int(num3)) print("What is your name?") a = input() print('Your name is...
import asyncio import functools import threading import numpy as np from numba import cuda from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim def with_asyncio_loop(f): @functools.wraps(f) def runner(*args, **kwds): loop = asyncio.new_event_loop() loop.set_debug(True) ...
import sqlite3 connect = sqlite3.connect('users.db') c = connect.cursor() passw = 'SELECT * FROM users' def Ler_Dados(): for row in c.execute(passw): print row Ler_Dados()
import requests from flask_restful import Resource, request import re from bs4 import BeautifulSoup import json from common import util from urllib.parse import urlencode class BolsaFamilia(Resource): SITE_URL = 'http://www.transparencia.gov.br/api-de-dados/bolsa-familia-disponivel-por-cpf-ou-nis' def get...
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton btn_go = InlineKeyboardButton('Начнем!', callback_data='go') start_menu = InlineKeyboardMarkup().row(btn_go) btn1_v1 = InlineKeyboardButton('[1, 2, 3]', callback_data='1') btn2_v1 = InlineKeyboardButton('[1, 2, 2]', callback_data='1well') btn...
import random import time import urllib2 import re from bs4 import BeautifulSoup import xlwt import xlrd from xlutils.copy import copy import sys reload(sys) sys.setdefaultencoding('utf-8') from fake_useragent import UserAgent ua = UserAgent() headers = {'User-Agent' : ua.random} def get_info_of_one_category(catego...
import os rpath=input("Enter your directory: ") if os.path.isfile(rpath): print(f'the given {rpath} is a file. Please pass directory only') else: listdire=os.listdir(rpath) if len(listdire)>0: ext=input("Required files extention .py/.sh/.bat/.log/.txt: ") allfiles=[] for eachfile in ...
import numpy as np from math import pi from gdshelpers.geometry.chip import Cell from gdshelpers.parts.waveguide import Waveguide from gdshelpers.parts.coupler import GratingCoupler from gdshelpers.parts.resonator import RingResonator from gdshelpers.layout import GridLayout from gdshelpers.parts.marker import C...
from aoc import aoc from functools import reduce lines = aoc.read_lines('data/08.txt') def unique_patterns(line): first = line.split(' | ')[0] return [''.join(sorted(p)) for p in first.split()] def find_mapping(line): patterns = unique_patterns(line) one = next(p for p in patterns if len(p) == 2...
import sys import os from os import path libpath = path.normpath(path.join(path.dirname(path.realpath(__file__)), os.pardir, "src")) sys.path.append(libpath) import elasticsearch as es import pytrec_eval from datasets import Robust2004 import numpy as np import random import torch from torch.utils.data import DataL...
# global.py # 3. 不能先声明局部变量,再用global声明为全局变量,此做法不 # 附合规则 v = 100 def f1(): v = 200 print(v) global v # 警告,且没有创建局部变量 v += 300 print(v) f1() print("v=", v) # ????
import tkinter as Tk from const import (WIDTH, HEIGHT) BACKGROUND_COLOR = 'white' class Frame(Tk.Frame): def __init__(self, master=None): Tk.Frame.__init__(self, master) self.master.title("FPS Simulater") self.master.geometry("+20+20") self.cvs = Tk.Canvas(self, width=WIDTH, heigh...
import unittest from math import sqrt from ..src.objects.bar import Bar from ..src.objects.nodes import Node2D from ..src.objects.materials.material import ElasticMaterial from ..src.objects.sections import CircleBar class TestMaterials(unittest.TestCase): _steel_young_m = 210e9 _steel_pos = 0.3 steel = E...
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """Test Sep client class.""" from __future__ import print_function import datetime from dateutil.tz import tzutc from mock import patch import pytest from fn_aws_iam.lib.aws_iam_clie...
#!/usr/bin/env python def fields_from_list(line, columns=None, default=""): for n in columns or xrange(len(line)): try: yield line[n].rstrip() except IndexError: yield default def split_lines(lines, fields=None, delim=None): for line in lines: yield tuple(fields...
#tcp server #web stranica ima server na kojem je hostana.on ceka,osluskuje konekcije import socket server_socket=socket.socket() host=socket.gethostname() port =9999 server_socket.bind((host,port)) print "Waiting for connection..." server_socket.listen(5) while True: conn,addr=server_socket.accept() print ...
import math from decimal import Decimal def main(x): ac= Decimal(1 /(1+Decimal(math.e)**(Decimal(-x)))) print ac #print 1+math.e**-x #print math.log(1-ac, math.e) demain(ac) def demain(y): a =Decimal(1/y) b = Decimal(a-1) print math.fabs(math.log(b)), "Math" print math.fabs(b.ln()), ...
# 列表 or 数组 squares = [1, 3, 7, 9, 11]; # 1.索引 print(squares[2]); print(squares[-1]); # 2.切片 # (1)简单的使用 print(squares[1:]); print(squares[:-1]); # (2)替换数组元素 squares[1:3] = [45,23,56]; print(squares); # (3)删除数组元素 squares[1:3] = []; print(squares); # (4)清空数组 arr = [1,2,3,4]; arr[:] = []; # or arr = [] print('arr',arr); ...
from rest_framework import serializers from . import models #Serelisation Domain class TempsInternetSerializer(serializers.ModelSerializer): class Meta: #year = serializers.DateField(format='%Y') model = models.TempsInternet fields = ('id','temps_moyens_internet','created_at') def create...
import platform from setuptools import setup, Extension from distutils.core import setup s = platform.platform() if s.startswith('Linux'): setup(name='v4l2_camera', ext_modules=[Extension("v4l2_camera", sources=["v4l2_camera_module.cpp", "v4l2_camera.cpp"], language="c++") ], ...
#!/usr/bin/env python import os from setuptools import setup, find_packages setup( name="iorn", version="1.0", description="IORN: An Effective Remote Sensing Image Scene Classification Framework, based on Oriented Response Networks", author="Jue Wang", author_email="2120170825@bit.edu.cn", # Re...
import gym import lunarlander_theta import torch import numpy as np from train_optimal_agent import QNetwork import pickle def gen_traj(episodes, t_delay=8, theta=None): # load environment env = gym.make('LunarLanderTheta-v0') # load our trained q-network path = "models/dqn_" + theta + ".pth" qn...
import datetime import uuid import sqlalchemy from wintellect_demo.data.modelbase import SqlAlchemyBase class CmsPage(SqlAlchemyBase): __tablename__ = 'CMSPage' url = sqlalchemy.Column(sqlalchemy.String, primary_key=True) created_date = sqlalchemy.Column(sqlalchemy.DateTime, ...
from django.conf import settings import boto3 class Bucket: def __init__(self, *args, **kwargs): session = boto3.session.Session() self.conn = session.client( service_name=settings.AWS_SERVICE_NAME, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_ac...
# -*- coding: utf-8 -*- """ Created on Mon Mar 26 17:03:26 2018 @author: Mohammad SAFEEA Test script of iiwaPy class. """ from sunrisePy import sunrisePy import time ip='172.31.1.148' #ip='localhost' iiwa=sunrisePy(ip) iiwa.setBlueOff() time.sleep(2) iiwa.setBlueOn() # read some data from the robot try: print('E...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models import datetime from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from oscar.apps.customer.abstract_models import AbstractUser # Create your models here. cla...
# -*- coding: utf-8 -*- # Copyright 2015-2016 Rackspace US, Inc. # # 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 appli...
from django.shortcuts import render from django.http import JsonResponse from django.views import View from locacaoeventos.utils.forms import PhotoProvisoryForm from locacaoeventos.utils.main import base_context from locacaoeventos.utils.datetime import test_date from locacaoeventos.apps.place.placecore.models import ...