text stringlengths 8 6.05M |
|---|
from flask import request
from projectmanager.app import app
from projectmanager.mongodb import (
project_collection
)
from projectmanager.dao.project import (
ProjectMongoDBDao
)
from projectmanager.utils.handle_api import handle_response, verify_request
META_SUCCESS = {'status': 200, 'msg': '修改成功!'}
@app... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
from multiprocessing import Manager
from multiprocessing.pool import Pool
import multiprocessing as mp
import time
import torch
class MultiPro():
def __init__(self, cuda_num=3, fun=None):
self.index = []
self.lists = []
for i ... |
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
import json
class Folders(QTableWidget):
def __init__(self, parent=None):
super(Folders, self).__init__(parent)
self.setColumnCount(2)
self.setHorizontalHeaderLabels(["Subject", "Folder"])
self.update_table()
def updat... |
#!env python3
# -*- coding: utf-8 -*-
print(complex(real=3, imag=5)) # キーワード引数
print(complex(**{'real': 3, 'imag': 5})) # キーワード引数
print(complex(3, 5)) # 位置引数
print(complex(*(3, 5))) # 位置引数
args = [1, 2, 3]
kwargs = {'sep': '-', 'end': '.'}
print('<<< ', end='')
print(*args, **kwargs)
print(' >>>')
# 任意個数の位置引数
... |
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
def load_dataset():
train_dataset = h5py.File('train_catvnoncat.h5', "r")
train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features... |
def main():
#write your code below this line
intList = []
cardinality=0
while(True):
number = int(input())
if(number==-1):
break
intList.append(number)
sum = 0
for i in range(len(intList)):
sum+=intList[i]
cardinality+=1
print("Average: %s"%(sum/cardinal... |
#!/usr/bin/env python3
"""Parse command line options and arguments for the Logic Simulator.
This script parses options and arguments specified on the command line, and
runs either the command line user interface or the graphical user interface.
Usage
-----
Show help: logsim.py -h
Command line user interface: logsim.p... |
# A telephone directory has N lines on each page, and each page has exactly C columns. An entry in any column has a name with the corresponding telephone number. On which page, column, and line is the X th entry (name and number) present? (Assume that page, line, column numbers, and X all start from 1.)
# prompt user ... |
from model.model_base_class import ModelBaseClass
from sklearn.linear_model import LinearRegression
# class LinearRegression(ModelBaseClass)
#
# def __init__(self,verbose=False):
# super().__init__(verbose=verbose)
if __name__ == '__main__':
mbc = ModelBaseClass()
train = mbc.get_df('model_data'... |
import scrapy
from bs4 import BeautifulSoup
from ..items import AppledailyItem
import re
import requests
class appledaily(scrapy.Spider):
name = 'appledaily'
#重写start_url
def start_requests(self):
print("网速较慢,耐心等待!")
for i in range(1,4):
self.url = 'https://tw.video.appledaily.... |
import numpy as np
# Lowest number to possibly generate
low = 5
# One avobe the largest number to possibly generate
high = 11
# Dimensions of the array
size = (3, 4)
np.random.randint(low, high, size)
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Admin
#
# Created: 02/11/2017
# Copyright: (c) Admin 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
#check size o... |
# 保存
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
'Content-Type': 'application/json; charset=UTF-8'
}
data = {
"projectDeclare": {
"id": "f4001645-c27e-4e3b-92ee-157... |
"""determination of order of evaluation of the problem"""
least_precedence = 1
supported_operations = {
'+': [1, lambda a, b: a + b],
'-': [1, lambda a, b: a - b],
'/': [0, lambda a, b: a / b],
'*': [0, lambda a, b: a * b]
}
def determine_order_of_operation(operands, operations):
# reduce to simp... |
# -*-coding:utf-8-*-
from flask import g
from flask_restful import reqparse
from albumy.api.albumy.const import VISIBLE_PUBLIC, TYPE_DEFAULT, VISBLE_PRIVATE
from albumy.common.restful import RestfulBase, success_response, raise_401_response
from albumy.extensions import login_required, db
from albumy.models import Alb... |
import uuid
from http import HTTPStatus
from flask_restful import Resource, reqparse, fields, marshal
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_required,
jwt_refresh_token_required,
get_jwt_identity,
get_raw_jwt
)
from flask import current_app, request, make_response,... |
def ukurNilai (val) :
kriteria = ""
if val >= 88 :
kriteria = "A"
if val >= 77 and val < 88 :
kriteria = "B"
if val >= 60 and val < 77 :
kriteria = "C"
if val >= 45 and val < 60 :
kriteria = "D"
if val < 45 :
kriteria = "E"
return kriteria |
from django.conf.urls import url
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('login/', views.login, name='login'),
path('signup/', views.signup, name='signup'),
path('signup/usernamecheck/', views.checkusernameexists, name='usernamecheck')... |
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
result = 0
i = 10
while result == 0:
no_remainder = True
# Doing it backwards because the divisions w... |
#!/usr/bin/env python
from scriptine import log, path
from scriptine.shell import sh
import yaml
import datetime
import time
config = yaml.safe_load(open("config.yml"))
def mysqldump():
for DB in config['databases']:
# check/fix paths in BACKUP_DIR - remove trailing slash
BACKUP_DIR = config['rs... |
#!/usr/bin/env python3
"""
Test for Always identifier
"""
import datetime
import unittest
from base_test import PschedTestBase
from pscheduler.limitprocessor.identifier.always import *
class TestLimitprocessorIdentifierAlways(PschedTestBase):
"""
Test the Identifier
"""
def test_data_is_valid(self)... |
import youtubetomp3.core.utils as Utils
import youtubetomp3.libs.youtube_dl as youtube_dl
import os
from youtubetomp3.const.constants import _Const
CONST = _Const()
class Downloader():
"""docstring for Downloader"""
def __init__(self, link, user):
self.link = link
self.user = user
... |
'''
Fetch hosts from github.com/racaljk/hosts and replace the system hosts.
'''
import platform
import os
import re
from datetime import datetime
import requests
FETCH_URL = 'https://raw.githubusercontent.com/racaljk/hosts/master/hosts'
MATCH_PATTERN = re.compile(
r'(.*?# Last updated: )(\d+)-(\d+)-(\d+)(.*?# ... |
import os
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
try:
import matplotlib.pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
import networkx as nx
import numpy as np
import queueing_tool as qt
TRAVIS_TEST = os.environ.get('TRA... |
from collections import OrderedDict
from warnings import warn
import numpy as np
from scipy.optimize import leastsq
from .eos import EOSFactory
def calculate_rmse(f, xdata, ydata, p):
return np.sqrt(np.average((ydata - f(xdata, *p)) ** 2))
class EOSFitting:
def __init__(self, eos_name):
self.eos = E... |
#Caleb Lewandowski
#February 21, 2021
#Module 9.3 Assignment
#Purpose: To insert, update, and delete a record.
#Import classes.
import mysql.connector
from mysql.connector import errorcode
#Create dictionary config.
config = {
"user": "pysports_user",
"password": "12345678",
"host": "127.0.0.1",
"data... |
token='368295679:AAFYu2zIKKDP9DxeL7CPqumOGKEpxz5HE2g'
|
# Test Case 1:
# The following variables contain values as described below:
# balance - the outstanding balance on the credit card
# annualInterestRate - annual interest rate as a decimal+
balance = 4773
annualInterestRate = 0.2
# aprxint = balance * annualInterestRate
# totalpay = balance + aprxint
# aprxmonthlypay =... |
#!/usr/bin/env python
# coding: utf-8
import os
import re
import pickle
import time
import copy
from functools import partial
from pathlib import Path
from collections import defaultdict
import seaborn as sns
import pandas as pd
import numpy as np
import scipy
from scipy import signal
from tqdm.autonotebook import t... |
#!/usr/bin/env python
for i in range(0, 512):
freq = i * 43
seperator = "HZ\t"
if i <= 232: seperator = "HZ\t\t"
print("#define FREQ_"+ str(freq) + seperator + str(i));
|
a=int(input())
for i in range(1,a+1):
b=10*i
if b>a:
print(b)
break
|
from dotenv import load_dotenv
from pathlib import Path
from mkmsdk.mkm import Mkm
from mkmsdk.api_map import _API_MAP
import csv
import os
import psycopg2
import pandas as pd
import math
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path, verbose=True)
df = pd.read_json('normalized_buylists.json', orien... |
class Pyceptron:
def __init__(self, dimension=2):
self._dimension = dimension
self._points = []
self._weights = [0] * (dimension + 1)
self._steps = 0
def populate(self, points=None):
if points != None:
self._points += points
return self._points
def weights(self, weights=None):
if weights != N... |
import tqdm
import glob
import os
import pdb
from tf_pose import common
import numpy as np
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
import subprocess
import pandas as pd
video_path = '/newdisk/AVEC2018/downloaded_dataset/recordings/recordings_video'
videos = s... |
import datetime
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.views import generic
from django.urls import reverse
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import Auto... |
"""
Script for loading Bhutan and Thimphu data into calibration targets and default.yml
"""
import pandas as pd
from sqlalchemy import DATE
from pathlib import Path
from autumn.settings import PROJECTS_PATH
from autumn.settings import INPUT_DATA_PATH
from autumn.core.utils.utils import update_timeseries
from autumn.m... |
import os
# To-adjust: bv-app file path
# if add app inside the app folder, can use this path:
# '.\\features\\app\\bvDev.apk'
app_path = os.path.abspath('D:\\bddTest\\bvDev.apk')
# To-adjust: the connection string info
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'... |
import json
import itertools
import logging
import re
import flask
from flask import request
from flask.ext.cache import Cache
import requests
import rethinkdb as r
import db
import util
try:
import secrets
_HIPCHAT_TOKEN = secrets.HIPCHAT_TOKEN
_HIPCHAT_ROOM_ID = secrets.HIPCHAT_ROOM_ID
except ImportErr... |
"""
URL configuration to display homepage and mentions page.
"""
from django.urls import path
from pages.views import HomePageView, MentionsView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('mentions/', MentionsView.as_view(), name='mentions'),
]
|
import numpy as np
import ot
import matplotlib.pyplot as plt
# 1D gauss
n = 100 # nb bins
# bin positions
x = np.arange(n, dtype=np.float64)
# Gaussian distributions
a1 = np.zeros(n) # m= mean, s= std
a2 = np.zeros(n)
a1[10:20] = 1
a2[60:70] = 1
a1 = a1 / sum(a1)
a2 = a2 / sum(a2)
# creating matrix A containing all... |
# Generated by Django 2.2.6 on 2019-10-21 06:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('techei', '0011_institutionprofile_state'),
]
operations = [
migrations.AddField(
model_name='individualprofile',
nam... |
#LC 8
import sys
class Solution(object):
def atoi(self, str):
# pull max/min value for boundary checking usage
MAX_INT = 2**31-1
MIN_INT = -2**31
#striping input
str = str.strip()
if not str:
return 0
# make sure we take care of negative sign
... |
import pytest
from freshdesk.v1.models import Comment
@pytest.fixture
def ticket(api):
return api.tickets.get_ticket(1)
def test_comments_list(ticket):
assert isinstance(ticket.comments, list)
assert len(ticket.comments) == 1
assert isinstance(ticket.comments[0], Comment)
def test_comment_str(tic... |
from sklearn.linear_model import LogisticRegression
import LoadData
import numpy as np
import math
import random
def prepareData(X, Y, seed=None):
np.random.seed(seed)
numPredictors = X.shape[1]
numRuns = X.shape[0]
trainingIdxs = np.random.choice(numRuns, numRuns, replace=False)
trainingPercentage... |
from base64 import b64encode
from uuid import uuid4
from collections import namedtuple
import transaction
from onegov.api.models import ApiKey
from onegov.api.token import jwt_decode, get_token
from onegov.core.utils import Bunch
from onegov.user import UserCollection
from freezegun import freeze_time
def test_token_... |
from django.contrib import admin
from .models import BackupDirectory, BackupTask
admin.site.register(BackupDirectory)
admin.site.register(BackupTask)
|
r1 = int(input('Valor da reta 1: '))
r2 = int(input('Valor da reta 2: '))
r3 = int(input('Valor da reta 3: '))
if (r1 + r2) > r3 and (r2 + r3) > r1 and (r1 + r3) > r2:
print('{}, {} e {} podem formar um triangulo'.format(r1, r2, r3))
else:
print('{}, {} e {} nao podem formar um triangulo'.format(r1, r2, r3))
|
"""
冒泡排序:始终是相邻的两个元素相比较,如果前面的比后面大就交换两个位置的值
"""
def bubble_sort(aList):
n = len(aList)
for j in range(n - 1):
b = False
for i in range(n - j - 1):
if aList[i] > aList[i + 1]:
aList[i], aList[i + 1] = aList[i + 1], aList[i]
b = True
if b == Fals... |
#! /usr/bin/python
import pygame
from pygame import *
from time import sleep
WIN_WIDTH = 256*3
WIN_HEIGHT = 224*3
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
moveNext = False
movePrev = False
done = False
DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
newX = 0
newY =... |
from flask import Flask, request, session, render_template
import json
import logging
import redis
import os
from logging.handlers import RotatingFileHandler
from datetime import datetime
from rq import Queue
from postworker import enqueue_work
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
app = Flask(__name__)
app.config['SESSION... |
from datetime import date
import datetime
from datetime import datetime
import time
import pandas as pd
import numpy as np
def hours_current_balance(nurse_or_not):
if nurse_or_not == 'yes':
nurse_hours_num = accruing_pto_hours()
nurse_hours_pto = input('Are you going to use PTO?')
... |
from django.shortcuts import render
from django.http.response import HttpResponse
import os
import time
import librosa
import numpy as np
# Create your views here.
from django.template import loader
# Create your views here.
import chardet # 获取上传文件编码格式
from Myapp_covert2musicscore.utils.music21tools import *
from M... |
from __future__ import unicode_literals
from functools import update_wrapper
from django.utils.decorators import classonlymethod
from django.views.generic import View
class ViewSetMixin(object):
"""
This code is "inspired" (aka stolen) from Django Rest Framework.
See https://github.com/tomchristie/django... |
'''
Created on 8 de dez de 2016
@author: vagnerpraia
'''
from sklearn.feature_selection import VarianceThreshold
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2, f_classif, mutual_info_classif
from sklearn.feature_selection import RFE
from sklearn.feature_selection import ... |
import os
import shutil
import unittest
import pathlib
from diagrams import Cluster, Diagram, Edge, Node
from diagrams import getcluster, getdiagram, setcluster, setdiagram
class DiagramTest(unittest.TestCase):
def setUp(self):
self.name = "diagram_test"
def tearDown(self):
setdiagram(None)
... |
import pandas as pd
from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
def init_browser():
executable_path = {'executable_path': 'C:/Windows/chromedriver'}
return Browser('chrome', **executable_path, headless=False)
def scrape():
#----------NASA Mars----------------------------------... |
# ugosc.py -- oscillator functions and unit generators
from Ugen import *
def osci(phz, pphase, ptable):
table_len = Var("table_len", Utable_len(ptable), "int")
phase_incr = phz * table_len * Ugen("AR_RECIP")
indexf = First("indexf", pphase * table_len)
index = Var("index", Uint(indexf), "int")
x... |
"""
#------------------------------------------------------------------------------
# Recording and processing OpenCV data for experiments - record_camera_live.py
#
# Track a payload, save the position data, and output the processed data
#
# Created: 4/27/17 - Daniel Newman -- danielnewman09@gmail.com
#
# Modified:
# ... |
#!/usr/bin/env python
import libxml2
import sys
def getServers(xml):
doc = libxml2.parseFile(xml)
ctxt = doc.xpathNewContext()
servers = ctxt.xpathEval("//FileZilla3/Servers/Server")
print servers;
for server in servers:
host = server.xpathEval('Host')[0].content
port = server.xpa... |
import matplotlib.pyplot as plt
from numpy import dtype
from Astar import astar
# class for defining an underwater exploration mission
class MISSION:
def __init__(self, discretization_distance=1, worldsize_x=100, worldsize_y=100):
"""
discretization_distance = discretization distance in met... |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2013 david reid <zathrasorama@gmail.com>
#
# 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
#... |
'''
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node.
Otherwis... |
from django.db import models
# Create your models here.
class Tag(models.Model):
'''
Tag is a short name for a specific thing.
'''
name = models.CharField(max_length=24,help_text='Short descriptive name of the Tag')
slug = models.SlugField(max_length=24,help_text="urlized version of tag name")
description = mode... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 30 12:27:57 2019
@author: war-machince
"""
import os,sys
pwd = os.getcwd()
sys.path.insert(0,pwd)
#%%
print('-'*30)
print(os.getcwd())
print('-'*30)
#%%
import pdb
import pandas as pd
import numpy as np
import gensim.downloader as api
import scipy.... |
import keras
from keras.models import Sequential
from keras import backend as K
import numpy as np
from skimage import transform
class PredictionModelSpecial():
"""
Create and evaluate neural network with angle ,dataset, structure.
Returns number of samples and loss
"""
def __init__(self, X, y, X_val, y_val... |
a=input()
b=1
for i in a:
b*=int(i)
print(b)
|
# Generated by Django 3.0.7 on 2020-10-09 09:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0024_customer'),
]
operations = [
migrations.AddField(
model_name='customer',
name='brandpoints',
... |
from flask import render_template, request, redirect, url_for, flash, request_started
from models import Cliente, Pedido, Producao, Entrega, cliente_key, pedido_key
from forms import ClienteForm, PedidoForm
from google.appengine.api import users
from microerp import app, usuarios_autorizados
from datetime import dateti... |
from django.urls import path, include, re_path
from . import views
urlpatterns = [
re_path(r'^$', views.index),
re_path(r'^(\d+)/(\d+)/$', views.detail),
re_path(r'^grades/$', views.grades),
re_path(r'^students/$', views.student),
re_path(r'^grades/(\d+)$', views.grades_students)
]
|
# Generated by Django 3.0 on 2021-06-21 03:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0014_auto_20210620_2226'),
]
operations = [
migrations.AlterField(
model_name='gallery',
name='Image',
... |
from src.item import Item
class ListIO:
"""Handles storing items from user input and retrieving previously stored data."""
def __init__(self, filename, userList):
self.filename = filename
self.userList = userList
def readData(self):
"""reads data from file into ItemList"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python 2.7
#
import sqlite3
_db = 'asm32.article.sqlite3'
_conn = sqlite3.connect(_db)
print '_conn OK!'
_cur = _conn.cursor()
strQuery = '''create table table_article(
id int,
strTitle varchar(255),
strFrom varchar(100) default null,
strFromLink varchar(255) de... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 09:09:44 2019
@author: jnguy126
"""
import numpy as np
import os
#=================================================================================
# create ex data
#=================================================================================
file_ou... |
# Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
n = int(input('Informe um número inteiro: '))
print('Par' if (n % 2 == 0) else 'Ímpar')
|
from daos.daos_impl.student_questions_dao_impl import StudentQuestionsDAOImpl
class StudentQuestionsServices:
students_questions_services = StudentQuestionsDAOImpl()
@classmethod
def get_all_student_questions(cls):
return cls.students_questions_services.get_all_questions()
|
#Importing Moudules
import pygame as pg
import time
#Intialize Pygame
pg.init()
# TO Make The Screen Stuff
display_width = 1000
display_height = 600
dp = pg.display.set_mode((display_width, display_height))
# Setting Caption
pg.display.set_caption('Pong')
# Paddle1 Stuff
x = 990
y = 300
# Paddle2 Stuff
x_2 = 0
y_2 = 30... |
# Functions from the following NumPy document
# https://docs.scipy.org/doc/numpy/reference/routines.sort.html
# "NOQA" to suppress flake8 warning
from cupy.sorting import count # NOQA
from cupy.sorting import search # NOQA
from cupy.sorting import sort # NOQA
|
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
Balance main module for preliminary design on conventional
aircraft, it evaluates:
* The centre of gravity;
* The Ixx, Iyy, Izz moments of inertia.
WARNING: The code deletes the ToolOutput folder and recre... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import scrapy
import redis
from bs4 import BeautifulSoup
from DistributedCrawler.items import DistributedCrawlerItem
from scrapy_redis.spiders import RedisSpider
from scrapy.http import Request
import re
class ItemSpider(RedisSpider):
name = "itemspider"
redis_key = "t... |
"""
Created on Feb 23, 2020
@author1: leyu_lin(Jack)
@author2: Parth_Thummar
"""
from basicsearch_lib02.searchrep import Problem
from basicsearch_lib02.tileboard import TileBoard
class NPuzzle(Problem):
"""
NPuzzle - Problem representation for an N-tile puzzle
Provides implementations for Problem action... |
import os
from .inference import get_prediction
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
fil... |
# -*- coding: utf-8 -*-
import os as os
for srcdir,destdir in zip(range(5,9),range(9,13)):
os.system('rsync -avr --exclude-from \'/home/z3439823/bin/exclude_cpexp.txt\'\
exp'+'{0:03d}'.format(srcdir)+'/ exp'+'{0:03d}'.format(destdir))
# os.system('him1 '+str(srcdir)+' '+str(destdir))
# os.sys... |
import datetime
import unittest
import os
import time
import multiprocessing
import sys
sys.path.append("..")
from cliEnvSetup.cmdconfig import userTwo,Paths
class Rvirtus_Cli_Nfs_Image_Manual(unittest.TestCase):
def setUp(self):
print("RunStarted at :" + str(datetime.datetime.now()))
print("Envir... |
from MDM import *
# emit_sizecalc: structinfo -> string
# emit_structpack: structinfo -> string
# emit_structunpack: structinfo -> string
# inb += unpack(inb, &out) -> inb = unpack(inb, outb, size, &out)
# unpack(uint8_t **inb, size_remain, out): if (size_remain < amount to read) or inb == NULL then return NULL else ... |
from bson import json_util
from api.utils.database import db
from datetime import datetime
from mongoengine import signals
from .Comment import Comment
class Post(db.Document):
added_by = db.ReferenceField('User')
title = db.StringField(required=True)
content = db.StringField(min_length=50)
comments ... |
"""
# author: shiyipaisizuo
# contact: shiyipaisizuo@gmail.com
# file: validation.py
# time: 2018/8/18 10:31
# license: MIT
"""
import argparse
import os
import torch
import torchvision
from torchvision import transforms
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
pa... |
from Abstract.NodoAST import NodoAST
from TS.Excepcion import Excepcion
from Abstract.Instruccion import Instruccion
from TS.Simbolo import Simbolo
from TS.Tipo import TIPO
import copy
class DeclaracionArr2(Instruccion):
def __init__(self, tipo, dimensiones, identificador, expresiones, fila, columna):
sel... |
CELERY_IMPORTS = ("tasks", )
CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json' |
# 000000000000000000000000000000000000000000000000000000000000000000000000000000
# 1 1
# 1 LOCALIZACION CHILE OPEN ERP 6.0.3 1
# 1 ================================= ... |
from decimal import *
import math
def convert(n):
getcontext().prec = math.ceil(math.log10(n))
numlist=[1]
while n-1:
f = int(findFactor(n))
n /= f
numlist+=[f*x for x in numlist]
numlist=list(set(numlist))
numlist.sort()
return(numlist)
def findFact... |
from __future__ import print_function
from optparse import OptionParser
from WMCore.Lexicon import splitCouchServiceURL
from WMCore.Database.CMSCouch import CouchServer
def cleanDeletedDoc(couchURL, totalLimit, filter, limit, type, lastSeq):
couchURLBase, dbName = splitCouchServiceURL(couchURL)
couchDB = Couch... |
import turtle
bob = turtle.Turtle()
print(bob)
def koch(t, length, n):
if n ==0 :
return
else:
angle = 60
koch(t, length, n-1)
t.fd(length/3)
t.lt(angle)
koch(t, length, n-1)
t.fd(length/3)
t.rt(angle*2)
koch(t, l... |
import os
base_url = os.path.abspath(os.path.dirname(__file__))
class Config:
DEBUG = True
TESTING = False
SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://online_teach:online_teach@localhost/online_teach'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'NIUBIPLUS'
UPLOAD_FOLDER... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
from ansible.module_utils.basic import *
class Beaker:
CMDs = dict(
reboot='bkr system-power --insecure --action reboot {bkr_name}',
)
def __init__(self, module):
self.module = module
self.bkr_name = module.params['bkr_... |
def make_arguments(arr, idxs=None):
line = "["
if idxs is None:
idxs = list(range(0, len(arr)))
for i in idxs:
line += arr[i] + ", "
line = line[:-2] + "]"
return line
def reduction2ppa(red_stack):
source = ""
for name in red_stack.keys():
app = red_stack[name]
... |
import gym
from gym import envs
import numpy as np
import sys
state_num = 4*4 # $B>uBV?t(B
action_num = 4 # $B9TF0?t(B
epiode_num = 10000 # $BI>2A$r9T$&%(%T%=!<%I?t(B
step = 1000
policySelect = 1 # 0: e-greedy$B<jK!(B 1: softmax$B<jK!(B
alpha = 0.7
gamma = 0.9
tau = 0.0016 # softmax$B<jK!... |
#!/usr/bin/env python3
import json
import yaml
from socket import gethostbyname
serviceStorageFile = "services.json"
def initialize():
try:
with open(serviceStorageFile) as f:
print("File exists.")
except IOError:
print("File not accessible. Populationg with defaults.")
defa... |
'''This file has the code for printing the board'''
from colorama import Fore
from Wall import Wall
class Board:
'''This class has the methods and attributes of the Board'''
matrix = []
def __init__(self):
'''This method initializes the attributes of the Board'''
matrix = []
matc ... |
from django.contrib.auth.backends import ModelBackend
import re
from . import constants
from . import models
from django.contrib.auth.hashers import check_password
class UserPhoneEmailAuthBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
print('#########')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from p01_startwith_single_underscore import *
if __name__ == "__main__":
# regular name can be imported
assert public_var == "public_var"
assert public_func() == "public_func"
assert PublicClass.__name__ == "PublicClass"
assert PublicClass._non_public_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.