text
stringlengths
38
1.54M
from django.shortcuts import render, HttpResponse, redirect from indexapp.models import TBook,TShipping,TUser # Create your views here. import json class Book: def __init__(self,id,num): book=TBook.objects.get(id=id) self.id=id self.picture=book.product_image_path self.name=book.bo...
from palindrome import is_palindrome def ans(): sum_ = 0 for i in range(1000000): if ( is_palindrome(str(i)) and is_palindrome("{0:b}".format(i)) ): sum_ += i return sum_ if __name__ == '__main__': print(ans())
import socket as s import IPToolz as ip # print(dir(ip)) website = 'gbprat.com' #get local ip address print(ip.getlocal()) #get website ip address print(ip.getIP(website)) a = ip.getIP(website) #get ip type # print(ip.IPType(a)) #socket module using from here hostname = s.gethostname() #computer name a = s.gethos...
from django import forms from .models import Post ,Category choices=Category.objects.all().values_list('name','name') choices_list=[] for item in choices: choices_list.append(item) class PostForm(forms.ModelForm): class Meta: model=Post fields=('title','author','image','body') widgets={ 'title':forms.Text...
import pandas as pd import random class AP: def __init__(self, first_term,common_difference): self.a = first_term self.d = common_difference def nth_term(self,n): return self.a + (n-1)*self.d def sum_n(self,n): return (n/2)*(self.a + self.nth_term(n)) def print...
import os from pro_tes.config.config_parser import get_conf from pro_tes.config.app_config import parse_app_config # Source the WES config for defaults flask_config = parse_app_config(config_var='TES_CONFIG') # Gunicorn number of workers and threads workers = int(os.environ.get('GUNICORN_PROCESSES', '3')) threads = ...
#!/usr/bin/env python3 import json import re import sqlite3 import argparse from sqlite3 import Error from random import randint import requests import db from settings import DB_LOCATION, SLACK_WEBHOOK def create_db(): try: conn = sqlite3.connect(DB_LOCATION) print(sqlite3.version) except Error as e: ...
# -*- coding: cp1252 -*- import logging import os from subprocess import * import win32api import win32con def LeeRegistro(variable): try: keyHandle = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,"Software\\Genomica",0,win32con.KEY_ALL_ACCESS) try: ...
# # [77] Combinations # # https://leetcode.com/problems/combinations/description/ # # algorithms # Medium (41.34%) # Total Accepted: 146.9K # Total Submissions: 351.3K # Testcase Example: '4\n2' # # Given two integers n and k, return all possible combinations of k numbers out # of 1 ... n. # # Example: # # # Inp...
for m in range(len(Ddefect)): n = Ddefect[m,0] test = size(np.where(nni[n]<0)) if test>0: # Fix it by changing nnitol print n, test # Change nnitol[48,2] to 0, nnitol[48,3] to 2 # Change nnltoi[116,2] to 0 #change
import re SUBST_TEMPLATE_RE = re.compile( r'<!--\s*' + r'(' + r'((Template|Wikipedia|WP):)' + r'([\w\-\d\ ]{1,50})' + r')' + r'\s*-->', re.I) def extract(text): return (m.group(1).lower().strip() for m in SUBST_TEMPLATE_RE.finditer(text.replace("_", " ")))
"""Views for Django countries module""" from rest_framework import viewsets from .serializers import CountryGeometrySerializer, CountryDemographicSerializer from .models import Country class CountryGeometryView(viewsets.ModelViewSet): """View for Country geometries""" serializer_class = CountryGeometrySerial...
import tweepy from feedgen.feed import FeedGenerator import os import urllib import sys import config import urllib2 from lxml import html from collections import defaultdict import ssl from tinydb import TinyDB, Query db = TinyDB('db.json') ConsumerKey = config.twitter['ConsumerKey'] ConsumerSecret = config.twitter[...
import tensorflow as tf from model.utils.bimpm import layer_utils, match_utils from model.utils.qanet import qanet_layers from model.utils.embed import char_embedding_utils from loss import point_wise_loss from base.model_template import ModelTemplate from model.utils.esim import esim_utils from model.utils.slstm impor...
import xml.sax from xml.sax.handler import ContentHandler import sys class SALDOHandler(ContentHandler): def __init__(self, sk2ss): self.saldoSense = "" self.synset = "" self.sk2ss = sk2ss def startElement(self, name, attrs): if name == "Sense": self.saldoSense = ""...
from django.db import models class Users(models.Model): user_login = models.CharField(max_length=50) email = models.CharField(max_length = 200) password = models.CharField(max_length = 20) startDate = models.DateTimeField('date published') user_name = models.CharField(max_length = 100)
from django.core.urlresolvers import reverse from ..tests import MetricTest class LandfillDiversionViewsTest(MetricTest): def test_volume_garden_details(self): resp = self.client.get(reverse('landfilldiversion_volume_garden_details', kwargs=self.get_garden_details_...
# Component 2 - randomly generate numbers # randomly generate numbers between low and high import random LOW = 1 HIGH = 6 for item in range(1, 20): equation_numbers = random.randint(LOW, HIGH) print(equation_numbers, end="\t") equation_numbers2 = random.randint(LOW, HIGH) print(equation_numbers2, end...
#!/usr/bin/python # -*- coding: UTF-8 -*- import sqlite3 #导入驱动 conn = sqlite3.connect('test.db') # 连接数据库 不存在则自动创建 cursor = conn.cursor() # 创建游标 # 创建user表 cursor.execute("CREATE TABLE use (id VARCHAR(10) PRIMARY KEY, name TEXT)") cursor.execute("INSERT INTO user(id,name) VALUES (1,'Creaway')") # 添...
from meshgen.vector import Vector3 from meshgen.meshbuilder import MeshBuilder import numpy as np class CircleMesh: def __init__(self): self.radius = 10 self.angle_start = 0 self.angle_end = 360 self.direction1 = Vector3.up() self.direction2 = Vector3.right() self.t...
metadata = """ summary @ GNU rewrite of netcat, the network piping application homepage @ http://netcat.sourceforge.net/ license @ GPL src_url @ http://downloads.sourceforge.net/netcat/netcat-$version.tar.bz2 arch @ ~x86_64 """ depends = """ runtime @ sys-libs/glibc """ def configure(): conf("--prefix=/usr --mand...
# -*- coding: utf-8 -*- import os import sys import random import timeit import argparse import numpy as np from .lib.data_utils import Query, load_log, load_prop from .lib.utils import * def generate(fout, query, qid, cost, doc_id): fout.write('1 qid:{} cost:{} {}\n'.format(qid, cost, query._docs[doc_id][3])) ...
from app import db MODEL_FIELDS = ( 'model_id', 'model_type', 'model_params', 'model', 'transformer' ) class CurrentModel(db.Model): id = db.Column(db.Integer, primary_key=True) model_id = db.Column(db.String(20), index=True) model_type = db.Column(db.String(64)) model_params = db.Column(db.Strin...
''' Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] E...
from django.conf.urls import url from . import views urlpatterns = [ # User profiles url(r'^profile/$', views.profile, name='profile'), url(r'^profile/password/$', views.change_password, name='change_password'), url(r'^profile/user-key/$', views.userkey, name='userkey'), url(r'^profile/user-key/...
import sys import openpyxl import os def show_usage(): print('Wrong number of arguments!') print('Usage: python conv_merged_profits_to_gap_xls.py [batch dir_prefix] merged_profit_file.txt') print('Expected CSV-format: instance;method1;...;methodN;methodRef') def gaps_for_row(row): gaprow = [] fo...
from __future__ import absolute_import, print_function import argparse import getpass import inspect import os import pickle import sys from distutils.version import StrictVersion import cleverbot from cleverbot.migrations import migratables from cleverbot.utils import get_migrations class KwargsParser(argparse.Arg...
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 18:06:31 2020 @author: Hugo """ import numpy as np import matplotlib.pyplot as plt import fit import stim def plot_spike_tc(ax, all_spiketimes, lab, col, ls = '-') : mean_spiketrains = [] std_spiketrains = [] for tria...
from random import randint import numpy as np import random print('Memorice') print('') matrix = [] pair_of_cards = int(input('how many pair of cards do you want?: ')) print('') player1 = 0 player2 = 0 total_score = 0 turn = 1 #Crear lista que contiene los pares del total de numeros que piden los jugadores game_li...
import cv2 import numpy as np def main(): capture = cv2.VideoCapture(0) while True: ret, frame = capture.read() gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges_detec = cv2.Canny(gray_frame, 50, 250, apertureSize=5, L2gradient=True) hough_lines = cv2.HoughLines(ed...
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3,3,50) y1 = 2*x+1 y2 = x**2 plt.figure() plt.plot(x,y1) new_ticks = np.linspace(-1,10,6) plt.xticks(new_ticks)#new unit on aixis plt.yticks(new_ticks) ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis....
import re """Given a code from python,C or java. This code must be able to detect whether the given code is from what programming langugae by just using regular expressions. this also needs to be effective in space""" #define regular expressions for Java java = re.compile(r'import\s*java.?') java_one = re.compile(r'pub...
import pandas as pd import torch test_set_unscaled_ys = torch.tensor(pd.read_csv('../data/test_unscaled_ys.csv').values, dtype=torch.float)[torch.randperm(128)]
import multiprocessing as mp from time import time from progressbar import ProgressBar, Percentage, Bar, Timer, ETA, FileTransferSpeed def split_list(lst, nums): nums = max(1, nums) rows = len(lst) interval = round(rows / nums) lsts = [] for i in range(nums): s = i * interval if...
from rest_framework import serializers from .models import Etalon class EtalonSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Etalon fields = ["pk", "nodes", "links"]
from __future__ import print_function import imageio import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from sklearn.linear_model import LogisticRegression from six.moves.urllib.request import urlretrieve from six.moves import cPickle as pic...
import socket import threading import time ENCODING = "utf-8" class UDPManager(threading.Thread): def __init__(self, port: int, broadcastAddress:str, buffersize=10000) -> None: threading.Thread.__init__(self) self.broadcastAddress = broadcastAddress self.port = port self.bufferSiz...
''' This script takes the formatted CSV files and adds the papers from this file to the ORKG. The scripts handles creating the triples and distinguishes between resources/literals. Additionally, a comparison object is created, so each survey can be viewed directly from the ORKG user interface. ''' import requests f...
from django.apps import AppConfig class TypesmanageConfig(AppConfig): name = 'CMS.apps.typesManage'
""" Test palindromicity Ignore non alphanumeric characters and case Start at beginning and end Set to lowercase, skip if non-alpha numeric If any chars do not match, return false If we reach the middle, return true """ def test_palindrome(s): start = 0 end = len(s) - 1 while start < end: while s[s...
import google as gs from pyexcel_xlsx import get_data import os import os.path class Bot(object): def __init__(self, xlsx_src, sheet_name='Sheet1', offset=1, search_page_size=5, search_stop=1): self.xlsx_src = xlsx_src self.sheet_name = sheet_name self.offset = offset self.search_...
#from collections import deque from itertools import product #class Grid: # def __init__(self,m,p=None): # self.n = len(m) # self.matrix = m # self.parent = p # if self.parent == None: # self.h = 0 # else: # self.h = self.parent.h + 1 # def IsNull(self): ...
import unittest from graphbrain import * class TestHypergraph(unittest.TestCase): def setUp(self): self.hg = hypergraph('test.hg') def tearDown(self): self.hg.close() def test_close(self): self.hg.close() def test_name(self): self.assertEqual(self.hg.name(), 'test.hg...
from Tkinter import * class Kanvas: def __init__(self,raiz): self.canvas1 = Canvas(raiz, width=400, height=400, cursor='fleur', bd=10, bg='white') # self.canvas1.create_line(coord,fill='black') # proposta original # self.canvas1.pack() coord = [] # define coord como uma...
import math import logging import time import epics import atexit from epics import PV import qlCalc.utils logger = logging.getLogger(__name__) class CavityTask: """A class representing a notification that a cavity needs it's data processed and a new data request sent.""" def __init__(self, cavity_name, re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 5 18:04:52 2019 @author: ratul """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 5 11:18:27 2019 @author: ratul """ import torch, numpy as np from glob import glob from scipy import io from torch import nn #from trainMod...
def dfs(y, x, cnt, one): global ans if cnt >= ans: return if not one: ans = cnt return if y == 10: return if plate[y][x] and not visited[y][x]: for k in range(5, 0, -1): if paper[k - 1]: if check(y, x, k): paper[...
from flask import Flask, render_template, request, redirect, url_for from flask_bootstrap import Bootstrap from flask_wtf import Form from flask_sqlalchemy import SQLAlchemy from wtforms import TextField, StringField, SubmitField import os import glob #import sqlite3 as sql from werkzeug import secure_filename import t...
cCodeHead = \ """ /* Copyright(C) 2013, OpenOSEK by Fan Wang(parai). All rights reserved. * * This file is part of OpenOSEK. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either versio...
from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from rest_framework_jwt.views import obtain_jwt_token, ObtainJSONWebToken from rest_framework_jwt.views import refresh_jwt_token from rest_framework_jwt.views import verify_jwt_token from authentication.serializers....
import torch import torchvision import numpy as np import matplotlib.pyplot as plt import torch.nn as nn import torch.nn. functional as F import torch.optim as optim import os import sys batch_size = 100 learning_rate = 1e-3 max_epoch = 100 device = torch.device("cuda") num_workers = 5 load_epoch = -1 generate = Tru...
""" Example: Flux Envelope Analysis @Author: Kai Zhuang """ __author__ = 'kaizhuang' from framed.cobra.variability import production_envelope, flux_envelope from framed.io.sbml import load_sbml_model, CONSTRAINT_BASED from framed.model.fixes import fix_cobra_model import matplotlib.pyplot as plt ### Basic Setup SMA...
""" EJERCICIO 1 Crear una función recursiva para crear una nueva cadena que contenga sólo los caracteres alfabéticos y espacios de otra cadena. Se espera que lo resuelva mediante una función recursiva. Desarrollar un programa para ingresar frases hasta que sea vacía y para cada frase mostrar la cadena creada con la f...
#!/usr/bin/env python ''' Make diagnostic persistence plots based on 2MASS cutouts for WFC3/IR exposures in an APT file. ''' import os import astropy.table import astropy.io.fits as pyfits from collections import OrderedDict import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ OCIOマニュアルカスタムのためのパラメータを吐き出すよ。ゲロゲロ~。 """ import os import numpy as np import colour import color_convert as cc from scipy import linalg import imp imp.reload(cc) def get_to_aces_matrix_param(src_xy, src_white): dst_xy = cc.const_aces_ap0_xy dst_white = cc.co...
# Generated by Django 2.1.7 on 2019-03-17 06:45 import common.models from django.db import migrations, models import media_upload.models import ulid.api class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Image',...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 import datetime import eav from django.utils.translation import ugettext as _, ugettext_lazy as __ from django.db import models from django.utils.datastructures import SortedDict from django.db.models.signals import m2m_changed from _indicato...
# -*- coding: utf-8 -*- # This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License import numpy as np from collections import defaultdict from sklearn.metrics im...
''' Created on Oct 1, 2014 @author: arya iranmehr ''' from cssvm_tools import * from time import time path='/home/arya/workspace/cssvm/datasets/' def main(): start=time() param={'measure':'Risk', 'verb':1} param['dataset_name']='german' param['dataset']=path + param['dataset_name'] param['train_y'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dataclasses import dataclass from typing import Any class Pila: @dataclass class _Nodo: dato: Any sig: '_Nodo' __slots__ = ['_tope', 'tamanio'] # Puntero al tope # Inicializo mi pila vacia o con una iterable, osea, le puedo pasar un...
import pandas as pd pd.set_option('display.max_columns', None) import numpy as np from numpy import mean, std from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt print('PART C-----------------------------------------------------------------------------------...
import numpy from PIL import Image,ImageDraw from pylab import * dpi=300 mm2pixel=dpi/25.4 def wheel_encoder_template(): outer_size = 20#mm shaft_size = numpy.array([3.5, 5.0]) width=5 template = numpy.zeros(tuple(2*[outer_size*mm2pixel+1]), dtype=numpy.uint8) template[0,:]=1 template[-1,...
# Log a single temperature record from the json data, create a graph to go with it. import requests import logging import json from datetime import datetime from matplotlib import pyplot as plt from matplotlib.pyplot import figure from dbconnector import DBConnector from const import Const from config import Config c...
#Python program to check if the input number is odd or even. #Solution: number = int(input("Enter the input number to check:")) def checker(number): if number % 2 == 0: return True return False result = checker(number) if (result): print(number,"is an even number.") else: prin...
import pandas as pd from matriz import (matrizCorreta, matrizEscadinha, matrizEscadinhaEstendida, matrizEscadinhaReversa, matrizInutilizavel_1, matrizInutilizavel_2, matrizEscadinhaNegativo) def isescadinha(dt_frame): rows = [i for i in range(len(dt_frame)-1)] columns =...
from Graph import Graph import copy class BipartiteGraph(Graph): # Двудольный граф def __init__(self, matrix, V1=None, V2=None): super().__init__(matrix) if V1 is None and V2 is None: self.V1 = [] self.V2 = [] self.__bipartite() else: self...
from django.urls import path from .views import myproduct_page, myproduct_detail,product_list,addtocart,showcart, getProducts, search, getdata urlpatterns = [ path('info', myproduct_page), path('detail/<str:pid>', myproduct_detail), path('products', product_list), path('addtocart', addtocart), path...
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
from django.shortcuts import render from django.http import HttpResponseRedirect from .models import user_note # Create your views here.
import pytest from tartiflette import Directive, Resolver, create_engine _SDL = """ directive @issue453Directive on SCHEMA type Query { fieldA: Int } schema @issue453Directive { query: Query } """ @pytest.mark.asyncio async def test_issue453(random_schema_name): @Directive("issue453Directive", schem...
"""Simplified interface to the CDK parser via JPype Extracted from Cinfony source code: https://github.com/cinfony/cinfony/blob/master/cinfony/cdk.py""" from jpype import * import os if not isJVMStarted(): _jvm = os.environ['JPYPE_JVM'] if _jvm[0] == '"': # Remove trailing quotes _jvm = _jvm[1:-1] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import ast import redis import sys import traceback import xmlrpclib from configobj import ConfigObj from subprocess import Popen, call, check_call from validate import Validator class ConfObjClass(): def __init__(self, configfile, configspec): self.configfile = conf...
def subArraySum(arr, x): if not arr: return None i1 = 0 i2 = 0 s1 = arr[0] while i1 < len(arr): if s1 == x: return [i1, i2] if s1 < x: i2 += 1 if i2 < len(arr): s1 += arr[i2] else: s1 -= arr[i1] ...
""" Starter code for the problem "Cart-pole swing-up". Author: Spencer M. Richards Autonomous Systems Lab (ASL), Stanford (GitHub: spenrich) """ import numpy as np from scipy.integrate import odeint import jax import jax.numpy as jnp import matplotlib.pyplot as plt from animations import animate_cartp...
#This Program will make use of the SenseHat Temperature Sensors #This Program will make use of the SenseHat Display / Joysticks #This Program was modified code retrieved from an online source - electromaker.io tutorials from sense_hat import SenseHat import time sense = SenseHat() red = (255, 0, 0) green = (0, 255...
#======================================================================== # Args #======================================================================== import sys try: model_type=sys.argv[1] except IndexError: model_type='lgb' try: learning_rate = float(sys.argv[2]) except IndexError: learning_rate =...
# Copyright 2021 Samsung Electronics Co., Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range, ) author = 'Your name here' doc = """ Your app description """ class Constants(BaseConstants): name_in_url = 'main' players_per_group = None num_r...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-01-31 12:28 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reference_books', '0012_bhm'...
"""Shift string characters by k position. letter should wrap around, z shifts one return a. """ def caesarCipherEncryptor(string, key): shiftedString = "" for char in string: unicode = (ord(char) - ord('a') + key) % 26 + ord('a') shiftedString = shiftedString + chr(unicode) return shiftedS...
from network import WLAN from mqtt import MQTTClient import machine # from machine import Pin, Timer import ujson import time # import gc import ubinascii # from deepsleep import DeepSleep # import deepsleep from pysense import Pysense from LIS2HH12 import LIS2HH12 from SI7006A20 import SI7006A20 from LTR3...
def sumtarget(arr, target): nums = set(arr) for num in arr: if target - num in nums: return (num, target - num) return None def sum3target(arr, target): arr = sorted(arr) for i in xrange(len(arr) - 2): start, end = i + 1, len(arr) - 1 while start < end: ...
#MenuTitle: Set Spacing Groups # -*- coding: utf-8 -*- # Created by Kyle Wayne Benson December 10, 2017 __doc__=""" Set Spacing Groups to spacing.extension if .extension is added """ import GlyphsApp Font = Glyphs.font FontMaster = Font.selectedFontMaster selectedLayers = Font.selectedLayers selectedLayer = selectedL...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist from std_msgs.msg import Int32MultiArray import time import RPi.GPIO as GPIO from AlphaBot2 import AlphaBot2 from TRSensors import TRSensor import Infrared_Obstacle_Avoidance as IRSensor # DEBUG def printLightSensors(res): print("leftmost: %d...
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y1 = 2 * x + 1 y2 = x ** 2 plt.figure(num=3, figsize=(8, 5)) # 设置X轴范围 plt.xlim((-1, 2)) # 设置Y轴范围 plt.ylim((-2, 3)) # 设置XY轴标题 plt.xlabel(u'价格', fontproperties='SimHei') plt.ylabel(u'利润', fontproperties='SimHei') # 设置刻度 new_st...
import random def guessGame(a, b, actual): guess = int(input(f"Guess a number between {a} and {b}\n")) nguess = 1 while guess != actual: if guess < actual: guess = int(input(f"Enter a bigger number\n")) nguess += 1 else: guess = int(input(f"Enter a smalle...
import re from datetime import datetime s=""" A|MAN GLB US|Payroll|MAN:Payroll Accrual|11/08/2019|USD|||784.90| |||||||| ||||||||NOV-2019|00706|611010|1006|000|106|00000|0000||||Accrual WBW191108|| ||||PR20191102 WBW191108 CAI ABA AREN200 E REG Regular Earnings|20200604185459486816|||||||||||||||||||| ...
import json import logging import os import re from collections import OrderedDict from threading import RLock CFG_PATH = '/opt/kirale/' CFG_FILE = CFG_PATH + 'kibra.cfg' # Default configuration CFG = {'dongle_name': 'Test', 'dongle_commcred': 'KIRALE'} # User configuration read from file CFG_USER = {} MUTEX = RLock(...
import init import tensorflow as tf import hparam as conf import sessionWrapper as sesswrapper import data_process_specialList as dp import model_zoo as mz import loss_func as l import random import math import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm tv_gen = dp.train_validation_generaotr()...
from app import app, db from flask import request, redirect from app.models import User from flask_login import current_user, login_user, logout_user, login_required REGISTER_ERROR = {'in_use': 'The username or the email is already in use', 'empty_fields': 'You must fill all the fields' ...
def twosum(nums, target): dic = {} for i in range(len(nums)): the_complement = target - nums[i] if the_complement in dic and the_complement != nums[i]: return [dic[the_complement],i] dic[nums[i]] = i
from core.tests import LoginTestCase from chat.routing import application from channels.testing import WebsocketCommunicator from channels.db import database_sync_to_async from core.utils import random_string class WSTest(LoginTestCase): users_count = 2 async def _subscribe(self, conn, creds): token ...
import cv2 import numpy as np # convolve function def convolve(image, kernel): # parameter value -1 is ddepth the desired depth of destination image # -1 means output image has same depth as source image return cv2.filter2D(image, -1, kernel) # step 1 read the input image image = cv2.imread("./images/b...
# -*- coding: utf-8 -*- import unittest import time from ._mouse_event import MoveEvent, ButtonEvent, WheelEvent, LEFT, RIGHT, MIDDLE, X, X2, UP, DOWN, DOUBLE from keyboard import mouse class FakeOsMouse(object): def __init__(self): self.append = None self.position = (0, 0) self.queue = No...
import matplotlib.pyplot as plt def form(i): delta = 1.2 fs = 13 space = 10 objective = r'$\min \ \ W$' plt.text(-1.0, i, objective, fontsize=fs) subjects = r'$\sum_{P: e \in P} x_P \leq W,$' plt.text(0.5, i - delta * 1, subjects, fontsize=fs) subjects = r'$e\in E,$' plt.text(0.5 ...
# recursive call # recursive01.py # 재귀함수 def hello(cnt): # 재귀 종료 조건 if cnt == 0: return print('hell0, recursive', cnt) cnt = cnt - 1 hello(cnt) hello(10)
def my_function(name): print("Hello " + name) def add_five(x): return x+5 # -------------------------------- num = add_five(10) print(num)
from datetime import timedelta from zeus import factories from zeus.constants import Status from zeus.tasks import cleanup_artifacts from zeus.utils import timezone def test_cleanup_artifacts_current(mocker, db_session): artifact = factories.ArtifactFactory.create(status=Status.finished) cleanup_artifacts()...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm class WholePainting(object): def __init__(self): self.data=pd.read_excel('WashedData.xls') def pairplot(self):#绘制四个变量的矩阵图 data=self.data sns.set_style('darkgrid') ...
#!/usr/bin/env python # # Copyright 2008 Doug Hellmann. # """VagueTextRecord format parser """ from pyparsing import * # Import system modules import datetime import fileinput import logging import time # Import local modules # Module log = logging.getLogger(__name__) def show_parse_action(f): """Decorator ...