text stringlengths 38 1.54M |
|---|
import sys, pygame
import time
import random
pygame.init()
white=(255,255,255)
size = width, height = 800, 600
speed = [20,0]
black = 0, 0, 0
car_width =128
screen = pygame.display.set_mode(size)
pygame.display.set_caption("my game")
clock=pygame.time.Clock()
ballimg = pygame.image.load("ball.png")
ballrect = ballimg.g... |
"""********************************************
* A sample Python script for creating / updating layers
* from Dataminr API responses.
Open questions:
- Should this be a push vs a bulk update (if the latter, how to paginate)?
- Are alertIds unique? s.t. we can query all alerts and ignore those that exist
- What's the ... |
import FWCore.ParameterSet.Config as cms
CSCTFObjectKeysOnline = cms.ESProducer("CSCTFObjectKeysOnlineProd",
onlineAuthentication = cms.string('.'),
subsystemLabel = cms.string('CSCTF'),
onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R'),
enableConfiguration = cms.bool( True ),
enablePtLut = cm... |
dani = 5
num = [11,22,33,44,55]
name = ["ina","pena", "gogudka", "razmarinapetkova"]
'''while body'''
while dani < num[0] :
print(dani)
'''increment the main variable'''
dani+=1 |
#!/usr/bin/python
from fortigateconf import FortiOSConf
import sys
import json
import pprint
import json
from argparse import Namespace
import logging
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logger = logging.getLogger('fortinetconflib')
hdlr = logging.FileHandler('... |
from __future__ import print_function
import connect4game as c4
import math as m
import time
neighbors = [-1,0,1]
#bot that takes board state c4 game and chooses a move
#return all valid moves for a given board state
def find_moves(board):
valid = []
for i in range(0,c4.width):
for j in range(0, c4.he... |
from datetime import *
def get_datetime_object(string):
return datetime.strptime(string, '%Y-%m-%d %H:%M')
def key_func(i):
date_time = i.split('\t')[2][:-1]
return get_datetime_object(date_time)
def start():
with open('logs.txt', 'r') as f:
lines = f.readlines()
lines.sort(key=key_func)... |
import logging
from pathlib import Path
from yapsy.PluginManager import PluginManager
def get_module_logger():
return logging.getLogger(__name__)
THIS_PATH = Path(__file__).parent
modules_plugin_manager = PluginManager()
modules_plugin_manager.setPluginPlaces([str(THIS_PATH)])
modules_plugin_manager.collectP... |
import requests
import json
import base64
def startlogo():
print('''
$$$$$$$$\ $$$$$$$$\ $$$$$$\ $$\
$$ _____| $$ _____| $$ __$$\ \__|
$$ | $$$$$$\ $$ | $$$$$$\ $$ / $$ | $$$$$$\ $$\
$$$$$\ $$ __$$\ $$$$$\ \____$$\ $$$$$$$... |
#! /usr/bin/env python3
"""
You have the following data structure:
arp_table = [('10.220.88.1', '0062.ec29.70fe'),
('10.220.88.20', 'c89c.1dea.0eb6'),
('10.220.88.21', '1c6a.7aaf.576c'),
('10.220.88.28', '5254.aba8.9aea'),
('10.220.88.29', '5254.abbe.5b7b'),
('10.220.88.30', '5254.ab71.e119'),
('10.220.88.32', ... |
import os
import math
class Circle:
def __init__(self,r):
self.r = r
def area(self):
a = math.pi * (self.r ** 2)
return "Area: {0:.03f}".format(a)
def circumference(self):
c = 2 * math.pi * self.r
return "Circumference: {0:.03f}".format(c)
print("Please enter dimension of circle.")
radius = float(input("R... |
# -*- coding: utf-8 -*-
"""
myads_service.models
~~~~~~~~~~~~~~~~~~~~~
Models for the users (users) of AdsWS
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy import Column, String, Text
fro... |
from django.shortcuts import get_object_or_404
from rest_framework import status, generics
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from application import serializers
from application import models
class HealthCheck(APIView... |
from django.contrib import admin
from .models import *
# Register your models here.
class AdminDeliveryboylctn(admin.ModelAdmin):
list_display = ['ename']
class AdminOrders(admin.ModelAdmin):
list_display = ['order_name']
admin.site.register(Deliveryboylctn,AdminDeliveryboylctn)
admin.site.register(Orders,Ad... |
"""
Format experimental results.
"""
# Author: Georgios Douzas <gdouzas@icloud.com>
# License: MIT
import pandas as pd
METRICS_NAMES_MAPPING = {'roc_auc': 'AUC', 'f1': 'F-SCORE', 'geometric_mean_score': 'G-MEAN'}
def generate_mean_std_tbl(experiment, name):
"""Generate table that combines mean and sem values."... |
class Solution:
def findDuplicate(self, nums):
blankArray={}
for i in nums:
if i in blankArray:
print(i)
print(blankArray)
blankArray[i]=""
nums=[1,3,4,2,2]
Solution().findDuplicate(nums) |
THANK_YOU_MESSAGE = "Vielen Dank für deine Spende!"
CONFIRMATION_AMOUNT = "Ich spende: 6,00 €"
class TestDonationPage:
def test_successful_five_euro_donation(self, donation_page, customer):
donation_page.click_accept_cookies_button()
confirmation = donation_page.fill_form_with_valid_data_and_subm... |
import socket
import math
TCP_IP = '127.0.0.1'
TCP_PORT = 9003
BUFFER_SIZE = 20
ndatos = 0
suma = 0
multp = 1
Datos = []
clientes = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(3)
while 1:
print "Esperando conexion"
conn, addr = s.accept()
... |
import argparse
import numpy as np
import matlab.engine
from scipy.io import savemat
import os
from time import time
def main(args):
start_time = time()
eng = matlab.engine.start_matlab()
eng.addpath(r'matlab_engine')
eng.addpath(r'matlab_engine/weight_utils')
eng.addpath(r'matlab_engine/error_mes... |
# Run Time: 2.750
def cycle_length(n):
if n == 1:
return 1
elif n & 1 == 1:
return 1 + cycle_length(3 * n + 1)
else:
return 1 + cycle_length(n >> 1)
cache = {}
for i in range(1, 10000):
cache[i] = cycle_length(i)
while True:
try:
i, j = input().split(... |
import cPickle
import numpy as np
from scipy.stats import pearsonr
z_scores = np.load('raw_z_npdump.dump')
channels_data = []
def calculate_pearson(start):
for index in range(64):
if start < index:
channels_data.append(pearsonr(z_scores[start], z_scores[index])[0])
def dump_z_score_pearso... |
from threading import Thread
import time
import queue;
class device(Thread):
def __init__(self, name, cpu, bandwidth, QIN, QOUT):
# Call the Thread class's init function
Thread.__init__(self)
self.name = name;
self.VFs = queue.Queue();
self.cpu = cpu;
self.IN = QIN;
... |
## # # !/usr/bin/env python2 # Chimera's python is used...
#------------------------------------------------------------------------------
# file: autoChimeraMinimization.py
# author: Jon David
# date: Monday, July 6, 2020
# description:
# This is a Chimera script. Automates Chimera's structure minimization
# proc... |
"App configuration"
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://root:omokhudu@localhost/flask-spa"
DEBUG = True
|
import os
from store.models import CartItem, Collection, Order, OrderItem, Product, Cart
from django.urls import reverse
from rest_framework import status
from model_bakery import baker
import pytest
@pytest.fixture
def cart_id():
return baker.make(Cart).id
@pytest.fixture
def get_cart(api_client):
def acti... |
N, M = [int(_) for _ in input().split()]
KA = [[int(_) for _ in input().split()] for i in range(N)]
from collections import defaultdict
cs = defaultdict(int)
for r in KA:
for n in r[1:]:
cs[n] += 1
result = sum([cs[k] == N for k in cs])
print(result)
|
class Node():
def __init__(self, val):
self.val = val
self.next = None
class LL():
def __init__(self):
self.head = None
#There is a lot of boilerplaer here
#Need to abstract it out. Later
def add(self, node):
if self.head:
cur = self.head
whi... |
# class Emp:
# def getInfo(self):
# self.name = input("Employee Name:")
# self.contact = int(input("Contact Number:"))
# self.workexp = int(input("Total Work Experience in Years:"))
# self.companyname = input("Company Name:")
# self.salary = float(input("Salary:"))
# ... |
"""
Various hard-coded data.
"""
# ISO 639-1 language codes
# The readable names are locale-dependent
LANGUAGE_CODES = [
('ab', u'Abkhazian'),
('aa', u'Afar'),
('af', u'Afrikaans'),
('is', u'Icelandic'),
('sq', u'Albanian'),
('am', u'Amharic'),
('is', u'Icelandic'),
('an', u'Aragonese')... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2018-11-18 16:17
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('login', '0001_initial'),
]
ope... |
# -*- coding: utf-8 -*-
import pytest
import klibs
from klibs import KLBoundary as klb
def test_rectangle_boundary():
rect = klb.RectangleBoundary('test1', p1=(10, 10), p2=(50, 50))
# Test position arguments and boundaries with floats
pos = klb.RectangleBoundary('test2', (10, 10), (50, 50))
floats ... |
import sys
sys.setrecursionlimit(100000)
memo = {}
def fib(n):
if n in memo: return memo[n]
if n == 1: return 1
if n == 2: return 2
else:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
print fib(9000)
|
# import module
import sqlite3, os
from prettytable import PrettyTable, from_db_cursor
# hapus layar
os.system("clear")
# koneksi ke database
conn = sqlite3.connect('db/mahasiswa.db')
# membuat variabel cursor
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS mahasiswa(
nim integer not null primary key,
nam... |
#-------------------------------------------------------------------------------
# Name: restapi
# Purpose: provides helper functions for Esri's ArcGIS REST API
# -Designed for external usage
#
# Author: Caleb Mackey
#
# Created: 10/29/2014
# Copyright: (c) calebma 2014
# Licence: ... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torchvision.models import inception_v3
from loguru import logger
class ImageEncoder(nn.Module):
""" Image Encoder at the end of the generation stages.
The image encoder is based on the learned features of the... |
#!/usr/bin/python2
import matplotlib.pyplot as plt
import seaborn as sns
import avec
import numpy as np
plt.rc('text',usetex=True)
plt.rc('font', family='serif') #Boston Housing Overfit
# sns.set_style("whitegrid") # plt.style.use('fivethirtyeight')
# plt.style.use('bmh')
# plt.style.use('ggplot')
sns.set_context('post... |
# -*- coding: utf-8 -*-
#script to rule all startup/import scripts
class splashing():
def __init__(self):
#try:
import lib.sirbot.splash as splash
#display splash
self.startsplash=splash.splash()
#except:
#open a terminal or something to let them know we are ga... |
from base import Base as BaseTestCase
from roletester.actions.keystone import user_create
from roletester.actions.keystone import user_delete
from roletester.actions.keystone import project_create
from roletester.actions.keystone import project_delete
from roletester.actions.keystone import role_grant_user_project
from... |
from pylab import *
import numpy as N
from scipy import integrate
import cosmology as cosmo
reload(cosmo)
z=linspace(0,2,1000)
omegam=0.3
omegax=0.7
w0=-1
w1=0.
h=0.7
params=[omegam,omegax,w0,w1]
clf()
xlabel('redshift')
ylabel('distance (Gpc/h)')
plot(z,cosmo.get_dist(z,type='prop',params=params))
plot(z,cosmo.ge... |
# this code is for python versions 3.x
x = int(input("Enter number of row for the pattern : "))
i = 1
while i <= x:
for j in range(x-i):
print("", end = " ")
for j in range(i):
print(j+1, end =" ") # for python 2.7.x write print('*'),
print("")
i+=1
|
# Generated by Django 3.2.5 on 2022-01-20 13:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#
# *******************************************************************************
#
# David Marzocca - 25.10.2015
#
# This script downloads a DSCOVR photo from the website to the /photos/ folder
#
# *******************************************************************************
# ************** Libraries and defini... |
import os
import tensorflow as tf
import numpy as np
from config_utils import read_config
from docker_path_helper import get_base_directory
from model_saver import ModelSaver
from network import Network
def parse_trajectory_line(line):
line = line.replace('[', '').replace(']', '')
parts = line.split(', ')
... |
import random
from Neuron import *
import typing as t
from Util import *
class NeuralNetwork:
def __init__(self, numNeurons:int, numInputs:int, outputsMap:dict, randomWeights=False):
assert len(tuple(outputsMap.keys())[0]) == numNeurons, \
"Results from neurons don't have the same size as neu... |
# TWITTER
"""
SOLVED -- NO SIMILAR PROBLEM FOUND
Given a binary search tree (BST) and a value s,
split the BST into 2 trees, where one tree has all values less than or equal to s,
and the other tree has all values greater than s
while maintaining the tree structure of the original BST.
You c... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from sensor_msgs.msg import Image
import numpy as np
import random
import sys
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2
# sys.path.append('/opt/ros/kinetic/lib/python2.7/dist-packages')
from cv_bridge import CvBridge,... |
string = "パタトクカシーー"
new_string1 = ""
new_string2 = ""
for i in range(len(string)):
if i % 2 == 0:
new_string1 += string[i]
else:
new_string2 += string[i]
print(new_string1)
print(new_string2)
|
"""Train WideResNet(s) on Google AI platform or locally."""
import argparse
import logging
import tensorflow as tf
from tensorflow import keras
import tensorflow_addons as tfa
from matplotlib import pyplot as plt
from image_augmentation.wide_resnet import WideResNet
from image_augmentation.preprocessing import imag... |
# -*- coding:utf-8 -*-
from flask.blueprints import Blueprint
from flask import url_for, redirect, flash
from werkzeug.security import check_password_hash
from flask.globals import request, g
from echo_telegram_base import try_except, dao, app
from app_logger import logger
from api.signup import __get_user
from db.us... |
#!/usr/bin/python
#coding = utf-8
import os
def find_pkg():
dir_name = r'/data/version'
file_list = os.listdir(dir_name)
bwcc_files = []
for i in file_list:
if i.startswith('bwccz'):
bwcc_files.append(i)
bwcc_files.sort()
count = len(bwcc_files)
#print bwcc_files
#pri... |
from Tkinter import *
class HelloButton(Button):
def __init__(self,parent=None,config={}):
Button.__init__(self,parent,config)
self.pack()
self.config(command=self.callback)
def callback(self):
print 'Goodbye world...'
self.quit()
if __name__ =='__main__':
HelloButto... |
#-*- coding: UTF-8 -*-
import cv2
import numpy as np
def func1():
img_data=cv2.imread('e.jpg')
gray=cv2.cvtColor(img_data,cv2.COLOR_BGR2GRAY)
face=cv2.imread('xiaogou.png',0)
w = face.shape[1]
h=face.shape[0]
print(face.shape)
print(w,h)
res = cv2.matchTemplate(gray,face,cv2... |
import json
import os
import sys
import urllib
import cv2
import requests
face_cascade = cv2.CascadeClassifier('/usr/share/opencv4/haarcascades/haarcascade_frontalface_default.xml')
stars = []
if os.path.isfile('stars.json'):
stars = json.loads(open('stars.json', 'r').read())
for star in stars:
print("F... |
import keras
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from keras.optimizers import SGD
import migrate
from model import create_model
from utils import load_data, load_wsi_patches, custom_loss
if __name__ == '__main__':
batch_size = 16
epochs = 1000
patience = 50
#... |
#!/usr/bin/python3
import sys
def main():
current_node = None
current_node_record_count = 0
rank_unchanged = False
current_total = 0
out_list = []
for inp in sys.stdin:
line = inp.strip()
node, rank = line.split("\t")
if node == current_node:
... |
"""
Пользователь вводит строку из нескольких слов, разделённых пробелами.
Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
Если слово длинное, выводить только первые 10 букв в слове.
"""
string = input("Введите строку из нескольких слов, разделённых пробелами: ")
for i, word in enumerate(string.s... |
### Divide and Conquer Example ###
### MergeSort: Order( nlog(n) )
#Helper Function: merge, for mergeSort
def merge(A, B):
out = []
i,j=0,0
while i < len(A) and j < len(B):
if A[i] < B[j]:
out.append(A[i])
i+=1
else:
out.append(B[j])
... |
import FWCore.ParameterSet.Config as cms
#track match
from TrackingTools.TransientTrack.TransientTrackBuilder_cfi import *
from SimTracker.TrackAssociation.trackMCMatchSequence_cff import *
# define post-reco generator sequence
postreco_generator = cms.Sequence(trackMCMatchSequence)
|
from memd.gulp.Gulp import Gulp
class Phonon(Gulp):
'''This class allows phonon calculations using traditional molecular mechanics potentials.'''
kpointMesh = ''
dosAndDispersionFilename = ""
broadenDos = False
projectDos = ''
def __init__(self, **kwds):
Gul... |
#!/usr/bin/env python
import os, re, sys, subprocess, plistlib
import eclim
from util import caret_position
def call_eclim(project, file, line, offset, applied_correction=None):
eclim.update_java_src(project, file)
correct_cmd = "$ECLIM -command java_correct \
-p %s \
-f %s \
... |
""" Interpreter-level implementation of array, exposing ll-structure
to app-level with apropriate interface
"""
from pypy.interpreter.gateway import interp2app, unwrap_spec
from pypy.interpreter.typedef import TypeDef, GetSetProperty, interp_attrproperty_w
from rpython.rtyper.lltypesystem import lltype, rffi
from pyp... |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
#
# 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... |
from planner import *
from othertools import *
import matplotlib.pyplot as plt
def main():
scores_t = readfile('rq2_TimeLIME.csv')
scores_f = readfile('rq2_LIME.csv')
scores_x = readfile('rq2_XTREE.csv')
scores_alve = readfile('rq2_Alves.csv')
scores_shat = readfile('rq2_Shat.csv')
scores_oliv... |
import requests
from django.utils.translation import ugettext_lazy as _
from payments import PaymentStatus
from payments import get_payment_model
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from django.conf import settings
import hashlib
def isset(data, columns):
for column ... |
from datetime import datetime
from dateutil.parser import parse
from django.db.models import Q
from events.models import Events
class EventsRepository:
def __init__(self):
pass
def find_all_cyclic_events_for_given_root(self, root):
return Events.objects.filter(Q(root=root) | Q(pk=root.id)).... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from flask import Flask
from flask import request
from flask import render_template
import numpy as np
from matplotlib import pyplot as plt
import os
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
from string import punctuation
import en_core_web_sm
app =... |
#
# coding:utf-8
#
'''
'''
__author__ = 'JyHu'
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print('%s => %s , %s' % (name, member, member.value)) |
# Vendor of company mno
class GeomStats:
def print_stats(obj):
print('Area : {0}'.format(obj.area()))
print('Perimeter: {0}'.format(obj.perimeter())) |
import falcon
class AutoresResource:
def on_get(self, req, resp):
"""Handles GET requests"""
autores = {
'autores': (
"Creado Por- Oscar Rubio Garcia"
)
}
resp.media = autores
api = falcon.API()
api.add_route('/', AutoresResource()) |
'''
Created on Dec 25, 2011
@author: ppa
'''
from ultrafinance.model import Type, Action, Order
from ultrafinance.backTest.tickSubscriber.strategies.baseStrategy import BaseStrategy
from ultrafinance.backTest.constant import CONF_STRATEGY_PERIOD, CONF_INIT_CASH
import logging
LOG = logging.getLogger()
class PeriodSt... |
DYNAMIC_RESOLUTION = 8 # ppp, pp, p, mp, mf, f, ff, fff
MEASURE_RESOLUTION = 5 # show every fifth measure number
GAP = 2
STROKE_WIDTH = 16
TEXT_HEIGHT = STROKE_WIDTH
Y_INDENT = STROKE_WIDTH / 2
SINGLE_DIGIT = '0.1875em' # 3/16 em
DOUBLE_DIGIT = '0.3750em' # 6/16 em
TRIPLE_DIGIT = '0.5625em' # 9/16 em
|
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
d={}
for i in s:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
for j in range(len(s)-1):
if d[s[j]]==1:
return j
if __name__ == '__main__':
... |
import math
sc = input()
s = sc.split()
#num = [int(x) for x in s]
num = list(map(int,s))
ave = sum(num)/len(s)
avf = sum((float(i)-ave)**2 for i in s)/len(s)
avb = math.sqrt(avf)
s.sort()
if len(s)%2!=0:
mid = s[int(len(s)/2)]
else:
mid = (s[int(len(s)/2)+s(len(s)/2-1)])/2
s.sort()
print("平均值{} 方差{} 标准差{} ... |
#!/usr/bin/env python
#python2
import nmap
import time
import datetime
import sys
nm = nmap.PortScanner()
print('----------------------------------------------------')
print(' ')
time.sleep(1)
#how_long = int(raw_input('How many minutes do you want to scan for? '))
#repeat = how_long*2 # because 2 sweeps per minute... |
import pickle
# Define the Bird class
from PickleIO.Bird import Bird
def main():
birds = []
# Create a list of Bird objects
birds.append(Bird("Huey", 13, "Duck"))
birds.append(Bird("Dewey", 10, "Duck"))
birds.append(Bird("Louie", 12, "Duck"))
birds.append(Bird("Jerry", 15, "Goose"))
bird... |
#!/usr/bin/env python
#This script calculates the actual retention index
#for each character (codon)
#The summary file is for the mean retention index of
#all the codons
#Input:
#1 - input file of codon score table
#2 - output file
#3 - output summary file
import sys
import numpy as np
infile = open(sys.argv[1],"r... |
from numbers import Number
from typing import Mapping
import numpy as np
import regex
_FLOAT_REGEX = r"[\-+]?\d+(?:.[\d]+)?"
_LINE_REGEX = regex.compile(
rf"^\s*([^\s]+)(?:\s+({_FLOAT_REGEX})|(?:\s+#(\d+(?:,\d+)*)[:=\s]+({_FLOAT_REGEX}))+)\s*$")
def format_loss_layers(loss_layers):
def _weight_to_string(wei... |
N = int(input())
ans = 0
l, m = [], []
for _ in range(N):
s, t = input().split()
t = int(t)
l.append(s)
m.append(t)
X = input()
idx = l.index(X)
for i in range(idx+1, N):
ans += m[i]
print(ans)
|
class Obstacle:
taille=100
def __init__(self, x, y):
self.x=x
self.y=y
def toString(self):
return "["+str(self.x)+" ; "+str(self.y)+"]"
|
# day 22
import copy
# return [min x, max x, min y, max y, min z, max z]
def process(s):
inst = [s[0], int(s[2]), int(s[3]), int(s[5]), int(s[6]), int(s[8]), int(s[9])]
return inst
def turn_on_off_cubes2(s):
global cubes, num_lit_cubes
for x in range(s[1], s[2] + 1):
if x > 5... |
import json
import traceback
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from discussion.models import Discussion
from user.models import User
@csrf_exempt
def create(requ... |
'''
Data processor for the CMOS count packets.
CMOS counts are processed into rates. The input packet contains up to 8 slots.
The counts are stored in the class (static) array. This runs in multiple greenlets,
so clashes are likely. Practically it doesn't matter, we get the correct rates.
input:
"type": "cmos_counts"... |
# If the numbers 1 to 5 are written out in words: one, two, three, four, five,
# then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
# how many letters would be used?
#
#import pdb #(debugger)
D = [0,3,3,5,4,4,3,5,5,4,3... |
import cloudpickle
import torch
from torchvision.utils import save_image
import numpy as np
import cv2
from GAN import Generator
#取り出すepochを指定する
point = 100
#モデルの構造を定義
z_dim = 30
num_class = 49
G = Generator(z_dim = z_dim, num_class = num_class)
#checkpointを取り出す
checkpoint = torch.load('./checkpoint_cGAN/G_model_{}... |
from django.contrib import admin
from django import forms
from django.db.models import Sum
from django.forms import ModelForm
from django.utils import timezone
#from django.contrib.contenttypes.admin import GenericTabularInline
#from tabbed_admin import TabbedModelAdmin
# Register your models here.
from .models impor... |
# -*- coding: utf-8 -*-
import os
#from plugin_color_widget import color_widget
from plugin_multiselect_widget import hmultiselect_widget
db.define_table('webadmin',
Field('webname',notnull=True,requires=IS_NOT_EMPTY(),label="网站名称",comment='必填'), # 网站名称
Field('weburl',label="网站地址"), ... |
import sys
from cx_Freeze import setup, Executable
setup(
name = "Soundset Manager",
version = "1",
executables = [Executable("manager.py")]
)
|
from bs4 import BeautifulSoup
import requests
class Parse:
def __init__(self, url):
self.soup = BeautifulSoup(requests.get(url).content, 'html5lib')
def generate_webpage(self):
list_of_output = self.soup.find_all(["h1", "p", "noscript"])
title = ""
html_script = ""
st... |
import pymysql
db = pymysql.connect("10.0.251.50","root","1234qwer","cms_ju",charset='utf8' )
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute("select * from tj_news_clob order by news_id desc limit %s,%s",(0,10))
rows = cursor.fetchall()
for row in rows:
print(row['news_id'])
db.close()
... |
from clients.codeforces import CodeforcesHttpClient
from models import MemberCodeforcesProfile
def fetch_member_codeforces_profile(codeforces_handle):
client = CodeforcesHttpClient()
profile = client.send_request("user.info", {"handles": codeforces_handle})
if profile:
return MemberCodeforcesProfi... |
import os
import math
from Pre_Process import punctuations_regex
from Pre_Process import make_words
from Pre_Process import return_lowered_lines
from Pre_Process import get_all_files_dir
from Pre_Process import merge
from Pre_Process import create_out_file
from Pre_Process import TRAIN_POS_OUT_FILE
from Pre_Process ... |
species(
label = '[CH]=C(C=C)O[C]=C(26507)',
structure = SMILES('[CH]=C(C=C)O[C]=C'),
E0 = (503.326,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([350,440,435,1725,1685,370,3010,987.5,1337.5,450,1655,3120,650,792.5,1650,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,267.015,26... |
import numpy as np
import cv2
import time
"""
Start of:
Reading input image
"""
# Reading image with OpenCV library
# In this way image is opened already as numpy array
image_BGR = cv2.imread('images/woman-working-in-the-office.jpg')
# Showing Original Image
# Giving name to the window with Original Image
# And sp... |
l = list(input("Enter your list: "))
v = input('Enter your value: ')
if v in l:
print(True)
else:
print(False)
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding M2M table for field author_nicks on 'Production'
db.create_table('demoscene_production_author_nic... |
import string
data = open("names.txt","r").read()
names = sorted(data.replace("\n", "").replace('"',"").split(","))
alphadict = dict((x,i) for (i,x) in enumerate(map(str,string.uppercase)))
total = 0
for y in range(len(names)):
total = total + sum([int(alphadict[x])+1 for x in map(str,names[y])]) * (y + 1)
prin... |
__version__ = "0.0.1"
__author__ = "Tongtong (Suri) Sun"
from .cbapi import get_org, get_ppl, set_key
__all__ = ['get_org', 'get_ppl', 'set_key']
|
print("helloworld")
name=int(input("enter the name"))
age=int(input("enter the number"))
#myself sree i am 20 years old
print("myself",name,"i am",age,"years old")
|
from django.shortcuts import render, redirect
from phonebook.models import PhoneBook
# Create your views here.
def test(request):
return render(request, 'phonebook/test.html')
def index(request):
alluser = PhoneBook.objects.values('id','이름', '전화번호')
print(alluser)
context = {
"phonebook":allus... |
import os
import sys
import scipy.misc
import pprint
import numpy as np
import time
import math
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
from glob import glob
from random import shuffle
from dfc_vae import *
from utils import *
from vgg_loss import *
pp = pprint.PrettyPrinter()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.