text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
# -----------------------------------------------------------------------------
try:
basestri... |
from django.urls import path
from .views import HomePageView, SearchResultsView
urlpatterns=[
path('search', SearchResultsView.as_view(), name='search_results'),
path('',HomePageView.as_view(), name='home'),
]
|
import json
import os
import zipfile
excludes = [".gitignore", ".idea", ".vscode", ".git", "build.py", "deploy.py", "__pycache__"]
def get_archive_name(basedir: str):
with open(basedir + '/info.json') as info:
version = json.load(info)['version']
return 'Loader-Furnaces_' + version + '.zip'
def get... |
from .training import Trainer
from .inferer import Inferer
|
#!/usr/bin/env python
from celeryutils import task
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Count
import amo
from addons.models import AddonDeviceType as ADT
from amo.utils import chunked
from mkt.site.decorators import write
@task
@write
def _task(**kw):
# Remove any ... |
"""
Django settings for example project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... |
#
# Copyright (C) 2016, 2017
# The Board of Trustees of the Leland Stanford Junior University
# Written by Stephane Thiell <sthiell@stanford.edu>
#
# 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 Lic... |
from .domain import TypeGame
from .get_all_type_games_use_case import GetAllTypeGamesUseCase
from .get_type_games_by_user import GetTypeGamesByUser
from .get_type_games_by_user import Params as ParamsGetTypeGamesByUser
from .get_all_type_games_use_case import Params as ParamsGetAllTypeGames
|
# Copyright (c) 2019 Microsoft Corporation
# Distributed under the MIT software license
import pytest
import numpy as np
from .. import gen_feat_val_list, gen_name_from_class
from .. import reverse_map, unify_data
@pytest.fixture
def fixture_feat_val_list():
return [("race", 3), ("age", -2), ("gender", 1)]
def... |
import requests
from bs4 import BeautifulSoup
import re
#this gets the html content of whatever webpage you want
page = requests.get('https://www.foxnews.com/politics/mcconnell-urges-white-house-not-to-make-coronavirus-deal-with-pelosi')
contents = page.content
all_urls = []
bad_urls = []
#regex = "www\.latimes\.com... |
# -*- coding: utf-8 -*-
#
# py2neo documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 4 23:41:38 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... |
"""PG-19 language modeling benchmark - a set of books extracted from the Project Gutenberg books library"""
from __future__ import absolute_import, division, print_function
import csv
import json
import os
from operator import itemgetter
import requests
import nlp
# TODO(pg19): BibTeX citation
_CITATION = """\
@a... |
from pyswagger import App
from datetime import datetime
from email._parseaddr import mktime_tz
from email.utils import parsedate_tz
cached_api: App = None
def header_to_datetime(header) -> datetime:
return datetime.fromtimestamp(mktime_tz(parsedate_tz(header)))
def get_api() -> App:
global cached_api
... |
"""
This module is a factory method what allows to import various objects, such as algorithms, crossover, mutation.
The definitions for each object are purposely defined as a list and not as a dictionary to keep an order for the documentation.
"""
import re
from pymoo.configuration import Configuration
from pymoo.... |
from south.modelsinspector import add_introspection_rules
try:
from annoying.fields import AutoOneToOneField
except ImportError:
pass
else:
#django-annoying's AutoOneToOneField is essentially a OneToOneField.
add_introspection_rules([], ["^annoying\.fields\.AutoOneToOneField"])
|
# -*- coding: utf-8 -*-
"""Test CLI Helpers' utility functions and helpers."""
from __future__ import unicode_literals
from cli_helpers import utils
def test_bytes_to_string_hexlify():
"""Test that bytes_to_string() hexlifies binary data."""
assert utils.bytes_to_string(b"\xff") == "0xff"
def test_bytes_t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-25 15:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0012_player'),
]
operations = [
migrations.AddField(
mode... |
# The piwheels project
# Copyright (c) 2017 Ben Nuttall <https://github.com/bennuttall>
# Copyright (c) 2017 Dave Jones <dave@waveform.org.uk>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistribution... |
from bver.Loader import Loader, AddonNotFoundError
from .CommonLoader import CommonLoader
class TestLoader(CommonLoader):
"""Test loader object."""
def test_constructor(self):
"""Should test the constructor."""
Loader()
def test_emptySoftwares(self):
"""Should test the result when... |
# -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git
# Licensed under MIT
"""gl switch - Switch branches."""
from __future__ import unicode_literals
from . import pprint
def parser(subparsers, _):
"""Adds the switch parser to the given subparsers object."""
desc = 'switch branches'... |
#handles filtering of posts
#def filter_by(primaryCriteria, secondaryCriteria):
#marks a post as appreaciated (featured for that location)
def appreciate(post):
#a post is appreciated if it reaches over 200 likes for a particular location
from globe.models import Post
post = Post.query.filter_by(id=postID).firs... |
# A function that returns names of the jobs on the queue
def jobs_on_queue():
onq = []
import os
import subprocess
if os.path.exists('/home/daveminh/stash'):
qstat = subprocess.Popen(['condor_q','-long','daveminh'], \
stdout=subprocess.PIPE).stdout.read().split('\n')
onq = [os.path.basename(l.spl... |
import pytest
from haystack.schema import Document
from haystack.nodes.document_classifier.base import BaseDocumentClassifier
@pytest.mark.slow
def test_document_classifier(document_classifier):
assert isinstance(document_classifier, BaseDocumentClassifier)
docs = [
Document(
content="""... |
import pydot
# Create the graph
graph = pydot.Dot("my_graph", graph_type="graph", overlap=False, splines='true')
# Add the node - replace "Node Name" with your desired Node Title
graph.add_node(pydot.Node("Node Name"))
# Save the output and included the "prog" argument - that takes a string.
# Default: dot.
# Possib... |
from ..__main__ import ACsploit
import os
import pytest
def test_acsploit_init():
cmdlineobj = ACsploit(None)
# Cmd2 has a transcript that is in the master branch but is not yet released.
# This feature is the most natural way to test ACsploit but cannot be installed
# via pip yet. When the next version of Cmd2 ... |
#!/usr/bin/python
import socket, threading, thread, select, signal, sys, time, getopt
LISTENING_ADDR = '0.0.0.0'
LISTENING_PORT = 2085
PASS = ''
BUFLEN = 4096 * 4
TIMEOUT = 60
DEFAULT_HOST = '127.0.0.1:339'
RESPONSE = 'HTTP/1.1 101 OpenVPN WebSocket\r\n'
class Server(threading.Thread):
def __init__(self, host, po... |
"""
Module: 'uasyncio.core' on micropython-v1.18-pyboard
"""
# MCU: {'ver': 'v1.18', 'port': 'pyboard', 'arch': 'armv7emsp', 'sysname': 'pyboard', 'release': '1.18.0', 'name': 'micropython', 'mpy': 7685, 'version': '1.18.0', 'machine': 'PYBv1.1 with STM32F405RG', 'build': '', 'nodename': 'pyboard', 'platform': 'pyboard... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
# Load the AlchemyAPI module code.
import AlchemyAPI
# Create an AlchemyAPI object.
alchemyObj = AlchemyAPI.AlchemyAPI()
# Load the API key from disk.
alchemyObj.loadAPIKey("api_key.txt");
# Detect the language for a web URL.
result = alchemyObj.URLGetLanguage("http://www.techcrunch.fr/");
print... |
# Copyright The PyTorch Lightning 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import calendar
c = calendar.TextCalendar(calendar.MONDAY)
str = c.formatmonth(2018,2)
print (str)
|
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import openstack
import unittest
from ansible_collections.os_migrate.os_migrate.plugins.module_utils \
import router_interface
def sdk_router_interface():
return openstack.network.v2.port.Port(**{
'allowed_addres... |
from __future__ import print_function
from functools import partial
import json
import sys
from textwrap import dedent
import time
import logging
logging.basicConfig()
import pika
from .config import Config
pika_logger = logging.getLogger('pika.adapters')
pika_logger.setLevel(logging.CRITICAL)
class AbstractQueu... |
import os
import sys
sys.path.insert(0, os.path.abspath(
os.path.join(os.path.dirname(__file__), '..')))
import {{cookiecutter.package_name}} |
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_lkas12, \
create_1191, create_1156, \
create_clu11
from selfdrive.car.hyundai.values import Buttons
from se... |
"""
GCN model for relation extraction.
"""
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from model.tree import head_to_tree, tree_to_adj
from utils import constant, torch_utils
class GCNClassifier(nn.Module):
""... |
# flake8: noqa: F811, F401
import asyncio
import time
import pytest
import pytest_asyncio
import logging
from shibgreen.protocols import full_node_protocol
from shibgreen.types.peer_info import PeerInfo
from shibgreen.util.ints import uint16
from shibgreen.wallet.transaction_record import TransactionRecord
from shib... |
import time
import streamlit as st
def main():
st.sidebar.title("About PPE UK Live")
st.sidebar.markdown(
"""
An open data project by the team at [Induction Healthcare](https://induction-app.com)
"""
)
st.sidebar.subheader("Contact")
st.sidebar.info(
"This is an [open source... |
import numpy as np
class InvalidMoveException(Exception):
pass
class GameOverException(Exception):
pass
class TicTacToeGame():
def __init__(self, agent1, agent2):
# a random player will have the first turn
self.turn = np.random.randint(2)
self.agents = [agent1, agent2]
# s... |
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
# -*- coding: utf-8 -*-
from ....Classes.LamHole import LamHole
from ....Classes.LamSlotWind import LamSlotWind
from ....Methods.Machine import MachineCheckError
def check(self):
"""Check that the Machine object is correct
Parameters
----------
self : MachineIPMSM
A MachineIPMSM object
... |
"""Message type identifiers for Trust Pings."""
PROTOCOL_URI = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0"
PING = f"{PROTOCOL_URI}/ping"
PING_RESPONSE = f"{PROTOCOL_URI}/ping_response"
NEW_PROTOCOL_URI = "https://didcomm.org/trust_ping/1.0"
NEW_PING = f"{NEW_PROTOCOL_URI}/ping"
NEW_PING_RESPONSE = f"{NEW_P... |
import re
from os import listdir
import pandas as pd
lists = listdir('/Users/jesusllanogarcia/Downloads/Scopus')
count = [[] for uni in lists]
# Names for the Table Attributes.
top_countries = ['Documents_by_country_top_1', 'Documents_by_country_top_2', 'Documents_by_country_top_3',
'Documents_by_co... |
from django.db import models
from django.core import exceptions
from django.template.loader import get_template
from django.utils.translation import gettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from populous.advertising.parts.utils import ge... |
# Local
from .base import *
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.rq import RqIntegration
# Core
ALLOWED_HOSTS = [
'.barberscore.com',
'.herokuapp.com',
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
SECURE... |
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding 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 require... |
"""
@author: Gabriele Girelli
@contact: gigi.ga90@gmail.com
"""
import argparse
import itertools
from joblib import cpu_count, delayed, Parallel # type: ignore
import logging
import numpy as np # type: ignore
import os
import pandas as pd # type: ignore
import pickle
from radiantkit import argtools
from radiantkit.... |
'''
Created on 02-Jul-2016
This module contains the forward and backward mapping functions
needed to shorten a given url. As opposed to url-value based hash mechanism,
we are using a counter based hash approach where a universally unique counter
value is hashed to a short string of characters. This becomes the new sh... |
import boto
from boto.dynamodb2 import exceptions
from boto.dynamodb2.fields import (HashKey, RangeKey,
AllIndex, KeysOnlyIndex, IncludeIndex,
GlobalAllIndex, GlobalKeysOnlyIndex,
GlobalIncludeIndex)
from boto.dynam... |
import cPickle
def save(p, filename):
f=file(filename,'wb')
cPickle.dump(p,f,cPickle.HIGHEST_PROTOCOL)
f.close()
def load(filename):
f=file(filename,'rb')
y=cPickle.load(f)
f.close()
return y
|
#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import postgkyl as pg
import scipy.optimize as opt
from mpl_toolkits.axes_grid1 import make_axes_locatable
#tIdxs = (117, 142)
tIdxs = (118,)
q = -1
x = 80
def doubleMaxwell(v, n1, u1, t1, n2, u2, t2):
retu... |
import numpy as np
from pydrake.common.eigen_geometry import AngleAxis
from pydrake.manipulation.planner import DoDifferentialInverseKinematics
from pydrake.math import RigidTransform, RollPitchYaw
from pydrake.systems.framework import BasicVector, LeafSystem, PortDataType
# TODO(russt): Clean this up and move it to... |
#! /usr/bin/env python
def contains_dupes(l):
for orig in range(0, len(l)):
for dup in range(0, len(l)):
if orig == dup: continue
if l[orig] == l[dup]:
return True
return False
def contains_no_dupes(l):
return not contains_dupes(l)
def main():
with op... |
import paddle.fluid as fluid
from paddle.fluid.layers.learning_rate_scheduler import _decay_step_counter
from paddle.fluid.initializer import init_on_cpu
import math
def conv_bn_pool(input,
group,
out_ch,
act="relu",
param=None,
bias... |
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
"""
The class that generates code to keep track of existing python
wrappers for a given root class.
"""
from pybindgen.typehandlers.base import NotSupportedError
class WrapperRegistry(object):
"""
Abstract base class for wrapepr registries.
"""
def __init__(self, base_name):
self.base_name =... |
"""
Wrapper for the layout.
"""
from typing import Dict, Generator, Iterable, List, Optional, Union
from prompt_toolkit.buffer import Buffer
from .containers import (
AnyContainer,
ConditionalContainer,
Container,
Window,
to_container,
)
from .controls import BufferControl, SearchBufferControl, UI... |
# (C) Copyright 1996-2016 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergov... |
from libsaas import http, parsers
from libsaas.services import base
class ActivitiesResource(base.RESTResource):
path = 'activities'
class Activities(ActivitiesResource):
@base.apimethod
def get(self, user_id=None, start=None, limit=None, start_date=None,
end_date=None):
"""
... |
def power(a, n):
if n == 0:
return 1
return a * power(a, n-1)
a = float(input())
n = int(input())
print(power(a, n))
|
import time
from typing import Optional
import torch
from falkon.options import ConjugateGradientOptions, FalkonOptions
from falkon.mmv_ops.fmmv_incore import incore_fdmmv, incore_fmmv
from falkon.utils.tensor_helpers import copy_same_stride, create_same_stride
from falkon.utils import TicToc
# More readable 'pseudo... |
import operator
import numpy as np
import pytest
from pandas.compat import np_version_under1p20
import pandas as pd
import pandas._testing as tm
from pandas.core import ops
from pandas.core.arrays.sparse import (
SparseArray,
SparseDtype,
)
@pytest.fixture(params=["integer", "block"])
def kind(request):
... |
def custom_viz(kernels, path=None, cols=None, size=None, verbose=False):
"""Visualize weight and activation matrices learned
during the optimization process. Works for any size of kernels.
Arguments
=========
kernels: Weight or activation matrix. Must be a high dimensional
Numpy array. Ten... |
from ..enums import *
class EventHandler(object):
"""
just a template class of eventHandler
"""
def handler(self, event: EventType) -> bool:
"""
when the event activated to call this function
:param event: the events args
:return:
"""
pass
|
def bfs(graph,visit):
queue = [[1,1]]
level = []
cnt = 0
while len(queue) is not 0:
for i in range(len(queue)):
visit[queue[i][0]-1][queue[i][1]-1] = 1
if [n, m] in queue:
break
if queue[i][0] - 1 >= 1:
if graph[queue[i][0]-2][q... |
#
# demo_kmeans.py
#
import kmeans
import numpy as np
import matplotlib.pyplot as plt
data = []
number_of_clusters = 5
points_per_cluster = 25
np.random.seed(4)
'''
Generate random clusters.
'''
for _ in range(number_of_clusters):
ages_centroid = np.random.uniform(20.0, 70.0)
income_centroid = np.random.... |
"""Models for Radonarr."""
from dataclasses import dataclass
from datetime import datetime, date
from typing import List, Optional
from .exceptions import RadonarrError
def dt_str_to_d(dt_str: str) -> date:
"""Convert ISO-8601 datetime string to datetime object."""
# utc = True if "Z" in dt_str else False
... |
d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
d_swap = {v: k for k, v in d.items()}
print(d_swap)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
def get_swap_dict(d):
return {v: k for k, v in d.items()}
d_swap = get_swap_dict(d)
print(d_swap)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
d_dupli... |
from plugin.sync.core.enums import SyncData, SyncMedia, SyncMode
from plugin.sync.handlers.core import DataHandler, MediaHandler, bind
from plex import Plex
import logging
import urllib
log = logging.getLogger(__name__)
class Base(MediaHandler):
@staticmethod
def build_action(action, **kwargs):
retu... |
from pprint import pformat
from torchreid.engine import get_initial_lr_from_checkpoint
from torchreid.utils import check_isfile, load_pretrained_weights, read_yaml
from scripts.default_config import merge_from_files_with_base
from scripts.script_utils import build_datamanager, is_config_parameter_set_from_command_lin... |
import os
import tempfile
import pytest
from werkzeug.datastructures import FileStorage
import cgen
import crypto
import req_handler
from backend import keyserver
from backend.req_models import RegisterRequest, VerifyRequest, CapsuleRequest, DecryptRequest
@pytest.fixture
def client():
db_fd, keyserver.app.conf... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ...lib.common import memoize, try_call
@memoize
def have_ffmpeg():
return try_call("which ffmpeg")
@memoize
def have_ffmpeg_vaapi_accel():
return try_call("ffmpeg -hide_banner -hwaccels | grep vaapi")
@memoi... |
# https://pydantic-docs.helpmanual.io/usage/dataclasses/
from mypy_extensions import TypedDict
from typing import Dict, List, Any, Optional
import pydantic
import spec_attribs as a
import radical.utils as ru
class PYDANTIC(pydantic.BaseModel):
kernel : Optional[str] = No... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2019/10/20 10:58
Desc: 外汇配置文件
"""
# headers
SHORT_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36'
}
# url
FX_SPOT_URL = "http://www.chinamoney.com.cn/r/cms/www/chinam... |
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core import serializers
# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.views... |
import numpy as np
import paddle
from paddle.fluid import dygraph
from paddle.fluid import layers
from paddle.fluid.framework import Variable
import cv2 as cv
PTensor = Variable
def broadcast_op(a, b, op='mul'):
a_expand_factors = []
b_expand_factors = []
assert len(a.shape) == len(
b... |
#!/usr/bin/env python3
import argparse
import biotools as bt
# Write a program that computes the amino acid composition of a protein file
# Use a dictionary
# Setup
parser = argparse.ArgumentParser(
description='Shows amino acid composition of a list of protein files')
# Required Arguments
parser.add_argument('--f... |
#tests for util module
import pytest
from astropy import units as u
from tardis import atomic
from tardis.util import species_string_to_tuple, species_tuple_to_string, parse_quantity, element_symbol2atomic_number, atomic_number2element_symbol, reformat_element_symbol, MalformedQuantityError
def test_quantity_parser_n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayEbppInvoiceMerchantEnterstatusQueryModel import AlipayEbppInvoiceMerchantEnterstatusQueryModel
class AlipayEbppInvoiceMerchant... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# triangle(a, b, c) analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'sca... |
# Based on https://github.com/facebookresearch/VideoPose3D
#
# Copyright (c) 2018-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.
#
import torch.nn as nn
class TemporalModelBase(nn.Mod... |
from aiovault import Vault
from conftest import async_test
import pytest
@async_test
def test_audit_syslog(dev_server):
client = Vault(dev_server.addr, token=dev_server.root_token)
# enable syslog
enabled = yield from client.audit.enable('syslog')
assert enabled
backends = yield from client.audi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
import unittest
import sys
sys.path.append('.')
from chempy.geometry import *
################################################################################
class GeometryTest(unittest.TestCase):
def testEthaneInternalReducedMomentOfInertia(self):
... |
# 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 u... |
from lagtraj.forcings.profile_calculation import FORCING_VARS
from .output.ncview_validation import check_for_ncview_warnings, build_valid_encoding
def validate_trajectory(ds_traj):
required_fields = [
"lat",
"lon",
"time",
"u_traj",
"v_traj",
"origin_lat",
... |
#
# 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
# ... |
#!/usr/bin/env python
""" Pascal Interpreter """
from collections import OrderedDict
############################## LEXER #############################
# Token types
# EOF (end-of-file) token is used to indicate that
# there is no more input left for lexical analysis
INTEGER = 'INTEGER'
REAL = 'REAL... |
import tensorly as tl
tl.set_backend('pytorch')
from torch import rand, randn, cos, sin, complex64, exp, matrix_exp, sqrt, unsqueeze, pi
from torch.nn import Module, ModuleList, ParameterList, Parameter
from tensorly.tt_matrix import TTMatrix
from copy import deepcopy
from .tt_operators import identity
from .tt_precont... |
import komand
from .schema import ProcessFileInput, ProcessFileOutput
# Custom imports below
import base64
from komand_awk.util import utils
class ProcessFile(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='process_file',
description='Proces... |
#!/usr/bin/env python
'''
' Riverbed Community SteelScript
'
' get_all_devices.py
'
' Encoding: UTF8
' End of Line Sequence: LF
'
' Copyright (c) 2021 Riverbed Technology, Inc.
'
' This software is licensed under the terms and conditions of the MIT License
' accompanying the software ("License"). This software is dist... |
# -*- coding: utf-8 -*-
result = []
for i in range(10):
a = int(input())
if a <= 0:
result.append("X[%i] = 1"%i)
else:
result.append("X[%i] = %i"%(i, a))
for i in result:
print(i) |
#Day-06 of 100 Days of Coding
#November 24, 2020
#Shazid Hasan Riam
#Problem solved on the given link and this code will not work here
#http://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%203&url=worlds%2Ftutorial_en%2Fhurdle3.jsonhttp://reeborg.ca/reeborg.ht... |
import argparse
import base64
from datetime import datetime
import os
import shutil
import cv2
import numpy as np
import socketio
import eventlet
import eventlet.wsgi
from PIL import Image
from flask import Flask
from io import BytesIO
from keras.models import load_model
import utils
sio = socketio.Server()
app = F... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import collections
import time
import csv
driver = webdriver.Chrome()
driver.get('https://stats.nba.com/search/player-game/... |
import unittest
import torch
from torch import Tensor
from app.classifiers.common_torch import to_prediction_top1, to_prediction_topk, to_prediction_top1_le, \
to_prediction_topk_le
from tests.common import data_provider
import ignite.engine # ignite import bug workaround
from ignite.metrics import TopKCategori... |
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions... |
import codecs
import operator
from typing import (
TYPE_CHECKING,
Any,
Callable,
Collection,
Dict,
Iterable,
NoReturn,
Tuple,
Union,
)
from eth_typing import (
HexStr,
)
from eth_utils.curried import (
apply_formatter_at_index,
apply_formatter_if,
apply_formatter_to_... |
#!/user/bin/python3
#^.^ coding=utf-8 ^.^#
from HelloWorld import cute_split_line
import re
# 1. re.search re.match re.findall
# 2. re.compile
# 3. re.sub
# 4. re.split
|
import matplotlib.pyplot as plt
import numpy as np
LOG_FILE = './log.txt'
def get_log(log):
f = open(log, 'r')
lines = f.readlines()
f.close()
loss = []
for line in lines:
loss.append(float(line.strip('\n').split(' ')[1]))
return loss
def plot_iteration(log):
loss = get_log(log)
plt.plo... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
cap.release()
cv2.destroyAllWindows() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.