text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
# auther:gaoshuai
# 2018/10/3 下午1:49
|
N = int( input())
S = input()
Q = int( input())
M = [0]*N
m = 0
D = [0]*(N+1)
C = [0]*(N+1)
for i in range(N):
if S[i] == 'D':
D[i+1] = D[i] + 1
C[i+1] = C[i]
elif S[i] == 'C':
C[i+1] = C[i] + 1
D[i+1] = D[i]
else:
C[i+1] = C[i]
D[i+1] = D[i]
if S[i] == 'M... |
'''a = [1,2,3]
b = a[:]
if b is a:
print("true")
else:
print("false")
print(b)
if b == a:
print("lala")
else:
print("wawa")
print(id(a))
print(id(b))'''
'''i = 1
while i < 10:
i += 1
if i % 2 != 0:
continue
print(i)'''
'''i = 1 #for i in range(1,11)
while i < 10: ... |
"""
------------------------------------------------------------------------
[program description]
Main function uses argparse to take arguments from user.
Take input file and output file to be parser argument.
And call the functions.
------------------------------------------------------------------------
Author: Jack... |
"""Client Module"""
import os
import sys
import socket
from user import User
from queue import Queue
from ui import Gui
from server import Server, get_server_list
from threads import Threads
from db_com import DBCom
class Client():
"""Client Client."""
def __init__(self):
self.socket = socket.socket... |
import time
import VkSpy
import telegram_bot
import json
def set_up() -> str:
try:
dic = json.load(open("config.txt"))
telegram_bot.init(dic['telegram_owner_id'], dic['telegram_api_token'])
return ''
except Exception as e:
return 'error - ' + str(e)
if __name__ == "__main__... |
import numpy as np
array = np.array([[1, 2, 3], [2, 3, 4]]) # 列表轉矩陣
print(array)
print('number of dim:', array.ndim) # 維度
print('shape:', array.shape) # 行數和列數
print('size:', array.size) # 元素個素
|
import sys
# Not needed after adding the CMD to Docker
#if len(sys.argv) > 1:
# addressee = sys.argv[1]
#else:
# addressee = 'partner'
print(f'Got {len(sys.argv)} args')
for a in sys.argv:
print(a)
addressee = sys.argv[1]
print(f'\n Well hey there {addressee}!')
|
class Car(object):
wheels = 4
doors=4
mirrors=2
@staticmethod
def make_car_sound():
print ('VRooooommmm!')
def __init__(self, make, model):
self.make = make
self.model = model
mustang = Car('Ford', 'Mustang')
print (mustang.wheels)
print (Car.wheels)
print (mustang.... |
from onegov.core.orm import Base
from onegov.core.orm.mixins import TimestampMixin
from onegov.core.orm.types import UUID
from sqlalchemy import Column
from uuid import uuid4
class UploadToken(Base, TimestampMixin):
""" Stores tokens for uploading using the REST interface. """
__tablename__ = 'upload_tokens'... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.count = 0
self.values = set()
def pseudoPalindromicPaths (self, root: ... |
#!/usr/bin/python3
def complex_delete(a_dictionary, value):
"""delete keys with a specific value in a dictionary"""
while value in a_dictionary.values():
for x, y in a_dictionary.items():
if y == value:
del a_dictionary[x]
break
return (a_dictionary)
|
def square_odd_sum(n):
if (not isinstance(n, int)) or (n <= 0):
return "Error: n is a positive integer"
total = sum(i*i for i in range(1, n+1, 2))
return total
if __name__ == '__main__':
print("Input {}: {}".format(-5, square_odd_sum(-5)))
print("Input {}: {}".format(10, square_o... |
# -*- coding: utf-8 -*-
import hashlib
import re
import redis
import scrapy
from article.items import ArticleItem, PressItem
from article.util import return_tag
m = hashlib.md5()
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)
conn = redis.StrictRedis(connection_pool=pool)
class YiqingSpider(scrapy.S... |
# Quiero Retruco
# El Truco es un juego de cartas muy popular en Argentina. Se suele jugar con naipes españoles de 40 cartas, las cuales tienen 4 palos (basto, oro, espada y copa) y 10 números, 1,2,3,4,5,6,7,10,11 y 12. Si bien en esta ocasión no vamos a programar un juego de truco, sí vamos a resolver uno de los probl... |
from tasks import *
result = task_1.apply_async(queue='queueA', args=(1,2))
|
#!/usr/bin/env python3
#
# Development Order #9:
#
# This will format a test spec into something that is human readable.
#
# To test this file, a spec is needed. You can generate one with cli-to-spec
# after you've written it. Use the following syntax:
# cat example-spec.json | ./spec-format text/plain
# cat example-s... |
__author__ = 'Галлям'
__all__ = ['core', 'data_transfer_process', 'protocol_interpreter'] |
from ED6ScenarioHelper import *
def main():
# 玛鲁加山道
CreateScenaFile(
FileName = 'R0302 ._SN',
MapName = 'rolent',
Location = 'R0302.x',
MapIndex = 21,
MapDefaultBGM = "ed60022",
Flags = 0,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.postgres.fields import JSONField
# Create your models here.
class Customer(models.Model):
id = models.AutoField(primary_key = True)
first_name = models.CharField(max_length=200, null=True)
last_name ... |
from torchvision.datasets import ImageFolder
import os
from download_ffhq import run
#---------------------------------------------------------------------
# Import packages for testing
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
#... |
#!/usr/bin/python
#
# Assignment 3 - Talk Python to Me
# 1520 - Monday
# By: Josh Rodstein - 4021607
# Email: jor94@pitt.edu
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Media class
class Media:
def __init__(self, title):
if not isinstance(title, str):
print("\... |
# Program "Rzut monetą"
# Program wyświetla ile razy wyrzucił reszkę, a ile razy orła na 100 rzutów
import random
numer_rzutu = 0
orzel = 0
reszka = 0
while True:
numer_rzutu += 1
moneta = random.randint(1,2)
if numer_rzutu > 100:
break
elif moneta == 1:
orzel += 1
... |
from conan import ConanFile
from conan.tools.microsoft import is_msvc
from conan.tools.files import export_conandata_patches, apply_conandata_patches, get, chdir, rmdir, copy, rm
from conan.tools.env import Environment
from conans import MSBuild, AutoToolsBuildEnvironment, VisualStudioBuildEnvironment
from conans.tools... |
# listy mozna modyfikować
# lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# print(len(lista))
# print(lista[0])
# print(lista[::2])
# lista.append('ala')
# print(lista)
# lista.insert(3, 'kot')
# print(lista)
# lista.insert(-2, 'kot')
# print(lista)
# print(lista.count(3))
# lista[3] = 'tu buł element 4'
# print(lista)
#
# l... |
from __future__ import print_function
import os, csv, sys, gzip, torch, time, pickle, argparse
import torch.nn as nn
import numpy as np
import scipy.misc
import imageio
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
from torch.utils.data import Datas... |
import os
import json
import re
import string
import random
import numpy as np
from collections import Counter
from tqdm import tqdm
import torch
from torch.utils.data import Dataset, TensorDataset, DataLoader, RandomSampler, SequentialSampler
from .utils import MyQADataset, MyDataLoader
from .zest_evaluate import ... |
# Run hardcoded experiments with the trust-region policy gradient
#
import os
from argparse import ArgumentParser
import warnings
import numpy as np
import gym
import torch as th
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common... |
#coding: utf-8
import pandas as pd
import numpy as np
import time
import re
import os
import json
import logging
from functools import reduce
import sqlalchemy as sql
class Pipeline:
def __init__(self,configDir,logDir=None,logLevel='INFO'):
self.configDir = os.path.abspath(configDir)
cwd = ... |
from user import user
class admin(user):
def delUser(self):
_id = input("ID User a supprimer: ")
monFichier = open("user.txt", "r")
maLine=monFichier.readline()
newfile = ""
while maLine :
if maLine.split(",")[0] != _id:
newfile += maLine
... |
class Solution(object):
def pacificAtlantic(self, matrix):
def fill(ocean, stack):
while stack:
r,c = stack.pop()
if (r,c) in ocean: continue
ocean.add((r,c))
stack.extend([
[nr, nc] for nr, nc in [[r-1,c], [r+1,c], [r,c-1], [r,c+1]]
if 0 <= nr < m and 0 <= nc < n and matrix[r][c] <= mat... |
#Update isReply ::: db.getCollection('tweets').update({"in_reply_to_status_id": "null" }, { $set: {"isReply": "N" } }, false, true)
#Fetch db with ocndition : db.getCollection('tweets').find({"truncated": "false"})
#delete field from all docuement : db.getCollection('tweets').update({}, {$unset: {contributors:1}}... |
import argparse
from torchvision.transforms import Compose, Resize, ToTensor
import cv2
import torch
from model import Unet
def predict(image_path,
checkpoint_path,
save_path):
model = Unet()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.load_state_d... |
# coding=utf-8
import pika
import sys
def Main():
credential = pika.PlainCredentials("alex", "alex")
parameters = pika.ConnectionParameters("localhost")
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# 定义queue
channel.queue_declare(queue="test1")
channel.qu... |
import os
import tensorflow as tf
from tensorflow.contrib import slim
from .networks.decoder_flat import vae_flat_decoder
from .networks.encoder_flat import encoder_flat
from ..callbacks.ctc_callback import CTCHook
from graph_lm.models.estimators.kl import kl
from ..sparse import sparsify
def make_model_vae_ctc_fla... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template("login.html")
if __name__ == '__main__':
app.run()
@app.route('/send', methods=['GET', 'POST'])
def send():
if request.method == 'POST':
username = request.form['user-name']
... |
#!/usr/bin/env python
# coding: utf-8
# python C:\temp\dlg\scripts\dlg-assignment.py
from datetime import datetime
from config import config
import common_utils as c_utils
import pandas as pd
import csv
import logging
import glob
import pyarrow as pa
import pyarrow.parquet as pq
import sys
import os
from os imp... |
def containList(firstList, secondList):
counter = 0
for itemOfFirstList in firstList:
for itemOfSecondList in secondList:
if itemOfFirstList == itemOfSecondList:
counter += 1
return True if counter == len(secondList) else False
# firstList = [
# [2, 3, 1],
# [4,... |
from contextlib import contextmanager
import json
from pathlib import Path
import pickle
import re
from typing import get_type_hints
from typing import TypeVar, Generic
from unittest.mock import Mock, DEFAULT
from .storage import Storage
def eafp(ask, default):
"""
Easier to ask for forgiveness than permissio... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-05-25 06:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bitcoin_crypto', '0032_orderbook_trading_fee'),
]
operations = [
migrations.A... |
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import config
import audio_helper
import os
import str_helper
import requests
app = Flask(__name__)
CORS(app)
# API routes
@app.route("/create/<prefix>", methods=["POST"])
def api_create(prefix):
not_new = True
while n... |
"""
תשע"ו מועד ב שאלה 2
"""
import numpy as np
from numpy import random as rn
import scipy.stats as ss
T=1
r=0.01
sigma1=0.1
sigma2=0.2
S01=10
S02=10
M=50000
n=252
z1=rn.randn(M,n)
z2=rn.randn(M,n)
S1=S01*np.ones((M,n+1))
S2=S02*np.ones((M,n+1))
h=T/n
k=20.4
ro=0.4
for i in range(0,n):
S... |
import pygtk
pygtk.require('2.0')
import gtk
import nltk
import socket
import sys
import subprocess
word_id1 = 0
word_id2 = 0
score1 = 0
score2 = 0
table = [[""]*5 for i in range(5)]
table[2][0] = "m"
table[2][1] = "a"
table[2][2] = "n"
table[2][3] = "g"
table[2][4] = "o"
# class word and count of letters in the wo... |
import numpy as np
import pylab as plt
import fitsio, yaml, os
import argparse
plt.switch_backend("pdf")
plt.style.use("y1a1")
print "----------------------------------------"
print "n(z) recalibration and diagnostic script"
print "Courtesy of Daniel Gruen"
print "-----------------------------------------"
print "I'v... |
"""
Author: JiaHui (Jeffrey) Lu
Student ID: 25944800
"""
import numpy as np
# import matplotlib.pyplot as plt
def function1(x):
return np.power(x, 3) - 2 * x - 5
def function2(x):
return np.exp(-x) - x
def function3(x):
return x * np.sin(x) - 1
def function4(x):
return np.power(x, 3) - 3 * np.... |
from Pages.MediaPages.Media import Media
from selenium.webdriver.common.by import By
from magic_box.find_elements import find_element
from selenium.webdriver.support.ui import Select
from Pages.MediaBrowser import MediaBrowser
import pytest
class PublicationMedia(Media):
def __init__(self, driver):
super(... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def post_list(request, category_id=None, tag_id=None):
content = 'post_list category_id={category_id}, tag_id={tag_id}'.format(
category_id=category_id, tag_id=tag_id)
return HttpResponse(content)
def... |
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
import os
DB_CONNECTION_STRING = os.getenv('DB_CONNECTION_STRING')
DB_ECHO = bool(os.getenv('DB_ECHO'))
|
import sys
input = sys.stdin.readline
from math import log2
def main():
N = int( input())
VW = [ tuple( map( int, input().split()))]
Q = int( input())
vL = [ tuple( map( int, input().split())) for _ in range(Q)]
for v, L in vL:
dp = [0]*(L+1)
while v > 0:
if __name__ == ... |
### Désactive les inscirptions ###
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class NoNewUsersAccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return False
|
# módulo destinado a implementar las bombas.
from PyQt5.QtCore import QThread, pyqtSignal, QObject
from PyQt5.Qt import QTest
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QLabel
from eventos import PositionMoveEvent, ReleaseEvent, ExplodeEvent, \
MoveBombEvent
from parameters import TIEMPO_EXPLOSION... |
"""Create multi-band raster from brightness, greenness, and wetness components"""
import os
import sys
from rgb2pct import RGB
from argparse import ArgumentParser
def make_composite(out_dir, fname, bands):
"""
:param out_dir
:param fname:
:param bands:
:return:
"""
if not os.path.exists(... |
# -*- coding: utf-8 -*-
"""
mundo.py
Created on Wed Oct 7 14:00:00 2020
@author: mlopez
"""
from tablero import Tablero
import random
def print_debug(msg, print_flag=False):
if print_flag:
print(msg)
class Mundo(object):
"""docstring for Mundo"""
def __init__(self, columnas, filas, n_leones, ... |
import sys
sys.stdin=open("input.txt", "r")
'''
# 써야할 자료구조 = stack
: stack을 활용한 문제이다.
# 문제 풀이 아이디어
: 먼저 가능 vs 불가능을 구분해야 한다.
: 스택으로 만들다가 안되면 NO 출력하기
: n을 뽑으려면 1 ~ n까지 일단 넣고 뽑아야 한다.
: + 뽑을 때는 무조건 내림차순이다.
: 현재까지 스택에 넣은 값보다 큰 수가 나오면 그 때까지 스택에 넣고 뽑는다.
: 아니면 스택에서 뽑는데
: 현재... |
print("---Gestor de ventas vehiculares---\n")
modelo = str(input("Modelo a vander: \n"))
CF = int(input("Digite el Costo de fabricación del modelo:\n"))
Ganancia = 0.17
IVI = 0.13
PVC = CF+(CF*Ganancia)+(CF*IVI)
print("El precio total a pagar por",modelo,"es: ¢",PVC) |
import datetime
import json
import random
import string
from django.db import transaction
from django.shortcuts import render, HttpResponse
from carapp.car import Car as cart
from carapp.models import TAddress, Car
from indexapp.models import TBook
from adminapp.models import TUser
def car(request):
try:
... |
from model import *
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
from skimage.io import imsave
def model_fn_base(features, labels, mode, params, net_config, config):
features = tf.cast(features, tf.float32)
logits = make_model(features, mode == tf.estim... |
from collections import namedtuple
n, titles = int(input()), input().split()
Students = namedtuple('Students', titles)
print((sum([int(Students._make(input().split()).MARKS) for _ in range(n)]) / n))
|
from PIL import Image
from PIL import ImageTk
from cmu_112_graphics_mod import *
from Character import *
from PhysicalObjects import *
import math
import time
import random
class Button(object):
def __init__(self,x0,y0,x1,y1,text):
self.x0, self.x1 = x0, x1
self.y0, self.y1 = ... |
from test_client import *
# Let's be sure to use conftest.py for sharing fixtures across multiple files
# Added after the recording but will help some folks.
# For more info, see:
# https://docs.pytest.org/en/6.2.x/fixture.html#conftest-py-sharing-fixtures-across-multiple-files
|
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import transforms,datasets
from torchvision.utils import save_image
class D_Net(nn.Module):
def __init__(self):
super(D_Net, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(1,12... |
import pandas as pd
import numpy as np
import os
import sys
import pickle
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardS... |
def main():
n = int(input("Quantidade: "))
cont_par = 0
cont_impar = 0
while n > 0:
num = int(input())
if num %2 == 0:
cont_par += 1
else:
cont_impar += 1
n -= 1
print("Quantidade de pares: ", cont_par)
print("Quantidade de impares: ", cont_impar)
#... |
import heapq
import copy
import re
import datetime
import sys
from PIL import Image
import math
import operator
from functools import reduce
import os
BLOCK = [[0,0,0],[0,0,0],[0,0,0]] # 给定状态
GOAL = [[0,0,0],[0,0,0],[0,0,0]] # 目标状态
# 4个方向
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
# OPEN表
OPEN = []
# 节点的总数
SU... |
#! usr/bin/python3
from listnode import ListNode
# Recursive
def reverseList(head: ListNode) -> ListNode:
if not head.next:
return head
start = reverseList(head.next)
node = start
while node.next:
node = node.next
node.next = head
head.next = None
return start... |
from flask import Flask, render_template, jsonify
from database import otuOutput, nameOutput, washFreq, metaOutput, sampleJson, sampleJsonAll
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/v1/otu')
def otu():
otuOutputList = otuOutput()
return... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.gis.db import models as gismodels
from django.conf import settings
import logging
import requests
import urllib
logger = logging.getLogger(__name__)
class Film(models.Model):
title = models.CharField... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 11:15:56 2020
@author: bruce
"""
import os
import xlrd as xl
import sys
def countRow(loc):
"""
Documenting
Parameters
----------
loc : a file system path of the location of the workbook file
Returns
----------
None
Example
--... |
from collections import OrderedDict
from cs285.critics.bootstrapped_continuous_critic import \
BootstrappedContinuousCritic
from cs285.infrastructure.replay_buffer import ReplayBuffer
from cs285.infrastructure.utils import *
from cs285.policies.MLP_policy import MLPPolicyAC
from .base_agent import BaseAgent
clas... |
from django.test import TestCase
from backend.grpc_gateway.connection.domain.message_queue import MessageQueue
class MessageQueueTestCase(TestCase):
def test_sharing_queue(self):
class Producer:
def __init__(self, mq):
self.mq = mq
def produce(self, item):
... |
filename = "learning_python.txt"
with open(filename) as file_object:
contents = file_object.read()
print(contents.replace('Python', 'Java'))
|
import string,csv
protocol_type = []
service = []
flag = []
attack_type = []
dos_type = ['back','land','neptune','pod','smurf','teardrop']
probe_type = ['ipsweep','nmap','portsweep','satan']
r2l_type = ['ftp_write','guess_passwd','imap','multihop','phf','spy','warezclient','warezmaster']
u2r_type = ['b... |
#import sys
#input = sys.stdin.readline
def mod(n):
if n > 0:
return -(n//2), n%2
elif n < 0:
return (-n+1)//2 ,(-n)%2
else:
return 0,0
def main():
N = int( input())
if N == 0:
print(0)
return
ANS = []
while N != 0:
N, b = mod(N)
A... |
from .base import *
class WidgetGroup(Widget):
_gfx = {
"": (
("widget_group_topleft", "widget_group_top", "widget_group_topright"),
("widget_group_left", "widget_group_center", "widget_group_right"),
("widget_group_bottomleft", "widget_group_bottom", "widget_group_bot... |
from builtins import len, open
from locale import str
import requests
import xlrd
import json
import pandas as pd
import time
import os
client_id = '6ff8da2ae4d057a6d048' # you have to write your own id
client_secret = '3b6868e71ae5ef6d14a5d8114a3638e84bc22c7a' # you have to write your own secret
id_secret = '?clien... |
import io
import pandas as pd
from boto3 import client
def train_right_eye_sphere_model(config):
try:
print("Model training started...")
# Import the dataset
bucket_file = get_training_data(config)
dataset = pd.read_csv(io.BytesIO(bucket_file['Body'].read()))
# Extract ... |
from __future__ import print_function, division, absolute_import
import tensorflow as tf
import numpy as np
import os
from utils import parameters
import utils.model as model
from tensorflow.contrib.layers import fully_connected
from tensorflow.contrib.layers import xavier_initializer
params = parameters.Parameters()
... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-29 19:23
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('press', '0004_auto_20170529_0040'),
]
operations = [
migrations.Remove... |
class ScrapeCounter:
def __init__(self):
self.totalCoursesCount = 0
self.createdCoursesCount = 0
self.totalSectionsCount = 0
self.createdSectionsCount = 0
self.totalMeetingsCount = 0
self.createdMeetingsCount = 0
self.totalProfessorsCount = 0
self.cre... |
# Generated by Django 3.0.2 on 2020-11-12 12:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogs', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Enquiries',
),
migrations.RemoveField(
... |
import time
from lxml import etree
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class BaiDuwenku:
def __init_... |
from keras.models import load_model
from keras_contrib.layers.normalization.instancenormalization import InstanceNormalization
from keras.engine.topology import Layer
from keras.engine import InputSpec
import tensorflow as tf
import cv2
import matplotlib.pyplot as plt
import numpy as np
from glob import glob
import os
... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from scipy import ndimage
from src import matrix as m
found_lines_colors = ["red", "green", "cyan", "magenta"]
points = [
(1, 4),
(2, 5),
(2, 7),
(2, 9),
(3, 10),
]
input_points = np.array([points])
x_space, y_space = in... |
# debugging
# # Pirates
# greeting = input("Hello, possible pirate! What's the password?")
# if greeting in ["Arrr!"):
# print("Go away, pirate.")
# elif
# print("Greetings, hater of pirates!")
# # correct code
# greeting = input("Hello, possible pirate! What's the password?")
# if greeting in ["Arrr!"] :
# ... |
# pca + optimal transport + circulaire, several source one target
# learn d components from source by pca,
# transform them on target
# use circulaire to learn reg, eta for optimal transform
# learn coupling by learned reg eta
# transform target with weighted source
from os import system
import os
import itertools
imp... |
#!/usr/bin/python
############################
# Application: pylatexpng.py
# Author: Ashley DaSilva
# Date: 2009, May 30
# Version: 0.1
'''Copyright 2009 Ashley DaSilva
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the... |
color=["red","green","white","black","pink","yellow"]
print(color[1:4])
|
from onegov.agency.utils import get_html_paragraph_with_line_breaks
from onegov.org.models import Organisation
from onegov.org.models.extensions import AccessExtension
from onegov.org.models.extensions import PublicationExtension
from onegov.people import Person
from sqlalchemy.orm import object_session
class Extende... |
cad1 = input()
cad2 = input()
cad3 = input()
cad4 = input()
sip = 'SI'
print(sip if (cad1[-2:] == sip and cad2[-2:]==sip and cad3[-2:] == sip and cad4[-2:]==sip) == True else 'NO' )
|
##########################
#User Input #
#Auteur: Marlene Marchena#
##########################
prenom = 'Jules'
age = 10
print("Ton prénom est:", prenom)
print("Ton âge est:", age)
#On va demander au utilisateur son prénom et son âge
prenom_utilisateur = input("Comment tu t'appelle ?")
age_utilisate... |
from fltk import Fl
from game import SimonGame
def main():
win = SimonGame(700, 730)
win.show()
Fl.run()
if __name__ == "__main__":
main() |
################################
# Niveis iniciais #
################################
nv_quartel = 0
nv_estabulo = 0
num_soldados = 0
diplomacia = 0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from sys import argv
from sherlock.config import *
def flatten_scopes(gold_semplus_data):
flattened = []
sentence = []
n = False
for line in [line.strip().split('\t') for line in open(gold_semplus_data)]:
if line ... |
filename = 'learning_python.txt'
with open(filename) as file_object:
lines = file_object.read()
lines = lines.replace('Python', 'C')
print(lines) |
from kubeflow.kubeflow.crud_backend import api, logging
from ...common import utils, status, viewer as viewer_utils
from . import bp
log = logging.getLogger(__name__)
@bp.route("/api/namespaces/<namespace>/pvcs")
def get_pvcs(namespace):
# Return the list of PVCs
pvcs = api.list_pvcs(namespace)
notebook... |
from itsdangerous import URLSafeTimedSerializer,SignatureExpired
from app import app
s=URLSafeTimedSerializer(app.config['SECRET_KEY']) #Serializer for token generation
def generate_token(email):
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
return serializer.dumps(email, salt='email-confirm')... |
# -*- coding: utf-8 -*-
"""
Created on Saturday July 27 17:13:06 2018
@author: vishnu
"""
# noinspection PyUnresolvedReferences
import os, sys, math
#import display from IPython.display
import keras
import pandas as pd
import numpy as np
import seaborn as sns
sns.set_context("notebook", font_scale=1.4)
import matplotli... |
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
# Init app
app = Flask(__name__)
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sconehungus.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_... |
from django.contrib.auth.models import User
from project.api import models
from rest_framework import serializers
import logging
logger = logging.getLogger(__name__)
class PartCategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.PartCategory
fields = ('id', 'name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.