text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Contain all consumer errors
"""
__all__ = [
'ConsumerConnectionError',
'AioKafkaConsumerBadParams',
'KafkaConsumerError',
'KafkaConsumerNotStartedError',
'KafkaConsumerAlreadyStartedError',
'ConsumerKafkaTimeoutError',
'... |
from flake8.main import main
# python -m flake8 (with Python >= 2.7)
main()
|
def solution(routes):
# [[-20,-15], [-18,-13], [-14,-5], [-5,-3]]
# routes[i][1] > routes[i+1][0]
routes.sort(key=lambda x: x[1])
answer = 1
check = routes[0][1]
for i in range(1, len(routes)):
if check < routes[i][0]:
print(check, routes[i][0])
answer += 1
... |
from db import db
class PriorityLevel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String, nullable=False)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -------------------- 打开文件 --------------------
print('-' * 20, '打开文件', '-' * 20)
# open(dir, method)
# dir 为文件路径,如果不想打太多\\可以使用raw字符串
# method 打开方式
# r 只读,没有文件则报错
# w 清空文件,再写入
# a 追加模式(从文件尾部开始写入)
# 加 + 读写模式
# 加 b 二进制模式
# python中的文件对象自带迭代器,以行为单位进行迭代,可以使用for line in f... |
#!/usr/bin/python
import argparse
import sys
import os
# Construct the argument parser
ap = argparse.ArgumentParser()
# Add the arguments to the parser
ap.add_argument("-robot", "--robot", required=True, help="name of the robot")
args = vars(ap.parse_args())
robot = args['robot']
base_path = "$HOME/catkin_ws/sr... |
import numpy as np
import xarray as xr
from dataset import Dataset
from config import Config
from utils import load_indexing
from crop import crop_center, crop_2d
from sklearn.metrics import jaccard_similarity_score
def equivalent_potential_temperature(temperature, specific_humidity, pressure):
e = pressure / (62... |
import pandas as pd
import numpy as np
import pyttsx3
import os
import shutil
import time
from datetime import date
from openpyxl import load_workbook
start = time.time()
print()
today = date.today()
folder_exp = f'E:/Total/Station Data/Master Data/export/AFR_{today}'
if os.path.exists(folder_exp)... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# update_rdb.py: update dataseeker rdb files for ccdm, pacd, mups, and elbi #
# ... |
"""
Utility functions for api module
"""
import re
import smtplib
from email.mime.text import MIMEText
from api.constants import MAIL_HOST, MAIL_PORT
def peek(bucket):
"""
Get first element of set without removing
:param bucket: set to peek
"""
elem = None
for elem in bucket:
break
... |
"""
Сложность:
1. Худший случай: O(n^2).
2. Лучший случай: O(n * log n).
3. Средний случай: O(n * log n).
Операция разделения массива на две части относительно опорного элемента занимает
время O(log n). Поскольку все операции разделения, проделываемые на одной глубине
рекурсии, обрабатывают разные части исходного масси... |
from collections import defaultdict
from copy import deepcopy
from functools import wraps
from importlib import import_module
from typing import (
Any,
Callable,
Dict,
Mapping,
Optional,
Sequence,
Type,
get_type_hints,
)
from ._types import FunctionDecorator, ModelType, NamingStrategy, ... |
from _typeshed import Incomplete
def uniform_random_intersection_graph(n, m, p, seed: Incomplete | None = None): ...
def k_random_intersection_graph(n, m, k, seed: Incomplete | None = None): ...
def general_random_intersection_graph(n, m, p, seed: Incomplete | None = None): ...
|
from django.shortcuts import render
import requests
# Create your views here.
def HomeView(request):
return render(request, 'project/home.html', {}) |
import cv2, os
import numpy as np
#切换工作目录
os.chdir(r'D:\application\Coding\Image Processing\CH03\DIP3E_CH03_Original_Images\DIP3E_Original_Images_CH03')
if os.getcwd() == r'D:\application\Coding\Image Processing\CH03\DIP3E_CH03_Original_Images\DIP3E_Original_Images_CH03':
print('Transformation Function:\n1.... |
"""
Minimal setup for listmycmds
"""
DEPENDENCIES = ['argh']
from setuptools import setup, find_packages
setup(name='listmycmds',
version='1.0',
py_modules=['listmycmds_for_setup', 'listmycmds'],
entry_points={'console_scripts': ['listmycmds=listmycmds_for_setup:main']},
install_requires=DEPENDENCIES
... |
from pycoingecko import CoinGeckoAPI
import pandas as pd
pd.set_option('float_format', '{:.5f}'.format)
#---------------------------- API Call
cg = CoinGeckoAPI()
#---------------------------- Get Data
def crypto_data(crypto):
list_crypto = cg.get_coins_list()
df_crypto = pd.DataFram... |
import os
import sys
import re
import random
import math
import matplotlib
import pandas as pd
import numpy as np
import ipaddress as ip
from os.path import split
from urllib.parse import urlparse
import matplotlib.pyplot as plt
import sklearn.ensemble as ek
from sklearn.model_selection import train_test_split
from skl... |
# Reverse Maker
# Done
# By Efrain
while True:
reverse = input("Enter A Word To Be Flipped: ")[::-1]
print(reverse)
|
def login(ac, id, pw): #ac = account
if id in ac:
if pw == ac[id]:
print("%s님이 로그인했습니다."%id)
else:
print("비밀번호가 다릅니다.")
else:
print("등록되지 않은 아이디입니다.")
account = {"pomin615":"0123", "thdehdduf20":"4567"}
uid = input("ID : ")
upw = input("PW : ")
login(... |
st = input()
st = st.replace("apple","NULL")
st = st.replace("peach", "apple")
st = st.replace("NULL", "peach")
print(st) |
from functools import partial
import itertools
import json
import logging
import sys
import warnings
import click
from cligj import (
compact_opt, files_in_arg, indent_opt,
sequence_opt, precision_opt, use_rs_opt)
import fiona
from fiona.transform import transform_geom
from .helpers import obj_gen
from . impo... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#
# (C) 2013 Varun Mittal <varunmittal91@gmail.com>
# JARVIS program is distributed under the terms of the GNU General Public License v3
#
# This file is part of JARVIS.
#
# JARVIS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-06-12 21:15
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('board', '... |
from pathlib import Path
from datasets import load_dataset, Dataset
from datasets.config import HF_DATASETS_CACHE
from . import registration
from ..utils import get_hash
_OOV_DELIMITER = '|'
def get_gold_dataset(challenge_name: str, ignore_verification: bool = False):
d = load_dataset(
str((Path(__file__... |
import cv2
import numpy as np
import argparse
ap=argparse.ArgumentParser()
ap.add_argument('-i','--image',required=True,help='Path to the image')
args=vars(ap.parse_args())
image=cv2.imread(args['image'])
image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image=cv2.GaussianBlur(image,(5,5),0)
cv2.imshow('Blurred... |
import os
import sys
from PyQt4.Qt import *
class AboutView(object):
__layout = None
__leftBox = None
__rightBox = None
def __init__(self, layout):
self.__layout = layout
def initView(self):
self.__initLayouts()
self.__initPixelMap(self.__leftBox, "VU_icon.svg")
... |
import pycurl
from StringIO import StringIO
for line in open('sites.txt').xreadlines():
buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, line.rstrip())
c.setopt(c.WRITEDATA, buffer)
c.perform()
print line + " status code: %s" % c.getinfo(pycurl.HTTP_CODE)
c.close()
# Body is a st... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Proposal.created'
db.add_column(u'landing_proposal', 'cre... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# clean_table.py: clean up op_limits.db table #
# ... |
from event_bot import EventBot |
import time
import shutil
import subprocess
import pytest
from dps.run import _run
from dps.rl.algorithms.a2c import reinforce_config
from dps.train import training_loop, Hook
from dps.env.advanced import translated_mnist
from dps.env.advanced import simple_addition
from dps.config import DEFAULT_CONFIG
from dps.utils... |
# 状态递推
# 矩阵快速幂优化
# 轻轻松松!!!
MOD = 10**9 + 7
class Solution:
def numTilings(self, n: int) -> int:
t1, t2, t3, t4 = 1, 0, 0, 1
for i in range(2, n+1):
h1, h2, h3, h4 = t1, t2, t3, t4
t1 = h4 % MOD
t2 = (h1 + h3) % MOD
t3 = (h1 + h2) % MOD
t4 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import blocks
import boosts
import monsters
import random
import config_level_generator as clg
from config_entity import WIDTH
class LevelGenerator:
def __init__(self, game):
self.game = game
self.locked_coordinates = []
self.ri... |
import numpy as np
gamma = 0.99
positive_reward = 10
negative_reward = -10
for i in range(500):
positive_reward = gamma * positive_reward - 0
for i in range(500):
negative_reward = gamma * negative_reward - 0
print('positive_reward', positive_reward)
print('negative_reward', negative_reward)
print(np.linspa... |
#! /usr/bin/python
"""A simple reverse backdoor script.
Uses Python 2.7.16"""
import subprocess
import optparse
import shutil
import base64
import socket
import json
import sys
import os
def get_arguments():
"""Get user supplied arguments from terminal."""
parser = optparse.OptionParser()
# arguments
... |
#문제 설명
#새로 생긴 놀이기구는 인기가 매우 많아 줄이 끊이질 않습니다. 이 놀이기구의 원래 이용료는 price원 인데, 놀이기구를 N 번 째 이용한다면 원래 이용료의 N배를 받기로 하였습니다. 즉, 처음 이용료가 100이었다면 2번째에는 200, 3번째에는 300으로 요금이 인상됩니다.
#놀이기구를 count번 타게 되면 현재 자신이 가지고 있는 금액에서 얼마가 모자라는지를 return 하도록 solution 함수를 완성하세요.
#단, 금액이 부족하지 않으면 0을 return 하세요.
# 제한사항
# 놀이기구의 이용료 price : 1 ≤ price ≤ 2,5... |
import numpy as np
import matplotlib.pyplot as plt
import os
import utils
# Import MNIST data
PLOT_DIR = './out/plots'
def plot_conv_weights(weights, name, channels_all=True):
"""
Plots convolutional filters
:param weights: numpy array of rank 4
:param name: string, name of convolutional layer
:... |
from tools.primes import factors_of
import numpy as np
def is_abundant(n):
sumn = sum(factors_of(n)[:-1])
return sumn > n
'''
plan of attack:
gen all abundant numbers till 28K
then do for all i,j in the abundant numbers, store the sums of those
then filter a range till 28k with those sums, and then sum out the... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math as m
#==1.ukol===============================================================================================================
def custom_grayscale(image):
for i in range(1,len(image)):
for j in range(1,len(image[1])):
... |
from django.conf.urls import include, url
from api import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^server/(?P<action>\w+)/$', csrf_exempt(views.Server.as_view())),
url(r'^account/(?P<action>\w+)/$', csrf_exempt(views.Account.as_view())),
url(r'^upload/(?P<action>\w+... |
# -*- coding: utf-8 -*-
# lib_excel.py written by Duncan Murray 11/2/2014
import csv
import os
import sys
from collections import namedtuple
import glob
from random import randint
import collections
import xlrd
fldr = os.getcwd() + '//..//aspytk'
print('startup folder = ' + fldr)
sys.path.append(fldr)
import li... |
from django.conf.urls import url
from points import apis
urlpatterns = [
url(r'^$', apis.PointsTableApi.as_view(), name="api_points_table")
]
|
from django.db import models
class Student(models.Model):
name = models.CharField(name='nome', max_length=255, db_index=True)
birthday = models.DateField(name='nascimento')
age = models.IntegerField(name='idade')
cpf = models.CharField(name='cpf', max_length=14, db_index=True)
street = models.Cha... |
from PIL import Image, ImageDraw, ImageFont
def addNum(filePath):
img = Image.open(filePath)
size = img.size
fontSize = size[1] / 4
draw = ImageDraw.Draw(img)
ttFont = ImageFont.truetype(r"C:\Windows\Fonts\Arial.ttf", fontSize)
draw.text((size[0]-fontSize, 0), "6", (255, 0, 0), font =... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
import platform
import shutil
from dataclasses import dataclass
from textwrap import dedent
from typing import Mapping, MutableMapping
import... |
#!/bin/python3
import os
import sys
#
# Complete the roadsInHackerland function below.
#
def roadsInHackerland(n, roads):
edges = [[-1 for _ in range(n + 1)] for _ in range(n + 1)]
for road in roads:
v1, v2, cost = road
edges[v1][v2] = 2 ** cost
edges[v2][v1] = 2 ** cost
result = ... |
myfamily = {
"child1": {
"name": "Tobias",
"year": 2009
},
"child2": {
"name": "Emili",
"year": 2010
},
"child3": {
"name": "Linux",
"year": 2015
}
}
print(myfamily) |
import numpy as np
from collections import defaultdict
class Agent:
def __init__(self, nA=6):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(lambda: np.zeros(self.nA))
self.a... |
from CompteSimple import CompteSimple
from Transaction import Transaction
class CompteCourant(CompteSimple):
_historique = []
def __init__(this, initMnt = 0):
CompteSimple.__init__(this, initMnt)
def afficherHistorique(this):
for transaction in this._historique:
message = ... |
__all__ = ['dynamodb']
|
# -*- coding: utf-8 -*-
# Personal Assistant Reliable Intelligent System
# By Tanguy De Bels
from Senses.mouth import speak
from Utilities.tools import *
import net
import os
from time import localtime, strftime
from datetime import date
def h(msg):
time = strftime("%X", localtime()).split(":")
... |
from os import path
import os
import socket
import atexit
import pickle
import select
class _UDS(object):
SOCK_FILE = path.join(path.dirname(__file__), 'pikaball.socket')
BUFF_SIZE = 256
def __init__(self, server):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
def rm(f):
... |
def divident(data,start,length,wordList ,res):
#length = len(data)
print("length is ", length)
if length == 0:
res.append(wordList)
return
for i in range(start+1,start+length):
temp = data[start:i]
wordList = wordList+ temp
data_temp = data[i:]
pr... |
from django.shortcuts import render
from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from playlist.models.Radio import Radio
from playlist.forms import RadioForm
def add_radio(request):
... |
import tornado.ioloop
import tornado.httpserver
import tornado.web
import tornado.websocket
import tornado.gen
from tornado import httpclient
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
(r"/now", BitNowHandler),
]
... |
import demjson
import json
# str = """
# {
# id: 225,
# is_in_serving: true,
# description: "有菜有肉,营养均衡",
# title: "简餐",
# link: "eleme://restaurants?filter_key=%7B%22activity_types%22%3A%5B3%5D%2C%22category_schema%22%3A%7B%22category_name%22%3A%22%5Cu7b80%5Cu9910%22%2C%22complex_category_ids%22%3A%5B209%2C212%2C215%2... |
# -*- coding: utf-8 -*-
import glob, os
import sys
import shutil
# 引数1からフォルダ名取得
args = sys.argv
if (len(args) != 3):
print("Usage: $ python" + args[0] + " <image folder> <ratio of test(%)>")
quit()
path_data = args[1]
percentage_test = int(args[2])
print("Folder name is '%s'. ratio of test is %d%%." % (path_d... |
from secureFlaskApp import app as application
import sys
import azure.functions as func
import os
import pathlib
root_function_dir = pathlib.Path(__file__).parent.parent
secureFlaskApp_path = os.path.join(root_function_dir, "secureFlaskApp")
sys.path.insert(0, secureFlaskApp_path)
def main(req: func.Htt... |
import pandas as pd
import numpy as np
from PIL import Image
import skimage
import imageio
import os
import glob
import warnings
import natsort
warnings.filterwarnings('ignore')
def findFiles(path):
return natsort.natsorted(glob.glob(path))
testlist = findFiles('three splits/split1/*.txt')
trainsamp... |
import requests
import uuid
from bs4 import BeautifulSoup
from config import YANDEX_TRANS_KEY
def update2text(update, locale): # locale="ru-RU" or "en-US"
message = update.message
text = ""
if message.text:
text = message.text # если в сообщении есть текст, то берём его для начала
if mess... |
import logging
from typing import Sequence
logger = logging.getLogger(__name__)
def gather_exception_subclasses(module, parent_classes: Sequence):
"""
Browse the module's variables, and return all found exception classes
which are subclasses of `parent_classes` (including these, if found in module).
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import functools
import os
from contextlib import contextmanager
from dataclasses import dataclass
from threading import Thread
from typing import Any, ... |
import os
import re
import sys
nginxConfPath = sys.argv[1]
confPathList_file = sys.argv[2]
nginxfile = nginxConfPath
file_tmp = confPathList_file + 'confPathList.txt'
def getConfPath(confFile,confFile_tmp):
if os.path.isfile(confFile):
fo = open(confFile)
readlines = fo.readlines()
for str... |
# Generated by Django 2.1.2 on 2019-02-15 16:44
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0040_auto_20190215_1449'),
]
operations = [
migrations.AddField(
model_name='type',
... |
import time
import string
import random
# import math
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# defines the number of times each algorithm will be processed to obtain the
# average time
num_rounds = 20
SEQUENCE_LENGTH = 0.1
DR = dict()
def Naive(T, S):
i, j = 0, 0
while i <... |
import json
import os
import re
import smtplib
import sys
from email.mime.text import MIMEText
import backoff
import requests
# get variables from environment
CHECK_JENKINS_UPDATES_SOURCE = os.getenv(
'CHECK_JENKINS_UPDATES_SOURCE',
'http://updates.jenkins-ci.org/stable/update-center.json')
CHECK_JENKINS_UPDA... |
import heapq
# def __init__(self):
# self.cost = 0
def connectRopes(ropes):
minH = []
for value in ropes:
heapq.heappush(minH, value)
cost = 0
while len(minH) >= 2:
first = heapq.heappop(minH)
second = heapq.heappop(minH)
cost = cost + first + second
heapq.hea... |
# coding: utf-8
# In[1]:
import numpy as np
import cv2
import imutils
# In[2]:
img = cv2.imread('./datasets/flower1.jpg')
cv2.imshow("Original_Image", img)
cv2.waitKey(0)
# In[3]:
#Flipping Horizontally
flip_horizontal = cv2.flip(img, 1)
cv2.imshow("Image_Flipped_Horizontal", flip_horizontal)
cv2.waitKey(0)
... |
import sys
import os
from ete3 import Tree
def str_2(ll):
return "{0:.2f}".format(ll)
def str_4(ll):
return "{0:.4f}".format(ll)
def print_likelihood_sums(treerecs_file):
ale_ll = 0.0
pll_ll = 0.0
for line in open(treerecs_file).readlines():
split = line.split(" ")
for index, val in enumerate(spli... |
# 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 agreed to in writing, software
# d... |
import re
import csv
import datetime
import dateutil
from dateutil.parser import parse
# xml input: change this path as needed based on where you're keeping the discogs xml dump
inputFile = './discogs_20161001_releases.xml'
# csv output: change this path based on where you want to write the csv
outputFile = open('./o... |
from moduleassign import modules as m
# from mod import *
print(dir(m))
#~ r = m.rangegenerator()
#~ print(r)
#~ reversedVals = m.reverser(r)
#~ print(reversedVals)
#~ evens = m.evener(r)
#~ print(evens)
#~ odds = m.odder(r)
#~ print(odds)
|
from django.contrib import admin
from .models import CustomUser as User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ("username", "email", "plan", "is_staff", "is_active")
|
# Write a script called "stats.py" that prints the
# mean, median, mode, range, variance, and standard deviation
# for the Alcohol and Tobacco dataset with full text
# (ex. "The range for the Alcohol and Tobacco dataset is ...").
# Push the code to Github and enter the link below.
import pandas as pd
import pdb
d... |
from flask import Flask, session, app, render_template, request, Markup
import sys, io, re
import os, base64
from io import StringIO
from datetime import datetime
import time
app = Flask(__name__)
# get root path for account in cloud
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# survey page
@app.route("/",... |
# -*- coding: utf-8 -*-
import os, sys, re, codecs, binascii, cgi, cgitb, datetime, pickle
from msg import *
import json
cgitb.enable()
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
def main():
q = cgi.FieldStorage()
print("Content-type: application-json; charset=utf-8\n\n")
r = {'ids': [["one" , ... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given an unsorted array of integers, find the length of longest increasing subsequence.
# For example,
# Given [10, 9, 2, 5, 3, 7, 101, 18],
# The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4.
# Note that there may be more than one LIS combi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
import os
import unittest
from scipy import linalg
from .. import auxfn_vers2 as auxfn
from ..model.io_triangle import IOTriangle as green
from . import test_tools
currentdir = os.path.join(os.getcwd(), "mea/tests")
@unittest.skip("This class... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#############################################################################################
# #
# update_dea_rdb.py: update DS deahk realated rd... |
"""
response schema
"""
import json
import typing
import jinja2
try:
from aiofile import AIOFile
except ImportError:
AIOFile = None
from kumquat._types import Scope, Receive, Send
from kumquat.context import env_var
try:
import ujson
except ImportError:
ujson = None
JSON = json if ujson is None els... |
# !/bin/python3
import json
import sys
import re
harvester_key = ""
harvester_vrf = ""
node_name = ""
with open('./config.json', 'r') as f:
data = json.load(f)
harvester_key = data["harvesterKey"]
harvester_vrf = data["harvesterVrfKey"]
node_name = data["nodeName"]
params_to_replace = [
{"name"... |
import torch
import pandas as pd
import numpy as np
import os
from pathlib import Path
import numpy as np
import os
np.random.seed(123)
os.environ["PYTHONHASHSEED"] = str(123)
torch.manual_seed(123)
VAL = 100
def get_sum_with_max_contribution_per_value(tensor: torch.Tensor):
values = tensor.tolist()
target_v... |
import numpy as np
import hpgeom as hpg
from .healSparseMap import HealSparseMap
from .utils import is_integer_value
import numbers
def realize_geom(geom, smap, type='or'):
"""
Realize geometry objects in a map.
Parameters
----------
geom : Geometric primitive or list thereof
List of Geom... |
# Copyright 2021 DAI Foundation
#
# 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 agreed to in writing,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-08 15:34
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("elections", "0052_auto_20181005_1645")]
operations = [
... |
'''
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example 1:
Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
In... |
import window.player
import svecova.player
#import svecova.player03
import sebastian.player
import martins.player
import lionel.player
import janmrzilek.player
import benda.player
import vrba.player
from gomoku_tournament import GomokuTournament
playerX = svecova.player.Player(1)
playerO = benda.player.Player(-1)
tou... |
import serial
ser = serial.Serial('COM1', baudrate=9600, bytesize=8, parity='N', stopbits=1)
ser.write(b'G1 X5 Y50 \r\n')
resp = serial.readline() |
items = ('st','BD','BTL','CG','DD','HBT')
a = ('thứ tự các quận trong thành phố:')
print(a,*items,sep=',')
number = ('150,300','247,100','333,300','266,800','420,900','318,000')
b = ('số dân theo thứ tự các quận:')
print(b,*number,sep=';')
smallest = ('st')
c = ('quận có số dân ít nhất:')
print(*c,*smallest,sep... |
def myGenFunc():
v = 2
yield v
v = 3
yield v
v = 4
yield v
gen_obj= myGenFunc()
print(next(gen_obj))
print(next(gen_obj))
print(next(gen_obj))
|
#! usr/bin/env python
# -*-coding:utf-8-*-
# author:yanwenming
# date:2020-06-30
import unittest
from page.init import *
import requests
import time as t
import os
import sys
from bs4 import BeautifulSoup
from lxml import etree
curPath = os.path.abspath ( os.path.dirname ( __file__ ) )
rootPath = os.path.split( cur... |
import sys,os
from socket import *
if(len(sys.argv)>2):
host=sys.argv[1]
port=int(sys.argv[2])
else:
print("Required Parameters not found. You should provide host and port to create socket connection")
sys.exit(1)
server_address=gethostbyname(host)
connection_socket=socket(AF_INET,SOCK_STREAM)
connection_socket.c... |
#!/usr/bin/env python
# coding: utf-8
# # Assignment 3
# In[ ]:
# 1. Why are functions advantageous to have in your programs?
# solu:
# The major advantage of functions is repeatability of them we can reuse them any number of times in the program which ultimately helps in avoiding the writing of code to perform ... |
from turtle import *
screen = Screen()
screen.bgcolor("green")
bob = Turtle()
bob.color("yellow")
bob.pensize(2)
bob.speed(0)
bob.shape("turtle")
for x in range(10):
bob.forward(15)
bob.left(10)
bob.backward(15)
bob.left(10)
mainloop() |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from app.models import City, Location, State
from app.serializers import CitySerializer, LocationSerializer, StateSerializer
class CityApiTestCase(APITestCase):
@classmethod
def setUpTestData(cls):
... |
from django.conf import settings
from django.contrib.auth.models import User
from todo.models import List
STAFF_ONLY = getattr(settings, 'TODO_STAFF_ONLY', False)
first_superuser = User.objects.filter(is_superuser=True)[0]
DEFAULT_ASSIGNEE = getattr(settings, 'TODO_DEFAULT_ASSIGNEE', first_superuser.username)
first_... |
import json
import urllib.parse
import urllib.request
import socket
MAPQUEST_API_KEY = 'n1VVYuFNFcNEGPdRBheFtlUjEPLiQmsn'
BASE_URL = 'http://open.mapquestapi.com/directions/v2/'
BASE_URL2 = 'http://open.mapquestapi.com/elevation/v1/'
def build_search_url(src: str, dest: [str]) -> str:
query_parameters... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 18:53:12 2018
@author: Consiousflow
"""
import numpy as np
import os
import math
from sklearn import mixture
import matplotlib.pyplot as plt
from pylab import *
from scipy import stats
path_av = "D:/Downloads/Cache/Desktop/Temp/embedding/AV/"
path_bv = "D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.