content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python3
import argparse
import logging
from pathlib import Path
import sys
from typing import Iterable
from typing import Union
import numpy as np
from espnet.utils.cli_utils import get_commandline_args
def aggregate_stats_dirs(
input_dir: Iterable[Union[str, Path]],
output_dir: Union[str, Pa... | nilq/baby-python | python |
import argparse
import parmed as pmd
def merge_gro_files(prot_gro, lig_gro, cmplx_gro):
prot = pmd.load_file(prot_gro)
lig = pmd.load_file(lig_gro)
cmplx = prot + lig
cmplx.save(cmplx_gro)
def merge_top_files(prot_top, lig_top, cmplx_top):
with open(lig_top, 'r') as f:
lig_top_sections ... | nilq/baby-python | python |
dictionary = {"name": "Shahjalal", "ref": "Python", "sys": "Mac"}
for key, value in dictionary.items():
print key, " = ", value
| nilq/baby-python | python |
def get_sum_by_route(route_val, nums):
sum_val = nums[0][0]
j = 0
route=[sum_val]
for i in range(1, len(nums)):
if route_val % 2 > 0:
j+=1
sum_val += nums[i][j]
route.append(nums[i][j])
route_val >>= 1
return route, sum_val
s = """75
95 64
17... | nilq/baby-python | python |
import numpy as np
from sort import algs
def test_bubblesort():
# 1) Test odd-sized vector + duplicate values
assert algs.bubblesort([1,2,4,0,1]) == [0,1,1,2,4]
# 2) Test even+duplicate values
assert algs.bubblesort([1,2,4,6,0,1]) == [0,1,1,2,4,6]
# 3) Test empty vector
assert algs.bubbleso... | nilq/baby-python | python |
from service.resolver_base import ResolverBase
from service.rule_item_mutex import RuleItemMutex
# 6宫无马数独
# DB 互斥规则已写入
class Resolver1623(ResolverBase):
ANSWER_RANGE = ['1', '2', '3', '4', '5', '6']
def get_answer_range(self) -> []:
return Resolver1623.ANSWER_RANGE
def calculate_rules(self):
... | nilq/baby-python | python |
from specusticc.data_preprocessing.preprocessed_data import PreprocessedData
from specusticc.model_testing.prediction_results import PredictionResults
class Tester:
def __init__(self, model, model_name: str, data: PreprocessedData):
self._model = model
self._data: PreprocessedData = data
s... | nilq/baby-python | python |
from .encodeClass import encoderClass
from .decodeClass import decoderClass
| nilq/baby-python | python |
import os
import uuid
from typing import Generator
from flask import current_app
from unittest import TestCase
from contextlib import contextmanager
from alembic import command
from sqlalchemy import create_engine
from {{ cookiecutter.app_name }} import app
from {{ cookiecutter.app_name }}.extensions import db
DATABA... | nilq/baby-python | python |
# #https://docs.pytest.org/en/reorganize-docs/new-docs/user/assert_statements.html
# # Assertions are the condition or boolean expression which are always supposed to be true
# import pytest
# def vowels():
# return set('aeiou')
# @pytest.mark.skip
# def test_vowels():
# result = vowels()
# expected = se... | nilq/baby-python | python |
#
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: December 29, 2020
#
"""It is utilities for Gaussian process regression and
Student-:math:`t` process regression."""
import numpy as np
from bayeso.utils import utils_common
from bayeso import constants
@utils_common.validate_types
def get_prior_mu(prior... | nilq/baby-python | python |
import rclpy,numpy,psutil
from rclpy.node import Node
from std_msgs.msg import Float32
class RpiMon(Node):
def __init__(self):
super().__init__('rpi_mon')
self.ramPublisher = self.create_publisher(Float32, 'freeram', 1)
timer_period = 2.0 # seconds
self.timer = self.create_timer(t... | nilq/baby-python | python |
from libspn.inference.type import InferenceType
from libspn.graph.op.base_sum import BaseSum
import libspn.utils as utils
@utils.register_serializable
class Sum(BaseSum):
"""A node representing a single sum in an SPN.
Args:
*values (input_like): Inputs providing input values to this node.
... | nilq/baby-python | python |
##############################################
##############################################
###### Predict the Bear ######################
# Flask app that uses a model trained with the Fast.ai v2 library
# following an example in the upcoming book "Deep Learning for Coders
# with fastai and PyTorch: AI Applications ... | nilq/baby-python | python |
import numpy as np
from nexpy.gui.datadialogs import NXDialog, GridParameters
from nexpy.gui.utils import report_error
from nexusformat.nexus import NXfield, NXdata, NeXusError
from nexusformat.nexus.tree import centers
def show_dialog():
try:
dialog = ConvertDialog()
dialog.show()
except NeXu... | nilq/baby-python | python |
from riemann.tx import tx_builder
from riemann import simple, script
from riemann import utils as rutils
from riemann.encoding import addresses
from workshop import crypto
from workshop.transactions import spend_utxo
from riemann import tx
'''
This is a hash timelock contract. It locks BTC until a timeout, or until ... | nilq/baby-python | python |
#!/usr/bin/env python
# Part of sniffMyPackets framework.
# GeoIP Lookup modules to cut down on code changes.
import pygeoip
from canari.config import config
def lookup_geo(ip):
try:
# homelat = config['geoip/homelat'].strip('\'')
# homelng = config['geoip/homelng'].strip('\'')
db = conf... | nilq/baby-python | python |
#python3 code
def count(i,s):
ans=0
for j in range(i,len(s)):
if(s[j]=="<"):
ans+=1
return ans
def higher(s):
res=0
for i in range(len(s)):
if(s[i]==">"):
b=count(i,s)
res=res+(b*2)
return res
def solution(s):
# Your code here
... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | nilq/baby-python | python |
if x == 'none':
if False:
print('None')
elif x == None:
print('oh')
elif x == 12:
print('oh')
else:
print(123)
if foo:
foo()
elif bar:
bar()
else:
if baz:
baz()
elif garply:
garply()
else:
qux()
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 地址:http: //www.runoob.com/python/python-exercise-example70.html
if __name__ == "__main__":
# s = input("please input a string:\n")
s = "Hello World"
print("the string has %d characters." % len(s))
| nilq/baby-python | python |
"""
Orchestrator module
"""
import logging
import os
import re
import shutil
import traceback
from functools import wraps
from glob import glob
from io import open
import six
from halo import Halo
from tabulate import tabulate
from toscaparser.common.exception import ValidationError
from yaml.scanner import ScannerErr... | nilq/baby-python | python |
#############################################################################
#
# VFRAME
# MIT License
# Copyright (c) 2020 Adam Harvey and VFRAME
# https://vframe.io
#
#############################################################################
import click
from vframe.settings.app_cfg import VALID_PIPE_MEDIA_EXT... | nilq/baby-python | python |
import os
import torch
import numpy as np
import warnings
try:
from typing import Protocol
except ImportError: # noqa
# Python < 3.8
class Protocol:
pass
from .dsp.overlap_add import LambdaOverlapAdd
from .utils import get_device
class Separatable(Protocol):
"""Things that are separatable.... | nilq/baby-python | python |
import pickle
import brewer2mpl
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from absl import app, flags
from utils import *
FLAGS = flags.FLAGS
flags.DEFINE_string('base_dir', '', 'Path to the base dir where the logs are')
... | nilq/baby-python | python |
# coding: utf-8
# # Table of Contents
# <p><div class="lev1 toc-item"><a href="#Blurring-a-part-of-an-image-in-Python" data-toc-modified-id="Blurring-a-part-of-an-image-in-Python-1"><span class="toc-item-num">1 </span>Blurring a part of an image in Python</a></div><div class="lev2 toc-item"><a href="#Blur... | nilq/baby-python | python |
import json
import logging
import requests
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import status
class ExternalUmbrellaServiceAuthenticationBackend:
logger = logging.getLogger(__name__)
def get_user(self, user_id):
"""
Retrieve the use... | nilq/baby-python | python |
# Copyright 2017,2018,2019,2020,2021 Sony Corporation.
#
# 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 |
from tclCommands.TclCommand import TclCommandSignaled
import collections
class TclCommandMirror(TclCommandSignaled):
"""
Tcl shell command to mirror an object.
"""
# array of all command aliases, to be able use
# old names for backward compatibility (add_poly, add_polygon)
aliases = ['mirror... | nilq/baby-python | python |
import torch.nn as nn
from qanet.encoder_block import EncoderBlock
class ModelEncoder(nn.Module):
def __init__(self, n_blocks=7, n_conv=2, kernel_size=7, padding=3,
hidden_size=128, conv_type='depthwise_separable', n_heads=8, context_length=400):
super(ModelEncoder, self).__init_... | nilq/baby-python | python |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self,root):
if not root:
return (0,0)
# get res from left
left=self.helper... | nilq/baby-python | python |
#%load_ext autoreload
#%autoreload 2
from pathlib import Path
from pprint import pformat
from hloc import extract_features, match_features, localize_inloc, visualization
dataset = Path('datasets/inloc/') # change this if your dataset is somewhere else
pairs = Path('pairs/inloc/')
loc_pairs = pairs / 'pairs-query-n... | nilq/baby-python | python |
from aws_cdk import (
aws_batch as _batch,
aws_ec2 as _ec2,
aws_iam as _iam,
core,
)
class BatchENV(core.Construct):
def getComputeQueue(self,queue_name):
return self.job_queue[queue_name]
def __init__(self, scope: core.Construct, id: str,CurrentVPC="default",TargetS3... | nilq/baby-python | python |
from vyper import basebot
from vyper.web import interface
import os
class PluginBot(basebot.BaseBot):
def __init__(self, token, debug=False, start_loop=False, loop_time=.05, ping=True, list_plugins=False, web_app=None, name=None):
if not os.path.exists('plugins'):
os.mkdir('plugins')
with open('plugins/__init... | nilq/baby-python | python |
import timeit
from copy import deepcopy
import time
import cProfile
import pstats
import numpy as np
from sympy import sin, symbols, Matrix, Symbol, exp, solve, Eq, pi, Piecewise, Function, ones
from CompartmentalSystems.moothmodel_run import SmoothModelRun
from CompartmentalSystems.smooth_reservoir_model import Smooth... | nilq/baby-python | python |
from django.contrib import admin
from .models import User, Agent
class UserAdmin(admin.ModelAdmin):
list_display = ['username', 'is_agent', 'is_superuser']
admin.site.register(User, UserAdmin)
admin.site.register(Agent)
| nilq/baby-python | python |
'''
'''
def main():
info('Pump Microbone After Jan diode analysis')
close(description="Jan Inlet")
close(description= 'Microbone to Minibone')
open(description= 'Microbone to Turbo')
open(description= 'Microbone to Getter NP-10H')
open(description= 'Microbone to Getter NP-10C')
o... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by Ruchir Chawdhry
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
from subprocess import run
from prettytable import PrettyTable
# PS: This only works on macOS & Linux. It will not work on W... | nilq/baby-python | python |
import os
import logging
from counterblock.lib import config
def set_up(verbose):
global MAX_LOG_SIZE
MAX_LOG_SIZE = config.LOG_SIZE_KB * 1024 #max log size of 20 MB before rotation (make configurable later)
global MAX_LOG_COUNT
MAX_LOG_COUNT = config.LOG_NUM_FILES
# Initialize logging (to file a... | nilq/baby-python | python |
from getpass import getpass
from pprint import pprint
from datetime import datetime
from sqlalchemy import create_engine
from pydango import state
from pydango.switchlang import switch
from pydango import (
primary_func,
secondary_func
)
from pydango.primary_func import chunks
from pydango.primary_func imp... | nilq/baby-python | python |
def _foo():
return "private" | nilq/baby-python | python |
from collections import defaultdict
from itertools import islice
from typing import Dict, List, Optional, Sequence
import torch
from tango.common.dataset_dict import DatasetDictBase
from tango.common.exceptions import ConfigurationError
from tango.common.lazy import Lazy
from tango.common.tqdm import Tqdm
from tango.... | nilq/baby-python | python |
import sproxel
from zipfile import ZipFile, ZIP_DEFLATED
import json
import os, sys
import imp
CUR_VERSION=1
def save_project(filename, proj):
# gather layers
layers=[]
for spr in proj.sprites:
for l in spr.layers:
if l not in layers: layers.append(l)
# prepare metadata
meta={... | nilq/baby-python | python |
import uuid
from django.db import models
class Dice(models.Model):
sides = models.PositiveIntegerField()
class Roll(models.Model):
roll = models.PositiveIntegerField()
class DiceSequence(models.Model):
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=True, unique=True)
seq_n... | nilq/baby-python | python |
class Solution(object):
def XXX(self, n):
"""
:type n: int
:rtype: str
"""
if not isinstance(n, int):
return ""
if n == 1:
return "1"
pre_value = self.XXX(n-1) # 递归
# 双指针解法
i = 0
res = ""
for ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.conf import settings
import requests
from sendsms.backends.base import BaseSmsBackend
TINIYO_API_URL = "https://api.tiniyo.com/v1/Account/SENDSMS_TINIYO_TOKEN_ID/Message"
TINIYO_TOKEN_ID = getattr(settings, "SENDSMS_TINIYO_TOKEN_ID", "")
TINIYO_TOKEN_SECRET = getattr(settings, "S... | nilq/baby-python | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch.nn as nn
from fairseq.models.transformer import TransformerEncoder
from .linformer_sentence_encoder_layer... | nilq/baby-python | python |
# file arrange, remove, rename
import os
import astropy.io.fits as fits
def oswalkfunc():
f=open('oswalk.list','w')
#workDIr = os.path.abspath(b'.')
for root, dirs, files in os.walk('.'): # os.walk(".", topdown = False):
# all files with path names
for name in files:
#print(os.path.join(root, name))... | nilq/baby-python | python |
from django.db import models
class TrackedModel(models.Model):
"""
a model which keeps track of creation and last updated time
"""
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
Created by 15 cm on 11/22/15 3:20 PM
Copyright © 2015 15cm. All rights reserved.
'''
__author__ = '15cm'
import json
import urllib2
import multiprocessing
import numpy as np
from PIL import Image
import io
import os
CURPATH = os.path.split(os.path.realpath(__file__))[0]
DATAPATH = os.path.... | nilq/baby-python | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .pygame_component import Pygame
from .pygame_surface import PygameSurface
from .blit_surface import BlitSurface
from .blocking_pygame_event_pump import BlockingPygameEventPump
from .color_fill import ColorFill
from .draw_on_resi... | nilq/baby-python | python |
#!/usr/bin/python
'''
(C) Copyright 2018-2019 Intel Corporation.
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 applic... | nilq/baby-python | python |
from UE4Parse.BinaryReader import BinaryStream
class FPathHashIndexEntry:
FileName: str
Location: int
def __init__(self, reader: BinaryStream):
self.FileName = reader.readFString()
self.Location = reader.readInt32()
| nilq/baby-python | python |
from typing import List
import cv2
from vision.domain.iCamera import ICamera
from vision.domain.iCameraFactory import ICameraFactory
from vision.infrastructure.cvCamera import CvCamera
from vision.infrastructure.cvVisionException import CameraDoesNotExistError
from vision.infrastructure.fileCamera import FileCamera
... | nilq/baby-python | python |
import contextlib
import logging
import six
import py.test
_LOGGING_CONFIGURED_STREAM = None
@py.test.fixture(scope="session")
def streamconfig():
global _LOGGING_CONFIGURED_STREAM
if not _LOGGING_CONFIGURED_STREAM:
_LOGGING_CONFIGURED_STREAM = six.StringIO()
logging.basicConfig(
... | nilq/baby-python | python |
import re
# Solution
def part1(data, multiplier = 1):
pattern = r'\d+'
(player_count, marble_count) = re.findall(pattern, data)
(player_count, marble_count) = (int(player_count), int(marble_count) * multiplier)
players = [0] * player_count
marbles = DoubleLinkedList(0)
k = 0
for i in range(... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import hexchat
import re
__module_name__ = "DeadKeyFix"
__module_version__ = "2.2"
__module_description__ = "Fixes the Us-International deadkey issue"
prev = ''
def keypress_cb(word, word_eol, userdata):
global prev
specialChars = {
'65104': {
'a': u'à',
'o': u'ò',
'e': u'è',
... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TREESPLITTER")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(0)
)
process.TreeSplitterModule = cms.EDAnalyzer(
"TreeSplitter",
InputFileName = cms.string("/afs/cern.ch/user/d/... | nilq/baby-python | python |
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from .ledger_close_value_signature import LedgerCloseValueSignature
from .stellar_value_type import StellarValueType
from ..exceptions import ValueError
__all__ = ["StellarValu... | nilq/baby-python | python |
import setuptools
def get_requires(filename):
requirements = []
with open(filename) as req_file:
for line in req_file.read().splitlines():
if not line.strip().startswith("#"):
requirements.append(line)
return requirements
with open("Readme.md", "r", encoding="utf8") a... | nilq/baby-python | python |
REGISTRY = {}
from .sc_agent import SCAgent
from .rnn_agent import RNNAgent
from .latent_ce_dis_rnn_agent import LatentCEDisRNNAgent
REGISTRY["rnn"] = RNNAgent
REGISTRY["latent_ce_dis_rnn"] = LatentCEDisRNNAgent
REGISTRY["sc"] = SCAgent
| nilq/baby-python | python |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Apache License Version 2.0.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright 2017 CPqD. 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 requi... | nilq/baby-python | python |
#
# @lc app=leetcode id=160 lang=python3
#
# [160] Intersection of Two Linked Lists
#
# https://leetcode.com/problems/intersection-of-two-linked-lists/description/
#
# algorithms
# Easy (39.05%)
# Likes: 3257
# Dislikes: 372
# Total Accepted: 438K
# Total Submissions: 1.1M
# Testcase Example: '8\n[4,1,8,4,5]\n[5... | nilq/baby-python | python |
def dividend(ticker_info):
for ticker, value in ticker_info.items():
value_dividends = value["dividends"].to_frame().reset_index()
dividend_groupped = value_dividends.groupby(value_dividends["Date"].dt.year)['Dividends'].agg(['sum'])
dividend_groupped = dividend_groupped.rename(c... | nilq/baby-python | python |
import markdown
from flask import abort, flash, redirect, render_template, request
from flask_babel import gettext as _
from flask_login import current_user, login_required
from ..ext import db
from ..forms.base import DeleteForm
from ..models import Brew, TastingNote
from ..utils.pagination import get_page
from ..uti... | nilq/baby-python | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from collections import OrderedDict
from teach.dataset.actions import (
Action_Audio,
Action_Basic,
Action_Keyboard,
Action_MapGoal,
Action_Motion,
Action_ObjectInteraction,
Action_Progres... | nilq/baby-python | python |
import collections
import pathlib
import sys
import os
import json
def as_dict(par):
if not par:
return None
if isinstance(par, dict):
return par
else:
return dict(par._asdict())
def from_dict(par_dict):
if not par_dict:
return None
# par = collections.namedtuple(... | nilq/baby-python | python |
import unittest
import ServiceGame
from model.Platform import platform
from model.Publishers import publisher
class TestServiceGame(unittest.TestCase):
def test_games_Wii(self):
wiigames = ServiceGame.platz(platform('Wii'))
self.assertEqual(15, len(wiigames))
def test_games_PC(self):
... | nilq/baby-python | python |
from robot_server.service.errors import RobotServerError, \
CommonErrorDef, ErrorDef
class SystemException(RobotServerError):
"""Base of all system exceptions"""
pass
class SystemTimeAlreadySynchronized(SystemException):
"""
Cannot update system time because i... | nilq/baby-python | python |
from flask import Flask, redirect, render_template, url_for
from flask_pymongo import PyMongo
import scrape_mars
app = Flask(__name__)
mongo=PyMongo(app, uri="mongodb://localhost:27017/mars_app")
@app.route("/")
def index():
mars_info = mongo.db.mars_info.find_one()
return render_template("index.html", mar... | nilq/baby-python | python |
import sys
with open(sys.argv[1]) as f:
data = f.read()
stack = []
for i in range(len(data)):
if i%1000000==0:
print("%.2f %%"%(i/len(data)*100))
stack += [data[i]]
if (len(stack)>=8 and
stack[-8] in "<" and
stack[-7] in "Ss" and
stack[-6] in "Cc" and
stack[-5] in "Rr" and
st... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np
import sys
from readFiles import *
thisfh = sys.argv[1]
linkerfh = "part_Im.xyz"
#Read the linker file
lAtomList, lAtomCord = readxyz(linkerfh)
sAtomList, sAtomCord = readxyz(thisfh)
a,b,c,alpha,beta,gamma = readcifFile(thisfh[:-4] + ".cif")
cell_params = [a, b, c... | nilq/baby-python | python |
import copy
import os
import random
import kerastuner
import kerastuner.engine.hypermodel as hm_module
import tensorflow as tf
from autokeras.hypermodel import base
class AutoTuner(kerastuner.engine.multi_execution_tuner.MultiExecutionTuner):
"""A Tuner class based on KerasTuner for AutoKeras.
Different fr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Lacework ContractInfo API wrapper.
"""
from laceworksdk.api.base_endpoint import BaseEndpoint
class ContractInfoAPI(BaseEndpoint):
def __init__(self, session):
"""
Initializes the ContractInfoAPI object.
:param session: An instance of the HttpSession class
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# Translated source for Order.
##
# Source file: Order.java
# Target file: Order.py
#
# Original file copyright original author(s).
# This file copyright Troy Melhase, troy@gci.net.
#
# WARNING: all changes to this file will be lost.
from ib.lib import Double, Integer... | nilq/baby-python | python |
"""
Wrap around the bottleneck distance executable from Dionysus, and provide
some utility functions for plotting
"""
import subprocess
import numpy as np
import matplotlib.pyplot as plt
import os
def plotDGM(dgm, color = 'b', sz = 20, label = 'dgm'):
if dgm.size == 0:
return
# Create Lists
# set a... | nilq/baby-python | python |
# foreign-state
| nilq/baby-python | python |
import tensorflow as tf
from tensorflow.python.platform import flags
import pandas as pd
import numpy as np
from pprint import pprint
from sklearn.model_selection import train_test_split
from data_postp.similarity_computations import transform_vectors_with_inter_class_pca
FLAGS = tf.python.platform.flags.FLAGS
METADA... | nilq/baby-python | python |
'''
bibtutils.slack.message
~~~~~~~~~~~~~~~~~~~~~~~
Enables sending messages to Slack.
'''
import os
import json
import logging
import requests
import datetime
logging.getLogger(__name__).addHandler(logging.NullHandler())
def send_message(webhook, title, text, color):
'''Sends a message to Slack.
.. code... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from datetime import timedelta
import re
import pymorphy2
import collections
def calc_popular_nouns_by_weeks(articles_info, nouns_count=3):
morph = pymorphy2.MorphAnalyzer()
words_by_weeks = _group_words_by_weeks(articles_info)
nouns_by_week = {}
for week in sorted(words_by_we... | nilq/baby-python | python |
"""
@UpdateTime: 2017/12/7
@Author: liutao
"""
from django.db import models
# Create your models here.
#产品表
class Product(models.Model):
p_id = models.AutoField(primary_key=True)
p_name = models.CharField(max_length=150)
p_money = models.IntegerField()
p_number = models.IntegerField()
p_info = mo... | nilq/baby-python | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import sys
import json
import pytest
from awsiot.greengrasscoreipc.model import (
JsonMessage,
SubscriptionResponseMessage
)
sys.path.append("src/")
testTokenJson = [
{
"id": "0895c16b9de9e... | nilq/baby-python | python |
from .property import LiteralProperty
import packaging.version as pv
import rdflib
class VersionProperty(LiteralProperty):
def convert_to_user(self, value):
result = str(value)
if result == '':
# special case, empty strings are equivalent to None
return None
return... | nilq/baby-python | python |
from __future__ import print_function, absolute_import
from os import getenv
from time import sleep
import click
import json
import getpass
from datetime import datetime, timedelta, timezone
from ecs_deploy import VERSION
from ecs_deploy.ecs import DeployAction, DeployBlueGreenAction, ScaleAction, RunAction, EcsCli... | nilq/baby-python | python |
"""helpers"""
import mimetypes
import os
import pkgutil
import posixpath
import sys
import time
import socket
import unicodedata
from threading import RLock
from time import time
from zlib import adler32
from werkzeug.datastructures import Headers
from werkzeug.exceptions import (BadRequest, NotFound,
... | nilq/baby-python | python |
import os
import numpy as np
from argparse import ArgumentParser
from pathlib import Path
from matplotlib import pyplot as plt
from matplotlib import colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pytorch_lightning import Trainer
from models.unet.unet import UNet
from configure import get_config
... | nilq/baby-python | python |
import datetime
import pymongo
client = pymongo.MongoClient('127.0.0.1', 27017)
db = client['qbot']
db.drop_collection('increase')
db.drop_collection('welcome')
db.create_collection('welcome')
db.welcome.insert_many([
{
'group_id': 457263503,
'type': 'card',
'icon': 'https://sakuyark.com/s... | nilq/baby-python | python |
import torch
import torch.nn as nn
from torch import optim
import mask_detector.trainer as trainer
from mask_detector.dataset import DatasetType, generate_train_datasets, generate_test_datasets
from mask_detector.models import BaseModel
from mask_detector.combined_predictor import Predictor_M1, submission_label_recalc
... | nilq/baby-python | python |
import logging
import os
import subprocess
import abc
from Bio.Sequencing import Ace
from .fasta_io import write_sequences
# compatible with Python 2 *and* 3:
ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})
try:
from tempfile import TemporaryDirectory
except ImportError:
from backports.tempfile import ... | nilq/baby-python | python |
import copy
from ..core.api import BaseFLKnowledgeDistillationAPI
class FedMDAPI(BaseFLKnowledgeDistillationAPI):
def __init__(
self,
server,
clients,
public_dataloader,
local_dataloaders,
validation_dataloader,
criterion,
client_optimizers,
... | nilq/baby-python | python |
import numpy as np
from pathfinding.core.diagonal_movement import DiagonalMovement
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
def max_pool(map, K):
# First, trim the map down such that it can be divided evenly into K by K square sections.
# Try to keep the trimmi... | nilq/baby-python | python |
import numpy as np
import os
from LoadpMedian import *
from LoadData import *
from gurobipy import *
from sklearn.metrics.pairwise import pairwise_distances
def kmedian_opt(distances, IP, k1, k2):
model = Model("k-median")
n = np.shape(distances)[0]
y,x = {}, {}
if IP:
var_type = GRB.BINARY
... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Created on 2 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.data.duplicates import Duplicates
from scs_core.data.json import JSONify
from scs_core.data.path_dict import PathDict
# ---------------------------------------------------------------------... | nilq/baby-python | python |
import validator.validator as validator
from validator.test.fixtures import Fixtures
class TestGetSchemaInfoFromPointer(object):
fxt = Fixtures('get_schema_info_from_pointer')
def do_fxt_test(self, fxt_path):
fixture = self.fxt.get_anymarkup(self.fxt.path(fxt_path))
obj = validator.get_schem... | nilq/baby-python | python |
#!/usr/bin/python
#####################################
### CIS SLOT FILLING SYSTEM ####
### 2014-2015 ####
### Author: Heike Adel ####
#####################################
import sys
import os
sys.path.insert(1, os.path.join(sys.path[0], '../../cnnScripts'))
import cPickle
import ... | nilq/baby-python | python |
from celery.schedules import crontab
from datetime import timedelta
from decimal import Decimal
import logging
DEBUG = True
TESTING = False
ASSETS_DEBUG = True
CSRF_SESSION_KEY = "blahblahblah"
SECRET_KEY = "blahblahblah"
GEOCITY_DAT_LOCATION = "/scout/scout/libs/GeoLiteCity.dat"
LOGGING_LEVEL = logging.DEBUG
LOGGING_... | nilq/baby-python | python |
import logging
import os
import csv
from typing import List
from ... import InputExample
import numpy as np
logger = logging.getLogger(__name__)
class CEBinaryAccuracyEvaluator:
"""
This evaluator can be used with the CrossEncoder class.
It is designed for CrossEncoders with 1 outputs. It ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/8/6
@Author : AnNing
"""
import os
import h5py
import matplotlib.pyplot as plt
import numpy as np
from lib.lib_read_ssi import FY4ASSI, FY3DSSI
from lib.lib_database import add_result_data, exist_result_data
from lib.lib_proj import fill_points_2d_nan... | nilq/baby-python | python |
# Problem: https://docs.google.com/document/d/1B-bTbxNllKj0wbou5h4iaLyzgW3EbF3un0-5QKLVcy0/edit?usp=sharing
h=int(input())
w=int(input())
for _ in range(h):
for _ in range(w):
print('O',end='')
print()
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.