text stringlengths 38 1.54M |
|---|
#https://github.com/Tanganelli/CoAPthon
from coapthon.server.coap import CoAP
from coapthon.resources.resource import Resource
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
class TesteResource(Resource):
def __init__(self, name="TesteResource", coap_server=None):
... |
#导入Flask类库
from flask import Flask,request,make_response,redirect,url_for,abort,session
#导入类库
from flask_script import Manager
#创建应用实例
app=Flask(__name__)
app.config['SECRET_KEY'] = '加密用的秘钥字符串'
# 创建对象
manager = Manager(app)
#视图函数
@app.route('/')
def index():
return '<h1>Hello AAAAAAGGFlask!</h1>... |
import functools
import requests
import suds.transport as transport
import traceback
from six import BytesIO
__all__ = ['RequestsTransport']
def handle_errors(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except requests.HTTPError as e:
... |
import pymysql.cursors
from src.classes import part_class
from src.functions import functions
parts_set = functions.create_parts() # Вызываем функцию создания партий
print(parts_set[14].further_time)
|
# -*- coding: utf-8 -*-
"""
Column Carver Thresh
Uses Skimage line detection to cut columns
Created on Wed Sep 25 09:46:01 2019
@author: Carver Coleman
"""
import os
import skimage
import numpy as np
import cv2
import copy
from glob import glob
TARGET_COLS = 3
DEBUG = True
os.chdir("INSERT_PATH_TO_FO... |
from django.db.models import Model, DateField, DateTimeField, ManyToManyField, FileField
from django.db.models.query import QuerySet
from django.db.models.fields.related import ForeignKey
from django.core.files import File
from django.conf import settings
from django.utils.timezone import utc
from datetime import date,... |
from copy import deepcopy
from typing import Tuple
import bson
from delphin_6_automation.database_interactions.db_templates import delphin_entry, result_processed_entry, \
result_raw_entry
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# -----------------------------------------------------------------... |
from gpudb import GPUdb
from gpudb import GPUdbRecordColumn
from gpudb import GPUdbRecordType
from gpudb import GPUdbRecord
from gpudb import GPUdbColumnProperty
from gpudb import collections
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import random
from album import *
def filterByTitle_ArtistID(seq, title, art_id):
for el in seq:
if el.artistID == art_id:
if el.title == el.formatTitle(title):
yield el
break
elif el.title... |
import os
import sys
import shutil
import logging
from pathlib import Path
from ruamel.yaml import YAML
# from easygqcnn import DataProcesser
file_path = os.path.split(__file__)[0]
ROOT_PATH = os.path.abspath(os.path.join(file_path, '..'))
sys.path.append(os.path.join(ROOT_PATH, 'src'))
try:
from easygqcnn import ... |
#! /usr/bin/python
#-*- coding: utf-8 -*-
import time,gzip,stat,os,string
import hashlib
import fivemin_gl
from fivemin_common import get_logname
from shutil import rmtree
from struct import pack,unpack,calcsize
import gevent.monkey
gevent.monkey.patch_all()
class read_access():
def __init__(self,config,log):
... |
from entitybook import BasicBook
from entitybook import BookSearchByName
from entitybook import BookSearchByAuth
from entitybook import BookSearchByCategorical
from entitybook import BookSearchByPublisher
from entitybook import BookSearchByIsbn
from entitybook import BookOrderByHotPoint
from entitybook import BookContr... |
# Generated by Django 2.2.1 on 2019-06-14 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0009_auto_20190614_1414'),
]
operations = [
migrations.AlterField(
model_name='bookcopy',
name='borrow_date... |
"""from copy import copy
from math import sqrt
import numpy as np
import itertools as it
"""
class Node(object):
num_instances = 0
def __init__(self, loc, val):
__class__.num_instances += 1
self.loc = loc
self.val = val
self.label = __class__.num_instances
self.connec... |
# SmileyBounce2.py
import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
keep_going = True
pic = pygame.image.load("CrazySmile.bmp")
colorkey = pic.get_at((0,0))
pic.set_colorkey(colorkey)
picx = 0
picy = 0
BLACK = (0,0,0)
timer = pygame.time.Clock()
speedx = 5
speedy = 5
... |
import time
import filtering as filt
import features as feat
import features2 as feat2
import matplotlib.pyplot as plt
import dwt
#path = 'data/'
def main(data):
signal_type = 0
fs = 250
qtcN = 470;
f = open(data, 'r')
lines = f.readlines()
f.close()
datafil = ... |
# --- Very Basic Instructions ---
# 1 - place a video clip in a bucket on your Google Cloud Storage and set permission to public
# 2 - run the code from the GCP cloud VM
# 3 - run the requirements.txt file (pip install -r requirements.txt)
# 4 - run video_processing.py clip_name bucket_name at the command prompt
# ... |
# -*- coding: utf-8 -*-
""" ymir.puppet
Defines a puppet mixin for the base ymir service service class
"""
import re
import os
import glob
import shutil
import functools
from fabric import api
from fabric.contrib.files import exists
from ymir.util import puppet as util_puppet
from ymir import data as ydata
GIT_R... |
#!/usr/bin/env python
# for each antibody, we want a different cell type
import re
import sys
import numpy as np
import os
import random
import subprocess
from optparse import OptionParser
class Data:
def __init__(self,A):
self.set_name = A[0][:-13] + '.set'
for a in A[1].split(';'):
... |
"""
This module gives access to the limitted word2vec model that contains the words
similar to the emojis in emojilib.
"""
import gc
import os
import numpy as np
from gensim import matutils
from gensim.models.keyedvectors import KeyedVectors
from paths import BIN_NAME, DP_NAME, SAVE_NAME, NSAVE_NAME
M... |
import abc
class Optimizer(abc.ABC):
@abc.abstractmethod
def function_to_minimize(self, parameters):
pass
@abc.abstractmethod
def run(self):
pass
|
'''
application of stack
1- function calls
2- checking for balanced paranthesis
3- reversing items
4- infix to prefix/postfix
5- evaluation to prefix/postfix
6- stock span problem and its variations
7- forward/backward
implementation of stack in python
1- using list :
--append at the end
--remove at the end
... |
#!/usr/bin/python
import sys
import yaml
import requests
import argparse
import logging
import logging.handlers
DEFAULT_APIBASE = 'https://api.aprs.fi/api/'
DEFAULT_USER_AGENT = 'aprsfi-py-api-client 1.0'
class APRSFIClient(object):
"""
Post objects to aprs.fi using the REST API. Note that this API is
cu... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.modules as M
import copy
from math import log10, floor
import time
import numpy as np
from .visualization_utils import *
def train(net, trainloader, criterion, optimizer, nbr_epochs=-1, nbr_images=-1, max_time=-1, train_monitors=[], resume=None):... |
import os
import django
import re
from PIL import Image
from django.core.files.base import ContentFile
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ImageAnnotation.settings")
django.setup()
from Annotation import models
from django.core.files import File
# load_path="/Users/qianzheng/Downloads/fd3/"
# pathDir=os... |
# -*- coding:utf-8 -*-
###########################################################################
# #
# Program : realize the calculation of various performance indicators #
# ... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .formsVentas import VehiculoFormAll, VehiculoFormOne, ClienteForm, UserForm
from administracion.models import Vehiculo
from django.http import HttpResponseRedirect
from django.contrib.sessions.models import Session
from d... |
from django.contrib import admin
from django.urls import path , include
from django.conf import settings
from django.conf.urls.static import static
from app1.views import error_500
from django.conf.urls import handler500
urlpatterns = [
path('admin/', admin.site.urls),
path('' , include("app1.urls"))
]
if... |
'''
安装、部署、打包的脚本。在 setup.py 文件中写明依赖的库和版本,以便到目标机器上能够使用 python setup.py install 安装。
''' |
import sys
from PyQt5.QtWidgets import QApplication, QMessageBox
from MainInterface import MainWindow
sys._excepthook = sys.excepthook
def my_exception_hook(exctype, value, traceback):
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText(str(value))
msg.setInformativeText(str(traceback)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayEbppInstserviceSignresultBatchqueryResponse(AlipayResponse):
def __init__(self):
super(AlipayEbppInstserviceSignresultBatchqueryResponse, self).__init__()
self.... |
import argparse
import json
import sys
import time
from copy import deepcopy
from json import JSONDecodeError
from math import factorial
import pq_trees
def fingerprint(tree, root=True):
# orders = tree.cardinality()
# if isinstance(tree, pq_trees.P):
# orders //= tree.number_of_children()
# retu... |
from .lpp_type import get_lpp_type
try:
import logging
except ImportError:
class logging:
def debug(self, *args, **kwargs):
pass
class LppData(object):
"""A single LPP data object representation
Attributes:
chn (int): data channel number
type (int): data ty... |
def zip(input1, input2):
if len(input1) == len(input2):
output = ""
for i in range(len(input1)):
output += input1[i] + input2[i]
return output
else:
return "Input two Strings of equal length."
print(zip("String", "Fridge"))
print(zip("Dog", "Cat"))
print(zip("True", ... |
import sys
def solve(N, xs):
table = [set() for _ in range(N)]
for idx, x in enumerate(xs):
table[x].add(idx)
stack = [idx for idx, s in enumerate(table) if not s]
while stack:
idx = stack.pop()
nxt = xs[idx]
table[nxt].remove(idx)
if not table[nxt]:
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 17:54:19 2021
# Equipe:
# * Juliane
# * Rubens Lopes
# * Aline Soares
"""
from numpy import linalg,apply_along_axis
from pylab import plot,show,pcolor,colorbar,bone
from minisom import MiniSom
import numpy as np
#Cria um objeto(bunch) com os dados da base e seu ... |
employees = {1:p = HourlyEmployee(1, 'joe', 10, 80), 2:p = HourlyEmployee(2, 'Mike', 80000)}
for i in employee.value():
print(p.calculate()) |
# Generated by Django 2.1.7 on 2019-05-01 14:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('index', '0004_auto_20190501_2201'),
]
operations = [
migrations.AddField(
model_name='jobinfoclik',
name='companySiz... |
__author__ = 's7a'
# All imports
from nltk.tree import Tree
# The Relative clauses class
class RelativeClauses:
# Constructor for the Relative Clauses class
def __init__(self):
self.has_wh_word = False
self.np_subtrees = []
self.wh_subtrees = []
self.other_subtrees = []
... |
import urllib2 # the lib that handles the url stuff
import csv
data = urllib2.urlopen("https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list.txt").read(20000) # it's a file like object and works just like a file
data = data.split("\n")
list = ''
for line in data: # files are iterable
if len(lin... |
def createDictionary():
'''Returns a tiny Spanish dictionary'''
number = dict()
number['One'] = 1
number['Two'] = 2
number['Three'] = 3
return number
def main():
dictionary = createDictionary()
print(dictionary['One'],dictionary['Two'],dictionary['Three'])
main() # run the pro... |
import json
import praw
def main():
with open("private/creds.json") as f:
cj = json.load(f)
creds = cj["credentials"]
reddit = praw.Reddit(
client_id = creds["id"],
client_secret = creds["secret"],
user_agent = creds["appname"],
username = creds["username"],
password = creds["password"]
)
subreddi... |
import os
path = 'C:/Users/64Squares/Desktop/Nikhil/financials_automated'
excel_files = [f for f in os.listdir(path) if f.endswith('.xlsx')]
print(excel_files)
#lets check for a particular value or file using regex
import re
# iterate the list
for item in excel_files:
p = re.compile('.*SAIS.*',item)
print(p)
#if(... |
'''
Start App
'''
import Tkinter as tk
from tkMessageBox import *
import ttk, tkFont, logging, os
import UsConfig as Config
from GUI.Dialogs.Login import Login
import Common.Constants.Singal as Signal
from Common.Notifier import Observer
from Common.Constants import DBStatus
from Common.Utilities import*
from agly... |
#!/usr/bin/env python
import boto
from . import logs
log = logs.getLogger(__name__)
conn = None
def init(options):
global conn
conn = boto.connect_ses(options.aws_key, options.aws_secret)
def send_email(frm, to, subject, body):
"""TODO: Docstring for send_email.
:param frm: TODO
:param to: T... |
import imghdr
import os
from random import shuffle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from PIL import Image
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from dateti... |
def inc(lis):
ini = lis[0]
c = 1
arr = []
for i in range(len(lis)):
if i == 0:
pass
elif lis[i] >= ini:
c += 1
ini = lis[i]
# print(lis[i], ini, c)
else:
ini = lis[i]
arr.append(c)
c = 1
arr.a... |
"""
helper functions for scraping
"""
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def get_url(url):
"""
Get the url
:param url: given url
:return: raw html
"""
response = requests.Session()
retries = Retr... |
# Generated by Django 2.1.3 on 2018-12-10 10:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0005_auto_20181209_0916'),
]
operations = [
migrations.AlterModelOptions(
name='backup',
options={'ordering': [... |
import json
import requests
from django.conf import settings
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from .models import FormConfig, FormLog
from .forms import FormConfigForm
def send(request, slug):
context = {}
form_config = FormConfig.objects.get(slug=slug)
d... |
# Generated by Django 3.0.7 on 2020-07-10 10:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('assignment_project', '0003_auto_20200709_1654'),
]
operations = [
migrations.AddField(
model_name='userprofile',
nam... |
import snap
Graph = snap.GenRndGnm(snap.PNGraph, 100, 1000)
for NI in Graph.Nodes():
CloseCentr = snap.GetClosenessCentr(Graph, NI.GetId())
print ("node: %d centrality: %f" % (NI.GetId(), CloseCentr))
UGraph = snap.GenRndGnm(snap.PUNGraph, 100, 1000)
for NI in UGraph.Nodes():
CloseCentr = snap.GetClosenes... |
"""
Each file that starts with test... in this directory is scanned for subclasses of unittest.TestCase or testLib.RestTestCase
"""
import unittest
import os
import testLib
class TestAddUser(testLib.RestTestCase):
"""Test adding users"""
def assertResponse(self, respData, count = 1, errCode = testLib.RestTest... |
import time
from boto import kinesis
from settings import KINESIS_REGION, KINESIS_STREAM_NAME
FLUSH_INTERVAL = 5
BATCH_SIZE = 20
running = True
def process_messages(batch_msgs):
print('messages processed: {}'.format(len(batch_msgs['Records'])))
for msg in batch_msgs['Records']:
print('message: "{}"... |
import simpy
import random
import statistics
import numpy as np
wait_times = []
class Restaurant(object):
def __init__(self,env, num_servers,num_cooks):
self.env = env
self.server = simpy.Resource(env, num_servers)
self.scanner = simpy.Resource(env, num_cooks)
def buy_food(self,custom... |
import torch
import numpy as np
import os
import re
from torch.utils.data import Dataset
class HMDB(Dataset):
def __init__(self, _data_root, _txt_root, _load_type, _split_num, transform=None):
self._root_dir = _data_root
self._load_type = _load_type
self._txt_path = os.path.join(_txt_root... |
# Copyright 2016-2017 Andreas Riegg - t-h-i-n-x.net
#
# 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 appli... |
wildcard_constraints:
xx = "x+"
rule recruit_round_0:
input:
seq = "initial_seq.fa",
reads = "hifi.fa"
output:
"reads_round_x.fa"
run:
shell("mummer -maxmatch -l 500 -b -threads 40 {input.seq} {input.reads} | scripts/pick_readnames_with_mums.py > picked_hifi_round0.txt"),
shell("cp picked_hifi_round0.txt... |
"""
ex.
[1,2,3,4,5,6,7,8]
double each item and get this
[2,4,6,8,10,12,14,16]
"""
list2 = [1,2,3,4,5,6,7,8]
result = [2*i for i in list2]
print(result)
result = [2*i for i in [1,2,3,4,5,6,7,8]]
print(result) |
color_start = '\033[34m'
color_end = '\033[0m'
def print_title(text):
print(color_start + text + color_end)
|
import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn import functional as F
from torchvision.models.segmentation.deeplabv3 import DeepLabHead
def set_parameter_requires_grad(model, feature_extracting):
if feature_extracting:
for param in model.parameters():
param... |
from flask import Flask
import folium
import pandas as pd
from flask import render_template
from flask import request
from flask import redirect
import daten
from folium import plugins
from folium.plugins import MeasureControl
from folium.plugins import FloatImage
from natsort import natsorted, ns
from operator import ... |
#Write a program that prints the numbers from 1 to 100
#But for multiples of three it will print “Fizz” instead of the number.
#For the multiples of five it will print “Buzz” and For multiples
#of both three and five it will print “FizzBuzz” .
def print_number(n):
''' print 'Fizz'for multiples of three,print'Bu... |
#! /usr/bin/python3
import requests
from bs4 import BeautifulSoup
import os
import sys
import csv
import re
from collections import defaultdict
from urlWordsExtractor import dataExtractor
import nltk
from nltk import pos_tag
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
def getUrlFtrV... |
#Analyze the proportion of features I have in my data (G and S)
import sys
import statistics as stat
f = open("../data/70aadata.txt","r")
f = f.read().splitlines()
structureset = []
for i in range(2, len(f), 3):
structureset.append(f[i])
total = len(structureset)
countG = 0
numberofS = []
for eachstruc in structurese... |
#coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render
from django.http import JsonResponse
#from .forms import AddForm
import nltk
import re
import CRFPP
def index(request):
return render(request, 'home.html')
def process(request):
NERtext = request.GET['NERtext2']
input_t... |
from unittest.mock import Mock
import pytest
from django.contrib.auth.models import AbstractUser
from ..models import CustomUser
class TestCustomUser:
def test_custom_user_inherits_from_abstract(self):
assert issubclass(CustomUser, AbstractUser)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 17:28:53 2020
@author: shkim
"""
"""
## 차원 감소(Dimensionality Reduction)
## SVD(Singular Value Decomposition, 특잇값분해)
* np.linalg.svd() 사용
"""
#%%
import numpy as np
import sys
sys.path.append('../../')
from myutils.util import preprocess, create_co_matrix, ppmi
text... |
class Dog():
def __del__(self):
print("对象被干掉了")
dog1 = Dog()
del dog1
dog2 = Dog()
dog3 = Dog()
del dog2
del dog3
print("程序结束了")
|
import numpy as np
from ..util import _is_na
from anndata import AnnData
import pandas as pd
from typing import Union
from ..io._util import _check_upgrade_schema
@_check_upgrade_schema()
def alpha_diversity(
adata: AnnData,
groupby: str,
*,
target_col: str = "clone_id",
inplace: bool = True,
... |
import socket
import sys
import time
total_bytes_sent = 0
total_messages_sent = 0
protocol = sys.argv[1]
stop_and_wait = int(sys.argv[2])
print('protocol ', protocol)
large_buffer = 'large_buffer'
large_buffer *= 100
large_buffer_size = len(large_buffer.encode('utf-8'))
mb_10 = 10485760
mb_500 = mb_10 * 50
mb_1000 ... |
import boto3
dynamodb = boto3.resource('dynamodb')
dynamodb = boto3.resource('dynamodb', region_name='eu-west-1')
table = dynamodb.Table('product-active')
table.meta.client.get_waiter('table_exists').wait(TableName='product-active')
aliasesResponse = table.scan()
f = open('sample_outputs/product-active.txt', 'w')
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Marco Torreggiani'
'''
Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla
The problem is as follows: choose a number, reverse its digits and add it to the original.
If the sum is not a palindrome (which means, it is not the same number... |
import flask
from flask_wtf import FlaskForm
from wtforms import BooleanField
from wtforms.validators import DataRequired
from costreport.services.admin_services import (
create_costcode,
check_if_project_has_costcodes,
add_default_costcodes_to_project,
)
from costreport.services.costcode_services import (
... |
import matplotlib
matplotlib.use('Qt4Agg')
# matplotlib.use('TKAgg')
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
from util.transformations import apply_matrix_to_vertices
mpl.rcParams['figure.figsize'] = 10, 8
class Painter:
def __init__(... |
import cocos
import pyglet
from cocos.director import director
class Background(cocos.layer.Layer):
def __init__(self):
super().__init__()
self.setBlock()
def setBlock(self, path_img=""):
self.__set(0, path_img)
def setPosible(self, path_img=""):
self.__set(1, path_img)
... |
# class suibian(object):
# def __init__(self,value):
# self.value=value
# def __call__(self,arg1,arg2):
# return arg1-arg2
# class Sample:
# def __enter__(self):
# return self
# def __exit__(self, type,
# value, trace):
# print ("type:", type)
# print ("value:",value)
# ... |
guess = 'please make a rock, paper or scissors guess: '
play = True
def play_again():
answer = input('Would you like to play again? ')
if answer != 'y':
play = False
while play:
p1 = input(f'Player {1} {guess}')
p2 = input(f'Player {2} {guess}')
if p1 == p2:
print("It's a tie")
... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
# 달력작업에 필요한 함수를 만든다
# 년도를 인수로 넘겨 받아 윤년, 평년을 판단해 윤년이면 True, 평년이면 False를 리턴하는 함수
# 논리값을 리턴하는 함수나 논리값을 기억하는 변수의 이름은 'is'로 시작하는 것이 관행이다
def isLeapYear(year):
# 년도가 4로 나눠 떨어지고 100으로 나눠 떨어지지 않거나 400으로 나눠 떨어지면 윤년
return year % 4 == 0 and year % 100 != 0 or... |
from deeprobust.graph.data import Dataset
from deeprobust.graph.defense import DeepWalk, Node2Vec
from deeprobust.graph.global_attack import NodeEmbeddingAttack
import numpy as np
dataset_str = 'cora_ml'
data = Dataset(root='/tmp/', name=dataset_str, seed=15)
adj, features, labels = data.adj, data.features, data.label... |
import tensorflow as tf
from layers.activation import relu
from layers.pooling import max_pool_2D
from layers.trainable import fc, conv_2D, residual_block
from layers.normalization import bn
from layers.regularization import weight_decay, var, shade, shade_conv
#import math
import numpy as np
REG_COEF = 0.8
FC_WEIGHT_S... |
# from django.shortcuts import get_object_or_404
# from rest_framework.decorators import api_view, permission_classes
# from rest_framework import status, permissions
# from rest_framework.exceptions import PermissionDenied
# from django.http import HttpResponse, JsonResponse
# from django.core.paginator import Paginat... |
#!/usr/bin/env python
from absl import app
from grr_response_core.lib import rdfvalue
from grr_response_server.export_converters import rdf_primitives
from grr.test_lib import export_test_lib
from grr.test_lib import test_lib
class RDFBytesToExportedBytesConverterTest(export_test_lib.ExportTestBase):
def testRDFB... |
from django.shortcuts import render
from django.db.models import Q
from django.shortcuts import render_to_response
from consolecommand import models
from datetime import datetime
import datetime
from django.db.models import Count
from django.db import connection
def top_100(request):
items = models.OrderItems.objects... |
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django.contrib.auth.models import User
from .models import Students, UserCollege, TShirt, CodingCompetition
# class CustomAuthenticationForm(AuthenticationForm):
# username = UsernameField(
# ... |
#! /usr/bin/env python
#coding=utf-8
import os
import sys
print ("hello")
print ("world")
print (2**8)
jack = "okay"
print (jack)
for x in "spam":
print (x)
print ("done")
print (sys.platform)
# from imp import reload #要避免使用此用法
# reload (hello)
import myfile
print (myfile.title) #先导入模块,并获取模块属性
from myfile i... |
# Use for loop in dictionary
"""list1 = ["Shivam", "Rohilla", "Shubham", "Harry"]
for item in list1:
print(item)"""
# List in List
"""list2 = [["Shivam", 20], ["Rohilla", 21], ["Shubham", 25], ["Harry", 30]]
for item, age in list2:
print(item, age)
"""
# Use for loop in dictionary
list1 = [["Shivam", 20], ["R... |
import torch
import utils
import gc
import pickle
from torch.utils.data import DataLoader
from ValuesDataset import ValuesDataset, CreateSubSet, TrainingSubset
from modelset import ModelSet
from tensorboardX import SummaryWriter
frame_file = 'gooddata0.pt'
state_file = "./state.pt"
device = torch.device("cuda" if tor... |
# Generated by Django 2.0.1 on 2018-03-31 16:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Prevent', '0002_auto_20170831_0134'),
]
operations = [
migrations.AlterModelOptions(
name='prevent',
options={},
),
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version Copyright (c) 2010 kne / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable f... |
#scikit-learnを学ぶ
#Chainer Tutorials のやり方を参考にする
from matplotlib import pyplot as plt
'''
Step1 : データセットの準備
'''
from sklearn.datasets import load_digits
dataset = load_digits()
x = dataset.data
t = dataset.target
print("x_shape : ",x.shape)
print("t_shape : ",t.shape)
# データセットを分割する関数の読み込み
from sklearn.model_selecti... |
start = input("Введите начальное значение ")
end = input("Введите конечное значение ")
day = 1
if str(start).isdigit() and str(end).isdigit():
if end >= start:
result = start
while float(result) < float(end):
day = day + 1
result = float(result) + float(result)/10
pri... |
#!/usr/bin/env python2.7
import os
import urllib
import json
import re
import subprocess
from glob import glob
SCRIPTS_URL = "https://bot.lua.run/u/anders/scripts.lua?json"
MAP_URL = "https://bot.lua.run/u/anders/web_useremails.lua"
# git settings
GIT = "git"
AUTHOR_NAME = "L. Bot"
AUTHOR_EMAIL = "luabot@codebust.co... |
#!/usr/bin/env python
# coding: utf-8
# In[16]:
from matplotlib import pyplot as plt
ages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
salary_y = [38496, 42000, 46752, 49320, 53200,
56000, 62316, 64928, 67317, 68748, 73752]
plt.bar(ages_x, salary_y, label="All Devs")
plt.legend()
plt.title("Median... |
import os
import numpy
import cPickle
from amuse.units import nbody_system, units
from amuse.io import write_set_to_file
from amuse.ic.kroupa import new_kroupa_mass_distribution
from amuse.ic.fractalcluster import new_fractal_cluster_model
from amuse.ic.plummer import new_plummer_model
from amuse.ext.spherical_model ... |
import contextlib
import uuid
from unittest import TestCase
from mock import patch, DEFAULT, MagicMock, Mock, ANY
from icommons_common.utils import Bunch
from icommons_ui.exceptions import RenderableException
from django.core.exceptions import ObjectDoesNotExist
from canvas_sdk.exceptions import CanvasAPIError
from ca... |
# GFF3-parser based on gffutils
# Extracts gene transcript information from a GFF3 file
# In addition to the GFF3 annotation the genomic sequence or the transcript sequences are needed
# to retrieve the transcript sequences,
# Some information is required to correctly parse the GFF3 file:
# Is the sequence format genom... |
from lxml import etree
text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourt... |
records = []
for i in range(5):
string_in=input("input costs\n")
records.append(string_in)#
print(records)
|
# coding: utf-8
from google.appengine.ext import ndb
import model
class Crumb(model.Base):
"""A class describing Crumbs."""
code = ndb.StringProperty()
lat = ndb.FloatProperty()
lng = ndb.FloatProperty()
place = ndb.StringProperty( required = False )
PUBLIC_PROPERTIES = ['code', 'lat', 'lng',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.