text
stringlengths
38
1.54M
def binarySearch(array,key): first_element = 0 last_element = len(array)-1 while first_element <= last_element: #base case mid_element = (first_element + last_element)//2 #if element at index [i] if array[mid_element] == key: return mid_element else: #left side of array i...
class Person: def __init__(self, n, a): self.name = n self.age = a def getName(self): return self.name def getAge(self): return self.age class Customer(Person): def __init__(self, nm, ag, tl): super().__init__(nm, ag) self.tel = tl ...
#!/usr/bin/python2.7 needed = [ str( x ) for x in range( 10 ) ] def solve( N, mult=1 ): global needed prev = N temp = N * mult for eachDigit in str( temp ): if eachDigit in needed: needed.remove( eachDigit ) if len( needed ) == 0: needed = [ str( x ) for x in range( 1...
import numpy as np import auto_diff as ad from .util import NumGradCheck class TestOpArange(NumGradCheck): def test_forward(self): x = ad.arange(3) actual = x.forward() expect = np.array([0, 1, 2]) self.assertTrue(np.allclose(expect, actual), (expect, actual)) x = ad.aran...
#! /usr/bin/env python # -*- coding:utf-8 -*- from networking.config_ospf import ospf_port_data from networking.config_rip import rip_port_data from networking.config_bgp import bgp_port_data def execute_data(): item_ospf_port_data, item_ospf_port, item_ospf_ip = ospf_port_data() item_rip_port, item_rip_nam...
import random import copy def read_file(file_name): f = open(file_name, "r") n_jobs, n_machines = [int(valor) for valor in f.readline().split()] operations = [] for i in range(1, n_jobs+1): line = f.readline().split() for j in range(0, n_machines*2, 2): operations.append(...
# -*- coding: utf-8 -*- # @Author: Yeshwanth # @Date: 2021-01-04 18:58:12 # @Last Modified by: Yeshwanth # @Last Modified time: 2021-01-09 12:30:53 # @Title: System Time import time print(time.ctime())
from sklearn.svm import SVC import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt ''' ### sklearn.svm.SVC C = 1.0, kernel = 'rbf', degree = 3, gamma = 'auto', coef0 = 0.0, shrinking = True, probabil...
import time as t class Timer(): # 初始化构造函数 def __init__(self): self.prompt = "未开始计时..." self.lasted = [] self.begin = 0 self.end = 0 # 重写__str__方法 (演示使用,代码可省略) def __str__(self): return self.prompt # 重写__repr__方法 def __repr__(self): return self.p...
from manga_py.fs import dirname, path_join, get_temp_path, rename from manga_py.provider import Provider from .helpers.std import Std class MangaChanMe(Provider, Std): def get_archive_name(self) -> str: idx = self.get_chapter_index().split('-') return 'vol_{:0>3}-{}'.format(*idx) def get_chap...
# -*- coding: utf-8 -*- premium_cost = 150 def ground_cost(weight): flat_charge = 20 if weight <= 2: cost = (1.50 * weight) + flat_charge return cost elif weight <= 6: cost = (3 * weight) + flat_charge return cost elif weight <= 10: cost = (4 * weight) + flat_charge return cost else: ...
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from utils.plotter import VisdomLinePlotter import gym class LinearAct(nn.Linear): def __init__(self, *args, activation=F.relu, **kwargs): super().__init__(*args, **kwargs) t...
''' Created on Feb 4, 2014 @author: Naved ''' import threading class MyThread(threading.Thread): def __init__(self): super(MyThread, self).__init__() def run(self): print "tada" threading.Lock.acquire() print "done" threading.Lock.release() threadli...
""" 通过spark的api, 或者直接调用MysqlDB的api从业务数据源中获取数据 """ from typing import Tuple, List, Union import datetime from pyspark import Row, RDD from pyspark.sql import SparkSession, DataFrame from process.spark.context import RetailerContext class MysqlDataLoader(object): def __init__(self, retailer_context): # ty...
from django import forms from .models import Pet, Owner class PetForm(forms.ModelForm): class Meta: model = Pet fields = ('name', 'age', 'breed', 'owner_name') class OwnerForm(forms.ModelForm): class Meta: model = Owner fields = ('name', 'age', 'pet_name')
from collections import Counter letters = ['A','B','A','C','C'] frequency = Counter(letters).items() print(frequency)
import os, sys, types, re # supposed to contain a class, FeatConf, to ease working with fsf files in # python. started as a quick-and-dirty parsing class with little semantic # knowledge of the fsf file, but now I'm using this in several places, this # code has a bunch of uglinesses that would require a search-and-re...
from django.contrib import admin from djCell.apps.productos.models import TiempoGarantia,Estatus,Marca,Gama,DetallesEquipo,Equipo,TipoIcc,DetallesExpres,Expres,Secciones,MarcaAccesorio,DetallesAccesorio,EstatusAccesorio,Accesorio,NominacionFicha,EstatusFicha,Ficha,TiempoAire, HistorialPreciosEquipos,HistorialPreciosAcc...
import matplotlib.pyplot as plt import matplotlib import numpy as np plt.style.use('natalia') Qx_list1, Qy_list1 = np.loadtxt('../output/mytunes_nominalSPS_QpxQPy0.txt', delimiter=",", unpack=True) Qx_list2, Qy_list2 = np.loadtxt('../output/mytunes_nominalSPS_QpxQPy2.txt', delimiter=",", unpack=True) f, ax = plt.sub...
# coding=UTF-8 import sys #import time import pygame # Load the required library #from gtts import gTTS filePath = sys.argv[1] #tts = gTTS(text=say, lang='zh-tw') #timeStamp = str(time.time()) #tts.save("sound/" + timeStamp + ".mp3") print(filePath) pygame.mixer.pre_init(44100, -16, 2, 1024*2) pygame.mixer.init()...
#Write a program that reads a name and an age for a person, until the name is blank. Once all names have been present the user with an option to list the entered people in alphabetical order, or in descending age order. For either choice, list each person's name followed by their age on a single line. Make sure you out...
from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from .models import Posts from .forms import CreatePostForm # Create your views here. def index(request): #return HttpResponse('HELLO FROM POSTS') posts = Posts.objects.all()[:10] contex...
def l_norm_distance(vector1, vector2, n): d = 0 l = len(vector1) for i in range(l): d = d + abs(vector1[i] - vector2[i]) ** n d = d ** (1 / n) return d def find_k_nearest_neighbours(train_x, value_to_be_predicted, k, n): l = len(train_x) # print(l) distances = [] ...
#! /usr/bin/env python # coding: utf-8 import time from dms.utils.singleton import Singleton from dms.objects.base import DBObject class WebConfig(Singleton, DBObject): def __init__(self): DBObject.__init__(self) self.t = "web_config" self.cache = dict() self.cols = ["config_key...
import thread import curses import time from threading import Lock #globals Scr = None P = 12 Count = 0 mutex=Lock() #functions def init(): global Scr Scr = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) Scr.keypad(1) def finish(): curses.nocbreak() Scr.keypad(0)...
#!/usr/bin/env python #-*- coding: utf-8 -*- import os import sys # reload(sys) # sys.setdefaultencoding("utf-8") """ Simple wrapper around the Feng-Hirst parser, used as an entry point for a Docker container. In contrast to parse.py, this script only accepts one input file. Since parse.py is quite chatty, it's stdo...
# -*- coding: utf-8 -*- import codecs import sys from pinyin import PinYin class NameSearch: def __init__(self): self.name_yin_tone_dict = self.get_name_yin_tone_dict('name_yin_tone_dict') self.TP = 200 self.score_thre = self.TP * 0.7 self.w = 1 / self.TP def calculate_sco...
''' opencv + numpy製作資料 ''' import cv2 import numpy as np print('------------------------------------------------------------') #60個 img=np.zeros((200,200),dtype=np.uint8) #預設為0, 黑色, 2維 print("img=\n",img) cv2.imshow("one",img) for i in range(50, 100): for j in range(50, 100): img[i,j] = 255 cv...
""" Classes from the 'TCC' framework. """ try: from rubicon.objc import ObjCClass except ValueError: def ObjCClass(name): return None def _Class(name): try: return ObjCClass(name) except NameError: return None OS_tcc_object = _Class("OS_tcc_object") OS_tcc_events_subscripti...
import numpy as np a = np.fix(3.643532) print(a) """< 3.0 >""" b = np.fix(-3.643532) print(b) """< -3.0 >""" c = np.fix(2) print(c) """< 2.0 >"""
#!/usr/bin/env python #encoding: utf-8 from django.conf.urls import patterns, include, url urlpatterns = patterns('', #url(r'^$', 'acra.views.dashboard', name='dashboard'), url(r'dashboard/', 'acra.views.dashboard', name='dashboard'), url(r'timeline/', 'acra.views.timeline', name='timeline'), url(r'^report/', 'acr...
people = 30 cars = 10 trucks = 40 # if there are more cars than people, print the line if cars > people and cars < trucks: print("We should take the cars.") # else if there are more people than cars, print the line elif cars < people: print("We should not take the cars.") # if cars are equal to people, print ...
import threading from gi.repository import GLib class UidReader: def __init__(self, func): self.func = func def readUid(self): #uid = rd.readCard() uid = input() GLib.idle_add(self.func, uid)
#!/usr/bin/python from Bio.Seq import Seq from Bio.Alphabet import generic_dna, generic_protein class Ab_read: def __init__(self, name = '', V = '', Vmut = [0], J='', Jmut=[0], ABtype = '',cdr3=Seq(''),cdr2=Seq(''),cdr1=Seq('')): self.name = name self.V = V self.Vmut = Vmut self.J = J self.Jmut = Jmut ...
import pickle from rummySearch.tilesearch import TileDetector, order_points import cv2 import imutils import argparse import numpy as np td = TileDetector() image = cv2.imread("rummySearch/all_black_tiles.jpg") td.set_image(image, resize_width=960) tile_images = td.get_tile_images() for i, tile in enumerate(tile_...
import matplotlib.pylab as plt x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2] plt.scatter(x,y,label='plus',color='blue',marker='*',s=500) #google : matplot lib marker plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.title('Intresting Graph\nCheck it Out') plt.show()
import requests from utils.config import NewConfig class PostMeasureGra(object): def __init__(self, common, headers, accesstoken): self.headers = headers self.baseUrl = common.get('baseUrl') self.accesstoken = accesstoken self.headers.update({"accesstoken": self.accesstoken}) ...
from pathlib import Path from lxml import etree as ET from MusicXMLSynthesizer.utils import parse_notes_meta_to_list from MusicXMLSynthesizer.Synthesizer import Synthesizer def read_musicxml(path): file_path = Path(path) if not file_path.is_file(): print("Path:{}, Contnet: {}".format("Invalid", "")) ...
import time def profiler(method): def wrapper_method(*arg, **kw): t = time.time() ret = method(*arg, **kw) print('Method ' + method.__name__ + ' took : ' + "{:2.5f}".format(time.time()-t) + ' sec') return ret return wrapper_method def get_baord_sum(board): r...
from typing import Mapping, Union import numpy as np from .operation import Operation from .op_placeholder import OpPlaceholder class OpSetitem(Operation): """Get item based on indexing""" def __init__(self, x: Operation, key, value: Operation, **kwargs): self.inputs = [x, value] self.key = k...
from marshmallow import Schema, fields, validate class CategorySchema(Schema): id = fields.Int(dump_only=True) name = fields.Str(required=True, validate=validate.Length(1, 50))
#!/usr/bin/python3 # # Created by Stephen Farnsworth # text_under20 = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'] text_tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty...
#!/usr/bin/env python #_*_ coding: utf8_*_ #TwisterxS repaso argparse #encontrar numeros primos scripting python import argparse parser = argparse.ArgumentParser(description="Encontrar Numeros Primos ") parser.add_argument('-m','--maximun',help="Limite para encontrar los primos anteriores ") parser = parser.parse_ar...
# from flask_sqlalchemy import SQLAlchemy #from pymongo import MongoClient #from mongoengine import * #from mv_nalign import settings # db = SQLAlchemy() # connect(app.config['SERVER_NAME'] ) # # # def reset_database(): # from rest_api_demo.database.models import Post, nalign # noqa # db.drop_all() # db.c...
from pprint import pprint import boto3 from botocore.exceptions import ClientError from rekognition_objects import ( RekognitionFace, RekognitionCelebrity, RekognitionLabel, RekognitionModerationLabel, RekognitionText, show_bounding_boxes, show_polygons) class RekognitionImage: """ Encapsulates an A...
from hashlib import sha256 import onesignal as onesignal_sdk from django.conf import settings from django_rq import job from openbook_common.utils.model_loaders import get_user_model onesignal_client = onesignal_sdk.Client( app_id=settings.ONE_SIGNAL_APP_ID, app_auth_key=settings.ONE_SIGNAL_API_KEY ) @job('...
# 练习: # 写一个程序,让用户输入两个以上的正整数,当输入小于零的数时结束 # 输入(要求不允许输入重复的数) # 1) 打印这些数的和 # 2) 打印这些数中的最大数 # 3) 打印这些数中的第二大的数 # 4) 删除最小的一个数 L = [] while True: x = int(input('请输入正整数: ')) if x < 0: # 如果L的个数大于等于2,则允许退出,否则继承输入 if len(L) >= 2: break else: print("您输入的数据个数太少,请继承...
from general.command import Command from general.dnaSequence import DnaSequence class Slice(Command): def __init__(self, command): super().__init__(command) def sub_dna(self,dna_string ,index_start,index_end): new_str_dna = '' if 0 <= int(index_start) < int(index_end )...
import datetime from unittest import IsolatedAsyncioTestCase from unittest.mock import AsyncMock from dipdup.config import ( ContractConfig, OperationHandlerConfig, OperationHandlerTransactionPatternConfig, OperationIndexConfig, OperationType, TzktDatasourceConfig, ) from dipdup.index import Op...
class Queue: #construct the list def __init__(self): self.items = [] #check if empty def emptyQ(self): return self.items == [] #insert into queue def enqueue(self,item): self.items.insert(0,item) #remove from queue def dequeue(s...
import unittest from . import utils as TE class TestReqifDatatypeDefinitionString(unittest.TestCase): def setUp(self): self.obj = TE.TReqz.reqif_datatype_definition_string() def test_name(self): self.assertEqual("DATATYPE-DEFINITION-STRING", self.obj.name) def test_decode(self): ...
# Generated by Django 3.1 on 2020-08-20 00:35 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vinhos', '0004_auto_20200819_2131'), ] operations = [ migrations.AlterField( model_name='vinhos', name...
# DFS FOR DIRECTED GRAPH from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, n1, n2): self.graph[n1].append(n2) def print_graph(self): for n1, n2 in self.graph.items(): print n1, n2 def do_dfs(self, start): visited = [False] * len(se...
import pickle import tensorflow as tf import numpy as np import csv import matplotlib.pyplot as plt import matplotlib.image as mpimg import pandas as pd import cv2 import scipy import sys import os import pandas import argparse import json from PIL import Image from keras.layers import Input, Flatten, Dense, Lambda, ...
#!/usr/bin/python import sys, getopt, os, json import datetime, time def print_help_and_exit(exit_code,exit_msg=''): if exit_msg == '': print('test.py -i <inputfile> -o <outputfile>') else: print(exit_msg) sys.exit(exit_code) def process_results(directory, failed_list, broken_list, skippe...
# -*- coding: utf-8 -*- """ =============================================== Project Name: Working with Python ----------------------------------------------- Developer: Operate:--Orion Analysis Team-- Program:--Vector Data Analysis Team-- ............................................... Author(Analyst):朱立松--Mr...
from operations.indices import ClickhouseIndices from operations.internal_transactions import ClickhouseInternalTransactions from operations.blocks import ClickhouseBlocks from operations.contract_transactions import ClickhouseContractTransactions from operations.contracts import ClickhouseContracts from operations.inp...
from lettuce import step, world # Choose which browser to use @step(r'am using (?:Z|z)ope') def using_zope(step): world.browser = world.zope @step(r'am using (?:C|c)hrome') def using_chrome(step): world.browser = world.chrome @step(r'am using (?:F|f)irefox') def using_firefox(step): world.browser = w...
from static import StaticInfo def choose_period(): period = None while period not in StaticInfo.periods: period = input('give period: {h for help list}') if period == 'h': print(StaticInfo.periods) elif period not in StaticInfo.periods: print('wrong pe...
import pymysql,time from config import Config from dal.base_dal import mysql class Report: '''举报投诉管理类''' def add_report(self,imgs,reportInfo): try: if imgs: # 如果有上传图片 img_ids = [] for i in imgs: with mysql() as cursor: ...
#Date: 26-07-18 #Author: A.Suraj Kumar #Roll Number: 181046037 #Assignment 10 #Python Program to Count the Number of Digits in a Number. n=int(input("Enter your number:")) count=0 while(n>0): count=count+1 n=n//10 print(count)
import tensorflow as tf def var_mask(var, cur_var, axis, ker_f): prune_nodes = get_nodes_to_prune(cur_var, axis, ker_f) keep_nodes = tf.logical_not(prune_nodes) prune_mask = get_prune_mask(cur_var, keep_nodes, 1 - axis) prune_sum = tf.multiply(cur_var, prune_mask) return get_var_from_sum(var, prun...
N = int(input()) S = input() move = { "R": (1, 0), "L": (-1, 0), "U": (0, 1), "D": (0, -1), } cur = (0, 0) visited = set() visited.add(cur) for c in S: dx, dy = move[c] cur = (cur[0]+dx, cur[1]+dy) if cur in visited: print("Yes") exit() visited.add(cur) print("No"...
def atoi(str): value = 0 for i in range(len(str)): c = str[i] # 0~9 if c >= '0' and c <= '9': digit = ord(c) - ord('0') else: break value = value * 10 + digit return value a = '123' # a = [1, 2, 3] print(type(a)) b = atoi(a) print(b, type(b)...
class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(f"The restaurant {self.restaurant_name} serves {self.cuisine_type} dishes") def open_restaurant...
from binary_trees.binary_search_tree import * def height(root): if not root: return 0 left = height(root.left) + 1 right = height(root.right) + 1 return max(left, right) if __name__ == "__main__": bst = BinarySearchTree() tree_nodes = [20, 8, 4, 12, 10, 14, 22, 25] """ Tree r...
from django.conf.urls import url from shop import views as application urlpatterns = [ url(r'^$', application.main, name='index'), url(r'^auth', application.auth, name='charges'), ]
try: execfile = execfile except NameError: def execfile(filename, globals=None, locals=None): code = compile(open(filename).read(), filename, 'exec') exec(code, globals, locals) try: reduce = reduce except NameError: from functools import reduce
import code, codechef_solution import requests, conf from models import URL with requests.Session() as s: code.codechef_login(s, URL.BASE) # Uncomment this line, if you want to fetch the rating #code.get_rating(s, conf.handle) codechef_solution.codechef_download(s, conf.handle) code.codechef_logout(s, URL.BASE + ...
import datetime from asyncio.events import AbstractEventLoop from typing import Generator, List, Union from ..exceptions import VoyagerException from .base import BaseResource __all__ = [ 'FireballResource', ] class FireballRecord(object): __slots__ = [ '_fc', '_date', '_lat', ...
class Credential: #mysql credentials mysql_host = "localhost" mysql_user = "root" mysql_password = "12345"
# coding:utf-8 import os import gc import numpy as np import pandas as pd from keras.layers import * from keras.models import Model from keras.utils import Sequence from keras.optimizers import Adam from matplotlib import pyplot as plt from keras.initializers import he_normal from sklearn.model_selection import KFold ...
#!/usr/bin/env python print "\n================================================" print " Serial Communication" print "================================================" from sys import stdout from time import sleep from Tkinter import * '''try: import serial except: print "Could not impor...
# py37 # # Partially automate generation of meeting YAMLs for CUAMS website # # If you're just looking to generate the updated file, change the contents of # the shows array on the line starting "shows =". # # Resources: # https://www.crummy.com/software/BeautifulSoup/bs4/doc/ # https://realpython.com/python-f-strings/...
#!C:/Python27/ArcGIS10.2/python.exe # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import sys import psycopg2 import time reload(sys) sys.setdefaultencoding('utf8') if not os.environ.get("DJANGO_SETTINGS_MODULE"): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ResultManage.settings")...
import logging from collections import namedtuple from datetime import datetime from io import BytesIO from zope.interface import alsoProvides import xlsxwriter from eea.cache import cache from plone import api from plone.api import portal from plone.api.content import get_state, transition from plone.api.portal impo...
#!/usr/bin/python3 import socket import struct import os import sys import json import time import signal import argparse # Authored by Alex Ionita taionita@uwaterloo.ca """ ___ ,-"" `. ,' _ e )`-._ ...
# Generated by Django 2.2 on 2020-08-21 02:42 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Candidat', fields=[ ...
import pygame from os import getcwd, path from random import shuffle class Button: sprites = ["Button_Sprite0.png", # Standby "Button_Sprite1.png", # Neutral "Button_Sprite2.png", # Flag "Button_Sprite3.png", # Bomb "Button_Sprite4.png", # Exploded ...
from itertools import combinations N = int(input()) students = [] numbers = [] same = False length = 0 for i in range(N): students.append(input()) numbers.append('/') length = len(students[0]) for index in range(length): for i, stu in enumerate(students): numbers[i] = str(stu[length-index-1]) + s...
from django.contrib.gis import admin from models import UserStop, BaseStop, Agency, Source, StopAttribute, SourceAttribute import reversion class StopAttributeInline(admin.TabularInline): model = StopAttribute class SourceAttributeInline(admin.TabularInline): model = SourceAttribute class StopAdmin(admin...
from django.urls import path, include from rest_framework.routers import DefaultRouter from product.views import ProductViewset, ListPublishedProductView router = DefaultRouter() router.register('products', ProductViewset, basename='product_crud') urlpatterns = [ path('published-products/', ListPublishedProductV...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect, get_object_or_404 from shop.models import Product from django.contrib.auth.decorators import login_required from .models import Wishlist, Wishli...
from django.contrib import admin from web.models import Place,Activity,Activity_Checkout,User_Account admin.site.register(Place) admin.site.register(Activity)
#DP and bottom up approach def Fibonacci_sequence(n): if n == 1 or n ==2: result = 1 #the bottom up list stored previous calculation bottom_up = [None] * (n+1) bottom_up[1] = 1 bottom_up[2] = 1 for i in range(3,n+1): bottom_up[i] = bottom_up[i-1] + bottom_up[i-2] return botto...
import argparse def argument(): parser = argparse.ArgumentParser(description = ''' Needs a profiler.py, already executed. Produces 3 png files, containing timeseries for some statistics, for each wmo. ''', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( '--maskfile', '-m', ...
# Imports from flask import Flask, render_template, redirect, url_for from flask_pymongo import PyMongo import pymongo from flask import Flask, jsonify import io import json from bson import ObjectId from flask.json import JSONEncoder app = Flask(__name__) myclient = pymongo.MongoClient("mongodb://localhost:27017/") ...
import sys import pdb import random import numpy as np import perm2 import unittest from wreath import wreath_yor, get_mat, WreathCycSn, cyclic_irreps, wreath_rep from utils import load_irrep from coset_utils import young_subgroup_perm, coset_reps from cube_irrep import Cube2Irrep sys.path.append('./cube') from str_cu...
from tensorboardX import SummaryWriter import os from Experiment import * Pendulum = ExperimentClass('Pendulum-v0') # os.chdir("debug") os.chdir("trainModel_runs") # actor_neuron_parameters = [25,35,45] # critic_neuron_parameters = [4,5,6] # min_reward = -100 # for actor_neuron in actor_neuron_parameters: # for c...
"""Callback registry""" from jwst.lib.signal_slot import Signal __all__ = ['CallbackRegistry'] class CallbackRegistry(): """Callback registry""" def __init__(self): self.registry = dict() def add(self, event, callback): """Add a callback to an event""" try: signal =...
################################################ #Try to blend the image # Make image as background and draw lines on it # ################################################# from PIL import Image import os def image_blend(path): images = [] for filename in os.listdir(path): if 'png' in filename or 'jpg' in filen...
#!/usr/bin/env python # -*- coding:utf-8 -*- 1、执行SQL 复制代码 # !/usr/bin/env pytho # -*- coding:utf-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1', charset='utf8') # 创建游标 cursor = conn.cursor() # 执行SQL,并返回收影响行数 effect_row = cursor.execute("select * from...
__author__ = 'Jakub Wojtanek. Kwojtanek@gmail.com' import re def L2(): xt = open('l2.txt', 'r') xt = xt.read() print ''.join(re.findall("[A-Za-z]", xt)) l2()
import requests import json from pathlib import Path # Gets your currentt ipv4 / ipv6 address class _ipify(): apiAddress = "https://api64.ipify.org" def __init__(self, ca=None, requestTimeout=15): self.requestTimeout = requestTimeout if ca != None: if type(ca) is str: ...
"""Program that outputs one of at least four random, good fortunes.""" __author__ = "730249177" from random import randint print("Your fortune cookie says...") choice = randint(1, 100) if choice < 50: print("An old love will come back to you in the coming days.") else: if choice <= 30: print("The spe...
import numpy import labrad cxn = labrad.connect() dv = cxn.data_vault import matplotlib from matplotlib import pyplot totalTraces = 200 #title = '2012 June 21 delay time 5 ions' ; datasets = ['2012Jun21_{0:=04}_{1:=02}'.format(x/100, x % 100) for x in [192851,193305,193518,193826, 194101,194327,194601,194925,200802,...
# -*- coding: utf-8 -*- """ A file with helper functions to create and Excel file with the associated analysis previously performed. Created on Fri Jul 12 12:03:48 2019Created on Mon Jul 15 10:01:37 2019 @author: sdtaylor """ # imports import pandas as pd import xlsxwriter import itertools import os from datetime im...
# 그래프 인접리스트 ajd_list = [ [2, 1], [3, 0], [3, 0], [9, 8, 2, 1], [5], [7, 6, 4], [7, 5], [6, 5], [3], [3] ] N = len(ajd_list) # 저점 방문 여부 확인 용 visited = [False] * N def dfs(v): visited[v] = True print(v, ' ', end='') for w in ajd_list[v]: if not visited[w]: # 정점) w에 인접한 정점으로 dfs...
import cwiid import time from phue import Bridge import requests #Check config for later use f = open("./config.py") lines = f.readlines() f.close() #Get Hue bridge ip from the site below r = requests.get('https://www.meethue.com/api/nupnp') x = r.json() for item in x: bridge_ip = dict(item)['internalipaddress'] p...
class Home: def get_cost(self): return 200000 class Plaster(Home): def __init__(self , wrapper): self.wrapper = wrapper def get_cost(self): return 10000 + self.wrapper.get_cost() class Painting(Home): def __init__(self , wrapper): self.wrapper = wrapper def...