text
stringlengths
8
6.05M
from datetime import datetime import os, time from src.entities.Temperature import Temperature _sensorPath = '/sys/bus/w1/devices/28-01144fdb5caa/w1_slave' class TemperatureSlave: def ReadTemperature(self): temperatureFile = open(_sensorPath, 'r') lines = temperatureFile.r...
# import blender gamengine modules from bge import logic from bge import events from bge import render from . import bgui from .settings import * from .helpers import * header = "Lighting" def update(panel): ''' called when model has changed''' showPanel(panel) def destroy(panel): pass def showPanel(panel): ...
import re def get_ip_from_cfg(filename): result = {} regex = (r"^interface (?P<intf>\S+)" r"|address (?P<ip>\S+) (?P<mask>\S+)") with open(filename) as f: for line in f: match = re.search(regex, line) if match: if match.lastgroup == "intf": ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 错误处理 # 在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。 # 在操作系统提供的调用中,返回错误码非常常见。比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1 # 所以高级语言通常都内置了一套try...except...finally...的错误处理机制,Python也不例外 try: print('try...') r = 10 / 0 print('result:', r) except ZeroDivisio...
""" tools class for api instances """ from abc import ABC, abstractmethod class ToolsBase(ABC): def __init__(self): super().__init__() @classmethod def build_new(cls, **kwargs): cls(**kwargs)
import ejemplo_paquete __all__=['ejemplo_paquete']
import symbol import streamlit as st import pandas as pd import base64 import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion...
# Python script # Script to test KLayout's "Basic" PCell library components # by Lukas Chrostowski, 2015/11 import pya import numpy as n def PCell_get_parameter_list ( cell_name, library_name ): # function to list all the parameters & defaults for a PCell # example usage: # PCell_get_parameter_list("CIRCLE",...
import os import shutil ROOT_FOLDER = '' DEST_FOLDER = '' NAME_FOLDER_SUFFIX = '' # returns folders not client.log files def retrieve_clogs_folders(folder): subfolders = [ f.path for f in sorted(os.scandir(folder), key=os.path.getmtime) if f.is_dir() ] curated_file_list = [] for s in subfolders: ...
from django.db import models from django.contrib.auth.models import AbstractUser from multiselectfield import MultiSelectField from GlobalModels.models import Skills, Tools, Field_of_work from GlobalModels.cleaner import avatar_cleanup def upload_path(instance, filename): return '/'.join(str('avatar', i...
from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from blog.models import Post def home(request): # """Main listing.""" # posts = Post.objects.all().order_by("-created") # paginator = P...
from typing import Any from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from lrs.base_model import BaseModel class LSAModel(BaseModel): def set_vectorizer(self, max_df: float, min_df: float, max_features: int) -> Any: self.vectorizer = TfidfVect...
# ============================================ # ; Title: edwards_calculator.py # ; Author: Professor Krasso # ; Date: 23 June 2019 # ; Modified By: Alan Edwards # ; Description: Calculator functions # ;=========================================== def add(x, y): return x + y def subtract(x, y): return x ...
#!/usr/local/bin/python # -*- coding: utf-8 -*- print("Hello, World.") input_string = input() print(input_string)
# !/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Gonzalo Chacaltana" __version__ = 1.0 from LinearAlgebra import console import matplotlib.pyplot as plt class CartesianPlane(object): def __init__(self, function: object, range=None): self.function = function self.range = 15 if range is...
import calendar import time def api_not_found(message): return (message, 404) def api_bad_request(message): return (message, 400) def to_timestamp(dt): return calendar.timegm(dt.timetuple()) def time_it(func): """Simple decorator to print out the execution time of a function.""" def wrapped(...
#!/usr/bin/env python # coding: utf-8 # # Discover sentiment in tweets # # Sentiment analysis is commonly used in marketing and customer service to answer questions such as "Is a product review positive or negative?" and "How are customers responding to a product release?" # # *Topic modeling* discovers the abstract...
import hashlib, bleach from markdown import markdown from flask import current_app, flash, request from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask_sqlalchemy import SQLAlchemy from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin fr...
import user_interface import players_of_event import obtain_probability from Game import Game def runner(): # Obtain the name of the game, the moments of the event, the id selected game_id, event_moments, event_id, event_description, shot_time = user_interface.get_event_sv() if not game_id: # if game_id...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Script to extract timestamps and corresponding transcription # Give tierNumber as the input # Author : Sishir Kalita (Armsoftech.air) # email id: sisiitg@gmail.com # Date: 22 March, 2020 import re import glob from itertools import islice tierNo = input("Enter the ti...
import PyPDF2 import re import matplotlib.pyplot as plt FIG_SIZE = (8,6) FILE = 'N:/Downloads/race_laps.pdf' DRIVERS = ['Daniel RICCIARDO', 'Lando NORRIS', 'Sebastian VETTEL', 'Kimi RAIKKONEN', 'Romain GROSJEAN', 'Pierre GASLY', 'Sergio PEREZ', 'Charles LECLERC...
from __future__ import print_function,division import os import os.path import torch import torch.utils.data as data import torchvision import cv2 from utils.utils_trans import * from utils.utils_rw import * ## dataset class for single-view CNN training class singleDataset(data.Dataset): def __init__(self,data_...
# Generated by Django 3.2 on 2021-05-11 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('results', '0002_result_answers_selected'), ] operations = [ migrations.CreateModel( name='TempResultToStoreBetweenRequests', ...
from tkinter import * root= Tk() v1 = IntVar() v1.set('hello') Entry = Entry(root,textvariable=v1) Entry.pack(padx=5,pady=5) root.mainloop() print(v1.get())
from MailSendingScript import * from reddit_quote_extractor import * import time try: SendMail(get_reddit()) print("mission sucsesfull") except: CloseConnection() print("mission failed, better luck next time")
import mysql.connector import stdiomask class ConfigFileError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value)) def db_connect(configpath): try: ...
""" Declare and configure the models for the blog part """ from django.db import models from django.utils import translation from django.utils.translation import ugettext_lazy as _ from cms.api import Page from cms.extensions.extension_pool import extension_pool from cms.models.pluginmodel import CMSPlugin from ...co...
#!/usr/bin/env python # coding: utf-8 # This python module is for getting historical data from the # nse api and storing its volume info into a csv # this could be extended for further features and more data organization # but i don't plan to do so in any forseeable future # i maily made this because my dad asked me t...
from django.shortcuts import render def test(request): return render(request, 'ajax_api_container.html', context={'response':"Hey this is a test"});
import numpy as np import scipy.integrate import matplotlib.pyplot as plt plt.ion() from radtrans_integrate import radtrans_integrate rhoarr = np.zeros((300,3)) jarr = np.tile(np.array([1.,0.,0.,0.]),300).reshape(300,4) a = np.array([10.,4.,1.,7.]) a2 = np.array([5.,3.,2.,1.]) a2arr = np.tile(a2,150).reshape(150,4) aar...
import argparse from balancer.balancer import balance def main(): """A command line driver for calculating transactions""" parser = argparse.ArgumentParser(description="""Given a list of people and payments they made returns a list of t...
# Generated by Django 2.1.7 on 2019-03-30 16:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20190330_1648'), ] operations = [ migrations.AlterModelOptions( name='profilemodel', options={'permissions...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import Http404 from django.shortcuts import render, get_object_or_404, redirect from .forms import AddPostForm, EditPostForm, PostCommentForm, AddReplyForm from soci...
# 다양한 for문의 사용 print('다양한 for문의 사용') a = [(1,2),(3,4),(5,6)] print('a = {}'.format(a)) for(first, last) in a: print(first + last) print() # for문과 continue print('for문과 continue') marks = [90, 25, 67, 45, 80] number = 0 for mark in marks: number = number + 1 if mark < 60: continue print('...
estudiante2 = { 'nombre': 'Rene', 'edad': 25 } estudiante = { 'nombre': 'Ivan', 'edad': 25 } ''' print estudiante['nombre'] print estudiante['edad'] ''' estudiantes = [estudiante, estudiante2] print estudiantes[0]['nombre']
import numpy as np import json import os import argparse import yaml import pathlib parser = argparse.ArgumentParser(description="transfer a kifu yml to a kifu json.") parser.add_argument('--json_src', type=str, help="The source 'json' path to extract kifu from.", default="KifuAssembler/shao/1592212293837...
import time import json import threading import uuid from urllib.parse import quote from hashlib import sha1 import hmac import base64 from websocket import create_connection # pip install websocket-client import websocket appId = "TiD3p6" accessKeyId = "HGTBv4hFj9" accessKeySecret = "JZ5J39vFncv3j3453X2...
from UserInputTypes import PlayUnitCard, PlaySpellCard, PlayBuildingCard import pickle class Actions: def __init__(self, protocol): self.protocol = protocol def play_unit_card(self, player_id, card, location): puc = PlayUnitCard(player_id, card, location) ppuc = pickle.dumps(puc) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ close是关闭connect的操作。在close的时候会自动rollback到上一次commit的状态。 由于sqlite是单线程写, 多线程读的设计。所以对于任意多connec读操作, 有没有 close都没有任何影响。而由于只有单线程写。所以其实有没有close所造成的影响只跟 上一次commit有关。所以其实不需要担心在多个连接同时存在时, 每个连接的任务完成后 是否关闭, 而只要在合适的时候commit即可。 Ref: - http://stackoverflow.com/questions/9561832/what...
"""Two point statistic support. """ from __future__ import annotations from typing import Dict, Tuple, Optional, final, Union import copy import functools import warnings import numpy as np import numpy.typing as npt import sacc.windows import scipy.interpolate import pyccl import pyccl.nl_pt from ....modeling_tool...
import math import torch.nn as nn import torch.utils.model_zoo as model_zoo from .channel_selection import channel_selection __all__ = ['resnet50_official'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } def conv3x3(in_planes, out_planes, stride=1): "3x3 convolutio...
#!/usr/bin/python3 # Autolab autograder for CSCI 2467 (M. Toups / Fall 2018) import subprocess # to launch tests import re # regular expressions please import difflib # to show differences import signal # to make sure grading script doesn't get stopped by SIGTSTP import sys # list of trace files to test on tracefiles...
#!/usr/bin/env python3 import argparse import re import subprocess import json import os import sqlite3 from enum import Enum import hashlib class DBHandler: ''' Table gifs id int64 fname string text string start int64 # msec length it64 # msec tg_id int64 #...
from aiohttp import web from aiohttp.web import json_response from pb_admin_api.models.paste import Paste, PasteSchema schema = PasteSchema(many=True) class PastesView(web.View): async def get(request): cursor = request.app['db'].pastes.find( {}, { '_id': 1, ...
# _*_coding:utf-8_*_ # 创建用户 :chenzhengwei # 创建日期 :2019/7/24 下午9:48 from users.models import VerifyCode from django.core.mail import send_mail from MxShop.settings import EMAIL_FROM def send_email(email,host,code): email_title = "商城注册验证码" email_body= "验证码为:{0},有效期为五分钟。".format(code) send_status = send_ma...
from flask import Flask,request,url_for,render_template,session,g,jsonify,abort from blog import app import MySQLdb as mysql import config #@app.before_request #def connect_db(): # g.db=mysql.connect( # host=config.dbhost,user=config.dbuser, # passwd=config.dbpass,db=config.dbname # ) @app.route('/p...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Top Block # Generated: Tue Mar 27 10:45:15 2018 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platform.sta...
#Function used for model testing import numpy as np #Sigmoid & Relu function def sigmoid(Z): """ Implements the sigmoid activation in numpy Arguments: Z -- numpy array of any shape Returns: A -- output of sigmoid(z), same shape as Z cache -- returns Z as well, useful during backp...
#!/usr/bin/env python ''' ------------------------------------------------------------------------------------------------ Author: @Isaac Last Updated: 8 Nov 2018 Contact: Message @Isaac at https://forum.c1games.com/ Copyright: CC0 - completely open to edit, share, etc Short Description: This is a file to help displ...
#!/usr/bin/env python3 import os import urllib.request def get_content(link): content = "" hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} try: req = urllib.request.Request(link, headers=hdr) with urllib.reques...
#!/usr/bin/env python3 # -*-coding: utf-8-*- # Author : Christopher Lee # License: MIT License # File : master.py # Date : 2016-12-28 23:11 # Version: 0.0.1 # Description: description of this file. import os import sys from contextlib import contextmanager __version__ = '0.0.1' __author__ = 'Chris' @contextmana...
import re phone1 = '800-555-1212' phone2 = '555-1212' m = re.match('(\d{3}-){1,2}\d{4}', phone1) print(m.group()) m = re.match('(\d{3}-){1,2}\d{4}', phone2) print(m.group())
def sum_of_divisors(n): result = 0 divisor = 1 while divisor <= n: if n % divisor == 0: result += divisor divisor += 1 return result print(sum_of_divisors(1000))
li = [] fo = open("Photo.png", 'rb') for l in fo: li.append(l) fo.close() with open("Photo3.png","wb") as fo: for i in range (0,11): fo.write(li[i])
import cv2 import numpy as np def getContours(img): contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for cnt in contours: area = cv2.contourArea(cnt) print(area) if area > 500: cv2.drawContours(imgContour, cnt, -2, (255, 0, 0), 3) ...
#-*- coding:utf8 -*- import datetime from django.db import models from shopback.base.fields import BigIntegerAutoField from shopback.signals import user_logged_in import logging logger = logging.getLogger('django.request') DEFAULT_GROUP_NAME ='default' class ValidUserManager(models.Manager): def get_query_set(sel...
import numpy as np import os from pysph.sph.basic_equations import IsothermalEOS from pysph.sph.gas_dynamics.basic import ScaleSmoothingLength from pysph.tools.geometry import get_2d_block from pysph.base.utils import get_particle_array from pysph.base.kernels import CubicSpline, QuinticSpline from pysph.sph.equation...
#!/usr/bin/env python import os import sys import inspect import re import argparse import random from Bio import SeqIO from heapq import nlargest parser = argparse.ArgumentParser(description=""" Description ----------- ...
import time import json import logging import threading from bs4 import BeautifulSoup from selenium import webdriver from urllib.request import urljoin import os.path import sys import time import utilities from company import HomestarCompanyInfo homestars_url = "https://www.homestars.com/" def get_companies_urls(b...
""" Test the routes that show results of predictive models """ import pytest from .conftest import check_for_docker DOCKER_RUNNING = check_for_docker() # use the testuser fixture to add a user to the database @pytest.mark.skipif(not DOCKER_RUNNING, reason="requires docker") def test_user(testuser): assert True ...
# compare_lists.py # # function eval() to turn the strings into lists, and return a sorted list # holding elements found in both lists. # Usage: # % python compare_lists.py # # Himanshu Mohan, Oct 29, 2019 from typing import List def compare_lists(s1: str, s2: str) -> List: "What items are on both lists?" ...
print("Let's practice everything.") print('You\'d need to know \'bout escapes with \\ that do:') print('\n newlines and \t tabs') poem = """ \tThe lovely world with logic cannot discern \n the needs of love nor comprehend passion from the institution\n\t where this is none. """ print("------------") print(poem) prin...
import random #from time import sleep import myModule from oscilloscope import Osc # adjust window_sec and intensity to improve visibility osc = Osc(window_sec=10, intensity=1) @osc.signal def increasing_signal(state): pullData = open("my_file.txt","r").read() dataArray = pullData.rspilt("/n") for eachline ...
import os import re from process_header import find_func, analyze_data ################## CHANGE HERE ONLY ################## # The name of module you want name_module = "adc_list" # name_driver = "stm_driver.h" # The path of repository ksdk_path = "e:/C55SDK/sdk_codebase/" # Type of module, this depends on th...
#!/usr/bin/python #\file run_command.py #\brief certain python script #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Jun.10, 2015 import subprocess, os if __name__=='__main__': print 'Run-1' os.system('''qplot -x 'sin(x)' ''') print 'Done-1' print 'Run-2' #subprocess.call('''qpl...
class Solution: def longestValidParentheses_dp(self, s: str) -> int: # 状态:以该点结尾的最长有效括号的子串长度 dp = [0 for _ in range(len(s))] if len(s) < 2: return 0 if s[1] == ')' and s[0] == '(': dp[1] = 2 if len(s) == 2: return dp[1] for i in r...
import datetime, logging from sqlalchemy import create_engine, Column, Integer, String, Boolean, ForeignKey, ARRAY, Sequence, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class vAcctManagement(Base): __tablename__ = 'v_dp_account' account_uid = Column(String, prim...
import turtle starSize = eval(input('Enter the size of the star: ')) cir = ['red', 'green', 'blue', 'yellow', 'purple'] turtle.pensize(4) turtle.pencolor('black') turtle.penup() turtle.setpos(-90, 30) turtle.pendown() turtle.pencolor(cir[0]) turtle.forward(starSize) turtle.right(144) turtle.pencolor(cir[1]) turtle...
from django.urls import path from . import views urlpatterns = [ path('',views.index), path('allpostcommunity', views.allpostcommunity), path('login', views.login), path('logout', views.logout), path('register',views.register), path('posts/<int:id>/', views.showposts), path('addpost',...
"""merging two heads Revision ID: 34e14ce1bdb5 Revises: eae8a2cd9858, aa73e6cd5d62 Create Date: 2021-08-18 21:01:44.648032 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '34e14ce1bdb5' down_revision = ('eae8a2cd9858', 'aa73e6cd5d62') branch_labels = None depen...
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer import math from auxiliary import bitfield def add(k, n): ''' Generates a quantum circuit that adds k to n qubits where represents q[0] the less significant qubit''' q = QuantumRegister(n) qc = QuantumCircui...
from tkinter import * from io import open """ Creado por: Isabela Caceres Palma, Carlos Eduardo Alvarez Cabrera y Esteban Hernandez. Descripcion: El siguiente programa fue diseñado e implementado con el objetivo de permitirle al usuario verificar la consecuencia a causa de sus decisiones en el...
#!/usr/bin/env python from abc import ( ABCMeta, abstractmethod ) import asyncio from typing import ( Callable, Dict, List, ) from hummingbot.core.data_type.order_book import OrderBook class OrderBookTrackerDataSource(metaclass=ABCMeta): def __init__(self, trading_pairs: List[str]): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -* import unittest import os import shutil import sqlite3 import chzip class ResourceInstallTestCase(unittest.TestCase): def setUp(self): self._download_dir = os.path.join(os.path.dirname(__file__), '__tmp_res') ...
##TODO(developer): Uncomment and set the following variables project_id = 'aiot-fit-xlab' compute_region = 'us-central1' model_id = 'TCN7656632053749434671' # file_path = '/local/path/to/file' from google.cloud import automl_v1beta1 as automl automl_client = automl.AutoMlClient() # Create client for predi...
import os TEST_FULL = os.environ.get('REGIONAL_TEST_FULL', 'false') if TEST_FULL.lower() in ('1', 'true', 'on', 'yes'): from .test.full import *
#!/usr/bin/env python # -*- coding: utf-8 -*- """ msseg.experiment.default_configs Author: Jacob Reinhold (jacob.reinhold@jhu.edu) Created on: Jul 03, 2020 """ __all__ = ['default_lightningtiramisu2d_config', 'default_lightningtiramisu3d_config'] from pytorch_lightning.utilities.parsing import AttributeDi...
# coding=utf8 ''' date = '2015/08/27 10:22 AM' author = 'yzimhao' ''' import cPickle from redis import Redis from configs import settings rd = Redis(host=settings.REDIS_SERVER_IP, port=settings.REDIS_SERVER_PORT, socket_timeout=300) def set(k, val, ttl=-1): val = cPickle.dumps(val) if ttl > 0: r = ...
from django.db import models from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.http import JsonResponse, HttpResponse from django.utils.dateformat import DateFormat from MetFilabApp.utils.DateTimeDjangoJSONEncoder import DateTimeDjangoJSONEncoder from Me...
from rest_framework import serializers import random from products.models import Product, Product_Batch, Product_Type, Package_Type class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'product_name', 'product_description', 'company'] class PackageTyp...
from django.shortcuts import render from .models import * # Create your views here. def index(request): return render(request, 'inicio.html') def funcion (request): numero = request.GET['numero'] Usuarios = Usuario.objects.all() Doctors = Doctor.objects.all() Nutriologos = Nutriologo.objects.a...
#%% displayHelper %cd ".." from displayhelper import * #%% func def funcname(parameter, default_param=10, default_2_param=None): """This func execute a statement.""" statement(parameter) if default_2_param is not None: statement(default_param) funcname(True) funcname(True, 30, "ABC")...
import paho.mqtt.client as mqtt import time ########## def on_message(client, userdata, message): print "message received " ,str(message.payload.decode("utf-8")) print "message topic=",message.topic print "message qos=",message.qos print "message retain flag=",message.retain ######## broker_address = "192.168.1....
from rest_framework import serializers from jobBoard.models import Job, Job_comment from accounts.api.serializers import AuthorSerializer from GlobalModels.api.serializers import LocationSerializer class JobSerializer(serializers.ModelSerializer): # due_date = serialiers.DateTimeField(format=None, input_f...
# Generated by Django 2.1.7 on 2019-04-01 00:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0008_auto_20190401_0030'), ] operations = [ migrations.AlterField( model_name='prof', name='biography', ...
from adapters.contact_adapter import ContactAdapter from adapters.generic.motion_sensor import MotionSensorAdapter from adapters.generic.smoke_sensor import SmokeSensorAdapter from adapters.generic.temp_hum_sensor import TemperatureHumiditySensorAdapter as TempHumAdapter from adapters.generic.water_leak_sensor import W...
from flask import Flask,render_template,request,jsonify,redirect,send_file from flask import request import requests import json from flask_restful import Resource, Api, reqparse import string from flask_cors import CORS health=1 app = Flask(__name__) CORS(app) @app.route('/api/v1/_count',methods=['GET']) def count():...
from functools import reduce class Solution: def superPow(self, x, y): """ :type a: int :type b: List[int] :rtype: int """ def quick_algorithm(a, b, c): a = a % c ans = 1 while b != 0: if b & 1: ...
from PyQt5 import QtWidgets from PyQt5.QtCore import Qt class ui_SurveyMod: def setupUi(self, window): window.setObjectName('SurveyMod') window.setWindowTitle('SurveyMod') window.resize(400, 600) self.widget = QtWidgets.QWidget() self.layout = QtWidgets.QVBoxLayout(self.wi...
minutes = input('Input the minutes: ') int_minutes = int(minutes) houres = str(int(int_minutes / 60)) minute = str(int_minutes % 60) print(houres + ':' + minute)
import torch from torch import nn from torch.nn import functional as F import numpy as np from .multilayer import FCLayer, VariableModel class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, drop_rate = 0, activation_func = nn.LeakyReLU): super(ConvLayer, self).__i...
# coding: utf-8 # In[10]: import numpy as np import h5py import gromacs import gromacs.formats import sys import mdtraj import sklearn.preprocessing # In[11]: FN = sys.argv[1] FRAME = int(sys.argv[2]) TOP = sys.argv[3] # In[12]: natoms = ('OP1', 'OP2', 'O1P', 'O2P', 'N4', 'N6', 'O4', 'O6', 'N7', 'N2', 'N3', '...
import json import time from hawkeye_test_runner import HawkeyeTestSuite, DeprecatedHawkeyeTestCase __author__ = 'chris' class SendAndReceiveTest(DeprecatedHawkeyeTestCase): """This test exercises the XMPP API by sending a message and ensuring that the side-effect caused by the message's receipt occurs. Doe...
import uuid import os import validators import sys from generate_php import generate_php url = sys.argv[1] if ( validators.url(url) ): code = uuid.uuid4().hex[:6] generate_php(url,code) print ( os.path.abspath(code+'.php') ) else: print('invalid url')
import keras from keras.datasets import mnist from keras.models import Sequential, load_model from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K import pickle import logging import os def load_preprocess(**kwargs): # load and preprocess MNIS...
#!env python3 # -*- coding: utf-8 -*- import pandas as pd import numpy as np df = pd.DataFrame.from_dict([ {'name': 'Albert Einstein', 'category':'Physics', 'year':'123', 'country':'abc'}, {'name': 'Marie Curie', 'category':'Chemistry', 'year':'456', 'country':'def'}, {'name': 'William Faulkner', 'cate...
from platypush.message.event import Event class NewWeatherConditionEvent(Event): """ Event triggered when the weather condition changes """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # vim:sw=4:ts=4:et:
import sys from cx_Freeze import setup,Executable import getpass import os, platform, psutil from win32api import * import hashlib import winreg def sys32_64(): system32 = os.path.join(os.environ['SystemRoot'], 'SysNative' if platform.architecture()[0] == '32bit' else 'System32') listtest_path = os.path...
from src.server import Server import argparse # Get the CLI args parser = argparse.ArgumentParser(description='Starts a web server serving files at the specifed location, on the specified port.') parser.add_argument('--path', dest='path', type=str, required=True, help='Absolute path to serve files ...