content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
"""
[6,2,4]
l
r
k
[12,24] [24, 8]
[36] [32]
[6,2,4,1]
l r
k
[12,24, 6] [8]
... | python |
screen = None
window = None
class Game():
scene = 'title'
state = ''
interaction = -1
interaction_level = -1
class Cursor():
menu = 0
class Camera():
position = [-6, -40]
class Field():
location = 'home'
player_position = [1, 1]
player_face = 'D'
class Player():
inventory =... | python |
# Electrum - Lightweight Bitcoin Client
# Copyright (c) 2012 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights t... | python |
from datalabframework import params, project
import os
from textwrap import dedent
import pytest
from testfixtures import TempDirectory
@pytest.fixture()
def dir():
with TempDirectory() as dir:
original_dir = os.getcwd()
os.chdir(dir.path)
p = project.Config()
p.__class__._insta... | python |
import os,time,requests,re
from time import sleep
id=[]
def search(url):
global id
sleep(2)
req=requests.get(url).text
usr=re.findall(r'<td class="bz ca"><a href="(.*?)"><div class="cb"><div class="cc">(.*?)</div></div>',req)
for user in usr:
username=user[0].replace("/","")
if 'prof... | python |
import logging
import json
class Logger:
def __init__(self):
pass
@staticmethod
def log(info_type, message):
try:
uid = json.loads(str(message[0]))['result']
if len(uid) == 16:
uid_file = open('./chaostoolbox/data/log/uid.log','a')
ui... | python |
import os
import glob
import re
path = '\Documents\python\C++Examples'
gramHash = {}
for filename in glob.glob('*.cpp'):
outFile = open('KnownCPP.txt', 'a')
fileOpen = open(filename, 'r', encoding='utf8', errors='ignore')
fileString = ""
for line in fileOpen:
# Removes non ASCII characters
lin... | python |
import torch
from ncc.modules.decoders.ncc_incremental_decoder import NccIncrementalDecoder
class SequenceCompletor(object):
def __init__(
self,
retain_dropout=False,
):
"""Generates translations of a given source sentence.
Args:
retain_dropout (bool, optional): u... | python |
from django.forms import ModelForm
from django.test import TestCase
from .models import JSONNotRequiredModel
class JSONModelFormTest(TestCase):
def setUp(self):
class JSONNotRequiredForm(ModelForm):
class Meta:
model = JSONNotRequiredModel
fields = '__all__'
... | python |
import collections
class Equalizer:
def __init__(self, levels: list):
_dict = collections.defaultdict(int)
_dict.update(levels)
_dict = [{"band": i, "gain": _dict[i]} for i in range(15)]
self.eq = _dict
self.raw = levels
@classmethod
def build(cls, *, levels: li... | python |
# Copyright 2019-2020 SURF.
# 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, soft... | python |
import sys,os
import traceback
import time
import shutil
import json
import requests
from selenium import webdriver
from PIL import Image
class ScriptError (Exception):
pass
def iw (webhook:str, message:str):
"""
post message to slack channel
"""
data = json.dumps({
'text' : message
})
... | python |
import json
from time import sleep
try:
from typing import Optional, Tuple
except ImportError:
pass
from google_play_scraper import Sort
from google_play_scraper.constants.element import ElementSpecs
from google_play_scraper.constants.regex import Regex
from google_play_scraper.constants.request import Format... | python |
from ..sql_helper import SQLHelper
from shapely import wkb
from shapely.geometry import Polygon
from .filtering import filtering_objects
def generate_rectangle_information(form):
"""
Функция для генерации информации по области
:param form: форма из POST запроса с координатами области (прямоугольника) и 6 ... | python |
from enum import Enum, unique
@unique
class MeboCommands(Enum):
READERS = "READERS"
FACTORY = "FACTORY"
BAT = "BAT"
WHEEL_LEFT_FORWARD = "WHEEL_LEFT_FORWARD"
WHEEL_LEFT_BACKWARD = "WHEEL_LEFT_BACKWARD"
WHEEL_RIGHT_FORWARD = "WHEEL_RIGHT_FORWARD"
WHEEL_RIGHT_BACKWARD = "WHEEL_RIGHT_BACKWAR... | python |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Final, Dict, Optional, final, List, Any
from ftplib import FTP_TLS
from functools import cached_property
import ssl
import os
class FTPClient(ABC):
HOSTS: Final[Dict[str, Optional[str]]] = {
'main': 'ree... | python |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
name = 'toyui'
namespace = 'toy'
export = 'TOY_UI_EXPORT'
subdir = 'toyui'
dependencies = ['toyobj']
rootdir = dir_path
basetypes = [] | python |
# This is a script that calculates WER of different decades in vks_kotus_sample.json.
# There are currently some decades not analysed, as we got sufficient picture when
# we just ensured that there are no excessive gaps of several decades.
# Also the current corpus is temporally relatively limited, so this is a minor ... | python |
# ---------------------------------------------------------------------
# Vendor: Zyxel
# OS: ZyNOS_EE
# ---------------------------------------------------------------------
# Copyright (C) 2007-2011 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : qichun tang
# @Date : 2020-12-15
# @Contact : qichun.tang@bupt.edu.cn
import hashlib
from copy import deepcopy
from typing import Union, Dict, Any
import numpy as np
from ConfigSpace import Configuration
from scipy.sparse import issparse
def get_hash_o... | python |
import unittest
from etl import sources
from unittest.mock import patch, MagicMock
class TestODKSource(unittest.TestCase):
def test_fix_odk_sunmission(self):
""" Testing fix odk submission"""
data = {
"@a": "a",
"b": "b",
"orx:meta": "should_not_be_there"
... | python |
"""Tests for driver.py"""
import pytest
import pandas as pd
from pandas.testing import assert_frame_equal
from timeflux.core.io import Port
def test_nexus():
assert True
| python |
# -*- coding: utf-8 -*-
from .file_read_backwards import FileReadBackwards # noqa: F401
__author__ = """Robin Robin"""
__email__ = 'robin81@gmail.com'
__version__ = '1.1.2'
__github__ = 'https://github.com/robin81/file_read_backwards'
| python |
import numpy as np
class Stats(list):
def __init__(self,list):
self.list = list
self.length = len(list)
self.mean = sum(list)/self.length
#If list is even
if self.length % 2 == 0:
self.medianEven = median(list)
else:
self.medianOdd = median(l... | python |
expected_output = {
'vll': {
'MY-QINQ-VLL-LOCAL': {
'vll_id': 4,
'ifl_id': '4096',
'state': 'UP',
'endpoint': {
1: {
'type': 'tagged',
'outer_vlan_id': 100,
'inner_vlan_id': 45,
'interface': 'ethernet2/1',
'cos': '--'
},
... | python |
""" Given an array A of strings made only from lowercase letters, return a list
of all characters that show up in all strings within the list (including
duplicates). For example, if a character occurs 3 times in all strings but
not 4 times, you need to include that character three times in the final
answe... | python |
#! /usr/bin/env python3
from sys import argv
errno = {
'0': 'Success',
'1': 'TooBig',
'2': 'Acces',
'3': 'Addrinuse',
'4': 'Addrnotavail',
'5': 'Afnosupport',
'6': 'Again',
'7': 'Already',
'8': 'Badf',
'9': 'Badmsg',
'10': 'Busy',
'11': 'Canceled',
'12': 'Child',
... | python |
"""
Read graphs in GML format.
"GML, the G>raph Modelling Language, is our proposal for a portable
file format for graphs. GML's key features are portability, simple
syntax, extensibility and flexibility. A GML file consists of a
hierarchical key-value lists. Graphs can be annotated with arbitrary
data structures. The... | python |
# py2.7 and py3 compatibility imports
from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'shadowsocks/config', views.ConfigViewSet)
router.re... | python |
'''
Working with files in Python
'''
# reading and writing files
path_to_file = '00 - Very Basics/text_files/'
file_name1 = input('What is the file name you want to write to? ')
try:
file1 = open('{}/{}.txt'.format(path_to_file, file_name1), 'w')
file1.write('''
You don't know how to be a man
I open ... | python |
from django.contrib.auth import get_user_model
from django.db import models, transaction
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from libs.models import BaseModel
User = get_user_model()
class State(BaseModel):
name = models.CharField(verbose_name=_('name'), max... | python |
from .contract import Contract # noqa
from .template import Template, TemplateError # noqa
from .asyncio.contract import AsyncContract # noqa
from .asyncio.template import AsyncTemplate # noqa
__all__ = (
"Contract",
"Template",
"TemplateError",
"AsyncContract",
"AsyncTemplate"
)
__version__... | python |
# Generated by Django 2.2.9 on 2020-02-12 10:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('events', '0075_change_place_srid'),
]
operations = [
migrations.AlterField(
model_name='image',... | python |
import memcache
import simplejson
class SimplejsonWrapper(object):
def __init__(self, file, protocol=None):
self.file = file
def dump(self, value)
simplejson.dump(value, self.file)
def load(self):
return simplejson.load(self.file)
cache = memcache.Client(['127.0.0.1:11211'], ... | python |
from pwn import *
context.binary = elf = ELF("shellcoded")
r = remote("challenge.ctf.games", 32175)
# shellcode from pwn library
shellcode = list(asm(shellcraft.sh()))
# manually find shellcode online
#shellcode = list(b'\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb... | python |
from kNUI.main import run
| python |
token = "your new token here" | python |
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.core.validators import MinLengthValidator
from django.db.models import Q
from django.contrib.auth.models import User
from social_django.views import complete
from a... | python |
import unittest
from mock import patch, MagicMock
from rawes.elastic import Elastic
from requests.models import Response
from rawes.http_connection import HttpConnection
class TestConnectionPooling(unittest.TestCase):
"""Connection pooling was added on top of Rawes, it wasn't designed from
the beggingin. We ... | python |
import os.path
__all__ = [
"__name__", "__summary__", "__url__", "__version__",
"__author__", "__email__", "__license__"
]
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
except NameError:
base_dir = None
__title__ = "makebib"
__summary__ = "A simple script to generate a local bib file... | python |
import json
import os
import sys
import logging
import traceback
import re
import boto3
import time
# helper functions
from queue_wrapper import *
from message_wrapper import *
# packages for listing to ebay
from ebaysdk.trading import Connection
# packages for the item info formatter
from bs4 import BeautifulSoup
fr... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 26 15:47:35 2019
@author: Dominic
"""
import numpy as np
def generate_points_on_hypercube(nsamples,origin,poffs,p=None,uvecs=None):
if uvecs is None:
epsilon = []
bounds = []
for i in range(len(origin)):
... | python |
from bot import merger_bot
WEBHOOK_HOST = merger_bot.webhook_host
WEBHOOK_PORT = merger_bot.webhook_port
WEBHOOK_SSL_CERT = './SSL/webhook_cert.pem' # Путь к сертификату
WEBHOOK_SSL_PRIV = './SSL/webhook_pkey.pem' # Путь к приватному ключу
WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT)
WEBHOOK_U... | python |
from mnist import MNIST
import sklearn.metrics as metrics
import numpy as np
NUM_CLASSES = 10
def load_dataset():
mndata = MNIST('./data/')
X_train, labels_train = map(np.array, mndata.load_training())
X_test, labels_test = map(np.array, mndata.load_testing())
X_train = X_train/255.0
X_test = X_te... | python |
import djclick as click
from core.utils import get_approximate_date
def gather_event_date_from_prompt():
date = None
while date is None:
date_str = click.prompt(
click.style(
"What is the date of the event? (Format: DD/MM/YYYY or MM/YYYY)",
bold=True, fg='y... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from quixote.errors import TraversalError
from vilya.views.util import jsonize, http_method
from vilya.models.linecomment import PullLineComment
from vilya.models.project import CodeDoubanProject
from vilya.libs.template import st
_q_exports = []
class... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from std_msgs.msg import Float32, UInt8
from sensor_msgs.msg import Image, CompressedImage
import enum
import time
import rospy
from cv_bridge import CvBridge
class ControlNode:
def __init__(self):
self.traffic_mission_start = False
self.parking_missio... | python |
# -*- coding: utf-8 -*-
from qiniu import config
from qiniu.utils import urlsafe_base64_encode, entry
from qiniu import http
class BucketManager(object):
"""空间管理类
主要涉及了空间资源管理及批量操作接口的实现,具体的接口规格可以参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/
Attributes:
auth: 账号管理密钥对,Auth对象
"""... | python |
import numpy as np
import pickle
from time import sleep
import cloudpickle
from redis import StrictRedis
from ...sampler import Sampler
from .cmd import (SSA, N_EVAL, N_ACC, N_REQ, ALL_ACCEPTED,
N_WORKER, QUEUE, MSG, START,
SLEEP_TIME, BATCH_SIZE)
from .redis_logging import logger
... | python |
# -*- coding: utf-8 -*-
import falcon.asgi
import log
from app.api.common import base
from app.api.v1.auth import login
from app.api.v1.member import member
from app.api.v1.menu import menu
from app.api.v1.statistics import image
from app.api.v1.twitter import tweet
from app.api.v1.user import users
from app.database... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import ParameterConstraintProvider_pb2 as ParameterConstraintProvider__pb2
class ParameterConstraintsProviderStub(object):
"""Feature: Parameter Constraint Provider
Allows a server to apply constraints on specific command p... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def tobacco(path):
"""Households Tobacco Budget Share
a cross-section ... | python |
from .wheel import Wheel
from .tree import SyncTree
| python |
from .exceptions import ApigeeError | python |
"""Const for Velbus."""
DOMAIN = "velbus"
CONF_MEMO_TEXT = "memo_text"
SERVICE_SET_MEMO_TEXT = "set_memo_text"
| python |
# -*- coding: utf-8 -*-
from typing import List, NoReturn, Optional
from .signal import Signal
from .light import Light
from .tv import TV
class Appliance:
def __str__(self):
return f"{self.__class__.__name__}: {self.nickname}"
def __init__(self, data: dict) -> NoReturn:
self._set_member(d... | python |
"""
COCO provides a simple way to use the coco data set thru a standardized interface. Implementing this
module can reduce complexity in the code for gathering and preparing "Coco data set" data. Besides that does the module
provide a standardized and simple interface which could be used with any data set containing... | python |
import os
all = [i[:-3] for i in os.listdir(os.path.dirname(__file__)) if i.endswith(".py") and not i.startswith(".")]
| python |
import sys
from datetime import datetime
from datapipe.configuracoes import Configuracoes
from datapipe.converters.tabela_hadoop import TabelaHadoop
from datapipe.datasources.db2 import Db2
from datapipe.utils.constantes import YAML_CONTINUA_ERRO
from datapipe.utils.log import Log, Niveis
class TabelaControleExcept... | python |
import inspect
from enum import Enum
from typing import Callable, cast, TypeVar
from .._internal.default_container import get_default_container
from ..core import DependencyContainer
from ..providers import IndirectProvider
T = TypeVar('T', bound=type)
def implements(interface: type,
*,
... | python |
# Exercícios Numpy-32
# *******************
import numpy as np
print(np.sqrt(16))
print(np.emath.sqrt(-16))#números complexos | python |
# SPDX-License-Identifier: Apache-2.0
"""
Python Package for controlling Tesla API.
For more details about this api, please refer to the documentation at
https://github.com/zabuldon/teslajsonpy
"""
import time
from typing import Text
from teslajsonpy.vehicle import VehicleDevice
class Climate(VehicleDevice):
"... | python |
# -*- coding: utf-8 -*-
class NoiseUtils:
def __init__(self, imageLen,imageWid):
self.imageLen=imageLen
self.imageWid=imageWid
self.gradientNumber = 256
self.grid = [[]]
self.gradients = []
self.permutations = []
self.img = {}
self.__generateGrad... | python |
VERSION = '0.1.7'
| python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from io import StringIO
from dktemplate.parse import nest
from dktemplate.tokenize import tokenize
class Render(object):
def __init__(self, content):
self.content = content
self.out = StringIO()
self.curlevel = 0
def value(... | python |
def findDuplicate(string):
list =[]
for i in string:
if i not in list and string.count(i) > 1:
list.append(i)
return list
n=input('Enter String : ')
print('Duplicate characters :',findDuplicate(n))
| python |
# Copyright 2020 Tyler Calder
import collections
import contextlib
import io
import unittest.mock
import os
import subprocess
import sys
import pytest
from pytest_mock import mocker
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import _realreq.realreq as realreq
CONTENT = """
i... | python |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
@Description: 工具
@Author: Zpp
@Date: 2019-10-28 11:28:09
LastEditors: Zpp
LastEditTime: 2020-11-24 16:27:50
'''
import platform
def IsWindows():
return True if platform.system() == 'Windows' else False
def ReadFile(path, type='r'):
try:
f = open(path,... | python |
# -*- coding: utf-8 -*-
import pytest
import time
import zwutils.dlso as dlso
# pylint: disable=no-member
def test_dict2obj():
r = dlso.dict2obj({
'ks': 'v1',
'kn': 2,
'ka': [1, '2'],
'kd': {'1':1, '2':2},
'knone': None
})
r2 = dlso.dict2obj(None)
assert r.ks ==... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import environment.grpc.jobshop_pb2 as jobshop__pb2
class EnvironmentStub(object):
"""Missing associated documentation comment in .proto file"""
def __init__(self, channel):
"""Constructor.
Args:
c... | python |
import os
class Config:
"""
Parent configuration class.
"""
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET')
TITLE = "Test API"
VERSION = "1.0"
DESCRIPTION = "Demo API."
| python |
# coding=utf-8
from app.api.base.base_router import BaseRouter
from app.config.config import HEADER
from app.api.src.geo.provider import Provider
class GeoTypesRoute(BaseRouter):
def __init__(self):
super().__init__()
def get(self):
answer = Provider().get_types()
return answer, HEADE... | python |
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from .forms i... | python |
nome = str(input("Qual é seu nome")).lower().strip()
if nome == "gustavo":
print("Que nome bonito")
elif nome == "pedro" or nome == "maria" or nome == "joão":
print ("O seu nome é bem popular")
elif nome == "ana katarina":
print ("que nome feio")
else:
print("Seu nome é bem chato")
| python |
from .jsonexporter import JSONExporter
from .ymlexporter import YMLExporter | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import math
import random
import time
from echomesh.sound import Level
from echomesh.util.registry.Registry import Registry
class _SystemFunction(object):
def __init__(self, function, is_constant):
self.function = function
s... | python |
print('=====QUANTO DE TINTA?=====')
alt = float(input('Qual a altura da parede?'))
lar = float(input('Qual a largura da parede?'))
area = alt*lar
print('A área da parede é de {:.2f}m²!'.format(area))
print('Serão necessários {} litros de tinta para pintar a parede'.format(area/2)) | python |
#########################################################################
# #
# C R A N F I E L D U N I V E R S I T Y #
# 2 0 1 9 / 2 0 2 0 #
# ... | python |
# https://leetcode.com/problems/pascals-triangle/
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
if numRows == 1:
return [[1]]
if numRows == 2:
... | python |
from .c2_server import C2Server
from .malware import Malware
from .actor import Actor
from .family import Family
| python |
import numpy as np
from IPython.display import clear_output
import itertools as it
import pylabnet.hardware.spectrum_analyzer.agilent_e4405B as sa_hardware
import time
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import clear_output, display
class O... | python |
import unittest
from runner.robot.zipper import zip_robot
class RobotChanges(unittest.TestCase):
def test_set_new_robot_position(self):
robot1 = {
'part': {
'connects_to': [
{
'part': {
}
... | python |
items = [
("Mosh", 100),
("Brad", 90),
("Ahmed", 10),
]
ratings = [items[1] for items in items] # Map Alternative
ratings = [items[1] for items in items if items[1] >= 20] # Filter Alternative
print(ratings)
| python |
import sys
import chessai
def main():
# parse script args
startup_config = sys.argv[1] if len(sys.argv) >= 2 else 'all'
# launch the training according to the specified startup config
if startup_config == 'pretrain_fx': launch_pretrain_fx()
if startup_config == 'pretrain_ratings': launch_pretra... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 20:48:30 2016
Convert Instagram handles to numeric IDs, which are needed as inputs
for API queries.
Sample output
ERROR: "not-a-handle" is not available
IG user data
------------
Platform: Instagram
Followers: 394
Ha... | python |
# Generated by Django 2.2.1 on 2020-09-20 01:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('chapters', '0013_auto_20200920_0042'),
]
operations = [
migrations.RemoveField(
model_name='orderablecontent',
name='content... | python |
#
# (C) Copyright 2011 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful... | python |
# encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:
@software: PyCharm
@time: 2019/11/30 20:03
""" | python |
from __future__ import unicode_literals
import os
import re
import tempfile
from io import open
import debug_backend
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='test_jtag_arm')
def test_examples_sysview_tracing_heap_log(env, extra_data):
rel_project_path = os.path.join('examples', 'system', 'sysview_tr... | python |
from tkinter import *
from tkinter.messagebox import showinfo,askyesnocancel
from tkinter.filedialog import askopenfilename,asksaveasfilename
import os
from tkinter import simpledialog
def new(event=None): #.................Creates new file and saves current flle...........#
global file
var=askyesnocan... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 读写文本文件
Desc :
"""
def rw_text():
# Iterate over the lines of the file
with open('somefile.txt', 'rt') as f:
for line in f:
# process line
print(line)
# Write chunks of text data
with open('somefile.txt', 'wt') ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'Eevee'
SITENAME = u'fuzzy notepad'
SITEURL = ''
#SITESUBTITLE = ...
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ATOM = None
FEED_ALL_ATOM = None
... | python |
"""
Commands for fun
"""
from discord.ext import commands
class FunCommands(commands.Cog, name='Fun'):
def __init__(self, bot):
print('Loading FunCommands module...', end='')
self.bot = bot
print(' Done')
@commands.command(help='You spin me right round, baby, right round')
async ... | python |
from logging.handlers import DatagramHandler, SocketHandler
from logstash import formatter
# Derive from object to force a new-style class and thus allow super() to work
# on Python 2.6
class TCPLogstashHandler(SocketHandler, object):
"""Python logging handler for Logstash. Sends events over TCP.
:param host:... | python |
"""
Get Shelly Cloud information for a given host through web api.
For more details about this platform, please refer to the documentation at
https://github.com/marcogazzola/custom_components/blob/master/README.md
"""
import logging
from homeassistant.helpers.entity import (Entity)
from .const import (
REQUIREMEN... | python |
from socket import *
from select import *
HOST = ''
PORT = 10001
BUFSIZE = 1024
ADDR = (HOST, PORT)
#소켓 생성
serverSocket = socket(AF_INET, SOCK_STREAM)
#소켓 주소
serverSocket.bind(ADDR)
#연결 수신
serverSocket.listen(1)
#연결 수락
clientSocekt, addr_info = serverSocket.accept()
print(clientSocekt)
while True:
data = clie... | python |
# -*- coding: utf-8 -*-
"""
Name: population.py
Authors: Christian Haack, Stephan Meighen-Berger, Andrea Turcati
Constructs the population.
"""
from typing import Union, Tuple
import random
import numpy as np # type: ignore
import logging
import networkx as nx # type: ignore
import scipy.stats
from networkx.utils im... | python |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
from sklearn.preprocessing import MinMaxScaler
dataset = pd.read_csv('../Dataset/GPS Database Cleaned Data-One Day.csv', parse_dates=True, index_col='d... | python |
import torch.nn as nn
from MyPyTorchAPI.CustomActivation import *
class FCCov(torch.nn.Module):
def __init__(self, fc_input_size):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(fc_input_size, 512),
nn.BatchNorm1d(512),
... | python |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import os
import imageio
import numpy as np
import cv2
from tqdm import tqdm_notebook as tqdm
import scipy.misc
from generator import read_videofile_txt
import os
import shutil
from generator import build_label2str
from predict_and_save_kitty import extract_bbox_f... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.