content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import json from csv import DictReader def parse_txt(fd, settings): return fd.read().splitlines() def parse_csv(fd, settings): return [dict(x) for x in DictReader(fd)] def parse_json(fd, settings): return json.load(fd)
nilq/baby-python
python
import torch import torch.nn as nn import pytorchvideo AVAILABLE_3D_BACKBONES = [ "i3d_r50", "c2d_r50", "csn_r101", "r2plus1d_r50", "slow_r50", "slowfast_r50", "slowfast_r101", "slowfast_16x8_r101_50_50", "x3d_xs", "x3d_s", "x3d_m", "x3d_l", ] class CNN3D(nn.Module): ...
nilq/baby-python
python
# Copyright 2016 VMware, 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 a...
nilq/baby-python
python
def distance(x, y): return (x-y).norm(2,-1) def invprod(x, y): return 1/(((x*y).sigmoid()).sum(-1))
nilq/baby-python
python
import os import cv2 import numpy as np if __name__ == '__main__': # 启动一个dicom server,用于接收来自X光机的dicom文件 from pydicom.uid import ImplicitVRLittleEndian from pynetdicom import AE, debug_logger, evt from pynetdicom.sop_class import XRayAngiographicImageStorage from pynetdicom.sop_class import _VERIFICATION_CL...
nilq/baby-python
python
from app.data_models.relationship_store import Relationship, RelationshipStore relationships = [ { "list_item_id": "123456", "to_list_item_id": "789101", "relationship": "Husband or Wife", }, { "list_item_id": "123456", "to_list_item_id": "ghijkl", "relations...
nilq/baby-python
python
import os import gc import gym import random import numpy as np from collections import deque import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Actor(nn.Module): def __init__(self, epochs, state_dim, action_size=2, action_limit=1.): super(Actor, self)._...
nilq/baby-python
python
#All MPOS MPOS = {"Abilene": {"Jones": "253", "Taylor": "441"}, "Amarillo": {"Potter": "375", "Randall": "381"}, "Brownsville": {"Cameron": "061"}, "Bryan-College Station": {"Brazos": "041"}, "Capital Area": {"Bastrop": "021", "Burnet": "053", "Caldwell": "055", "Hays": "209", "Travis":...
nilq/baby-python
python
from drivers import * print "Driver loaded" from drivers.nidaq.asserv import Asserv from PyDAQmx import * import numpy as np from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import sys default_fm_dev = 400 # Profondeur de modulation (Hz pour 5 V) fs = E8254A(gpibAdress=19,name="freqSyn...
nilq/baby-python
python
#!/usr/bin/env python3 # # Copyright 2018 Brian T. Park <brian@xparks.net> # # MIT License # """Monitor the output of the given serial port and echo the output to the STDOUT. If nothing is seen on the serial output for more than 10 seconds, an error message is printed. If the --test flag is given, the output is assume...
nilq/baby-python
python
# Lint as: python3 # Copyright 2018, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
nilq/baby-python
python
import pandas as pd pd.options.display.max_columns = None from sklearn.preprocessing import OrdinalEncoder from torchvision import datasets, transforms import torch import plotly.express as px import os, sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append...
nilq/baby-python
python
import asyncio import logging from ottoengine import const, helpers from ottoengine.model import dataobjects _LOG = logging.getLogger(__name__) # _LOG.setLevel(logging.DEBUG) class RuleActionItem(object): """ This is a single action step in an action sequence """ def get_dict_config(self) -> dict: ...
nilq/baby-python
python
import tests2 as t t.testing(method = 'KIR', initial = 'sin', velocity = 'const') t.testing(method = 'KIR', initial = 'sin', velocity = 'x') t.testing(method = 'KIR', initial = 'sin', velocity = 'func') t.testing(method = 'KIR', initial = 'peak', velocity = 'const') t.testing(method = 'KIR', initial = 'peak', ve...
nilq/baby-python
python
import numpy as np import tqdm def add_iteration_column_np(df): """ Only used for numerical integral timings, but perhaps also useful for other timings with some adaptations. Adds iteration information, which can be deduced from the order, ppid, num_cpu and name (because u0_int is only done once, we h...
nilq/baby-python
python
""" 0.92% """ import collections class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = collections.deque() self.minlist = [] def push(self, x): """ :type x: int :rtype: void """ ...
nilq/baby-python
python
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It"s nice, because now 1) we have a top level # README file and 2) it"s easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path....
nilq/baby-python
python
index = {'Halifax': 'Q2141', 'Los Angeles': 'Q65', 'Wilkesboro': 'Q1025995', 'New York': 'Q1384', 'Uvalde': 'Q868860', 'Saint James': 'Q7401398', 'Ottawa': 'Q1930', 'Newton': 'Q49196', 'Mahé':'Q277480', 'Milwaukee': 'Q37836', 'Pom...
nilq/baby-python
python
num=input("enter any number") if num > 0: print("positive") elif num < 0: print("negative") else: print("it is a zero")
nilq/baby-python
python
import pyviz3d.visualizer as viz import numpy as np import math def main(): v = viz.Visualizer() v.add_arrow('Arrow_1', start=np.array([0, 0.2, 0]), end=np.array([1, 0.2, 0])) v.add_arrow('Arrow_2', start=np.array([0, 0.5, 0.5]), end=np.array([0.5, 0, 0.5]), color=np.array([0, 0, 255])) v.add_arrow('A...
nilq/baby-python
python
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import keras from keras.models import Sequential from keras.layers import Dense, Dropout from sklearn.metrics import confusion_matri...
nilq/baby-python
python
# encoding=utf8 import jenkins_job_wrecker.modules.base from jenkins_job_wrecker.helpers import get_bool, gen_raw from jenkins_job_wrecker.modules.triggers import Triggers PARAMETER_MAPPER = { 'stringparameterdefinition': 'string', 'booleanparameterdefinition': 'bool', 'choiceparameterdefinition': 'choice'...
nilq/baby-python
python
import itertools import pymel.core as pm import flottitools.test as mayatest import flottitools.utils.materialutils as matutils import flottitools.utils.skeletonutils as skelutils import flottitools.utils.skinutils as skinutils class TestGetSkinCluster(mayatest.MayaTestCase): def test_get_skin_cluster_from_cube...
nilq/baby-python
python
import array import unittest import pickle import struct import sys from pyhmmer.easel import Vector, VectorF, VectorU8 class _TestVectorBase(object): Vector = NotImplemented def test_pickle(self): v1 = self.Vector(range(6)) v2 = pickle.loads(pickle.dumps(v1)) self.assertSequenceEqu...
nilq/baby-python
python
from distutils.core import setup import requests.certs import py2exe setup( name='hogge', version='1.0.1', url='https://github.com/igortg/ir_clubchamps', license='LGPL v3.0', author='Igor T. Ghisi', description='', console=[{ "dest_base": "ir_clubchamps", "script": "main.py...
nilq/baby-python
python
import re from abc import ABC class TemplateFillerI(ABC): def fill(self, template: str, entity: str, **kwargs): return template.replace("XXX", entity) class ItalianTemplateFiller(TemplateFillerI): def __init__(self): self._reduction_rules = {'diil': 'del', 'dilo': 'dello', 'dila': 'della', '...
nilq/baby-python
python
import gc import os import cv2 import numpy as np import torch from SRL4RL import SRL4RL_path from SRL4RL.rl.utils.runner import StateRunner from SRL4RL.utils.nn_torch import numpy2pytorch, pytorch2numpy, save_model from SRL4RL.utils.utils import createFolder, loadPickle from SRL4RL.utils.utilsEnv import ( NCWH2W...
nilq/baby-python
python
# coding=utf-8 from __future__ import unicode_literals from django.db import models import pytz import requests from datetime import timedelta import datetime import math import wargaming from django.db.models.signals import pre_save from django.db.models import Q from django.contrib.postgres.fields import JSONField...
nilq/baby-python
python
""" python setup.py sdist twine upload dist/* """ import cv2 if cv2.cuda.getCudaEnabledDeviceCount() > 0: print("检测到cuda环境")
nilq/baby-python
python
import librosa as lr import numpy as np def mu_law_encoding(data, mu): mu_x = np.sign(data) * np.log(1 + mu * np.abs(data)) / np.log(mu + 1) return mu_x def mu_law_expansion(data, mu): s = np.sign(data) * (np.exp(np.abs(data) * np.log(mu + 1)) - 1) / mu return s def quantize_data(data, classes)...
nilq/baby-python
python
from random import randint cpu = randint(0,5) usuario = int(input('Digite um numero entre 0 a 5: ')) if(cpu == usuario): print('\033[33;mAcertô, mizeravi!') else: print('Errou Zé Ruela')
nilq/baby-python
python
from DBMS_Software.queryProcessor.ReadGlobalDataDictionary import readGlobalDataDictionary from DBMS_Software.queryProcessor.ReadGlobalDataDictionary import fetchFileFromGCP import os def createSQLDump(): print("Enter the TableName:") TableName = input() tableLocation = readGlobalDataDictionary(TableName) ...
nilq/baby-python
python
"""STACK Configs.""" import os import yaml config = yaml.load(open('stack/config.yml', 'r'), Loader=yaml.FullLoader) PROJECT_NAME = config['PROJECT_NAME'] STAGE = config.get('STAGE') or 'dev' # primary bucket BUCKET = config['BUCKET'] # Additional environement variable to set in the task/lambda TASK_ENV: dict = di...
nilq/baby-python
python
""" Script for testing purposes. """ import zmq def run(port=5555): context = zmq.Context() # using zmq.ROUTER socket = context.socket(zmq.ROUTER) # bind socket socket.bind('tcp://*:{}'.format(port)) while True: msg = socket.recv_multipart() print('Received message {}'.format...
nilq/baby-python
python
from itertools import product from string import ascii_lowercase import numpy as np import pytest from pandas import ( DataFrame, Index, MultiIndex, Period, Series, Timedelta, Timestamp, date_range, ) import pandas._testing as tm class TestCounting: def test_cumcount(self): ...
nilq/baby-python
python
# Copyright 2019 The Bazel 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 la...
nilq/baby-python
python
""" Referral answer related API endpoints. """ from django.db.models import Q from django.http import Http404 from django_fsm import TransitionNotAllowed from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.permissions import BasePermission, IsAuthenticated from rest_fra...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='BookInfo', fields=[ ('id', models.AutoField(aut...
nilq/baby-python
python
from tests.system.common import CondoorTestCase, StopTelnetSrv, StartTelnetSrv from tests.dmock.dmock import SunHandler from tests.utils import remove_cache_file import condoor class TestSunConnection(CondoorTestCase): @StartTelnetSrv(SunHandler, 10023) def setUp(self): CondoorTestCase.setUp(self) ...
nilq/baby-python
python
#!/usr/bin/env python3 # encoding=utf-8 #codeby 道长且阻 #email @ydhcui/QQ664284092 from core.plugin import BaseHostPlugin import re import socket import binascii import hashlib import struct import re import time class MongodbNoAuth(BaseHostPlugin): bugname = "Mongodb 未授权访问" bugrank = "高危" def fi...
nilq/baby-python
python
""" Example of how to make a MuJoCo environment using the Gym library. """ from pathlib import Path from gym.envs.mujoco.mujoco_env import MujocoEnv from gym.utils import EzPickle class SpiderEnv(MujocoEnv, EzPickle): """ Spider environment for RL. The task is for the spider to move to the target button. ...
nilq/baby-python
python
# coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh...
nilq/baby-python
python
from mock.mock import patch import os import pytest import ca_test_common import ceph_volume_simple_activate fake_cluster = 'ceph' fake_container_binary = 'podman' fake_container_image = 'quay.ceph.io/ceph/daemon:latest' fake_id = '42' fake_uuid = '0c4a7eca-0c2a-4c12-beff-08a80f064c52' fake_path = '/etc/ceph/osd/{}-{}...
nilq/baby-python
python
import glob import matplotlib.pyplot as plt import pickle import numpy as np import os import sys from argparse import ArgumentParser from utils import get_params_dict def parseArgs(): """Parse command line arguments Returns ------- a : argparse.ArgumentParser """ parser = Argument...
nilq/baby-python
python
from django.shortcuts import render_to_response, render from django.contrib.auth.decorators import login_required from grid_core.managers import GridManager @login_required def account_deshbord(request): allfriends = GridManager.get_friends_user(request.user) allgroups = GridManager.get_group_user(request.use...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: pydbgen/pbclass/data_define.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SleekXMPP: The Sleek XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ import sys import logging import getpass from optparse import OptionParser import sleekxmpp # P...
nilq/baby-python
python
import datetime as dt from datetime import datetime from datetime import timedelta from .error import WinnowError valid_rel_date_values = ( "last_full_week", "last_two_full_weeks", "last_7_days", "last_14_days", "last_30_days", "last_45_days", "last_60_days", "next_7_days", "next_1...
nilq/baby-python
python
""" 创建函数,在终端中打印矩形. number = int(input("请输入整数:")) # 5 for row in range(number): if row == 0 or row == number - 1: print("*" * number) else: print("*%s*" % (" " * (number - 2))) """ def print_rectangle(number): for row in range(number): if row == 0 or row == number - 1: prin...
nilq/baby-python
python
import os.path # manage descriptive name here... def input_file_to_output_name(filename): get_base_file = os.path.basename(filename) base_filename = get_base_file.split('.')[0] # base_filename = '/pipeline_data/' + base_filename return base_filename
nilq/baby-python
python
# Import Modules from module.Mask_RCNN.mrcnn import config as maskconfig from module.Mask_RCNN.mrcnn import model as maskmodel from module.Mask_RCNN.mrcnn import visualize import tensorflow as tf import numpy as np import warnings import json import cv2 import os # Ignore warnings old_v = tf.compat.v1.logging.get_verb...
nilq/baby-python
python
from django.urls import path from api import views app_name = "api" urlpatterns = [path("signup/", views.SignUp.as_view(), name="signup")]
nilq/baby-python
python
import os from glob import glob from os.path import join, basename import numpy as np from utils.data_utils import default_loader from . import CDDataset class OSCDDataset(CDDataset): __BAND_NAMES = ( 'B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12' ...
nilq/baby-python
python
"""All the url endpoint hooks for facebook""" import os from sanic.response import json, text from sanic import Blueprint from .base import FacebookResponse from taggo.parsers import FacebookYamlExecutor VERIFY_TOKEN = os.environ.get("VF_TOKEN") fb = Blueprint('facebook', url_prefix="/fb") @fb.post('/recieve_message...
nilq/baby-python
python
from flask import render_template, url_for, request, redirect, session, flash from home_password.models.user import User from home_password.models.site import Site from flask_login import login_user, current_user, logout_user from flask import Blueprint main = Blueprint('main', __name__) @main.route('/') @main.rout...
nilq/baby-python
python
"""*Text handling functions*.""" import json import subprocess import sys from os.path import basename, splitext from pathlib import Path from urllib.parse import urlparse from loguru import logger as log import iscc_sdk as idk __all__ = [ "text_meta_extract", "text_extract", "text_name_from_uri", ] TEX...
nilq/baby-python
python
import data_processor import model_lib if __name__ == "__main__": train_set = data_processor.read_dataset("preprocessed/training_nopestudio.json") valid_set = data_processor.read_dataset("preprocessed/validation_nopestudio.json") combined_set = data_processor.read_dataset("preprocessed/dataset_nopestudio....
nilq/baby-python
python
import numba as nb import numpy as np class Zobrist(object): MAX_RAND = pow(10, 16) BLACK_TABLE = np.random.seed(3) or np.random.randint(MAX_RAND, size=(8, 8)) WHITE_TABLE = np.random.seed(7) or np.random.randint(MAX_RAND, size=(8, 8)) @staticmethod def from_state(state): return Zobrist.h...
nilq/baby-python
python
#!/usr/bin/env python """ CloudFormation Custom::FindImage resource handler. """ # pylint: disable=C0103 from datetime import datetime from logging import DEBUG, getLogger import re from typing import Any, Dict, List, Tuple import boto3 from iso8601 import parse_date log = getLogger("cfntoolkit.ec2") log.setLevel(DEBU...
nilq/baby-python
python
import rsa from django.db import models import base64 class RSAFieldMixin(object): def loadKeys(self, keys=[]): if len(keys) == 0: (pubkey, privkey) = rsa.newkeys(512) keys.append(pubkey) keys.append(privkey) elif len(keys) == 2: pubkey = keys[0] ...
nilq/baby-python
python
import tensorflow as tf # for deep learning import pathlib # for loading path libs # data loader class class DataLoader(): # init method def __init__(self, path_to_dir): self.__path_to_dir = pathlib.Path(path_to_dir) # proecess image method # @tf.function def process_image(self, image_data...
nilq/baby-python
python
import json from wtforms import widgets class CheckboxInput(widgets.CheckboxInput): def __call__(self, field, **kwargs): kwargs.update({"class_": "checkbox-field"}) rendered_field = super().__call__(field, **kwargs) return widgets.HTMLString( """ %s<label class="st...
nilq/baby-python
python
import heterocl as hcl import numpy as np def test_zero_allocate(): def kernel(A): with hcl.for_(0, 10) as i: with hcl.for_(i, 10) as j: A[j] += i return hcl.compute((0,), lambda x: A[x], "B") A = hcl.placeholder((10,)) s = hcl.create_schedule(A, kernel) p ...
nilq/baby-python
python
import abc class LayerBase(object): """Base class for most layers; each layer contains information which is added on top of the regulation, such as definitions, internal citations, keyterms, etc.""" __metaclass__ = abc.ABCMeta # @see layer_type INLINE = 'inline' PARAGRAPH = 'paragraph' ...
nilq/baby-python
python
import os import hashlib from download.url_image_downloader import UrlImageDownloader def test_download_image_from_url(): url = ('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/RacingFlagsJune2007.jpg/575px-' 'RacingFlagsJune2007.jpg') image_path = 'test.jpg' # download the image ...
nilq/baby-python
python
#!/router/bin/python from trex_general_test import CTRexGeneral_Test from tests_exceptions import * from interfaces_e import IFType from nose.tools import nottest from misc_methods import print_r class CTRexNbar_Test(CTRexGeneral_Test): """This class defines the NBAR testcase of the T-Rex traffic generator""" ...
nilq/baby-python
python
from rest_framework import permissions from rest_framework.reverse import reverse class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to...
nilq/baby-python
python
from ms_deisotope.peak_dependency_network.intervals import Interval, IntervalTreeNode from glycan_profiling.task import TaskBase from .chromatogram import Chromatogram class ChromatogramForest(TaskBase): """An an algorithm for aggregating chromatograms from peaks of close mass weighted by intensity. Th...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0001_initial'), ] operations = [ migrations.CreateModel( name='InformationDocument', fi...
nilq/baby-python
python
import re class Command: def __init__(self, name, register, jump_addr=None): self.name = name self.register = register self.jump_addr = jump_addr class Program: def __init__(self, commands, registers): self.commands = commands self.registers = registers self.i...
nilq/baby-python
python
if __name__ == "__main__": import argparse import os import torch import torch.nn as nn import torch.optim as optim from mnistconvnet import MNISTConvNet from mnist_data_loader import mnist_data_loader from sgdol import SGDOL # Parse input arguments. parser = ar...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @Time : 2019/9/8 14:18 # @Author : zhoujun import os import cv2 import torch import subprocess import numpy as np import pyclipper BASE_DIR = os.path.dirname(os.path.realpath(__file__)) def de_shrink(poly, r=1.5): d_i = cv2.contourArea(poly) * r / cv2.arcLength(poly, True) pco =...
nilq/baby-python
python
count = 0 print('Before', count) for thing in [9, 41, 12, 3, 74, 15]: count += 1 # zork = zork + 1 print(count, thing) print('After', count)
nilq/baby-python
python
# import src.stacking.argus_models
nilq/baby-python
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2015-2017 by ExopyPulses Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ---------...
nilq/baby-python
python
import torch import torch.nn as nn """ initial """ class InitialBlock(nn.Module): def __init__(self, in_channels, out_channels, bias=False, relu=True): super(InitialBlock, self).__init__() if (relu): activation = nn.ReLU else: activation = nn.PReLU # maini...
nilq/baby-python
python
''' A flask application for controlled experiment on the attention on clickbait healdines ''' # imports from flask import Flask, render_template, url_for, redirect, request, jsonify, session from flask_session import Session from flask_sqlalchemy import SQLAlchemy from datetime import datetime, date, timedelta import ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Scraping all the 10 qoutes here:http://quotes.toscrape.com/ # All the authors,tags and text # follow pagination link with scarpy import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" allowed_domains = ["toscrape.com"] start_urls = ['http://quotes.toscrape.com'] def parse(s...
nilq/baby-python
python
import numpy as np import pandas as pd from fmow_helper import ( BASELINE_CATEGORIES, MIN_WIDTHS, WIDTHS, centrality, softmax, lerp, create_submission, csv_parse, read_merged_Plog ) BASELINE_CNN_NM = 'baseline/data/output/predictions/soft-predictions-cnn-no_metadata.txt' BASELINE_CNN = 'baseli...
nilq/baby-python
python
#!/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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
import os from setuptools import find_packages, setup def read(*parts): filename = os.path.join(os.path.dirname(__file__), *parts) with open(filename, encoding="utf-8") as fp: return fp.read() setup( name="django-formtools", use_scm_version={"version_scheme": "post-release", "local_scheme": ...
nilq/baby-python
python
#!/usr/bin/python import cStringIO as StringIO from fnmatch import fnmatch import difflib import os import sys def get_name(filename): return os.path.splitext(filename)[0] def list_dir(dir_path, filter_func): return sorted(filter(filter_func, os.listdir(dir_path)), key=get_name) def main(): test_dir ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from ..utils import get_offset, verify_series def ohlc4(open_, high, low, close, offset=None, **kwargs): """Indicator: OHLC4""" # Validate Arguments open_ = verify_series(open_) high = verify_series(high) low = verify_series(low) close = verify_series(close) offset =...
nilq/baby-python
python
# # Copyright (c) 2021 Incisive Technology Ltd # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pu...
nilq/baby-python
python
#!/usr/bin/env python2.7 import socket import sys import os import json import time import serial import availablePorts import argparse DATA_AMOUNT = 1024 MAXLINE = 40 def getArgs(): parser = argparse.ArgumentParser(prog=sys.argv[0]) parser.add_argument('-p','--port',type=int,default=10000,dest='port',he...
nilq/baby-python
python
# coding: utf-8 # In[1]: import netCDF4 # In[2]: #url = 'http://52.70.199.67:8080/opendap/ugrids/RENCI/maxele.63.nc' url = 'http://ingria.coas.oregonstate.edu/opendap/ACTZ/ocean_his_3990_04-Dec-2015.nc' # In[3]: nc = netCDF4.Dataset(url) # In[4]: nc.variables.keys() # In[5]: nc.variables['lat_rho'] # I...
nilq/baby-python
python
from django.db import models from django.conf import settings from mainapp.models import Product class Order(models.Model): FORMING = 'FM' SENT_TO_PROCEED = 'STP' PROCEEDED = 'PRD' PAID = 'PD' READY = 'RDY' CANCEL = 'CNC' ORDER_STATUS_CHOICES = ( (FORMING, 'формируется'), ...
nilq/baby-python
python
import gluonts.mx.model.predictor as pred from kensu.gluonts.ksu_utils.dataset_helpers import make_dataset_reliable from kensu.utils.helpers import eventually_report_in_mem from gluonts.dataset.common import ListDataset from kensu.utils.kensu_provider import KensuProvider from kensu.gluonts.model.forecast import Sampl...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import print_function from select import select import termios import os import sys import optparse import subprocess import random import time #import cv2 import curses #from awscli.customizations.emr.constants import TRUE from keras.optimizers import RMSprop, Ad...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 3 10:51:05 2016 @author: dyanni3 """ # %% imports and prep from threading import Lock import numpy as np from numpy.random import rand as r from collections import defaultdict as d, defaultdict from PIL import Image from functools import reduce f...
nilq/baby-python
python
import tensorflow as tf import numpy as np from load_data import load_data import sklearn.preprocessing as prep from tensorflow.examples.tutorials.mnist import input_data from sklearn.metrics import accuracy_score class LR(object): def __init__(self, n_input=750, n_class=2, ...
nilq/baby-python
python
# -------------------------------------------------------- # High Resolution Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Rao Fu, RainbowSecret # -------------------------------------------------------- import os import pdb import logging import tor...
nilq/baby-python
python
from fixtures.builder import FixtureBuilder def build(): fixture = FixtureBuilder('TUFTestFixtureDelegated')\ .create_target('testtarget.txt')\ .publish(with_client=True)\ .delegate('unclaimed', ['level_1_*.txt'])\ .create_target('level_1_target.txt', signing_role='unclaimed')\ ...
nilq/baby-python
python
#!/usr/bin/env python import os import sys if __name__ == "__main__": if len(sys.argv) < 2: print("Uso: test_fs.py part_file_name") exit(1) # testa tamanho do FS virtual total statinfo = os.stat(sys.argv[1]) if statinfo.st_size != 4194304: print("Tamanho invalido. Deve ter exatamente 4Mb (41...
nilq/baby-python
python
''' 有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k。当然,我们希望得到的小段越长越好,你需要计算能够得到的小段木头的最大长度。 Example 样例 1 输入: L = [232, 124, 456] k = 7 输出: 114 Explanation: 我们可以把它分成114cm的7段,而115cm不可以 样例 2 输入: L = [1, 2, 3] k = 7 输出: 0 说明:很显然我们不能按照题目要求完成。 Challenge O(n log Len), Len为 n 段原木中最大的长度 Notice 木头长度的单位是厘米。原木的长度都是正整数,我们要求切割得到的小段木头...
nilq/baby-python
python
import logging from autobahn.twisted.websocket import WebSocketServerProtocol logger = logging.getLogger(__name__) class PsutilRemoteServerProtocol(WebSocketServerProtocol): def onConnect(self, request): logger.info("Client connecting: {}".format(request.peer)) def onOpen(self): logger.inf...
nilq/baby-python
python
DEFAULT_SYSTEM = 'frontera.tacc.utexas.edu'
nilq/baby-python
python
#!/usr/bin/env python3 """Positive Negative. Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. source: https://codingbat.com/prob/p162058 """ def pos_neg(a: int, b: int, negative: bool) -> bool: """Di...
nilq/baby-python
python
import numpy as np import pandas as pd from gensim.models import Word2Vec from sklearn.decomposition import TruncatedSVD from sklearn.model_selection import StratifiedKFold from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer def creat...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-01 05:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Interface', '0003_auto_20171201_0503'), ] operations = [ migrations.AddFiel...
nilq/baby-python
python