text
stringlengths
8
6.05M
import argparse from common import * def main(directory, template, overwrite): """ Copies the default_package to the directory passed in, the environment variable PKG_ROOT_DIRECTORY or the current working directory. :param directory: Directory to create for this package :param template: Path to t...
from flask import Flask,render_template,request import numpy as np import re import requests import json import csv import pandas as pd app = Flask(__name__) def check(output): url = "https://rapidapi.p.rapidapi.com/generate/" payload = {"text": output} #print(payload) headers = { ...
from .utils.nnet_named import NamedGradientStatus from .utils.nnet import symbolic_variable_for_dimension from numpy import array import theano, theano.tensor as T, numpy as np from collections import OrderedDict REAL = theano.config.floatX class GradientModel(object): """ A gradient model for updating your model w...
from __future__ import annotations from contextlib import AsyncExitStack from datetime import datetime from functools import partial from typing import Iterable from uuid import UUID import attrs from anyio import to_thread from anyio.from_thread import BlockingPortal from ..abc import AsyncDataStore, AsyncEventBrok...
from jnius import autoclass, JavaException import sys PyJNIusExample = autoclass("PyJNIusExample") pyJNIusExample = PyJNIusExample() print "Calling instantiated addNumbers... The result is %d"%pyJNIusExample.addNumbers(13,1,20,8) print "Calling instantiated addition... The result is %d"%pyJNIusExample.addition(13,1,...
# Time Zones and Daylight Saving!! # In this chapter, you'll learn to confidently tackle the time-related topic that causes people the most trouble: time zones and daylight saving. Continuing with our bike data, you'll learn how to compare clocks around the world, how to gracefully handle "spring forward" and "fall bac...
import sys sys.path.append('..') import uuid from src.database_tools.DatabaseAdapter import DatabaseAdapter from src.entities.Temperature import Temperature from datetime import datetime class TemperatureDataService(): # constructor: def __init__(self): self.__tableName = "temperature"...
import utils import lstm as net import argparse import os import torch import torch.nn.functional as F import torch.optim as optim import data_loader from sklearn.metrics import accuracy_score arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--embedding_file', default='data/balanced/embs/tokens.txt',...
# this is still a comment in py3 print("have to do this parentheses now") #but this is still a comment, i think # print("block this VIM!")
from myhdl import * import argparse W0 = 9 flags_i = Signal(intbv(0)[3:]) left_i = Signal(intbv(0)[W0:]) right_i = Signal(intbv(0)[W0:]) sam_i = Signal(intbv(0)[W0:]) clk_i = Signal(bool(0)) update_i = Signal(bool(0)) update_o = Signal(bool(0)) res_o = Signal(intbv(0, min=-(2**(W0)), max=(2**(W0)))) def cliparse(): ...
# Generated by Django 3.2 on 2021-05-13 22:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_accounts_user_type'), ] operations = [ migrations.AlterField( model_name='accounts', name='user_type'...
from json import load from coala_json.reporters.ResultReporter import ResultReporter class HtmlReporter(ResultReporter): """ Contain methods to produce Html test report from coala-json coala_json is coala output in json format, usually produced by running coala with --json option """ def to_...
from random import random,seed,randint,shuffle import numpy,os colors=['R','G','Y','B'] for k in range(18): seed(k) m=randint(1,60) n=randint(1,60) testname="test"+str(k) discs=[] for i in range(m): for j in range(n): seed(i+j) numpy.random.shuffle(colors) ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase from odoo.modules.module import get_module_resource class TestCSVFile(TransactionCase): """ Tests for import bank statement ofx file format (account.bank.statement.impo...
import numpy as np GAMMA = np.exp(-5) NSUBSETSIZE = 20 BOUND = 5 NN = 1000 BIN0 = 10 BIN1 = 30
import pygame pygame.init() crash_sound = pygame.mixer.Sound("assets/sounds/crash.wav") window_width = 800 window_height = 600 surface = pygame.display.set_mode((window_width, window_height)) clock = pygame.time.Clock() pygame.display.set_caption("Race Car by S^#!L") car_obj = pygame.image.load("assets/img/racecar.pn...
import numpy as np import pandas as pd from sklearn.ensemble import GradientBoostingRegressor from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split # 1. 데이터 values = '3.00427759e-02 1.53808812e-04 2.66646072e-03 1.13227503e-03\ 3.07877293e-02 3.79559378e-01 8.50877684e-03 9.791...
#MenuTitle: Metrics Key Manager # -*- coding: utf-8 -*- __doc__=""" Batch apply metrics keys to the current font. """ import vanilla LeftKeys=""" =H: B D E F I K L N P R Thorn Germandbls M =O: C G Q =o: c d e q eth =h: b k l thorn =n: idotless m p r =|n: u """ RightKeys=""" =|: A H I M N O T U V W X Y =O: D =U: J...
#调用低通api实现RSA import rsa import time #计算下时间 start_time = time.time() key = rsa.newkeys(1024) #数字代表 p * q 产生的存储空间 bit 大小, 也就是密文长度,数字越大,时间越长 privateKey = key[1] publicKey = key[0] #print(privateKey) #print(publicKey) end_time = time.time() print("make a key:", end_time - start_time) #产生公钥和私钥 message = 'hello' message ...
from game.items.item import Log from game.skills import SkillTypes class NormalLog(Log): name = 'Normal Log' value = 97 xp = {SkillTypes.firemaking: 40, SkillTypes.fletching: 1} skill_requirement = {SkillTypes.firemaking: 1, SkillTypes.fletching: 1}
#!/usr/bin/python # --*-- coding:utf-8 --*-- from __future__ import print_function import subprocess import threading # def is_reacheable (ip): #subprocess.call() 调用系统命令 #os.system() if subprocess.call(["ping","-c","1",ip]): print ("{0} is alive ".format(ip)) else: print...
import os import time import tensorflow as tf import joblib import logging from utils.all_utils import get_time_stamp def create_and_save_checkpoint_callback(callbacks_dir,checkpoint_dir): checkpoint_file_path = os.path.join(checkpoint_dir, "ckpt_model.h5") checkpoint_callback = tf.keras.callbacks.ModelCheck...
# %% import os # %% DataFolder = os.path.join(os.environ['HOME'], 'RSVP_dataset', 'processed_data')
from selenium import webdriver from BrowserFactory.AbstractFactory import AbstractFactory # This class is obsolete class FirefoxBrowser(AbstractFactory): def __init__(self): self.driver = webdriver.Firefox(executable_path="/usr/bin/geckodriver") self.driver.implicitly_wait(10) self.dr...
import os def split_by_n(fname,n=3): ''' :param fname: input, file :param n: input, int :return: output, n files ''' assert isinstance(fname,str) assert isinstance(n,int) assert 1<=n<=99 sum = os.path.getsize(fname) ave = sum/n with open(fname,'r') as f:...
import os import subprocess ''' Read events from allEvents.txt file. Each line of the file has to be of the structure: run:lumi:event ''' eventList = [] with open("allEvents.txt","r") as f: while True: l = f.readline() if l =='': break eventList.append(l.replace('\n','')) runsAndEras = {\...
#!/usr/bin/env python """Clone an Oracle DB Using python""" ### usage: ./cloneOracle.py -v mycluster \ # -u myuser \ # -d mydomain.net \ # -ss oracleprod.mydomain.net \ # -ts oracledev.mydomain.net \ # ...
from 规则分词.mmcut import DicHelper class RMMCut(): def __init__(self,window_size=1): self.window_size=window_size def cut(self,text,dic): result=[] delimiter='--' index=len(text) while index > 0: for size in range(index-self.window_size,index):#从index-window_...
from pwn import * import sys #import kmpwn sys.path.append('/home/vagrant/kmpwn') from kmpwn import * #fsb(width, offset, data, padding, roop) #config context(os='linux', arch='i386') context.log_level = 'debug' FILE_NAME = "./secret-flag" HOST = "2020.redpwnc.tf" PORT = 31826 if len(sys.argv) > 1 and sys.argv[1] ...
import tensorflow as tf import numpy as np true_parameter = np.array([3, 10]).reshape(2, 1) train_x = np.hstack((np.ones([100, 1]), np.random.rand(100, 1))) train_y = np.dot(train_x, true_parameter) + np.random.randn(100, 1) x = tf.placeholder(tf.float32, [100, 2]) theta = tf.Variable(tf.zeros([2, 1])) hypothesis = ...
from uuid import UUID from onegov.fsi import FsiApp from onegov.fsi.collections.attendee import CourseAttendeeCollection from onegov.fsi.collections.audit import AuditCollection from onegov.fsi.collections.course import CourseCollection from onegov.fsi.collections.course_event import CourseEventCollection, \ PastC...
import json import unittest from unittest import mock from django.test import RequestFactory from django.conf import settings from api import views, middleware settings.configure() class TestStringMethods(unittest.TestCase): def setUp(self): self.factory = RequestFactory() self.middleware = midd...
# -*- coding: UTF-8 -*- # Date : 2020/2/17 15:53 # Editor : gmj # Desc : # # import os # import time # ret = os.system('tasklist | find "QQ.exe"') # # print(ret) import psutil def get_count_of_nodejs(): i = 0 for pro in psutil.process_iter(): if pro.name() == 'node.exe': i += 1 r...
# Tab length compensation a negative number will increase the gap between the tabs # a fudge factor that increases the gap along the finger joint when negative - it should be 1/4 of the gap you want fudge=0.1 thickness=3 # box_width=60 box_height=15 box_depth = 25 cutter='laser' tab_length=5 centre = V(0,0) mo...
def twoSum(self, nums: List[int], target: int) -> List[int]: """ 1. 暴力,双循环 O(n^2) """ """ method 2 遍历一次存入hash,再遍历第二次查询 target-num 是否存在于hash O(n), O(n) """ dic = {} # key val: num , index for i in range(len(nums)): dic[nums[i]] = i for i in range(len(nums)): ...
# -*- coding: utf-8 -*- from time import time import button import thingSpeakService import buzzer import servo import rotation import led from grove import grove_4_digit_display THING_SPEAK_CHANNEL = 935198 THING_SPEAK_API_KEY = '81SYGRV7PHQU25C8' class StateMachine(): def __init__(self, button, display, sensor...
class Solution(object): """ # This solution times out on long sets. Passed 1607/1808 test cases def isMatch(self, s, p): if len(s) == 0: if len(p) == 0: return True return p == "*"*len(p) if len(p) == 0: return False if s[0] == p[...
# Generated by Django 2.2.13 on 2020-12-16 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('carts_api', '0018_auto_20201123_1702'), ] operations = [ migrations.CreateModel( name='UploadedFiles', fields=[ ...
import base64 import os def generate_token() -> str: return base64.b64encode(os.urandom(32)).decode()
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from ava.task import action from bs4 import BeautifulSoup @action def parse(html_text, parser='html.parser'): """ Use BeautifulSoup4 to parse HTML document. :param html_text: the HTML data :param parser: the...
setnumber = {10, 5, 65, 'saquib', 'python', 'flask', 10, 'value'} set2 = {'python', 'flask', 10} print(set2) print(setnumber) # denoted by {} does not show the duplicate value # can store string and integer values setnumber.add(2.6) print(setnumber) setnumber.copy() print(setnumber) set2 = setnumber.copy() print(set2)...
#scattegories ? #provides basic framework for playing #still need pencils and other players #TODO: fully automate + AI ? import random, time numPlayers = 0 timer = 180 #seconds numCategories = 12 categoryList = [] letter = "" def getNum(): num = 0 loop = True while loop: try: num = input('') num = in...
#!/usr/bin/python #\file simple_read.py #\brief Simply read from serial port. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Jul.01, 2021 import sys import serial if __name__=='__main__': dev= sys.argv[1] if len(sys.argv)>1 else '/dev/ttyACM0' baudrate= int(sys.argv[2]) if len(sys.arg...
# python 2.7.3 import sys import math n = input() words = [None for i in range(n)] for i in range(n): words[i] = raw_input() ans = [] for i in range(1, n + 1): if n % i != 0: continue q = n / i lan = set() valid = True for j in range(q): temp = set(words[j * i:(j + 1) * i]) if 'unknown' in temp: temp.r...
from .base import BaseModel class FooterModel(BaseModel): def init(self): self.add_property('copyright')
from fractions import gcd def simplify_fraction(fraction): return (fraction[0] // gcd(fraction[0], fraction[1]), fraction[1] // gcd(fraction[0], fraction[1]))
import sys import re from pprint import pprint, pformat from datetime import datetime, timedelta import pytz import logging from collections import namedtuple from netCDF4 import Dataset import numpy as np FORMAT = '%(asctime)s %(message)s' logger = logging.getLogger() handler = logging.StreamHandler() formatter = lo...
from datetime import datetime from behave import given, then from behave.runner import Context from freezegun import freeze_time from pepy.domain.model import ProjectName, ProjectDownloads, Downloads from tests.tools.stub import ProjectStub @given("today is {date}") def step_impl(context: Context, date: str): f...
from onegov.ballot import Election from onegov.ballot import List from onegov.core.security import Public from onegov.election_day import ElectionDayApp from onegov.election_day.layouts import ElectionLayout from onegov.election_day.utils import add_last_modified_header from sqlalchemy import func def list_options(re...
# -*- coding: utf-8 -*- """ Name: SQLite example of creating tables and inserting rows. Author: Martin Bo Kristensen Grønholdt. Version: 1.0 (2017-04-22) """ # Import the SQLite module import sqlite3 # Start an exception block to catch errors. try: # Create a connection to a database with the file name 'example.d...
# -*- coding: utf-8 -*- # jieba_wikiData.py将wiki数据用jieba进行分词,生成wiki.zh.text.seg文件 import jieba # jieba.load_userdict('userdict.txt') # 创建停用词list def stop_words_list(filepath): stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()] return stopwords # 对句子进行分词 def seg_sentence...
#!/bin/python3 def mini_max_sum(arr): current_min = min(arr[:2]) current_max = max(arr[:2]) running_sum = 0 for value in arr[2:]: if value < current_min: running_sum += current_min current_min = value elif value > current_max: running_sum += current_m...
############################################################################### # # trackers.py # # Python OpenCV program for testing different trackers. # It is based on code from [https://www.learnopencv.com/object-tracking-using-opencv-cpp-python/] # # The program has three operating modes: # 'm' key Mark: ...
# Jaemin Lee (aka, J911) # 2019 import cv2 import numpy as np class CustomCapture: def _cam_initialize(self): self.cam = cv2.VideoCapture(0) self.cam.set(3, 1280) self.cam.set(4, 720) def _cam_release(self): self.cam.release() def capture(self, label=''): ...
import os import shutil import sys from pathlib import Path import click from subprocess import check_output from onegov.core.cli import command_group from onegov.core.utils import module_path cli = command_group() def pre_checks(): node_version = check_output('node --version', shell=True) if 'v10' not in no...
from rv.modules import Behavior as B from rv.modules import Module from rv.modules.base.kicker import BaseKicker class Kicker(BaseKicker, Module): behaviors = {B.receives_notes, B.sends_audio}
import torch num = 32 num_priors = 8732 print(num, num_priors) loc_t = torch.Tensor(num, num_priors, 4) print(loc_t) t = torch.cat(1,1) print(t)
""" """ from leetCodeUtil import TreeNode class Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ root = self.constructTree(nums, 0, len(nums)) return root def constructTree(self, nums, start, end): if ...
import cv2 import numpy as np pic=cv2.imread('image.jpg') threshold_value=100 (T_value, binary_threshold)=cv2.threshold(pic, threshold_value, 255, cv2.THRESH_BINARY) cv2.imshow('binary', binary_threshold) cv2.waitKey() cv2.destroyAllWindows()
# [실습] # keras67_1 남자 여자에 noise를 넣어서 제거하시오. # 실습 # 남자 여자 구별 # ImageDataGenerator / fit_generator 사용해서 완성 import numpy as np from matplotlib import pyplot as plt import random from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras....
from .common import * # import the common settings, across all deployments DEBUG = True TEMPLATE_DEBUG = DEBUG def has_debug_toolbar(): try: import debug_toolbar dir(debug_toolbar) return True except ImportError: return False if has_debug_toolbar(): INSTALLED_APPS += ( ...
""" 匿名函数与lambda lambda表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数。 lambda所表示的匿名函数的内容应该是很简单的,如果复杂的话,干脆就重新定义一个函数了,使用lambda就有点过于执拗了。 lambda就是用来定义一个匿名函数的,如果还要给他绑定一个名字的话,就会显得有点画蛇添足,通常是直接使用lambda函数。如下所示: add = lambda x, y : x+y add(1,2) # 结果为3 那么到底要如何使用lambda表达式呢? 1、应用在函数式编程中 ...
/home/ajitkumar/anaconda3/lib/python3.7/fnmatch.py
#!/usr/bin/python2 __module_name__ = "invite.py" __module_version__ = "1.0" __module_description__ = "Invite Plugin" __module_author__ = "Ferus" import xchat def invited(word, word_eol, userdata): '''Looks like we've been invited to a channel, lets join it!''' print("* \x02[Invite]\x02 Invited to {0}, Now joining."...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-09 15:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('carto', '0041_auto_20171109_1634'), ] operations =...
#Missing numbers def findMissingNums(arr): minNum = arr[0] maxNum = arr[len(arr) - 1] limit = 10 i = 0 res = '' while i < len(arr): if i < minNum: res += str(i) + ' - ' + str(minNum - 1) + ' , ' print(res) ...
# @Title: 汉明距离 (Hamming Distance) # @Author: 2464512446@qq.com # @Date: 2019-09-06 16:58:22 # @Runtime: 20 ms # @Memory: 11.4 MB class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ return bin(x ^ y).count('1')
from .zhihu import ZhihuSpider from .hupu import HupuSpider from .v2ex import V2exSpider from .weibo import WeiBoSpider from .github import GithubSpider from .tieba import TiebaSpider from .douban import DoubanSpider from .tianya import TianyaSpider from .baidu import BaiduSpider from .spider_36kr import Spider36kr fro...
import cv2 import logging import numpy as np from .tracklet import Tracklet class Tracker: def __init__(self, detector, encoders, matcher, predictor=None, last_frame=None, max_ttl=30, max_feature_history=30, max_detection_history=3000, min_time_lived=5): self.detector = detector s...
"""Class definition for the MODSCAG snow cover fraction data type. .. module:: modscag :synopsis: Definition of the MODSCAG class .. moduleauthor:: Kostas Andreadis <kandread@jpl.nasa.gov> """ import dbio from datetime import timedelta import datasets import modis import requests from requests.auth import HTTPDi...
from pprint import pprint, pformat # pylint: disable=unused-import import logging import time from copy import deepcopy # from collections import defaultdict from pymongo import UpdateOne, InsertOne from pymongo.errors import BulkWriteError def bulk_write(db, item_type, ops, stat=None, retries=3, log_first_failop=...
from django.urls import path from savings import views app_name = "savings" urlpatterns = [ path('indexs/', views.Index.as_view(), name="indexs"), path('list_users/', views.ListUsers.as_view(), name="list_users"), path('user_lists/', views.list_Users, name="user_lists"), path('list_saving/', views.Lis...
from django.contrib import admin from django.urls import path from .views import SocialListView, SocialUpdateView urlpatterns = [ path('social/list/', SocialListView.as_view(), name='socialList'), path('social/update/<int:pk>/', SocialUpdateView.as_view(), name='socialUpdate') ]
a = int(input("fyrri tala ")) b = int(input("seinni tala ")) def multiple (a,b): result = a * b return result samtals = multiple(a, b) print("n * n = ", samtals)
# coding=utf-8 try: from setuptools import setup except ImportError: from distutils.core import setup import githon requirements = open('requirements.pip').read().splitlines() kw = dict( name = 'githon', version = '0.7.0', description = 'A simple Data Scraping library for GitHub REST API v3', ...
class MyBeautifulGril(object): """我的漂亮女神""" __instance = None __isFirstInit = False def __new__(cls, name): if not cls.__instance: MyBeautifulGril.__instance = super().__new__(cls) return cls.__instance def __init__(self, name): if not self.__isFirstInit: ...
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...
# By Rakeen Rouf import pandas as pd import os import platform import time class TxtToCsv: """ Converts ae txt files into csv. History.csv keeps track of incoming data. The CSV is updated based on modification time """ def __init__(self, data_file='C:/Users/rakee/Downloads/livedata.txt'): ...
from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views app_name = 'customer' urlpatterns = [ path('create-customer/', views.create_cutomer, name='create_customer'), path('', views.home, name='home'), ...
#!/usr/bin/env python import numpy as np import kaldiio from ABXpy.misc import any2h5features import os, shutil #read from feats.scp #add feats scp direc if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("feats_file", help="path to the ivector.scp we're go...
from itty import * @error(500) def my_great_500(request, exception): html_output = """ <html> <head> <title>Application Error! OH NOES!</title> </head> <body> <h1>OH NOES!</h1> <p>Yep, you broke it.</p> <p>Exception: %s</p> </b...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4222 ._SN', MapName = 'Grancel', Location = 'T4222.x', MapIndex = 1, MapDefaultBGM = "ed60017", Flags = 0, ...
#import sys #input = sys.stdin.readline def main(): N, L = map( int, input().split()) S = [ input() for _ in range(N)] S.sort() V = [1]*N print("".join(S)) if __name__ == '__main__': main()
import threading import time from concurrent.futures import ThreadPoolExecutor from socket import socket, AF_INET, SOCK_STREAM def client(sock, addr): print('Got connection from', addr) while True: msg = sock.recv(1024) if not msg: break print(str(msg)) sock.sendall(...
class School: def admission(self,name,adress): self.name=name self.adress=adress print(self.name,self.adress) class College(School): def admission(self,name,adress,admnno): self.name=name self.adress=adress self.admnno=admnno print(self.name,self.adress,se...
# Objects Are Like Import class Mymodule(object): def __init__(self): self.mehmet = "Hahahahahha" def apple(self): print("I'm apples") # If a class is like a ”mini-module,” then there has to be a concept similar to import but for classes. That # concept is called ”instantiate”, which is just ...
import pygame as pg boje = { "bojaPKvadrata": (50, 168, 82), "bojaKKvadrata": (168, 64, 50), "bojaGrida": (0, 0, 0), "bojaPrepreke": (0, 0, 0), "bojaPuta": (212, 203, 30), "radnaBoja": (66, 147, 245), "bojaTrenutna": (245, 47, 50)} dugmiciZaGui = [{"id": 0, "fontV...
def fun(): print('hello') # return 1 # 结束函数,并返回一个对象 # return 1,2,[23,4] # 如果返回对个对象,解释器会将其封装成一个元组(1,2,[23,4]) # print(1) # 不会执行 # 如果不写return python默认会return一个None print(fun())
#!/usr/bin/env python # coding: utf-8 """ From a file containing Decompressed relations, this script generates a set of files containing SPLITS percentage of the dataset. Thus, a file containing 100 frames, this script creates a folder `10/` containing a file with the same name of the input file, but containing only 1...
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> import sys import re import os import subprocess from math import log, ceil from error im...
#!/usr/local/bin/python # -*- coding: utf-8 -*- import requests import json import sys import os class GingerSummary(object): """Ginger Summary""" def __init__(self, original, results): super(GingerSummary, self).__init__() self.original = original self.results = sorted(results, cmp=lambda x, y: cmp(x.from_, y...
import socket import sys import threading # Define socket host and port SERVER_HOST = '127.0.0.1' SERVER_PORT = 8000 # Create socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((SERVER_HOST, SERVER_PORT)) serv...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import os import sys DOIT_CONFIG = {'default_tasks': ['hello']} sys.path.append(os.path.join('.', 'src')) def is_windows(): return sys.platform.startswith('win') def task_hello(): """hello""" de...
from qhue import Bridge import math from pathlib import Path def getHueInfo(): filePath = Path("C:\\homeAutomation\\categories\\lighting\\hueInfo.txt") f = open(filePath, "r") data = f.readlines() f.close() #info = data.split(",") bridgeInfo = data[0].split(":") userInfo = data[1].split(...
import sys, os import os.path as osp import numpy as np import torch.utils.data as data __all__ = ['FlyingThings3DSubset'] class FlyingThings3DSubset(data.Dataset): """ Args: train (bool): If True, creates dataset from training set, otherwise creates from test set. transform (callable): ...
from collections import defaultdict from contextlib import contextmanager from variable import Variable, Assignments def evaluable(clause, assignment): for variable in clause: if assignment[variable.name] is None: return False return True def istautology(clause): variables = {} ...
from django.db import models from django.conf import settings # Create your models here. class Post(models.Model): title = models.CharField(max_length=240) body = models.TextField() created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, au...
from app.main import db from app.main.model.customer import Customer def get_all_customers(): return Customer.query.all() def get_customers_by_lead(data): return Customer.query.filter_by(lead_id=data["lead_id"]) def save_new_customer(lead): new_customer = Customer(lead) save_changes(new_customer) ...
#ex14.py = Prompting and Passing #https://learnpythonthehardway.org/book/ex14.html #from sys import argv #script, user_name = argv #prompt = '>' #print "Hi %s, I'm the %s script." % (user_name, script) #print "I'd like to ask you a few questions." #print "Do you like me %s?" % user_name #likes = raw_input(prompt) #...
import numpy as np import random from collections import namedtuple, deque import torch torch.manual_seed(0) # set random seed import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Categorical from agents.policy_search import PolicySearch_Agent BUFFER_SIZE ...