content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import torch
import numpy as np
import pandas as pd
from os.path import join
from pathlib import Path
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
class DSet(Dataset):
''' This is the WSJ parser '''
def __init__(self, path, split):
# Setup
self.path = path
... | nilq/baby-python | python |
#!/usr/bin/env python
import astropy.units as u
__all__ = ['toltec_info', ]
toltec_info = {
'instru': 'toltec',
'name': 'TolTEC',
'name_long': 'TolTEC Camera',
'array_physical_diameter': 127.049101 << u.mm,
'fov_diameter': 4. << u.arcmin,
'fg_names': ['fg0', 'fg1', 'fg2', 'fg3'],
'fg0'... | nilq/baby-python | python |
"""\
Examples
For the development.ini you must supply the paster app name:
%(prog)s development.ini --app-name app --init --clear
"""
from pyramid.paster import get_app
import atexit
import logging
import os.path
import select
import shutil
import sys
EPILOG = __doc__
logger = logging.getLogger(__name__)
def... | nilq/baby-python | python |
import logging
import os.path
DEFAULT_LOG_PATH = None
DEFAULT_LOG_DIR = os.path.join(os.path.dirname(__file__), "logs")
if not os.path.exists(DEFAULT_LOG_DIR):
try:
os.mkdir(DEFAULT_LOG_DIR)
except OSError:
DEFAULT_LOG_DIR = None
if DEFAULT_LOG_DIR:
DEFAULT_LOG_PATH = os.path.join(DEFAULT_L... | nilq/baby-python | python |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Hea... | nilq/baby-python | python |
# coding: utf-8
from mhw_armor_edit.ftypes import StructFile, Struct
class WpDatEntry(Struct):
STRUCT_SIZE = 65
id: "<I"
unk1: "<H"
base_model_id: "<H"
part1_id: "<H"
part2_id: "<H"
color: "<B"
tree_id: "<B"
is_fixed_upgrade: "<B"
crafting_cost: "<I"
rarity: "<B"
kire_... | nilq/baby-python | python |
# Generated by Django 3.2.4 on 2021-06-20 12:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth... | nilq/baby-python | python |
from setuptools import setup
from os import path
with open('README.md') as f:
long_description = f.read()
setup(
name='itrcnt',
module='itrcnt.py',
version='0.1.2',
license='BSD',
author='mao2009',
url='https://github.com/mao2009/Python_Counter',
description='Alternative for Range ... | nilq/baby-python | python |
"""
testing for agent's config
"""
import os
import pytest
import yaml
from eha.agent.config import load
@pytest.mark.parametrize('content, envs, result', (
(
"""
foo: 123
bar: 234
""",
{},
{
'foo': 123,
'bar': 234,
}
),
(
"""
foo: 1... | nilq/baby-python | python |
default_app_config = 'kolibri.content.apps.KolibriContentConfig'
| nilq/baby-python | python |
import os
import pandas as pd
def read_parquet(data_path, num_partitions=None, random=False, verbose=True, columns=None):
files = os.listdir(data_path)
if random:
import random
random.shuffle(files)
if num_partitions is None:
num_partitions = len(files)
data = []
n... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
fn_read_keys = None
dn_sstable_keys = None
read_keys = []
key_sstgen = {}
def LoadReadKeys():
global read_keys
print "loading read keys from %s ..." % fn_read_keys
with open(fn_read_keys) as fo:
for line in fo.readlines():
read_keys.append(line.strip().lower())
... | nilq/baby-python | python |
#
# Copyright (c) Sinergise, 2019 -- 2021.
#
# This file belongs to subproject "field-delineation" of project NIVA (www.niva4cap.eu).
# All rights reserved.
#
# file in the root directory of this source tree.
# This source code is licensed under the MIT license found in the LICENSE
#
from typing import Callable, List,... | nilq/baby-python | python |
# Copyright 2016
# Drewan Tech, LLC
# ALL RIGHTS RESERVED
db_user = 'web_service_admin'
db_password = 'web_service_admin'
db_host = 'postgres'
db_port = '5432'
users_to_manage = {'random_matrix':
{'authorized_databases':
['matrix_database'],
'password':
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2014 Arulalan.T <arulalant@gmail.com>
#
# This file is part of 'open-tamil/txt2ipa' package examples
#
import sys
sys.path.append("../..")
from tamil.txt2ipa.ipaconvert import ipa, broad
from tamil.txt2ipa.transliteration import tam2lat
text = "வணக்கம் தமிழகம் "
... | nilq/baby-python | python |
import tkinter as tk
import tkinter.messagebox as msg
import socket
import configparser
import threading
import time
import os
def warning(message):
msg.showwarning("Предупреждение", message)
def error(message, error=None):
msg.showerror("Ошибка", message)
print(error)
class Server(socket.socket):
d... | nilq/baby-python | python |
import pytest
from text_normalizer.tokenization import replace_bigrams
@pytest.mark.benchmark(group='ivr_convert')
def test_benchmark_replace_synonyms(benchmark, tokenize, benchmark_text):
tokens = list(tokenize(benchmark_text))
benchmark(lambda: list(replace_bigrams(tokens)))
| nilq/baby-python | python |
from product import product
from company import company
from pathlib import Path
# Loading products info
products = []
products_list_file = open(str(Path(__file__).resolve().parent) + "/products_list.txt", "r")
for p in products_list_file:
p = p.replace("\n", "")
p = p.split(",")
products.append(product(... | nilq/baby-python | python |
# Title: Trapping Rain Water
# Link: https://leetcode.com/problems/trapping-rain-water/
import sys
from heapq import heappop, heappush
sys.setrecursionlimit(10 ** 6)
class Solution():
def trap(self, heights: list) -> int:
water = 0
walls = []
for i, height in enumerate(heights):
... | nilq/baby-python | python |
from __future__ import unicode_literals
from django.contrib import admin
from authtools.admin import NamedUserAdmin
from .models import Profile, TokenFirebase
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from import_export.admin import ImportExportModelAdmin
from import_... | nilq/baby-python | python |
from decimal import Decimal
from django.apps import apps
from rest_framework import serializers
from rest_flex_fields import FlexFieldsModelSerializer
from ....checkout.utils import get_taxes_for_checkout
from ....glovo.utils import glovo_get_lowest_price
from ....runningbox.utils import runningbox_order_estimate
from... | nilq/baby-python | python |
import requests
import json
import re
class RestApi(object):
# base_url example http://aaa.co.com/webhdfs
def __init__(self, base_url, username, password):
self.name = "nhso core api" + base_url
self.base_url = base_url
self.username = username
self.password = password
... | nilq/baby-python | python |
import threading
import time
import socket
import sys
import copy
import pprint
pp = pprint.PrettyPrinter(indent=2)
# global variables
turn = 1
convergence = 0
round = 1
update_occured = 0
nodes = {
"0" : {"name": "A", "index": 0, "port": 10000, "update": 1},
"1" : {"name": "B", "index": 1, "port": 10001, "up... | nilq/baby-python | python |
#!/usr/bin/env python
"""Setup script for the package."""
import os
import sys
import setuptools
PACKAGE_NAME = 'api'
MINIMUM_PYTHON_VERSION = 3, 6
def check_python_version():
"""Exit when the Python version is too low."""
if sys.version_info < MINIMUM_PYTHON_VERSION:
sys.exit("Python {}.{}+ is r... | nilq/baby-python | python |
# Back compatibility -- use broad subdirectory for new code
from bcbio.broad.metrics import *
| nilq/baby-python | python |
import copy
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
class BlackBoxAttack(object):
MEAN = np.array([0.485, 0.456, 0.406])
STD = np.array([0.229, 0.224, 0.225])
def __init__(self, model, input_size=224, epsilon=16, num_iters=10000,
early_s... | nilq/baby-python | python |
import RPi.GPIO
import sys
import random
sys.path.append("../../")
from gfxlcd.driver.nju6450.gpio import GPIO
from gfxlcd.driver.nju6450.nju6450 import NJU6450
RPi.GPIO.setmode(RPi.GPIO.BCM)
def hole(o, x, y):
o.draw_pixel(x+1, y)
o.draw_pixel(x+2, y)
o.draw_pixel(x+3, y)
o.draw_pixel(x+1, y + 4)
... | nilq/baby-python | python |
from utils.functions import get_env
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': get_env("POSTGRES_HOST", "db"),
'PORT': get_env("POSTGRES_PORT", "5432"),
'NAME': get_env("POSTGRES_DB"),
'USER': get_env("POSTGRES_USER"),
'PASS... | nilq/baby-python | python |
# Copyright 2022 The HuggingFace Team. 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 applicabl... | nilq/baby-python | python |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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... | nilq/baby-python | python |
import tensorflow as tf
class Model:
def __init__(self, image_size = 224, n_classes = 16, fc_size = 1024):
self.n_classes = n_classes
tf.compat.v1.disable_eager_execution()
self.dropout = tf.compat.v1.placeholder(tf.float32, name="dropout_rate")
self.input_images = tf.compat.v1.... | nilq/baby-python | python |
'''
based on the noise model of https://github.com/paninski-lab/yass
'''
import numpy as np
from scipy.spatial.distance import pdist, squareform
import os
import torch
def make_noise(n, spatial_SIG, temporal_SIG):
"""Make noise
Parameters
----------
n: int
Number of noise events to generate
... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
p_guess = [0.5,0.55,0.6,0.7]
repeat_experiment = 30
n = 32
k = 5
plt.title('n = 32, k = 5')
plt.xlabel("Number of CRPs", fontsize=12)
plt.ylabel("Accuracy (x100%)", fontsize=12)
crps = np.load('./xorpuf'+str(k)+'_n'+str(n)+'_reps'+str(repeat_experiment... | nilq/baby-python | python |
# Copyright 2013 NEC 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 ... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
# @yasinkuyu
import sys
import time
import config
from BinanceAPI import *
# trader.py --quantity -- symbol --profit --wait_time
# ex: trader.py 1 IOTABTC 1.3 1
#int(sys.argv[0]) #quantity
#sys.argv[1] #symbol
#sys.argv[2] #percentage of profit
#sys.argv[3] #wait_time
TEST_MODE = False
PRO... | nilq/baby-python | python |
from typing import List, Dict, Optional, Set, Any, Tuple, Type
from Dataset import GraphDataset
from Models.EmbeddingLayers import EmbeddingLayer
from Models.GnnLayers import GCNLayer, GATLayer, HGCNLayer, IHGNNLayer
from Models.PredictionLayers import HemPredictionLayer
from Helpers.Torches import *
from Helpers.Glob... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
# Define a main() function that prints a data statistics.
def main():
data = np.loadtxt('data/populations.txt')
year, hares, lynxes, carrots = data.T # trick: columns to variables
plt.axes([0.1, 0.1, 0.5, 0.8])
plt.plot(year, hares, year, lynxes, ye... | nilq/baby-python | python |
from ..datapack import DataPack
from ..logging import logging
from .data_utils import make_coord_array
import numpy as np
import os
import astropy.time as at
def make_example_datapack(Nd,Nf,Nt,pols=None, time_corr=50.,dir_corr=0.5*np.pi/180.,tec_scale=0.02,tec_noise=1e-3,name='test.hdf5',clobber=False):
logging.in... | nilq/baby-python | python |
#! /usr/bin/env python
# If you ever need to modify example JSON data that is shown in the sampleData.js file, you can use this script to generate it.
import sys
import os
from pathlib import Path
sys.path.append(str(Path(os.path.dirname(__file__)).parent))
import json
from cloudsplaining.shared.validation import check... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# id3v1.py
# From the stagger project: http://code.google.com/p/stagger/
#
# Copyright (c) 2009-2011 Karoly Lorentey <karoly@lorentey.hu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following con... | nilq/baby-python | python |
a = np.arange(30).reshape((2,3,5))
a[a>5] | nilq/baby-python | python |
import os
import sys
from cseg import cut_file
msr_test = 'corpus/msr_test.utf8'
msr_test_gold = 'corpus/msr_test_gold.utf8'
msr_out = ['output/msr_test_2_add1', 'output/msr_test_2_ad', 'output/msr_test_2_kn', 'output/msr_test_1',
'output/msr_test_2_add1_hmm', 'output/msr_test_2_ad_hmm',
'output/... | nilq/baby-python | python |
"""
created by ldolin
"""
"""
正则表达式
动机:
1.经常性文本处理
2.文本内容的快速搜索,定位,提取比较复杂
3.产生正则表达式
定义:
正则即是文本的高级匹配模式,提供搜索,替代,查找等功能,
本质是由一系列特殊符号和字符组成的字符串
特点:
1.方便检索和修改文本内容的操作
2.支持多种编程语言
3.灵活多样
目标:
1.能够看懂并编写基本简单的正则表达式
2.能够使用python操作正则表达式
设... | nilq/baby-python | python |
from datetime import timezone, timedelta, datetime, date, time
import databases
import pytest
import sqlalchemy
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL, force_rollback=True)
metadata = sqlalchemy.MetaData()
class DateFieldsModel(ormar.Model):
class Meta:... | nilq/baby-python | python |
import json
import os
from pathlib import Path
import shutil
from appdirs import user_data_dir
from elpis.engines.common.objects.fsobject import FSObject
from elpis.engines.common.utilities import hasher
from elpis.engines.common.utilities.logger import Logger
from elpis.engines.common.errors import InterfaceError
fro... | nilq/baby-python | python |
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader, sampler
import h5py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from itertools import cycle
import seaborn as sns
from matplotlib.colors import ListedColormap
import matplotlib as mpl
from matplotlib.font_man... | nilq/baby-python | python |
from django import forms
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Ore
class CreateNewOreupdate(forms.ModelForm):
class Meta:
model = Ore
fields = ('oret','... | nilq/baby-python | python |
import pytest
import pandas as pd
from hypper.data import (
read_banking,
read_breast_cancer_data,
read_churn,
read_congressional_voting_records,
read_german_data,
read_hr,
read_phishing,
read_spect_heart,
)
@pytest.mark.parametrize(
"read_fun",
[
read_banking,
... | nilq/baby-python | python |
"""Base camera module
This file contains the class definition for the Camera class on which
all subsequent cameras should be based on.
"""
from __future__ import print_function, division
import numpy.random as npr
from .log import logger
# from .ringbuffer import RingBuffer
from .camprops import CameraProperties
# f... | nilq/baby-python | python |
from .copy import files_copy
from .delete import files_delete
from .download import files_download
from .history import files_history
from .import_files import files_import
from .list import files_list
from .mkdir import files_mkdir
from .move import files_move
from .pems_delete import files_pems_delete
from .pems_list... | nilq/baby-python | python |
import turtle
def draw_piece(row, col, color):
x = offset_x + 25 + col * 2 * (radius + gap)
y = offset_y - 25 - row * 2 * (radius + gap)
t.up()
t.home()
t.goto(x,y)
t.down()
t.color(color)
t.begin_fill()
t.circle(radius)
t.end_fill()
def draw(x, y):
global board, rb, winner
col = int((x - ... | nilq/baby-python | python |
from machine.tokenization import ZwspWordDetokenizer
def test_detokenize_empty() -> None:
detokenizer = ZwspWordDetokenizer()
assert detokenizer.detokenize([]) == ""
def test_detokenize_space() -> None:
detokenizer = ZwspWordDetokenizer()
assert (
detokenizer.detokenize(["គែស", "មាង់", " ", ... | nilq/baby-python | python |
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2017-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.... | nilq/baby-python | python |
#!/bin/python3
# name: vignette_testing.py
# author: nbehrnd@yahoo.com
# license: 2019, MIT
# date: 2019-12-02 (YYYY-MM-DD)
# edit: 2019-12-03 (YYYY-MM-DD)
#
""" Probe for gnuplot palettes' differences
Script 'palette_decomposition.py' provides rapid access to visualize
the channels of R, G, B of RG... | nilq/baby-python | python |
from learnml.metrics import mean_squared_error
import numpy as np
import unittest
class Test(unittest.TestCase):
def test_mean_squared_error(self):
expected_results = [0, 1]
for i, y_pred in enumerate(np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])):
self.assertEqual(expected_results[i],... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
from TM1py.Objects.User import User
from TM1py.Services.ObjectService import ObjectService
class SecurityService(ObjectService):
""" Service to handle Security stuff
"""
def __init__(self, rest):
super().__init__(rest)
def create_user(self, user):
... | nilq/baby-python | python |
from abc import abstractmethod
from typing import Callable, Tuple
import numpy as np
from ._func import Func
class OriFunc(Func):
@abstractmethod
def __call__(self, t: float) -> float:
"""
:param t: Time.
:return: Orientation in degrees.
"""
pass
class Tangential(Or... | nilq/baby-python | python |
a = ["1", 1, "1", 2]
# ex-14: Remove duplicates from list a
a = list(set(a))
print(a)
# ex-15: Create a dictionary that contains the keys a and b and their respec
# tive values 1 and 2 .
my_dict = {"a":1, "b":2}
print(my_dict)
print(type(my_dict))
# Add "c":3 to dictionary
my_dict["c"] = 3
print(my_dict)
my_dict2... | nilq/baby-python | python |
from task_grounding.task_grounding import TaskGrounding, TaskGroundingReturn, TaskErrorType
from database_handler.database_handler import DatabaseHandler
import unittest
from unittest.mock import Mock
from ner_lib.ner import EntityType
from ner_lib.command_builder import Task, TaskType, ObjectEntity, SpatialType, Spati... | nilq/baby-python | python |
# Generated by Django 3.2.5 on 2022-01-24 05:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('metrics', '0002_initial'... | nilq/baby-python | python |
from itertools import count
CARD_PUBLIC_KEY = 14205034
DOOR_PUBLIC_KEY = 18047856
def transform_one_step(value, subject_number):
return (value * subject_number) % 20201227
def transform(loop_size, subject_number=7):
value = 1
for _ in range(loop_size):
value = transform_one_step(value, subject_... | nilq/baby-python | python |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
Sequence,
SubFactory,
post_generation,
)
from accelerator.tests.factories.core_profile_factory import CoreProfileFactory
from accelerator.tests.factories.expert_category_fac... | nilq/baby-python | python |
from typing import Callable, Dict, Tuple, Text
from recommenders.datasets import Dataset
import numpy as np
import tensorflow as tf
import tensorflow_recommenders as tfrs
from pathlib import Path
SAVE_PATH = Path(__file__).resolve().parents[1] / "weights"
class RankingModel(tfrs.models.Model):
def __init__(
... | nilq/baby-python | python |
"""Convert Noorlib library html to OpenITI mARkdown.
This script subclasses the generic MarkdownConverter class
from the html2md module (based on python-markdownify,
https://github.com/matthewwithanm/python-markdownify),
which uses BeautifulSoup to create a flexible converter.
The subclass in this module, NoorlibHtml... | nilq/baby-python | python |
import pytest
from bot.haiku.models import HaikuMetadata
@pytest.fixture()
def haiku_metadata(data_connection):
"""Create a haiku metadata."""
HaikuMetadata.client = data_connection
return HaikuMetadata
| nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import os
import re
import sys
from itertools import product
import h5py
import numpy as np
if __name__ == "__main__":
ORIG_WIDTH = 512
ORIG_NUM_PARAMS = 4
parser = argparse.ArgumentParser()
parser.add_argument("hdf5_files", nargs="*",
h... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : EINDEX Li
@File : __init__.py.py
@Created : 26/12/2017
"""
from aiospider.tools.singleton import OnlySingleton
class AIOSpider(metaclass=OnlySingleton):
def __init__(self, loop=None):
self.config = dict()
self.loop ... | nilq/baby-python | python |
# @author: Michael Vorotyntsev
# @email: linkofwise@gmail.com
# @github: unaxfromsibiria
import logging
import string
from enum import Enum
from hashlib import sha256, md5
from random import SystemRandom
_cr_methods = {
'sha256': sha256,
'md5': md5,
}
class ServiceGroup(Enum):
service = 1
server = 2... | nilq/baby-python | python |
from decimal import *
N = int(input())
print(int(int((N-1)*N)/2))
| nilq/baby-python | python |
# -*- coding: utf-8 eval: (yapf-mode 1) -*-
#
# January 13 2019, Christian E. Hopps <chopps@labn.net>
#
# Copyright (c) 2019, LabN Consulting, L.L.C.
# 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 ob... | nilq/baby-python | python |
from pyrete.settings import settings
from . import (
get_attr_name,
ParserLiterals,
)
class DataLayer(object):
"""
The DataLayer is responsible for fetching data from the database.
It parses the provided rules and fetches only the data required for running the rules.
Example:
.. code-bl... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Raven-django
============
Raven-Django is a Raven extension that provides full out-of-the-box support
for `Django <https://www.djangoproject.com>`_ framework.
Raven itself is a Python client for `Sentry <http://www.getsentry.com/>`_.
"""
# Hack to prevent stupid "TypeError: 'NoneType' object... | nilq/baby-python | python |
from typing import List
import allure
from markupsafe import Markup
from overhave.entities import OverhaveDescriptionManagerSettings
class DescriptionManager:
""" Class for test-suit custom description management and setting to Allure report. """
def __init__(self, settings: OverhaveDescriptionManagerSetti... | nilq/baby-python | python |
# Copyright 2021 The Pigweed 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | nilq/baby-python | python |
from django.apps import AppConfig
class ExternalLinksConfig(AppConfig):
name = 'wagtail_external_menu_items'
| nilq/baby-python | python |
# Standard
import logging
# Third Party
import six
import pygame as pg
from pytmx.util_pygame import load_pygame
from pytmx import TiledImageLayer, TiledTileLayer
# Project
from harren.utils import color
LOG = logging.getLogger(__name__)
class Renderer(object):
"""This object renders tile maps from Tiled."""
... | nilq/baby-python | python |
from discord.ext import commands
import discord, typing, random
import utils
from discord.ext.commands.cooldowns import BucketType
import collections, itertools
class Test(commands.Cog):
"""A cog to have people test new commands, or wip ones"""
def __init__(self, bot):
self.bot = bot
@commands.command()
a... | nilq/baby-python | python |
"""Built-in reducer function."""
# pylint: disable=redefined-builtin
from __future__ import absolute_import
import sys
from .base import BuiltinFunction, TargetCode
from ..runtime import ir
from ..runtime.ir import var
class ReduceFunction(BuiltinFunction):
"""Base builtin reduce function class."""
def _in... | nilq/baby-python | python |
### packages
import os
import numpy as np
import torch
import pickle as pkl
from copy import deepcopy
### sys relative to root dir
import sys
from os.path import dirname, realpath
sys.path.append(dirname(dirname(realpath(__file__))))
### absolute imports wrt root
from problems.problem_definition import ProblemDefinit... | nilq/baby-python | python |
import config
from metaL import *
app = App('metaL')
app['host'] = Ip(config.HOST)
app['port'] = Port(config.PORT)
app.eval(glob)
| nilq/baby-python | python |
#!/usr/bin/env python
"""This module is for running the measurement process multiple times.
Requires the use of batch_table.csv"""
__author__ = "Camellia Magness"
__email__ = "cmagness@stsci.edu"
import sys
import glob
import logging
import pandas as pd
from tqdm import tqdm
from astropy import constants
from . im... | nilq/baby-python | python |
from flask import Flask
app = Flask(__name__)
from flask import render_template, url_for, send_file
import pkg_resources
logo = None
integration_data = None
packagename = None
@app.route('/')
def index():
global logo, integration_data, packagename
return render_template('index.html', name=packagename, logo=logo, ... | nilq/baby-python | python |
import pymongo
import nltk
from nltk.stem.porter import *
from nltk.corpus import stopwords
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer,TfidfTransformer
from itertools import islice
from sklearn import preprocessing
import numpy as np
import pandas as pa
... | nilq/baby-python | python |
# Code from - https://github.com/Cartucho/mAP
import glob
import json
import os
import shutil
import operator
import sys
import argparse
import math
import matplotlib.pyplot as plt
import numpy as np
def log_average_miss_rate(prec, rec, num_images):
"""
log-average miss rate:
Calculated by ... | nilq/baby-python | python |
import ujson as json
def read_json_file(file_name: str) -> None:
try:
fp = open(file_name, 'r')
config = json.load(fp)
fp.close()
print(json.dumps(config))
except Exception as e:
print(f'exception: {e}')
read_json_file('C:\\Users\\s\\Desktop\\config.txt... | nilq/baby-python | python |
# Copyright (c) 2012-2013 SHIFT.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 without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, dist... | nilq/baby-python | python |
"""Tests for accounts.views."""
# pylint: disable=no-value-for-parameter,maybe-no-member,invalid-name
from datetime import datetime
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.ur... | nilq/baby-python | python |
def fetch_base_view(context, next):
base_blocks = [
{
"type": "input",
"block_id": "block_packages",
"element": {
"type": "plain_text_input",
"action_id": "package_input",
"placeholder": {
"type": "plain_... | nilq/baby-python | python |
#!/usr/bin/env python
from fireworks import LaunchPad, Firework, Workflow, PyTask
import glob
launchpad = LaunchPad(
host = 'localhost',
port = 27017, # REPLACE
authsource = 'admin',
name = 'fireworks',
password = None,
ssl = False,
username = None
)
for inp in glob.glob('eda*.inp'):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE!
# This file has been autogenerated by dephell <3
# https://github.com/dephell/dephell
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
readme = ''
here = os.path.abspath(os.path.dirname(__file__))
readme_... | nilq/baby-python | python |
from .paths import get_backup_path, get_resources_path
from .logging import initialize_logging
| nilq/baby-python | python |
from collections import defaultdict
import numpy as np
from yt.funcs import mylog
from yt.utilities.exceptions import YTDomainOverflow
from yt.utilities.io_handler import BaseIOHandler
from yt.utilities.lib.geometry_utils import compute_morton
from yt.utilities.on_demand_imports import _h5py as h5py
class IOHandler... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-11 08:42
from __future__ import unicode_literals
import django.contrib.postgres.fields
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('laptimes', '0007_auto_2018... | nilq/baby-python | python |
import numpy as np
import imageio
infile = 'rawtext'
outfile = 'map_{:03d}{}_{}.png'
#
# 0 land
# 1 water
# 2 deepwater
# 3 void
#
colors = [
np.array([206, 169, 52], dtype = np.uint8),
np.array([0, 40, 220], dtype = np.uint8),
np.array([0, 20, 140], dtype = np.uint... | nilq/baby-python | python |
import os
import subprocess
import torchaudio
from glob import glob
from torch import Tensor
from typing import Any, Tuple, Optional
from clmr.datasets import Dataset
class AUDIO(Dataset):
"""Create a Dataset for any folder of audio files.
Args:
root (str): Path to the directory where the dataset is... | nilq/baby-python | python |
# Copyright 2013-2020 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 import *
class Microbiomeutil(MakefilePackage, SourceforgePackage):
"""Microbiome analysis utilities"""
... | nilq/baby-python | python |
n = int(input())
num_list = list(int(num) for num in input().strip().split())[:n]
for i in range(len(num_list) - 1):
if num_list[i] > 0 and num_list[i + 1] > 0 or num_list[i] < 0 and num_list[i + 1] < 0:
print("YES")
exit()
print("NO")
| nilq/baby-python | python |
import pytest
from mockito import mock, unstub, when
from SeleniumLibrary.keywords import ElementKeywords
@pytest.fixture(scope='function')
def element():
ctx = mock()
ctx._browser = mock()
return ElementKeywords(ctx)
def teardown_function():
unstub()
def test_locator_should_match_x_times(element... | nilq/baby-python | python |
from django.apps import AppConfig as DjangoAppConfig
from django.utils.translation import gettext_lazy as _
class AppConfig(DjangoAppConfig):
name = 'account'
verbose_name = _('Bank account management')
| nilq/baby-python | python |
import bpy
from dotbimpy import File
from collections import defaultdict
def convert_dotbim_mesh_to_blender(dotbim_mesh, mesh_id):
vertices = [
(dotbim_mesh.coordinates[counter], dotbim_mesh.coordinates[counter + 1], dotbim_mesh.coordinates[counter + 2])
for counter in range(0, len(dotbim_mesh.coo... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.