text stringlengths 38 1.54M |
|---|
# coding: utf-8
print("hello world")
#↓の書き方はversion3系ではエラー
#print "hello world"
#文字列を分割して配列(リスト化)
print("hello world".split(" "))
print("文字列結合")
x = "hello"
y = "world"
print(x+y)
print("文字列置き換え")
x = "Hello World"
print(x.replace("o","u"))
print("大文字小文字変換")
print(x.upper())
print(x.lower())
print("結合")
x = ["H... |
import os
from time import sleep
import tflite_runtime.interpreter as tflite
import numpy as np
import cv2
from firebase import firebase
import pandas as pd
import json
CWD_PATH = os.getcwd()
firebase_url = "firebase-url"
firebase = firebase.FirebaseApplication(firebase_url,None)
db_id=0
def make_report(data,filename... |
from unittest import TestCase, main
from socketio.namespace import BaseNamespace
from socketio.virtsocket import Socket
from mock import MagicMock
class MockSocketIOServer(object):
"""Mock a SocketIO server"""
def __init__(self, *args, **kwargs):
self.sockets = {}
def get_socket(self, socket_id='... |
print('Provide answers between 1 and 10 for each of these questions:')
loan_size = int(input('Between 1 and 10, how large is the loan? '))
credit_status = int(
input('Between 1 and 10, how good is your credit history? '))
income = int(input('Between 1 and 10, how high is your income? '))
down_payment = int(input('... |
#!/usr/bin/env python
# coding: utf-8
# Imports
import pandas as pd
import operator
import numpy as np
import geopandas as gpd
import json
import tempfile
import os
import csv
import sys
from datetime import datetime
sys.path.insert(0,'../')
import db_connection as db_con
starttime = datetime.now()
# Get length of t... |
from django.http import HttpResponse
import re
# import os
# from django.utils import timezone
# from django.template import loader
# import random
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.order_by('-created_date')
# post_title = '<ul>'
# f... |
from django.shortcuts import render
# Create your views here.
from jsonschema import ValidationError
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import ... |
from repositories.base_repository import BaseRepository
from database.connection import db
groups_repo = BaseRepository(db['groups'])
|
import inspect
import logging
import socket
import traceback
from datetime import datetime
try:
import simplejson as json
except ImportError:
import json
class LogstashFormatterBase(logging.Formatter):
# The list contains all the attributes listed in
# http://docs.python.org/library/logging.html#logr... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wx
from MenuAbstraction import MenuAbstraction
from MenuPresentation import MenuPresentation
from MenuInteraction import MenuInteraction
from MenuController import MenuController
class BattleshipApp(wx.App):
def OnInit(self):
abstrac... |
import http.server
import requests
import json
import time
import secrets
import threading
import logging
import sys
from socketserver import ThreadingMixIn
from http.server import HTTPServer
from http.server import urllib
from enum import IntEnum
from threading import Event
from argparse import Argum... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import login as auth_login, authenticate, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contr... |
"""
This playbook runs all the pan actions one by one.
"""
import phantom.rules as phantom
import json
from datetime import datetime
from datetime import timedelta
def block_url_cb(action, success, container, results, handle):
if not success:
return
return
def unblock_ip_cb(action, success, contai... |
M = int(input())
mo = [input() for _ in range(M)]
P = int(input())
pattern = [input() for _ in range(P)]
cnt = 0
for i in range(M-P+1):
for j in range(M-P+1):
for x in range(P):
if mo[i+x][j:j+P] != pattern[x]:
break
else:
cnt += 1
print(cnt)
# 플래그 사용해서 문제풀... |
from os import path, getcwd
from re import match, split
import yaml
from collections import OrderedDict
from profit.run import Runner
VALID_FORMATS = ('.yaml', '.py')
"""
yaml has to be configured to represent OrderedDict
see https://stackoverflow.com/questions/16782112/can-pyyaml-dump-dict-items-in-non-alphabetica... |
import click
import logging
from .migrate import Migrant
from .wrapper import coroutine
def setup_logger(verbosity):
log_level = {
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}.get(verbosity, logging.INFO)
logger = logging.getLogger(__package__)
logger.setLevel(log_... |
import pathlib
import re
import typing
import matplotlib.pyplot as plt
import numpy
import pandas
import seaborn as sns
import functions
import plotly.express as px
sns.set(style = "darkgrid")
def RS(array: numpy.ndarray, step: int) -> float:
def compose(array: numpy.ndarray, step: int) -> numpy.ndarray:
... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('news.views',
url(r'^$', 'news', name='news'),
url(r'^(?P<post_id>\d+)/$', 'one_new', name='one_new'),
) |
import boto
import errno
from socket import error as SocketError
from boto.kinesis.exceptions import ProvisionedThroughputExceededException
import time
from bolt import SpoutBase, BoltBase
import collections
import logging
import json
import msgpack
import base64
import msgmodel
import concurrent.futures
import Queue
f... |
from math import floor
from clubsandwich.blt.nice_terminal import terminal
from clubsandwich.blt.state import blt_state
from .view import View
class FirstResponderContainerView(View):
"""
Manages the "first responder" system. The control that receives
BearLibTerminal events at a given time is the first r... |
from textblob import TextBlob
file1 = open("check.txt","r+")
a=file1.read()
print("Original text :",str(a))
b = TextBlob(str(a))
print("\n")
print("Corrected text :",str(b.correct()))
file1.close()
d = open("corrected.txt",'w')
d.write(str(b.correct()))
d.close()
|
# -*- coding: utf-8 -*-
from pymysql.err import (Warning, Error, InterfaceError, DataError,
DatabaseError, OperationalError, IntegrityError,
InternalError,
NotSupportedError, ProgrammingError, MySQLError)
from .conf import DBCONFIG, APPCONFIG
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 21:01:42 2021
@author: praveen
"""
import os
os.chdir('/Users/praveen/kinduct_final_code')
cwd = os.getcwd()
print("Current working directory: {0}".format(cwd))
from kinduct import *
def main():
print(task1_string_conver... |
from flask import Flask, render_template, request
from time import sleep
import os
app = Flask(__name__)
import AES_CBC as acbc
import AES_CFB as acfb
import AES_ECB as aecb
import AES_OFB as aofb
import DES_CBC as dcbc
import DES_CFB as dcfb
import DES_ECB as decb
import DES_OFB as dofb
@app.route(... |
import logging
from jsonutils import Values
from . import ProcessingGenerator
import sanitychecks
class JsonGenerator(ProcessingGenerator):
terms_template = '''
<div class="terms-text">
<h2>Licence summary</h2>
<p>{{/spec/license/summary}}</p>
<h2>Licence type</h2>
<ul>
<li>Open source: {{/auto/license... |
"""Create splits for the dataset.
See ``python create_splits.py --help`` for more information.
"""
import json
import logging
import os
import random
import re
import click
logger = logging.getLogger(__name__)
# helper functions
def _normalize(s):
"""Return a normalized version of s."""
# Remove repeate... |
def foreigned(to_db='default', in_db="operator_main_dbs"):
u""" декоратор для foreign tables """
assert to_db == 'default' and in_db == "operator_main_dbs"
for
for
for
for
|
import base64
import requests
from utils import REQUEST_ERRORS
def file_to_base64(file_name) -> str:
with open(file_name, 'rb') as fp:
return base64.b64encode(fp.read()).decode()
class Training:
URL = 'https://snowboy.kitt.ai/api/v1/train/'
PARAMS = {
'name': 'alice_mdm',
'lang... |
import socket
import threading
import json
def recv_sockdata(the_socket):
total_data = ""
while True:
data = the_socket.recv(1024).decode()
if "END" in data:
total_data += data[:data.index("END")]
break
total_data += data
return total_data
def deal_data(data... |
from Crypto.Util.number import inverse
c=2205316413931134031074603746928247799030155221252519872650080519263755075355825243327515211479747536697517688468095325517209911688684309894900992899707504087647575997847717180766377832435022794675332132906451858990782325436498952049751141
n=2933192249979498578273597604559116493... |
import re
import json
import scrapy
class ArtistsSpider(scrapy.Spider):
name = "artists"
f = open("artists_urls.txt")
start_urls = [url.strip() for url in f.readlines()]
f.close()
def parse(self, response):
artist_url = response.url
img = response.xpath('//img[@id="main_fichacread... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 14:11:52 2020
@author: charm
"""
import dataset_lib as dat
import models as mdl
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.op... |
from django.contrib.auth.models import User
from django.http.response import Http404
from perfil.models import Endereco, Perfil
from .models import ItemPedido, Pedido
from typing import Dict, List
from django.shortcuts import redirect, render
from django.views import View
from sabores import models
from django.contrib ... |
#!/usr/bin/env python3
# Imports
def cm2inch(value):
return value/2.54
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
import pandas as pd
import numpy as np
import seaborn.apionly as sns
lsc = mpl.colors.LinearSegmentedColormap
niceblue = '#64B5CD'
nicered = '#C44E52'
nicey... |
"""
Solve 1 layer shallow water equation [-2pi, 2pi]**3 with periodic bcs
(u,v)_t = -g*grad(h) - Cd*(u,v)*sqrt(u**2+v**2) (1)
h_t = -div( (H+h)*u) (2)
Discretize in time with 4th order Runge-Kutta
with both u(x, y, t=0) and h(x, y, t=0) given.
Using the Fourier basis ... |
def super_digit(num):
digit = 0
while num > 0:
digit += num % 10
num //= 10
if digit < 10:
return digit
else:
return super_digit(digit)
num = int("861568688536788" * 100000)
print(super_digit(num))
|
import turtle
import random
import sqlite3
##전역 변수 선언 부분(turtle)##
swidth, sheight, pSize, exitCount = 300, 300, 3, 0
r, g, b, angle, dist, curX, curY = [0] * 7
##전역 변수 선언 부분(DB)##
con, cur, row, col = None, None, None, None
data1, data2, data3, data4, data5, data6, data7 = 0, 0, 0, 0, 0, 0, 0
i = 0
sql = ""
count =... |
import inspect
# ViewSets define the view behavior.
from django.views.generic import TemplateView
from rest_framework import viewsets, mixins, generics, permissions, status
from rest_framework.decorators import api_view, detail_route
from rest_framework.permissions import IsAuthenticated
from rest_framework.response i... |
from Node import Node
def constructPaths(graph):
"""
Args --> graph, a list of Node objects
Returns --> A list of lists. Each list consists of a list of indices of the nodes to be followed along the path
"""
paths = [ [] for x in xrange(len(graph)) ] # Initialise our list
for i in xrange(l... |
"""
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd... |
from django.conf.urls.defaults import *
from siteapps_v1.ntgreekvocab.models import SimpleCard
urlpatterns = patterns('',
# renders template called <modelname>_list.html
# (r'^$', 'django.views.generic.list_detail.object_list', info_dict),
url(r'^card/all/$',
'django.views.generic.list_detail.objec... |
import os
import time
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from discord_webhook import DiscordWebhook, DiscordEmbed
import schedule
from dotenv import load_dotenv
load_do... |
import pyclesperanto_prototype as cle
import numpy as np
#initialise as float 32 arrays with zeros or array_equal method won't work
#cle.pull returns float 32, np.zeros is float 64
source = np.zeros((10, 10, 10),dtype=np.float32)
source[1, 1, 1] = 1
reference = np.zeros((5, 19, 10),dtype=np.float32)
#will this change... |
# Copyright (c) 2005-2011, NumPy Developers.
# 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 ... |
import os
import threading
import time
def sing(*args):
print('a'*80)
print('-' * 30, '参数args:{}'.format(args))
for i in range(5):
print('i am sing', i)
time.sleep(1)
def dance(args):
print('-' * 30, '参数args:%s' % args)
for i in range(5):
print('iam danc... |
'''
@Date : 01/11/2020
@Author: Zhihan Zhang
@mail : zhangzhihan@pku.edu.cn
@homepage: ytyz1307zzh.github.io
Prepare input instances for retrieve_para.py
'''
import argparse
import json
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument('-input', type=str, default='../ConceptNet/rough_... |
GPU_ID = 1
BATCH_SIZE = 64
VAL_BATCH_SIZE = 104
NUM_OUTPUT_UNITS = 397 # This is the answer vocabulary size
MAX_WORDS_IN_EXP = 36
MAX_ITERATIONS = 40000
PRINT_INTERVAL = 100
# what data to use for training
TRAIN_DATA_SPLITS = 'train'
# what data to use for the vocabulary
ANSWER_VOCAB_SPACE = 'train'
EXP_VOCAB_SPACE ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AntMerchantExpandActivitySignupCreateModel(object):
def __init__(self):
self._activity_code = None
self._ext_info = None
@property
def activity_code(self):
return... |
# -*- encoding: utf-8 -*-
'''
@Time : 2022/04/06 23:52:52
@Author : Yu Runshen
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
'''
# here put the import lib
import sys, os
class Solution:
def climbStairs(self, n):
if n == 1:
return 1
elif n == 2:
return 2
... |
#!/usr/bin/env python
"""
Summarizes resulting reactivities.out of spats based on expected results. Part of Read_Mapping tests.
Usage: python check_reactivities.py --input <> --output <> --linker <> --sequence <>
Options:
--input reactivities.out file from spats
--output File to output result summary
--linker Link... |
import numpy as np
from math import sqrt
from time import time
# Number of points to us in the approximation
N = 10000000
start = time()
# Create a matrix of N paris of numbers
points = np.random.rand( N, 2 )
# Calculate the norm of each row
norms = np.linalg.norm(points, axis = 1)
# Determine if each point is ... |
from __future__ import division
import re
import datetime
import json
import glob
import os
import multiprocessing
import argparse
import hashlib
import random
from bs4 import BeautifulSoup
from pyparsing import Optional, Group, Word, nums, Literal
from tqdm import tqdm
import numpy as np
from toolbox.strings import ... |
from threading import Thread
from lxml import etree
from copy import copy
import logging
import commands
from anansi.xml import XMLMessage,XMLError,gen_element
from anansi.comms import TCPClient
from anansi.config import config
from anansi import log
logger = logging.getLogger('anansi.mpsr')
OBS_TYPES = ['TRACKING', '... |
# class Renderer(object):
# def __init(self, results):
# self.results = results
#
# def __call__(self):
# raise NotImplementedError()
#
# class TrainResultRenderer(Renderer):
# def __call__(self):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridsp... |
"""An example for using the TackEverything package
This example uses an Object Detection model from the TensorFlow git
for detecting humans. Using a simple citizen/cop classification model
I've created using TF, it can now easily detect and track cops in a video using
a few lines of code.
The use of the TrackEverything... |
from itertools import accumulate
from collections import Counter
from math import comb
input()
nums = [int(x) for x in input().split()]
cnts = Counter([0] + list(accumulate(nums)))
ans = sum(comb(cnt, 2) for _, cnt in cnts.items())
print(ans)
|
from TableUtils import VTTable
import sys
import hashlib
basedir = 'C:/Data/Genomes/PlasmodiumFalciparum/Release_21/OriginalData_04'
# Build index of all available studies
tableStudies=VTTable.VTTable()
tableStudies.allColumnsText=True
#tableStudies.LoadFile(basedir+"/PartnerStudies.txt")
tableStudies.LoadXls(b... |
import os
import csv
import re
from getpass import getpass
from email_utils import Email, EmailConnection
from file_utils import FileUtils
from datetime import datetime
f_utils = FileUtils()
# ------ Variables gloables de configuration ------
SERVER_SMTP = "smtp.gmail.com"
SERVER_PORT = 587 # Port SMTP
#FROM = "refl... |
#library
import re as e
import dns.resolver
import socket as soc
import smtplib as sl
#enter Address to verify
addrtov = input("enter Email : ")
#specifying regular expression
verified = e.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', addrtov)
if verified == None:
print('Bad Syntax... |
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls', namespace='blog')),
url(r'^accounts/', include('accounts.urls')),
... |
# -*- coding: utf-8 -*-
import requests
from config import TG_TOKEN, USE_PROXY, PROXY, CHAT_ID
__author__ = 'ihciah'
class TGBot:
@staticmethod
def send_message(text, user=0):
tg_message_url = "https://api.telegram.org/bot%s/sendMessage" % TG_TOKEN
user = int(user)
data = {"chat_id":... |
def Max2(n,k):
for i in range(len(n)):
if(n[i]>=k):
return i
return None
def Max(n,k,first,last):
if n[0] >= k:
return 0
if(n[len(n)-1]<k):
return None
else:
if((last-first)<=1):
if(n[first]>=k):
return first
else:
... |
import json
import boto3
import base64
import re
import numpy as np
lambda_func = boto3.client('lambda')
lambda_name = ""
def lambda_handler(event, context):
global lambda_name
lambda_name = event['functionId']
memory = linear_algorithm()
set_lambda_memory_level(memory)
return {'statusCode': 200,... |
import builtins
import unittest
import ex3_5
class MyTestCase(unittest.TestCase):
def test_case_1(self):
input_value = "1\n2\n1\n3\n2\n3"
expected = "1/4"
self.common_test(input_value, expected)
def test_case_2(self):
input_value = "3\n6\n1\n6\n4\n9"
expected = "3/4"
... |
#Acceleration and angular acceleration visualization program
# July 7, 2020
# Yuto Nakayachi
import sys
import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Variable to get real value
MPU9250A_2g = 0.000061035156 # 0.000061035156 g/LSB
MPU9250A_4g = 0.000122070312 # 0.00... |
from nmr import *
import fornotebook as fnb
fullPath = '/Users/stupidrobot/ActiveProjects/exp_data/ryan_cnsi/nmr/151012_Annex_162C_Tris_RT_ODNP/'
close('all')
fl = fnb.figlist()
#overNight,fl.figurelist = integrate(fullPath,[42],integration_width=75,first_figure=fl.figurelist,pdfstring='overNight')
#overNight.data *=... |
def main():
t = input("First time? ")
t1= input("Second time? ")
t2= input("Third time? ")
a = float(t)* 0.299792
a1 = float(t1)*0.299792
a2 = float(t2)*0.299792
print (a)
print(a1)
print(a2)
return
main()
|
import dateutil.parser
import numpy as np
def sort_log(log_string):
lines = np.asarray(log_string.split('\n')[:-1])
times = [dateutil.parser.parse(line[1:27]) for line in lines]
sort_indexes = np.argsort(times)
print('\n'.join(lines[sort_indexes]))
|
"""
Leetcode #989
"""
from leetcode.utils import List
class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
if not A:
return list(k)
if not K:
return A
for i in reversed(range(len(A))):
# 1 2 0 0
# 3 4
... |
import os
import csv
from datetime import datetime
import boto3
from botocore.exceptions import ClientError
date = datetime.today().strftime("%d-%m-%Y")
dir_name = "Reports"
fields = [
"SI No",
"Instance Name",
"Instance Id",
"Elastic IP",
"Private IP",
"Instance State",
]
fields_unassociated ... |
#!/usr/bin/env python
"""
deletes the first line
necessary for xml output of xml.dom.ext.PrettyPrint to help
IE 6 and 7 to read the webpage in standard mode.
otherwise it falls back to the stupid quirks mode and everything is fubar
"""
def delFirstLine(fn):
"""
deletes first line
@fn: string of file name
... |
from keras.models import Sequential, Model, Input
from keras.layers import Dot, Dense, Dropout, Embedding, Reshape, Conv1D, MaxPooling1D
from keras.layers.merge import Concatenate
from keras.callbacks import ModelCheckpoint
from keras import metrics, utils, losses
from keras.utils.vis_utils import model_to_dot
from skl... |
from django.shortcuts import render
from static.hotel.bd.connection import conn
# Create your views here.
def suites():
with conn.cursor() as read:
sql = "select id, identifica from tb_suites where sit = 1"
read.execute(sql)
suites = read.fetchall()
read.close()
return suites... |
# Mirko Mantovani
class UndirectedGraph:
def __init__(self):
self.graph = {}
def __repr__(self):
return 'Graph:'+ str(self.graph)
def add_node(self, node):
if node not in self.graph:
self.graph[node] = {}
def add_edge(self, i, j, weight):
if i not in self... |
#Efetuar a leitura de quatro números inteiros e apresentar os números que são divisíveis, ao mesmo tempo,
#por 2 e 9
print('Apresenta os números que são divisíveis por 4 e 9')
i=1
number=[]
while i<=4:
a=int(input('Digite um número: '))
if a%4==0 and a%9==0:
number.append(a)
i=i+1
if len(number) ... |
#!/usr/bin/env python
#
# BakeBit example for the basic functions of BakeBit 128x64 OLED (http://wiki.friendlyarm.com/wiki/index.php/BakeBit_-_OLED_128x64)
#
# The BakeBit connects the NanoPi NEO and BakeBit sensors.
# You can learn more about BakeBit here: http://wiki.friendlyarm.com/BakeBit
#
# Have a question about... |
#!/usr/local/bin/python2.7
# encoding=utf8
'''
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
first should = return [0, 1]
second should = return 2 7
'''
nums = [2, 7, 11, 15]
target = 9
dic = {}
for i, num in enumerate(nums):
if num in dic:
print [dic[num], i] ## prin... |
"""
GSSHA-based model using gsshapy.
"""
import os
import geopandas as gpd
import param
from gsshapy.modeling import GSSHAModel
class RoughnessSpecification(param.Parameterized):
"""Abatract class for a parameterized specification of surface roughness."""
__abstract = True
# If we could modify cod... |
#This program determines if a number is cousin or not
number = int(input('Dame un numero para determinar si es primo: '))
if number > 1:
I_think_hes_a_cousin = True
for divider in range(2, number):
if number % divider == 0:
I_think_hes_a_cousin = False
else:
I_think_hes_a_cousin = False
if I_think_hes_a_cous... |
#Para declarar uma variável global dentro de function
global variavel
#Variável global
f= 0
print(f)
f = "abc"
print(f)
#Forma de Concatenar
print("Isto é uma string " + str(123))
#Criar Função equivale ao método no c#
#Variável local
def PrimeiraFuncao():
global f
f= "def"
print(f)
PrimeiraFuncao()
... |
"""
This module is part of the 'farben' package,
which is released under MIT license.
"""
from ..palette import Palette
from ..utils import hex2rgb
class Copic(Palette):
"""
Holds Copic® utilities
"""
# Identifier
identifier = "copic"
# Dictionary holding fetched colors
sets = {
... |
from agents.agent import Agent
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from torch.utils.data import SubsetRandomSampler, BatchSampler
import numpy as np
class PPOAgent(Agent):
def __init__(self, state_space: int, ac... |
# Fecha: 12 de Abril de 2016
# Autora: Yurani Melisa Palacios Palacios
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Background
# In this ssesion we will complete our study of the 1D random walk and move on to applications in higher
# dimensions. In particular we will prepare our way to... |
import re
validation_schemes = {
"byr": "^(19[2-9][0-9]|200[0-2])$",
"iyr": "^(201[0-9]|2020)$",
"eyr": "^(202[0-9]|2030)$",
"hgt": "^((1[5-8][0-9]|19[0-3])cm)|((59|6[0-9]|7[0-6])in)$",
"hcl": "^#[0-9a-f]{6}$",
"ecl": "^(amb|blu|brn|gry|grn|hzl|oth)$",
"pid": "^[0-9]{9}$",
"cid": ""
}
... |
"""
@author: xuanke
@time: 2020/1/11
@function: 对sys模块进行操作
"""
import sys
def test_dynamic():
"""
sys动态属性
:return:
"""
# 接收命令行参数,更复杂的传参,可以使用argparse
print(sys.argv)
# 打印python解释器搜索模块的路径
print(sys.path)
# 获取已经加载的模块
print(sys.modules)
def test_static():
"""
... |
import json
from sseclient import SSEClient as EventSource
from kafka import KafkaProducer
def get_wiki_recent_changes(producer):
url = 'https://stream.wikimedia.org/v2/stream/recentchange'
try:
for event in EventSource(url):
if event.event == 'message':
try:
... |
from sklearn import tree
from sklearn import svm
from sklearn import neighbors
from sklearn import discriminant_analysis
from sklearn import linear_model
dt = tree.DecisionTreeClassifier()
# CHALLENGE - create 3 more classifiers...
# 1
lsvc = svm.LinearSVC()
# 2
kn = neighbors.KNeighborsClassifier(3)
# 3
svc = svm... |
from graphs.graph import Graph
from graphs.node import Node
from graphs.edge import Edge
from graphs.tests.test_utils import compare_graphs, get_default_graph
from pytest import raises
def test_find_node_in_graph():
graph = get_default_graph()
expected_path = ["a","c","f"]
actual_path = graph.breadth_first... |
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
'''双指针,快慢指针,时间复杂度O(n) 空间复杂度O(1)'''
index = 0
for i in range(len(nums)):
if nums[i] != val:
nums[index] = nums[i]
index += 1
print(index, nu... |
from gym.envs.registration import register
register(
id='SingleVideoEnv-v0',
entry_point='SVE.SVE:SingleVideoEnv',
) |
#!/usr/bin/python
# coding=utf-8
import sys
import getopt
import os
import multiprocessing
#Función para abrir y leer archivo ingresado por terminal.
def LecturaArchivo(ruta, tamanio, cola_inicial):
EOF = False
#Abrir archivo para lectura.
fd = os.open(ruta, os.O_RDONLY)
#Bucle para particionar y le... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 22:16:31 2018
@author: chakyu
"""
import sys
import os
import time
time.sleep(2.5)
os.system('clear')
print('-'*50)
print('The platform you are on is: %s' % sys.platform) |
#Riccardo Seppi - MPE - HEG (2019) - 25 October
#This code reads halo masses from DM simulations (GLAM)
#builds HMF and fits them to models with fixed cosmological parameters
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import uniform
from scipy.stats import norm
from bayesco... |
import pyrebase
config = {
"Service key of firebase"
}
firebase=pyrebase.initialize_app(config)
storage=firebase.storage()
path_on_cloud = "/Storage/TaskImage/AAA00"
path_on_local = "C:/Users/Administrator/Pictures/firebase_downloaded/"
all_files = storage.child(path_on_cloud).list_... |
"""
Tegner en retvinklet trekant
"""
import turtle
myTurtle = turtle.Turtle()
myTurtle. forward(50)
myTurtle.left(135)
myTurtle. forward(70)
myTurtle.left(135)
myTurtle. forward(50)
myTurtle.left(120)
turtle.done() |
from move import BoardMove
class TicTacToeBoard:
BOARD_SIZE = 3
EMPTY = None
def __init__(self):
self._board = self.initialize_board()
@property
def board(self):
return self._board
def initialize_board(self):
return [ [self.EMPTY] * self.BOARD_SIZE for row in range(se... |
import json
from copy import deepcopy
from schematics import types
from schematics.schema import Field
from .base import PyLexObject, SlotsProperty, GenericAttachmentsProperty
from .input import LexInputEvent
class ResponseCardProperty(PyLexObject):
version = types.IntType()
contentType = types.StringType('... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 2, 2015
# Question: 019-Remove-Nth-Node-From-End-of-List
# Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# ==================================... |
# coding: utf-8
import dataset
class Banco:
def saveUsuario(self, nome, usuario, senha, tipo):
with dataset.connect('sqlite:///pizzaria.db') as db:
if ( self.getUsuario(usuario, senha) ):
return False
else:
return db['usuario'].insert(dict(nome=nome, usuario=usuario, senha=senha, tipo=tipo))
def g... |
# Copyright 2019 Alethea Katherine Flowers
#
# 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 or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.