text stringlengths 2 999k |
|---|
from typing import Type, Tuple
from wai.annotations.core.component import ProcessorComponent
from wai.annotations.core.domain import DomainSpecifier
from wai.annotations.core.specifier import ProcessorStageSpecifier
class SubImagesISPSpecifier(ProcessorStageSpecifier):
"""
Specifies the sub-images ISP.
"... |
import numpy as np
from multiagent.core import World, SkilledAgent, Landmark
from multiagent.scenario import BaseScenario
from multiagent.utils import bound_reward, ObsDecorator
class Scenario(BaseScenario):
def make_world(self, **kwargs):
self.before_make_world(**kwargs)
world = World()
... |
def clean_filename(filename):
if not filename:
return filename
exclusions = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '+']
filename = ''.join(s for s in filename if s not in exclusions)
return filename.rstrip()
|
"""Setup file"""
import setuptools
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
setuptools.setup(
name="rival_regions_wrapper",
version="1.3.2",
author="Joost Sijm",
author_email="joostsijm@gmail.com",
description="Rival Regions API wrapper",
long_description=LONG_DESCR... |
from transformers import AutoModel, AutoTokenizer
import numpy as np
import torch
class BertSimilarity:
def __init__(self):
# self.model_name_or_path = "DeepPavlov/rubert-base-cased-sentence"
self.model_name_or_path = "/rubert"
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"... |
#!/usr/bin/env python3
import torch
import unittest
from gpytorch.lazy import BlockDiagLazyTensor, NonLazyTensor
from test.lazy._lazy_tensor_test_case import LazyTensorTestCase
class TestBlockDiagLazyTensor(LazyTensorTestCase, unittest.TestCase):
seed = 0
should_test_sample = True
def create_lazy_tensor... |
from .TagAlternateChoice import TagAlternateChoice
from .IfTag import IfTag
from .ElifTag import ElifTag
from .ElseTag import ElseTag
from ..exceptions import TagsubTemplateSyntaxError
class IfTagContainer(TagAlternateChoice):
tag = "if"
def __init__(self, tagchar, template):
super().__init__(tagchar, t... |
def call_consensus_sequences_mask_reference_bases(roots, ref, bams):
''' roots is a list of base names '52_Late', ref is full path to reference .fa (or just filename if in cwd) '''
''' bams is list of full paths to alignment files (or filenames if in cwd) '''
''' output files to cwd '''
''' requires... |
#!/bin/python3
from collections import Counter
# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
print("Yes") if Counter(note) - Counter(magazine) == {} else print("No")
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = inp... |
from django.urls import path, include
from .tables import urls as table_urls
from .views import urls as view_urls
from .fields import urls as field_urls
from .rows import urls as row_urls
app_name = 'baserow.contrib.database.api'
urlpatterns = [
path('tables/', include(table_urls, namespace='tables')),
path(... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_analysis.ipynb (unless otherwise specified).
__all__ = ['calculate_doublingtimes']
# Cell
import pandas as pd
import numpy as np
# Cell
def calculate_doublingtimes(df:pd.DataFrame, col_suffix:str='cumCases',
median_incubation_period:float=5.2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import pprint
import sys
import time
import traceback
import giturlparse
import yaml
from inlineplz import interfaces
from inli... |
import torch
from torch.nn.functional import grid_sample
import math
def back_project(coords, origin, voxel_size, feats, KRcam, use_sparse_method1=False, depth_im=None):
'''
Unproject the image fetures to form a 3D (sparse) feature volume
:param coords: coordinates of voxels,
dim: (num of voxels, 4) (... |
#=========================================================================
# srl
#=========================================================================
import random
from pymtl3 import *
from .inst_utils import *
#-------------------------------------------------------------------------
# gen_basic_test
#------... |
# -*- coding: utf-8 -*-
from mahjong.hand_calculating.yaku import Yaku
from mahjong.utils import is_pon, is_sou, is_pin, is_man, simplify
class SanshokuDoukou(Yaku):
"""
Three pon sets consisting of the same numbers in all three suits
"""
def __init__(self, yaku_id=None):
super(SanshokuDoukou... |
# Script to generate HTML (and javascript) file for searching through sentence
# completion norms.
#
# Run with:
#
# $ python3 makehtml.py
#
# which will result in a self-contained sentences.html file that can be opened with
# a web browser.
path = 'sentences.html'
f = open(path, 'w')
longStr = """
<!DOCTYPE html>
... |
# Copyright 2017 Google 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 or agreed to in writing, ... |
# Copyright (c) 2020 mingruimingrui
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
"""LASER LSTM sequence encoder"""
import torch
from torch import nn
from typ... |
# coding=utf-8
# pylint: disable-msg=E1101,W0612
import pytest
from datetime import datetime
from numpy import nan
import numpy as np
from pandas import Series
from pandas.core.indexes.datetimes import Timestamp
import pandas._libs.lib as lib
from pandas.util.testing import assert_series_equal
import pandas.util.t... |
# -*- coding: utf-8 -*-
#
# Configuration file for Sphinx builds for the zhmcclient project.
#
# Originally created by sphinx-quickstart, but then manually maintained.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... |
from .attentive_encoder import TransformerEncoder
from .nonauto_encoder import NonAutoATTEncoder
from .rnn_encoder import RNNEncoder
MODEL_CLS = {
'rnn': RNNEncoder,
'att': TransformerEncoder,
'non-att': NonAutoATTEncoder
}
def get_encoder(model: str, **kwargs):
if model.lower() not in MODEL_CLS:
... |
# coding=utf-8
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRe... |
import torch as T
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import math
class routing(nn.Module):
def __init__(self, D, n_in, n_out, in_dim, out_dim, device):
super(routing, self).__init__()
self.D = D
self.in_dim = in_dim
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 16:00:04 2020
@author: islam
"""
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from DF_Training import computeBatchCounts, fairness_loss, sf_loss, prule_loss
from fairness_metrics import computeE... |
# Generated by Django 3.1 on 2021-01-27 06:40
import api.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='room',
name='code',
... |
#!/usr/bin/env python
# Copyright (c) 2021-2021 The Studscoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import os, sys
from subprocess import check_output
def countRelevantCommas(line):
openParensPosStack = [... |
""" Functions connected to signing and verifying.
Based on the use of xmlsec1 binaries and not the python xmlsec module.
"""
import base64
import datetime
import dateutil
import hashlib
import itertools
import logging
import os
import re
import six
import sys
from uuid import uuid4 as gen_random_key
from time import ... |
from __future__ import unicode_literals
import io
import yaml
import logging
import os
from . import errors
ENV_VAR_TRITON_ZMQ_HOST = 'TRITON_ZMQ_HOST'
ENV_VAR_TRITON_ZMQ_PORT = 'TRITON_ZMQ_PORT'
ZMQ_DEFAULT_HOST = '127.0.0.1'
ZMQ_DEFAULT_PORT = 3515
log = logging.getLogger(__name__)
REQUIRED_CONFIG_KEYS = ['name',... |
annotation_zip = tf.keras.utils.get_file('captions.zip',
cache_subdir=os.path.abspath('.'),
origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',
extract = True)
an... |
#Result is 648
def bang(num):
r = 1
for i in range(1, num+1): r *= i
return r
t = 0
for i in str(bang(100)): t += int(i)
print t |
import os
import sys
import uuid
import common
import traceback
import numpy as np
from PIL import Image
from enums import*
from common import*
from common_config import Common_config
from common import str2bool, delete_all_uploaded
config = Common_config()
root_direc = config.get_root_path()
max_file_size = 3750000
... |
import torch
from torch import nn
import torch.nn.functional as F
import math
from backbone.repvgg import get_RepVGG_func_by_name
import utils
class SixDRepNet(nn.Module):
def __init__(self,
backbone_name, backbone_file, deploy,
bins=(1, 2, 3, 6),
droBatchNorm=nn.... |
from ircu import p10
from ircu import server
from ircu import util
class MessageHandler(p10.MessageHandler):
token = 'S'
command = 'SERVER'
def __init__(self, *args, **kwargs):
super(MessageHandler, self).__init__(*args, **kwargs)
def unreg(self, client, source, args):
# newton.ircpl... |
# Copyright 2019 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# As we are using python, this challenge is identical to a previous one.
input()
print(sum(map(int, input().split())))
|
from typing import List
import databases
from sqlalchemy import MetaData, Table, Column, Integer, Float, String, create_engine
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy_utils import drop_database, create_database, database_exists
from fastapi_crudrouter import DatabasesCRUDRouter
fro... |
# 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 ... |
# ./gft.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:e92452c8d3e28a9e27abfc9994d2007779e7f4c9
# Generated 2018-09-07 17:35:53.618209 by PyXB version 1.2.6 using Python 3.6.4.final.0
# Namespace AbsentNamespace0
from __future__ import unicode_literals
import pyxb
import pyxb.binding
import pyxb.binding.saxer
impor... |
from argparse import ArgumentParser, RawTextHelpFormatter
from .user_config_mgr import UserConfigManager
if __name__ == "__main__":
description = """Directly manipulate items in user config"""
parser = ArgumentParser(description=description,
prog='GCRCatalogs.user_config',
... |
#Pilas
"""
Una pila es una lista ordenada o estructura de datos en la que el modo de acceso a sus elementos es de tipo LIFO (Last In First Out, ultimo en entrar es el primero en salir) que permite almacenar datos.
Para el manejo de los datos se cuenta con dos operaciones basicas: apilar(push), que coloca un objeto... |
# coding: utf-8
import sys
import gettext
import pycountry
from django.conf import settings
from django.forms import MultipleChoiceField
from django.contrib.admin.widgets import FilteredSelectMultiple
from .countries_list import ALL_COUNTRIES, EXTRA_COUNTRIES
class CountriesFormField(MultipleChoiceField):
""" Пол... |
import random
from commons.town import get_town_with_max_hazard
def large_neighborhood_search(facilities: list, towns: list, hazards: list, max_iteration: int = 50, max_improvement: int = 10) -> tuple:
"""
Implements a local search on the solution obtained by the greedy.
This algorithm is inspired ... |
def read(prompt: str) -> str:
return input(prompt)
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
class Foo(object):
__slots__ = (<warning descr="'foo' in __slots__ conflicts with a class variable">'foo'</warning>, 'bar')
foo = 1 |
import os
import gym, roboschool
from gym.spaces.box import Box
from baselines import bench
from baselines.common.atari_wrappers import make_atari, wrap_deepmind
try:
import pybullet_envs
import roboschool
except ImportError:
pass
def make_env(env_id, seed, rank, log_dir):
def _thunk():
pri... |
import numpy as np
import cv2
import pickle
__author__ = "Sachin Mehta"
class LoadData:
'''
Class to laod the data
'''
def __init__(self, data_dir, classes, cached_data_file, normVal=1.10):
'''
:param data_dir: directory where the dataset is kept
:param classes: number of class... |
import asyncio
import json
import logging
import random
import time
import traceback
from asyncio import CancelledError
from pathlib import Path
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
from blspy import AugSchemeMPL, PrivateKey
from packaging.version import Version
from chia.conse... |
import os
# import sqlite3
from django.db import connection, transaction
path = './filestxt'
def limpar_tabelas():
try:
cursor = connection.cursor()
cursor.execute('TRUNCATE core_alimento, core_arquivo')
print('Limpeza das tabelas concluída.')
except:
print('Não possivel cone... |
# Copyright (c) 2019 NVIDIA Corporation
import torch
from torch.autograd import Variable
import torch.nn.functional as F
@torch.jit.script
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
n_channels_int = n_channels[0]
in_act = input_a + input_b
t_act = torch.tanh(in_act[:, :n_channels_i... |
import argparse
class ActionNoYes(argparse.Action):
def __init__(self,
option_strings,
dest,
nargs=0,
const=None,
default=None,
type=None,
choices=None,
required=False,
... |
# Copyright (c) 2020 Room 525 Research Group, Zhejiang University.
# All Rights Reserved.
import paddle.fluid as fluid
import os
import sys
sys.path.insert(1, os.path.dirname(__file__))
from openKS_distributed import KSDistributedFactory
from openKS_distributed.base import RoleMaker
from openKS_strategy... |
example_inst = dict(
tags={'Name': 'example_inst'},
connection={'user': 'ubuntu'},
instance_type='t2.small',
ami='ami-efd0428f',
)
config = dict(
variable=dict(
vpc_id={}
),
resource=dict(
aws_instance=dict(
example_inst=example_inst
)
)
)
|
# -*- coding: future_fstrings -*-
#
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Di... |
# -*- coding: utf-8 -*-
def main():
x = int(input())
if x == 3 or x == 5 or x == 7:
print('YES')
else:
print('NO')
if __name__ == '__main__':
main()
|
import time
import logging
from pathlib import Path
# DEBUG: Detailed debug information
# INFO: Things working as intended
# WARNING: Something unexpected happened
# ERROR: The software cannot perform some function
# CRITICAL: Program crashes for example
# Setup the logger
logger = logging.getLogger(__name__)
logger.... |
from pyobjus import autoclass
# First we load NSString into pyobjus
NSString = autoclass('NSString')
# Then we can call some class methods of NSString
text = NSString.stringWithUTF8String_('some string')
# Now we can call instance methods
print text.UTF8String()
# If you want to improve performance of you app, cons... |
# Author: Jakub Zalas
# License: MIT https://opensource.org/licenses/MIT
import sys,os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources', 'lib'))
from urlparse import parse_qsl
from tvseriesonlinepl import list
from threading import Thread
import urllib
import xbmcgui
import xbmcplugin
import urlr... |
from os import remove
from tempfile import NamedTemporaryFile
from asynctest import TestCase as AsyncTestCase, mock as async_mock
from ...core.in_memory import InMemoryProfile
from ...ledger.base import BaseLedger
from ...ledger.error import LedgerError
from ...wallet.base import BaseWallet
from .. import ledger as ... |
""" --- Day 4: Passport Processing ---
Part 1:
Count the number of valid passports - those that have all required fields.
Treat cid as optional. In your batch file, how many passports are valid?
Part 2:
Count the number of valid passports - those that have all required fields
and valid values. Continue to treat cid a... |
"""
These are a set of drivers for the XL-MaxSonar EZ series of sonar modules.
The devices have a few different ways of reading from them, and the these drivers attempt to cover
some of the methods
"""
import wpilib
from . import driver_base
from . import units
class MaxSonarEZPulseWidth(wpilib.SensorBase, driver_ba... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# 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 with... |
import os
import argparse
import gc
from PIL import Image
import numpy as np
import torch
from torchvision.transforms.functional import to_tensor, to_pil_image
from model import Generator
gc.collect()
torch.backends.cudnn.enabled = False
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = ... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationE... |
"""A command-line client for server.py."""
# pylint: disable=broad-except
import json
import sys
import time
import requests
from sailor_fox.helpers import get_prefix
def main():
"""Main method to start the bot."""
with open("config.json") as config_file:
config = json.load(config_file)
pref... |
# Copyright 2020 Red Hat, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from decimal import Decimal
from test_framework.test_framework imp... |
ranks = [ 0, 1, 2, 3, 4, 5 ]
straights = []
for i in range(13):
straight = [(j + i) % 13 for j in range(5)]
straight.sort()
print(i, straight)
|
#!C:\pycharmproject\profilepage\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
s... |
"""Generated message classes for apikeys version v2alpha1.
Manages the API keys associated with developer projects.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import... |
#!/usr/bin/env python
#
# Copyright (c) 2017-2018 Nest Labs, Inc.
# Copyright (c) 2019 Google, LLC.
# 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
#... |
"""
WSGI config for djangoProject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO... |
"""Matplotlib distplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
import numpy as np
from ....stats.density_utils import get_bins
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwa... |
import numpy as np
import h5py
from examples.seismic import AcquisitionGeometry, Model
from examples.seismic.acoustic import AcousticWaveSolver
from fwi.azureio import load_blob_to_hdf5
from fwi.io import Blob
from fwi.solvers import DensityWaveSolver, DensityModel
def overthrust_solver_iso(h5_file, kernel='OT2', t... |
# Número por Extenso
cont = ('zero','um','dois','três', 'quatro ',
'cinco', 'seis', 'sete', 'oito', 'nove',
'dez', 'onze', 'doze', 'treze', 'catorze',
'quinze', 'dezesseis', 'dezessete','dezoito',
'dezenove', 'vinte ')
while True:
número = int(input(' Digite um número entre 0 a 2... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import FWCore.ParameterSet.Config as cms
#FEVT
RecoLocalFastTimeFEVT = cms.PSet(
outputCommands = cms.untracked.vstring(
'keep *_ftlUncalibratedRecHits_*_*',
'keep *_ftlRecHits_*_*',
'keep *_mtdUncalibratedRecHits_*_*',
'keep *_mtdRecHits_*_*',
)
)
#RECO content
Reco... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class Employee(models.Model):
_inherit = 'hr.employee'
resume_line_ids = fields.One2many('hr.resume.line', 'employee_id', string="Resumé lines")
employee_skill_ids = fi... |
"""
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Input: root = [1,null,2,3]
Output: [3,2,1]
Post-order traversal is to traverse the left subtree first. Then traverse the right subtree. Finally, visit the root.
For example, for the following tree result will be [A, C, E, D, B, ... |
"""
Distributed under the MIT License. See LICENSE.txt for more info.
"""
from django.test import TestCase
from ..models import User, UserRole, Role
from ..utility import get_admins
class TestGetAdmin(TestCase):
"""
Class to test get admin
"""
def test_get_admins_no_admin(self):
"""
... |
#!/usr/bin/env python3
from torch import Tensor
from ..utils.broadcasting import _mul_broadcast_shape
from ..utils.memoize import cached
from .lazy_tensor import LazyTensor
from .non_lazy_tensor import lazify
from .zero_lazy_tensor import ZeroLazyTensor
# from .broadcasted_lazy_tensor import BroadcastedLazyTensor
c... |
# -*- coding: utf-8 -*-
'''
Execute batch runs
'''
# Import python libs
from __future__ import absolute_import, print_function
import math
import time
import copy
# Import salt libs
import salt.client
import salt.output
import salt.exceptions
from salt.utils import print_cli
# Import 3rd-party libs
# pylint: disable... |
import os
import sys
from onmt.modules.walsinfo import WalsInfo
path = sys.argv[1]
dirs = os.listdir(path)
wals_dir = sys.argv[2]
codes_path = os.path.join(wals_dir, "codes.csv")
languages_path = os.path.join(wals_dir, "languages.csv")
parameters_path = os.path.join(wals_dir, "parameters.csv")
with open(codes... |
'''
Advent of Code - 2015
--- Day 4: The Ideal Stocking Stuffer ---
'''
from hashlib import md5
def part1(key='ckczppom'):
for i in range(1000000):
h = md5((key + str(i)).encode()).hexdigest()
if h[:5] == '00000':
return i
def part2(key='ckczppom'):
for i in range(100000000):
... |
import csv
from collections import Counter, defaultdict
import itertools
import os
import re
from poi_interlinking import config, helpers
def extract_freqterms(fname, encoding, exp_path):
"""Extract and count occurrences of all distinct terms found in ``fname`` file and sort them in descending order.
Parame... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
constants.py
"""
from binascii import unhexlify, hexlify
from BitVector import *
import logging
log = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-4s %(levelname)-4s %(message)s')
handler.setFormatter(formatte... |
"""Simple Python Chunker
Usage
from chunker import chunk_sentences
chunked_sentences = chunk_sentences(sentences)
chunked_sentences = chunk_sentences(sentences, terms)
The optional terms argument allows you to hand in a dictionary of terms indexed
on their beginning offsets. With this dictionary, terms are ... |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'sequencing.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
]
|
from __future__ import print_function
import requests
import threading
import datetime
import json
import math
from .api_service import *
ONE_KILOMETER = 1000
FIVE_KILOMETERS = 5000
TOTAL_DISTANCE = 0
MATRIX_SIZE = 5
start_lat = 0
start_lon = 0
w, h = MATRIX_SIZE, MATRIX_SIZE
mat = [[0 for x in range(w)] for y in ... |
import numpy as np
from get_dictionaries import *
import pandas as pd
def meilleur_score(d,n):
liste=[]
new_d={}
for k, v in sorted(d.items(), key=lambda x: x[1]):
liste.append([k,v])
liste.reverse()
for i in range(n):
new_d[liste[i][0]]=liste[i][1]
return new_d
def average_pop... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import uuid
from enum import Enum, unique
from typing import Any, ClassVar, Dict, List, Optional, Set, Tuple, Type, Union, cast
import boto3
from botocore.exceptions import ClientError... |
import torch
import torch.utils.data as data
import os, math, random
from os.path import *
import numpy as np
from glob import glob
import utils.frame_utils as frame_utils
from scipy.misc import imread, imresize
class StaticRandomCrop(object):
def __init__(self, image_size, crop_size):
self.th, self.tw ... |
from utils import validate_address
from driver import netcat
try:
from django.conf import settings
except ImportError:
import settings
import logging
def pl_switch(address, value):
if value not in ["on", "off"]:
raise ValueError("Switch value must be 'on' or 'off'")
validate_address(addres... |
'''
Add webserver to all app/modules
Author: Klaus Bild
E-Mail: klaus.bild@gmail.com
Blog: http://kbild.ch
Version: 5.5
Date: 05/26/2016
License: Apache 2.0
Does only work on Windows if Regional Settings are set to English
'''
import ibmcnx.appServer
WS1 = ibmcnx.appServer.WasServer... |
import logging
import re
from git import Repo
from . import constants as C
from . import wish
logger = logging.getLogger(__name__)
def get_wishes(wishlist_file=C.wishlist):
"""
click command 'ls'
Returns list of wishes
"""
_regex = C.wish_regex
wishlist = []
with open(wishlist_file, 'r')... |
#!/usr/bin/env python3
# license removed for brevity
#策略 機械手臂 四點來回跑
import threading
import time
import rospy
import os
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
import math
import enum
import Hiwin_RT605_ArmCommand_Socket as ArmTask
##----Arm state----... |
"""Runs the CAGECAT web service
Author: Matthias van den Belt
"""
# own project imports
from cagecat import app
### main code
if __name__ == "__main__":
app.run()
|
"""
Copyright 2017-present, Airbnb 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 or agreed to in writing, sof... |
"""backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.