text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
"""
Author: Philippe 'paHpa' Vivien <philippe.vivien@nerim.com>
Copyright: Nerim, 2014
"""
from __future__ import unicode_literals
from django.conf import settings
from runner.utils.logger import logger, logdebug
logdebug()
class DatabaseAppsRouter(object):
"""
A router to control al... |
# Generated by Django 2.2.4 on 2019-08-31 10:53
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('vehicle', '0014_log_reason'),
]
operations = [
migrations.AddField(
model_name='vehicle',
... |
from lol import More
courses = []
def print_courses():
for lol in courses:
print('{0}',
print(),
'{1}',
print(),
'{2}',
print(),
'{3}',
print(),
'{4}',
print(),
'{5}',
print(),
'{6}... |
'''
Created on Mar 12, 2016
@author: zhongzhu
'''
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tree import Tree
lemmatizer = WordNetLemmatizer()
def insert_aux(node, mainvb, aux):
for c in node:
if isinstance(c, nltk.Tree):
if c.label() == "INSERT":
c.... |
import os
from tests.utils import check_or_update
def test_cast(parser, update):
code = """
typedef int int32_T;
typedef unsigned int uint32_T;
int32_T i;
int32_T icng;
uint32_T jsr;
int main(){
i = (int32_T)(icng + jsr);
return 0;
}
"""
tree =... |
class Tile():
def __init__(self, position, is_snake, is_ladder, destination=None):
self.position = position
self.snake = is_snake
self.ladder = is_ladder
self.destination = destination
def is_snake(self):
return self.snake == True
def is_ladder(self):
return... |
#!/usr/bin/env python3
"""
Causes appveyor to wait for testing
"""
from os import getenv
from time import sleep, time
import requests
HEADERS = {
'Authorization': 'Bearer {}'.format(
getenv('APPVEYOR_TOKEN'))}
BASE_URI = "https://ci.appveyor.com/api"
INFO_URI = "projects/{}/{}/build/{}".format(
geten... |
from twitterAPIKey import TwitterAPIKey
import sys
sys.path.append('/home/ec2-user/workspace/work')
class TwitterAPIManager:
# ไฝๆใใAPIใญใผใTwitterAPIKeyใฏใฉในใซใปใใใใAPIKeysใชในใใซ่ฉฐใใฆใใ
# key๏ผใคใง15ๅ้ใซ300ใชใฏใจในใใใใชใใกๆฏๅ20ใชใฏใจในใใพใงใ
# ใใฃใฆใญใผใฎๆฐ * 20ใขใซใฆใณใใๅๅพๅถ้็ฎๅฎใ
key1 = TwitterAPIKey(
'hogehoge1',
'fug... |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class MatrixMathNode(Node, ArmLogicTreeNode):
'''Matrix math node'''
bl_idname = 'LNMatrixMathNode'
bl_label = 'Matrix Math'
bl_icon = 'CURVE_PATH'
property0: EnumProperty(
items ... |
from importlib import reload as reload_module
import json
from re import match
from django.contrib.auth import get_user_model
from django.urls import reverse, NoReverseMatch
from django.http import SimpleCookie
from django.test import TestCase
User = get_user_model()
class APITest(TestCase):
longMessage = Tru... |
#Find the length of the list
#find the node of K+1
#K and K+1 devided, move to in the front of the list
def rotateList(head,k):
if not head or head.next:return head
Length = 0
cur = head
while cur:
Length += 1
cur = cur.next
k %= Length
if k == 0: return head
#how to find the... |
# -*- coding: utf-8 -*-
"""
Created on Mon 11 Jan 2016
Last update: -
@author: Michiel Stock
michielfmstock@gmail.com
Pairwise performance measures
"""
import numpy as np
from sklearn.metrics import roc_auc_score as auc
import numba
# PERFORMANCE MEASURES
# --------------------
rmse = lambda Y, P : np.mean((Y - P)... |
"""Test the Julython API library."""
from julythontweets import config
from julythontweets.julython import Connection, Project
#User, Commit
import json
import time
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application, RequestHandler, HTTPError
# Building out the fake API. Contract drive... |
# -*- coding: utf-8 -*-
#Steven Ramirez
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from .models import Users
from .models import Friendship
from django.contrib import messages
from django.contrib.messages import error
import time
import bcrypt
def main(request... |
'''
Dividing two integers without using mod or dividing
'''
def divide(self,dividend,divisor):
is_negative = (dividend<0) != (divisor<0)
divisor,dividend = abs(divisor),abs(dividend)
quotient = 0
the_sum = divisor
while the_sum <= dividend:
current_quotient = 1
while(the_sum+the_s... |
# import the necessary packages
import numpy as np
import argparse
import cv2
from PIL import Image
import math
isShowImage = True
def showCV2Image(title, img):
cv2.namedWindow(title, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # ่ฐๆด็ชๅฃๅคงๅฐๅนถไฟๆๆฏไพ
cv2.imshow(title, img)
cv2.waitKey(0)
# construct the argument p... |
import sys
sys.stdin = open('lunchtime.txt')
T = int(input())
def group(n,k):
if n == k :
seq = []
for i in range(n):
if groups[i] == 1:
gotostair(P[i],S[0],seq,0)
else:
gotostair(P[i],S[1],seq,1)
seq.sort(key=lambda x: x[2])
... |
"""
Run this script after modifying the data.json file.
Regenerate the *m.png files according to new data.json.
"""
import json
from utilities import picture
import os
if __name__ == "__main__":
os.chdir(os.getcwd() + "/..")
data_path = "views/"
f = open(data_path + "data.json", 'r')
data = f.read()
... |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from swagger_client.api.accounts_api import AccountsApi
from swagger_client.api.addresses_api import AddressesApi
from swagger_client.api.agreements_api import AgreementsApi
from swagger_client.api.auth_api import AuthApi
from swagge... |
import torch
import torch.nn as nn
import torch.nn.functional as F
##################################
######### ConvBn block ###########
##################################
class ConvBn(nn.Module):
def __init__(self,
in_channels, out_channels,
kernel_size=3, stride=1, padding=... |
#! /usr/bin/env python
from os import path
from flask.ext.openid import OpenID
from openid.extensions import pape
from wmt.flask import create_app
import local_settings
application = create_app(settings_override=local_settings,
wmt_root_path=path.abspath(path.dirname(__file__)))
oid = OpenI... |
#!/usr/bin/env python
# coding: utf-8
# # **0. ์ปดํจํฐ์์ ์ํต์ ์ํ ๋๊ตฌ ์๊ฐ**
#
# > **Python**
# > - ๊ฐ๊ฒฐํ๊ณ ์ฌ์ด ์ปดํจํฐ์์ ์ํต์ธ์ด
# > - ๋ฐ์ดํฐ๋ถ์๊ณผ ๋จธ์ ๋ฌ๋์ ์ํ ์๋ง์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ํฌํจ
# > - ๋ค์ํ ํ์ฅ์ด ์ฉ์ด(ex. R, SPSS, etc.)
#
# > **Anaconda**
# > - Python๊ธฐ๋ฐ์ Open Data Science Platform
# > - Python์ ํฌํจํ์ฌ Python Library ๋ฑ์ ํ๋๋ก ์ ๋ฆฌํด ๋ ๋ฐฐํฌํ
# > - Pandas, Numpy,... |
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QRadioButton, QLabel, QPushButton, QVBoxLayout
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.infoLabel = QLabel("What is your fav lang?")
self.radioButton = QRa... |
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.Div(
html.H3('first dash app and you can type something : ')
),
html.Div(['type... |
# Generated by Django 2.0 on 2017-12-08 17:03
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contacts', '0003_auto_20160102_1338'),
]
operations = [
migrations.AlterModelOptions(
name='categ... |
from django import forms
from createproject.models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 14:47:06 2019
@author: Henrik
"""
def calc(y0,x0,T,N,evaluateModel,calculateTimeStep,euler):
dt=T/N
y=[]
x=[]
y.append(y0)
x.append(x0)
i=1
a=[]
while i<N:
a=calculateTimeStep(x[i-1],y[i-1],dt... |
import tensorflow as tf
from taskman_client.task_proxy import get_local_machine_name, assign_tpu_anonymous
from trainer_v2.chair_logging import c_log
import atexit
def device_list_summary(device_list):
if not device_list:
return "No device found"
n_gpu = 0
name_set = set()
for dev in device_l... |
import mapnik
m = mapnik.Map(3500,1500)
m.background = mapnik.Color('red')
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer()
polygon_symbolizer.fill = mapnik.Color('#96ff00')
r.symbols.append(polygon_symbolizer)
line_symbolizer = mapnik.LineSymbolizer()
line_symbolizer = mapnik.Line... |
import json
import os
from random import randint
from locust import HttpLocust
from locust import TaskSet
from locust import task
from locust.web import app
from src import report
# For reporting
app.add_url_rule('/htmlreport', 'htmlreport', report.download_report)
# Read json file
json_file = os.path.join(os.path.... |
from urllib.request import urlopen, Request
from html.parser import HTMLParser
import binascii
import argparse
import re
import os
# global functions
def saveImg(url, name, header):
if name == "-1" or url == "-1":
print("Not a correct URL or name for an image!")
exit()
else:
print("down... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import subprocess
from grooveshark import Client
client = Client()
client.init()
#for song in client.favorites("hasantayyar"):
# print(song)
playlist = client.playlist("32271770")
print("This is a huge link of my favorite songs on grooveshark. This l... |
import appuifw, time, os, sys, e32db, key_codes, e32
from time import strftime
from string import replace
db = e32db.Dbms()
dbv = e32db.Db_view()
class View( object ):
## The constructor.
def __init__(self, dbpath):
self.dbpath = dbpath
self.old_title = appuifw.app.title
self.old_quit = appuifw.ap... |
from fparser import api
def test_reproduce_issue():
source_str = '''\
subroutine bndfp()
use m_struc_def
C-
C
C
C
C
C
end
'''
tree = api.get_reader(source_str, isfree=False, isstrict=False)
tree = list(tree)
s, u, c, e = tree[:3]+tree[-1:]
assert s.span==(1,1),repr(s.span)
a... |
import logging
from decimal import Decimal
from typing import Iterable, Optional
from django.db import models
from auction.models.client import Client
from auction.models.product import Product
from core.errors import CodeError
logger = logging.getLogger(__name__)
class BidStatus(models.TextChoices):
ACTIVE = ... |
import unittest
from BowlingGame import BowlingGame
class BowlingGameTest(unittest.TestCase):
def setUp(self):
self.game = BowlingGame()
def rollMany(self, pins, times):
for i in xrange(0, times):
self.game.roll(pins)
def rollSpare(self):
self.game.roll(5)
self.game.roll(5)
def rollStrike(self):
se... |
def file_reader_1():
# pythonๅจๅฝๅๆง่ก็ๆไปถๆๅจ็็ฎๅฝไธญๆฅๆพๆๅฎ็ๆไปถ
with open('test.txt', encoding='utf-8') as file_obj:
contents = file_obj.read()
print(contents.rstrip()) # rstrip()ๅ ้คๅญ็ฌฆไธฒๆซๅฐพ็็ฉบ็ฝ
def file_reader_2():
filename = r'test.txt'
with open(filename, encoding='utf-8') as file_obj:
for l... |
#https://www.programiz.com/python-programming/decorator
#https://realpython.com/blog/python/primer-on-python-decorators/
#http://www.bogotobogo.com/python/python_decorators.php
"""
Decorators provide a simple syntax for calling higher-order functions.
By definition, a decorator is a function that takes another funct... |
from django.urls import path, re_path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.home, name='home'),
re_path(r'^search/$', views.search_list, name='search_list'),
re_path(r'^search/(?P<string>.+)/$', views.download, name='details'),
re_path(r'^download/(?P<strin... |
# coding: utf-8
from typing import Optional, Union
from urllib.parse import urlparse, parse_qs
from django.conf import settings
from django.contrib.auth.models import User
from django.core.signing import Signer
from django.db import models
from django.utils import timezone
class OneTimeAuthToken(models.Model):
... |
# Standard library imports
import json
import logging
# Third party imports
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.con... |
# -*- coding: utf-8 -*-
'''
Created on Feb 6, 2013
@author: Hugo
'''
import xlrd, xlwt
from xlutils.copy import copy
import os
from decimal import Decimal
#xlrd.Book.encoding = "gbk"
location = './/Data/'
location_ws = './/Data2/'
stand_cells_conf = './conf/standcells.conf'
cell_cells_conf = './conf/ce... |
import yaml
import os
import json
import codecs
def test_read_data_from_json_yaml(data_file):
return_value = []
data_file_path = os.path.abspath(data_file)
print(data_file_path)
_is_yaml_file = data_file_path.endswith((".yml", ".yaml"))
with codecs.open(data_file_path, 'r', 'utf-8') as f:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 17 12:20:57 2021
@author: hernando
"""
import numpy as np
import clouds.dclouds as dclouds
def mcimg(img, mccoors, mcenes, steps = None, x0 = None):
bins = dclouds._bins(img, steps, x0)
mcimg, _ = np.histogramdd(mccoors, b... |
import numpy as np
A250000 = (0, 0, 1, 2, 4, 5, 7, 9, 12, 14, 17, 21, 24, 28, 32)
def exclude_squares(pos):
row = pos // n
col = pos - (row * n)
# Eight directions: up, down, left, right, leftup, leftdown, rightup, rightdown
return {i for i in range(pos, -1, -n)} | \
{i for i in ... |
# Generated by Django 2.2.3 on 2019-08-01 10:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('openbook_moderation', '0010_auto_20190601_1909'),
]
operations = [
migrations.AddField(
model_name='moderationcategory',
... |
#!/usr/bin/env python
from setuptools import setup
setup(name='neo-observer',
py_modules=['neo_observer'],
packages=[],
install_requires=[],
version='1.0.1',
description='Python module implementing the observer pattern using a centralized registry',
keywords=['messaging'],
au... |
from setuptools import setup
import os
import io
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = '\n' + f.read()
VERSION = '0.8.0'
setup(
name='vertis_periodtask',
description='Periodic task with timezone',
... |
german = {'รค':100, 'ร':100, 'รฉ':50, 'รถ':100, 'ร':100, 'รผ':50, 'ร':100, 'ร':100}
french = {'รจ':50, 'ร ':50, 'รฉ':50, 'ล':50,'ร':100, 'รป':100, 'รด':100,'รฎ':100,'รช':100,'รข':100,'ร':100,'ล':100}
spanish = {'รฑ':100,'รก':50,'รฉ':50,'รญ':50,'รผ':50, 'ยก':100, 'ยฟ':200}
g=0
f=0
s=0
A=raw_input()
# for i in range(len(A)):
# #print A... |
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("gen_chunks.pyx"))
# complilation: python gen_chunks_setup.py build_ext --inplace |
from django.contrib.auth import login, authenticate
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .forms import CustomUserForm
class SignUpView(CreateView):
form_class = CustomUserForm
success_url = reverse_lazy('index')
template_name = 'registration/signup.ht... |
from _mystruct import ffi, lib
p1 = ffi.new('struct MyStruct*');
p1.a = 1;
print p1.a;
lib.ChangeStruct(p1, 10);
print p1.a;
|
from qtpy import QtCore, QtWidgets, QtGui
class Assets:
@staticmethod
def load_icon() -> QtGui.QIcon:
"""
Loads the time capture icons.
:return app_icon
"""
app_icon = QtGui.QIcon()
app_icon.addFile("assets/icons/16x16.jpeg", QtCore.QSize(16, 16))
app_... |
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route("/hello-world", methods=['GET', 'POST'])
def hello():
if request.method == 'POST':
return "Hello %s" % request.form["name"]
else:
return "Hello World"
|
from scryfall_image_crop_downloader import *
# Scan every card in a set
page = 1
cardnames = []
cardnumbers = []
totalcards = 0
more = True
expansion = input("Type the three-character set code for the set you want to scan: ")
# ensure we get every card from the set (multiple search result pages)
while more:
time.sle... |
'''
Created on 21 nov. 2015
@author: Vlad
'''
class IDObject(object):
'''
Base class for all objects having unique id within the application
'''
def __init__(self, objectID):
'''
Constructor for IDObject Class
objectID - the unique objectID of the object in the application
... |
# -*- coding:utf-8 -*-
import re
import pandas as pd
import numpy as np
import datetime
import os.path
import glob
from sklearn.externals import joblib
from mean_data import mean_data
from operator import itemgetter
def printu(data):
print(unicode(data, 'utf-8'))
DEBUG = False
class RaceDetail:
def __init__(s... |
import astropy.units as u
from copy import deepcopy
from ruamel.yaml import YAML
import logging
log = logging.getLogger(__name__)
yaml = YAML(typ='safe')
class Config:
def __init__(self, config_dict):
self.n_burn_steps = config_dict.get('n_burn_steps', 10000)
self.n_used_steps = config_dict.ge... |
import numpy as np
import PIL as pil
from functools import reduce
import functools
import os
from PIL import Image
import imageio
from skimage import io
import types
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
d = {"3": 4, 4: 4, int(input()) + 3: 6}
print(d[d["3"]])
print(d)
def power(x, n=2):
s = 1
tmp = x
... |
# https://programmers.co.kr/learn/courses/30/lessons/12953?language=python3
def compute_gcd(x, y):
while y:
x, y = y, x % y
return x
def compute_lcm(x, y):
return x * y // compute_gcd(x, y)
def solution(arr):
lcm = arr[0]
for a in arr[1:]:
lcm = compute_lcm(lcm, a)
return lcm... |
# Script to execute previously build models on a testing dataset
import sys;
import numpy
sys.path.append("loader/")
sys.path.append("preprocess/")
sys.path.append("ml/")
sys.path.append("configs/")
sys.path.append("utils/")
import logging
import data_load
import data_load_csv
import datetime
import utils
im... |
import glob
import os
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'height': tf.Fixed... |
'''
Okay, you have just built an autoencoder model. Let's see how it handles a more challenging task.
First, you will build a model that encodes images, and you will check how different digits are represented with show_encodings(). You can change the number parameter of this function to check other digits in the conso... |
import setuptools
import sys
try:
with open("version.txt", "r") as f:
version = f.read()
except FileNotFoundError:
print('You must either provide the file version.txt or build using make')
sys.exit(1)
with open("README.md", "r") as f:
long_description = f.read()
with open("requirements.txt",... |
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import serial
import sys
import json
import signal
import time
PORT = 3000
planted = False
myinst = 0
#If we ctrl+C out of python, make sure we close the serial port first
#handler catches and closes it
def signal_handler(signal, frame):
ser.cl... |
import pygame #import all the resources and utilities from pygame
pygame.init() #initialize pygame resources
# set mode will set the information regarding our game window and initializes it
gamewindow = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
# Initialize... |
#!/bin/python
array = ["a", "abcd", "az", "bcd", "bcda"]
a = dict()
for w in array:
key = ''.join(sorted(w))
print (key)
if key in a:
v = a[key]
v.append(w)
else:
v = []
v.append(w)
a[key] = v
for k, v in a.items():
print (v)
|
import numpy as np
import abc
import util
from game import Agent, Action
import math
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome t... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
from gensim.models.keyedvectors import KeyedVectors
from data_utils import dump_pkl
from annoy import AnnoyIndex
import os
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# TODO:
BASE_DIR = '/root/share/HCLG/ZN_... |
def solution(phone_book):
length = len(phone_book)
phone_book.sort()
if length == 1:
return True
for i in range(length - 1):
prefix = phone_book[i]
prefix_len = len(prefix)
for j in range(i + 1, length):
# ๊ฐ ์ ํ๋ฒํธ์ ๊ธธ์ด๊ฐ 1์ด์์ด๋ฏ๋ก 0์ผ๋ก ํ๋์ฝ๋ฉ ๊ฐ๋ฅ
if phone... |
# -*- coding: utf-8 -*-
import logging
import math
import random
from Interfaces.AI.Human import sleep, random_lat_long_delta, action_delay
from Interfaces.AI.Stepper.Normal import Normal
from Interfaces.AI.Worker.Utils import encode_coords, distance, format_dist
log = logging.getLogger(__name__)
class Spiral(Normal... |
# Solution of;
# Project Euler Problem 736: Paths to Equality
# https://projecteuler.net/problem=736
#
# Define two functions on lattice points:$r(x,y) = (x+1,2y)$$s(x,y) =
# (2x,y+1)$A path to equality of length $n$ for a pair $(a,b)$ is a sequence
# $\Big((a_1,b_1),(a_2,b_2),\ldots,(a_n,b_n)\Big)$, where:$(a_1,b_1... |
#!/usr/bin/python
import sys, re, numpy, gzip
import jkgenome
from gzip import GzipFile
class segInfo:
def __init__(self,seg):
self.seg = seg
self.staOffset,self.endOffset = map(int,seg[1].split('..'))
self.span = self.endOffset - self.staOffset + 1
self.numMatch = int(re.search('matches:([0-9]*),',seg... |
from flask import Flask, redirect, render_template, request
from flask.json import jsonify
app = Flask(__name__)
@app.route('/api/merge_tiffs', methods=('POST',))
def merge_tiffs():
uploaded_files = request.files.getlist('files[]')
print(uploaded_files)
return jsonify({ 'status': 'SUCCESS', 'file': 'http://l... |
"""
Hyperparameter tuning with scikit-learn
=======================================
This tutorial shows you how to tune hyperparameters with scikit-learn
(GridSearchCV) in the setting of trialwise decoding on dataset
BCIC IV 2a.
"""
######################################################################
# Loading and... |
from gans.utils import data_loader, sample_noise, show_images, show_cifar
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import init
from torch.autograd import Variable
num_train=50000
num_val=5000
noise_dim=96
batch_size=128
loader_train, loader_val = data_loader()
def initialize_weight... |
import SoftLayer
import json
def main(args):
name = args
namejson = name
virtualGuestName = namejson["vsiname"]
print("VSI Name: " + virtualGuestName)
power = namejson["poweraction"]
print("Power Action: " + power)
ibmcloud_iaas_user = namejson["username"]
print("Username: " + ibmcloud_iaas_user)
ibmcloud_iaa... |
from django.db import models
from blog.models import Post
from django.conf import settings
# Create your models here.
class LikeQuerySet(models.QuerySet):
def post_like_count(self, post_id):
return self.filter(post__id=post_id).count()
class Like(models.Model):
post = models.ForeignKey(
Po... |
"""Contains the Serve class"""
import os
from nltk.tokenize import word_tokenize, sent_tokenize
import seq2seq
class Serve:
"""Serve an instance of the trained model"""
def __init__(self, sess, model_name, checkpoint):
os.makedirs(os.path.join('training', 'data', 'dataset', model_name), exist_ok=True)
... |
#PyAutoGUI๏ผ่ชๅๆงๅถๆป้ผ ่้ต็ค
# ๆๅ้ก
from selenium import webdriver
import pyautogui as auto
import pandas as pd
import time
import sys
# ๅปบ็ซ็่ฆฝๅจ็ฉไปถ
driver = webdriver.Chrome() #ไฝฟ็จChrome
#driver = webdriver.Firefox() #ไฝฟ็จFirefox
driver.set_window_position(0, 0) #่จญๅฎ่ฆ็ชไฝ็ฝฎ
driver.set_window_size(800, 600) #่จญๅฎ่ฆ็ชๅคงๅฐ
driver.maximiz... |
import enum
class Place:
"""
A place is a general concept of a physical location, such as a powerplant,
a weather station, a position on a river etc.
"""
def __init__(self, kind, key, name, unit=None, fuels=None, area=None,
location=None, children=None, curves=None):
#: T... |
# Generated by Django 3.0.2 on 2020-01-28 16:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('chat', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='conversation',
name='name',
),
]
|
# https://leetcode.com/problems/design-tic-tac-toe/
class TicTacToe:
def __init__(self, n: int):
"""
Initialize your data structure here.
"""
self.board = [[0] * n for _ in range(n)]
def move(self, row: int, col: int, player: int) -> int:
"""
Player {player} ma... |
# name = raw_input("what is your name ")
# print("hello "+ str(name))
number = input("input a number: ")
number = int(number)
if number % 2 == 0:
print(str(number) + " is a EVEN number.")
else: # number %2 ==1
print(str(number)+ " is a ODD number.")
|
#Task 1
zoo_animals = ["tiger", "lion", "monkey"]
if len(zoo_animals) > 2:
print('the first animal at the zoo is the ' + zoo_animals[0])
print('the second animal at the zoo is the ' + zoo_animals[1])
print('the third animal at the zoo is the ' + zoo_animals[2])
zoo_animals[2] = "deer"
print(zoo_animals)
... |
class Ruisekiwa:
def __init__(self,lst):
s = 0
self.r = [0]
for i,_ in enumerate(lst):
self.r.append(s+lst[i])
s += lst[i]
def query(self,a,b):
#ใชในใๅ
ใฎๅ้ๅบ้[a,b)ใฎ็ทๅ
return self.r[b] - self.r[a]
def main():
pass
##def ruisekiwa(l):
## #้ขๆฐใใผใธ... |
# Generated by Django 2.1.7 on 2019-03-16 18:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0004_auto_20190316_1722'),
]
operations = [
migrations.AlterField(
model_name='quiz',
name='course',
... |
from __future__ import absolute_import
from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.deprecation import MiddlewareMixin
from corsheaders.middleware import (
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACC... |
"""
Custom decorators
=================
Custom decorators for various tasks and to bridge Flask with Eve
"""
from flask import current_app as app, request, Response, abort
from functools import wraps
from ext.auth.tokenauth import TokenAuth
from ext.auth.helpers import Helpers
# Because of circu... |
#!/usr/bin/env python3
from os import execv
from sys import argv
from sys import exit
from sys import maxsize
import socket
from subprocess import check_call
from time import sleep
from math import floor
import struct
import RPi.GPIO as GPIO
from RPLCD.gpio import CharLCD
import spidev
from gpiozero import Button... |
from random import randint
p1Score=1001
p2Score=1001
p1Roll=0
p2Roll=0
p1Name=str(input("Player 1 enter your name: ")).capitalize()
p2Name=str(input("Player 2 enter your name: ")).capitalize()
dRound=1
while p1Score!=0 and p2Score!=0:
print("\nRound No {}".format(dRound))
input("\n{} press ENTER to roll the dic... |
#!/usr/bin/env python
"""
Returns:
Given:
"""
from splat.SPLAT import SPLAT
import splat.Util as Util
from splat.parsers.TreeStringParser import TreeStringParser
import splat.complexity as cUtil
from splat.tokenizers.RawTokenizer import RawTokenizer
import json, sys, traceback, re
from linguine.transaction_exception i... |
try:
from PyQt4 import QtCore, QtGui
except ImportError:
from PySide import QtCore, QtGui
from maya import OpenMayaUI as omui
from shiboken import wrapInstance
import maya.cmds as cmds
def get_maya_window():
"""
This gets a pointer to the Maya window.
:return: A pointer to the Maya window.... |
import os
l = []
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
... |
import sys
import math
lon = raw_input()
lat = raw_input()
lon = float(lon.replace(",","."))
lat = float(lat.replace(",","."))
n = int(raw_input())
defibList = []
for i in xrange(n):
defib = raw_input()
defibList.append(defib.split(";"))
dmin = sys.maxint
for i in xrange(len(defibList)):
x = ... |
from unittest import TestCase, TestSuite
from time import sleep
import random
import shutil
from os.path import join, dirname
from os import mkdir
import subprocess
import tempfile
import sqlite3
from sleekxmpp import ClientXMPP
def filepath(name):
return join(dirname(__file__), name)
class ProsodyLiveTestCas... |
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta
# Create your models here.
class UserProfile(models.Model):
STATUS_CHOICES = (
('T', 'True'),
('F', 'False'),
)
user = models.OneToOneField(User, related_name='user_profile',... |
'''
Created on 19-May-2018
@author: srinivasan
'''
import logging
import os
from scrapy import signals
from scrapy.exceptions import NotConfigured
from Data_scuff.utils.fileutils import FileUtils
logger = logging.getLogger(__name__)
class ClearDownloadPath:
def __init__(self, settings):
self.sett... |
from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from apps.courses.models import Course,CourseResource,Video
from apps.operations.models import UserFavourite,UserCourses,CourseComments,UserMessage
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.