text stringlengths 1 927k |
|---|
from typing import FrozenSet, Tuple
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... |
"""Basic tests.
And I mean reeeaaaally basic, I'm just making sure the main example runs here.
That's because the project is still experimental and "expected behavior" is
a very fluid concept at this time.
"""
import os
import matplotlib
matplotlib.use('Agg')
from taskpacker import (tasks_from_spreadsheet,
... |
import threading
import time
import datetime
import pandas as pd
from functools import reduce, wraps
from datetime import datetime, timedelta
import numpy as np
from scipy.stats import zscore
import utils.queries as qrs
import utils.helpers as hp
from data_objects.NodesMetaData import NodesMetaData
from alarms impor... |
"""Test balancer contracts."""
import pytest
from Arbie import IERC20TokenError
from Arbie.Contracts import ContractFactory
from Arbie.Contracts.balancer import BalancerFactory, BalancerPool
from Arbie.Contracts.tokens import BadERC20Token, GenericToken
from Arbie.Variables import BigNumber, PoolType
bg10 = BigNumber... |
"""
Copyright 2021 Inmanta
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 ... |
import json
import unittest
from hachinai_scraping import get_pages
class TestGetPage(unittest.TestCase):
def test_url(self):
url = ''
actual = get_pages(url)
print(json.dumps(actual, indent='\t', ensure_ascii=False))
self.assertIsNotNone(actual)
if __name__ == '__main__':
u... |
import json
import os
import requests
# Input
QL_HOST = os.environ.get('QL_HOST', '0.0.0.0')
QL_PORT = os.environ.get('QL_PORT', '8668')
ORION_HOST = os.environ.get('ORION_HOST', '0.0.0.0')
ORION_PORT = os.environ.get('ORION_PORT', '1026')
# Internal
QL_URL = 'http://{}:{}'.format(QL_HOST, QL_PORT)
NOTIFY_URL = notif... |
import unittest
from nose.tools import assert_raises
import target_postgres
class TestUnit(unittest.TestCase):
"""
Unit Tests
"""
@classmethod
def setUp(self):
self.config = {}
def test_config_validation(self):
"""Test configuration validator"""
validator = target_pos... |
"""
Test inferior restart when breakpoint is set on running target.
"""
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
class BreakpointSetRestart(TestBase):
mydir = TestBase.compute_mydir(__file__)
BREAKPOINT_TEXT = 'Set a breakpoint here'
@skipIfNet... |
"""
This module provides the Scan Op
Scanning is a general form of recurrence, which can be used for looping.
The idea is that you *scan* a function along some input sequence, producing
an output at each time-step that can be seen (but not modified) by the
function at the next time-step. (Technically, the function can... |
# Generated by Django 3.2.1 on 2021-05-17 04:17
from django.db import migrations
from django.db.models import F
from django.db.models.functions import Upper
from manual.operations.manual_operations import ManualOperation
def one_off_delete_case_sensitive_aliases(apps, schema_editor):
GeneSymbolAlias = apps.get_... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: nexus/models/proto/typed_document.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refl... |
### scope-xy-adafruitlogo v1.0
"""Output a logo to an oscilloscope in X-Y mode on an Adafruit M4
board like Feather M4 or PyGamer (best to disconnect headphones).
"""
### copy this file to PyGamer (or other M4 board) as code.py
### MIT License
### Copyright (c) 2019 Kevin J. Walters
### Permission is hereby grante... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "heroku_blog.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure... |
# %% Load packages
import numpy as np
from kanga.chains import ChainArrays
from bnn_mcmc_examples.examples.mlp.pima.setting2.constants import diagnostic_iter_thres, num_chains
from bnn_mcmc_examples.examples.mlp.pima.setting2.hmc.constants import sampler_output_path, sampler_output_run_paths
# %% Load chain arrays
... |
from onelang_core import *
import OneLang.Parsers.Common.Reader as read
import OneLang.Parsers.Common.ExpressionParser as exprPars
import OneLang.Parsers.Common.NodeManager as nodeMan
import OneLang.Parsers.Common.IParser as iPars
import OneLang.One.Ast.AstTypes as astTypes
import OneLang.One.Ast.Expressions as exprs
i... |
"""
Select widget for MonthField. Copied and modified from
https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes
"""
from datetime import date
from django.forms import widgets
from django.utils.dates import MONTHS
from month.util import string_type
class MonthSelectorWidget(widgets.MultiWidget... |
# -*- coding: utf-8 -*-
# Copyright 2008-2013 Alex Zaddach (mrzmanwiki@gmail.com)
# This file is part of wikitools.
# wikitools 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... |
STEVILO_DOVOLJENIH_NAPAK = 10
PRAVILNA_CRKA = '+'
PONOVLJENA_CRKA = 'o'
NAPACNA_CRKA = '-'
ZMAGA = 'w'
PORAZ = 'x'
class Igra:
def __init__(self, geslo, crke):
self.geslo = geslo
self.crke = crke[:]
def napacne_crke(self):
return [crka for crka in self.crke if crka not in self.geslo]
... |
"""Demo of how to pop up plots asynchronously using separate processes."""
from __future__ import print_function
# https://gist.github.com/dwf/1222883
from multiprocessing import Process
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
def demo():
i = 0
processes = []
while True:
... |
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2018/11/4 下午12:04
# 2.8 TensorFlow 实现创建张量
# 1. 导入相应的工具库,初始化计算图
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
import tensorflow as tf
sess = tf.Session()
# 2. 导入iris数据集,根据目标数据是否为山鸢尾将其转换成1或者0。由于iris数据集将山鸢尾标记为... |
# Author: Bichen Wu (bichen@berkeley.edu) 08/25/2016
"""The data base wrapper class"""
import os
import random
import shutil
from PIL import Image, ImageFont, ImageDraw
import cv2
import numpy as np
from utils.util import iou, batch_iou, drift_dist, recolor, scale_trans, rand_flip
class imdb(object):
"""Image dat... |
"""Placeholder empty test to verify that tests are run properly."""
def test_placeholder():
"""Empty test to verify that tests get run.""" |
def test_get(session, organization):
from dispatch.organization.service import get
t_organization = get(db_session=session, organization_id=organization.id)
assert t_organization.id == organization.id
def test_get_all(session, organizations):
from dispatch.organization.service import get_all
t_o... |
# Copyright 2020 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 applica... |
#sign
import onnx
from onnx import helper
from onnx import numpy_helper
from onnx import AttributeProto, TensorProto, GraphProto
import numpy as np
from Compare_output import compare
# Create the inputs (ValueInfoProto)
x = helper.make_tensor_value_info('x', TensorProto.FLOAT, [11,])
# Create one output (ValueInfoP... |
# -*- coding: utf-8 -*-
#
# 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, software
... |
# Criar o jogo da forca
# O jogador poderá errar 6 vezes antes de ser inforcado
palavra_secreta = 'caso'
espacos = ' '.join(["_"] * len(palavra_secreta))
tentativa = 1
# import pdb; pdb.set_trace()
while tentativa <= 6:
letra = input("Digite uma letra: ")
if letra in palavra_secreta:
print(palavra_s... |
class Solution:
# @param version1, a string
# @param version2, a string
# @return an integer
def compareVersion(self, version1, version2):
version1 = [int(v) for v in version1.split(".")]
version2 = [int(v) for v in version2.split(".")]
len_min = min(len(version1), len(version2))... |
def solution(N, number):
possible_set = [0, [N]] # 조합으로 나올수 있는 가능한 숫자들, 여기에 계속 append하며 이후에 사용함
if N == number: # 주어진 숫자와 사용해야 하는 숫자가 같은 경우는 1개면 족하므로 1으로 놓는다.
return 1
for i in range(2, 9): # 2부터 8까지로 횟수를 늘려 간다.
case_set = [] # 임시로 사용할 케이스 셋, 각 I 별로 셋을 만들어 possible set에 붙인다.
basi... |
'''
Note:
print statements go to: ~openbis/servers/datastore_server/log/startup_log.txt
'''
import sys
sys.path.append('/home-link/qeana10/bin/')
import checksum
import time
import re
import os
import ch.systemsx.cisd.etlserver.registrator.api.v2
from java.io import File
from org.apache.commons.io import FileUtils
fr... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {'fields': ('email', 'pas... |
import unittest
from power_dict.errors import NoneParameterError
from power_dict.utils import DictUtils
class GetListDictPropertyTests(unittest.TestCase):
properties = {
"property_1": [1, 2, 3],
"property_1_none": None
}
def test_get_property(self):
target = DictUtils.get_list_di... |
import json
import logging
from jose import jwt
from base64 import b64decode
from flask import Flask, request, abort
from functools import wraps
from json import dumps
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__, static_url_path='', static_folder='wwwroot')
app.config.update({
'TESTING': True,
... |
from sqlalchemy.sql.elements import not_
from citywok_ms import db
from citywok_ms.auth.permissions import manager, shareholder
from citywok_ms.file.forms import FileForm
from citywok_ms.file.models import File, OrderFile
from citywok_ms.order.forms import OrderForm, OrderUpdateForm
from citywok_ms.order.models import ... |
import argparse
import pandas as pd
from dpmModule.character.characterKernel import JobGenerator
from dpmModule.character.characterTemplate import TemplateGenerator
from dpmModule.jobs import jobMap
from dpmModule.kernel import core
from dpmModule.status.ability import Ability_grade
from .loader import load_data
from... |
# -*- coding: utf-8 -*-
"""
Custom management command to rebuild documentation for all projects.
Invoked via ``./manage.py update_repos``.
"""
import logging
from django.core.management.base import BaseCommand
from readthedocs.builds.constants import EXTERNAL, INTERNAL
from readthedocs.builds.models import Build, ... |
from mock import patch
from ceph_hooks import check_for_upgrade
from test_utils import CharmTestCase
__author__ = 'Chris Holcombe <chris.holcombe@canonical.com>'
def config_side_effect(*args):
if args[0] == 'source':
return 'cloud:trusty-kilo'
elif args[0] == 'key':
return 'key'
elif arg... |
class BlockStatus():
NORMAL = 'normal'
BROKENBLOCK = 'brokenBlock'
BROKENCHECKSUM = 'brokenChecksum'
BLOCKNOTFOUND = 'blockNotFound'
CHECKSUMNOTFOUND = 'checksumNotFound'
MIGRATE = 'migrate'
MIGRATING = 'migrating'
RECOVING = 'recoving'
@classmethod
def def_status(cls):
... |
# 北国网
TASK_NAME = 'lnd'
# 起始URL',
START_URL = 'http://www.lnd.com.cn/'
# 控制域,必须为list格式
DOMAIN = ['lnd.com.cn']
# 请求头
HEADERS = {
'Host': 'www.lnd.com.cn',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0',
'Accept': 'text/html,application/xhtml+xml,applicat... |
import torch
from torch.utils.data import DataLoader
from util.log_util import create_file_console_logger
from util.train import config_path, split_dataset, train_model
from torch.utils.tensorboard import SummaryWriter
class BaseModel:
def __init__(self):
self.loader_args = None
self.model = None... |
# 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 ... |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import argparse
import codecs
from codecs import StreamWriter # pylint: disable=unused-import
import collections
import copy
import functools
import io
import logging
import os
import signal
import sys
from typing import (IO, Any, Callable,... |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.aws_hook import AwsHook
class StageToRedshiftOperator(BaseOperator):
sql_unformated = """
COPY {} FROM '{}'
ACCESS_KEY_ID '{}'
... |
# coding=utf-8
# Copyright 2017 The Tensor2Tensor 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 by applicable... |
"""
this is a place where we put datastructures used by legacy apis
we hope ot remove
"""
import keyword
import attr
from _pytest.config import UsageError
@attr.s
class MarkMapping(object):
"""Provides a local mapping for markers where item access
resolves to True if the marker is present. """
own_mark... |
from typing import Tuple, List, Union, Dict, cast, Optional
import torch
import kornia as K
from kornia.constants import Resample, BorderType, pi
from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
from kornia.geometry.transform.projwarp import warp_affine3d
from kornia.... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from .. import _utilities, _tables
from ... |
import tkinter as tk
import tkinter.font as Font
from .content import EditorContent
from ...breadcrumbs import BreadCrumbs
class Editor(tk.Frame):
def __init__(self, master, path=None, exists=True, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.base = master.base
self.ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file graph.py is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/classes/graph.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# Aric Hagberg <hagberg@lanl.gov>
# D... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Empty, String
from robot_learning.srv import SetString, SetStringResponse
from enum import IntEnum
class FSM_STATES(IntEnum):
USER = 1
RL = 2
USER_PROMPT = 3
class MarshallNode(object):
def __init__(self, name='rl_marshall'):
rospy... |
"""Coders for individual Variable objects."""
import warnings
from functools import partial
from typing import Any, Hashable
import numpy as np
import pandas as pd
from ..core import dtypes, duck_array_ops, indexing
from ..core.pycompat import dask_array_type
from ..core.utils import equivalent
from ..core.variable i... |
import time
import struct
import dataclasses
from dataclasses import dataclass
TECH = {
# Should match mapping in ArgyllCMS spectro/oemarch.c, parse_EDR
0: 'Color Matching Function',
1: 'Custom',
2: 'CRT',
3: 'LCD CCFL IPS',
4: 'LCD CCFL VPA',
5: 'LCD CCFL TFT',
6: 'LCD CCFL Wide Gamut ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutSandwichCode in the Ruby Koans
#
from runner.koan import *
import re # For regular expression string comparisons
class AboutWithStatements(Koan):
def count_lines(self, file_name):
try:
file = open(file_name)
try:
... |
from copy import deepcopy
import sys
import numbers
from enum import Enum
from functools import lru_cache
import pystac
from pystac.utils import get_required
from typing import (
Any,
Dict,
Generic,
List,
Optional,
Union,
TypeVar,
Iterable,
TYPE_CHECKING,
)
if sys.version_info >= ... |
#!/usr/bin/env python3
#-*- coding: UTF-8 -*-
"""
完成mysql巡检、巡检结果以html的形式输出
作者: 蒋乐兴
报bug: 1721900707@qq.com
时间: 2017-05-25
"""
from jinja2 import Template
import mysql.connector as connector
import argparse
import json
import datetime
import logging
import psutil
import sys
def get_cpu_info():
"""
通过一个字典的等式返... |
# coding=utf-8
"""
Generates rst files for model options
"""
from thetis.configuration import *
from thetis.options import CommonModelOptions, ModelOptions2d, ModelOptions3d, GLSModelOptions, LinearEquationOfStateOptions, SedimentModelOptions
with open('model_options_2d.rst', 'w') as f:
content = """
.. _model_o... |
import torch
import shutil
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
class ImbalancedDatasetSampler(torch.utils.data.sampler.Sampler):
def __init__(self, datas... |
# File: msadgraph_view.py
#
# Copyright (c) 2022 Splunk 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 applicab... |
#coding=utf-8
"""
Implementation of some commonly used losses.
"""
# python 2.X, 3.X compatibility
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
#import os
#import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class BC... |
import tensorflow as tf
import numpy as np
from gym.spaces import Box
import copy
from stable_baselines.common.policies import BasePolicy, nature_cnn, register_policy, cnn_1d_extractor
from stable_baselines.sac.policies import mlp
from stable_baselines.a2c.utils import lstm, batch_to_seq, seq_to_batch
class TD3Policy... |
"""Painting domain, which allows for two different grasps on an object (side or
top).
Side grasping allows for placing into the shelf, and top grasping allows
for placing into the box. The box has a lid which may need to be opened;
this lid is NOT modeled by any of the given predicates.
"""
from typing import Any, Cl... |
"""
Django settings for first_project project.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import... |
# encoding: utf-8
import parse
class WhenParsingSingleEntry:
def setup_method(self, method):
text = u"""
1. Marois R, Ivanoff J (2005) Capacity limits of information processing
in the brain. Trends Cogn Sci 9: 296–305. doi:
10.1016/j.tics.2005.04.010. Find this article online
... |
"""Remote Functions and decorators for Views.
Authors:
* Brian Granger
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, ... |
import asyncio
import concurrent.futures
import threading
import click
def safe_run_async(async_fn, *argv):
loop = asyncio.get_event_loop()
try:
ret = loop.run_until_complete(async_fn(*argv))
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
loop.close()
return ret
... |
"""Compatibility fixes for older version of python, numpy and scipy
If you add content to this file, please give the version of the package
at which the fixe is no longer needed.
# XXX : copied from scikit-learn
"""
# Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
# Gael Varoquaux <gael... |
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib import messages
from django.shortcuts import HttpResponseRedirect
from base.views import GenericDataGridView, GenericModalCreateView
from base.mixin import GeneralContextMixin
from models import Project
from forms import ProjectForm
... |
'''Token每日重新加载'''
import redis
token_redis = redis.StrictRedis(host='127.0.0.1', port=6379, db=4)#token与剩余次数数据库
token_redis.flushdb() |
# qubit number=5
# total number=59
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as ... |
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import Required,Email,EqualTo,Length
from ..models import User
from wtforms import ValidationError
class LoginForm(FlaskForm):
email = StringField('Your Email Address',validators=[Required... |
'''
Randomly assign images in a folder to a training, validation, and test set.
~ Christopher Pramerdorfer
'''
import os
import sys
import pickle
import random
import json
rng = 1337 # rng seed
frac_test = 0.1535 # test fraction
frac_val = 0.0905 # val fraction of training set (after removing test samples)
source... |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansi... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2019-04-15 14:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Tb3UIG... |
import pyperclip
class User:
user_details = []
def __init__(self, account, first_name, last_name, phone_number, email_address, username, password):
self.account = account
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
self.email_... |
import pytest
from pca.utils.serialization import load_ini_from_filepath
@pytest.fixture
def contents():
ini_contents = "\n".join(
(
"[pytest]",
"python_files =",
" pca/**/tests/**/*.py",
" pca/**/tests/*.py",
" devops/**/tests/*.py",
... |
import sys
from dcim.models import Region, Site
from startup_script_utils import load_yaml, pop_custom_fields, set_custom_fields_values
from tenancy.models import Tenant
sites = load_yaml("/opt/netbox/initializers/sites.yml")
if sites is None:
sys.exit()
optional_assocs = {"region": (Region, "name"), "tenant": ... |
from django.contrib import admin
from nectr.chat.models import Message, Conversation
@admin.register(Conversation, Message)
class ConversationAdmin(admin.ModelAdmin):
pass |
# encoding: UTF-8
__author__ = 'CHENXY'
# C++和python类型的映射字典
type_dict = {
'int': 'int',
'char': 'string',
'double': 'float',
'short': 'int',
'unsigned': 'string'
}
def process_line(line):
"""处理每行"""
if '///' in line: # 注释
py_line = process_comment(line)
elif 'typede... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
import torch
from tor... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import io
import logging
import tempfile
import datetime
import os
from builtins import object
from concurrent.futures import ProcessPoolExecutor as ProcessP... |
#
# 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... |
from __future__ import division
import sys
from torch.utils.data import Dataset
import os
import numpy as np
import pickle
import imp
import trimesh
import torch
import json
from tqdm import tqdm
from timeit import default_timer as timer
from utils.gaps_utils import read_pts_file
class SDFDataset(Dataset):
def ... |
from __future__ import absolute_import
from proteus import *
from proteus.default_n import *
try:
from .clsvof_p import *
except:
from clsvof_p import *
multilevelNonlinearSolver = Newton
levelNonlinearSolver = CLSVOFNewton
fullNewtonFlag = True
updateJacobian = True
timeIntegration = BackwardEuler_cfl
if ep... |
from os.path import abspath, dirname, join
from fnmatch import fnmatchcase
from operator import eq
from robot.api import logger
from robot.api.deco import keyword
ROBOT_AUTO_KEYWORDS = False
CURDIR = dirname(abspath(__file__))
@keyword
def output_should_be(actual, expected, **replaced):
actual = _read_file(act... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Presentation',
fields=[
('id', models.AutoField... |
"""
Acknowledgement:
This rule based agent is adapted from
https://github.com/rocanaan/hanabi-ad-hoc-learning/tree/AIIDE/
"""
from .rule_based_parallel import ParallelRulebasedAgent
from .ruleset import Ruleset |
"""Unit tests for the CarbonBlack downloading Lambda function."""
# pylint: disable=protected-access
import base64
import io
import os
from unittest import mock
import boto3
import cbapi
from pyfakefs import fake_filesystem_unittest
class MockBinary(object):
"""Mock for cbapi.response.models.Binary."""
clas... |
# model settings
model = dict(
type="RetinaNet",
pretrained="open-mmlab://resnext101_64x4d",
backbone=dict(
type="ResNeXt",
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type="BN", re... |
# Copyright 2014 Netflix, 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... |
"""
Run Annalist server.
"""
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2014, G. Klyne"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import os, os.path
import sys
i... |
import copy
import logging
import numpy as np
from collections import defaultdict, namedtuple
from functools import partial
from typing import Callable, Tuple, Set, Dict, List
from alibi.utils.distributed import ActorPool, RAY_INSTALLED
from alibi.utils.distributions import kl_bernoulli
logger = logging.getLogger(__... |
# Copyright 2020 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, ... |
import re, collections
def get_stats(vocab):
pairs = collections.defaultdict(int)
for word, freq in vocab.items():
symbols = word.split()
for i in range(len(symbols) - 1):
pairs[symbols[i], symbols[i + 1]] += freq
return pairs
def merge_vocab(pair, v_in):
v_out = {}
b... |
import os
import pyodbc
import pandas
from django.conf import settings
DB = "UWSDBDataStore"
def get_day1_enrollments(year, quarter):
"""
Returns a list of student system_keys enrolled on day one and EOP status
"""
campus = 0
db_query = """
SELECT *
FROM (
SELECT
C... |
#!/usr/bin/env python3
import json
import logging
import argparse
from project.default import get_homedir
def validate_generic_config_file():
sample_config = get_homedir() / 'config' / 'generic.json.sample'
with sample_config.open() as f:
generic_config_sample = json.load(f)
# Check documentatio... |
import unittest
from test import support
# xxx - forces a skip in the case we haven't built ctypes_test module in ant (which is not yet a task as of now)
try:
import _rawffi
_rawffi.CDLL("ctypes_test")
except:
raise ImportError
class RawFFITestCase(unittest.TestCase):
def setUp(self):
self.l... |
import argparse
from pathlib import Path
import numpy as np
import h5py
from scipy.io import loadmat
import torch
from tqdm import tqdm
import logging
import pickle
import cv2
import pycolmap
from .utils.parsers import parse_retrieval, names_to_pair
def interpolate_scan(scan, kp):
h, w, c = scan.shape
kp = k... |
from app import app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=bool(app.config.get('DEBUG')), threaded=True) |
import numpy as np
import pyxacc as xacc
from pyxacc import InstructionParameter
import pyxaccvqe as vqe
from pyxaccvqe import PauliOperator
from scipy.optimize import minimize
xacc.Initialize()
# Construct the First Quantized 2x2 and 3x3 Hamiltonians
hamiltonian3x3 = PauliOperator(7.7658547225) + PauliOperator({0:'X... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.