content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
Immutable config schema objects.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import namedtuple
from enum import Enum
MASTER_NAMESPACE = "MASTER"
CLEANUP_ACTION_NAME = 'cleanup'
def config_object_factory(name, required=None, optional=None):
"""
Cr... | nilq/baby-python | python |
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2011 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.... | nilq/baby-python | python |
from functools import wraps
from logzero import logger
from driver_singleton import DriverSingleton
def requires_url(required_url):
def inner_function(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
if DriverSingleton.get_driver().current_url != required_url:
... | nilq/baby-python | python |
from django.utils import six
from debug_toolbar_multilang.pseudo import STR_FORMAT_PATTERN, \
STR_FORMAT_NAMED_PATTERN
from debug_toolbar_multilang.pseudo.pseudo_language import PseudoLanguage
class ExpanderPseudoLanguage(PseudoLanguage):
"""
Pseudo Language for expanding the strings. This is useful
f... | nilq/baby-python | python |
# Jak znaleźć najkrótsze ścieżki z wierzchołka s do wszystkich innych w acyklicznym grafie skierowanym?
from math import inf
def dfs(graph, source, visited, result):
visited[source] = True
for v in graph[source]:
if not visited[v[0]]:
dfs(graph, v[0], visited, result)
result.insert(0, ... | nilq/baby-python | python |
import unittest
from unittest.mock import patch
from tmc import points, reflect
from tmc.utils import load, load_module, reload_module, get_stdout, check_source, sanitize
from functools import reduce
import os
import os.path
import textwrap
from random import choice, randint
from datetime import date, datetime, timede... | nilq/baby-python | python |
from typing import Dict
import base64
import json
import logging
import os
from shlex import quote as shq
from gear.cloud_config import get_global_config
from ....batch_configuration import DOCKER_ROOT_IMAGE, DOCKER_PREFIX, DEFAULT_NAMESPACE, INTERNAL_GATEWAY_IP
from ....file_store import FileStore
from ....instance_... | nilq/baby-python | python |
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class NoaAccount(ProviderAccount):
"""Noa Account"""
pass
class NoaProvider(OAuth2Provider):
"""Provider for Noa"""
id = 'noa'
name = 'Noa'
account_cl... | nilq/baby-python | python |
import nltk
grammar = nltk.data.load('file:agree_adjunct.fcfg',cache=False)
parser = nltk.parse.FeatureChartParser(grammar)
agreement_test_sentences = ['Often John left','John left often',
'John often left',
'Because John left Mary cried',
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Time : 2019-12-20
# @Author : mizxc
# @Email : xiangxianjiao@163.com
from flask_mongoengine import MongoEngine
from flask_login import LoginManager
db = MongoEngine()
loginManager = LoginManager()
| nilq/baby-python | python |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
stack = []
while ro... | nilq/baby-python | python |
"""
A DataNodeServer which serves APEX weather from disk. Based on the original
example, which served modified APEX weather files.
"""
import glob
import os
import six
import time
import numpy as np
from os import environ
from autobahn.wamp.types import ComponentConfig
from autobahn.twisted.wamp import ApplicationSe... | nilq/baby-python | python |
def add(x,y):
return x + y
#print add(3,4)
print reduce(add, [1,3,5,7,9,11])
def fn(x,y):
return x*10 + y
print reduce(fn, [1,3,5,7,9])
| nilq/baby-python | python |
'''
Created by auto_sdk on 2014.11.15
'''
from aliyun.api.base import RestApi
class Slb20130221CreateLoadBalancerHTTPListenerRequest(RestApi):
def __init__(self,domain='slb.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.backendServerPort = None
self.cookie = None
self.cookieTimeout =... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 15:43:09 2017
@author: juherask
"""
import os
DEBUG_VERBOSITY = 3
COST_EPSILON = 1e-10
CAPACITY_EPSILON = 1e-10
# how many seconds we give to a MIP solver
MAX_MIP_SOLVER_RUNTIME = 60*10 # 10m
MIP_SOLVER_THREADS = 1 # 0 is automatic (parallel computing)
# venv doe... | nilq/baby-python | python |
"""
This program handle incomming OSC messages to MIDI
"""
import argparse
import random
import time
import json
import sqlite3
import mido
from pythonosc import dispatcher
from pythonosc import osc_server
from pythonosc import osc_message_builder
from pythonosc import udp_client
from lib.midiHelper import *
from ... | nilq/baby-python | python |
from builtins import range
from .partition import LabelSpacePartitioningClassifier
import copy
import random
import numpy as np
from scipy import sparse
class RakelD(LabelSpacePartitioningClassifier):
"""Distinct RAndom k-labELsets multi-label classifier."""
def __init__(self, classifier=None, labelset_size=... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import nose
from nose.tools.trivial import eq_
from jpgrep.morpheme import tokenize
from jpgrep.morpheme import StreamDetector
class Test_tokenize(object):
def test(self):
""" 文章が適切に形態素に分解される """
text = u'吾輩は猫である'
expect = [u'吾輩', u'は', u'猫'... | nilq/baby-python | python |
def or_op(ctx, a, b):
if isinstance(b, list):
if a == True:
return True
if a == False:
return []
if isinstance(a, list):
return []
if isinstance(a, list):
if b == True:
return True
return []
return a or b
def and_op(c... | nilq/baby-python | python |
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import json
import os
import chalk
import youtube_dl
import random
import io
import aiohttp
import time
import datetime
from datetime import datetime as dt
import logging
import re
from itertools import c... | nilq/baby-python | python |
import datetime
import os
from django import forms
from django.conf import settings
from decharges.decharge.models import UtilisationTempsDecharge
from decharges.decharge.views.utils import calcul_repartition_temps
from decharges.user_manager.models import Syndicat
class UtilisationTempsDechargeForm(forms.ModelForm... | nilq/baby-python | python |
''' Parser for creating mathematical equations.
'''
import re
from regex_parser import BaseParser
import src.svg as svg
from StringIO import StringIO
matplotlib_included = True
try:
import matplotlib
matplotlib.use('SVG')
from matplotlib import pyplot
except:
matplotlib_included = False
def registe... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import time
import json
import random
import logging
import collections
import configparser
import requests
logging.basicConfig(stream=sys.stderr, format='%(asctime)s [%(name)s:%(levelname)s] %(message)s', level=logging.DEBUG if sys.argv[-1] == '-v'... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 the HERA Collaboration
# Licensed under the 2-clause BSD license.
import numpy as np
from astropy.time import Time
from pyuvdata import UVData
from hera_mc import mc
a = mc.get_mc_argument_parser()
a.description = """Read the obsid from a... | nilq/baby-python | python |
#!/usr/bin/env python
'''
Lucas-Kanade tracker
====================
Lucas-Kanade sparse optical flow demo. Uses goodFeaturesToTrack
for track initialization and back-tracking for match verification
between frames using webcam
Usage
-----
flow_rotation.py
Keys
----
r - reset accumulated rotation
ESC - exit
'''
impo... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nilq/baby-python | python |
from hcipy import *
import numpy as np
def check_energy_conservation(shift_input, scale, shift_output, q, fov, dims):
grid = make_uniform_grid(dims, 1).shifted(shift_input).scaled(scale)
f_in = Field(np.random.randn(grid.size), grid)
#f_in = Field(np.exp(-30 * grid.as_('polar').r**2), grid)
fft = FastFourierTrans... | nilq/baby-python | python |
# coding=utf-8
# Copyright 2018 StrTrek Team Authors.
#
# 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 ... | nilq/baby-python | python |
#-------------------------------------------------------------------------------
# Name: Spatial Parser Helper functions
# Purpose: A suite of functions which are used by the SpatialParser
# class.
#
# Author: Ashwath Sampath
# Based on: http://mentalmodels.princeton.edu/programs/space-6.li... | nilq/baby-python | python |
####################################################################################################
## A simple feed forward network using tensorflow and some of its visualization tools
##Architecture
## 2 hidden layers 1 input and 1 output layers
## input layer : 10 neurons corresponding to season, mnth,holiday,weekd... | nilq/baby-python | python |
import os
class Plugin:
def __init__(self, *args, **kwargs):
self.plugin_name = os.path.basename(__file__)
super()
def execute(self, args):
print('request',self.plugin_name,args)
return {
'contents': f'Hello, {self.plugin_name} '
} | nilq/baby-python | python |
def foo(*a):
if a
pass<caret> | nilq/baby-python | python |
def multiplication(x):
return x * x
def square(fn, arg):
return fn(arg)
print(square(multiplication,5)) | nilq/baby-python | python |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RRcppziggurat(RPackage):
"""'Rcpp' Integration of Different "Ziggurat" Normal RNG ... | nilq/baby-python | python |
# Copyright (c) 2015, MapR Technologies
#
# 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... | nilq/baby-python | python |
#add parent dir to find package. Only needed for source code build, pip install doesn't need it.
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
from bullet.tm700_rgbd_Gym... | nilq/baby-python | python |
from __future__ import absolute_import, print_function
import sys
import json
try:
import rapidjson
fast_json_available = True
except ImportError:
fast_json_available = False
from xml.dom.minidom import parseString as parse_xml_string
try:
from lxml import etree
fast_xml_available = True
except Im... | nilq/baby-python | python |
from twisted.trial.unittest import TestCase
import jasmin.vendor.txredisapi as redis
from twisted.internet import reactor, defer
from jasmin.redis.configs import RedisForJasminConfig
from jasmin.redis.client import ConnectionWithConfiguration
@defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
waitDef... | nilq/baby-python | python |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .models import Book
# Create your views here.
def all_book(request):
all_shit = Book.objects.all()
return render(request, 'bookstore/all_book.html', locals())
def add_book(request):
if request.method == '... | nilq/baby-python | python |
import inpcon_posint as icpi
while True:
#bug: the zero fibonaccinumber is 0
inptext='Which Fibonacci number do you want to see?: '
inp=icpi.inputcontrol(inptext)
if inp==0:
print(0)
print()
print()
continue
erg=[0,1]
for i in range(0,(inp-1),1):
... | nilq/baby-python | python |
import scipy.signal as ss
import matplotlib.pyplot as plt
import numpy as np
from .PluginManager import PluginManager
class HilbertPlugin(PluginManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.hilbert = {}
def hilbert_transform(self, phase_freq=0):
self.hilbert['data'] =... | nilq/baby-python | python |
# Description: Sample Code to Run mypy
# Variables without types
i:int = 200
f:float = 2.34
str = "Hello"
# A function without type annotations
def greet(name:str)-> str:
return str + " " + name
if __name__ == '__main__':
greet("Dilbert")
| nilq/baby-python | python |
# This is library template. Do NOT import this, it won't do anything.
# Libraries are loaded with __import__, and thus, the script is ran on load. Be careful what you write here.
| nilq/baby-python | python |
version = "2.4.5"
default_app_config = "jazzmin.apps.JazzminConfig"
| nilq/baby-python | python |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1093/A
t = int(input())
for _ in range(t):
n = int(input())
print(n//2)
| nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
from shutil import rmtree
from librosa.feature import mfcc
import numpy as np
from tensorflow.io import gfile
import uuid
from constants import *
def read_dir():
if... | nilq/baby-python | python |
import os.path
import yaml
from pathlib import Path
CONFIG_DIRECTORY = str(Path.home()) + "/.tino"
CONFIG_FILENAME = CONFIG_DIRECTORY + "/conf.yml"
class TinoConfig:
def __init__(self):
if not os.path.exists(CONFIG_DIRECTORY):
os.makedirs(CONFIG_DIRECTORY)
if os.path.exists(CONFIG... | nilq/baby-python | python |
"""
Parameter-Based Methods Module
"""
from ._regular import RegularTransferLR, RegularTransferLC, RegularTransferNN
from ._finetuning import FineTuning
from ._transfer_tree import TransferTreeClassifier
from ._transfer_tree import TransferForestClassifier
__all__ = ["RegularTransferLR",
"RegularTransferLC... | nilq/baby-python | python |
"""
abuse.ch Palevo C&C feed RSS bot.
Maintainer: Lari Huttunen <mit-code@huttu.net>
"""
import urlparse
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class PalevoCcBot(AbuseCHFeedBot):
feed_malware = "palevo"
feed_type = "c&c"
feeds = bot.ListParam(defau... | nilq/baby-python | python |
import unittest
import logging
# se desabilita el sistema de logs del API
logging.disable(logging.CRITICAL)
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
root_response = '''<html>
<head>
<title>Guane Inter FastAPI</title>
</head>
<body>
<h1... | nilq/baby-python | python |
"""Represents a realm in World of Warcraft."""
from __future__ import annotations
__LICENSE__ = """
Copyright 2019 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
https://www.apach... | nilq/baby-python | python |
# Copyright (c) 2018 - 2020 Institute for High Voltage Technology and Institute for High Voltage Equipment and Grids, Digitalization and Power Economics
# RWTH Aachen University
# Contact: Thomas Offergeld (t.offergeld@iaew.rwth-aachen.de)
# #
# This module is part of CIMPyORM.
# #
# CIMPyORM is licensed un... | nilq/baby-python | python |
import json
import sewer
class ExmpleDnsProvider(sewer.dns_providers.common.BaseDns):
def __init__(self):
self.dns_provider_name = 'example_dns_provider'
def create_dns_record(self, domain_name, base64_of_acme_keyauthorization):
pass
def delete_dns_record(self, domain_name, base64_of_a... | nilq/baby-python | python |
r"""
Backrefs for the 'regex' module.
Add the ability to use the following backrefs with re:
* \Q and \Q...\E - Escape/quote chars (search)
* \c and \C...\E - Uppercase char or chars (replace)
* \l and \L...\E - Lowercase char or chars (replace)
Compiling
=========
pattern = compile_search(r'somepattern'... | nilq/baby-python | python |
# Classes for rsinc module
import subprocess
import os
from time import sleep
THESAME, UPDATED, DELETED, CREATED = tuple(range(4))
NOMOVE, MOVED, CLONE, NOTHERE = tuple(range(4, 8))
class File:
def __init__(self, name, uid, time, state, moved, is_clone, synced, ignore):
self.name = name
self.ui... | nilq/baby-python | python |
import json
import csv
import argparse
import http.client
import base64
fieldnames = ("TenantID","First Name","Last Name","Extension","Voice DID","Fax DID","Caller ID","ID for MS Exchange","Home Phone","Cell Phone","Fax Number",
"E-mail","Alternate E-mail","User Name","Password","PIN","Pseudonym","User... | nilq/baby-python | python |
import os
from itertools import product
import re
from numpy import append, array, bincount, diff, ma, sort #cumsum, nditer, roll, setdiff1d, where
from numpy import product as np_prod
seating_re = re.compile('[L\.]')
workPath = os.path.expanduser("~/Documents/Code/Advent_of_code/2020")
os.chdir(workPath)
#with open... | nilq/baby-python | python |
import re
import unittest
from rexlex import Lexer
from rexlex.lexer.itemclass import get_itemclass
class TestableLexer(Lexer):
"""Test tuple state transitions including #pop."""
LOGLEVEL = None
re_skip = re.compile('\s+')
tokendefs = {
'root': [
('Root', 'a', 'bar'),
... | nilq/baby-python | python |
from unityagents import UnityEnvironment
from utils import dqn, get_env_spec
from dqn_agents import Agent
import os
import argparse
EXPS_ROOT_PATH = './data'
parser=argparse.ArgumentParser(description="train a RL agent in Unity Banana Navigation Environment")
parser.add_argument('-n', '--name', type=str, metavar='', ... | nilq/baby-python | python |
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name='todoapp'
urlpatterns = [
path('',views.home, name='home'),
path('index',views.lhome, name='lhome'),
# Delete Paths
path('<int:todo_id>/delete', views.delete, name='delete'),
path('<in... | nilq/baby-python | python |
#!/usr/bin/env python3
# Transpose chroma matrix by nTransp semitones up (right rotation) where nTransp is 1st argument.
# If two additional arguments are present, those are input and output file paths, respectively.
# Otherwise, read/write on STDIN
import sys, csv
if __name__ == '__main__':
ntransp = (int(sys.argv[... | nilq/baby-python | python |
from collections import defaultdict
import networkx as nx
import numpy as np
import hashlib
from .solver_utils import root_finder, get_edge_length
def find_split(
nodes,
priors=None,
considered=set(),
fuzzy=False,
probabilistic=False,
minimum_allele_rep=1.0,
):
# Tracks frequency of stat... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
def DrawPlotOnPage(N, CanvasSize_W, CanvasSize_H, Lval, Tval, Wval, Hval, solNo):
#print("plotter called")
fig, ax = plt.subplots()
rectangles = []
for x in range(N):
myRect = mpatch.Rectangle((Lval[x], Tval[x]), Wval[x], Hv... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# This utility will generate the swift code from the c Fit SDK
# You can download the Fit SDK from https://developer.garmin.com/fit and update your local copy using the diffsdk.py script
#
# in the python directory run ./fitsdkparser.py generate Profile.xlsx
#
#
import re
import argp... | nilq/baby-python | python |
from __future__ import absolute_import, unicode_literals
import base64
import cgi
import contextlib
import datetime
import decimal
import json
import time
from mock import Mock, patch
import pytest
import six
from six.moves import range, urllib
import mixpanel
class LogConsumer(object):
def __init__(self):
... | nilq/baby-python | python |
_architecture_template = r'''#!/usr/bin/env bash
EXPERIMENT_NAME="$(basename $(realpath $(pwd)/..))"
SETUP_ID="$(basename $(pwd))"
NAME="${EXPERIMENT_NAME}.${SETUP_ID}-mknet"
USER_ID=${UID}
docker rm -f $NAME
#rm snapshots/*
echo "Starting as user ${USER_ID}"
CONTAINER='%(container)s'
nvidia-docker run --rm \
-u... | nilq/baby-python | python |
import pathlib
from pw_manager.utils import constants, utils
from colorama import Fore, Style
def require_valid_db(enter_confirmation=False):
def decorator(func):
def inner(*args, **kwargs):
if constants.db_file is None:
print(f"{Fore.RED}You need to select a database first!{... | nilq/baby-python | python |
import os
import numpy as np
import logging
from app_globals import *
from alad_support import *
from r_support import matrix, cbind
from forest_aad_detector import *
from forest_aad_support import prepare_forest_aad_debug_args
from results_support import write_sequential_results_to_csv
from data_stream import *
""... | nilq/baby-python | python |
import requests
class AppClient:
def __init__(self, endpoint: str = 'http://localhost:5000'):
self._endpoint = endpoint
def get_index(self):
return requests.get(self._endpoint).text
| nilq/baby-python | python |
import rng
import socket
import pytest
@pytest.fixture
def index_test():
return rng.index()
def test_index_content(index_test):
hostname = socket.gethostname()
assert "RNG running on {}\n".format(hostname) in index_test
def test_rng_status():
statuscode = rng.rng(32).status_code
assert statusc... | nilq/baby-python | python |
from PyCA.Core import *
import PyCA.Common as common
import PyCA.Display as display
import numpy as np
import matplotlib.pyplot as plt
def PrimalDualTV(I0, \
DataFidC, \
TVC = 1.0, \
nIters = 5000, \
stepP = None, \
stepI = None, \
... | nilq/baby-python | python |
# Jan28Report on General Accureacy #####################################################################################
# date = 'Jan-23-2020-22-N-noneSpark-R0-noOpt'
# notes = 'noneSpark-R0-noOpt'
# date = 'Jan-23-2020-21-N-UseSpark-R0-noOpt'
# notes = 'UseSpark-R0-noOpt'
# date = 'Jan-24-2020-2-N-UseSpark-R1-noOpt'
... | nilq/baby-python | python |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def sum(x, y):
if not 0 <= x <= 100:
raise ValueError('arg x must be between 0 and 100')
if not 0 <= x <= 100:
raise ValueError('arg y must be between 0 and 100')
return x + y
| nilq/baby-python | python |
"""
Fabric tools for managing users
"""
from __future__ import with_statement
from fabric.api import *
def exists(name):
"""
Check if user exists
"""
with settings(hide('running', 'stdout', 'warnings'), warn_only=True):
return sudo('getent passwd %(name)s' % locals()).succeeded
def create(n... | nilq/baby-python | python |
#!/usr/bin/python
# coding: utf8
from __future__ import print_function
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
from enum import Enum
from collections import MutableSequence
from collections import namedtuple
from collections import OrderedDict
from itertools impor... | nilq/baby-python | python |
'''
Code Challenge: Solve the Eulerian Cycle Problem.
Input: The adjacency list of an Eulerian directed graph.
Output: An Eulerian cycle in this graph.
'''
import random
import copy
with open('test1.txt','r') as f:
#with open('dataset_203_2.txt','r') as f:
adjacency_list = dict()
eulerian_edge_len ... | nilq/baby-python | python |
"""Comic Rereading Discord Bot"""
from .rereadbot import *
async def setup(bot):
"""Setup the DoA Cogs"""
bot.add_cog(DoaRereadCog(bot, envfile="./.env"))
| nilq/baby-python | python |
from datetime import datetime, timezone
import requests
from schemas import Contest
from spider.utils import update_platform
def main():
headers = {"x-requested-with": "XMLHttpRequest"}
resp = requests.get("https://csacademy.com/contests/", headers=headers)
json_data = resp.json()
data = []
tz... | nilq/baby-python | python |
#
# This source code is licensed under the Apache 2 license found in the
# LICENSE file in the root directory of this source tree.
#
import json
import cPickle as pickle
import numpy as np
import h5py
import random
import pandas as pd
from nltk.tokenize import TweetTokenizer
word_tokenize = TweetTokenizer().tokenize
... | nilq/baby-python | python |
# Generated by Django 2.1.11 on 2019-11-18 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("course_catalog", "0052_userlistitem_contenttypes")]
operations = [
migrations.CreateModel(
name="Playlist",... | nilq/baby-python | python |
"""Helpers to integrate the process on controlling profiles."""
from dataclasses import dataclass
from typing import List, Set, Optional
from bson import ObjectId
from flags import ProfilePermission, PermissionLevel
from mongodb.factory import ProfileManager, ChannelManager
from mongodb.helper import IdentitySearcher... | nilq/baby-python | python |
import uos
import network
import socket
import select
import time
from machine import UART, Pin
ap_mode = False
recvPollers = []
sockets = []
clients = []
def socketSend(message):
for socket in sockets:
try:
socket.sendall(message)
except:
socket.close()
def ge... | nilq/baby-python | python |
from importlib import import_module
def load_extensions(app):
for extension in app.config["EXTENSIONS"]:
module_name, factory = extension.split(":")
ext = import_module(module_name)
getattr(ext, factory)(app)
def load_blueprints(app):
for extension in app.config["BLUEPRINTS"]:
... | nilq/baby-python | python |
#let's work on dictionaries
'''stuff = {'name':'Vivek', 'age':18, 'height':6*2}
print(stuff['name'])
print(stuff['age'])
print(stuff)
'''
'''
state = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California': 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
cities = {
'CA': 'California',
'NY' ... | nilq/baby-python | python |
from dataclasses import dataclass, field
from typing import Optional
from .geometry import Geometry
__NAMESPACE__ = "sdformat/v1.3/collision.xsd"
@dataclass
class Collision:
"""The collision properties of a link.
Note that this can be different from the visual properties of a
link, for example, simpler ... | nilq/baby-python | python |
import trio
from socket import (
inet_aton,
)
import pytest
import pytest_trio
from async_service import background_trio_service
from p2p.discv5.channel_services import (
DatagramReceiver,
DatagramSender,
Endpoint,
IncomingDatagram,
OutgoingDatagram,
OutgoingPacket,
PacketDecoder,
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from dataclasses import dataclass
from dataclasses_io import dataclass_io
from pathlib import Path
_TEST_PATH = Path(__file__).parent
@dataclass_io
@dataclass
class _MyDataclass:
id: int
name: str
memo: str
if __name__ == "__main__":
dataclass1 = _MyDataclass(id=42, name="... | nilq/baby-python | python |
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
#
# 示例:
#
# 输入: s = 7, nums = [2,3,1,2,4,3]
# 输出: 2
# 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。
# 进阶:
#
# 如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
# 著作权归领扣网络所有。商... | nilq/baby-python | python |
"""
Clean and validate a DataFrame column containing country names.
"""
from functools import lru_cache
from operator import itemgetter
from os import path
from typing import Any, Union
import dask
import dask.dataframe as dd
import numpy as np
import pandas as pd
import regex as re
from ..progress_bar import Progres... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-11-15 02:47
from __future__ import unicode_literals
from django.db import migrations, models
import jobs.models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0008_auto_20161115_0222'),
]
operations = [
migra... | nilq/baby-python | python |
from normality import normalize
def text_parts(text):
text = normalize(text, latinize=True)
if text is None:
return set()
return set(text.split(' '))
def index_text(proxy):
texts = set()
for name in proxy.names:
texts.update(text_parts(name))
return ' '.join(texts)
| nilq/baby-python | python |
import torch
import torch.nn as nn
from nn_blocks import *
from torch import optim
import time
class DApredictModel(nn.Module):
def __init__(self, utt_vocab, da_vocab, tod_bert, config):
super(DApredictModel, self).__init__()
if config['DApred']['use_da']:
self.da_encoder = DAEncoder(d... | nilq/baby-python | python |
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime.now(),
'email': ['chris@fregly.com'],
'email_on_failure': False,
'email_on_retry': Fals... | nilq/baby-python | python |
from typing import Any, Tuple, Union
from lf3py.lang.annotation import FunctionAnnotation
from lf3py.routing.errors import UnresolvedArgumentsError
from lf3py.routing.types import Middleware
from lf3py.serialization.deserializer import Deserializer
from lf3py.serialization.errors import DeserializeError
from lf3py.tas... | nilq/baby-python | python |
#!/usr/bin/env python
# coding=utf8
from __future__ import unicode_literals
from datetime import timedelta
import collections
import functools
import os
import re
import string
from io import StringIO
import pytest
from hypothesis import given, settings, HealthCheck, assume
import hypothesis.strategies as st
import ... | nilq/baby-python | python |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
import argparse
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
import numpy
import scipy.stats
import torch
import torch.optim as optim
import jammy_flows
from jamm... | nilq/baby-python | python |
from m5.params import *
from m5.SimObject import SimObject
from Controller import RubyController
class PMMU(RubyController):
type = 'PMMU'
cxx_class = 'PMMU'
cxx_header = "mem/spm/pmmu.hh"
# version = Param.Int("");
page_size_bytes = Param.Int(512,"Size of a SPM page in bytes")
ruby_system = Par... | nilq/baby-python | python |
import requests
import mimetypes
import hashlib
class Tebi:
def __init__(self, bucket, **kwargs):
self.bucket = "https://" + bucket
self.auth = kwargs.get('auth', None)
if (self.auth):
self.auth = "TB-PLAIN " + self.auth
def GetObject(self, key):
headers = {}
... | nilq/baby-python | python |
from __future__ import absolute_import, print_function, unicode_literals
import cwltool.main
import pkg_resources
import signal
import sys
import logging
from cwl_tes.tes import TESWorkflow
from cwl_tes.__init__ import __version__
log = logging.getLogger("tes-backend")
log.setLevel(logging.INFO)
console = logging.S... | nilq/baby-python | python |
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.utils.timezone import now
from rest_framework import generics
from bluebottle.bluebottle_drf2.pagination import BluebottlePagination
from bluebottle.clients import properties
from .models i... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.