content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Write to a text file
#Open the file, write the value and close the file
f = open("output.txt","w")
message="Hi all! Welcome from CEEO Innovations!"
text=f.write(message)
f.close()
| python |
#!/usr/bin/env python3
import argparse
import os
cgroup = '/sys/fs/cgroup'
class Containers(object):
def __init__(self, glob_dir: str = 'devices/lxc') -> None:
self.containers = []
for name in filter(lambda d: os.path.isdir(os.path.join(cgroup, glob_dir, d)),
os.listdi... | python |
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QPaintEngine(__Shiboken.Object):
# no doc
def begin(self, *args, **kwargs): # real signature unknow... | python |
import asyncio
import aioredis
import jinja2
import peewee_async
import aiohttp_jinja2
import aiohttp_debugtoolbar
from aiohttp import web
from aiohttp_session import session_middleware
from aiohttp_session.redis_storage import RedisStorage
import settings
from settings import logger
from helpers.middlewares import... | python |
import os
from elasticsearch import Elasticsearch
from elasticsearch import helpers
class Pes:
def __init__(self):
self.client = Elasticsearch([
{"host": os.getenv("ES_GATEWAY"),
"port": os.getenv("ES_PORT") or 9200}
])
def create_index(self, index_name: str):
... | python |
import csv
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
s... | python |
import requests
from configparser import ConfigParser
import os
import json
import pandas as pd
lat_long_request_url= 'https://cdn-api.co-vin.in/api/v2/appointment/centers/public/findByLatLong?'
class DetailsAssigner:
def __init__(self, *args) -> None:
self.config_obj= args[0]
self.dose_type= 'ava... | python |
from ftis.analyser.descriptor import Chroma
from ftis.analyser.audio import CollapseAudio
from ftis.world import World
from ftis.corpus import Corpus
import argparse
parser = argparse.ArgumentParser(description="Process input and output location")
parser.add_argument(
"-i",
"--input",
default="~/corpus-fo... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2018 Daniel Koguciuk <daniel.koguciuk@gmail.com>
#
# 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 with... | python |
#!/usr/bin/python
import sys
sys.path.insert(0,"/var/www/janus/")
from janus import app as application
| python |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_file", help="file to encode/decode using the provided key")
parser.add_argument("output_file", help="name under which the processed file should be saved")
parser.add_argument("key", help="cryptographic key to process file with")
args =... | python |
# coding: utf-8
from fabkit import filer, sudo, env
from fablib.base import SimpleBase
# from fablib import git
from fablib.python import Python
from oslo_config import cfg
CONF = cfg.CONF
class FabClient(SimpleBase):
def __init__(self):
self.data_key = 'fabkit_tools'
self.data = {
'... | python |
class LinearElasticMaterialModel:
def __init__(self, youngs_modulus, poissons_ratio):
self.young_modulus = youngs_modulus
self.poissons_ratio = poissons_ratio
class LinearElasticPlaneMaterialModel(LinearElasticMaterialModel):
def __init__(self, youngs_modulus, poissons_ratio, thickness):
... | python |
"""
The purpose of this script is to train an AI agent to play the custom-built
Kuiper Escape game using the A2C reinforcement learning algorithm.
"""
# 3rd party imports
import gym
import gym_kuiper_escape
# from code.evaluation import evaluate_policy
from stable_baselines.common.evaluation import evaluate_policy
fr... | python |
from copy import deepcopy
from unyt import dimensions
from mosdef_cassandra.utils.units import validate_unit, validate_unit_list
import parmed
import warnings
import unyt as u
class MoveSet(object):
def __init__(self, ensemble, species_topologies):
"""A class to contain all the move probabilities and rel... | python |
import unittest
import unittest.mock
import uuid
from g1.asyncs import kernels
from g1.asyncs.bases import tasks
from g1.messaging import reqrep
from g1.messaging.reqrep import clients
from g1.messaging.reqrep import servers
from g1.messaging.wiredata import jsons
class InvalidRequestError(Exception):
pass
c... | python |
GET_PACKAGE_ADT_XML='''<?xml version="1.0" encoding="utf-8"?>
<pak:package xmlns:pak="http://www.sap.com/adt/packages" xmlns:adtcore="http://www.sap.com/adt/core" adtcore:masterLanguage="EN" adtcore:name="$IAMTHEKING" adtcore:type="DEVC/K" adtcore:changedAt="2019-01-29T23:00:00Z" adtcore:version="active" adtcore:create... | python |
#
# 13. Roman to Integer
#
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D, M
#
# Symbols Value
#
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
#
# For example, two is written ... | python |
from factory import DjangoModelFactory, Sequence, SubFactory
from movie_planet.movies.models import Comment, Movie
class MovieFactory(DjangoModelFactory):
title = Sequence(lambda n: "Title %03d" % n)
class Meta:
model = Movie
class CommentFactory(DjangoModelFactory):
body = "test body"
mov... | python |
import uuid
import time
import pickle
from redis import Redis
class AcquireTimeoutError(Exception):
"""
在规定时间内,没有获取到到锁时,抛出的异常
"""
class RedisLock:
"""
redis 分布式锁
"""
@classmethod
def register_redis(cls, redis: Redis):
cls.redis = redis
def __init__(self, lock_key, acqui... | python |
from django.db import models
class MyPublicModel(models.Model):
name = models.CharField(max_length=32)
class MyPrivateModel(models.Model):
name = models.CharField(max_length=32)
class MyPresenceModel(models.Model):
name = models.CharField(max_length=32)
| python |
# -*- coding: utf-8 -*-
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
## Linear model of a Boeing 747
# Level flight at 40,000 ft elevation
# Velocity at 774 ft/sec (0.80 Mach)
# States
# u - uw (ft/sec) - horizontal velocity - horizontal wind
# w - ww (ft/sec) - vertical velocity - ... | python |
#! /usr/bin/env python3.7
from modules.commands.helpers.textutil import add as quote_add
HELP_TEXT = ["!addquote <quote>", "Add the selected text for review (broadcasters adding bypass review."]
def call(salty_inst, c_msg, **kwargs):
success, response = quote_add(salty_inst, c_msg, "quote", **kwargs)
return... | python |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import time
import luigi
from servicecatalog_factory import constants
from servicecatalog_factory.workflow.portfolios.get_bucket_task import GetBucketTask
from servicecatalog_factory.workflow.... | python |
"""Delta-v estimation for propulsive landing."""
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import fsolve
# Speed of sound in air at 290 K [units: meter second**-1].
a = 342
# Graviational acceleration [units: meter second**-2].
g_0 = 9.81
# Atmosphere scale height [units: meter].
#... | python |
"""Auto-generated file, do not edit by hand. EG metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_EG = PhoneMetadata(id='EG', country_code=20, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[189]\\d?|[24-6])\\d{8}|[13]\\d{7}', p... | python |
import tensorflow as tf
from tensorflow.contrib.framework.python.ops import arg_scope
#from utils_fn import *
from ops import *
import time
class InpaintModel():
def __init__(self, args):
self.model_name = "InpaintModel" # name for checkpoint
self.img_size = args.IMG_SHAPES
# yj... | python |
import os
#determine n - the number of training observations
nFile = open('CV_folds/training_set_0.txt','r')
n = 0.0
for i in nFile:
n += 1
#determine the number of folds
#nFolds = sum(os.path.isdir(i) for i in os.listdir('CV_decomp'))
nFolds = len(os.listdir('CV_decomp'))
print nFolds
#determine values of p
inL... | python |
import re
import random
import os
import pandas as pd
try:
import torch
except ImportError:
pass
from tqdm import tqdm
import spacy
from spacy import displacy
from visuUtils import train2myVisu, build_color_scheme
from visuUtils import conll2sent_list, sent_list2spacy, myScores
class visualizer(object):
... | python |
from ._text import BufferText
__all__ = [
"BufferText",
]
| python |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
import six
from leather import svg
from leather import theme
class Axis(object):
"""
A horizontal or vertical chart axis.
:param ticks:
Instead of inferring tick values from the data, use exactly this
sequence of ticks values. Th... | python |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class GaussianMixture(nn.Module):
def __init__(self, n_mix, d_inp, learn_var=True, share_prior=False):
super(GaussianMixture, self).__init__()
"""
The current implementation is s... | python |
#!/usr/bin/env python
from iris_sdk.models.base_resource import BaseData
from iris_sdk.models.data.rate_centers_list import RateCentersList
from iris_sdk.models.maps.rate_centers import RateCentersMap
class RateCentersData(RateCentersMap, BaseData):
@property
def total_count(self):
return self.result... | python |
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth.models import User
from rest_framework import viewsets
from usuarios.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lpp_test', '0003_auto_20191024_1701'),
]
operations = [
migrations.AddField(
model_name='uhost',
nam... | python |
import pglet
from pglet import Icon
def test_icon_add():
c = Icon(name="Mail", color="#FF7F50", size="tiny")
assert isinstance(c, pglet.Control)
assert isinstance(c, pglet.Icon)
# raise Exception(s.get_cmd_str())
assert c.get_cmd_str() == (
'icon color="#FF7F50" name="Mail" size="tiny"'
... | python |
# CyberHeist Lab - Beginner Level
# Good luck :D
import hashlib
import binascii
import colorama
import cowsay
USERNAME = "Grubsy"
PASSWORD = "4aa765fdbe4bf83f7a51a1af53b170ad9e2aab35a9b9f0b066fd069952cffe44"
# PASSWORD HINT: Tristan really likes noodles
# In order he likes:
# 1) udonnoodles (not the password)
# 2) *... | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import click
from ..data import EventList
from ..maps import Map
from ..cube import fill_map_counts
log = logging.getLogger(__name__)
@click.command("bin")... | python |
import json
from threading import Lock
from requests.exceptions import HTTPError
from py42.exceptions import Py42ChecksumNotFoundError
from py42.exceptions import Py42Error
from py42.exceptions import Py42HTTPError
from py42.exceptions import Py42SecurityPlanConnectionError
from py42.exceptions import raise_py42_erro... | python |
from trame import state
from trame.html import vuetify, Element, simput
from ..engine.simput import KeyDatabase
def update_cycle_list(*args, **kwargs):
pxm = KeyDatabase().pxm
cycleIds = []
subCycleIds = {}
for cycle in pxm.get_instances_of_type("Cycle"):
cycleIds.append(cycle.id)
subC... | python |
from typing import List
def pascal(N: int) -> List[int]:
"""
Return the Nth row of Pascal triangle
"""
# you code ...
if N == 0:
return []
triangle_rows = []
for i in range(1, N+1):
add_row = [None]*i
add_row[0] = 1
add_row[-1] = 1
... | python |
# Copyright (c) 2021 PaddlePaddle Authors. 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 by ap... | python |
import numpy as np
import pandas as pd
from pandas import DataFrame
from pandas.core.indexes.timedeltas import timedelta_range
import pandas.util.testing as tm
from pandas.util.testing import assert_frame_equal
class TestTimedeltaIndex(object):
def test_asfreq_bug(self):
import datetime as dt
df ... | python |
# -*- coding: utf-8 -*-
import os
import sys
package_path = '/user/specified/path/to/matsdp/'
sys.path.insert(0, os.path.abspath(package_path))
def test_plot_proxigram_csv():
from matsdp.apt import apt_plot
retn_val = apt_plot.plot_proxigram_csv(
proxigram_csv_file_path = './apt/profile-interface0.csv... | python |
import os
import pandas as pd
import nltk
import gensim
from gensim import corpora, models, similarities
os.chdir("D:\semicolon\Deep Learning");
df=pd.read_csv('jokes.csv');
x=df['Question'].values.tolist()
y=df['Answer'].values.tolist()
corpus= x+y
tok_corp= [nltk.word_tokenize(sent.decode('utf-8')) for sent i... | python |
#!/usr/bin/env python
import subprocess
x = list(range(1,9))
print(x)
y = [];
resultf = open('avg', 'a')
for i in x:
i = 2 ** i
print(i)
out_bytes = subprocess.check_output(['../../build/bin/mapreduce_hand', '131072', str(i)])
out_text = out_bytes.decode('ascii')
value = out_text.split('\n')[-2]
value = value.sp... | python |
# coding: utf-8
"""
InfluxDB OSS API Service.
The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa:... | python |
# flake8: noqa
"""
This is the local_settings file for Mezzanine's docs.
"""
from random import choice
from mezzanine.project_template.project_name.settings import *
DEBUG = False
ROOT_URLCONF = "mezzanine.project_template.project_name.urls"
characters = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
# Gener... | python |
import json
import datetime as dt
import dateutil.parser
import backends.entities.Players as Players
import backends.database as db
import backends.trueskillWrapper as ts
## A comment on why the login-offset is nessesary ##
## - losing teams tend to have players leaving and joining more rapidly
## - every time... | python |
from .declare_a_mapping import User, create_table
from .connection import Session
session = Session()
def user_operator():
ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
print(ed_user is our_user)... | python |
import enchant
import re
import itertools
# derived from a google image search of an "old fashioned" phone
letters_from_numbers_lookup = {'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
... | python |
# --depends-on config
# --depends-on format_activity
from src import ModuleManager, utils
from src.Logging import Logger as log
@utils.export("botset", utils.BoolSetting("print-motd", "Set whether I print /motd"))
@utils.export(
"botset",
utils.BoolSetting("pretty-activity", "Whether or not to pretty print a... | python |
import numpy as np
import dask.array as da
from napari.components import ViewerModel
from napari.util import colormaps
base_colormaps = colormaps.CYMRGB
two_colormaps = colormaps.MAGENTA_GREEN
def test_multichannel():
"""Test adding multichannel image."""
viewer = ViewerModel()
np.random.seed(0)
data... | python |
import argparse
import collections
import datetime
import os
import shutil
import time
import dataset
import mlconfig
import toolbox
import torch
import util
import madrys
import numpy as np
from evaluator import Evaluator
from tqdm import tqdm
from trainer import Trainer
mlconfig.register(madrys.MadrysLoss)
# General... | python |
"""
"""
from jax import numpy as jnp
from jax import jit as jjit
@jjit
def _calc_weights(x, x_table):
n_table = x_table.size
lgt_interp = jnp.interp(x, x_table, jnp.arange(0, n_table))
it_lo = jnp.floor(lgt_interp).astype("i4")
it_hi = it_lo + 1
weight_hi = lgt_interp - it_lo
weight_lo = 1 - w... | python |
import os
DEBUG = True
SECRET_KEY = os.getenv("APP_SECRET_KEY")
MYSQL_USERNAME = os.getenv("MYSQL_USERNAME")
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD")
MYSQL_PORT = 3306
MYSQL_DB = os.getenv("MYSQL_DB")
LOGGING_LEVEL = "DEBUG"
LOGGIN_FILE = "activity.log"
LOGGING_BACKUPS = 2
LOGGING_MAXBYTES = 1024
TIMEZONE = "... | python |
#
# PySNMP MIB module HP-ICF-OOBM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-OOBM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:34:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | python |
"""
MARL environment for google football
"""
import numpy as np
import gym
import gfootball.env.football_env as football_env
from gfootball.env import _process_representation_wrappers
from gfootball.env import _process_reward_wrappers
from gfootball.env import config
from gfootball.env import wrappers
class Goog... | python |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""This mo... | python |
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies... | python |
#!/usr/bin/env python
def getinput(): return open('day23.input.txt').read()
### PART 1
import re
def solve(program, a=0, hack=False):
instrs = [l.split() + [''] for l in program.strip().splitlines()]
tgl = { 'cpy': 'jnz', 'inc': 'dec', 'dec': 'inc', 'jnz': 'cpy', 'tgl': 'inc' }
ip, regs = 0, { 'a': a, ... | python |
"""
二维数组
"""
# use numpy
import numpy as np
import pandas as pd
sdarry = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])
# different way to get element
print(sdarry[1, 2])
print(sdarry[:, 2])
print(sdarry[2, :])
# get a row or a column mean of data
# axis=1 is row
# axis=0 is column
print(sdar... | python |
from .confirm import ShutdownConfirmationDialog
def load(manager, params):
"""Launch shutdown confirmation manager"""
pos = (100, 100)
if params and len(params) > 0:
pos = params[0]
ShutdownConfirmationDialog(pos, manager)
| python |
from handlers.chord import ChordHandler
from handlers.base import IndexHandler
url_patterns = [
(r"/index/", IndexHandler),
]
| python |
"""
Pytools
Server module
Run server
>> (base) C:\\Users\\ginanjar\\AppData\\Roaming\\Sublime Text 3\\Packages\\pythontools>python core\\server\\pytools
""" | python |
import unittest
from operator import itemgetter
import tonos_ts4.ts4 as ts4
from utils.wallet import create_wallet, DEFAULT_WALLET_BALANCE
from utils.nft_root import create_nft_root, mint_nft, get_nft_addr, DEFAULT_NFT_ROOT_BALANCE
from utils.nft import restore_nft_by_addr, get_nft_info
from random import randint
un... | python |
__author__ = 'akshay'
import socket
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
# create a socket and bind socket to the host
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('10.42.0.1', 8001))
buffe=1024
def measure():
"""
measure distance
"""
... | python |
"""
Function for matching delimiters in an arithmetic expression
"""
from ArrayStack import *
def is_matched(expr):
"""
Return True if all delimiters are properly match; False otherwise
"""
lefty = '({['
righty = ')}]'
S = ArrayStack()
for c in expr:
if c ... | python |
"""
File: caesar.py
Name: Max Chang
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic ... | python |
from django.db import models
from django.contrib.auth.models import AbstractUser
class StudentUser(AbstractUser):
matric_no = models.CharField(max_length=14, unique=True)
mac_add = models.CharField(max_length=17, unique=True)
| python |
from typing import Any, Dict
import attr
from targets.config import is_in_memory_cache_target_value
@attr.s(frozen=True)
class TargetCacheKey(object):
target = attr.ib(converter=str)
value_type = attr.ib(converter=str)
class TargetCache(object):
def __init__(self, cache=None):
self._cache = ca... | python |
import datetime
from Module.MainThread_Socket_Client import MainThread_Socket_Client
from Module.SocketServer_Client import SocketServer_Client
class Socket_Client_Core():
def __init__(self):
try:
self.MainThread_Socket_Client=MainThread_Socket_Client
self.SocketServer_C... | python |
from tqdm import tqdm
from src.reranker.lambdamart import LambdaMart
from src.interface.corpus import Corpus
from src.interface.iohandler import InputOutputHandler
from src.interface.features import FeatureEngineer
# import src.evaluation.validate_run as validate
OUT = f"./evaluation/fairRuns/submission_lambdamart-fu... | python |
# coding: utf-8
import time
i=0
while(i<20):
print('-----------main--------[',i,']')
i+=1
time.sleep(1)
print("ok man yeaaaaahh!")
#send block --> input IP and message
#message='abcedf'
#IP='127.0.0.1'
#send_len=client.sendto(message.encode('utf-8'),(IP,recieve_port))
#recieve block -->None
#rx_message,... | python |
#main.py
# set up track structure
# this one loops over alpha and epsilon
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
N0 = 2048 # number of cells
nstim = 10 # number of nonplace stimuli
percell= 1.0 # probability that eac... | python |
#Created by Oli MacPherson and Ben O'Sullivan!
#For use with only Python 2 at the moment cause i cant be bothered changing all the raw_inputs.
import sys, os, random
import time
intro_phrases = ["The world is changing. \n",
"Humanity's voracious appetite for and consumption of electricity born of bu... | python |
HW_SOURCE_FILE = __file__
def num_eights(x):
"""Returns the number of times 8 appears as a digit of x.
>>> num_eights(3)
0
>>> num_eights(8)
1
>>> num_eights(88888888)
8
>>> num_eights(2638)
1
>>> num_eights(86380)
2
>>> num_eights(12345)
0
>>> from construct_c... | python |
from cacahuate.auth.base import BaseHierarchyProvider
class BackrefHierarchyProvider(BaseHierarchyProvider):
def find_users(self, **params):
return [
(params.get('identifier'), {
'identifier': params.get('identifier'),
'email': params.get('identifier'),
... | python |
# coding: utf-8
# # Categorical VAE with Gumbel-Softmax
#
# Partial implementation of the paper [Categorical Reparameterization with Gumbel-Softmax](https://arxiv.org/abs/1611.01144)
# A categorical VAE with discrete latent variables. Tensorflow version is 0.10.0.
# # 1. Imports and Helper Functions
# In[1]:
i... | python |
#!/usr/bin/env python3
""" Checks if a new ts3 version is available """
import re
import smtplib
import json
import sys
from email.mime.text import MIMEText
from email import utils
import argparse
import requests
"""
CONFIG = {}
CONFIG['CHANGELOG'] = ''
CONFIG['URL'] = 'https://www.teamspeak.com/versions/server.jso... | python |
import bsddb3
import struct
import json
import flask
import time
from threading import Thread
from Queue import Queue
from StringIO import StringIO
from sqlalchemy import text
from sqlalchemy.sql.elements import TextClause
from table_pb2 import *
from itertools import product, chain, combinations
from dct import *
de... | python |
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
... | python |
def f(<caret>x):
return 42 | python |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_fofin
__commandname__ = "FoFin_init"
def RunCommand(is_interactive):
sc.sticky["FoFin"] = {
'cablenet' : None,
'settings' : {
'scale... | python |
import pytest
from geocodr.keys import APIKeys
from werkzeug.test import EnvironBuilder
from werkzeug.wrappers import Request
@pytest.fixture()
def key_file(tmpdir):
key_file = tmpdir.join("keys.csv")
key_file.write(
'key,domains\n'
'wildcard,\n'
'# comment,with,commas,\n'
'mu... | python |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Header
from humanoid_league_msgs.msg import BallRelative, ObstaclesRelative, ObstacleRelative, Strategy, GameState, RobotControlState
from geometry_msgs.msg import Point, PoseWithCovarianceStamped, Pose2D
import math
import yaml
import rospkg
import os
impo... | python |
import os
import sys
sys.path.append('../')
import numpy as np
import convert_weights
import tensorflow as tf
############## REPRODUCIBILITY ############
tf.set_random_seed(0)
np.random.seed(0)
###########################################
from keras.models import load_model
from keras.models import Sequential, Model
f... | python |
from django.contrib import admin
# DJANGAE
from djangae.contrib.gauth.sql.models import GaeUser
admin.site.register(GaeUser)
| python |
from .handler import handler
| python |
"""OVK learning, unit tests.
The :mod:`sklearn.tests.test_learningrate` tests the different learning rates.
"""
import operalib as ovk
def test_constant():
"""Test whether constant learning rate."""
eta = ovk.Constant(1)
assert eta(10) == 1
def test_invscaling():
"""Test whether inverse scaling le... | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Discovery
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... | python |
# coding: utf-8
from common.db import write_session_scope
from mall_spider.common.enums import TaobaoPageType, TaobaoTaskType
from mall_spider.dao.stream_handle_task_dao import get_stream_handle_task_dao
from mall_spider.dao.stream_opt_data_dao import get_stream_opt_data_dao
from mall_spider.dao.stream_unhandle_task_d... | python |
from qtpy import QtCore, QtGui
class DataTreeModel(QtCore.QAbstractItemModel):
def __init__(self, data_node, parent=None):
super(DataTreeModel, self).__init__(parent)
self.data_node = data_node
self.rootItem = DataTreeItem(self.data_node)
data_node.changed.connect(self.on_node_chan... | python |
import math
style_normal = "\033[0m"
style_great_success = "\033[1;32m"
style_success = "\033[32m"
style_error = "\033[31m"
style_warning = "\033[33m"
style_info = "\033[0m"
style_stealthy = "\033[1;37m"
def __generic_style(c):
def _x(s):
return c + s + style_normal
return _x
success = __generic_style(style... | python |
# pip install feedparser
# pip install notify2
# [Python Desktop News Notifier in 20 lines](http://geeksforgeeks.org/python-desktop-news-notifier-in-20-lines/)
# [Desktop Notifier in Python](https://www.geeksforgeeks.org/desktop-notifier-python/)
import feedparser
import notify2
import os
import time
# https://www.es... | python |
import requests
from sniplink.utils import *
from sniplink.api import API
from sniplink.objects import ShortLinkData
class Client:
"""
The Backend Client
Sniplink-Py is powered by a back-end client/runner, this system is responsible for ensuring safety among API access.
Once you've registered a clien... | python |
class AbilityChangeEvent:
"""Event that indicates an ability change"""
def __init__(self, data, type) -> None:
"""Init event"""
self.data = data
self.type = type
@property
def sphere_id(self) -> str:
return self.data['sphere']['id']
@property
def cloud_id(self)... | python |
from tkinter import messagebox
import pandas as pd
import matplotlib.pyplot as plt
import tkinter as tk
import os
def get_chart_user(date):
if os.path.exists("re/drowsiness_files/"+date+".csv"):
data=pd.read_csv("re/drowsiness_files/"+date+".csv")
data.fillna("Unknown",inplace=True)
gb=data... | python |
"""User memberships in teams."""
import dataclasses
import kaptos.db
import roax.schema as s
from roax.resource import operation
@dataclasses.dataclass
class Member:
"""User membership in team."""
id: s.uuid(description="Identifies the membership.")
team_id: s.uuid(description="Identifies the team.")
... | python |
#
# Copyright (c) 2016, deepsense.io
#
# 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 w... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.