text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
"""
disk_check.py
Parse kstat for scsi device errors.
Copyright (C) 2013 Nexenta Systems
William Kettler <william.kettler@nexenta.com>
"""
import functions
import sys
# The error types can be individually tracked.
errors = {
'Soft Errors': False,
'Hard Errors': True,
'Transport ... |
from spira.yevon.aspects.base import __Aspects__
from spira.yevon.geometry.ports.port_list import PortListParameter
from spira.core.transformable import Transformable
from spira.yevon.gdsii.elem_list import ElementListParameter
from spira.core.parameters.descriptor import Parameter
from spira.yevon.process.gdsii_layer ... |
list_of_birds = ['peacock', 'rooster', 'bluejay', 'cardinal']
# modify the first element
list_of_birds[0] = 'sparrow'
print(f'the first bird in the list is a {list_of_birds[0]}')
print(f'the second bird in the list is a {list_of_birds[1]}')
print(f'the third bird in the list is a {list_of_birds[2]}')
print(f'the four... |
# http://www.pythonchallenge.com/pc/def/map.html
orig_str = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb " \
"gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. " \
"lmu ynnjw ml rfc spj."
#orig_str = "p... |
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
while(1):
pygame.event.pump()
e = j.get_axis(0)
print (e)
|
"""
This example uses docopt with the built in cmd module to demonstrate an
interactive command application.
Usage:
view create_room <room_type> <room_name>...
view add_person <fname> <lname> <person_job> [<accom>]
view display_all_offices
view display_greeting
view print_room <room_name>
view p... |
import torch
from torch import nn
from models.base_structure import ConvBNAct, ResModule
import numpy as np
class BaseLayer(nn.Module):
def __init__(self, channles, **kwargs):
super(BaseLayer, self).__init__()
mid_channels = channles // 2
self.conv1 = ConvBNAct(3, mid_channels, 3, 1, 1, **... |
# -*- coding: utf-8 -*-
#
# Copyright © 2013 Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""Support for pytest framework."""
# Standard library imports
import os
import os.path as osp
# Local imports
from spyder_unittest.backend.runnerbase import Category,... |
def bin_sum(n, SeriesA, SeriesB):
SeriesC = []
add = 0
for i in range(0, n):
if sum([add, SeriesA[i], SeriesB[i]]) == 0:
SeriesC.append(0)
elif sum([add, SeriesA[i], SeriesB[i]]) == 1:
SeriesC.append(1)
add = 0
elif sum([add, SeriesA[i], SeriesB... |
# -*- coding: mbcs -*-
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
m... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... |
import numpy
import itertools
import sys
import time
import matplotlib.pyplot
class MLP:
trained_ann = {}
def train(x, y, net_arch, max_iter=5000, tolerance=0.0000001, learning_rate=0.001, activation="sigmoid",
debug=False):
"""
train(x, y, w, max_iter, tolerance, lea... |
import pygame
from gettext import gettext as _
from config import Entries, DefaultValues
from menu import Menu, MenuItem, MenuGroup
class Scene(object):
def __init__(self, context, name, scene_speed=40):
self._name = name
self._exit = context.exit
self._scene_speed = scene_speed
... |
from django.test.testcases import FSFilesHandler
from rest_framework.test import APILiveServerTestCase
class _TestFilesHandler(FSFilesHandler):
def get_base_dir(self):
return "api/tests/test_files/"
def get_base_url(self):
return "/"
class TestFileServerTestCase(APILiveServerTestCase):
... |
from pypokerengine.players import BasePokerPlayer
from pypokerengine.utils.card_utils import gen_cards, estimate_hole_card_win_rate
NB_SIMULATION = 200
Players = 4
class HonestPlayer(BasePokerPlayer): # Do not forget to make parent class as "BasePokerPlayer"
# we define the logic to make an action through this ... |
import sys
from collections import deque
def bfs(y, x, group):
g[y][x] = group
d[y][x] = 0
bfs_q.append((y, x))
q = deque([(y, x)])
while q:
b, a = q.popleft()
for i in range(4):
ny = b+dy[i]
nx = a+dx[i]
if 0 <= ny < N and 0 <= nx < N ... |
"""Ezviz API."""
from __future__ import annotations
import hashlib
import logging
from typing import Any
from uuid import uuid4
import requests
from pyezviz.camera import EzvizCamera
from pyezviz.cas import EzvizCAS
from pyezviz.constants import (
DEFAULT_TIMEOUT,
FEATURE_CODE,
MAX_RETRIES,
DefenseMo... |
fin = open("A-large.in", 'r')
fout = open("large.out", 'w')
t = int(fin.readline())
for cases in range(1, t+1):
n = int(fin.readline())
raw_in = fin.readline().split()
parties = []
people = 0
for i in range(n):
parties.append([str(unichr(i+65)), int(raw_in[i])])
people += int(raw_i... |
from django.urls import path
from . import views, apiviews
from rest_framework_simplejwt.views import TokenRefreshView
app_name = "assignment"
urlpatterns = [
path("home/", views.home_view, name="home"),
path("student/", views.student_view, name="student"),
path(
"student_detail/<int:student_id>/"... |
import unittest
from zigzag_conversion import Solution
from ddt import ddt, data, unpack
@ddt
class TestLongestPalindrome(unittest.TestCase):
def setUp(self):
self.s = Solution()
@data(
["ABC", 3, "ABC"],
["ABCDE", 3, "AEBDC"],
["ABCDEF", 3, "AEBDFC"],
["ABCDEFGHI", 3, ... |
import pickle
with open('train_song_data_1543840506.251837.pkl', 'rb') as unpkl:
trainSongData = pickle.load(unpkl)
file = open('popularity_rankings.txt', 'w')
for song in trainSongData:
print(song[2])
file.write(str(song[2]) + '\n')
# print('song name: {}, \n song popularity: {}'.format(song[0]['name'... |
#!/usr/bin/env python3
import re
import sys
import os
import getopt
import json
def Version():
print(" ====verison is V1.0, write by kkzou=====")
exit()
def Usage():
print("""
-e gene and exon file,the gene name must exist.
-r refGene.txt , if you have not this file ,this command l... |
# -*- coding: utf-8 -*-
import os
if os.path.exists( r'\\10.99.1.6\Digital\Library\hq_toolbox' )==False and os.path.exists(r'\\XMFTDYPROJECT\digital\film_project\Tool\hq_toolbox')==False :
raise IOError()
#####################################################################################
import maya.cmds as cmds... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2016-11-22 10:15:31
# Project: pyspider
import re, requests, hashlib, time
from pyspider.libs.base_handler import *
# import pymysql
# import sys, json
class Handler(BaseHandler):
crawl_config = {
}
search_list = ['小麦粉', '低筋粉', '全麦面粉', '高筋面粉'... |
# Copyright (c) 2013-2015 Siphon Contributors.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for data conversion and presentation."""
import numpy as np
def get_wind_components(speed, wdir):
r"""Calculate the U, V wind vector components from the speed... |
import json
import os.path
import requests
import traceback
from django.conf import settings
class MoboltClient(object):
"""
Mobolt API wrapper
"""
def __init__(self, api_key, logger):
"""
Initializes the MoboltClient
"""
self.api_key = api_key
self.logger = logg... |
# coding=utf8
import re
state_pattern = re.compile('\s([a-z|_|.]+?:s)[\s|)]')
city_pattern = re.compile('\s([a-z|_|.]+?:c)[\s|)]')
river_pattern = re.compile('\s([a-z|_|.]+?:r)[\s|)]')
place_pattern = re.compile('\s([a-z|_|.]+?:p)[\s|)]')
lake_pattern = re.compile('\s([a-z|_|.]+?:l)[\s|)]')
location_pattern = re.comp... |
import os
import datetime
import base64
import uuid
import xlsxwriter
from flask import render_template, redirect, url_for, request, g, jsonify, abort, send_file
from flask_login import current_user, login_user, logout_user, login_required
from werkzeug.urls import url_parse
from flask_admin import Admin, AdminIndexVie... |
from .elixir import megacam_to_sdss, sdss_to_megacam # NOQA
from .msun import solar_mag # NOQA
from .wircam import wircam_vega_to_ab # NOQA
from .hst_cousins import ACS_606_814_to_VRI, ACS_475_814_to_BVRI # NOQA
from .hst import WFC3_275_336_to_u, WFC3_110_160_to_JK, ACS_475_814_to_gri # NOQA
from .hst import ACS_... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class MedicalItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
p_classify = scrapy.Field()
#p_href... |
"""
from leetcode.com/problems/jewels-and-stones
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinc... |
import logging
from pathlib import Path
FS_DIR = Path("freesurfer/")
SUBJECTS_DIR = Path(FS_DIR / "subjects")
log = logging.getLogger(__name__)
def test_fs_subj_works(caplog, install_gear):
"""Make sure license and subject get installed."""
caplog.set_level(logging.DEBUG)
install_gear("fs_subj.zip")
... |
from flask import Blueprint
api_v1 = Blueprint('api_v1', __name__)
from knowledge.apis.v1 import resources
|
__author__ = 'zoulida'
# -*- coding: utf-8 -*-
import pandas as pd
import baostock as bs
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
#获取给定时间段的股票交易信息
def get_stock_data(t1,t2,stock_name):
lg = bs.login()
print('login respond error_code:' + lg.error_code)
print('login respond ... |
#!/urs/bin/env python3
"""Experimenting with debugging"""
__author__ = 'Luke Swaby (lds20@ic.ac.uk)'
__version__ = '0.0.1'
def buggyfunc(x):
"""Recursively divide x by all natural numbers < x
"""
y = x
for i in range(x):
y -= 1
if y == 0:
break
z = x/y
return z... |
"""
This file holds all settings and configuration for backend searching
"""
ELASTIC_SEARCH_PORT = 9200
ELASTIC_SEARCH_HOST = "localhost"
ELASTIC_SEARCH_URL = ELASTIC_SEARCH_HOST + ":" + str(ELASTIC_SEARCH_PORT)
ES_INDEX_NAME = "test2"
|
from rich.traceback import install
from rich import print as rprint
import numpy as np
import matplotlib.pyplot as plt
import time
install()
import simplifyline
from simplifyline import simplify_line_2d, MatrixDouble
example_points = np.load('fixtures/points/example_1.npy')
rprint(example_points.shape)
# print(exampl... |
#--------------------------------------
# Declaration:
# lambda parameters : expression
two = lambda : 2
sqr = lambda x:x*x
pwr = lambda x, y : x ** y
for a in range(-2, 3):
print(sqr(a), end=' ')
print(pwr(a, two()))
print('-'*20)
#--------------------------------------
print('Standard Functions:')
def prin... |
import functools
from flask import session, jsonify, g
from ihome.utils.response_code import RET
# 判断用户是否登录
def login_required(f):
# 被装饰器装饰的函数,默认会更改其__name__属性
@functools.wraps(f) # 防止装饰器去装饰函数的时候,被装饰的函数__name__属性被更改的问题
def wrapper(*args, **kwargs):
# if 没有登录:
user_id = session.get("user... |
# -*- coding: utf-8 -*-
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
def set(id, data):
r.set(id, data)
def get(id):
return r.get(id)
|
from django.db import models
from django.db.models import ForeignKey
from common.models import BaseModel
from config.models.attr_spec import AttrSpec
# 属性值
class AttrValue(BaseModel):
attr_value_id = models.AutoField(primary_key=True, verbose_name='属性值标识')
attr_value = models.CharField(max_length=30, verbose... |
import numpy as np
import DateTimeTools as TT
from .GetStationInfo import GetStationInfo
from .GetDataAvailability import GetDataAvailability
def GetLonChain(lat,dlat=5.0,lonr=[-180.0,360.0],Network=None,
Date=None):
'''
Get a longitudinal chain of ground magnetometers.
Inputs
======
lat : float
Approxim... |
# https://pika.readthedocs.io/en/0.10.0/examples/twisted_example.html
#
# Stanley H.I. Lio
# hlio@hawaii.edu
# Ocean Technology Group
# University of Hawaii
# All Rights Reserved. 2018
import sys, logging, json, time, socket, zmq
from os.path import expanduser, basename
sys.path.append(expanduser('~'))
from twisted.int... |
import io
import warnings
import numpy
import torch
from syft.workers.abstract import AbstractWorker
# Torch dtypes to string (and back) mappers
TORCH_DTYPE_STR = {
torch.uint8: "uint8",
torch.int8: "int8",
torch.int16: "int16",
torch.int32: "int32",
torch.int64: "int64",
torch.float16: "floa... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import pandas_datareader as pdr
import pandas as pd
import datetime
import sys
import os
import json
# Import Matplotlib's `pyplot` module as `plt`
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy as cp
import sys
ticker = sys.a... |
from sys import exit
from random import randint
class Game(object):
def __init__(self, start):
self.deck = [
"Introduction",
"Problem",
"Closing",
"Flow Chart",
"Buzzwords"
]
self.awake = 10
self.pee =... |
from django.shortcuts import render
from app_silkshadow.models import item
from forms import feedback
# Create your views here.
def home(erquest):
return render(erquest,'app_silkshadow/home.html')
def products(request):
item_list=item.objects.all()
my_dict={'item_list':item_list}
return render(request,... |
import socket
from threading import *
from time import *
class Chatroom:
socket_list = []
user_info = {"John": "12345"}
def __init__(self, sock):
self.sock = sock
def send(self, data):
self.sock.send(bytes(data, encoding="utf-8"))
def recv(self):
data = str(self.sock.rec... |
import numpy as np
import enum
instr_ex = """
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
"""
@enum.unique
class Op(enum.Enum):
acc = "acc"
jmp = "jmp"
nop = "nop"
def parse(s):
ops = []
for line in s.strip().splitlines():
s_op, s_arg = line.split()
op = Op(s_o... |
import sublime_plugin
from html.entities import codepoint2name as cp2n
class EncodeHtmlEntities(sublime_plugin.TextCommand):
def run(self, edit, **args):
view = self.view
for sel in view.sel():
buf = []
for pt in range(sel.begin(), sel.end()):
ch = view.s... |
import argparse, numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--inFile", type=str, default="./day6Input.txt", help="file contianing input key")
args = parser.parse_args()
with open(args.inFile, "r") as f:
commands = [x.strip() for x in f.readlines()]
grid = np.zeros((1000,1000), dtype=np.i... |
#!/usr/bin/env python
import numpy as np
import cv2
import os
import random
import json
import math
import collections
import utils
class Dataset():
def readImage(self, path):
im = cv2.imread(path)
if im is None:
return None
im = cv2.res... |
from database import SQLite
class Message():
def __init__(self, id, content, sender_id, company_id):
self.id = id
self.content = content
self.sender_id = sender_id
self.company_id = company_id
def to_dict(self):
message_data = self.__dict__
return message_data
... |
# name: Gerry Jenkins
# youtube channel: https://youtube.com/gjenkinslbcc
# program: rock paper scissors
# version using 'lookup table' program structure
import random
prompt = "Enter your choice:\nR or r for rock\nP or p for paper\nS or s for scissors\nQ or q to quit\n"
# dictionary with entries to lookup result
... |
from .abstract_model import Model
from .launch_model import LaunchModel
from .settings_model import SettingsModel
__all__ = ['LaunchModel', 'Model', 'SettingsModel']
|
#这个题如果用寻路的方法做是不行滴。。。
''' [ 1, 5, 9],
[10, 11, 13],
[12, 13, 15] '''
#如果一直在右/下取较小值走到了9,就没法再回到第二行开头的10
下面的方法,按值二分,而非传统的按有序数组下标二分
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
row, col = len(matrix), len(matrix[0])
if k==1:
return matrix[0][... |
class Fibonacci(object):
"""
A Fibonacci sequence is a series where the next term is the sum of
previous two terms. The first two terms of the Fibonacci sequence is 0
followed by 1.
"""
def __init__(self, n, term_1 = 0, term_2 = 1, next_term = 0):
self.n = n
self.term_1 = term_1
... |
import json
import uuid
import web3
from eth_account.messages import defunct_hash_message
from web3 import Web3
class BlockChainUtil(object):
def __init__(self, provider_type, provider):
if provider_type == "HTTP_PROVIDER":
self.provider = Web3.HTTPProvider(provider)
elif provider_t... |
from django.urls import path
from .views import Home, Contact,Singleproject,Multipleproject,Aboutus
urlpatterns = [
path('',Home, name='home'),
path('contact/',Contact, name='Contact'),
path('project/<int:id>/',Singleproject, name='singleproject'),
path('multipleproject/',Multipleproject, name='Multiple... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 09:49:52 2019
@author: 姜
"""
#一个try就有一个except
try:
" 框住了你感觉会抛出异常的代码 "
print("41223123")
print( "hahaha")
except:
" try代码块里的代码如果抛出异常了,该执行什么内容"
print( u"哈哈")
else:
"try代码块里的代码如果没有跑出异常,就执行这里"
print( "hoho")
finally:
"不管如何,finally里的代码,是总会执行的... |
# this is not for the snake game , may be for another like space invaders or, hurdle cross, or silimar obstacle based games
import pygame
from random import randint
from package.constants import *
from package.snake import Direction, Snake
pygame.init()
win = pygame.display.set_mode((width, height))
pygame.displa... |
#!/usr/bin/env python
def xorss(s1,s2): # xor for strings - non repetitive
if len(s1) > len(s2):
return "".join([chr(ord(s1[i])^ord(s2[i])) for i in range(len(s2))])
return "".join([chr(ord(s1[i])^ord(s2[i])) for i in range(len(s1))])
txt = xorss("1c0111001f010100061a024b53535009181c".decode('hex'),"686974207... |
#dictionary example keys onthe left
#values on the right side Key value pairs
addresses = {
"Hiwi":"Shantly",
"Sam":"Potomac",
"Ermi":"Silver Spring",
"Maki":"Beltsvill"
}
print(addresses)
for k in addresses.keys():
print(k,"is in",addresses.get(k),end=".\n")
'''key's are the once
in the left side... |
import random
class ShipContent:
def __init__(self, name, capacity=0, energycosts=0):
self.name = name
self._encost = Stat(energycosts)
self._cap = Stat(capacity)
def __str__(self):
return self.name
def __eq__(self, other):
return str(self) == str(other)
de... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'RestoreVault.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impo... |
def dec2bin(target):
amari = []
while target != 0:
amari.append(target % 2)
target = target // 2
amari.reverse()
return amari
print(dec2bin(26)) |
"""
This is a core module for Telegram bot version.
Adjusts bot replies to user command/messages.
"""
import hashlib
import logging
import time
from typing import Dict, Union
import requests
from telegram import Bot, Message
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Comm... |
with open("rosalind_iev.txt", "r") as f:
v, w, x, y, z, _ = map(int, f.readline().strip().split())
print(2*(v+w+x) + 1.5*y + z) |
import os
from dotenv import load_dotenv
import telebot
import requests
from ocr import TextScanner
from nlp import ExtractiveSummarizer
from PIL import Image
import numpy as np
load_dotenv()
API_KEY = os.getenv("token")
print("Initializing ocr scanner....")
scanner = TextScanner()
print("Done.")
print("Initializing... |
# encoding= utf-8
import logging.handlers
import datetime
import time
import pymongo
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
#import importlib #py3
#importlib.reload(sys)#py3
reload(sys)#py2
sys.setdefaultencoding('utf8')
logger = logging.getLogge... |
# directory management:
# delete all previous memory maps
# and create dirs for checkpoints (if not present)
import os
import shutil
from tempfile import mkstemp
import numpy as np
import algorithms.dqn.params as params
from util.sumtree import SumTree
class Memory():
def __init__(self, Model):
# crea... |
class Solution:
def countNegatives(self, grid: List[List[int]]) -> int:
count = 0
cols = len(grid[0])
print(cols)
for row in grid:
for j in range(cols - 1, -1, -1):
if row[j] >= 0:
break
count += 1
... |
# Generated by Django 2.2.4 on 2019-10-26 04:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('steamify', '0004_alloweddevice_created_at'),
]
operations = [
migrations.AddField(
model_name='alloweddevice',
name=... |
#! /usr/bin/env python3
from sys import argv
from misc import str_list, is_number
from table import SymbolTable
class Token:
def __init__(self, token_name:str, token_value:str=None, line_number:int=None):
"""Token constructor
Attributes
token_name The name of the token (e... |
#Mothur tutorial
#Considering we have a directory called data with the directories called mothur, process, raw and references.
#Get into process directory
cd data/process
#Start mothur
mothur
#Set input and output directories
set.dir(input=../raw) #raw directory that contains all our raw files
set.dir(output=.) #a... |
from cs50 import get_int
print("Number: ", end='')
card_number = get_int()
card_number_list = list(map(int, str(card_number)))
leng = len(card_number_list)
j = 1
summ1 = 0
summ2 = 0
summ3 = 0
i = int(leng - 1)
while i >= 0:
if j % 2 == 0:
summ1 += int((card_number_list[i] * 2) % 10 + (card_number_list[i] *... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
massfloors = UnwrapElement(IN[0])
elementlist = list()
for item in massfloors:
try:
elementlist.append(item.Document.GetElement(item.OwningMassId).ToDSType(True))... |
from rest_framework import serializers
from taggit_serializer.serializers import (TagListSerializerField,
TaggitSerializer)
from taggit.models import Tag
from parladata.models import *
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Per... |
import csv
filepath='C:/.../somename.csv'
with open(filepath,'r') as f:
reader = list(csv.reader(f))
for row in reader:
'''
Do Something
'''
|
class Node():
def __init__(self):
self.next = Node next
self.data = data
x = Node(y,1)
|
import smtplib
#instructions
#gmail account: username=franken.llama.sama@gmail.com; password=DraculasDentalDam
#setup account for smtpserver:
#1) goto https://mail.google.com/mail/u/1/#settings/fwdandpop and enable imtp and pop
#2) if texting, find service provider's sms server (ex. @msg.telus.com)
username="franken... |
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
'''
88. 合并两个有序数组
'''
# 2. 原地排序
k = m + n - 1
while m > 0 and... |
import numpy as np
import h5py
import argparse
import bsplines
description="""\
Artery short-axis in xz-plane with a plaque ball located
at the border and rotating with constant angular velocity.
"""
def create_phantom(args):
xs = np.array(np.random.uniform(size=(args.num_scatterers,), low=args.x_min, hig... |
import torch.nn as nn
import torch.nn.functional as F
class Subnet1Features(nn.Module):
def __init__(self):
super(Subnet1Features, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
self.co... |
import time, random
class Colorize:
_instances_by_owner = {}
@classmethod
def for_owner(cls, owner):
if owner in cls._instances_by_owner:
return cls._instances_by_owner[owner]
# Create new instance
instance = cls(owner)
# Store it so it can be found next time
... |
import keras
import numpy as np
from keras.layers import *
from keras.models import Model, Sequential
from keras import models, layers
from keras.optimizers import SGD, Adam
import tensorflow as tf
class GAN():
def __init__(self, input_dim = 100):
self.input_dim = input_dim
self.optimizer = Adam(lr... |
import numpy as np
import pandas as pd
from scipy.io import loadmat
def load_mat(mat: str, show_debug=False) -> {}:
data = loadmat(mat)
if(show_debug):
print("Mat has " + str(len(data.keys())) + " keys.")
if verify_flat_mat(data):
print("Mat is flat.")
else:
pr... |
# Generated by Django 3.1.4 on 2020-12-31 15:52
from django.db import migrations, models
import django.db.models.deletion
import keyboard.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
('games', '0001_initial'),
]
operations = [
migrations.CreateM... |
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
'''
topological sort approach. build indegree/graph -> build sources -> iterate child of sources
'''
if numCourses <= 0:
return False
#prep inDegree and... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
DATABASE = 'flasktskr.db'
CSRF_ENABLED = True
SECRET_KEY = 'I\x88\xa0.\x01#\xd5+\x12w\xa0\xa8[46.yh\xcfSH\xff4\x1e'
DATABASE_PATH = os.path.join(basedir,DATABASE)
SQLALCHEMY_DATABASE_URI = 'sqlite:///'+ DATABASE_PATH
|
import tensorflow as tf
sess = tf.Session()
x = tf.Variable([1.,2.]) # Variable은 초기화initializer가 꼭 필요
a = tf.constant([3.,3.])
sess.run(x.initializer)
sub = tf.subtract(x,a)
# print(sess.run(sub))
print(sub.eval())
sess.close()
# 오리 타이핑? 덕 타이핑? duck typing |
#Obsolete
from fugazzi.objects import Movie, Show, Description, Links, Season, Episode
def modelToMovie(modelList):
try:
models = modelList #Takes Model
content_type = Movie #Content type
object_list = []
for o in models:
descr = Description(o.title, o.image, o.langua... |
##18Sep13
##복합대입연산자 결과를 간단하게 나오게하기위해
##변수선언부분
Money,c500,c100,c50,c10=0,0,0,0,0
##MainCode Part
Money=int(input("교환할 돈은 얼마?"))
c500=Money//500
Money%=500
c100=Money//100
Money%=100
c50=Money//50
Money%=50
c10=Money//10
Money%=10
##PrintCode
print("\n 오백원짜리==>%d개"%c500)
print("백원짜리==>%d... |
import json
import requests
import time
from bs4 import BeautifulSoup
URL_BASE = 'https://kitnet.jp/laboratories/'
INDEX_URL = 'https://kitnet.jp/laboratories/index.html'
def get_keywords(url):
time.sleep(0.5)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'lxml')
keywords_csv = soup.find('met... |
"""
# TODO:
EASY DISPLAY STUFF
"Back" links from lexicon entries
Permalinks to paragraphs using pilcrow symbol, and give paragraph numbers in the
lexical index instead of source code line numbers. (Or have a setting for this?)
Make section permalinks use the section symbol and appear to the left o... |
from django.db import models
from tinymce import models as tinymce_models
class Category(models.Model):
title = models.CharField(max_length=100)
order = models.IntegerField(blank=True, null=True)
def __unicode__(self):
return self.title
class Link(models.Model):
title = models.CharField(max... |
from numpy import *
senha = input("Senha: ")
t = len(senha)
for i in range(t):
if senha[i] == senha[i].isupper():
print(a) |
'''
Created on 27.06.2014
@author: Matthias Jaenicke
@source: Steering: http://engineeringdotnet.blogspot.de/2010/04/simple-2d-car-physics-in-games.html
@source: Car physics: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html
'''
from OpenGL.GL import *
from pygame.locals imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*_
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("foo")
parser.add_argument("bar")
args = parser.parse_args()
# EOF |
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('dataset.csv', dtype=int, delimiter = '\t')
questions = {
"Q1" : "I would never audition to be on a game show.",
"Q2" : "I am not much of a flirt.",
"Q3" : "I have to psych myself up before I am brave enough to make a phone call.",
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.