content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import bitmex
import time
import pandas as pd
from keys import ID, SECRET, SLACK_TOKEN
from slackclient import SlackClient
sc = SlackClient(SLACK_TOKEN)
client = bitmex.bitmex(test=False, api_key=ID, api_secret=SECRET)
dfpair = []
def get_volume_data(client):
dfpair.clear()
dfxbt = client.Trade.Trade_getBuc... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
if len(sys.argv) > 1:
infilename = sys.argv[1]
else:
infilename = 'input.txt'
with open(infilename, 'r') as infile:
buf= [line.strip().split() for line in infile]
max_col = max([len(x) for x in buf])
print(max_col)
row_checksums = []
for line in buf:
maximum = 0
minim... | nilq/baby-python | python |
import itertools
from typing import Optional, Sequence
from eth_typing import Address, BlockNumber, Hash32
from eth_utils import is_same_address
from sqlalchemy import orm
from sqlalchemy.orm.exc import NoResultFound
from cthaeh.filter import FilterParams
from cthaeh.loader import get_or_create_topics
from cthaeh.mod... | nilq/baby-python | python |
import yaml
import contextlib
import logging
from teuthology import misc as teuthology
from teuthology.orchestra import run
log = logging.getLogger(__name__)
import os
import pwd
import time
import argparse
"""
# Test yaml to test script mapper for boto3
tests_mapper_v2 = {'test_Mbuckets_basic': 'test_Mbuckets_basic'... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# program068:
# Please write a program using generator to print the even numbers between
# 0 and n in comma separated form while n is input by console.
# Example:
# If the following n is given as input to the program:
# 10
# The... | nilq/baby-python | python |
import numpy as np
from typing import Union, Optional
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.utils.annotations import override
from ray.rllib.utils.exploration.exploration import Exploration, TensorType
from ray.rllib.utils.framework import try_import_tf, try_import_torch, \
get... | nilq/baby-python | python |
version = "2021.11.29.01"
| nilq/baby-python | python |
import logging
from itertools import chain
from pprint import pformat
from future.utils import lmap
from foxylib.tools.collections.collections_tool import merge_dicts, DictTool, lchain
from foxylib.tools.database.elasticsearch.elasticsearch_tool import ElasticsearchTool
from foxylib.tools.json.json_tool import JsonTo... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
from .models import User
# Create your views here.
def help(request):
helpdict = {'help_insert':'HELP PAGE'}
return render(request,'appTwo/help.html',context=helpdict)
def index(request):
return render(request,'appTwo/index.html')
d... | nilq/baby-python | python |
import wx
from wx.adv import CalendarCtrl, GenericCalendarCtrl
from get_file import get_file
from wx import adv
from static.MButton import MButton
class TimeFrame(wx.Frame):
'''类似于日程表, 可以添加事件及其时间段, 到了相应的时间会提醒用户'''
def __init__(self, parent, data=None):
wx.Frame.__init__(self, parent, title='日程表', si... | nilq/baby-python | python |
import argparse
import cv2
# ap = argparse.ArgumentParser()
# ap.add_argument("--i", "--image", required=True, help="path to input image")
# args= vars(ap.parse_args())
# image = cv2.imread(args["image"])
image = cv2.imread("lena.png")
(h, w, c)= image.shape[:3]
#height= no of rows, width= no of columns, channnel= ... | nilq/baby-python | python |
import discord
from discord.ext import commands
from discord.utils import get
class c259(commands.Cog, name="c259"):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name='Abyssal_Awakening', aliases=['c259', 'Abyssal_10'])
async def example_embed(self, ctx):
embed =... | nilq/baby-python | python |
# Imports
from django.db import models
from django.contrib.auth.models import User
# Lead
class Lead(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
message = models.CharField(max_length=500, blank=True)
owner = models.ForeignKey(User, related_name=... | nilq/baby-python | python |
# ckwg +28
# Copyright 2018 by Kitware, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... | nilq/baby-python | python |
# Copyright 2017 The TensorFlow 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 applica... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
r"""Consider the following properties of relation $r$. Because the corruption operations (see `Corruption`_)
are applied independently of triples, the resulting candidate corrupt triples could overlap with known positive
triples in $\mathcal{K}$.
===================== ========================... | nilq/baby-python | python |
import statistics
import os
import jwql.instrument_monitors.miri_monitors.data_trending.utils.mnemonics as mn
import jwql.instrument_monitors.miri_monitors.data_trending.utils.sql_interface as sql
import jwql.instrument_monitors.miri_monitors.data_trending.utils.csv_to_AstropyTable as apt
from jwql.utils.utils imp... | nilq/baby-python | python |
import matplotlib.pyplot as plt
def show(*args, **kws):
"""Show a window with the given plot data. Blocks until window is closed.
Parameters
----------
*args : pyplot args
**kws : pyplot kw
Examples
--------
Plot a line.
>>> bplot.line(x, y)
>>> bplot.show()
"""
plt.show(*args, *... | nilq/baby-python | python |
import matplotlib.pyplot as plt
from keras.preprocessing import image
import warnings
warnings.filterwarnings("ignore")
import time
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
import json
#from basemodels import VGGFace, OpenFace, Facenet, Age, Gender, Race, Emotion
#from extendedmodels impo... | nilq/baby-python | python |
"""Module containing a template class to generate counterfactual explanations.
Subclasses implement interfaces for different ML frameworks such as TensorFlow or PyTorch.
All methods are in dice_ml.explainer_interfaces"""
from abc import ABC, abstractmethod
from collections.abc import Iterable
import numpy as np... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | nilq/baby-python | python |
from setuptools import setup
setup(name='my-package-ahadmushir',
version='0.0.1',
description='Testing installation of Package',
url='https://github.com/ahadmushir/my_first_package',
author='ahadmushir',
author_email='a.ahad.mushir@gmail.com',
license='MIT',
packages=['mypackage'],
zip_safe=False)
| nilq/baby-python | python |
'''
Author : Bhishm Daslaniya [17CE023]
"Make it work, make it right, make it fast."
– Kent Beck
'''
n = int(input("Enter number: "))
print("Factors of "+ str(n) )
for _ in range(1,n):
if(n % _ == 0):
print( _ ,end=" ") | nilq/baby-python | python |
# coding: utf-8
from flask import Blueprint
scope = Blueprint("scope", __name__, url_prefix="/scope/")
| nilq/baby-python | python |
__author__ = 'matth'
import unittest
import sys
from processfamily.test import ParentProcess, Config
import os
import subprocess
import requests
import time
import socket
import logging
import glob
from processfamily.processes import process_exists, kill_process, AccessDeniedError
from processfamily import _traceback_... | nilq/baby-python | python |
import os
import torch
from sklearn.manifold import TSNE
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
def plot_tsne(feat, index, output_dir):
print("feat: global mean = {:.4f}, {:.4f}".format(feat.mean(), feat.std()))
embed = TSNE(n_components=2).fit_tran... | nilq/baby-python | python |
# pylint: skip-file
from yamicache import Cache
c = Cache()
class App1(object):
@c.cached()
def test1(self, argument, power):
"""running test1"""
return argument ** power
@c.clear_cache()
def test2(self):
return 0
def test_clear():
"""Make sure cache gets cleared"""
... | nilq/baby-python | python |
import os
import argparse
import requests
from sanic import Sanic
from sanic.response import json
from osf_pigeon.pigeon import main, sync_metadata, get_id
from concurrent.futures import ThreadPoolExecutor
from sanic.log import logger
from asyncio import events
def run(main):
loop = events.new_event_loop()
tr... | nilq/baby-python | python |
import random
import requests
from bs4 import BeautifulSoup
from colorama import Fore
from colorama import Style
from blagues_api import BlaguesAPI
import asyncio
def faituneblague():
blagues = BlaguesAPI(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMjAwNTQ5NjM1MDY3MDg0ODAwIiwibGltaXQiOjEwMCwia2... | nilq/baby-python | python |
from .weibo_h5 import WeiboH5API as WeiboAPI
from .base import WeiboVisible
| nilq/baby-python | python |
class Cursor:
def __init__(self, wnd):
self.wnd = wnd
self.pos = 0
self.preferred_col = 0
self.preferred_linecol = 0
self.last_screenpos = (-1, -1)
def refresh(self, top=None, middle=None, bottom=None,
align_always=False):
self.pos, y, x = self.w... | nilq/baby-python | python |
import warnings
import numpy as np
import math
def ugly_number(n):
"""
Returns the n'th Ugly number.
Ugly Numbers are numbers whose only prime factors are 2,3 or 5.
Parameters
----------
n : int
represent the position of ugly number
"""
if(n<1):
raise NotImplemente... | nilq/baby-python | python |
"""
ARC's settings
"""
import os
import string
import sys
servers = {
'local': {
'path': '/storage/ce_dana/',
'cluster_soft': 'HTCondor',
'un': '[username]',
'cpus': 8,
'memory': 256,
},
}
# List here servers you'd like to associate with specific ESS.
# An ordered list... | nilq/baby-python | python |
from setuptools import setup, find_packages
setup(
name='PyloXyloto',
version='1.0',
description='PyloXyloto is a simple Deep learning framework built from scratch with python that supports the main '
'functionalities needed for a deep learning project',
py_modules=["activation... | nilq/baby-python | python |
import unittest
from libsaas.executors import test_executor
from libsaas.services import base, twilio
class TwilioTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
self.executor.set_response(b'{}', 200, {})
self.service = twilio.Twilio('my-sid', 'my-token... | nilq/baby-python | python |
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
import os
import pandas
from functions import getbinary
from sklearn.utils import shuffle
class LogisticModel(object):
def __init__(self):
pass
def fit(self,X,Y,X_test,Y_test,lr = 10e-7,reg = 10e-22,epoc... | 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 |
# Copyright 2013 OpenStack Foundation
# 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 requ... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
# Let's import what we need
import os
import sys
import tld
import time
import random
import warnings
import argparse
import threading
from math import log
from re import search, findall
from requests import get, post
try:
impor... | nilq/baby-python | python |
from flask import Flask
from flask_restful import Api
from status import Status
from runner import Runner
app = Flask(__name__)
api = Api(app)
# Routing
api.add_resource(Status, '/')
api.add_resource(Runner, '/analyze')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=3000)
| nilq/baby-python | python |
"""
Main lesscss parse library. Contains lexer and parser, along with
utility classes
"""
| nilq/baby-python | python |
# coding=utf-8
# Marcelo Ambrosio de Goes
# marcelogoes@gmail.com
# 2022-03-07
# 100 Days of Code: The Complete Python Pro Bootcamp for 2022
# Day 20/21 - Snake Game
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self, input_width, input_height):
super().__init__()
self... | nilq/baby-python | python |
from tests.nlg.test_nlg import BaseTestTemplateNLG, BaseTestCamrest
from convlab2.nlg.template.camrest.nlg import TemplateNLG
class TestTemplateCamrest(BaseTestTemplateNLG, BaseTestCamrest):
@classmethod
def setup_class(cls):
BaseTestTemplateNLG.setup_class()
BaseTestCamrest.setup_class()
... | nilq/baby-python | python |
from threading import Thread, Timer
from time import time
import logging
import random
import numpy as np
class Brandbox_temperature_humidity(Thread):
"""This class is reads out continiously the temperature and humidity from the Brandbox
This class inherits all function from the threading class an therefore c... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# laaso/hydrator.py
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
'''
Main program to hydrate the Lustre namespace from blob.
'''
import datetime
import multiprocessing
import os
import pickle
import queue
import stat
import sys
import syslog... | nilq/baby-python | python |
from admin_tabs.tests.metaadminpageconfig import *
| nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import operator
import unittest
import hypothesis
from .util import lattice_dimensions_with_lower_bound
from synth.search import Simple
from synth.search import MinimizedSplit
from synth.search import BinaryPartition
from synth.search import Saddleback
class DummyFunction:
def ... | nilq/baby-python | python |
from vumi.transports.twitter.twitter import (
ConfigTwitterEndpoints, TwitterTransport)
__all__ = ['ConfigTwitterEndpoints', 'TwitterTransport']
| nilq/baby-python | python |
#!/usr/bin/env python
"""A mercurial external differ for notebooks.
Uses nbdime to create diffs for notebooks instead of plain text diffs of JSON.
See the documentation for how to correctly configure mercurial to use this.
Use with:
hg extdiff -p hg-nbdiff [<commit> [<commit>]]
"""
from __future__ import print_... | nilq/baby-python | python |
# imports
import matplotlib.pyplot as plt
import scipy.stats as stats
import numpy as np
import json
import pickle
from urllib.request import urlopen
# helper functions
def bisection(array, value):
'''Given an ``array`` , and given a ``value`` , returns an index j such that ``value`` is between array[j]
a... | nilq/baby-python | python |
# Copyright 2016 Google Inc. 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 law or agreed ... | nilq/baby-python | python |
#!/usr/bin/python3
"""
Consumer
--------
Write a generator that consumes lines of a text and prints them to standard
output. Use this generator and a `flatten` function from the previous task to
print contents of two different files to a screen pseudo-simultaneously.
"""
from course.lesson07.task05.flatten import flat... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 13:55:09 2019
@author: Mrinmoy Bhattacharjee, PhD Scholar, EEE Dept., IIT Guwahati
"""
import os
import numpy as np
import pickle
from sklearn import preprocessing
import json
from sklearn.metrics import confusion_matrix, precision_recall_fscore_... | nilq/baby-python | python |
"""
Incident Updates API Endpoint
"""
# Third Party Library
from django.views import View
from django.urls import reverse
from pyvalitron.form import Form
from django.http import JsonResponse
from django.forms.fields import DateTimeField
from django.utils.translation import gettext as _
# Local Library
from app.modul... | nilq/baby-python | python |
class TreeNode:
def __init__(self, val, left, right):
self.val = val
self.right = right
self.left = left
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
Given two binary trees and imagine t... | nilq/baby-python | python |
from owslib.etree import etree
from owslib.util import Authentication, openURL
from urllib.parse import urlencode, parse_qsl
class WFSCapabilitiesReader(object):
"""Read and parse capabilities document into a lxml.etree infoset
"""
def __init__(self, version="1.0", username=None, password=None, headers=... | nilq/baby-python | python |
import shutil
from django.core.checks import Error, register
@register
def check_binaries(app_configs, **kwargs):
errors = []
if not shutil.which("convert", path="/usr/local/bin:/usr/bin:/bin"):
errors.append(
Error(
'The "convert" binary could not be found',
... | nilq/baby-python | python |
import pytest
from ..traittypes import _DelayedImportError
def test_delayed_access_raises():
dummy = _DelayedImportError('mypackage')
with pytest.raises(RuntimeError):
dummy.asarray([1, 2, 3])
| nilq/baby-python | python |
import os
import time
import pytest
from huntsman.drp.services.plotter import PlotterService
@pytest.fixture(scope="function")
def plotter_service(config, exposure_collection_real_data):
ps = PlotterService(config=config)
yield ps
# Make sure the service is stopped
ps.stop()
# Cleanup the imag... | nilq/baby-python | python |
from nn_recipe.NN import Network
import numpy as np
from nn_recipe.utility import OneHotEncoder
from nn_recipe.DataLoader import MNISTDataLoader
# Loading Data fro mnist Data set
mnist = MNISTDataLoader(rootPath="C:\\Users\\mgtmP\\Desktop\\NNRecipe\\mnist", download=False)
mnist.load()
X_test = mnist.get_test_data().... | nilq/baby-python | python |
import os
import unittest
from conans.model.env_info import DepsEnvInfo
from conans.model.profile import Profile
from conans.model.settings import Settings
from conans.paths import CONANFILE
from conans.test.utils.tools import TestBufferConanOutput, TestClient
from conans.util.files import save
class MockSetting(str... | nilq/baby-python | python |
from abc import ABCMeta, abstractmethod
from argparse import ArgumentParser
from distutils import dir_util
import logging
from pathlib import Path
import platform
import sys
from typing import NoReturn
from hephaistos import backups, config, hashes, helpers, interactive, lua_mod, patchers, sjson_data
from hephaistos.c... | nilq/baby-python | python |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | nilq/baby-python | python |
import requests
import os
if 'TPU_DRIVER_MODE' not in globals():
url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver0.1-dev20191206'
resp = requests.post(url)
TPU_DRIVER_MODE = 1
# The following is required to use TPU Driver as JAX's backend.
from jax.config import con... | nilq/baby-python | python |
"""usersエンティティ用モジュール"""
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional
from aws.dynamodb.base import Base
from aws.exceptions import DynamoDBError
ALL = 0
WEST_JR = 1
HANKYU = 2
HANSHIN = 3
@dataclass
class DelayInfoMessages(Base):
"""鉄道遅延情報メッセージ群クラス"""
west_jr: ... | nilq/baby-python | python |
from typing import Optional, Iterable, Any
from platypush.message.event import Event
class DbusSignalEvent(Event):
"""
Event triggered when a signal is received on the D-Bus.
"""
def __init__(
self, bus: str, interface: str, sender: str, path: str, signal: str,
params: Optional[Iterab... | nilq/baby-python | python |
"""
https://github.com/invl/retry
"""
import random
import time
from functools import partial, wraps
from typing import Callable, Optional, ParamSpecArgs, ParamSpecKwargs, Tuple, Type, List, Any
# sys.maxint / 2, since Python 3.2 doesn't have a sys.maxint...
from pydantic import Field, PositiveFloat, PositiveInt, ... | nilq/baby-python | python |
# Distributed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE, distributed with this software.
#
# Author: Philipp Schmidt <philipp.schmidt@xfel.eu>
# Copyright (c) 2020, European X-Ray Free-Electron Laser Facility GmbH.
# All rights reserved.
from collections.abc import Sequenc... | nilq/baby-python | python |
# coding: utf-8
"""
SnapshotSnapshotsApi.py
Copyright 2016 SmartBear Software
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 ... | nilq/baby-python | python |
#
# [To-Do] 1. Loop-Unrolling
# 2. Boundary Checks
# 3. Instuction Reordering
#
def tc_code_kernel_Store_Results(f, opt_gen_full, l_t3_mapping_tb_2D, l_t3_mapping_reg, size_reg_x, size_reg_y, idx_kernel, opt_accumulated):
#
#
#
f.write("\n")
f.write("\t// Store Results (Registe... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import opresource
from openprocurement.auctions.core.views.mixins import AuctionAuctionResource
@opresource(name='belowThreshold:Auction Auction',
collection_path='/auctions/{auction_id}/auction',
path='/auctions/{auction_id}/auc... | nilq/baby-python | python |
from django.db import models
# ePrice(比價王)
# Create your models here.
class Post(models.Model):
### id
post_id = models.CharField(max_length=64) #帖子ID
# 以 https://www.eprice.com.tw/life/talk/9/5242470/1/ 而言, 帖子ID = 5242470
### user
pu_id = models.CharField(max_length=255) #... | nilq/baby-python | python |
import lmfit
from time import time
class ModelFit:
""" We collect all information related to a fit between a pygom model and a set of data in this class
It has access to the model structure and defines all required parameters and details of fit """
def dumpparams(self,run_id=''): # Have to add self si... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-10-28 13:54
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ems', '0023_auto_20171028_0756'),
('registrations',... | nilq/baby-python | python |
VO = "https://www.vote.org"
VA = "https://www.voteamerica.com"
CODE = 'code'
REG = 'reg'
POLLS = 'polls'
CITIES = 'cities' # XXX This should move to campaign.Campaign but it's disruptive
ABS = 'abs'
REGDL = 'regdl'
ABROAD = 'abroad'
class States:
ALABAMA = 'Alabama'
ALASKA = 'Alaska'
ARIZONA = 'Arizona'
ARKANSAS... | nilq/baby-python | python |
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.keyvault import KeyVaultClient
from common_util import CommonUtil
from credentials.credentials_provider import ResourceCredentialsProvider
import logging as log
from azure.mgmt.keyvault.v2016_10_01.models import AccessPolicyUpdateKind, VaultAccessPolic... | nilq/baby-python | python |
import numpy as np
from numpy.linalg import norm
from MeshFEM import sparse_matrices
def preamble(obj, xeval, perturb, etype, fixedVars = []):
if (xeval is None): xeval = obj.getVars()
if (perturb is None): perturb = np.random.uniform(low=-1,high=1, size=obj.numVars())
if (etype is None): etype = obj._... | nilq/baby-python | python |
from functools import partial
from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import get_random_string
generate_random_string = partial(
get_random_string,
length=50,
allowed_chars='abcdefghijklmnopqrstu... | nilq/baby-python | python |
from setuptools import setup
from os import path
# Read the contents of the README file
cwd = path.abspath(path.dirname(__file__))
with open(path.join(cwd, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="pysvglib",
version="0.3.2",
description="SVG drawing library",
... | nilq/baby-python | python |
from argparse import ArgumentParser
import numpy as np
import py360convert
import os
import cv2
import os.path as osp
from typing import Union
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot, ret_result
from mmseg.core.evaluation import get_palette
from PIL import Image
import mmcv
fro... | nilq/baby-python | python |
import json
import requests
import logging
import hashlib
import time
from fake_useragent import UserAgent
from uuid import uuid4
from .camera import EzvizCamera
# from pyezviz.camera import EzvizCamera
COOKIE_NAME = "sessionId"
CAMERA_DEVICE_CATEGORY = "IPC"
API_BASE_URI = "https://apiieu.ezvizlife.com"
API_ENDPOINT... | nilq/baby-python | python |
# coding: utf-8
import os
import sh
import logging
import shutil
import tempfile
from unittest import TestCase
from nose.tools import nottest
class UncanningTest(TestCase):
""" Let's try to uncan a new project and run tests to see everything is ok
Estimated running time 260s"""
def setUp(self):
... | nilq/baby-python | python |
"""
Solution to https://adventofcode.com/2018/day/4
"""
from pathlib import Path
# path from the root of the project
INPUT_FILE = Path.cwd() / "2018" / "dec4.txt"
def part1() -> int:
sorted_lines = sorted(line for line in INPUT_FILE.read_text().split("\n") if line)
if __name__ == "__main__":
print(part1())... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from numpy import cos, exp, sin
from ....Classes.Arc1 import Arc1
from ....Classes.Segment import Segment
from ....Classes.SurfLine import SurfLine
def build_geometry(self, alpha=0, delta=0, is_simplified=False):
"""Compute the curve (Segment) needed to plot the Hole.
The ending poin... | nilq/baby-python | python |
import pydantic
import os
import yaml
import re
import typing
@pydantic.dataclasses.dataclass(frozen=True, order=True)
class RegexTestCase:
text: pydantic.constr()
matches: typing.Optional[typing.List[str]] = None
def run(self, regex):
""" evaluate the test case against the pattern """
ac... | nilq/baby-python | python |
#!/usr/bin/env python3
__author__ = "Leon Wetzel"
__copyright__ = "Copyright 2021, Leon Wetzel"
__credits__ = ["Leon Wetzel"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Leon Wetzel"
__email__ = "post@leonwetzel.nl"
__status__ = "Production"
import praw
from nltk import sent_tokenize
def main():
... | nilq/baby-python | python |
# coding: utf-8
# # Download TCGA Pan-Cancer Datasets from the UCSC Xena Browser
#
# This notebook downloads TCGA datasets for Project Cognoma. The file contents (text) remains unmodified, but files are given extensions and bzip2 compressed.
#
# [See here](https://genome-cancer.soe.ucsc.edu/proj/site/xena/datapages... | nilq/baby-python | python |
def palindromeRearranging(inputString):
characters = {}
error_count = 0
for character in inputString:
if character not in characters:
characters[character] = 1
else:
characters[character] += 1
print(characters.values())
for value in characters.values(... | nilq/baby-python | python |
from .mock_plugin import MockPlugin
__all__ = ['mock_plugin']
| nilq/baby-python | python |
# encoding: utf-8
import os.path as osp
from .bases import BaseImageDataset
class target_test(BaseImageDataset):
"""
target_training: only constains camera ID, no class ID information
Dataset statistics:
"""
dataset_dir = 'target_test'
def __init__(self, root='./example/data/challenge_data... | nilq/baby-python | python |
#!/usr/bin/python
from bs4 import BeautifulSoup
import urllib2
import csv
import codecs
linksList = []
#f = csv.writer(open("worksURI.csv", "w"))
#f.writerow(["Name", "Link"])
f = codecs.open("alllinkstrial.txt", encoding='utf-8', mode='w+')
#'http://www.isfdb.org/cgi-bin/ea.cgi?12578 ',
target_url=['ht... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 21:11:25 2019
@author: Jorge
"""
import tkinter as tk
from tkinter import ttk
import crearcapasconv
from threading import Thread
import sys
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure impor... | nilq/baby-python | python |
#!/usr/bin/env python
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('classic')
fig = plt.figure()
population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age,... | nilq/baby-python | python |
# -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache
#... | nilq/baby-python | python |
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from .models import Project,Profile
from .forms import ProjectForm,ProfileForm,VoteForm
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response im... | nilq/baby-python | python |
from torchvision import datasets, transforms
def imagenet_transformer():
transform=transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.2... | nilq/baby-python | python |
import base64
import json
import logging
from io import BytesIO
from urllib.parse import urljoin
import feedparser
from flask_babel import lazy_gettext as _
from PIL import Image
from authentication_document import AuthenticationDocument
from model import Hyperlink
from opds import OPDSCatalog
from problem_details im... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2005-2009,2011 Joe Wreschnig
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
import glob
import os
import shutil
import sys
import subprocess
from... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# :Project: pglast -- DO NOT EDIT: automatically extracted from pg_trigger.h @ 13-2.0.6-0-ga248206
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2017-2021 Lele Gaifax
#
from enum import Enum, IntEnum, IntFlag, auto... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.