text stringlengths 2 999k |
|---|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
from pympler import asizeof, muppy
from .memgraph import _MemInfo, _MemNode, _RootNode, _MemEdge, MemGraph, num_str
def test_num_str():
assert num_str(1) == "1"
assert num_str(12) == "12"
assert num_str(123) == "123"
assert num_str(1234) == "1.23k"
assert num_str(12345) == "12.3k"
assert num_s... |
"""
Created on Mon Jul 26 17:23:16 2021
@author: Andile Jaden Mbele
"""
"""
Complexity of the iterative fibonacci
1. Best case: O(1)
2. Worst case: O(1) + O(n) + O(1) => O(n)
"""
def fib_iter(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
fib_i = 0
fib_ii = 1
for i in range(n - 1):
tmp = fib_i
... |
import tensorflow as tf
from tensorflow.python.layers.core import Dense
from Optimizer import Optimizer
class DecodeModel:
def __init__(self, inputs, input_length, targets, target_length, max_target_length,
num_layers, rnn_size, sample_prob, keep_prob, learning_rate, num_labels,
... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# ... |
#!c:\users\welcome\supermarket\superenv\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
import os
import time
from cv2 import cv2
import numpy as np
from collections import defaultdict
from PIL import Image
from torch import torch
import torch.nn.functional as F
from torchvision import transforms as T
from face_utils import norm_crop, FaceDetector
from model_def import WSDAN, xception
class DFDCLoade... |
import pandas as pd
from pandas import DataFrame, Series
import math
from primesense import openni2, nite2
import time
import numpy as np
class Person(object):
MOVEMENT_SMOOTHING_WINDOW_SIZE_SECONDS = 0.1
def __init__(self):
# lh_y, rh_y, head_y, body_z, hand_dist
self.param_values = [0, 0... |
import pytest
# pytest rewrites `assert` in test cases to give additional info for debugging. This class isn't a
# test case itself, but it contains the asserts that are used to test the various run storages.
# We need to explicitly inform pytest that these asserts are part of the test cases, and not just
# arbitrary ... |
#!/usr/bin/env python
#
# Copyright 2016 Google 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 requir... |
import pytest
from .context import Memory, User
class TestMemory(object):
url = "http://www.awesomestuff.com/this/is/a/long/url"
def test_store_and_get_url(self):
db = Memory()
db.store_url("somekey", self.url)
assert(db.get_url("somekey") == self.url)
def test_store_raises_if_key... |
from matplotlib import pyplot as plt
from wordcloud import WordCloud
import jieba
filename = 'tianlongbabu.txt'
with open(filename , encoding="utf-8") as f_obj:
contents = f_obj.read()
s = jieba.lcut(contents)
txt = " ".join(s)
font = r'C:\Windows\Fonts\simkai.ttf'
wc = WordCloud(font_path=font, #... |
# -*- coding: utf-8 -*-
################################################################################
## A validation script for ##
## BonnMotion - a mobility scenario generation and analysis tool ##
## Copyright (C) 2002-2012 University of Bonn ... |
#!/usr/bin/env python3
# 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 copy
import random
from typing import Any, Dict, List, Optional
from parlai.agents.fixed_response.fixed_response... |
"""
1. Clarification
2. Possible solutions
- Brute force + Recursion
- dp
- Binary Search
3. Coding
4. Tests
"""
# T=O(n^2), S=O(n), dp[i]: len of LIS when selecting nums[i]
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums: return 0
n = len(nums)
dp = ... |
#!/usr/bin/env python
""" Class representing a AI Model.
Represents a AI Model. AI Models are used by AI Agents to process
incoming data.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without re... |
import requests
from requests.auth import HTTPBasicAuth
#set the url
#make sure to replace <servername> with the correct value
url = "https://<servername>.fa.us2.oraclecloud.com/hcmRestApi/scim/Users"
#set the payload
payload = """{
"schemas":["urn:scim:schemas:core:2.0:User"],
"name":{"familyName":"R... |
from src.litvar import utils
from src.litvar import core
class TestUtils:
def test_publications_from_query(self):
var_pmids = utils.publications_from_query("VHL")
assert all([isinstance(var_pmid, core.Model) for var_pmid in var_pmids])
|
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import pickle
import re
from collections import OrderedDict
from copy import deepcopy
from dataclasses import dataclass
from enum import Enum
from typing import Any
import torch
import torchvision
from mmf.common.registry import registry
from mmf.modules.emb... |
def generated_cmake_targets(ctx):
ctx = ctx.push_directory(ctx, "")
ctx.set(ctx, "LLVM_ALL_PROJECTS", "clang;clang-tools-extra;compiler-rt;debuginfo-tests;libclc;libcxx;libcxxabi;libunwind;lld;lldb;llgo;openmp;parallel-libs;polly;pstl")
ctx.set(ctx, "LLVM_ENABLE_PROJECTS", "", "CACHE", "STRING", "Semicolon-... |
import importlib
import xarray as xr
import numpy as np
import pandas as pd
import sys
from CASutils import filter_utils as filt
from CASutils import readdata_utils as read
from CASutils import calendar_utils as cal
importlib.reload(filt)
importlib.reload(read)
importlib.reload(cal)
expname=['SASK_CLM5_CLM5F_02.001... |
# Copyright 2022 kunwuluan. All Rights Reserved.
# Author-Github: github.com/kunwuluan
# get_order_time.py 2022/4/14 13:01
import requests
from requests import utils,cookies
import json
import ddddocr
import io
import PIL.Image
import re
import config
def convert_Image(img, standard=210):
image = img.convert('L')... |
from __future__ import unicode_literals, print_function, division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from data_util import config
from numpy import random
use_cuda = config.use_gpu and torch.cuda.is_available()
r... |
"""
Initialize the version column of the migrate_tools database table to 1. No tool migrations are handled in this version.
"""
def upgrade(migrate_engine):
print(__doc__)
def downgrade(migrate_engine):
pass
|
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
""" Implements Ta... |
# Script pour calcule l’angle de réfraction dans l'air
import math
# Valeur du premier milieu
n1 = 1
# Saisi des données
θ1 = int(input("Veuillez saisir l'angle d'incidence : "))
n2 = float(input("Veuillez saisir l'indice de réfraction du milieu 2 : "))
# Calcule de l'angle
θ2 = round(math.degrees(math.asin((n1*math.si... |
from qmpy import *
from qmpy.analysis.miedema import *
import matplotlib
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
comps = Composition.objects.filter(ntypes__gt=1)
comps = comps.filter(exptformationenergy__dft=False)
f = open('data.txt', 'w')
for comp in comps.distinct():
print(comp)
... |
### publish new version of this library to PyPI
import git
from shutil import copyfile
import fileinput
import sys
import os
copyfile("./setup.py.default", "./setup.py")
repo = git.Repo(".")
lasttag = sorted(repo.tags, key=lambda t: t.commit.committed_date)[-1]
nexttag = "0." + str(int(str(lasttag).replace("0.",... |
"""Pseudo terminal utilities."""
# Bugs: No signal handling. Doesn't set slave termios and window size.
# Only tested on Linux, FreeBSD, and macOS.
# See: W. Richard Stevens. 1992. Advanced Programming in the
# UNIX Environment. Chapter 19.
# Author: Steen Lumholt -- with additions by Guido.
from sele... |
from .dcgannet import dcgan_mnist
from .pix2pixnet import pix2pix_facde
from .animegannet import animenet |
from django.conf.urls import url
from . import views
app_name = 'hkplayer'
urlpatterns = [
url(r'^hkplayer', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
u... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Create and save a new user"""
if no... |
import sys
import cPickle
import glob
import subprocess
import os
import set_up
print '[Grepper for FUNCTION]'
if sys.argv[1]=='train':
in_dir = set_up.train_folder_path
elif sys.argv[1]=='test':
in_dir = set_up.test_folder_path
else:
print 'Unknown option'
sys.exit()
out_dir = set_up.feats_folder_... |
"""TSV Class"""
import re
import math
import pandas as pd
import random
import json
from omigo_core import tsvutils
from omigo_core import utils
import sys
class TSV:
"""This is the main data processing class to apply different filter and transformation functions
on tsv data and get the results. The design is ... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import json
import zipfile
import requests
from .constants import QUERY_BASEURL, MARC_BASEURL
class SolrAPI(object):
def query(self, querystring, rows=10, start=0, fields=None):
"""
Arguments:
... |
"""Tests for Comment related views."""
from conduit.auth.tests.test_auth_views import USER_ONE_JWT
from webtest import TestApp
def test_GET_comments(testapp: TestApp, democontent: None) -> None:
"""Test GET /api/articles/{slug}/comments."""
res = testapp.get("/api/articles/foo/comments", status=200)
ass... |
# Code is from OpenAI baseline.
# https://github.com/openai/baselines/tree/master/baselines/common/vec_env
import numpy as np
from multiprocessing import Process, Pipe
def worker(remote, parent_remote, env_fn_wrapper):
parent_remote.close()
env = env_fn_wrapper.x()
while True:
cmd, data = remote.r... |
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
__all__ = ['GradualWarmupScheduler']
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
from os.path import join as pjoin
import torch
import torch.nn as nn
import numpy as np
from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, ... |
#!/usr/bin/env python3
from cereal import car
from panda import Panda
from common.numpy_fast import interp
from common.params import Params
from selfdrive.car.honda.values import CarControllerParams, CruiseButtons, HondaFlags, CAR, HONDA_BOSCH, HONDA_NIDEC_ALT_SCM_MESSAGES, HONDA_BOSCH_ALT_BRAKE_SIGNAL
from selfdrive.c... |
from __future__ import division
from __future__ import print_function
import time
import os
# Train on CPU (hide GPU) due to memory constraints
os.environ['CUDA_VISIBLE_DEVICES'] = ""
import tensorflow as tf
import numpy as np
import scipy.sparse as sp
from utility.model import clustering, pairwise_precision_recall... |
r"""
.. role:: html(raw)
:format: html
.. _variational_classifier:
Variational classifier
======================
.. meta::
:property="og:description": Using PennyLane to implement quantum circuits that can be trained from labelled data to
classify new data samples.
:property="og:image": https://pe... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class SoftmaxLoss(nn.Module):
"""
Softmax loss
Takes logits and class labels
"""
def __init__(self, margin=128.0, size_average=True):
super(SoftmaxLoss, self).__init__()
self.xentropy = nn.CrossEn... |
"""
A Cython plugin for coverage.py
Requires the coverage package at least in version 4.0 (which added the plugin API).
"""
from __future__ import absolute_import
import re
import os.path
import sys
from collections import defaultdict
from coverage.plugin import CoveragePlugin, FileTracer, FileReporter # requires ... |
from pizza_store.db.crud.refresh_token.crud import RefreshTokenCRUD
from pizza_store.db.crud.refresh_token.interface import IRefreshTokenCRUD
__all__ = ["IRefreshTokenCRUD", "RefreshTokenCRUD"]
|
from migen import *
from litex.soc.interconnect.csr import AutoCSR, CSRStorage, CSRField
class PWM(Module):
def __init__(self, bitwidth, tick, offset):
self.out = pwm = Signal(1)
pwm_counter = Signal(bitwidth)
counter_value = Signal(8)
counter = Signal(16)
# Sine Modulati... |
import scrapy
from scrapy.selector import Selector
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class CoinSpiderSelenium(scrapy.Spider):
name = 'coin_selenium'
allowed_domains = ['www.livecoin.net/en']
start_urls = [
'https://www.livecoin.net/en'
]
... |
import pyautogui as pya
import keyboard
import winsound
from threading import Thread
import pyperclip # handy cross-platform clipboard text handler
import time
count=0
def copy_clipboard():
return pyperclip.paste()
# double clicks on a position of the cursor
#pya.doubleClick(pya.position())
listT = list()
def ch... |
from yaml import load
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
class ConfigReader:
__singleton = None
def __new__(cls, *args, **kwargs):
if cls.__singleton == None:
cls.__singleton = super(ConfigReader, cls).__new__(cls)
return cl... |
import pygame
import speech_recognition as sr
from time import sleep
import events
import objects as obj_types
from settings import SPEECH_CRED_FILE
from speech_helpers import correct_text, either_side, get_after, get_position, get_positions, get_size, is_in_objects, process_relative, select_obj_type
# A variable lis... |
#!/usr/bin/env python
#
# revert_tests.py: testing 'svn revert'.
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or mo... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 - 2019, doudoudzj
# Copyright (c) 2012, VPSMate development team
# All rights reserved.
#
# InPanel is distributed under the terms of the (new) BSD License.
# The full license can be found in 'LICENSE'.
'''Module for Service Management.'''
from glob import g... |
# -*- coding: utf-8 -*-
"""
Dummy conftest.py for oloid.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
# import pytest
|
from setuptools import setup
setup(name='args_catcher',
version='0.1',
description='Catch expected arguments together with test doubles',
url='https://github.com/ProjectThor/args-catcher',
author='Franco Sebregondi',
author_email='franco.sebregondi@siroop.ch',
license='MIT',
... |
# Tuple is an ordered sequence of items same as a list.
# The only difference is that tuples are immutable.
# Tuples once created cannot be modified.
# It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program... |
_base_ = "./fcos_r50_caffe_fpn_gn-head_4x4_1x_coco.py"
img_norm_cfg = dict(
mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False
)
train_pipeline = [
dict(type="LoadImageFromFile"),
dict(type="LoadAnnotations", with_bbox=True),
dict(
type="Resize",
img_scale=[(1333, 640... |
#
# Copyright (c) 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 applicable law or agreed to... |
"""
Combinatorial maps
This module provides a decorator that can be used to add semantic to a
Python method by marking it as implementing a *combinatorial map*,
that is a map between two :class:`enumerated sets <EnumeratedSets>`::
sage: from sage.combinat.combinatorial_map import combinatorial_map
sage: class... |
import datetime
import os
from decimal import Decimal
from unittest import mock, skipUnless
from django import forms
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import connec... |
import copy
import warnings
import six
from chainer import backend
from chainer import configuration
from chainer.dataset import convert
from chainer.dataset import iterator as iterator_module
from chainer import function
from chainer import iterators
from chainer import link
from chainer import reporter as reporter_... |
from builtins import range
from airflow import configuration
from airflow.utils.state import State
from airflow.utils.logging import LoggingMixin
PARALLELISM = configuration.getint('core', 'PARALLELISM')
class BaseExecutor(LoggingMixin):
def __init__(self, parallelism=PARALLELISM):
"""
Class to... |
import cv2
import dlib
from scipy.spatial import distance
def calculate_EAR(eye):
A = distance.euclidean(eye[2], eye[4])
B = distance.euclidean(eye[1], eye[3])
C = distance.euclidean(eye[1], eye[2])
ear_aspect_ratio = (A+B)/(2.0*C)
return ear_aspect_ratio
cap = cv2.VideoCapture(0)
hog_face_detector = dlib.get_f... |
import time
import numpy as np
import random
import matplotlib.pyplot as plt
# from transitions import Machine
from transitions.extensions import GraphMachine as Machine
class Connection(object):
pass
class SarsaSimplified(object):
def __init__(self, epsilon=0.3, total_episodes=5000, max_steps=1000, alpha=... |
xs = [[],
{},
(),
42] |
import FWCore.ParameterSet.Config as cms
pythia8CP2TuneDownSettingsBlock = cms.PSet(
pythia8CP2TuneDownSettings = cms.vstring(
'Tune:pp 14',
'Tune:ee 7',
'PDF:pSet=17',
'MultipartonInteractions:bProfile=2',
'MultipartonInteractions:ecmPow=0.1391',
'MultipartonInteractions:pT0Ref=2.333',
'MultipartonInteract... |
import pyvista
pl = pyvista.Plotter()
pl.camera.elevation
# Expected:
## 0.0
pl.camera.elevation = 45.0
pl.camera.elevation
# Expected:
## 45.0
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
#!/usr/bin/env python
import sys, re, os.path, errno, fnmatch
import json
import logging
import codecs
from shutil import copyfile
from pprint import pformat
from string import Template
if sys.version_info[0] >= 3:
from io import StringIO
else:
import io
class StringIO(io.StringIO):
def write(self... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2017 František Brožka <sentientfanda@gmail.com>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details... |
from collections import defaultdict
from collections import Counter
import nltk
import sys
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils.np_utils import to_categorical
def load_dataset():
nltk.download('brown')
nltk.download('universal_tagset')
# list of sente... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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 ... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import socket
import traceback, sys
from binascii import hexlify
import time, os
from socks5 import Socks5Conf... |
from ledfxcontroller.effects.temporal import TemporalEffect
from ledfxcontroller.color import COLORS, GRADIENTS
from ledfxcontroller.effects import Effect
from scipy.misc import comb
import voluptuous as vol
import numpy as np
import logging
_LOGGER = logging.getLogger(__name__)
@Effect.no_registration
class Gradient... |
""" Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
"""
__version_info__ = ('0', '2', '3')
__version__ = '.'.join(__version_info__)
|
import datetime
import time
from nanoid import generate
#
# print(generate()) # => NDzkGoTCdRcaRyt7GOepg
#
# #collision might increase for a lesser size
# print(generate(size=10) )# => "IRFa-VaY2b"
#
# # custome alphabet
# print(generate('1234567890abcdef', 10)) # => "4f9zd13a42"
shortId = generate()
date_value = t... |
# 151. Reverse Words in a String
#
# Given an input string, reverse the string word by word.
#
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
#
class Solution:
def reverseWords(self, s):
return ' '.join(reversed(s.split()))
# pythonic
def reverseWords(self, s):
re... |
from celery import shared_task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@shared_task
def squash_counts():
"""
Task to squash all daily counts
"""
from .models import DailyCount, DailySecondTotalCount, TotalCount
TotalCount.squash()
DailyCount.squash()
... |
import torch
from apex import amp
from math import ceil
import random
import PIL
from tqdm import tqdm
#torch.multiprocessing.set_start_method('spawn', force=True)
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
urbangan_dir = os.path.dirname(curr... |
from app import db |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
# Copyright (c) 2020 Jan Tünnermann. All rights reserved.
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from tvatojpower import hierarchical_model_noncentered, sim_and_fit
'''
This example is based on Experiment 1 from Tünnermann, Krüger, & Scha... |
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [https://neo4j.com]
#
# This file is part of Neo4j.
#
# 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... |
"""
This file offers the methods to automatically retrieve the graph Chlorogloeopsis fritschii.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2... |
import sideserver
if __name__ == '__main__':
server = sideserver.SideServer()
server.start()
while True:
msg = server.receive()
content = msg.json()
server.reply(msg, json=[content, content])
server.shutdown()
|
# Copyright 2020 Zhejiang Lab. 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 or... |
print("LeBron James")
|
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# ... |
import grasp_utils as gu
import sys
sys.path.append("..")
import robothelper as yh
import numpy as np
if __name__ == "__main__":
rhx = yh.RobotHelper()
hndfa = rhx.rgthndfa
objcm = rhx.cm.CollisionModel(objinit="../objects/" + "tubebig_capped.stl")
predefinedgrasps = []
c0nvec = rhx.np.array([0, -... |
def parse(grammar, ulta=False):
""" Parses the grammar """
if not grammar:
return None
rules = grammar.strip().split("\n")
productions_l = map(lambda x: map(lambda x: x.strip(), x.split("->")), rules)
productions_l = [
[x, set(map(lambda x: x.strip(), y.split("|")))] for x, y in pro... |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from scipy.stats import spearmanr
import scipy
###############
tosyo=0
new_list_tadoku = []
new_list_ippann = []
#textをnew_listに読み込む
#多読図書
with open("CohMetrixOutput.txt", "r", encoding="utf-8") as f:
list_tadoku = f.readlines()
for i... |
import keras
import tensorflow as tf
from tqdm import tqdm
import numpy as np
import six
import os
import json
import sys
from .data_utils.data_loader import image_segmentation_generator
from .train import CheckpointsCallback
from tensorflow.keras.models import Model
def get_pariwise_similarities( feats ):... |
from ast import unparse
import modules.core.database as database
#import modules.core.extract as extract
import modules.core.extract as extract
import modules.core.unparse as unparse
import time
import threading
import json
class filter_switch():
def __init__(self,update,context) -> None:
sel... |
#!C:\Users\User\PycharmProjects\Password_Locker\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.7'
__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)?$', '', ... |
# 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 ... |
# DataviewQuery.py
#
import json
class DataviewQuery(object):
"""
Dataview Query
"""
def __init__(self, id=None, query=None):
"""
:param id: required
:param query: a query string
"""
self.__id = id
if query:
self.__query = query
e... |
# -*- coding:utf-8 -*-
"""
deprecated, 使用md2
在pyctp2的父目录,执行ipython3
并且在提示行
import pyctp2.testbed.ctp as ctp
"""
import logging
from ..common.base import BaseObject,INFO_PATH,DATA_PATH
from ..md import ctp_md as cm
from ..common import controller as ctl
from ..common.contract_type import CM_ALL,CM_SH,... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from argparse import (ArgumentParser as ArgumentParserBase, REMAINDER, RawDescriptionHelpFormatter,
SUPPRESS, _Coun... |
#! /usr/bin/env python3
import os
import re
import json
import argparse
import numpy as np
import matplotlib
# select matplotlib backend
matplotlib.use('pdf')
import matplotlib.pyplot as plt
def load_evo_file(file, total_num_sim=None):
with open(file) as evo_file:
raw_data = json.load(evo_file)
sin... |
from __future__ import absolute_import
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from ..account import app_settings as account_settings
from ..account.adapter import get_adapter as get_account_adapter
from ..account.app_se... |
from typing import List
import torch
import torch.nn.functional as F
from kornia.filters.__tmp__ import _deprecation_wrapper
from kornia.filters.kernels import normalize_kernel2d
def _compute_padding(kernel_size: List[int]) -> List[int]:
"""Compute padding tuple."""
# 4 or 6 ints: (padding_left, padding_ri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.