content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import ops
import ops.cmd
import ops.env
import ops.cmd.safetychecks
VALID_OPTIONS = ['all', 'permanent', 'cached']
class PasswordDumpCommand(ops.cmd.DszCommand, ):
def __init__(self, plugin='passworddump', **optdict):
ops.cmd.DszCommand.__init__(self, plugin, **optdict)
def validateInput(self):
... | nilq/baby-python | python |
"""An App Template based on Bootstrap with a header, sidebar and main section"""
import pathlib
import awesome_panel.express as pnx
import panel as pn
from awesome_panel.express.assets import SCROLLBAR_PANEL_EXPRESS_CSS
BOOTSTRAP_DASHBOARD_CSS = pathlib.Path(__file__).parent / "bootstrap_dashboard.css"
BOOTST... | nilq/baby-python | python |
import codecs
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import itertools
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
prefix="",
cmap=None,
... | nilq/baby-python | python |
class DataFilePath:
def __init__(self):
self.dataDir = '../data/citydata/season_1/'
return
def getOrderDir_Train(self):
return self.dataDir + 'training_data/order_data/'
def getOrderDir_Test1(self):
return self.dataDir + 'test_set_1/order_data/'
def getTest1Dir(self)... | nilq/baby-python | python |
from __future__ import print_function
import argparse
import logging
import os
import warnings
import torch.nn as nn
import torch.utils.data
from torch.utils.data import SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from Colorization import utils
from Multi_label_classification.dataset.datase... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import Http404
from django.views.generic.edit import UpdateView
from django.views.generic import ListView, View
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator... | nilq/baby-python | python |
from src.traces.traces import main as traces_main
import pandas as pd
def main():
db_path = '/Users/mossad/personal_projects/AL-public/src/crawler/crawled_kaggle.db'
traces_path = '/Users/mossad/personal_projects/AL-public/src/traces/extracted-traces.pkl'
clean_traces_path = '/Users/mossad/personal_project... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
# Copyright 2012-2017 Luc Saffre
#
# License: BSD (see file COPYING for details)
"""Defines the :class:`Page` model.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext_lazy
from django.utils.translation import... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from annotator import annotation
from annotator import document
from h._compat import text_type
class Annotation(annotation.Annotation):
@property
def uri(self):
"""Return this annotation's URI or an empty string.
The uri is es... | nilq/baby-python | python |
import os
import string
from file2quiz import utils, reader
def convert_quiz(input_dir, output_dir, file_format, save_files=False, *args, **kwargs):
print(f'##############################################################')
print(f'### QUIZ CONVERTER')
print(f'##############################################... | nilq/baby-python | python |
# Copyright (c) 2021 by xfangfang. All Rights Reserved.
#
# Using potplayer as DLNA media renderer
#
# Macast Metadata
# <macast.title>PotPlayer Renderer</macast.title>
# <macast.renderer>PotplayerRenderer</macast.title>
# <macast.platform>win32</macast.title>
# <macast.version>0.4</macast.version>
# <macast.host_versi... | nilq/baby-python | python |
import numpy as np
from metod_alg import objective_functions as mt_obj
from metod_alg import metod_algorithm_functions as mt_alg
def test_1():
"""
Test for mt_alg.forward_tracking() - check that when flag=True,
track is updated.
"""
np.random.seed(90)
f = mt_obj.several_quad_function
g = ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
import os
import sys
from .main import main as main_main
from .. import CondaError
from .._vendor.auxlib.i... | nilq/baby-python | python |
with open('input') as fp:
grid = [line[:-1] for line in fp]
grid_width = len(grid[-1])
x, y = (0, 0)
n_trees = 0
while y < len(grid):
if grid[y][x % grid_width] == '#':
n_trees += 1
x += 3
y += 1
print(n_trees, "trees")
| nilq/baby-python | python |
from __future__ import absolute_import
import sys, os
from subprocess import Popen, PIPE, check_output
import socket
from ..seqToolManager import seqToolManager, FeatureComputerException
from .windowHHblits import WindowHHblits
from utils import myMakeDir, tryToRemove #utils is at the root of the package
class HHBlit... | nilq/baby-python | python |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# edge cases - if the element is present at start or last
if not head:
... | nilq/baby-python | python |
# Export individual functions
# Copy
from .scopy import scopy
from .dcopy import dcopy
from .ccopy import ccopy
from .zcopy import zcopy
# Swap
from .sswap import sswap
from .dswap import dswap
from .cswap import cswap
from .zswap import zswap
# Scaling
from .sscal import sscal
from .dscal import dscal
from .cscal i... | nilq/baby-python | python |
import torch
import trtorch
precision = 'fp16'
ssd_model = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_ssd', model_math=precision)
input_shapes = [1, 3, 300, 300]
model = ssd_model.eval().cuda()
scripted_model = torch.jit.script(model)
compile_settings = {
"input_shapes": [input_shapes],
"... | nilq/baby-python | python |
# Main file for the PwnedCheck distribution.
# This file retrieves the password, calls the module check_pwd,
# and check if the password has been breached by checking it with
# the database in the following website
# https://haveibeenpwned.com/Passwords
import sys
import logging
from getpass import getpass
from checkp... | nilq/baby-python | python |
"""
================================
Symbolic Aggregate approXimation
================================
Binning continuous data into intervals can be seen as an approximation that
reduces noise and captures the trend of a time series. The Symbolic Aggregate
approXimation (SAX) algorithm bins continuous time series into... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-10 01:54
from __future__ import unicode_literals
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cxp_v1', '0001_initial'),
]
operations = [
m... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pytest
from click.testing import CliRunner
from jak.app import main as jak
import jak.crypto_services as cs
@pytest.fixture
def runner():
return CliRunner()
def test_empty(runner):
result = runner.invoke(jak)
assert result.exit_code == 0
assert not result.exception
... | nilq/baby-python | python |
try:
import matplotlib.pyplot as plt
import fuzzycorr.prepro as pp
from pathlib import Path
import numpy as np
import gdal
except:
print('ModuleNotFoundError: Missing fundamental packages (required: pathlib, numpy, gdal).')
cur_dir = Path.cwd()
Path(cur_dir / "rasters").mkdir(exist_ok=True)
... | nilq/baby-python | python |
"""Support for Vallox ventilation units."""
from __future__ import annotations
from dataclasses import dataclass, field
import ipaddress
import logging
from typing import Any, NamedTuple
from uuid import UUID
from vallox_websocket_api import PROFILE as VALLOX_PROFILE, Vallox
from vallox_websocket_api.exceptions impor... | 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 |
import numpy as np # type: ignore
import pandas as pd # type: ignore
# imported ML models from scikit-learn
from sklearn.model_selection import (ShuffleSplit, StratifiedShuffleSplit, # type: ignore
TimeSeriesSplit, cross_val_score) # type: ignore
from sklearn.discriminant_anal... | nilq/baby-python | python |
#!/usr/bin/env python
__author__ = 'Florian Hase'
#=======================================================================
from DatabaseHandler.PickleWriters.db_writer import DB_Writer
| nilq/baby-python | python |
#
# @lc app=leetcode id=383 lang=python
#
# [383] Ransom Note
#
# https://leetcode.com/problems/ransom-note/description/
#
# algorithms
# Easy (49.29%)
# Total Accepted: 107.4K
# Total Submissions: 216.8K
# Testcase Example: '"a"\n"b"'
#
#
# Given an arbitrary ransom note string and another string containing lette... | nilq/baby-python | python |
"""
Guidelines from whitehouse.gov/openingamerica/
SYMPTOMS:
- Downward Trajectory of Flu-like illnesses
AND
- Downward Trajectory of Covid symptoms 14 day period
CASES:
- Downward Trajectory of documented cases within 14 day period
OR
- Downward Trajectory of positive tests within 14 days
... | nilq/baby-python | python |
from pymodm import connect, MongoModel, fields
from pymodm.base.fields import MongoBaseField
import pymongo
from datetime import datetime as dt
db_server = "mongodb+srv://AtlasUser:8dNHh2kXNijBjNuQ@cluster0.a532e"
db_server += ".mongodb.net/ECGServer?retryWrites=true&w=majority"
mongodb_server = connect(db_server)
... | nilq/baby-python | python |
from django.urls import path
from account.views import (
index, profile,
LOGIN, LOGOUT, REGISTER,
activate, change_password, update_profile, change_profile_pic
)
from account.api import (
check_username_existing, get_users
)
app_name = 'account'
urlpatterns = [
# API URLs
path('api/check_usern... | nilq/baby-python | python |
import msgpack_numpy
import os
import torch
from collections import defaultdict
from typing import List
import lmdb
import magnum as mn
import numpy as np
from torch.utils.data import Dataset
from tqdm import tqdm
import habitat
from habitat import logger
from habitat.datasets.utils import VocabDict
from habitat.task... | nilq/baby-python | python |
from visualization import plot_binary_grid # used to show results
from wrapper import multi_image # import segmenter for multiple images
if __name__ == "__main__":
# Apply segmenter to default test images.
print("Classifying images...")
masks = multi_image() # uses default test image
print("Complete... | nilq/baby-python | python |
# from sqlalchemy package we can import Column, String, Integer, Date, Sequence
from sqlalchemy import Column, String, Integer, Date, Sequence
# imports Config class from config module
from config import Config
#exception handling using try except for FeatureRequestAppClass.
try:
# A class FeatureRequestApp will be... | nilq/baby-python | python |
from typing import List
import config
import datetime
from email.mime.text import MIMEText
from html.parser import HTMLParser
import email.utils as utils
import logging
import queue
import re
import sys
import threading
from time import strftime
import socket
import feedparser
import yaml
from imap_wrapper import Im... | nilq/baby-python | python |
from flask.views import MethodView
class APIView(MethodView):
api_version = None
path = None
@classmethod
def get_path(self):
if self.path:
return self.path
elif self.__name__.endswith('View'):
return self.__name__[:-4].lower()
else:
return ... | nilq/baby-python | python |
'''
- Application Factory
'''
from app import create_app
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pytest import fixture
@fixture
def client():
'''Cliente do FastAPI.'''
app = create_app()
return TestClient(app)
def test_create_app(client):
assert isinstance(create_a... | nilq/baby-python | python |
"""A module for evaluating policies."""
import os
import json
import pandas as pd
import matplotlib.pyplot as plt
from tf_agents.environments.tf_py_environment import TFPyEnvironment
from lake_monster.environment.environment import LakeMonsterEnvironment
from lake_monster.environment.variations import MultiMonsterEnvi... | nilq/baby-python | python |
import numpy as np
from numpy import exp,dot,full,cos,sin,real,imag,power,pi,log,sqrt,roll,linspace,arange,transpose,pad,complex128 as c128, float32 as f32, float64 as f64
from numba import njit,jit,complex128 as nbc128, void
import os
os.environ['NUMEXPR_MAX_THREADS'] = '16'
os.environ['NUMEXPR_NUM_THREADS'] = ... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2014 Spotify AB.
#
# 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 Ap... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from maro.backends.frame import FrameBase, FrameNode
from .port import Port
from .vessel import gen_vessel_definition
from .matrix import gen_matrix
def gen_ecr_frame(port_num: int, vessel_num: int, stop_nums: tuple, snapshots_num: int):
"""... | nilq/baby-python | python |
"""Provide functionality to handle package settings."""
import logging
from enum import Enum
from os import makedirs
from os.path import isdir
from urllib.error import URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from dynaconf import Validator, settings
LOGGER = logging.getLo... | nilq/baby-python | python |
# Copyright 2017 The Sonnet 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 applicable l... | nilq/baby-python | python |
#!/usr/bin/env python
"""
(C) 2007-2019 1024jp
"""
import pickle
import cv2
import numpy as np
import matplotlib.pyplot as plt
_flags = (cv2.CALIB_ZERO_TANGENT_DIST |
cv2.CALIB_FIX_K3
)
class Undistorter:
def __init__(self, camera_matrix, dist_coeffs, rvecs, tvecs, image_size,
... | nilq/baby-python | python |
#!/usr/bin/env python
names = ["Amy", "Bob", "Cathy", "David", "Eric"]
for x in names:
print("Hello " + x)
| nilq/baby-python | python |
# coding: utf-8
from __future__ import unicode_literals
import pytest
from django.contrib.auth.models import AnonymousUser
from mock import Mock
from saleor.cart import decorators
from saleor.cart.models import Cart
from saleor.checkout.core import Checkout
from saleor.discount.models import Voucher
from saleor.produ... | nilq/baby-python | python |
#!/usr/bin/env python
from re import sub
from sys import argv,exit
from os import path,getenv
from glob import glob
import argparse
parser = argparse.ArgumentParser(description='make forest')
parser.add_argument('--region',metavar='region',type=str,default=None)
toProcess = parser.parse_args().region
argv=[]
import RO... | nilq/baby-python | python |
from tensorflow.keras import initializers
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
def build_subnet(output_filters, bias_initializer='zeros', name=None):
"""构建功能子网络.
Args:
output_filters: int,
功能子网络输出层的神经元数量.
bias_initializer: str or tf.ke... | nilq/baby-python | python |
from .seld import * | nilq/baby-python | python |
import numpy as np
class UnionFind:
def __init__(self, n):
self.n = n
self.parent = np.arange(n)
self.rank = np.zeros(n, dtype=np.int32)
self.csize = np.ones(n, dtype=np.int32)
def find(self, u):
v = u
while u != self.parent[u]:
u = self.parent[u]
... | nilq/baby-python | python |
import logging.config
from .Camera import Camera
import time
from io import BytesIO
from PIL import Image
from dateutil import zoneinfo
timezone = zoneinfo.get_zonefile_instance().get("Australia/Canberra")
try:
logging.config.fileConfig("/etc/eyepi/logging.ini")
except:
pass
try:
import picamera
imp... | nilq/baby-python | python |
# 建立一个登录页面
from tkinter import *
root = Tk()
root.title("登陆页面")
msg = "欢迎进入海绵宝宝系统"
sseGif = PhotoImage(file="../img/hmbb1.gif")
logo = Label(root,image=sseGif,text=msg, compound=BOTTOM)
logo.grid(row=0,column=0,columnspan=2,padx=10,pady=10)
accountL = Label(root,text="Account")
accountL.grid(row=1)
pwdL = Label(r... | nilq/baby-python | python |
from setuptools import setup
setup(
name='YinPortfolioManagement',
author='Yiqiao Yin',
version='1.0.0',
description="This package uses Long Short-Term Memory (LSTM) to forecast a stock price that user enters.",
packages=['YinCapital_forecast']
)
| nilq/baby-python | python |
import analysis
#Create historgram
analysis.histogram()
#Create scatterplot
analysis.scatterplot("sepal_length","sepal_width")
analysis.scatterplot("petal_length","petal_width")
analysis.pair_plot()
#Create summary.txt
analysis.writeToAFile
| nilq/baby-python | python |
import os
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('cron', hour=9)
def scheduled_job():
os.system("python manage.py runbot")
sched.start() | nilq/baby-python | python |
from django.db import models
from i18nfield.fields import I18nCharField
from pretalx.common.mixins import LogMixin
from pretalx.common.urls import EventUrls
class Track(LogMixin, models.Model):
event = models.ForeignKey(
to='event.Event', on_delete=models.PROTECT, related_name='tracks'
)
name = I... | nilq/baby-python | python |
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy import Column, Integer, String, Boolean, BigInteger, Text, ForeignKey, Float
from sqlalchemy.orm import relationship
#from sqlalchemy_views import CreateView, DropView
# connection.execute("CREATE TABLE `jobs` (`clock` BIGINT(11),`j... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import os
import sys
import time
import caffe
import numpy as np
from timer import Timer
from db_helper import DBHelper
import matplotlib.pyplot as plt
from caffe.proto import caffe_pb2
from google.protobuf import text_format
# Load LabelMap file.
def get_labelmap(labelmap_path):
labelmap... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
Script to delete files that are also present on Wikimedia Commons.
Do not run this script on Wikimedia Commons itself. It works based on
a given array of templates defined below.
Files are downloaded and compared. If the files match, it can be deleted on
the source wiki... | nilq/baby-python | python |
#@+leo-ver=5-thin
#@+node:ville.20110403115003.10348: * @file valuespace.py
#@+<< docstring >>
#@+node:ville.20110403115003.10349: ** << docstring >>
'''Supports Leo scripting using per-Leo-outline namespaces.
Commands
========
.. note::
The first four commands are a light weight option for python calculations
... | nilq/baby-python | python |
#Let's do some experiments to understand why to use numpy and what we can do with it.
#import numpy with alias np
import numpy as np
import sys
# one dimensional array
a=np.array([1,2,3])
print(a)
# two dimensional array
a= np.array([(1,2,3),(4,5,6)])
print(a)
#why numpy better than list..
#1)Less memory
#2)faste2... | nilq/baby-python | python |
if '__file__' in globals():
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import numpy as np
from dezero import Variable
import dezero.functions as F
# im2col
x1 = np.random.rand(1, 3, 7, 7)
col1 = F.im2col(x1, kernel_size=5, stride=1, pad=0, to_matrix=True)
print(col1.shape) ... | nilq/baby-python | python |
import sys
import os
from os.path import join as opj
workspace = os.environ["WORKSPACE"]
sys.path.append(
opj(workspace, 'code/GeDML/src')
)
import argparse
import logging
logging.getLogger().setLevel(logging.INFO)
import torch.distributed as dist
from gedml.launcher.runners.distributed_runner import Distributed... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class Company(models.Model):
_inherit = 'res.company'
hr_presence_control_email_amount = fields.Integer(string="# emails to send")
hr_presence_control_ip_list = fields.Char(... | nilq/baby-python | python |
#!/usr/bin/env python
"""
_ConfigureState_
Populate the states tables with all known states, and set the max retries for
each state. Default to one retry.
Create the CouchDB and associated views if needed.
"""
from WMCore.Database.CMSCouch import CouchServer
from WMCore.DataStructs.WMObject import WMObject
class ... | nilq/baby-python | python |
import numpy as np
from numba import float32, jit
from numba.np.ufunc import Vectorize
from numba.core.errors import TypingError
from ..support import TestCase
import unittest
dtype = np.float32
a = np.arange(80, dtype=dtype).reshape(8, 10)
b = a.copy()
c = a.copy(order='F')
d = np.arange(16 * 20, dtype=dtype).resha... | nilq/baby-python | python |
import json
import numpy as np
def pack(request):
data = request.get_json()
furniture = data['furniture']
orientations = []
'''
Test TEST TTEESSTT
'''
##################################################################
####### Preliminary Functions
##############... | nilq/baby-python | python |
#!/usr/bin/env python3
# Dependencies: python3-pandas python3-plotly
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.colors
df = pd.read_csv(".perf-out/all.csv")
fig = make_subplots(
rows=2, cols=2,
horizontal_spacing = 0.1,
vertical_spacing ... | nilq/baby-python | python |
import json, re, pymongo, os
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem
from unidecode import unidecode
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from datetime import date, datetime
from scrapy import settings
format="%d/%m/%Y"
class NoticiasPipeline:... | nilq/baby-python | python |
from math import *
from scipy.integrate import quad
from scipy.integrate import dblquad
from scipy import integrate
from scipy import special
from numpy import median
from numpy import linspace
from copy import deepcopy
from scipy.stats import fisk
"Defining the parameters for the tests"
alpha = 0.05
delta = 0.002
k ... | nilq/baby-python | python |
from rest_framework import permissions
class AnonymousPermission(permissions.BasePermission):
"""
Non Anonymous Users.
"""
message = "You are already registered. Please logout and try again."
def has_permission(self, request, view):
print(not request.user.is_authenticated)
return n... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
from operator import itemgetter
from copy import deepcopy
from pydruid.utils import aggregators
from pydruid.utils import filters
class TestAggregators:
def test_aggregators(self):
aggs = [('longsum', 'longSum'), ('doublesum', 'doubleSum'),
('min', 'min'), ('max'... | nilq/baby-python | python |
import os
from django.templatetags.static import static
from django.utils.html import format_html
from django.utils.module_loading import import_string
from wagtail.core import hooks
from wagtail_icons.settings import BASE_PATH, SETS
@hooks.register("insert_global_admin_css")
def global_admin_css():
stylesheets... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Author: Ting'''
import logging
import traceback
from argparse import ArgumentParser
from datetime import date
from pprint import pprint
from subprocess import call
import re
from collections import defaultdict
from os.path import join, abspath, dirname, isfile
import csv... | nilq/baby-python | python |
#
# wcsmod -- module wrapper for WCS calculations.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
We are fortunate to have several possible choices for a python WCS package
compatible with Ginga: astlib, kapteyn, starlink and astropy.
kapteyn and astr... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# Configure logging
#
import logging
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--debug", action="store_true", help="Show debugging output.")
args = parser.parse_args()
log_level = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(level=log_level, ... | nilq/baby-python | python |
from multiprocessing import Manager, Process
def to_add(d, k, v):
d[k] = v
if __name__ == "__main__":
process_dict = Manager().dict()
p1 = Process(target=to_add, args=(process_dict, 'name', 'li'))
p2 = Process(target=to_add, args=(process_dict, 'age', 13))
p1.start()
p2.start()
p1.join(... | nilq/baby-python | python |
''' Create words from an existing wordlist '''
import random
import re
class WordBuilder(object):
''' uses an existing corpus to create new phonemically consistent words '''
def __init__(self, initial='>', terminal='<', chunk_size=2):
#indicators for start and ends of words - set if necessary to avoid... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun May 01 20:28:46 2016
@author: Anna
Directory structure: assumes galaxy directory is the working directory, input_data/ should contain pars, phot and fake files
This code generates a CMD plot in the same directory where the program, CMDscript.py, is
Use optional -phot, -f... | nilq/baby-python | python |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2013,2014 Contributor
#
# 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... | nilq/baby-python | python |
"""Request handler base classes
"""
from decorator import decorator
from pyramid.httpexceptions import HTTPForbidden
from dd_app.django_codec import DjangoSessionCodec
from dd_app.messaging.mixins import MsgMixin
class DDHandler(object):
"""Base view handler object
"""
def __init__(self, request, *args,... | nilq/baby-python | python |
"""Module with view functions that serve each uri."""
from datetime import datetime
from learning_journal.models.mymodel import Journal
from learning_journal.security import is_authenticated
from pyramid.httpexceptions import HTTPFound, HTTPNotFound
from pyramid.security import NO_PERMISSION_REQUIRED, forget, remem... | nilq/baby-python | python |
import os
import torch
import pickle
import numpy as np
from transformers import RobertaConfig, RobertaModel, RobertaTokenizer
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
roberta = RobertaModel.from_pretrained('roberta-base')
path = '../wikidata5m_alias'
if not os.path.exists('../wikidata5m_alias_emb... | nilq/baby-python | python |
from array import array
import numpy as np
import os
import cv2
import argparse
from tensorflow import lite as tflite
from matplotlib import pyplot as plt
import time
import torch
from torchvision import transforms
from omegaconf import OmegaConf
import torch.nn.functional as F
import tensorflow as tf
from torch.opti... | nilq/baby-python | python |
import os
# Bot Setup
os.environ["prefix"] = "g!"
os.environ["token"] = "NzM5Mjc0NjkxMDg4MjIwMzEw.XyYFNQ.Mb6wJSHhpj9LP5bqO2Hb0w8NBQM"
os.environ["botlog"] = "603894328212848651"
os.environ["debugEnabled"] = "False"
# Database Setup
os.environ["db_type"] = "MySQL" # Either MySQL or Flat (or just leave empty for Flat ... | nilq/baby-python | python |
###
# Adapted from Avalanche LvisDataset
# https://github.com/ContinualAI/avalanche/tree/detection/avalanche/benchmarks/datasets/lvis
#
# Released under the MIT license, see:
# https://github.com/ContinualAI/avalanche/blob/master/LICENSE
###
from pathlib import Path
from typing import List, Sequence, Union
from PIL i... | nilq/baby-python | python |
import os
import cv2
import numpy as np
from constants import DATA_DIR
MYPY = False
if MYPY:
from typing import Tuple, Union
Pair = Tuple[int, int]
def scale(image, scale_percent):
height, width = image.shape[:2]
return cv2.resize(image, (int(width * scale_percent), int(height * scale_percent)))
... | nilq/baby-python | python |
from django.contrib import admin
# Register your models here.
from .models import SiteConfiguration, SingleOrder, Order, UniqueFeature, Size, Color
admin.site.register(Size)
admin.site.register(Color)
admin.site.register(SiteConfiguration)
admin.site.register(UniqueFeature) | nilq/baby-python | python |
import pygame
from pygame import draw
from .player import Player, Enemy
from .utils import Director, TileSet
class lvl1(Director):
def __init__(self) -> None:
super().__init__(self)
self.tile = TileSet("assets/tileset.png", 10, 28)
self.tile.gen_map(self.alto, self.ancho, 52)
self... | nilq/baby-python | python |
from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('titles', TitleViewSet, basename='titles')
router.register('categories', CategoryViewSet, basename='categories')
router.register('genres', GenreViewSet, basena... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-09 10:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_prices.models
class Migration(migrations.Migration):
dependencies = [
('order', '0016_order_language_co... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
##
# @file goldman_equation.py
# @brief Contain a function that calculates the equilibrium potential using the Goldman equation
# @author Gabriel H Riqueti
# @email gabrielhriqueti@gmail.com
# @date 22/04/2021
#
from biomedical_signal_processing import FARADAYS_CONSTANT as F
from biom... | nilq/baby-python | python |
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | nilq/baby-python | python |
''' Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.
Example:
Input: str = “0100110101”
Outp... | nilq/baby-python | python |
from Cocoa import *
gNumDaysInMonth = ( 0, 31, 28, 31, 30, 21, 30, 31, 31, 30, 31, 30, 31 )
def isLeap(year):
return (((year % 4) == 0 and ((year % 100) != 0)) or (year % 400) == 0)
class CalendarMatrix (NSMatrix):
lastMonthButton = objc.IBOutlet()
monthName = objc.IBOutlet()
nextMonthButton = objc.I... | nilq/baby-python | python |
import warnings
from collections import OrderedDict
from ConfigSpace import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter
from mindware.components.feature_engineering.transformations import _bal_balancer, _preprocessor, _rescaler, \
_image_preprocessor, _text_preprocessor, _b... | nilq/baby-python | python |
# Copyright 2020 by Christophe Lambin
# All rights reserved.
import logging
from prometheus_client import start_http_server
from libpimon.version import version
from libpimon.configuration import print_configuration
from libpimon.cpu import CPUTempProbe, CPUFreqProbe
from libpimon.gpio import GPIOProbe
from libpimon.o... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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-... | nilq/baby-python | python |
# reference: https://github.com/open-mmlab/mmclassification/tree/master/mmcls/models/backbones
# modified from mmclassification timm_backbone.py
try:
import timm
except ImportError:
timm = None
from mmcv.cnn.bricks.registry import NORM_LAYERS
from openmixup.utils import get_root_logger
from ..builder import B... | nilq/baby-python | python |
import torch
import os
import pickle
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class TrainUtil():
def __init__(self, checkpoint_path='checkpoints', version='mcts_nas_net_v1'):
self.checkpoint_path = checkpoint_path
self.version = versio... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.