content stringlengths 5 1.05M |
|---|
import argparse
import os
import dgl
from dgl import DGLGraph
from dgl.data import register_data_args, load_data
import dill
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
from torch.nn.functional import binary_cross_entropy_with_logits as BCELoss
... |
word = 'Jeni'
print (word)
word[2] = m
print word |
from _shared_python.aoc import *
from pprint import pprint
from copy import copy
#------------------------------------------------------------------------------#
def count_paths(edges, n, path, part2 = False, double = False):
if re.match(r"[a-z]+", n) and n in path:
if not part2 or double:
ret... |
#%%
# #!/usr/bin/env python
import sys
# [Define group level master information]
current_vin = None
make = None
year = None
curr = {}
def reset():
# [Logic to reset master info for every new group]
global current_vin
global curr
global make
global year
current_vin = None
cu... |
from scapy.all import Ether, IP as ScapyIP, TCP
from IPy import IP
import random
class getRandomIP:
def __init__(self, network, ipfail=None):
self.used_ips = []
self.network = network
self.ipfail = ipfail
def get(self):
iplist = IP(self.network)
... |
from flask import Flask
from flask import json
import logging
app = Flask(__name__)
@app.route("/")
def hello():
app.logger.info("Main requested!")
return "Hello Bhupend!"
@app.route("/status")
def status():
response = app.response_class(
response=json.dumps({"result": "OK - healthy"}),
... |
from django.test.testcases import TestCase
from mock import patch
from robber import expect
from data import cache_managers
class CacheManagersTestCase(TestCase):
@patch('data.cache_managers.allegation_cache_manager.cache_data')
@patch('data.cache_managers.officer_cache_manager.cache_data')
@patch('data... |
"""
Code adapted from https://github.com/UKPLab/sentence-transformers
"""
import csv
import gzip
import os
from typing import Union, List
from torch.utils.data import Dataset
from typing import List
import torch
import logging
from tqdm import tqdm
class InputExample:
"""
Structure for one input example with... |
import <warning descr="Python versions 2.6, 2.7 do not have module _bz2">_bz2</warning> |
'''import all'''
from .sources import *
from .utils import *
|
from pathlib import Path
from typing import List, Tuple
import yaml
import torch
from sodium.utils import setup_logger
logger = setup_logger(__name__)
class BaseTrainer:
"""Base Trainer for all models
"""
def __init__(self, model, criterion, optimizer, config, device):
self.model = model
... |
"Models and views for Types (aka 'Items', except generic)"
from sqlalchemy import Integer, String, Float, Column, ForeignKey, Boolean
from sqlalchemy.orm import relationship, backref
try:
# Python 3
from urllib.request import urlopen
from urllib.parse import urlencode
except ImportError:
# Python 2
... |
#!/usr/bin/python
import png,argparse,sys,math,bbc
##########################################################################
##########################################################################
def save_file(data,path,options):
if path is not None:
with open(path,'wb') as f:
f.write(''.... |
from datetime import date
import boundaries
boundaries.register('Census subdivisions',
domain='Canada',
last_updated=date(2011, 11, 28),
name_func=boundaries.attr('CSDNAME'),
id_func=boundaries.attr('CSDUID'),
slug_func=boundaries.attr('CSDUID'),
authority='Statistics Canada',
source_url='... |
import discord
from discord.commands import Option, slash_command
from discord.commands.context import AutocompleteContext
from discord.ext import commands
from discord.utils import format_dt
import datetime
import random
import traceback
import humanize
import pytimeparse
from data.model.giveaway import Giveaway as G... |
"""
=============================
Lasso with Cross-validation
=============================
This example shows how to perform hyperparameter optimization
for a Lasso using a full cross-validation score.
"""
# Authors: Quentin Bertrand <quentin.bertrand@inria.fr>
# Quentin Klopfenstein <quentin.klopfenstein@u... |
#first file uploaded
|
class Solution:
def generateMatrix(self, n):
if not n:
return []
res = [[0 for _ in range(n)] for _ in range(n) ]
left, right, top, bottom = 0, n-1, 0, n-1
while left <= right and top <= bottom:
for i in range(left, right):
res[top][i] = num
... |
def _identify_strategy(self):
self.strategy_name = 'Unknown strategy'
# Identify the strategy implemented
if len(self) is 4:
if(self.long_calls and self.long_puts and self.short_calls and self.short_puts):
# Same expiration
if(self.long_calls[0][1... |
import unittest
import re
import subprocess
from StringIO import StringIO
from mock import patch
DATA_POSITIVE_VALUES = [10, 20, 30, 40, 30, 20, 30, 25, 10, 20]
DATA_NEGATIVE_VALUES = [-20, -30, -40, -50, -40, -40, -40, -30, -20, -10]
DATA_FLOATS = [10.1, 10.2, 10.3, 4.5, 27, 99.9, 10, 20, 30, 40]
class Test... |
# copybara:insert_for_google3_begin
# load("//tools/build_defs/proto/cpp:cc_proto_library.bzl", _cc_proto_library="cc_proto_library")
# copybara:insert_end
# copybara:strip_for_google3_begin
_cc_proto_library = native.cc_proto_library
# copybara:strip_end
def proto_library(**kwargs):
native.proto_library(
... |
__version__ = "1.0.2"
from .api import *
|
#!/usr/bin/env python
'''calculate packet header overhead
requires python3
usage:
python3 calc_packet_overhead.py $1 $2 $3
$1 = line speed in mbps
$2 = average packet size expected
$3 = ethernet overhead e.g. 18 bytes for ethernet +4 with dot1q
use whole numbers!
example:
python calc_packet_overh... |
from RocketPy import RocketPy
#%matplotlib notebook
##################################################################
rocket = RocketPy()
rocket.initialize("params_config.xml", "")
rocket.move(0.8)
#print(rocket.get_states())
|
"""Widget for Node One sensor. Displas data from it in form of tile"""
from service.widget import Widget, Clickable
from PIL import Image
import service.comm as comm
class NodeOne(Widget, Clickable):
"""Class NodeOne"""
def __init__(self, font):
super().__init__()
self.font = font
self... |
#!/usr/bin/env python3
import argparse
import lzma
import sys
import unicodedata
def preprocess_corpus(inf, outf):
outf = lzma.open(outf, 'wt', encoding='utf-8')
for line in lzma.open(inf, 'rt', encoding='utf-8'):
if line.startswith("FILE"):
continue
sent = []
for w in li... |
from sys import argv
import os
class cl:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def cmpStrings():
#Get List1
print("[ ] get strings of "+argv[1])
cmdReturn = os.popen("strings "+argv[1]).re... |
# The following file was auto-generated, but has been edited to remove tests that
# do not pass; we have verified that they should NOT pass, due to our interpretation
# of regex formats. The tests were removed for the following reasons (which were not
# easily recognizable during the parsing and creation of this file)... |
# -*- coding: utf-8 -*-
# Copyright 2014 Mirantis, Inc.
#
# 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 requi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... |
# -*- coding: utf-8 -*-
#
import os
os.environ['HUB_HOME'] = "./modules"
import sys
import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
import paddlehub as hub
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import wx
import wx.xrc
import warnings
warnings.... |
import os
import sys
from PyQt4 import QtCore, QtGui, uic
from lantz import Q_
from PyQt4.Qt import QApplication
import pharos.view.GUI.QtCreator.resources_rc
from pharos.view.GUI.laser_widget import LaserWidget
from pharos.view.GUI.monitor_config_widget import MonitorConfigWidget
class MainWindow(QtGui.QMain... |
# -*- coding: utf-8 -*-
u"""
Created on 2017-6-8
@author: cheng.li
"""
from PyFin.tests.CashFlows.testCashFlow import TestCashFlow
from PyFin.tests.CashFlows.testInterestRate import TestInterestRate
__all__ = ['TestCashFlow',
'TestInterestRate'] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 10:25:01 2018
train a CNN for puma. The cnn configuration used is the one obtained
in the tuning process.
At the moment, this script is for a training set which is small
enough to fit into memory in one go.
This is the main experiment, which do... |
#!/usr/bin/python
import re
import time
from Enums.typeHash import TypeHash
from Functions import HashDef
nb_password_found = 0
world_list_tab = []
timer = time.time()
world_list = open('./dico.txt', 'r')
for password in world_list.readlines():
world_list_tab.append(password)
world_list.close()
shadow = open('... |
import pytest
import numpy as np
from deephyper.problem import HpProblem
from deephyper.evaluator import Evaluator
from deephyper.search.hps import AMBS
def run(config):
return config["x"]
problem = HpProblem()
problem.add_hyperparameter((0.0, 10.0), "x")
def test_ambs():
create_evaluator = lambda: Evalu... |
##
## Update asset prerequisites
## Walk asset directory and update easy to fixup asset prerequisites
##
import argparse
import sys
import json
import os
from os.path import splitext, join, realpath
import base64
import uuid
from subprocess import Popen, PIPE
parser = argparse.ArgumentParser(prog='generate asset prer... |
from math import *
import pyglet
import rabbyt
from pyglet.window import key
from pyglet.window import mouse
from pyglet.gl import *
def CalcRot(prev_time, rps, step, direction):
time = rabbyt.get_time()
rt = (1.0 / rps) / (360 / step)
if time - prev_time >= rt:
num_steps = int((time - prev_time) /... |
import tensorflow as tf
import math
import numpy as np
# http://archive.ics.uci.edu/ml/datasets/Iris
# load train data set
input = np.loadtxt('iris_train.data', unpack=True, dtype='float')
data = np.transpose(input)
x_data = data[:, 0:4]
y_data = data[:, 4:]
# load test data set
input = np.loadtxt('iris_test.data', ... |
import copy
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_adapt.hooks import (
AFNHook,
BNMHook,
BSPHook,
DomainConfusionHook,
GANEHook,
GANHook,
MCCHook,
VADAHook,
validate_hook,
)
from pytorch_adapt.layers import EntropyLoss, Uniform... |
import os
import dotenv
from configparser import ConfigParser
from . import functions as fn
# dir
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)
CONF_DIR = os.path.join(BASE_DIR, 'conf')
CONTRACTS_DIR = os.path.join(BASE_DIR, 'contracts')
# config.ini
cfg = ConfigParser()
c... |
#UNIVERSIDAD DE EL SALVADOR
#FACULTAD DE INGENIERIA Y ARQUITECTURA
#Escuela de Ingenieria Electrica
#Analisis Numerico
#Docente: Msr. Ing. Wilber Calderon
#Tarea final: Metodos de integracion de Simpson
#Tarea realizada por:
#Henry Anselmo Torres Vanegas
#Deiby Josue Moreira Gomez
# -*- coding: utf-8 -*-
... |
#pip install pygame
#pip install tinytag
#pip install PIL
import os, tkinter, tinytag, time, threading, random, pygame, sqlite3
from tkinter import messagebox, filedialog
from PIL import Image, ImageTk
#library listi baraye neghahdashtane esme ahang ha
import mutagen.mp3
library = os.listdir(r'library')
#playlist listi... |
class _Tigger:
def __str__(self):
return "I'm the only one!"
def roar(self):
return 'Grrr!'
_instance = None
def Tigger():
global _instance
if _instance is None:
_instance = _Tigger()
return _instance |
#########################################################
# Name: Asmit De #
# ID: aud311 #
# Date: 09/07/2016 #
# Assignment: Homework 1, Problem 7 #
# Description: Program to conver... |
# -*- coding: utf-8 -*-
#
# SPDX-FileCopyrightText: © 2013 The glucometerutils Authors
# SPDX-License-Identifier: MIT
"""Common exceptions for glucometerutils."""
from typing import Any, Optional
class Error(Exception):
"""Base class for the errors."""
class CommandLineError(Error):
"""Error with commandli... |
# -*- coding: utf-8 -*-
"""
Created on 3/14/2021
Author: Arnold Souza
Email: arnoldporto@gmail.com
"""
|
# 1177. Can Make Palindrome from Substring
import collections
class Solution:
# Brute force: TLE
def canMakePaliQueries2(self, s: str, queries):
ans = []
for q in queries:
l, r, k = q[0], q[1], q[2]
cnt = sum([v % 2 for v in collections.Counter(s[l:r+1]).values()])
... |
from hypothesis import (assume,
given,
note)
from pode.pode import Graph
from tests.strategies.geometry.base import nonnegative_integers
from tests.strategies.graphs import graphs
@given(graphs)
def test_last_node(graph: Graph) -> None:
note(f'Graph nodes: {list(gr... |
import imgui
from imgui.integrations.glfw import GlfwRenderer
class Gui:
def __init__(self, window):
imgui.create_context()
self.impl = GlfwRenderer(window)
self.color = 0.45, 0.55, 0.60, 1.00
def NewFrame(self):
self.impl.process_inputs()
imgui.new_frame()
d... |
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
import pathlib
import itertools as it
import csv
from math import sqrt
from ._functions import ACTIVATIONS, ACTIVATIONS_DERIVATIVES, COST_FUNCTIONS, COST_FUNCTION_SELECTION
from ._stochasticoptimisers import OPTIMISERS
# Exception for wrong n... |
import os
import pandas as pd
from pyexlatex.tools import csv_to_raw_latex, date_time_move_latex
def df_to_pdf_and_move(dflist, outfolder, outname='table', tabular_string='', string_format='',
above_text='', below_text='',
font_size=12, caption='', missing_rep=' - ', land... |
import os
import reporter
from http.server import BaseHTTPRequestHandler, HTTPServer
def report(type, msg):
reporter.report(type, msg, 'Backup Manager')
class BackupServerWeb(BaseHTTPRequestHandler):
backupFunction = None
secureDeleteFunction = None
challengeCode = os.environ['CHALLENGE_CODE']
... |
from django.db import models
from django.utils import timezone
from news.enums import ArticleStatus
class ArticleManager(models.Manager):
def published(self):
return super().get_queryset().filter(status=ArticleStatus.PUBLISHED)
|
# DO NOT EDIT! This file is automatically generated
import typing
from commercetools.helpers import RemoveEmptyValuesMixin
from commercetools.platform.models.inventory import (
InventoryEntry,
InventoryEntryDraft,
InventoryEntryUpdate,
InventoryEntryUpdateAction,
InventoryPagedQueryResponse,
)
from... |
import math
from torch.optim.lr_scheduler import LambdaLR
class LinearLRLambda:
def __init__(self, num_warmup_steps, num_training_steps):
self.num_warmup_steps = num_warmup_steps
self.num_training_steps = num_training_steps
def __call__(self, current_step): # the function formerly known as ... |
import asyncio
import datetime as dt
from aiohttp import web
class ListTasks:
__history_num = 0
done_tasks = []
not_done_tasks = {"history_num": [], "date_created": [], "num": [], "timeout": []}
@classmethod
def get_not_done_tasks(cls):
data = {
f"task_{num}": {
... |
''' Generate glue layer '''
import argparse
import yaml
import os.path
import sys
import logging
import importlib
from tools.gen.dump import PrintDump, FileDump
from tools.gen.generate import generate
prog_description = 'Generate c++ glue layer mapping TEQ and some data-processing library.'
def parse(cfg_str):
... |
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
from . proxy import Proxy
from . event import Event
class EvtHandler(object):
"""
This class represents an event raising base class, to which specific
callbacks can be attached to be called when appropriate event is fired.
... |
from tkinter import *
from PIL import ImageTk
from . import Actor
from . import Wall
"""
Main script. Without it
the game engine wouldn't run.
"""
has_prev_key_release = None
class Main:
def __init__(self, canvas=None, window=None, wh=(100, 100), bgcolor=None, bgimg=None, title=None,
resizablex... |
# import: os, csv
import os
import csv
#path of data file
csvpath = os.path.join("Resources", "election_data.csv")
#set containers/variables
voter_count = 0
candidates = []
#open and read file
with open(csvpath,'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
#read header
election_header =... |
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import numpy as np
import random as random
import matplotlib.pyplot as plt
import classes.configClass as cf
import classes.IsingLatticeClass as Ising
from classes.SimulationClass import Simulation
#--------------... |
# ------ Python standard library imports ---------------------------------------
from typing import Any, Union
# ------ External imports ------------------------------------------------------
# ------ Imports from own package or module ------------------------------------
from movieverse.metadatalib.base import MetaDat... |
# Copyright (c) 2012, CyberPoint International, LLC
# 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 lis... |
# Copyright 2021 Allan Galarza
#
# 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 writi... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
"""
Module with reading functionalities for filter profiles.
"""
import os
import warnings
import configparser
from typing import Union, Tuple
import h5py
import numpy as np
from typeguard import typechecked
from scipy.interpolate import interp1d, InterpolatedUnivariateSpline, interpolate
from species.data import ... |
#!/usr/bin/env python
import os, sys, time
import matplotlib.nxutils as nxutils
import matplotlib.numerix as nx
def report_memory(i):
pid = os.getpid()
a2 = os.popen('ps -p %d -o rss,sz' % pid).readlines()
print i, ' ', a2[1],
return int(a2[1].split()[1])
for i in range(500):
report_memory(i)
... |
from __future__ import print_function
import sys, os
import time
import getopt
import re
import xml.etree.ElementTree as etree
def trimToSingleSpace(text):
if text is None or len(text) == 0:
return ""
t = text.strip()
if len(t) == 0:
return t
if text[0].isspace():
t = " %s" % t
... |
import sys
from typeseam.app import create_app
from typeseam.auth.tasks import invite_new_user
class MissingEmailError(Exception):
pass
def run(emails):
app = create_app()
with app.app_context():
for email in emails:
invite_new_user(email)
if __name__ == '__main__':
if len(sys.... |
import benchmark_evaluator.search.query_engine_impl as query_engine
import benchmark_evaluator.search.url_comparator as url_comparator
from benchmark_evaluator.util.file_util import FileUtil
from benchmark_evaluator.util.data_structure import SearchResults
def __get_baseline_for_single_query(input_query, conn):
"... |
# 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... |
from autofit.database import query as q
class TestCombination:
def test_simple(
self,
less_than,
greater_than,
simple_and
):
assert q.Q(
"a",
less_than
) & q.Q(
"a",
greater_than
) == simple... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017 Guenter Bartsch
#
# 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
#
# ... |
#!/usr/bin/python3
from selenium import webdriver
import time
import json
from selenium.webdriver.firefox.options import Options
from EnvLoginGatherer import EnvLoginGatherer
import sys
import re
class KeywordCrawler(EnvLoginGatherer):
def __init__(self, gecko_directory, login_directory="login.json", search_dire... |
def calc_ls(num, expected):
val = 1
loopsize = 0
while True:
val = val * num
rem = val % 20201227
val = rem
loopsize += 1
if val == expected:
break
return loopsize
def transform(num, ls):
val = 1
for i in range(ls):
val = ... |
import os
import re
import objc
from AppKit import *
from Foundation import *
from lib.utils import detect_dropbox_folder, set_pref
from lib.windows import UpShotWindowController
DROPBOX_URL_RE = re.compile(r'^https?://dl.dropbox.com/u/(\d+)/.*')
class DropboxDetectWindowController(UpShotWindowController):
ni... |
#!/usr/bin/env python3
## binary.py
## This script takes a file containing one or more binary strings and
## them into their ASCII values. Configurable start and stop bits, as well as
## byte length.
import sys
start = 0
byte = 8
stop = 1
if not len(sys.argv) > 1:
print("You need to specify an input file.")
... |
from FASTQBasics import QualityProfile
def default_illumina_1_5():
serial_illumina = 'QUAL_PDNOZPK3Z5WUXEQV6ZL5A6PWIPPC67VUYBOAZPQAA3NTIHBVKBZLPBFKOBLTLKFVWT7LXV4XGFZ4IJJD6632WC26CCWVN5Z6POXTLV544SGIYMLCYSENOL577O33776NL762PX747NP77XK77T4V77P6S777D36ECDB6O77D77YHPRF77XXK6773Q5P773O77T5B677X7O77ZQ2773XLPH6PXV7ATH77TP... |
class UpdateDataIntegrationModel:
def __init__(self,
Code: str = None,
SourceConnectionName: str = None,
SourceSchema: str = None,
SourceTableName: str = None,
SourceQuery: str = None,
TargetConnectionName: str = N... |
from __future__ import absolute_import
from past.builtins import basestring
from .transformer import Transformer
class Sieve(Transformer):
"""
Filters rows depending on provided filter expression.
Only records complying with filter condition are kept.
Examples
--------
>>> transformer = T.Sie... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2016
# --------------------------------------------------------------------------
from docplex.mp.... |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V1CSINodeDriverDict generated type."""
from typing import TypedDict, List
from kubernetes_typed.client import V1VolumeNodeResourcesDict
V1CSINodeDriverDict = TypedDict(
"V1CSINodeDriverDict",
{
"allocatable": V1VolumeNodeResourcesDict,
"name"... |
import abc
from pathlib import Path
from configs import configurator as Configs
###
class Storage():
@staticmethod
def initialize() -> None:
# Storage._weights_intervals_dir().mkdir(parents=True, exist_ok=True)
Storage._logs_dir().mkdir(parents=True, exist_ok=True)
Storage._weights_... |
import datasets
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from itertools import combinations
def main():
print ('Train and test join data using baseline model')
num_rows, ... |
import os
import random
import pygame
import zwave.helper
class Player(pygame.sprite.Sprite):
def __init__(self, game, model = "01"):
super(Player, self).__init__()
self.weapon = {}
self.weapon["type"] = "gun"
self.weapon["delay"] = 20
self.weapon["timer"] = 0
s... |
from typing import List
# 减少了空间的使用量
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n == 0 or n == 1:
return 0
# 第i天拥有股票的最大profit
hold = [None for _ in range(n)]
# 第i天卖出股票的最大profit
unhold = [None for _ in range(n)]
... |
import re
import copy
from . import LLS_rules
from .LLS_messages import print_message
from .LLS_literal_manipulation import negate, variable_from_literal, implies
def parse_input_string(input_string, indent = 0, verbosity = 0):
"""Transforms a "search pattern" given as a string into a SearchPattern"""
print_m... |
# """
# To run tests:
# pytest-3 connect4
# """
# from collections import namedtuple
# import textwrap
# import numpy as np
# from .Connect4Game import Connect4Game
# # Tuple of (Board, Player, Game) to simplify testing.
# BPGTuple = namedtuple('BPGTuple', 'board player game')
# def init_board_from_moves(moves, he... |
import os
import copy
import pandas as pd
from ..toolPack import tools_file
from ..toolPack import tools_app
from ..toolPack import tools_log
def initArgs(args):
if args.taskType == None:
if args.dirIn.endswith('_c'):
args.taskType = 'c'
elif args.dirIn.endswith('_r'):
args.... |
# View more 3_python 2_tensorflow_old on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
# 7 - Activation function
"""
The available activation functions in theano can be found in this link:
h... |
from .proto import *
__all__ = proto.__all__
|
#!/usr/bin/env python3
import ast
import sys
from itertools import chain
from pathlib import Path
STUBS_SUPPORTING_PYTHON_2 = frozenset(
path.parent for path in Path("stubs").rglob("METADATA.toml") if "python2 = true" in path.read_text().splitlines()
)
CONTEXT_MANAGER_ALIASES = {"ContextManager": "AbstractContex... |
import asyncio
from random import randrange
async def foo(n):
s = randrange(5)
print(f'{n} will sleep for: {s} seconds')
await asyncio.sleep(s)
print(f'n: {n}!')
async def main():
tasks = [foo(1), foo(2), foo(3)]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
... |
from django.db import models
class YumPackages(models.Model):
name = models.CharField(max_length=128)
packages = models.CharField(max_length=2048)
releasever = models.CharField(max_length=128)
repo_name = models.CharField(max_length=128)
|
import os
import sys
import json
import logging
import argparse
import uuid
import time
from shutil import copyfile
import shure
import offline
import tornado_server
APPNAME = 'micboard'
CONFIG_FILE_NAME = 'config.json'
FORMAT = '%(asctime)s %(levelname)s:%(message)s'
config_tree = {}
gif_dir = ''
group_update_l... |
from typing import List, Iterator, TYPE_CHECKING
from pyot.conf.model import models
from pyot.core.functional import parse_camelcase
from .base import PyotCore, PyotStatic
if TYPE_CHECKING:
from ..riot.account import Account
# PYOT STATIC OBJECTS
class LeaderboardPlayerData(PyotStatic):
puuid: str
game... |
#!/usr/bin/python
# coding: utf-8
import logging
import logging.config
import pendulum
import time
from datetime import datetime
from functools import partial
from ..storage.connection import Connection
from ..storage.models import TimeSeries, EventList, MetaDataItem, FastDictTimeseries
from ..core.helper import set... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES)
#
# 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
#
# ... |