content stringlengths 5 1.05M |
|---|
'''test pysftp.Connection.readlink - uses py.test'''
from __future__ import print_function
from common import SKIP_IF_CI
from io import BytesIO
@SKIP_IF_CI
def test_readlink(lsftp):
'''test the readlink method'''
rfile = 'readme.txt'
rlink = 'readme.sym'
buf = b'I will not buy this record, it is scra... |
import numpy as np
# sigmoid function
def nonlin(x):
return 1 / (1 + np.exp(-x))
def get_rand_weights(num_inputs, num_outputs, hidden_layer_nodes):
# Generate weights with value between -1 to 1 so that mean is overall 0
weights_1 = 2 * np.random.random((num_inputs, hidden_layer_nodes)) - 1
weights_2... |
#!/usr/bin/python
import collections
import fnmatch
import os
import re
import subprocess
import sys
import time
import traceback
from pytools.common.common import *
def remove_repeated_spaces(line):
return " ".join(line.split())
def chunk_list(array_to_chunk, chunk_size):
"""Yield successive n-sized chunks ... |
import msvcrt # Windows only
def getch():
if msvcrt.kbhit():
return ord(msvcrt.getch())
return 0
'''
while True: # test
ch = getch()
if ch != b'\xff':
if ch == b'\x1b': # ASCII Esc
print("exit\n")
break
... |
n = int(input())
print(n)
for i in range(n):
print(1) |
import socket
import cv2
import numpy
TCP_IP = 'localhost'
TCP_PORT = 5001
sock = socket.socket()
sock.connect((TCP_IP, TCP_PORT))
frame = cv2.imread('scene.jpeg')
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]
result, imgencode = cv2.imencode('.jpg', frame, encode_param)
data = numpy.array(imgencode)
stringDa... |
from abc import ABC, abstractmethod
class VestDevice(ABC):
@abstractmethod
def set_pin(self, index, intensity):
pass
@abstractmethod
def set_pins_batched(self, values = dict):
pass
@abstractmethod
def set_frequency(self, frequency):
pass
@abstractmeth... |
# Number of Connected Components in an Undirected Graph: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
# You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.
# Return th... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.com.h21lab.TS29510_Nnrf_NFDiscovery.handler.base_model_ import Model
from openapi_server.com.h21lab.TS29510_Nnrf_NFDiscovery.handler.ipv6_addr impor... |
#!/usr/bin/env python3
""" This script creates histogram of which txout types are present in a snapshot.
Namely, this script creates two CSV files in the given --target-folder:
1. Histogram CSV file containing the counts for each txout type that occurred.
2. Another CSV file, which contains the output scri... |
# Copyright 2021, Google LLC.
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# hsh
# Copyright 2016 Christopher Simpkins
# MIT license
# ------------------------------------------------------------------------------
import sys
from commandlines import Command
from h... |
#!/usr/bin/env python3
import os
from sys import platform
def Lynx(busqueda):
buscador = f'lynx -source {busqueda} > prueba.html'
os.system(buscador)
buscador = f'lynx {busqueda}'
os.system(buscador)
def Mensaje():
print('Tipos de Busquedas permitidas:')
print('1. Busqueda simple')
print('... |
import itertools
import numpy
from ..cg import voronoi_frames
from ..io.fileio import FileIO
from ._contW_lists import ContiguityWeightsLists
from .util import get_ids, get_points_array
from .weights import WSP, W
from .raster import da2W, da2WSP
try:
from shapely.geometry import Point as shapely_point
from ... |
from datetime import date, timedelta
import json
from django.conf import settings
from mock import patch
from nose.tools import eq_
from lib.buyers.models import Buyer, BuyerPaypal
from solitude.base import APITest
@patch('lib.paypal.client.Client.get_preapproval_key')
@patch.object(settings, 'PAYPAL_USE_SANDBOX',... |
#!/usr/bin/env python3
import streamlit as st
showWarningOnDirectExecution = False
import pandas as pd
import numpy as np
import gzip
import gensim.downloader as api
from gensim import corpora
from gensim.similarities import WordEmbeddingSimilarityIndex
from gensim.similarities import SparseTermSimilarityMatrix
import ... |
import os, csv, platform, argparse
from tqdm import tqdm
from bs4 import BeautifulSoup
from selenium import webdriver
def main(args):
# To do
# make csv file checker
# Check Platform
if platform.system() == 'Windows':
print('Detected OS : Windows')
executable = './webdriv... |
# Copyright 2013 IBM Corporation
# All Rights Reserved.
#
# 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 ... |
# There are exactly ten ways of selecting three from five, 12345:
# 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
# In combinatorics, we use the notation, 5C3 = 10.
# In general,
# nCr = n! / r!(n-r)! ,where r <= n, n! = n*(n-1)*...*3*2*1, and 0! = 1.
# It is not until n = 23, that a value exceeds one-million: 2... |
import requests
from flask import request, abort, jsonify
from .settings import config
import datetime
ERROR_CODES = {
400: {"errorCode": "INVALID_JSON"},
403: {"errorCode": "INVALID_API_KEY"},
404: {"errorCode": "NOT_FOUND"},
410: {"errorCode": "INVALID_USER_TOKEN"},
429: {"errorCode": "RATE_LIMI... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import re
from sqlalchemy.dialects.oracle.base import OracleDialect
from sqlalchemy.sql import sqltypes
from sqlalchemy import util, exc
from .base import MixedBinary, BaseDialect
colspecs = util.update_copy(
Oracl... |
from systemcheck.checks.models.checks import Check
from systemcheck.models.meta.orm_choices import choices
from systemcheck.models.meta import Base, ChoiceType, Column, ForeignKey, Integer, QtModelMixin, String, qtRelationship, \
relationship, RichString, generic_repr, Boolean, RestrictionsMixin, OperatorMixin, Dat... |
from __future__ import print_function
# Uncomment to run this module directly. TODO comment out.
#import sys, os
#sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
# End of uncomment.
import unittest
import subprocess
import runserver
from views import neo4j_driver
import helper
from passlib.hash import ... |
#########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# 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... |
import sys
import os
import sqlite3
import json
import subprocess
from pprint import pprint
INDEX_FILE_NAME = 'index.json'
def get_database_path():
if len(sys.argv) < 2:
raise ValueError('Usage: requiem path/to/database/directory')
return os.path.join(
os.path.dirname(sys.argv[0]),
... |
import numpy as np
from PIL import Image
def is_image_file(filename):
return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])
def load_img(filepath):
img = Image.open(filepath).convert('RGB')
img = img.resize((256, 256), Image.BICUBIC)
return img
def save_img(image_tens... |
from pydantic.main import BaseModel
from pydantic.networks import EmailStr
from app.models.rwmodel import MongoModel
class TokenPayload(MongoModel):
email: EmailStr = ""
class Token(BaseModel):
accsee_token: str
token_type: str |
import os
import requests
import datetime as dt
from twilio.rest import Client
STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"
now = dt.datetime.now()
if now.day < 12:
yesterday = f"{now.year}-{now.month}-0{now.day - 2}"
day_before = f"{now.year}-{now.month}-0{now.day - 3}"
else:
yesterday = f"{now.year}-{now.... |
import pytest
import sys
import io
from adjust_driver import Ec2WinDriver, DESC, HAS_CANCEL, VERSION
adjust_json_stdin = '''\
{
"application": {
"components": {
"web": {
"settings": {
"UriEnableCache": {"value": 1},
"UriScavengerPeriod":... |
import pytest
from habr_challenge.site_config import Selector, SiteConfig
@pytest.fixture(scope="module")
def selector():
return Selector('div', class_='test', id_='me')
@pytest.fixture(scope="module")
def site_config():
SiteConfig.SITE_CONFIG['test'] = {
'url': 'http://test.com/',
'paginat... |
# Copyright 2016 Chr. Hansen A/S and The Novo Nordisk Foundation Center for Biosustainability, DTU.
# 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.... |
import sys, logging, os, random, math, arcade, open_color
#check to make sure we are running the right version of Python
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
#turn on logging, in case we have to leave ourselves debugging... |
from versions.default import *
class Magma(Server):
def getlink(version_number:str) -> str:
versions = {
'1.12':'https://www.mediafire.com/file/0t95jcbgint6bod/Magma-761933c-STABLE-server.jar/file',
'1.12.2':'https://www.mediafire.com/file/un8i590pylhxx3r/Magma-dd991e7-DE... |
from dearpygui.core import *
import os
def set_style(heron_path):
set_style_window_padding(8.00, 8.00)
set_style_frame_padding(4.00, 3.00)
set_style_item_spacing(8.00, 4.00)
set_style_item_inner_spacing(4.00, 4.00)
set_style_touch_extra_padding(0.00, 0.00)
set_style_indent_spacing(21... |
# TODO Comment
class Node:
def __init__(self, parent):
self._children = []
self._leaf_data = None
self._parent = parent
# TODO Comment
def get_children(self):
return self._children
# TODO Comment
def get_parent(self):
return self._parent
# TODO Comment... |
import json
import csv
import script
import numpy
input_file = open("migrantData.json",'r', encoding='utf-8')
input_data = json.load(input_file)
input_file.close()
causeList = []
uniqueCause = []
causesNewDefList = []
#generalizing causes of death
def deathCauseReplacement(input_data):
for i in input_data:
... |
import unittest
from il2fb.ds.events.definitions.base import Event
from il2fb.ds.events.definitions.cheating import CheatingInfo
from il2fb.ds.events.definitions.cheating import CheatingDetectedEvent
from il2fb.ds.events.definitions import registry
class CheatingDetectedEventTestCase(unittest.TestCase):
def tes... |
from __future__ import absolute_import
from django.test import TestCase
from .models import Tournament, Organiser, Pool, PoolStyle
class ExistingRelatedInstancesTests(TestCase):
fixtures = ['tournament.json']
def test_foreign_key(self):
with self.assertNumQueries(2):
tournament = Tournam... |
from collections import defaultdict
class FrequencyList(list):
def __init__(self, members):
super().__init__(members)
def frequency(self):
counts = defaultdict(int)
for item in self:
counts[item] += 1
return counts
class BinaryNode:
def __init__(self, value, ... |
import re
import jax.numpy as jnp
import numpy as np
import pytest
from pgmax import fgroup, vgroup
def test_single_factor():
with pytest.raises(ValueError, match="Cannot create a FactorGroup with no Factor."):
fgroup.ORFactorGroup(variables_for_factors=[])
A = vgroup.NDVarArray(num_states=2, shape... |
import time
from WVPoster import WVPoster
wv = WVPoster()
wv.postToSIO("chat", {'id': str(time.time()),
'name': 'Zeno',
't': time.time(),
'text': 'Hello.....'})
|
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
from __main__ import *
import os,sys
def reset():
os.remove("current.txt")
sys.exit()
master = Tk()
master.title("DCM - Home Cinema")
top = Label(master, text="Cinema!", font=("Helvetica", 50))
top.grid()
def adverts():
global advertselect... |
from __future__ import print_function
import sys
import os
import csv
def parse_homeowners(csv_file):
with open(csv_file, 'r') as f:
reader = csv.DictReader(f)
homeowners = [x for x in reader]
return homeowners
if __name__ == "__main__":
parse_homeowners(sys.argv[1])
|
#!/usr/bin/env python3
import re
def calc_ore_count(reaction_graph, product, amount, stash):
count, dependencies = reaction_graph.get(product)
reserve = stash.get(product, 0)
while amount > 0 and reserve > 0:
reserve -= 1
amount -= 1
stash[product] = reserve
ore_count = 0
... |
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
from mycroft.util.log import LOG
from random import randint
import re
__author__ = "HellCatVN"
class RandomSkill(MycroftSkill):
def __init__(self):
super(RandomSkill, self).__init__(name="RandomSkill")
@... |
class HostNetworkAddress(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_network_address(idx_name)
class HostNetworkAddressColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
|
from typing import List, Mapping, Optional
import torch
from ._translation_base import _TranslationBase, NullableTensor
class Field(_TranslationBase):
"""
A field is not actually a translator, this is experimental
and will later be refactored to inherit from another interface.
"""
def batch_tensor_... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from local_utils import detect_lp
from os.path import splitext,basename
from keras.models import model_from_json
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.mobilenet_v2 ... |
"""
Exposes regular shell commands as services.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/shell_command/
"""
import logging
import subprocess
import shlex
import voluptuous as vol
from homeassistant.helpers import template
from homeassistant.excep... |
from hypernets.conf import configure, Configurable, Bool, Float, Int, Enum, List
from hypernets.tabular.sklearn_ex import DatetimeEncoder
@configure()
class HyperGBMCfg(Configurable):
# numeric
numeric_pipeline_mode = \
Enum(['simple', 'complex'], default_value='complex',
config=True,
... |
import os
from django.apps import apps
from django.conf import settings
from .utils import get_tailwind_src_path
class ValidationError(Exception):
pass
class Validations:
def acceptable_label(self, label):
if label not in ["init", "install", "npm", "start", "build", "deploy"]:
raise V... |
"""
Tool for visualizing OVAL rules from
ARF XML generated with SCAP scanners.
"""
__version__ = '1.3.2'
|
import os
shuffle_f = open('/data/Datasets/DiOR/DeepFashionDX/deepfashion_test_up_no_shuffle.txt','r')
lines = shuffle_f.readlines()
std_txt = open('/data/Datasets/DiOR/DeepFashionDX_noshuffle/standard_test_anns.txt', 'w')
std_txt.write('pose\n')
std_txt.write('v0200c120000bs0leo700hftjqr66jg0-frmaes_0132.jpg\n') # 随... |
from sklearn.model_selection import KFold
import tensorflow
import numpy
import os
import sys
# --- Machine Learning Hyper Parameters [START] --- #
BATCH_SIZE = 1000
LEARNING_RATE = 0.001
EPOCHS = 100
CLASSES = 2 # Buggy vs Non-Buggy
LAYER_NEURONS = 128
FEATURE_NUM = 130 # 34 + (16 * 6)
DROPOUT_RATE = 0.5
# --- Machin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#=======================================================================
#
# sha256.py
# ---------
# Simple, pure Python model of the SHA-256 hash function. Used as a
# reference for the HW implementation. The code follows the structure
# of the HW implementation as much a... |
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
c1 = ComplexNumber(2, 3)
c1.holy = 'This attr used to not exist but it does now'
|
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
class BackendSession(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
print("Backend session joined: {}".format(details))
def onhello(msg=None):
print("event received... |
"""Validation"""
import re
from . import Instance
class Validator:
"""Factory for a misc.validation.MultiValidator
that guesses which validator to use
"""
def __new__(cls, *checks):
"""Create a new mis.validation.MultiValidator guessing
which validator to use
... |
import psycopg2 as dbapi2
from flask import current_app
from flask_login import UserMixin
from passlib.apps import custom_app_context as pwd_context
class EventRestaurants():
def __init__(self, eventId, userId):
self.Id = ""
self.eventId = eventId
self.userId = userId
with dbapi2.co... |
import numpy as np
import torch
from .base_model import BaseModel
from . import networks
from .nce import PatchNCELoss
import util.util as util
class CUTModel(BaseModel):
""" This class implements CUT and FastCUT model
The code borrows heavily from the PyTorch implementation of CycleGAN
https://github.com... |
from django.urls import path
from blog import views
#TEMPLATE TAGGING
app_name = 'blog'
urlpatterns = [
path('<int:year>/', views.archeive_posts, name='archeive_post'),
path('<int:year>/<int:month>/<int:day>/', views.archeive_posts_by_date, name='archeive_date'),
path('tag/<str:tag>/', views.archeive_post... |
# This code is provided by Foroozan Karimzadeh- PhD student at Gatech
# coding: utf-8
# In[155]:
import numpy as np
import json
from sklearn.feature_extraction import text
x = open('fedpapers_split.txt').read()
papers = json.loads(x)
papersH = papers[0] # papers by Hamilton
papersM = papers[1] # papers by Madison
p... |
from .modules import * # noqa: F403
|
#! /usr/bin/env python
from .device_base import Device_Base
class Device_Dimmer(Device_Base):
def __init__(self, container, name, address):
Device_Base.__init__(self,container,'dimmer', name, address)
self.add_property('level',0) #in percent
def set_level(self,level):
pass
|
#!/usr/bin/env python3
"""
Usage:
eval.py [options] SAVE_FOLDER TRAIN_DATA_PATH VALID_DATA_PATH TEST_DATA_PATH
eval.py [options] [SAVE_FOLDER]
*_DATA_PATH arguments may either accept (1) directory filled with .jsonl.gz files that we use as data,
or a (2) plain text file containing a list of such directories (u... |
from .blueprint import GraphQL
from .graphqlview import GraphQLView
__all__ = ['GraphQL', 'GraphQLView']
|
from __future__ import annotations
import dataclasses
import unittest
from datetime import date, datetime
import pydantic
from cl_sii.dte.constants import TipoDte
from cl_sii.dte.data_models import DteDataL1, DteNaturalKey, DteXmlData
from cl_sii.libs import encoding_utils, tz_utils
from cl_sii.rtc.data_models impor... |
import fcntl
class LockedException (Exception):
pass
class flock (object):
__slots__ = [ "file", "shared", "locked", "block" ]
def lock (self, *, shared=None):
shared = self.shared if shared is None else shared
flg = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
fcntl.flock(self.fi... |
from ffov.setters.base import FovSetter
from ffov.setters.nv import NewVegasFovSetter |
import random
numero = random.randint(0,100)
def pedir_numero():
while True:
intento = int (input ("Dime un numero del 1 al 99: "))
if intento < 0 or intento > 99:
break
return intento
print("BIENVENIDO AL JUEGO DE ADIVINAR")
pedir_numero()
contador = 1
while num... |
from urllib.parse import urlencode
from django import http
from django.apps import apps
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.shortcuts import render
from django.template.loader imp... |
#!/usr/bin/python
# coding: utf-8
# Copyright (c) 2016 Mountainstorm
#
# 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
# to use,... |
import datetime
from bx_py_utils.test_utils.datetime import parse_dt
from django.test import SimpleTestCase
from django.utils import translation
from bx_django_utils.templatetags.humanize_time import human_duration
class HumanizeTimeTestCase(SimpleTestCase):
def test_basic(self):
with translation.overri... |
from . import vk
def get_mutual_friends(user_id: int):
friends = vk.get_friends(user_id)
mutual_ids = vk.get_mutual_friends_ids_batch([user.id for user in
friends], user_id)
return friends, mutual_ids
|
from .apmeter import APMeter
from .aucmeter import AUCMeter
from .averagevaluemeter import AverageValueMeter
from .classerrormeter import ClassErrorMeter
from .confusionmeter import ConfusionMeter
from .mapmeter import mAPMeter
from .movingaveragevaluemeter import MovingAverageValueMeter
from .msemeter import MSEMeter
... |
#
# Autogenerated by Thrift Compiler (0.9.2)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style,utf8strings
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinary... |
from numpy import load
from numpy import zeros
from numpy import ones
from numpy.random import randint
from tensorflow.keras import backend as K
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.initializers import RandomNormal
from tensorflow.keras.models import Model
from tensorflow.keras.layers impo... |
from sqlalchemy.sql.expression import func
from hokuto_flask.extensions import db
from ..relationships import character_category_association
class CategoryModel(db.Model):
"""Database model for a category in the Hokuto no Ken universe.
"""
__tablename__ = "categories"
id = db.Column(db.String(32), pr... |
def collapse(nu_fe_sa):
print("Before collapsing: {}".format(nu_fe_sa.shape))
nu_fe_sa = nu_fe_sa.groupby(level=0).median()
print("After: {}".format(nu_fe_sa.shape))
return nu_fe_sa
|
import pickle
import shelve
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen
from kivy.uix.scrollview import ScrollView
class SketchyLoad(Screen):
root = None
def __init__(self, **kwargs):
super(SketchyLoad, self).__init__(**kwargs... |
import setuptools
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setuptools.setup(
name="thompyson",
version="1.0.0",
author="William Angus",
author_email="william@ngus.co.uk",
description="Utility for computations in R J Thompson's groups F and T.",
long_d... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-11-22 01:52
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0003_comment_offset'),
]
operations =... |
from flask_socketio import SocketIO, emit
lastDetection = None
def initSocketIO(app):
global socketio
socketio = SocketIO(app, cors_allowed_origins="*")
return socketio
def getSocketIO():
return socketio
def emitEvent(event, message):
socketio.emit(event, message)
print(event, message)
... |
from neo4j.v1 import GraphDatabase, basic_auth
from .neo4j_wrapper import Neo4jWrapper
from .neo4j_init_wrapper import Neo4jInitWrapper
class WrapperFactory:
@staticmethod
def build_neo4j_wrapper(host, port, username, password):
connect = f'bolt://{host}:{port}'
auth = basic_auth(username, pas... |
from streamer import *
from time import sleep
from helper import *
import os
import re
from threadclient import ThreadClient
from ftplib import error_perm
from zfec import filefec
import random
import urllib2
import csv
import math
import sys
import thread
import string
# Debugging MSG
DEBUGGING_MSG = True
VLC_PLAYER_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
import gym
import random
import logging
import numpy as np
from tqdm import trange
from agents.imt_agent import IMTAgent
from agents.qtable_agent import QAgent
class GoWrapper(gym.ObservationWrapper):
def __init__(self, env=None):
super(GoWrapper, self).__init__(env)
self.observation_space = gym.sp... |
"""xancestry URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
import pytz
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class TimezoneMiddleware(MiddlewareMixin):
tzname = None
def process_request(self, request):
self.tzname = request.session.get('django_timezone')
if self.tzname:
timezone.activate(pyt... |
"""
LeetCode Problem: 1302. Deepest Leaves Sum
Link: https://leetcode.com/problems/deepest-leaves-sum/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
queue = [root]
ans = 0
... |
# Generated by Django 3.1 on 2020-08-25 10:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_set_minimum_datetime_timezone'),
]
operations = [
migrations.RemoveField(
model_name='board',
name='is_ka... |
# Copyright 2020 Xilinx 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 required by applicable law or agreed to in writing, ... |
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 请找出其中最小的元素。
#
# 你可以假设数组中不存在重复元素。
#
# 示例 1:
#
# 输入: [3,4,5,1,2]
# 输出: 1
#
# 示例 2:
#
# 输入: [4,5,6,7,0,1,2]
# 输出: 0
# Related Topics 数组 二分查找
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-04 19:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
# Generated by Django 2.0.7 on 2018-07-14 11:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('road', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='situation',
name='endTime',
... |
"""InVEST Seasonal water yield model tests that use the InVEST sample data"""
import glob
import unittest
import tempfile
import shutil
import os
import numpy
from osgeo import ogr
from natcap.invest.pygeoprocessing_0_3_3.testing import scm
SAMPLE_DATA = os.path.join(
os.path.dirname(__file__), '..'... |
inputfile = open('day-8/day8_input.txt', 'r')
def getDigitsList(inputfile):
digitsList = []
with inputfile as f:
for line in f.readlines():
lineEntry = []
line = line.strip()
pattern, output = line.split(' | ')
pattern = pattern.split()
output... |
from __future__ import unicode_literals
from django.db import models, transaction
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils import timezone
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.core.exceptions import ObjectDoes... |
import numpy as np
import pprint
import sys
import gym.spaces
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.gridworld import GridworldEnv
pp = pprint.PrettyPrinter(indent=2)
env = GridworldEnv()
def value_iteration(env, epsilon=0.0001, discount_factor=1.0):
"""
Value Iteration Algorithm.
... |
from office365.sharepoint.base_entity import BaseEntity
class UserResource(BaseEntity):
"""An object representing user-defined localizable resources."""
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.