text stringlengths 38 1.54M |
|---|
# Generated by Django 3.0.3 on 2020-03-03 13:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
import keras.backend as K
from keras.layers import Dense, Input
from keras.models import Model
from keras.engine import Layer
import tensorflow as tf
from keras.utils import to_categorical
from keras.callbacks import ModelCheckpoint, History
from glob import glob
import numpy as np
from keras.backend.tensorflow_backend... |
# flake8: noqa
# import all models into this package
# if you have many models here with many references from one model to another this may
# raise a RecursionError
# to avoid this, import only the models that you directly need like:
# from from ory_oathkeeper_client.model.pet import Pet
# or import this package, but ... |
import sys
import json
import math
import itertools as it
import steane as st
import chper_wrapper as wrapper
import qcircuit_functions as qfun
#p1q, p2q = float(sys.argv[1]), float(sys.argv[2])
#ns, nt = float(sys.argv[3]), float(sys.argv[4])
error_model = 'ion_trap_eQual3'
output_folder = './MC_results/QECd3_flags/... |
import numpy as np
from GPyOpt.acquisitions import AcquisitionBase as GPyOptAcquisitionBase
from src.experiment.config_helpers import ConfigMixin
class AcquisitionBase(ConfigMixin):
pass
class AcquisitionModelMismatch(AcquisitionBase):
def __init__(self, *models, beta=2):
assert len(models) == 2, "I... |
# -*- coding: utf-8 -*-
import os
import threading
import time
import datetime
import json
import shutil
import queue
from queue import Queue
from multiprocessing import Process
from subprocess import PIPE
from app import Android
from app_config.config import ZHIHU_PACKAGE_NAME
from app_config.config import ZHIHU_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ----------------------------------
# @Date : 2020/4/6
# @Author : Zhicheng Qian
# @Version : 1.0
# @Brief :
# @Description :
# @Reference :
# ----------------------------------
class T:
def __init__(self, LL):
self.dp = [[-1] * ... |
class AuthToken:
tokens: list
current_token = 0
def __init__(self, tokens: list) -> None:
self.tokens = ['Bearer {}'.format(token)
for token in tokens]
def next_token(self):
if self.current_token < len(self.tokens) - 1:
self.current_token += 1
... |
# -*- coding: utf8 -*-
import requests
from models import oper_para
from django.contrib.auth.models import User
from models import LineUserInfo
def GetToken(code):
import json
client_id = oper_para.objects.get(name='client_id')
client_secret = oper_para.objects.get(name = 'client_secret')
redirect_uri... |
import os
import math
import time
import datetime
from multiprocessing import Process
from multiprocessing import Queue
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import imageio
import cv2
from sklearn.metrics import auc
import math
import torch
imp... |
import tweepy
creds = {
"consumer_key": "0Ex34lGWEnplcisTVzfZV5nOv",
"consumer_secret": "wcIasfkl8W8p4Haw3gvQpywKDdftKslRUf9okALfgTPjpf9hp9",
"access_token": "1459501699-7yL7Yyq9TgjIQvgomwxT0ey73LSR1zNGy1MgCWV",
"access_token_secret": "j7B1WczL0dExfO9ondn4Z61fn7hviNhTVqiZZD58VgUvS",
}
auth = tweepy.OA... |
__author__ = "Andrea Giovanni Nuzzolese"
__email__ = "andrea.nuzzolese@cnr.it"
__license__ = "Apache 2"
__version__ = "0.1"
__status__ = "Pre-Alpha"
from abc import ABC, abstractclassmethod
from builtins import staticmethod
import re, os, unidecode
from typing import Dict, Union, Set, List
from pandas.core.frame impo... |
#####################################
# Python Imports
#####################################
from quickscmp.bitstream import basic
from sys import path
#####################################
# Manakin Imports
#####################################
path.append('../')
from chaching import fileHandler
##########... |
import random
from the_tale.common.utils import testcase
from the_tale.game.logic_storage import LogicStorage
from the_tale.game.logic import create_test_map
from the_tale.game.postponed_tasks import ComplexChangeTask
from the_tale.game.companions import storage as companions_storage
from the_tale.game.companions ... |
#! /usr/bin/env python
import sys
import numpy as np
import time
usageMsg='''alienIndex.py
Calculate alien index (AI) for a Diamond output file that includes taxonomy info. MUST create using output format 6 command:
--outfmt 6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue evalue staxids... |
#23212 | Contract with Mastema
sm.setSpeakerID(2450017)
if sm.sendAskYesNo("Everything is ready. Let us begin the contract ritual. Focus on your mind."):
sm.setJob(3110)
sm.addSP(5)
sm.completeQuest(parentID)
sm.setPlayerAsSpeaker()
sm.sendNext("#b(You feel a curious energy flowing into you.)")
... |
import logging
import yass
from yass import preprocess
from yass import process
# configure logging module to get useful information
logging.basicConfig(level=logging.DEBUG)
# set yass configuration parameters
yass.set_config('config_sample.yaml')
# run preprocessor
score, clr_idx, spt = preprocess.run()
# run pro... |
import pygame
import load
from locals import *
from physics import *
from entity import Entity
from ice import Ice
from rock import Rock
from score import Score
from math import sin, cos, pi
def init():
Player.image = load.load_image("sledder")
def drawMessage(screen):
msgNum = 0
messages = ["SMASHED ... |
"""The geometry shader should populate the feedback buffer with
vertex indices. However, it only does this if both EmitVertex calls
are commented out."""
NUM_NODES = 6
import numpy as np
from OpenGL.GL import *
from PyQt4 import QtCore, QtGui, QtOpenGL
VS = """#version 440
in vec4 position;
out VSOUT
{
vec4 gl_Pos... |
###
# Copyright (c) 2009, paulv
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and th... |
# -*- coding: utf-8 -*-
from mechanize import Browser
from bs4 import BeautifulSoup
import timeit
import unicodedata
import encodings
import os,sys
busc=raw_input('QUE DESEAS BUSCAR?'+'\n')
inicio1=timeit.default_timer()
print 'BUSCANDO EN GOOGLE ........'+'\n'
if busc=='pythan':
obag='.python'
else... |
import string
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
base_document = "This is an example sentence for the document to be ... |
# -*- coding: utf-8 -*-
#Tweet classifier using SVM
#Boyang Zhang and Jason Lucibello
import nltk
import numpy as np
#this might be a challenge to install
#from mayavi import mlab
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import matplotlib.pyplot as plt
f... |
#130. Surrounded Regions
'''
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X... |
from django.db import models
# Create your models here.
class Post(models.Model):
nama = models.CharField(max_length=255)
alamat = models.TextField()
def __str__(self):
return "{}".format(self.nama) |
# -*- coding: utf-8 -*-
# flake8: noqa
from rest_framework.mixins import DestroyModelMixin as DeleteMixin
from rest_framework.mixins import RetrieveModelMixin as RetrieveMixin
from rest_framework.mixins import UpdateModelMixin as UpdateMixin
from .creation import CreateMixin
from .pagination import ListMixin
|
class Base(object):
pass
class Derived(Base):
pass
print(issubclass(Derived,Base))
print(issubclass(Base,Derived))
d = Derived()
b = Base()
print(isinstance(b,Derived))
print(isinstance(d,Base))
|
import sys
S=0
M=int(sys.stdin.readline().strip())
for i in range(0,M):
t=sys.stdin.readline().strip()
if t.find(' ')>=0:
t,x=t.split()
x=int(x)-1
if t=="add":
S |= (1<<x)
elif t=="remove":
S &= ~(1<<x)
elif t=="check":
if S & (1<<x) :
print(1)
... |
import argparse
version_parser = argparse.ArgumentParser(add_help=False)
version_parser.add_argument('--version',
action='version',
version='%(prog)s script version: 1.0')
|
from typing import Callable
Vector = [float]
ActivationFunc = Callable[[float], float]
def neuron(inputs: Vector, weights: Vector, activation_func: ActivationFunc) -> float:
return activation_func(
sum(
z[0] * z[1] for z in zip([1.0] + inputs, weights)
)
)
def step(x: float) -> float:
return 1 if x > 0 el... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from q3_run import *
from cs224d.data_utils import *
CONTEXT_SIZE = 5
EMBEDDING_DIM = 10
HIDDEN = 30
BATCH_SIZE = 5
NUM_LAYER=2
SEQ = 1
class LSTMTagger(nn.Module):
def __init__(self, embedding_dim, hidden_dim, tagset... |
def bowlingScore(frames):
frame = frames.split(" ")
score = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0,0,0,0]]
finalScore = 0
frame[9]+="0"
for i in range(0,3):
score[9][i] = checkValue(frame[9][i])
if score[9][i]=="/": score[9][i] = addSpare(score[9][i-1])
for i... |
from pwn import *
# s= process('./notepad')
s = remote("46.101.23.188",32663)
elf = ELF('./notepad')
pause()
secret_func = elf.symbols['secret']
log.info("secret at: 0x%x"%secret_func)
def add_note(size,note):
s.sendlineafter(">","1")
s.sendlineafter('size',str(size))
s.sendlineafter("Note:",str... |
# Basic training configuration file
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import MultiStepLR
from torchvision.transforms import RandomHorizontalFlip, Compose, RandomResizedCrop
from torchvision.transforms import FiveCrop, Lambda, Resize
from torchvision.transforms import ColorJitter, T... |
import numpy as np
import numba as nb
@nb.njit(cache=True)
def as_rect(tlbr):
tlbr = np.asarray(tlbr, np.float64)
tlbr = np.rint(tlbr)
return tlbr
@nb.njit(cache=True)
def get_size(tlbr):
tl, br = tlbr[:2], tlbr[2:]
size = br - tl + 1
return size
@nb.njit(cache=True)
def area(tlbr):
si... |
from .models import *
from django.http import HttpResponse
from .serializers import *
import datetime
from django.http import JsonResponse
from django.core.mail import BadHeaderError, send_mail
from datetime import date,timedelta
import json
from django.conf import settings
from rest_framework import status
from rest... |
# Copyright (c) 2008, Michigan State University.
"""Reader and writer for screed."""
from __future__ import absolute_import
import os
import io
import sys
import gzip
import bz2
from collections.abc import MutableMapping
try:
import sqlite3
except ImportError:
pass
from . import DBConstants
from . import sc... |
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from models import Post
def main(request):
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts,2)
try:
page = int(request.GET.get("page",'1'))
except Value... |
from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination
class ArticleLimitOffsetPagination(LimitOffsetPagination):
default_limit = 2
max_limit = 3
class ArticlePageNumberPagination(PageNumberPagination):
page_size = 2
|
import main
from argparse import Namespace
# for submission in api.getContestSubmissions(1003,'minhphuoc1998'):
# print(submission['id'])
# api.API.getContestResult(1003,'minhphuoc1998')
# print(api.API.getContestInfo(1003))
# This equal to :
# python main.py -contests 1003 1004 1005 -users ferez.96 minhphuoc1998
arg... |
#主要看内存地址变化没,可变类型,不可变类型
#显示data是100,函数调用后a也是100,a后来赋值200,是不可变类型,现在就是data是100,a是200
# def test1(a):
# a = 200
# print('test1--- %d' % a)
# data = 100 # data 是一个数字
# test1(data)
# print('main --- %d' % data)
#列表是可变类型,data是[11],a是[11],a.append(22),内存地址不变,data和a一样
# def test1(a):
# a.append(22)
# print('t... |
from snack import *
import gettext
#import os
class Menu:
def __init__(self, texto, ancho=60, altomenu=25, opciones=None, titulo='',
scroll=0, screen=None, posicion=0):
self.texto = texto
self.titulo = titulo
self.screen = screen
self.altomenu = alt... |
import getopt
import sys
from datetime import datetime, timedelta
WIN_OUTPUT_DIR_PATH = r"D:\flo2d_output"
try:
buf_size = 65536
GRID_SIZE = 250
INPUT = '2016May'
try:
opts, args = getopt.getopt(sys.argv[1:], "s:e:i:g:",
["start=", "end=", "input=", "grid="])... |
#finalgraph.py
import urllib2
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from matplotlib.finance import candlestick #candlestick
import matplotlib.animation as animation
import matplotlib
import pylab
matplotlib.r... |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... |
from collections import deque
N, A, B = map(int, input().split())
# [0] = 현 위치, [1] = timeline, [2] = 어떤 동물의 접근이지 파악 목적 0 오리, 1 육리
queue = deque()
queue.append([A, 1, 0])
queue.append([B, 1, 1])
# 이동 와중에 동시성만 챙기면 되니, timeline만 확인 어차피 한번 지나간 시간은 중복되지 않으니 중복될 걱정 X
time = [[1] * (N+1) for _ in range(2)]
flag = False
wh... |
# coding: utf-8
# Es el año 2049 y todavía existen las loterias, esta particular sortea con numeros de 16 bits todos los días a la medianoche. La leyenda cuenta que esta implementada en assembler de 6502, y sospechamos que el generador de numeros al azar no sería fuerte.
#
# A continucación estan los resultados para... |
import asyncio
from time import time
from ew.static import cfg as ewcfg
from ew.static import poi as poi_static
from ew.utils import core as ewutils
from ew.utils import frontend as fe_utils
from ew.utils import rolemgr as ewrolemgr
from ew.utils.combat import EwUser
from ew.utils.district import EwDistrict
from ew.ba... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-28 03:45
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assetstracker', '0011_auto_20170326_2139'),
]
operations = [
migrations.RenameField... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2017年12月11日
@author: Irony."[讽刺]
@site: http://alyl.vip, http://orzorz.vip, https://coding.net/u/892768447, https://github.com/892768447
@email: 892768447@qq.com
@file: HotKey
@description:
'''
import ctypes # @UnusedImport
import ctypes.wintypes
from date... |
import os
from io import BytesIO
from adaguc.CGIRunner import CGIRunner
import unittest
import shutil
import sys
import subprocess
from lxml import etree
from lxml import objectify
import re
from adaguc.AdagucTestTools import AdagucTestTools
ADAGUC_PATH = os.environ["ADAGUC_PATH"]
class TestWMSPolylineLabel(unittest... |
from abc import ABC, abstractmethod
import torch
import random
import math
# from torch_ac.format import default_preprocess_obss
# from torch_ac.utils import DictList, ParallelEnv
from ReplayMemory import ReplayMemory
from utils import default_preprocess_obss, DictList, ParallelEnv
import numpy as np
class BaseSRAl... |
# -*- coding: utf-8 -*-
#
# Web API module of Dashboard.
#
# (C) 2013 Internet Initiative Japan Inc.
# All rights reserved.
#
# Created on 2013/05/28
# @author: yosinobu@iij.ad.jp
try:
import json
except ImportError:
import simplejson as json
from trac.core import Component, implements, ExtensionPoint
from tr... |
# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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... |
from django.shortcuts import render,redirect
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
# from django.contrib.auth.decorat... |
# /*
# * Copyright 2018 IBM Corporation
# *
# * 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 applicab... |
__author__ = 'Julie'
import re,math
wordposPATT=re.compile('(.*)/(.*)')
def untag(wordpos):
matchobj=wordposPATT.match(wordpos)
if matchobj:
(word,pos)=(matchobj.group(1),matchobj.group(2))
return (word,pos)
else:
print "Warning: Does not match word/pos pattern: "+wordpos
... |
#! /usr/bin/env python3
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
df = pd.read_csv("../data/japandeaths.csv")
t = [datetime.datetime(int(x["年"]), int(x["月"]), 1) for i, x in df.iterrows()]
def days(year, month=None):
year = int(year)
leap = (year % 4 == 0) and (ye... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-18 02:45
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score, roc_curve, confusion_matrix
from sklearn.utils import shuffle
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB, BernoulliNB
import models
from data.utils import load_sparse_csr, generate_fol... |
#encoding=utf-8
import tornado.web
import tornado.ioloop
from tornado.escape import json_encode
class IndexHandler(tornado.web.RequestHandler):
def get(self,*args,**kwargs):
self.render('templates\login.html')
class LoginHandler(tornado.web.RequestHandler):
def get(self,*args,**kwargs):
name... |
from anoky.syntax.form import Form
from anoky.syntax.node import Element
from anoky.syntax.util import is_identifier, identifier_in
from anoky.transducers.arrangement_rule import ArrangementRule
class RightLeftBinaryOperator(ArrangementRule):
"""
::
⋅ ⦅X a b⦆ a ⋅ X b
"""
def __init__(self, s... |
from lib.Storage import Storage
from utils import Transmitter, Singleton, Worker
class StorageManager(metaclass=Singleton):
def __init__(self):
self.__transmitter = Transmitter(StorageWorker)
self.__health_monitor = None
def start(self):
self.__transmitter.start()
# self.__h... |
# Generated by Django 3.1 on 2020-11-09 05:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app1', '0009_auto_20201107_2123'),
('app1', '0008_booking_booking_date'),
]
operations = [
]
|
from tensorboard_logger import Logger
logger = Logger(logdir='experiment_cnn', flush_secs=2)
for i in range(100):
logger.log_value('loss', 10-i**0.5, step=i)
logger.log_value('accuracy', i**0.5/10) |
import sympy as sp
import numpy as np
# from sympy import cos, sin, exp
# CC: is this above line useful here ?
t = sp.Symbol("t")
class Boundary:
"""
Defines the class Boundary, that contains geometric features of a boundary
Attributes
==========
param: parametrization of a boundary
velo... |
from heapq import heapq
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
"""
Purpose: Returns the min. no. of conference rooms required, given an array
of meeting time `intervals` where intervals[i] = [start_i, end_i].
"""
if not inte... |
from prac_06.guitar import Guitar
gibson = Guitar("Gibson L-5 CES", 1922, 16035.40)
print(gibson.get_age()) # Expected answer is 98
print(gibson.is_vintage()) # Expected answer is True |
import random
import numpy as np
class Agent(object):
def __init__(self, env, net, args):
self.env = env
self.net = net
# Training epsilon
self.exploration_rate_start = args.exploration_rate_start
self.exploration_rate_end = args.exploration_rate_end
self.exploratio... |
from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin
from nose.tools import make_decorator
class Todo(Exception):
"""The `Exception` raised when a to-do test fails as expected.
These results are not counted as errors in the test suite results.
"""
pass
class MoreTodo(ErrorClassPlugin... |
import meshio
import Optimization_w_CS as ocs
import numpy as np
PATH = '/home/mltn/Documents/Meshes/Basicmodels/Simplest/bigger/'
# bound = 'bdata_m1.txt'
names = ['tet.vtk', 'otet_m1.vtk']
mesh = meshio.read(PATH+names[0])
points = mesh.points
# print len(points)
el = mesh.cells['tetra']
# print len(el)
vn, eln = o... |
from threading import Thread, Lock
import socket
import os
import time
import shutil
clients = []
addrs = []
isStudent = []
keyset = "`~"
colors = ["Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua","Aqua"]
lock = Lock()
flag = 0
def cr... |
def settingDicts():
""" This dicts is used to make settings form"""
dicts = [
{
"id": 1,
"name": "Bot User OAuth Access Token",
"isEncrypted": False,
"properties": {
"rules": [
{
"r... |
# from distutils.core import setup
from setuptools import setup
setup(
name='socksproxy',
version='1.0.0',
packages=['socksproxy'],
url='https://github.com/UltrafunkAmsterdam/socksproxy',
license='MIT',
author='UltrafunkAmsterdam',
author_email='info@ultrafunk.nl',
description=... |
import time
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, \
NoSuchElementException, InvalidElementStateException
from selenium.webdriver import ActionChains
from selenium.we... |
#!/usr/bin/env python
"""
CMSC733 Spring 2019: Classical and Deep Learning Approaches for
Geometric Computer Vision
Project 1: MyAutoPano: Phase 2 Starter Code
Author(s):
Nitin J. Sanket (nitinsan@terpmail.umd.edu)
PhD Candidate in Computer Science,
University of Maryland, College Park
"""
# Dependencies:
# opencv... |
'''
a -> aRbFR
b -> LFaLb
Some setup stuff to play around with the problem, then the actual solution. Runs very quickly--didn't even bother memoizing it, though this
would help for larger input.
'''
def D(n):
if n == 0:
return 'Fa'
else:
return D(n-1).replace('a', 'aRcFR').replace('b', 'LFaLb').replace('c'... |
# coding=utf-8
import os
import configparser
prjDir = os.path.split(os.path.realpath(__file__))[0]
configfile_path = os.path.join(prjDir, "config.ini") # 获取config配置文件所在路径
class Readconfig:
def __init__(self):
self.conf = configparser.ConfigParser()
self.conf.read(configfile_path)
def getAp... |
x = 50
def test1():
global x
x = 40
def test2():
print(x)
test1()
test2()
#Pull from Master/develop to update local master/develop
#Go to your branch and rebase with master/develop
#This should pull the latest and greatest into your branch
#this is what you should do.
#added new develop branc... |
import requests
import json
r = requests.get("http://localhost:8080/deleteQuery/sleepProfileQuery")
print r.text
mainLogic = """
inadequateSleep.
"""
queryInput = { "predicates" : [] }
queryOutput = {
"predicates" : []
}
devices = [
]
knowledgeDependencies = {"externalServices": [],
... |
import re
regS = '\#(.\n)*'
txt = '''# \t # ? | string a = "ayush \n agarwal"; '''
print(re.fullmatch(regS,txt))
# txt = '# ayush'
# if(re.search(regS,txt)):
# print("matched")
# else:
# print("notMatched")
# import re
# txt = "The rain in Spain"
# x = re.fullmatch("The rai in Spain", txt)
# print(x) |
# -*- coding: utf-8
# Models
from ..models import Channel, ChannelUser, Message
async def test_channel_model(channel_data):
channel = Channel(
owner_id=1,
name='General')
channel = await channel.create()
assert repr(channel) == "<Channel: 'General'>"
async def test_channel_user_model(c... |
import json
import quizlet_api_wrapper
class QuizletApiUtilities:
def get_new_set_id(json_string):
# fetches set_id from json response of create_new_set() method from Quizlet API
datastore = json.loads(json_string)
return datastore['set_id']
def get_new_term_id(json_string):
... |
import json
import web3
from web3 import Web3
from contracts.packer import *
address_deployed_contract = '0xbDaAe5285BEE72Ac7DEfaD987A8d67C36cde612f'
def getw3():
#target = 'http://172.13.0.2:8545'
target = 'http://127.0.0.1:8545'
aprovider = Web3.HTTPProvider(target)
w3 = Web3(aprovider)
assert w3.isConnec... |
from media import Movie
def generate_movies(codes):
"""Takes a dictionary of IMDB movie codes, generates their associated movie
objects and generates the Fresh Tomatoes site with that data.
Args:
codes (dict): A dictionary of codes with the following format
"Movie Name": "imdb_code",
... |
#
#Copyright (c) 2018 Jie Zheng
#
import queue
import traceback
from e3net.common.e3keeper import root_keeper
from pysyncobj import SyncObj
from pysyncobj import SyncObjConf
from pysyncobj import replicated
from e3net.common.e3rwlock import e3rwlock
from e3net.common.e3log import get_e3loger
from e3net.common.e3config ... |
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
@ app.route('/')
def hello_world():
return 'Hello World from Flask!'
port = int(os.getenv('PORT', 8000))
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=port)
|
from math import ceil
while True:
n = int(input())
if n == 0:
break
if n != 1:
temp = n / 3
corridas = ceil(temp)
while temp > 1:
temp /= 3
corridas += ceil(temp)
print(corridas)
else:
print(0)
|
#!/usr/bin/python
from scapy.all import Ether, IP, sendp, get_if_hwaddr, get_if_list, TCP, Raw, UDP, NTP, fuzz
import sys
import time
import random, string
import socket
import fcntl
import struct
def randomword(max_length):
length = random.randint(1, max_length)
return ''.join(random.choice(string.lowercase)... |
#!/usr/bin/env python3
from loadCOLOR import load_color
from LOGClassify import log_energy, log_classify
# could really just use pickle here instead of numpy
import numpy
from viewCLASSES import view_classes
img, X, Xtrain, y = load_color()
lambdapickles = [ ( .005,'color_005.pickle'),
(.05, 'color_0... |
import pytest
from PlayerRepository import PlayerRepository
from gamecomponents import PlayerInfo
repo = None
p1, p2 = None, None
@pytest.fixture(autouse=True)
def initPlayers():
global repo, p1, p2
p1, p2 = PlayerInfo("1"), PlayerInfo("2")
p1.sigma = 3
p2.sigma = 5
repo = PlayerRepository()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by weihang huang on 17-11-18
import sys
import os
import numpy as np
from collections import Counter
reload(sys)
sys.setdefaultencoding('utf-8')
root = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + "/"
def create_dataset(in_file, max_size):
... |
#!/usr/bin/env python3
API_Key = "i3BgiDWeRDGgx1MieH5pfsQdI"
API_Secret = "W3tQRuhqBhYCm2PSezofEb0N069DNOT2r36LZzdAOQW29FdWwy"
token: '616379578-w3ElYEoF40uO4GyW0KoMAnzM0SG9lhiWhVsY0aj3'
secret: 'nY86GsXMNmttcivMlYJ1iWnqFWhcBsWgLbFbdF5vln9Jz' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# a0 a1 a2 a3 a4
# a = [1, 11, 21, 1211, 111221,
#1個の1
#2個の1
#1個の2,1個の1
#1個の1,1個の2、2個の1
#3個の1,2個の1,1個の1
from itertools import groupby
# 参考
# http://stackoverflow.com/questions/6972764/python-look-and-say-sequence-improved
def lookandsay(n):
return ''.join... |
# -*- coding: utf-8 -*-
"""
OCR 数据读入添加数据的绝对路径
@author: libo
"""
labelPath = 'D:/work_xinhuo/txt_add_path/txt/test.txt'
imgPath = 'D:/work_xinhuo/txt_add_path/img/'
labelPath2 = 'D:/work_xinhuo/txt_add_path/txt/test_add.txt'
with open(labelPath, 'r', encoding='utf-8') as f:
file_names = f.readlines()
print('------... |
from collections import OrderedDict
from pprint import pprint
from contextlib import contextmanager
import os
import pickle
from flask import Flask, request, abort, jsonify
from flask_cors import CORS
from werkzeug.exceptions import HTTPException
import dotenv
import redis
# Grab the .env values to use globably in thi... |
#!/usr/bin/env python
"""
------------------------------------------------------------------------------
COPYRIGHT: Copyright (c) 200x - 2010, Greenplum Inc. All rights reserved.
PURPOSE:
LAST MODIFIED:
------------------------------------------------------------------------------
"""
#disable deprecationwarnings
impo... |
#!/usr/bin/env python
####################
# Required Modules #
####################
# Generic/Built-in
import logging
# Libs
# Custom
from .collaborations import CollaborationTask
from .projects import ProjectTask
from .experiments import ExperimentTask
from .runs import RunTask
from .participants import Particip... |
vet = []
n = (input('Insira um valor no vetor (1)'))
menor1 = float(n)
menor2 = float(n)
for i in range(4):
vet.append(n)
n = float((input('Insira um valor no vetor ({})' .format(i+2))))
if(menor1>n):
menor2 = menor1
menor1 = n
input('O menor número é {} e o segundo menor é {}' .format(menor... |
from rest_framework import serializers
from apps.authentication.models import CustomUser
from datetime import datetime, date
from apps.setup.models import MyFile
class MyFileSerializer(serializers.ModelSerializer):
name = serializers.CharField(required=True)
description = serializers.CharField(required=Fals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.