content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import time import random from const import * from util.logger import logger class Session(): def __init__(self): # requests.adapters.DEFAULT_RETRIES = 5 # 增加重試次數,避免連線失效 self.has_login = False self.session = requests.Session() self.session.headers = { 'User-Agent': make...
nilq/baby-python
python
# Requests may need to be installed for this script to work import requests import re import config # Here we pass our client id and secret token auth = requests.auth.HTTPBasicAuth(config.client_id, config.secret_token) # Here we pass our login method (password), username, and password data = {'grant_type': 'password...
nilq/baby-python
python
""" # ============================================================================= # Simulating the double pendulum using Runge–Kutta method (RK4) # ============================================================================= Created on Fri Jul 17 2020 @author: Ahmed Alkharusi """ import numpy as np import ...
nilq/baby-python
python
from __future__ import annotations from datetime import date from typing import ( Literal, Optional, Sequence, ) from pydantic.fields import Field from pydantic.types import StrictBool from ..api import ( BodyParams, EndpointData, Methods, WrApiQueryParams, ) from ..types_.endpoint import...
nilq/baby-python
python
import datetime as _datetime import os import random import string import inflect import six from . import mock_random inflectify = inflect.engine() def _slugify(string): """ This is not as good as a proper slugification function, but the input space is limited >>> _slugify("beets")...
nilq/baby-python
python
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet import reactor from twisted.web import proxy, server site = server.Site(proxy.ReverseProxyResource('www.yahoo.com', 80, '')) reactor.listenTCP(8080, site) reactor.run()
nilq/baby-python
python
from torch.optim.lr_scheduler import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period. """ def lr_lambda(current_step): ...
nilq/baby-python
python
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import pytest import vector ak = pytest.importorskip("awkward") numba = pytest.importorsk...
nilq/baby-python
python
import socket #for sockets import sys #for exit # create dgram udp socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print('Failed to create socket') sys.exit() HOST = '' # Symbolic name meaning all available interfaces PORT = 6000 # Arbitrary non-privileged por...
nilq/baby-python
python
# Copyright (c) 2018 Sony Pictures Imageworks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
nilq/baby-python
python
#!/usr/bin/env python3 # # Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center # Distributed under the terms of the 3-clause BSD License. import time import unittest from ipykernel.tests.utils import execute, wait_for_idle from sos_notebook.test_utils import flush_channels, sos_kernel, Noteboo...
nilq/baby-python
python
"""Base method for all global interpretations. Is a subclass of base ModelInterpreter""" from ..model_interpreter import ModelInterpreter class BaseGlobalInterpretation(ModelInterpreter): """Base class for global model interpretations""" pass
nilq/baby-python
python
import json import unittest from pyshared.server.ref import CallCommand from pyshared.server.ref import DelCommand from pyshared.server.ref import ListCommand from pyshared.server.ref import LocalSharedResourcesManager from pyshared.server.ref import SetCommand from pyshared.server.ref import default_command_mapper fr...
nilq/baby-python
python
from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class RightBoard: def __init__(self, driver): self.driver = driver self.elements = RightBoardElements(self.driver) def click(self, elem): self.driver.execute_script( "arguments[0].c...
nilq/baby-python
python
import threading import time import signal import sys from callbacks_event_listener import EventListener from wpwithin_python import WPWithin,\ PricePerUnit,\ Price,\ Service,\ CommonPSPKeys,\ ...
nilq/baby-python
python
from django.urls import path, include urlpatterns = [ path('', include('accounts.urls.accounts')), path('', include('accounts.urls.employers')), path('', include('accounts.urls.professionals')), ]
nilq/baby-python
python
from django.shortcuts import render from django.http import HttpResponse from notice.models import Notice, Qna from main.models import search_word from django.views.generic import ListView from django.db.models import Q from django.utils import timezone import datetime def main(request): # Main_Notice = Notice.ob...
nilq/baby-python
python
import json from django import template register = template.Library() @register.filter def here(page, request): return request.path.startswith(page.get_absolute_url()) @register.simple_tag def node_module(path): return '/node_modules/{}'.format(path) @register.assignment_tag(takes_context=True) def navi...
nilq/baby-python
python
from django.db import models from django.contrib.auth.models import User from pyuploadcare.dj.models import ImageField # Create your models here. class Neighborhood(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=100) admin = models.ForeignKey("Profile", on_del...
nilq/baby-python
python
## # Copyright © 2020, The Gust Framework Authors. All rights reserved. # # The Gust/Elide framework and tools, and all associated source or object computer code, except where otherwise noted, # are licensed under the Zero Prosperity license, which is enclosed in this repository, in the file LICENSE.txt. Use of # this ...
nilq/baby-python
python
#!/usr/bin/env python3 import sys from os import path sys.path.insert(0, path.join(path.dirname(__file__))) from importers.monzo_debit import Importer as monzo_debit_importer from beancount.ingest import extract account_id = "acc_yourMonzoAccountId" account = "Assets:Monzo:Something" CONFIG = [ monzo_debit_impo...
nilq/baby-python
python
import os import sys import tensorflow as tf from absl import app, logging from absl.flags import argparse_flags import _jsonnet def parse_args(args, parser): # Parse command line arguments parser = parser if parser else argparse_flags.ArgumentParser() parser.add_argument("input", type=str) # Name of T...
nilq/baby-python
python
import logging from typing import Any, List, Optional from homeassistant.components.select import SelectEntity from gehomesdk import ErdCodeType from ...devices import ApplianceApi from .ge_erd_entity import GeErdEntity from .options_converter import OptionsConverter _LOGGER = logging.getLogger(__name__) class G...
nilq/baby-python
python
import webbrowser def open_page(url: str, new: int = 0, autoraise: bool = True): webbrowser.open(url, new=new, autoraise=autoraise) actions = {'open webpage': open_page}
nilq/baby-python
python
def util(node,visited,recstack): visited[node]=True recstack[node]=True for i in graph[node]: if visited[i]==False: if util(i,visited,recstack): return True elif recstack[i]==True: return True recstack[node]=False return False de...
nilq/baby-python
python
#!/usr/bin/env python """ @package mi.dataset.parser.test @file marine-integrations/mi/dataset/parser/test/test_adcpt_m_log9.py @author Tapana Gupta @brief Test code for adcpt_m_log9 data parser Files used for testing: ADCPT_M_LOG9_simple.txt File contains 25 valid data records ADCPT_M_LOG9_large.txt File conta...
nilq/baby-python
python
# Inspired by ABingo: www.bingocardcreator.com/abingo HANDY_Z_SCORE_CHEATSHEET = ( (1, float('-Inf')), (0.10, 1.29), (0.05, 1.65), (0.025, 1.96), (0.01, 2.33), (0.001, 3.08))[::-1] PERCENTAGES = {0.10: '90%', 0.05: '95%', 0.01: '99%', 0.001: '99.9%'} DESCRIPTION_IN_WORDS = {0.10: 'fairly conf...
nilq/baby-python
python
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from past.utils import old_div import rlpy import numpy as np from hyperopt import hp param_space =...
nilq/baby-python
python
import os from jobControl import jobControl from pyspark.sql import SparkSession from pyspark.sql import functions as f from pyspark.sql.types import IntegerType, StringType from utils import arg_utils, dataframe_utils job_args = arg_utils.get_job_args() job_name = os.path.basename(__file__).split(".")[0] num_partiti...
nilq/baby-python
python
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(item_type, item_id, item): # Filter out external tool checks for testing purposes. if item_type == "check" and item_id in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/0...
nilq/baby-python
python
# Generated by Django 3.2.5 on 2021-07-18 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('src', '0006_auto_20210718_1014'), ] operations = [ migrations.AddField( model_name='job', name='delivery_address', ...
nilq/baby-python
python
"""fix Contact's name constraint Revision ID: 41414dd03c5e Revises: 508756c1b8b3 Create Date: 2021-11-26 20:42:31.599524 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '41414dd03c5e' down_revision = '508756c1b8b3' branch_labels = None depends_on = None def u...
nilq/baby-python
python
#/usr/bin/env python import sys import logging logger = logging.getLogger('utility_to_osm.ssr2.git_diff') import utility_to_osm.file_util as file_util from osmapis_stedsnr import OSMstedsnr if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) # diff is called by git with 7 parameters: ...
nilq/baby-python
python
# THIS FILE IS GENERATED FROM SIGPROFILEMATRIXGENERATOR SETUP.PY short_version = '1.1.0' version = '1.1.0'
nilq/baby-python
python
from gym_minigrid.minigrid import * from gym_minigrid.register import register class WarehouseSortEnv(MiniGridEnv): """ Environment with a door and key, sparse reward """ def __init__(self, size=8): super().__init__( grid_size=size, max_steps=10*size*size ) ...
nilq/baby-python
python
"""Plot road network """ import os import cartopy.crs as ccrs import geopandas import matplotlib.patches as mpatches import matplotlib.pyplot as plt from atra.utils import load_config, get_axes, plot_basemap, scale_bar, plot_basemap_labels, save_fig def main(config): """Read shapes, plot map """ data_p...
nilq/baby-python
python
import torch import torch.nn as nn from utils.util import count_parameters class Embedding(nn.Module): """A conditional RNN decoder with attention.""" def __init__(self, input_size, emb_size, dropout=0.0, norm=False): super(Embedding, self).__init__() self.embedding = nn.Embedding(input_s...
nilq/baby-python
python
class FileReader(object): def read(self, file): with open(file) as f: return f.read() def read_lines(self, file): lines = [] with open(file) as f: for line in f: lines.append(line) return lines
nilq/baby-python
python
from locust import HttpUser, task from locust import User import tensorflow as tf from locust.contrib.fasthttp import FastHttpUser def read_image(file_name, resize=True): img = tf.io.read_file(filename=file_name) img = tf.io.decode_image(img) if resize: img = tf.image.resize(img, [224, 224]) r...
nilq/baby-python
python
# coding=utf-8 import unittest import urllib2 import zipfile import random from tempfile import NamedTemporaryFile from StringIO import StringIO from . import EPUB try: import lxml.etree as ET except ImportError: import xml.etree.ElementTree as ET class EpubTests(unittest.TestCase): def setUp(self): ...
nilq/baby-python
python
"""Collection of Object.""" import sqlite3 class Connection(sqlite3.Connection): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.execute('pragma foreign_keys=1') class CustomCommand: """Object for custom command.""" __slots__ = ( "id", "type...
nilq/baby-python
python
import networkx as nx import numpy as np import sys from scipy.io import mmread from scipy.sparse import coo_matrix np.set_printoptions(threshold=sys.maxsize) if len(sys.argv) != 2: print("Usage: python3 ./hits.py <file.mtx>") exit() graph_coo = mmread(sys.argv[1]) print("Loading COO matrix") print(graph_coo....
nilq/baby-python
python
import pickle from typing import Any, Union from datetime import datetime class DataStorage: _DataStorageObj = None def __new__(cls, *args, **kwargs): if cls._DataStorageObj is None: cls._DataStorageObj = super().__new__(cls) return cls._DataStorageObj def __init__(self): ...
nilq/baby-python
python
class discord: Colour = None class datetime: datetime = None
nilq/baby-python
python
import math import os def activator(data, train_x, sigma): #data = [p, q] #train_x = [3, 5] distance = 0 for i in range(len(data)): #0 -> 1 distance += math.pow(data[i] - train_x[i], 2) # 計算 D() 函式 return math.exp(- distance / (math.pow(sigma, 2))) # 最後返回 W() 函式 def grnn(data, train_x, train_y, ...
nilq/baby-python
python
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,line-too-long from unittest import mock import os import pytest from eze.plugins.tools.checkmarx_kics import KicsTool from eze.utils.io import create_tempfile_path from tests.plugins.tools.tool_helper import ToolMetaTestBase ...
nilq/baby-python
python
"""Simple templating engine. See `TemplateEngine` class.""" import os import re import inspect __all__ = ['TemplateEngine', 'TemplateSyntaxError', 'annotate_block'] class TemplateEngine: """Simple templating engine. WARNING: do NOT use this engine with templates from untrusted sources. Expressions in th...
nilq/baby-python
python
from rdkit import Chem from rdkit.ML.Descriptors import MoleculeDescriptors from rdkit.Chem import Descriptors from padelpy import from_smiles import re import time nms=[x[0] for x in Descriptors._descList] print('\n') calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms) f=open('/scratch/woon/b3lyp_2017/datas...
nilq/baby-python
python
from torch import randn from torch.nn import Linear from backpack import extend def data_linear(device="cpu"): N, D1, D2 = 100, 64, 256 X = randn(N, D1, requires_grad=True, device=device) linear = extend(Linear(D1, D2).to(device=device)) out = linear(X) vin = randn(N, D2, device=device) vou...
nilq/baby-python
python
# -*- coding: utf-8 -*- import logging from pathlib import Path import yaml logger = logging.getLogger(__name__) def recursive_update(original_dict: dict, new_dict: dict) -> dict: """Recursively update original_dict with new_dict""" for new_key, new_value in new_dict.items(): if isinstance(new_valu...
nilq/baby-python
python
# Generated by Django 3.2.6 on 2021-11-29 00:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kube', '0003_auto_20210917_0032'), ] operations = [ migrations.RemoveField( model_name='kubecluster', name='type', )...
nilq/baby-python
python
import json from flask import make_response from marshmallow import fields, Schema, post_load, EXCLUDE from flask_apispec.utils import Ref from flask_apispec.views import MethodResource from flask_apispec import doc, use_kwargs, marshal_with # All the following schemas are set with unknown = EXCLUDE # because part ...
nilq/baby-python
python
from abc import ABC, abstractmethod import itertools import numpy as np import matplotlib.pyplot as plt import tqdm from . import _heatmap from . import preprocessing class Regressor(ABC): ''' Mix-in class for Regression models. ''' @abstractmethod def get_output(self): ''' Retu...
nilq/baby-python
python
from __future__ import absolute_import, print_function import pytest from steam_friends import app from steam_friends.views import api, auth, main def test_app(flask_app): assert flask_app.debug is False # todo: should this be True? assert flask_app.secret_key assert flask_app.testing is True asser...
nilq/baby-python
python
# from classify.data.loaders.snli import SNLIDataLoader # __all__ = ["SNLIDataLoader"]
nilq/baby-python
python
import numpy as np class InvertedPendulum: def __init__(self, length, mass, gravity=9.81): self.length = length self.mass = mass self.gravity = gravity # matrices of the linearized system self.A = np.array([[0, 1, 0, 0], [gravity/length, 0, 0, 0]...
nilq/baby-python
python
class Base: @property def id(self): return self._id def __repr__(self): return '({} {})'.format(self.__class__.__name__, self.id) def __unicode__(self): return u'({} {})'.format(self.__class__.__name__, self.id) def __eq__(self, other): return self.id == other.id ...
nilq/baby-python
python
# from DETR main.py with modifications. import argparse import datetime import json import random import time from pathlib import Path import math import sys from PIL import Image import requests import matplotlib.pyplot as plt import numpy as np from torch.utils.data import DataLoader, DistributedSampler import torc...
nilq/baby-python
python
# Generated by Django 2.1.2 on 2018-12-05 14:28 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("barriers", "0020_auto_20181025_1545")] operations = [ migrations.RemoveField(model_name="barriercontributor", name="barr...
nilq/baby-python
python
#special thanks to this solution from: #https://stackoverflow.com/questions/40237952/get-scrapy-crawler-output-results-in-script-file-function #https://stackoverflow.com/questions/41495052/scrapy-reactor-not-restartable from scrapy import signals from scrapy.signalmanager import dispatcher from twisted.internet import...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Helper module to work with files.""" import fnmatch import logging import os import re from stat import S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR # pylint: disable=redefined-builtin from ._exceptions import FileNotFoundError MAXLEN = 120 ILEGAL = r'<>:"/\|?*' LOGGER = logging.ge...
nilq/baby-python
python
from numpy import dtype db_spec = True try: import sqlalchemy.types as sqlt except: db_spec = False return_keys = [ 'id', 'created_at', 'number', 'total_price', 'subtotal_price', 'total_weight', 'total_tax', 'total_discounts', 'total_line_items_price', 'name', 'tota...
nilq/baby-python
python
from setuptools import find_packages, setup setup( name='serverlessworkflow_sdk', packages=find_packages(include=['serverlessworkflow_sdk']), version='0.1.0', description='Serverless Workflow Specification - Python SDK', author='Serverless Workflow Contributors', license='http://www.apache.org/l...
nilq/baby-python
python
#!/usr/bin/env python3 # coding: utf-8 # PSMN: $Id: 02.py 1.3 $ # SPDX-License-Identifier: CECILL-B OR BSD-2-Clause """ https://github.com/OpenClassrooms-Student-Center/demarrez_votre_projet_avec_python/ Bonus 1, json """ import json import random def read_values_from_json(fichier, key): """ create an new em...
nilq/baby-python
python
# encoding: utf8 from pygubu import BuilderObject, register_custom_property, register_widget from pygubu.widgets.pathchooserinput import PathChooserInput class PathChooserInputBuilder(BuilderObject): class_ = PathChooserInput OPTIONS_CUSTOM = ('type', 'path', 'image', 'textvariable', 'state', ...
nilq/baby-python
python
""" Anserini: A toolkit for reproducible information retrieval research built on Lucene 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 a...
nilq/baby-python
python
from picamera import PiCamera from time import sleep def record_video(sec): pi_cam = PiCamera() pi_cam.start_preview() pi_cam.start_recording('./video.mp4') sleep(sec) pi_cam.stop_recording() pi_cam.stop_preview() record_video(5)
nilq/baby-python
python
import logging from hearthstone.enums import CardType, Zone, GameTag from hslog import LogParser, packets from hslog.export import EntityTreeExporter from entity.game_entity import GameEntity from entity.hero_entity import HeroEntity from entity.spell_entity import SpellEntity # import entity.cards as ecards logger =...
nilq/baby-python
python
''' Train all cort models Usage: train_all.py [--num_processes=<n>] --type=<t> <consolidated_conll_dir> <out_dir> ''' import os from cort.core.corpora import Corpus import codecs import random import subprocess from cort_driver import train from joblib import Parallel, delayed import sys import itertools from doco...
nilq/baby-python
python
""" Yoga style module """ from enum import Enum from typing import List class YogaStyle(Enum): """ Yoga style enum """ undefined = 0 hatha = 1 yin = 2 chair = 3 def get_all_yoga_styles() -> List[YogaStyle]: """ Returns a list of all yoga styles in the enum """ return [YogaStyle.hatha, Yo...
nilq/baby-python
python
#!/usr/bin/python import os import sys import argparse from collections import defaultdict import re import fileUtils def isBegining(line): m = re.match(r'^[A-Za-z]+.*', line) return True if m else False def isEnd(line): return True if line.startswith('#end') else False def getItem(item): m = re...
nilq/baby-python
python
import speech_recognition as sr import pyaudio #optional # get audio from the microphone while True: #this loop runs the below code infinite times until any inturrupt is generated r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print...
nilq/baby-python
python
from django.conf.urls import url from django.urls import path from . import views from . import dal_views from .models import * app_name = 'vocabs' urlpatterns = [ url( r'^altname-autocomplete/$', dal_views.AlternativeNameAC.as_view( model=AlternativeName,), name='altname-autocomplete'...
nilq/baby-python
python
from dancerl.models.base import CreateCNN,CreateMLP import torch.nn as nn if __name__ == '__main__': mlp=CreateMLP(model_config=[[4,32,nn.ReLU()], [32,64,nn.ReLU()], [64,3,nn.Identity()]]) print(mlp) cnn=CreateCNN(model_config=[[4,32,3,2,1,n...
nilq/baby-python
python
from DB import Database db = Database("db") MENU = range(1) def reminder_handler(user_id, obj): date, type, name = obj db.add_event(user_id, date, "birthday" if type == "Birthday" else "regular", name) if type == "Birthday": db.add_reminder(user_id, date - 7 * 24 * 60 * 60, "birthday" if type ==...
nilq/baby-python
python
import glob import os import sys import argparse import time from datetime import datetime import random import numpy as np import copy from matplotlib import cm import open3d as o3d VIRIDIS = np.array(cm.get_cmap('plasma').colors) VID_RANGE = np.linspace(0.0, 1.0, VIRIDIS.shape[0]) LABEL_COLORS = np.array([ (255,...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function from distutils.version import LooseVersion import pickle import numpy as np import pytest import xarray as xr import xarray.ufuncs as xu from . import ( assert_array_equal, assert_identical as assert_identical_, mock, raises_regex, ) require...
nilq/baby-python
python
from .utils import * from .ps.dist_model import DistModel from .ps import ps_util def evaluate_ps(gpu_available, options): model_path = os.path.join(options.model_path, 'alex.pth') model = DistModel() model.initialize(model='net-lin', net='alex', model_path=model_path, use_gpu=gpu_available) dist_sta...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Cisco-IOS-XR-Get-Full-ClearText-Running-Config Console Script. Copyright (c) 2021 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at ...
nilq/baby-python
python
#Uses Money Flow Index to determine when to buy and sell stock import numpy as np import pandas as pd #import warnings import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') #warnings.filterwarnings('ignore') df = pd.read_csv('StockTickers/JPM.csv',nrows=200) df.set_index(pd.DatetimeIndex(df['Date'].values),...
nilq/baby-python
python
from synapse import Synapse from timemodule import Clock from neuron import * import random clock = Clock() neurons = [] for i in range(20): neurons.append(Neuron(clock.get_time(),7/10)) for i in range(30): connect(neurons[random.randrange(20)],neurons[random.randrange(20)] ,random.randrange(2),1)...
nilq/baby-python
python
#!/usr/bin/env python3 import logging import os import yaml from jinja2 import Environment, FileSystemLoader logging.getLogger().setLevel(logging.DEBUG) def main(template_name, vars_file): logging.info("Enter main.") with open(vars_file, 'r') as yaml_vars: variables = yaml.load(yaml_vars) thes...
nilq/baby-python
python
from status import Status import errors from unittest import TestCase class TestStatus(TestCase): def test_ok(self): try: Status.divide(Status.OK.value, None) self.assertTrue(True) except errors.JstageError: self.assertTrue(False) def test_no_results(self):...
nilq/baby-python
python
# -*- coding: utf-8 -*- # file: train_atepc_english.py # time: 2021/6/8 0008 # author: yangheng <yangheng@m.scnu.edu.cn> # github: https://github.com/yangheng95 # Copyright (C) 2021. All Rights Reserved. ###################################################################################################################...
nilq/baby-python
python
#!env python3 import pyd4 import sys file = pyd4.D4File(sys.argv[1]) chrom = sys.argv[2] begin = int(sys.argv[3]) end = int(sys.argv[4]) for (chrom, pos, value) in pyd4.enumerate_values(file, chrom, begin, end): print(chrom, pos, value)
nilq/baby-python
python
XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXX XXX XXXXXXXXXXXX XXXXXXXXXX XXX XXXXXXXXXX XXXXXXX XXXXXXXXXXX XXXXXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XX XXXXXX XXXXXX XXXX X XXXXXXXXX XXXX XXXXXX X...
nilq/baby-python
python
import datetime model_date_to_read = '20200125' model_version_to_read = '2.0' model_date_to_write = datetime.datetime.today().strftime('%Y%m%d') model_version_to_write = '2.0'
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on 2017-8-23 @author: cheng.li """ import numpy as np import pandas as pd from PyFin.api import * from alphamind.api import * from matplotlib import pyplot as plt plt.style.use('ggplot') import datetime as dt start = dt.datetime.now() universe = Universe('custom', ['zz800']) f...
nilq/baby-python
python
# Other imports import numpy as np import torch # DeepCASE Imports from deepcase.preprocessing import Preprocessor from deepcase import DeepCASE if __name__ == "__main__": ######################################################################## # Loading data ...
nilq/baby-python
python
""" [summary] [extended_summary] """ # region [Imports] # * Standard Library Imports ------------------------------------------------------------------------------------------------------------------------------------> import os from datetime import datetime import re # * Third Party Imports -----------------------...
nilq/baby-python
python
import math import sys import time import numpy as np import owl from net import Net import net from net_helper import CaffeNetBuilder from caffe import * from PIL import Image class NetTrainer: ''' Class for training neural network Allows user to train using Caffe's network configure format but on multiple G...
nilq/baby-python
python
import numpy as np import torch import torch.nn.functional as F import os, copy, time #from tqdm import tqdm import pandas as pd from ipdb import set_trace path = '/home/vasu/Desktop/project/' ### helper functions def to_np(t): return np.array(t.cpu()) ### Losses def calc_class_weight(x, fac=2): ...
nilq/baby-python
python
# Copyright Jetstack Ltd. See LICENSE for details. # Generates kube-oidc-proxy Changelog # Call from the branch with 3 parameters: # 1. Date from which to start looking # 2. Github Token # requires python-dateutil and requests from pip from subprocess import * import re from datetime import datetime import dateutil....
nilq/baby-python
python
from PIL import Image import numpy as np from matplotlib import pylab as plt img = np.array(Image.new("RGB", (28, 28))) img[:,:,:] = 255 img[2,2,:] = 0 img[2,5,:] = 0 img[2,6,:] = 0 img[2,10,:] = 0 img[2,11,:] = 0 img[3,10,:] = 0 img[3,11,:] = 0 plt.imshow(img) plt.imsave("p.png", img) np.save('p,npy', img, allo...
nilq/baby-python
python
""" Hyperparameters for MJC peg insertion trajectory optimization. """ from __future__ import division from datetime import datetime import os.path import numpy as np from gps import __file__ as gps_filepath from gps.agent.mjc.agent_mjc import AgentMuJoCo from gps.algorithm.algorithm_traj_opt import AlgorithmTrajOpt ...
nilq/baby-python
python
import os import sys PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.join(PROJECT_ROOT, 'vendor', 'pyyaml', 'lib')) import yaml from git import apply as git_apply class Patch: def __init__(self, file_path, repo_path): self.file_path = file_pa...
nilq/baby-python
python
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # See LICENSE comming with the source of python-quilt for details. import runpy import sys from unittest import TestCase from six.moves import cStringIO from helpers import tmp_mapping class Test(TestCase): def test_registration(self): with tmp_mapping(v...
nilq/baby-python
python
from django.test import TestCase from rest_framework.test import APIRequestFactory from rest_framework.test import APIClient import json from django.utils import timezone from datetime import timedelta # Create your tests here. from .models import Contact from .serializers import ContactSerializer from agape.people....
nilq/baby-python
python
#!/usr/bin/python import sys def __test1__(__host__): import pylibmc print 'Testing <pylibmc> ... %s' % (__host__) mc = pylibmc.Client([__host__], binary=True, behaviors={"tcp_nodelay": True,"ketama": True}) print mc mc["some_key"] = "Some value" print mc["some_key"] assert(mc["some_key"...
nilq/baby-python
python
import json import argparse import requests parser = argparse.ArgumentParser() parser.add_argument("--extension-uuid", dest="extension_uuid", type=str) parser.add_argument("--gnome-version", dest="gnome_version", type=str) args = parser.parse_args() def get_extension_url(extension_uuid, gnome_version): base_url ...
nilq/baby-python
python