text stringlengths 2 999k |
|---|
from ._event import Event
class MoveBar(Event):
UP = "BAR_UP"
DOWN = "BAR_DOWN"
LEFT = "BAR_LEFT"
RIGHT = "BAR_RIGHT"
ID = "BAR_MOVE_BAR"
def __init__(self, value):
super().__init__(self.ID, value)
|
class Solution(object):
def XXX(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return 0
start = 1
end = x
while(start <= end):
mid = start + (end - start)/2
if (mid **2) == x:
return mid
... |
import logging
from nmigen import *
from nmigen.hdl.cd import ClockDomain
from nmigen.hdl.rec import Record
from ....gateware.pads import *
from ....gateware.pll import *
from ... import *
class VGAOutput(Elaboratable):
def __init__(self, pads):
self.pads = pads
self.hs = Signal()
self.v... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.execute('CREATE INDEX tracker_rank_year_category_position_lte on tracker_rank ... |
import json
from django.conf import settings
from hippoapi.utils.key import AppSetting
from host.models import Host
from .main import app
@app.task(name='schedule_task')
def schedule_task(cmd, hosts_ids):
"""计划任务"""
hosts_objs = Host.objects.filter(id__in=hosts_ids)
result_data = []
private_key, pub... |
import pyOcean_cpu as ocean
# Create an index based on A
A = ocean.int64([1,2,3])
idx = ocean.index[A]
# Make sure that the tensor is properly detached
A.fill(5)
# Apply the index
print(idx)
b = ocean.arange(10)
print(b[idx])
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Package'
db.create_table(u'parsr_package', (
... |
import copy
import json
import os
import pytest
import tempfile
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
from requests import HTTPError
from RPA.Robocorp.WorkItems import (
BaseAdapter,
EmptyQueue,
FileAdapter,
RobocorpAdapter,
State,
WorkItems,
... |
from collections import defaultdict, OrderedDict
import copy
import datetime
import logging
import time
import numpy as np
from . import mask as maskUtils
logger = logging.getLogger(__name__)
class COCOeval:
# Interface for evaluating detection on the Microsoft COCO dataset.
#
# The usage for CocoEval ... |
#!/usr/bin/env python3
# Copyright (c) 2019 The PIVX developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Performs the same check as in Test_02 verifying that zPoS forked blocks that stake a zerocoin which is spent on ma... |
#
# -*- py-indent-offset:2 -*-
from logging import ERROR, WARN, INFO, DEBUG
import copy
import re
from block import *
from block_cfg_utils import *
query_var_re = re.compile('^\\$\\{(.+)\\}$')
PROPERTIES = [
required_prop('database', validator=str,
help='The name of the mongo db database'),
req... |
import numpy as np
import cv2
#red detection
vid = cv2.VideoCapture(0) #Webcam=0
while True:
_, frame = vid.read() #_ is used for those returned things whch are of no use
# HSV = HUE, SATURATION, VALUE
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([0,70,50]) #provides a range
u... |
import copy
import numpy as np
import pytest
import qcelemental as qcel
from qcelemental.testing import compare_molrecs
_schema_prov_stamp = {'creator': 'QCElemental', 'version': '1.0', 'routine': 'qcelemental.molparse.from_schema'}
@pytest.mark.parametrize("inp,expected", [
({
'frag_pattern': [[0], [1]... |
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
version = __import__('instant').__version__
setup(
name='django-instant',
packages=fin... |
# Generated by Django 3.1.2 on 2020-10-06 15:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django102', '0002_game_level_of_difficulty'),
]
operations = [
migrations.AlterField(
model_name='game',
... |
from __future__ import print_function
# bangyoulater plugin by AliAbdul
from Plugin import Movie, Plugin
import re
import urllib2
##################################################
class bangYouLaterSub(Plugin):
def __init__(self, name, url):
self.url = url
self.moreEntries = True
Plugin.__init__(self, name, ... |
import logging
import typing as tp
from collections import namedtuple, OrderedDict
import numpy as np
from pgdrive.utils import get_np_random
PGBoxSpace = namedtuple("PGBoxSpace", "max min")
PGDiscreteSpace = namedtuple("PGDiscreteSpace", "number")
PGConstantSpace = namedtuple("PGConstantSpace", "value")
"""
This fi... |
import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models
from common.managers import UserManager
class TimestampedModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_on = models.DateTimeField(auto_now_add=True)
upd... |
import functools
import io
import pickle
from pathlib import Path
import pytest
import torch
from builtin_dataset_mocks import parametrize_dataset_mocks, DATASET_MOCKS
from torch.testing._comparison import assert_equal, TensorLikePair, ObjectPair
from torch.utils.data.datapipes.iter.grouping import ShardingFilterIterD... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
"""
Functions for reversing a regular expression (used in reverse URL resolving).
Used internally by Django and not intended for external use.
This is not, and is not intended to be, a complete reg-exp decompiler. It
should be good enough for a large class of URLS, however.
"""
import re
# Mapping of an escape charact... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
#LA SETENCIA FOR (PARA)
# Puede hacer recorridos mas eficientes en codigo de listas.
#Ejemplo de Comparación con while.
numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
indice = 0
while(indice < len(numeros)):
print(numeros[indice])
indice += 1
#Ahora con FOR
for numero in numeros:
print(numero)
#EJEMPLO
indic... |
import networkx as nx
def digital_plumber(inp):
graph = nx.Graph()
for line in inp:
left, right = line.split(' <-> ')
left = int(left)
for r in map(int, right.split(', ')):
graph.add_edge(left, r)
return len(nx.components.node_connected_component(graph, 0)), len(list(nx... |
from typing import Optional
from typing import Sequence
from typing import Union
from clikit.api.io import IO
from poetry.poetry import Poetry
from poetry.utils._compat import Path
from poetry.utils._compat import decode
from poetry.utils._compat import urlparse
class Exporter(object):
"""
Exporter class to... |
import numpy as np
import time
from field_ops import Engine2 as Engine
n = 100
v = np.linspace(0, 1, n)
x, y, z = np.meshgrid(v, v, v, indexing='ij')
# setup simulation engine
sim = Engine()
# allocate variables
c = sim.zeros([], [n,n,n], float)
c_hat = sim.zeros([], [n,n,n], complex)
u = sim.zeros([3], [n,n,n], flo... |
# 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 ... |
######################################################################
######################################################################
# Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2016 #
######################################################################
####################################... |
# Generated by Django 2.2.5 on 2019-10-07 17:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('smart_contract', '0038_auto_20191006_1535'),
]
operations = [
migrations.AlterField(
model_name='useraccept',
name='... |
import mock
from moto.athena import mock_athena
from oedi.AWS.athena import OEDIAthena
@mock_athena
@mock.patch("oedi.AWS.athena.Connection")
def test_oedi_athena__properties(mock_connection):
staging_location = "s3://my-testing-bucket/"
region_name = "us-west-2"
athena = OEDIAthena(staging_location, re... |
import traceback
def exception_to_string(excp):
stack = traceback.extract_stack()[:-3] + traceback.extract_tb(excp.__traceback__) # add limit=??
pretty = traceback.format_list(stack)
return ''.join(pretty) + '\n {} {}'.format(excp.__class__,excp)
|
# make a gif from the stored images
import imageio
robot_name = 'sawyer'
images = []
for _ in range(51, 250):
filename = "data/{}-contact-force-visual-{}-force.png".format(robot_name, _)
images.append(imageio.imread(filename))
imageio.mimsave('data/{}-contact-visual-force.gif'.format(robot_name), images) |
import os
import sys
dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.append(dir)
sys.path.append(f'{dir}/app')
|
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for ``flocker.common.plugin``
"""
from pyrsistent import PClass, field
from flocker.testtools import TestCase
from ..plugin import (
PluginLoader,
PluginNotFound,
MissingPluginAttribute,
InvalidPluginType,
)
class DummyDescription... |
# Copyright 2014 Midokura SARL
#
# 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... |
import random
from django.db import transaction
from django.core.management.base import BaseCommand
from core.models import *
from core.factories import *
from django.contrib.contenttypes.models import ContentType
NUM_CATEGORIES = 5
NUM_COURSES = 10
NUM_SECTIONS = 50
NUM_SESSION = 150
NUM_QUESTIONS = 100
class Co... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.allProjects, name='projects'),
path('<int:project_id>/', views.projectDetail, name='projectDetail')
]
|
__title__ = "murmurhash"
__version__ = "1.0.6"
__summary__ = "Cython bindings for MurmurHash"
__uri__ = "https://github.com/explosion/murmurhash"
__author__ = "Matthew Honnibal"
__email__ = "matt@explosion.ai"
__license__ = "MIT"
|
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
# 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.
# -----------------------------------------------------... |
#
# @lc app=leetcode id=118 lang=python3
#
# [118] Pascal's Triangle
#
# @lc code=start
class Solution:
def generate(self, numRows: int) -> [[]]:
# 当numRows为0时, 返回空list
if not numRows: return []
elif numRows == 1: return [[1]]
elif numRows == 2: return [[1], [1,1]]
# 注意为res... |
import itertools
from .base import Package
class FedEx(Package):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:22].lstrip('0') + self.barcode[22:]
@property
def valid_checksum(self):
c... |
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import re # noq... |
import math
import fnmatch
import getpass
import glob
import json
import yaml
import os
import re
import platform
import shutil
import socket
import tarfile
import tempfile
import thread
import json
import subprocess
import commands
import signal
from collections import defaultdict
from behave import given, when, then... |
#!/usr/bin/env python3
from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run
from caproto import ChannelType
import numpy as np
import time
from textwrap import dedent
class Thermo(PVGroup):
"""
Simulates (poorly) an oscillating temperature controller.
Follows :math:`T_{output} = T_{var} ex... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Module for integrating Yahoo Weather with the system
#
# by Peter Juett
# References:
#
# Copyright 2018
#
# 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 th... |
import sys
import numpy as np
output = open(sys.argv[1], "w")
def gen_mat(name, m, n=None):
output.write("dbl_t " + name + " [] = {\n")
np.random.seed(3531354)
if n:
mat = np.random.rand(m, n)
for row in mat:
output.write("\t" + ", ".join([str(x) for x in row]) + ",\n")
el... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Marcel Bollmann <marcel@bollmann.me>
#
# 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/L... |
from pathlib import Path
from menpo.io.output.base import (
_export,
_export_paths_only,
_normalize_extension,
_validate_and_get_export_func,
_enforce_only_paths_supported,
)
from menpo.io.output.extensions import image_types
def export_landmark_file(landmark_group, fp, extension=None, overwrite=... |
"""
MergeConcat
-----------
A class to merge or concat dataframes
"""
from typing import List, Union
import pandas as pd
from pandas.core.common import maybe_make_list
from soam.core import Step
class MergeConcat(Step):
def __init__(
self, keys: Union[str, List[str], None] = None, **kwargs,
):
... |
"""Simple maze launcher
"""
import sys
import logging
import numpy as np
from joblib import hash, dump, load
import os
from deer.default_parser import process_args
from deer.agent import NeuralAgent
from deer.learning_algos.CRAR_keras import CRAR
from simple_maze_env_diff_obs import MyEnv as simple_maze_env ####inve... |
# -*- coding: utf-8 -*-
from multiplierless.csd import to_csd, to_csdfixed, to_decimal
def test_csd1():
"""[summary]"""
csdstr = "+00-00+"
csdnumber = to_decimal(csdstr)
csdnew = to_csd(csdnumber)
assert csdnew == csdstr
def test_csd2():
"""[summary]"""
csdstr = "+00-.000+"... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
# Copyright 2021 CR.Sparse Development Team
#
# 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... |
cmd.do('run $HOME/Scripts/PyMOLscripts/supercell.py;')
cmd.do('supercell 1, 1, 1, , orange, supercell1, 1;')
|
from maze_env_extend import Maze
# from maze_env import Maze
# from RL_brain import DeepQNetwork
from RL_brain_extend import DeepQNetwork
import time
def run_maze(RL, iteration):
step = 0
start = time.clock()
flag = True
for episode in range(iteration):
# initial observation
observatio... |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/PlanDefinition
Release: STU3
Version: 3.0.2
Revision: 11917
Last updated: 2019-10-24T11:53:00+11:00
"""
import typing
from pydantic import Field, root_validator
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.e... |
#########################################################
# 2020-01-21 20:50:01
# AI
# ins: RL A
#########################################################
import random
from .. import testutil as u
from ..asmconst import *
p = u.create_test()
for x in range(4900):
value = random.getrandbits(8)
r = ((value ... |
from io import open
import pathlib
import shutil
# Mover
ruta_origen = str( pathlib.Path().absolute() ) + "/fichero_texto.txt"
ruta_destino = str( pathlib.Path().absolute() ) + "/fichero_texto_movido.txt"
shutil.move(ruta_origen, ruta_destino)
|
#!/usr/bin/env python
#
# FakeNet-NG is a next generation dynamic network analysis tool for malware
# analysts and penetration testers.
#
# Developed by Peter Kacherginsky
import logging
import os
import sys
import time
from collections import OrderedDict
from optparse import OptionParser,OptionGroup
from ConfigPar... |
"""Normal Kalman Filters."""
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
from jax import lax
def f(carry, noise_t):
"""Propagate forward the time series."""
beta, z_prev, tau = carry
z_t = beta * z_prev + noise_t
z_prev = z_t
return (beta, z_prev, tau), z_t
def si... |
# Generated by Django 3.1.5 on 2021-04-12 15:03
import core.shortcuts
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import functools
class Migration(migrations.Migration):
initial = True
dependencies = [
]
opera... |
from django.shortcuts import render, redirect, HttpResponse
from student.forms import StudentsForm
from student.models import Students
def std(request):
if request.method == "POST":
form = StudentsForm(request.POST)
if form.is_valid():
try:
form.save()
r... |
import jwt
import os
from sparrow_cloud.utils.get_cm_value import get_env_value
from sparrow_cloud.utils.get_settings_value import get_settings_value
def get_jwt_secret():
return get_env_value("JWT_SECRET") or get_settings_value("JWT_MIDDLEWARE").get("JWT_SECRET")
# def decode_jwt(token):
# secret = get_jwt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 15/04/18
"""
from Base.Recommender import Recommender
from Base.Recommender_utils import check_matrix, similarityMatrixTopK
from Base.SimilarityMatrixRecommender import SimilarityMatrixRecommender
from sklearn.preprocessing import normalize
import numpy a... |
from ._serialconfig import SerialConfig
from ._serial import MCUSerial
from ._sockets import Sockets
__all__ = [
'SerialConfig',
'Sockets',
'MCUSerial',
] |
# coding: utf8
from __future__ import unicode_literals
from ..symbols import POS, ADV, NOUN, ADP, PRON, SCONJ, PROPN, DET, SYM, INTJ
from ..symbols import PUNCT, NUM, AUX, X, CONJ, ADJ, VERB, PART, SPACE, CCONJ
TAG_MAP = {
"ADV": {POS: ADV},
"NOUN": {POS: NOUN},
"ADP": {POS: ADP},
"PRON... |
import okonf.connectors
import okonf.facts
import okonf.utils
from okonf.facts.multiple import Sequence, Collection
assert Sequence
assert Collection
assert okonf.utils
|
import numpy as np
from cntk.ops import relu, plus
from cntk.initializer import he_normal
from cntk.layers import BatchNormalization, Convolution, MaxPooling, Dropout
def conv_bn(layer_input, filter_size, num_filters, strides, init=he_normal(), name=''):
"""
Returns a convolutional layer followed by a batch n... |
'''
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/symbology.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="ht... |
"""Algorithm to invert a binary tree"""
import unittest
import queue
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def invert_binary_tree_recursive(tree):
"""Recursive implementation of the binary tree inversion algorithm"""
... |
import torch
from mmdet.core import bbox2roi
from ..builder import HEADS, build_head
from .standard_roi_head import StandardRoIHead
@HEADS.register_module()
class MaskScoringRoIHead(StandardRoIHead):
"""Mask Scoring RoIHead for Mask Scoring RCNN.
https://arxiv.org/abs/1903.00241
"""
d... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Some constants used throughout Monorail."""
import os
import re
# Number of seconds in var... |
import Testing.ZopeTestCase
class TestNavigation(Testing.ZopeTestCase.ZopeTestCase):
def test_interfaces(self):
from App.interfaces import INavigation
from App.Management import Navigation
from zope.interface.verify import verifyClass
verifyClass(INavigation, Navigation)
def... |
from absl import app
from absl import flags
import os
import re
import numpy as np
import string
import tensorflow as tf
import tensorflow_text
import tensorflow_hub as hub
from tensorflow import keras
from pprint import pprint
from read_dbpedia import load_dbpedia
from read_imdb import load_imdb
from read_trec_50 imp... |
"""
This module demonstrates MUTATION of a LIST in two ways:
-- From an assignment in main.
-- From within a function call.
Authors: David Mutchler, Amanda Stouder, Chandan Rupakheti, Katie Dion,
Claude Anderson, Delvin Defoe, Curt Clifton, Matt Boutell,
and their colleagues.
"""
# ----------... |
def index_settings(table_name):
"""
Return the Elasticsearch mapping for a given table in the database.
:param table_name: The name of the table in the upstream database.
:return:
"""
mapping = {
"image": {
"settings": {
"index": {
"number... |
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))
import server
# ref : https://cloud.kt.com/portal/openapi-guide/computing_enterprise-Server-server_api_make
# Zone parameter : Mandatory
# 1) KR-CA : KOR-Central A Zone
# ... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
import unittest
from dns import dnssec, name
class NSEC3Hash(unittest.TestCase):
DATA = [
# Source: https://tools.ietf.org/html/rfc5155#appendix-A
("example", "aabbccdd", 12, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom", 1),
... |
from . import decorators
import anndata as ad
import scanpy as sc
import scprep
import warnings
_scran = scprep.run.RFunction(
setup="library('scran')",
args="sce, min.mean=0.1",
body="""
sce <- computeSumFactors(sce, min.mean=min.mean, assay.type="X")
sizeFactors(sce)
""",
)
@decorators.nor... |
#
# Fit an arbitrary function with a model using maximum likelihood,
# assuming exponential distributions.
#
import numpy as np
import scipy.optimize as op
from scipy.stats import gamma
from scipy.special import gammaincc, gammainccinv
#
# Log likelihood function. In this case we want the product of exponential
# di... |
{% if cookiecutter.add_gcs|lower == 'y' %}import app.gcs{% endif %}
{% if cookiecutter.add_aws|lower == 'y' %}import app.aws{% endif %}
import app.notification
|
import re
from django.test import RequestFactory
from tri_declarative import (
dispatch,
Namespace,
)
from tri_struct import Struct
from iommi import (
Table,
middleware,
)
from iommi.base import items
from iommi.traversable import (
Traversable,
)
def reindent(s, before=" ", after=" "):
... |
# Copyright (c) 2019 The Unit-e developers
# Distributed under the MIT software license, see the accompanying
# file LICENSE or https://www.opensource.org/licenses/MIT.
from doc_parser import DocParser
import pytest
def test_parse_format():
doc_data = """one line
another line
\\startformat
name1
type1
descripti... |
import pytest
from fanstatic import NeededResources, Library, Resource, Slot, SlotError
def test_fill_slot():
needed = NeededResources()
lib = Library('lib', '')
slot = Slot(lib, '.js')
a = Resource(lib, 'a.js', depends=[slot])
b = Resource(lib, 'b.js')
needed.need(a, {slot: b})
resour... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class NavbarSettings(Document):
def validate(self):
self.validat... |
import subprocess
cmd_output = subprocess.run(["kubectl", "api-versions"], stdout=subprocess.PIPE, text=True)
fit_out = cmd_output.stdout.split("\n")
service_names = []
for i in fit_out:
rm_space = " ".join(i.split())
service_names.append(rm_space.split(" ")[0].split("/")[0])
print(list(set(service_names))) |
"""This file includes a collection of utility functions that are useful for
implementing DQN."""
import random
from collections import namedtuple
import gym
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
from cs285.infrastructure.atari_wrappers import wrap_deepmind
OptimizerSpe... |
import tensorflow as tf
import math
from tensor2tensor.utils import beam_search
from .bert import modeling
class TransformerDecoder(object):
def __init__(self, params):
self.params = params
def get_decoder_self_attention_mask(self, length):
"""Calculate bias for decoder that maintains model'... |
"""
tests specific to "pip install --user"
"""
import imp
import os
import textwrap
from os.path import curdir, isdir, isfile
from pip.backwardcompat import uses_pycache
from tests.lib.local_repos import local_checkout
from tests.lib import pyversion
def _patch_dist_in_site_packages(script):
sitecustomize_path... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed i... |
from torch.optim.lr_scheduler import ReduceLROnPlateau
from transformers import get_linear_schedule_with_warmup
def get_scheduler(optimizer, args):
if args.scheduler == "plateau":
scheduler = ReduceLROnPlateau(
optimizer, patience=0, factor=0.9, mode="max", verbose=True
)
elif arg... |
# coding: utf-8
from __future__ import unicode_literals, print_function, division, absolute_import
from django.conf import settings
url = False
if hasattr(settings, 'KOBOFORM_URL') and settings.KOBOFORM_URL:
url = settings.KOBOFORM_URL
else:
url = False
active = bool(url)
autoredirect = active
if active and... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('communication_app', '0001_initial'),
... |
#
# Copyright 2014-2015 Yasser Gonzalez Fernandez
#
# 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
#
"""
Text classification based on charac... |
from cereal import car
from common.realtime import DT_CTRL
from common.numpy_fast import clip, interp
from selfdrive.config import Conversions as CV
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfahda_mfc, create_acc_commands, c... |
from nltk import pos_tag, conlltags2tree
class ToConll(object):
def __init__(self):
self.entity_names = {
'timestamp': 'I-TIM',
'timestamp2': 'B-TIM',
'sequence_number': 'I-SEQ',
'level': 'I-LEV',
'hostname': 'I-HOS',
'service2': 'B-S... |
#
# 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... |
#!/usr/bin/env python
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_client
from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashiv... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import mmcv
from mmcv import Config, DictAction
from mmdet.datasets import build_dataset
def parse_args():
parser = argparse.ArgumentParser(description='Evaluate metric of the '
'results saved in pkl ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.