content stringlengths 5 1.05M |
|---|
# ================ AlphaZero algorithm for Connect 4 game =================== #
# Name: config.py
# Description: Meta-parameters and various options
# Authors: Jean-Philippe Bruneton & Adèle Douin & Vincent Reverdy
# Date: 2018
# License: BSD 3-Clause License
# ==========... |
import tensorflow as tf
import numpy as np
import argparse
import os
import cv2
from networks.factory import get_network
from utils import read_labels
parser = argparse.ArgumentParser(description='Run a training of the Network')
parser.add_argument('--testing_folder', type=str, required=True, help='path to testing spl... |
## main file to preprocess
## 1. generate table from outgroup (S.paradoxus), for multiple S_para
import sys
from extract_diffs_w_chr import *
#import pdb
if __name__ == '__main__':
print ('extracting diffs from S.cer and S.para...')
in_dir = '../multi_para/data/'
S_para_list=["CBS432","N44","UFRJ50816","... |
import astropy.units as u
import numpy as np
import pytest
from astropy.time import Time, TimeDelta
from astropy.wcs import WCS
from ndcube.tests.helpers import assert_cubes_equal
import sunraster.spectrogram
from sunraster import SpectrogramCube
# Define a sample wcs object
H0 = {
"CTYPE1": "WAVE ",
"CUNI... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Clockwerkbot is a Discord bot that gives you Dota2 Stats."""
# imports
import json
import os
import random
import re
import urllib.parse
import urllib.request
from urllib.request import urlopen as spyder
from collections import defaultdict
import aiohttp
import dis... |
"""
codegen.py generates pika/spec.py
"""
from __future__ import nested_scopes
import os
import sys
RABBITMQ_PUBLIC_UMBRELLA = '../../rabbitmq-public-umbrella'
RABBITMQ_CODEGEN = 'rabbitmq-codegen'
PIKA_SPEC = '../pika/spec.py'
CODEGEN_PATH = os.path.realpath('%s/%s' % (RABBITMQ_PUBLIC_UMBRELLA,
... |
# -*- coding: utf8 -*-
# ============LICENSE_START=======================================================
# org.onap.vvp/validation-scripts
# ===================================================================
# Copyright © 2019 AT&T Intellectual Property. All rights reserved.
# ========================================... |
# Zu erzeugende images pro Font
IMAGE_COUNT = 50
# Erster Index im Name des erzeugten Bildes
START_NUM = 0
# Name der Datei, die Text für Zufallssätze enthält
INPUT_TXT_FILE = "text_it_mgmt"
# Pfad zur Eingabedatei, aus der Zufallssätze erzeugt werden
TEXT_INPUT_FILE_PATH = "text_res/" + INPUT_TXT_FILE + ".txt"
# ... |
import mxnet as mx
import mxnet.gluon as gl
import mxnet.ndarray as nd
import copy
print mx.gpu()
a = nd.array([1, 2, 3], ctx=mx.gpu())
CTX = mx.gpu()
# ===========================
# Deep Q Network
# ===========================
class DeepQNetwork(object):
"""
Input to the network is the state and action, o... |
import pandas as pd
#import path_shell as ps
import server.logic.Team1903.JMH as J
import os
import time
import server.logic.Team1903.infomation as Info
import datetime
from collections import Counter
import matplotlib.pyplot as plt
res=["apache/cassandra","apache/camel","apache/hive","apache/commons-lang"]
def gitda... |
"""
This is sample code showing how tensorflow code can be instrumented in MCenter.
"""
import argparse
import time
import numpy as np
import tensorflow as tf
from sklearn.datasets import make_classification
from parallelm.mlops import mlops as mlops
from parallelm.mlops.stats.bar_graph import BarGraph
from parallelm... |
import io
import json
import sys
from pathlib import Path
import jmespath
class JSONInventory:
def write_file(
self,
file_path,
data,
extra_data=None,
fields=None,
format=None,
merge=True,
):
# raw data
local_data = data
file_pa... |
# Copyright 2021 Tianmian Tech. 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 la... |
import string
import random
import hashlib
import zmq
import time
import sys
from random import sample
from operator import itemgetter
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
from sklearn.datasets.samples_generator import make_blobs
import numpy as np
from scipy.stats i... |
# 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 applica... |
import json
import os
from os.path import join
from PIL import Image
LIGHTNING_CKPT_PATH = 'lightning_logs/version_0/checkpoints/'
LIGHTNING_TB_PATH = 'lightning_logs/version_0/'
LIGHTNING_METRICS_PATH = 'lightning_logs/version_0/metrics.csv'
class Args(dict):
def __init__(self, *args, **kwargs):
super(... |
class DuplicatedRegistrationError(ValueError):
pass
class MappingError(Exception):
pass
class CircularReferenceError(Exception):
def __init__(self, *args: object) -> None:
super().__init__(
"Mapper does not support objects with circular references yet", *args
)
|
"""API for JupyterHub's proxy.
Custom proxy implementations can subclass :class:`Proxy`
and register in JupyterHub config:
.. sourcecode:: python
from mymodule import MyProxy
c.JupyterHub.proxy_class = MyProxy
Route Specification:
- A routespec is a URL prefix ([host]/path/), e.g.
'host.tld/path/' for ho... |
from collections import defaultdict
from icecream import ic
def part1(lines):
number_of_unique_output_values = 0
for line in lines:
_in, out = line.split(" | ")
for v in out.split(" "):
if len(v) in [2,3,4,7]:
number_of_unique_output_values += 1
return number_... |
#!/usr/bin/env python
from slashproc_parser.basic_parser import BasicSPParser
from parse_helpers import traverse_directory
class SysVm(BasicSPParser):
VM = "/proc/sys/vm"
@staticmethod
def get_groups():
"""Enumerates groups depending on number of directories in /proc/sys/vm.
Returns:
... |
<<<<<<< HEAD
from django.test import TestCase
# Create your tests here.
=======
class Test:
@staticmethod
def static_call(word):
print 'calling static method: {}'.format(word)
if __name__ == '__main__':
t = Test()
t.static_call('hello')
>>>>>>> a1c36b07fbdd3d2c91462ecec37ffa8a83176473
|
# USBConfiguration.py
#
# Contains class definition for USBConfiguration.
import struct
from .USB import USBDescribable
from .USBInterface import USBInterface
from .USBEndpoint import USBEndpoint
# TODO: Section these out into their own folder?
from .USBClass import USBClass
from .HIDClass import HIDClass
class USB... |
"""Model interface for CERF
@author Chris R. vernon
@email chris.vernon@pnnl.gov
License: BSD 2-Clause, see LICENSE and DISCLAIMER files
"""
import logging
import time
from cerf.process_region import process_region
from cerf.read_config import ReadConfig
from cerf.stage import Stage
class Mod... |
class Savable(object):
@staticmethod
def load(model_path, *args, **kwargs):
pass
@staticmethod
def save(model_path, *args, **kwargs):
pass
|
import choraconfig, glob
batch = choraconfig.clone_batch("assert")
batch["toolIDs"] = ["duetcra", "icra", "chora"]
|
def tournamentWinner(competitions, results):
'''
This fuction takes two arrays one of which contains competitions, another array contains results of the competitions
and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions,
O(i) space comp... |
"package containing various sphinx extensions"
#legacy aliases
from __future__ import absolute_import
from . import (autodoc_sections as nested_sections,
index_styling as index_styles,
)
|
import json
import numpy as np
from decibel.audio_tab_aligner.hmm_parameters import HMMParameters
from json import JSONEncoder, JSONDecoder
from decibel.music_objects.chord_alphabet import ChordAlphabet
from decibel.music_objects.chord_vocabulary import ChordVocabulary
class HMMParametersEncoder(JSONEncoder):
... |
import os
import tweepy as tw
import pandas as pd
from dotenv import load_dotenv, find_dotenv
ENV_FILE = find_dotenv()
if ENV_FILE:
load_dotenv(ENV_FILE)
api_key = os.environ.get('api_key')
api_secret_key = os.environ.get('api_secret_key')
access_token = os.environ.get('access_token')
access_token_secret = os.... |
import socket
from google.cloud.pubsub_v1.publisher.client import publisher_client
from google.cloud.pubsub_v1.subscriber.client import subscriber_client
class GoogleCloudPubsub:
def __init__(self, project, role, study_title) -> None:
self.project = project
self.publisher = publisher_client.Publi... |
import requests
import rows
from pathlib import Path
class DownloadFileProcessor:
def __init__(self, url: str, filename: str, path: str):
self.url = url
self.filename = filename
self.path = path
def _download(self):
destination_path = f'{self.path}/{self.filename}'
re... |
#! /bin/python3
"""
This is a model for my Craigslist Scanner
You enter a city, category, keyword and the program scans the results to
return a link to the post with the included keyword
"""
import requests, bs4, sys, city_dict, pprint
from requests.exceptions import HTTPError
URL = city_dict.ALL_CITIES
CITY_LIST... |
import tensorflow as tf
x = tf.constant(3.0)
with tf.GradientTape() as g:
g.watch(x)
y = x * x
dy_dx = g.gradient(y, x)
print(dy_dx)
|
import os
import docker
import zipfile
import random
from jinja2 import Environment, FileSystemLoader
import requests
''':key
url for doc = https://docker-py.readthedocs.io/en/stable/containers.html
'''
def selector(msg, portfolio):
if portfolio == 1:
return docker_master.container_web(username=msg)
... |
from bs4 import BeautifulSoup as bs
def getMovieRanking():
movie_rankings = {}
rankings = open('topmovies.html').read()
soup = bs(rankings, 'html.parser')
movies = soup.find_all("div",{"class":"film "})
for movie in movies:
try:
title = movie.find("div",{"class":"film__original... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from grad_reverse import grad_reverse
class Feature(nn.Module):
def __init__(self):
super(Feature, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = n... |
''' Helper functions'''
from __future__ import print_function
import os
import sys
from jinja2 import (StrictUndefined, Template, TemplateSyntaxError, UndefinedError)
def fail_unless(condition, msg):
"""If condition is not True print msg and exit with status code 1"""
if not condition:
print("{}".fo... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_PASSWORD
from homeassistant.core import callback
from .const import DOMAIN, DEFAULT_PORT, DEFAULT_SSL
class BroadlinkHubConfigFlow(config_entries.ConfigFlow, domain=DO... |
try:
import json
except:
import simplejson as json
import urllib2
class Jolokia:
'''
pyJolokia class Jolokia is a JSON featching python class.
It uses urllib2 and json or simplejson to do post requests
to a jolokia URL. Then returns back a python dictionary.
.. code-block:... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: link.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflecti... |
#!/usr/bin/env python
from __future__ import generators
## Copyright (c) 1999 - 2003 L. C. Rees. All rights reserved.
## See COPYRIGHT file for license terms.
__name__ = 'spider'
__version__ = '0.5'
__author__ = 'L.C. Rees (xanimal@users.sf.net)'
__all__ = ['ftpurls', 'ftppaths', 'weburls', 'ftpmirror', 'ftpspider',... |
from random import choice, randint
martial_weapons = [
"battleaxe", "flail", "glaive", "greataxe", "greatsword", "halberd", "lance", "longsword", "maul", "morningstar", "pike", "rapier",
"scimitar", "shortsword", "trident", "war pick", "warhammer", "whip"
]
simple_weapons = ["club", "dagger", "greatclub", "ha... |
import flask
import sys
import time
from flask import request, jsonify
from io import StringIO
from contextlib import redirect_stdout
from flask_cors import CORS, cross_origin
from bridge_utils import code_to_file
from flask import stream_with_context, request
import code_engine
import bridge_utils
import os
app = f... |
#!/bin/env python
# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# purify_coverage.py
import logging
import optparse
import os
import re
import sys
import google.path_utils
# local modules
imp... |
# -*- coding: utf-8 -*-
"""Top-level package for nola."""
__author__ = """Raghuveer Naraharisetti"""
__email__ = 'raghuveernaraharisetti@gmail.com'
__version__ = '0.1.0'
|
import ast
import re
import enum
import inspect
from typing import Any, List, Optional
from inspect import Signature, Parameter
from nb_autodoc.pycode.unparser import unparse
def convert_anno_new_style(s: str) -> str:
"Converts type annotation to new styles."
# noqa: change pattern of unparser is not good id... |
import numpy as np
import cv2
"""
Shi Tomasi - Good Features To Track;
*Similar to Harris Corner Detector but gives better results.
*We can provide the no. of corners to detect
"""
image = cv2.imread('../images/pic1.png')
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# find the strongest corners (as s... |
import boto3
import json
import os
controlTowerHomeRegion = os.environ.get('controlTowerHomeRegion', '')
configurationAggregatorName = os.environ.get('configurationAggregatorName', '')
audit_account_id = os.environ.get('auditAccountId', '')
config = boto3.client('config')
config_ct_home = boto3.client('config', region... |
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from django.conf import settings # noqa
from celery import Celery
app = Celery('mendelmd')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
a... |
import unittest
from import_new_tournaments.process_hh_files.process.hands.extract.table_type import table_type
from GLOBAL_VARIABLES import TEST_RANDOM_HAND_HISTORIES_FOLDER
from import_new_tournaments.process_hh_files.process.tournament.extract.hands import get_hands_in_list
class test(unittest.TestCase):
def t... |
def solution(a):
sm_num = min(a)
while not( all(x % sm_num == 0 for x in a)):
a = sorted(a)
lg_num = a[-1]
sm_num = a[0]
if lg_num % sm_num == 0:
a[-1] = sm_num
else:
a[-1] = lg_num % sm_num
return len(a) * sm_num |
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from ._base import TelegramObject
if TYPE_CHECKING: # pragma: no cover
from .mask_position import MaskPosition
from .photo_size import PhotoSize
class Sticker(TelegramObject):
"""
This object represents a sticker.
S... |
try:
from normatrix.source.file_parser import CFileParse
from normatrix.source.config import TypeLine
except ModuleNotFoundError:
from normatrix.normatrix.source.file_parser import CFileParse
from normatrix.normatrix.source.config import TypeLine
import re
reg = re.compile('^(?!.*=)(\w{1,} {0,1}){2,}\... |
import asyncio
import logging
import typing
import asyncpg
async def periodic_task(
pool: asyncpg.Pool,
frequency: int,
failure_message: typing.Optional[str] = None,
*execute_args: any
) -> None:
"""
Runs an sql statement every `frequency` seconds. Restarts on failure.
If... |
import numpy as np
from pylab import *
"""
Value-based learning in the unit-test environment.
Note that the agent needs to start off believing that cooperate is better.
"""
ENVIRONMENT_SWAPPING = False
n_steps = 3000
n_learners = 5
eps = .1
# IIRC, initial state needs to be cooperate
states = [[1] for n in range(n_... |
def find_evil_ingredients(s: str) -> dict:
cnt = {}
ing = []
recipes = []
for l in s.strip().strip("\n").splitlines():
i, c = l.split(" (contains ")
i = i.split(" ")
c = c[:-1].split(", ")
recipes.append([i, c])
for k in c:
if not k in cnt:
... |
"""Discover Netgear routers."""
from netdisco.util import urlparse
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
"""Add support for discovering Netgear routers."""
def info_from_entry(self, entry):
"""Return the most important info from a uPnP entry."""
url = urlparse(e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import app.models
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="MealService",
fields=[
(
... |
"""
Tests for odometry function.
"""
import dataclasses
import math
from pytest import fixture
from highlevel.robot.entity.configuration import Configuration
from highlevel.util.geometry.vector import Vector2
from highlevel.util.filter.odometry import odometry_arc
DISTANCE_BETWEEN_WHEELS = 200
@fixture(name='confi... |
import sys
import typing
import numba as nb
import numpy as np
@nb.njit
def fw_set(
fw: np.ndarray,
i: int,
x: int,
fn: typing.Callable[[int, int], int],
) -> typing.NoReturn:
while i < len(fw):
fw[i] = fn(fw[i], x)
i += i & -i
@nb.njit
def fw_get(
fw: np.ndarray,
i: int... |
#pip install aliyun-python-sdk-core
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
client = AcsClient('uXIWtuAQspvFqpCt', 'g4dRrretS3HDiACJuwkaUzoUgUG8C4', 'cn-hangzhou')
def send_sms(telephone,code):
request = CommonRequest()
request.set_accept_format('json')
r... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# FEDERAL UNIVERSITY OF UBERLANDIA
# Faculty of Electrical Engineering
# Biomedical Engineering Lab
#------------------------------------------------------------------------------
# Author: Italo Gustavo Sampaio Fern... |
import h5py, time
import numpy as np
from utility import randomData
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
def buildModel(trainXShape, trainYShape, numLayers, neuonPerLayer):
... |
import math
# Uses Euclid's algorithm
def greatest_common_divisor(a, b):
if a == b:
return a
if a > b:
return greatest_common_divisor(a - b, b)
if b > a:
return greatest_common_divisor(a, b - a)
def least_common_multiple(a, b):
return int((a * b) / greatest_common_divisor(a, b)... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
... |
from sklearn import datasets
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
np.random.seed(1234)
from sklearn import metrics
def knn_classify(train_x, test_x, train_y, k):
"""
Params:
train_x:training dataset,ndarry
test_x:test dataset,ndarry
train_y:training la... |
def get_output_schema():
return pd.DataFrame({
'Name': prep_string(),
'ID': prep_int(),
'Student': prep_bool(),
'Birth_Date': prep_date(),
'Fastest_Speed': prep_decimal(),
'Test_DateTime': prep_datetime()
}) |
from ArubaCloud.Compute.LoadBalancer.Models import Instance, Rules, NotificationContacts, NotificationContact
from ArubaCloud.base import Request
class SetEnqueueLoadBalancerCreation(Request):
def __init__(self, healthCheckNotification, instance, ipAddressResourceId, loadBalancerClassOfServiceID, name,
... |
taboada = int(input('Qual taboada você quer ver? '))
contador = 0
continuar = ''
while True:
if taboada < 0:
print('Não imprimimos taboada com números negativos!')
break
if contador != 10:
contador += 1
print(f'{taboada} x {contador} = {taboada * contador}')
if contador == 10... |
#!/usr/bin/env python3
import getpass
import smtplib
import socket
import sys
import threading
import time
from email.message import EmailMessage
from os.path import dirname, realpath
sys.path.append(dirname(dirname(dirname(realpath(__file__)))))
from logger.utils.formats import Text # noqa: E402
from logger.write... |
from pyquilted.quilted.contact import *
class ContactFactory:
"""A factory class that returns contact objects"""
@staticmethod
def create(key, val):
contact = None
if key in 'email':
contact = EmailContact(val)
elif key in 'phone':
contact = PhoneContact(val... |
from .config import args |
# AUTOGENERATED! DO NOT EDIT! File to edit: 09_ensemble2.ipynb (unless otherwise specified).
__all__ = ['ensemble2_test']
# Cell
# # Include local library paths
# import sys
# sys.path.append('path/to/local/lib') # put path to local libraries in system path
# Import local libraries # now local libraries in a non_loc... |
#!/usr/bin/env python
import optparse
import re
import os
import subprocess
import boto3
def initialize():
print "initialize"
from os.path import expanduser
home = expanduser("~")
if os.path.isfile(home + "/.aws/config"):
print "AWS credrentials config exists"
else:
print "AWS credrentials config NOT... |
import numpy as np
### From Riess et al., 1903.07603
def get_loglike(class_input, likes_input, class_run):
return -0.5 * (class_run.h() * 100 - 74.03)**2. / 1.42**2.
|
import numpy as np
import pytest
from tengp import FunctionSet, Parameters
@pytest.fixture
def function_set():
funset = FunctionSet()
funset.add(np.add, 2)
funset.add(np.subtract, 2)
funset.add(np.multiply, 2)
return funset
@pytest.fixture
def advanced_function_set():
funset = FunctionSet()
... |
import numpy as np
import cv2
def paste_imgs(lst_imgs, n_rows, n_cols, sep=5):
n_imgs = len(lst_imgs)
assert (n_imgs <= n_rows * n_cols)
h, w = lst_imgs[0].shape[:2]
new_im = np.ones(((h+sep)*n_rows+sep, (w+sep)*n_cols+sep,3))*255
k = 0
for i in range(n_rows):
for j in range(n_cols)... |
###==========================================================
###==========================================================
### visualize the cnv-activations of CNN in training
### buildSet: similarity and grouping
###==========================================================
###=======================================... |
"""Load rviz2 node."""
# Copyright 2022 HarvestX 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 ... |
"""389. Find the Difference
https://leetcode.com/problems/find-the-difference/
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more
letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explan... |
"""
1.Строка
2.Числа (Целые,С плав. запятой)
3.Bool (True : 1,False :0)
4.Списки (изменяемая,упорядоченная)
5.Кортеж (неизменяемый,упорядоченный)
6.Словарь
7.Множества
-----
Классы
-----
"""
import random
class Planet:
def __init__(self, name, size, loc):
self.name = name
self.... |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
import subprocess
import time
pos=input("Enter Your Name: ")
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices[1].id)
engine.setProperty('voice', voices[0].id)
... |
from django import template
from api import models
from django.utils.translation import ugettext_lazy as _, string_concat
register = template.Library()
def verifiedToString(value):
return models.verifiedToString(value)
def playWithToString(value):
return models.playWithToString(value)
def languageToString(v... |
#!/bin/env python3
# Author: ph-u
# Script: basic_io.py
# Desc: 1. first of three basic_io.py sections -- output lines from `txt` file; 2. print a list of numbers into `txt` file; 3. save a python dictionary into binary file, then read and print in python interpreter
# Input: python3 basic_io.py
# Output: 1. 22-lined ... |
# coding=utf-8
# Copyright 2020 HuggingFace Datasets 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 applica... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Assigns the given tag to an agent by GUID, name, IP address, MAC address or user name"
class Input:
AGENT = "agent"
TAG = "tag"
class Output:
MESSAGE = "message"
class... |
import BySykkelConfig
import argparse
parser = argparse.ArgumentParser(description='BySykkel Demo App Parameters',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--gbfs', dest='gbfs', type=str, default=BySykkelConfig.OnlineGBFS,
help=... |
#
# PySNMP MIB module CISCO-CEF-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CEF-TC
# Produced by pysmi-0.3.4 at Wed May 1 11:53:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
from cdb.testcase import PlatformTestCase
from cs.platform.web.root import root as RootApp
from webtest import TestApp
class TestStateColorEndpoint(PlatformTestCase):
def __init__(self, *args, **kwargs):
super(TestStateColorEndpoint, self).__init__(*args, **kwargs)
self.client = None
... |
from .clickhouse_hook import ClickHouseHook
|
# Generated by Django 3.2.6 on 2021-08-30 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('models', '0004_model_agency'),
]
operations = [
migrations.AlterField(
model_name='measurements',
name='chest',
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 20:56:02 2020
@author: Arthur
"""
import torch
from torch.nn import Module, MSELoss
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
from .utils import print_every, RunningAverage
class Trainer:
"""Training object for a neural ... |
# Generated by Django 2.1.4 on 2019-01-08 06:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('user', '0002_auto_20190108_1448'),
]
operations = [
migrations.CreateModel(
... |
import pytest
import numpy as np
from pyuplift.datasets import make_linear_regression
def test_make_linear_regression__repeated_random_state():
random_state, size = 101, 1000
df1 = make_linear_regression(size, random_state=random_state)
df2 = make_linear_regression(size, random_state=random_state)
as... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
import numpy as np
import pandas as pd
import gensim
import multiprocessing
import argparse
import random
import json
import sys
sys.path.append('../../rdf2vec/')
sys.path.append('../../lib/')
sys.path.append('.')
from Evaluator import Evaluator
from RDF2Vec_Embed import get_rdf2vec_embed
parser = argparse.ArgumentPa... |
from django.urls import reverse
from django.http import HttpResponsePermanentRedirect
ENTITY_NAME_TO_URL_NAME = {
'compound': 'compound_report_card',
'target': 'target_report_card',
'assay': 'assay_report_card',
'doc': 'document_report_card',
'cell': 'cell_line_report_card',
'tissue': 'tissue_... |
import math
import pytest
import ipywidgets
from pandas_visual_analysis import DataSource
from pandas_visual_analysis.utils.config import Config
from pandas_visual_analysis.widgets import BrushSummaryWidget
from tests import sample_dataframes
@pytest.fixture(scope="module")
def small_df():
return sample_datafra... |
#
# Object-Oriented Python: Advanced Objects
# Python Techdegree
#
# Created by Dulio Denis on 12/15/18.
# Copyright (c) 2018 ddApps. All rights reserved.
# ------------------------------------------------
# Filled List Class
# ------------------------------------------------
import copy
class FilledList(list):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.