text stringlengths 2 999k |
|---|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import itertools
import socket
import time
import kdputils.replies
import kdputils.requests
import lldbagilityutils
from kdputils.protocol import (
KDP_FEATURE_BP,
KDP_VERSION,
MAX_KDP_DATA_SIZE,
KDPError,
KDPRequest,
)
logger = lldbagilityutils.creat... |
# Copyright (c) 2017 Boocock James <james.boocock@otago.ac.nz>
# Author: Boocock James <james.boocock@otago.ac.nz>
#
# 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, incl... |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
class NandosUSSpider(scrapy.Spider):
name = "nandos_us"
item_attributes = {'brand': "Nando's", 'brand_wikidata': "Q3472954"}
allowed_domains = ['www.nandosperiperi.com']
start_urls = [
'https://www.n... |
# Copyright (C) 2022 by Higher Expectations for Racine County
r"""Specific column types."""
from sqlite3 import (
Binary,
Date,
)
from numpy import (
bytes_,
float_,
int_,
str_,
)
from column_data_type import ColumnDataType
COLUMN_BLOB = ColumnDataType('blob',
b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import os.path
import shutil
import subprocess
import yaml
# The path used by the bootstrapper
BOOTSTRAPPER_REGISTRY = "/opt/registries/kubeflow/kubeflow"
# The current release of Kubeflow. This should be upgraded on every release.
CURRENT_R... |
"""
Module to read MODPATH output files. The module contains two
important classes that can be accessed by the user.
* EndpointFile (ascii endpoint file)
* PathlineFile (ascii pathline file)
"""
import itertools
import collections
import numpy as np
from numpy.lib.recfunctions import append_fields, stack_arrays
... |
# -*- coding: utf-8 -*-
"""
Customized Widgets
:author: Sergio Aparicio Vegas
:version: 0.1
:date: 28 Nov. 2017
"""
__docformat__ = "restructuredtext"
from PyQt5 import QtWidgets
from PyQt5.Qt import Qt, QEvent
class QSpinBoxRetrofitWidget(QtWidgets.QSpinBox):
def __init__(self, planHea... |
"""
link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii
problem: 升序数组从中间某点断开后重拼接,求最小值,数组中元素可能相等
solution: 二分。与 153 相比,重复元素唯一可能的影响的数组前后一致,向前移l以排除此场景即可。
"""
class Solution:
def findMin(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l < r and nums[l] == nums[r]... |
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import os, sys
import configparser
import csv
import time
re="\033[1;31m"
gr="\033[1;32m"
cy="\033[1;36m"
def banner():
print(f"""
{re}╔╦╗{cy}┌─┐┬ ┌─┐{r... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
de... |
"""
Implement a function isMember.
It takes an input list of strings called words eg. ["foo", "bar", "baz"]
and an input string called query eg. "foo",
It should return true if a query matches any string in words.
If a query includes * it's considered a wildcard.
ie. it matches exactly one character o... |
#!/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 difflib
import logging
import multiprocessing
import os
import time
from queue import Empty
from typing import... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Ian Good
# Copyright 2014 Ryan Lane
#
# 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/LICEN... |
"""
Lib module.
"""
import datetime
import re
from pathlib import Path
VAR_DIR = Path(__file__).parent / "var"
PDF_DIR = VAR_DIR / "pdf"
PNG_DIR = VAR_DIR / "png"
SLUG_PATTERN = re.compile(r"[\W_]+")
ADD_DATETIME_DEFAULT = False
DATETIME_FORMAT = "%Y-%m-%d--%H:%m"
def read(path_str: str) -> list[str]:
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, time
from selenium import webdriver
reload(sys)
sys.setdefaultencoding('utf-8')
def update_system(baseurl):
driver = webdriver.Firefox()
driver.set_window_size(1024, 768)
driver.get(baseurl)
driver.find_element_by_link_text('Information').clic... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import torch
from torchvision import transforms
normalization_parameters = {"mean": [0.485, 0.456, 0.406],
"std": [0.229, 0.224, 0.225]}
use_bbox_info_config = {False: {"max_trial": 1, "minimum_bbox_interlap": 0.0},
... |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
__all__ = ['birealnet18', 'birealnet34']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... |
class Clkdiv:
def __init__(self):
self.c = 0
def tick(self, n) -> bool:
self.c += 1
if self.c == n:
self.c = 0
return True
return False
class FPS:
def __init__(self):
self.timeElapsed = 0
def tick(self, fps, dt) -> bool:
self.tim... |
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, Yoel Cortes-Pena <yoelcortes@gmail.com>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details... |
'''
Created on Apr 27, 2016
@author: Brian
'''
class Restrictions(object):
def __init__(self,sd=None,ed=None,sl=None,el=None,rLocs=None,startDriveTime=None,endDriveTime=None):
self.startDate=sd
self.endDate=ed
self.startLoc=sl
self.endLoc=el
self.restrictedLocations=rLocs
... |
from discord.ext import commands
import discord
class länder(commands.Cog):
def __init__(self,bot):
self.bot = bot
@commands.command()
async def seyffenstein(self, ctx):
embed = discord.Embed(title="Fakten über das Erzherzogtum Seyffenstein")
embed.add_field(name="Landesoberhaupt",... |
# Generated by Django 3.0.7 on 2020-07-03 15:42
import device.models
from django.db import migrations, models
import django.utils.timezone
import stdimage.models
class Migration(migrations.Migration):
dependencies = [
('device', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
from osutk import Beatmap
from osutk import SampleSet
import osutk.osufile.beatmap as bm
import unittest
__author__ = 'Agka'
beatmap = None
def setUpModule():
global beatmap
print("Attempting to load test1.osu.")
beatmap = Beatmap()
beatmap = bm.read_from_file("maps/test1.osu")
class TestBeatmapLoad... |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
############################################################################
#
# This file is the collectd 'Platform CPU Usage' Monitor.
#
# The Platform CPU Usage is calculated as an averaged percentage of
# platform core usable ... |
from unittest import TestCase
import numpy as np
from scattertext.termscoring.ScaledFScore import ScaledFScore, ScaledFScorePresets
class TestScaledFScore(TestCase):
def test_get_scores(self):
cat_counts, not_cat_counts = self._get_counts()
scores = ScaledFScore.get_scores(cat_counts, not_cat_co... |
from tests import app
from flask import request
@app.route("/test-mode")
def test_mode():
assert 'Content-Type' not in request.headers
assert 'Content-Length' not in request.headers
assert len(request.data) == 0
return 'Hello World!'
|
import _plotly_utils.basevalidators
class MarkerValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self,
plotly_name='marker',
parent_name='scattergl.unselected',
**kwargs
):
super(MarkerValidator, self).__init__(
plotly_name=plotly_na... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Schema for gitlab-ci.yaml configuration file.
.. literalinclude:: ../spack/schema/gitlab_ci.py
:lines: 13-
"""
ima... |
# Copyright 2019 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 numpy as np
import time
import random
import math
import pygame
import cv2
screen_width = 768
screen_height = 768
class Player:
size = 8
alive = True
def __init__(self, screen):
self.screen = screen
self.position = [screen_width / 2, screen_height / 2]
self.color = (0, 0, 25... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
verbose_name_plural = "categories"
def __str__(self):
r... |
"""This test do not ensure correct server side behaviour they only check that the cli makes the correct requests and
that validates input correctly"""
import os
import tempfile
import unittest
import sys
import json
from io import StringIO
from cbmgr import CouchbaseCLI, CollectionManage
from mock_server import MockRES... |
from functools import cmp_to_key
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return "{} {}".format(self.name, self.score)
def comparator(a, b):
if a.score == b.score and a.name == b.name:
return ... |
from rest_framework import viewsets
from rest_framework.renderers import BrowsableAPIRenderer
from app_api.custom_render import MyJSONRenderer
class MyViewSet(viewsets.ReadOnlyModelViewSet):
pagination_class = None
renderer_classes = (MyJSONRenderer, BrowsableAPIRenderer) |
# flake8: noqa
from fabric.testing.fixtures import cxn
|
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# 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 ... |
# Copyright 2019 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 os
from flask import Flask, render_template, request
from peewee import *
app = Flask(__name__)
db = SqliteDatabase("core.db")
class User(Model):
id = AutoField()
password = CharField()
username = CharField(unique=True)
class Meta:
database = db
@db.connection_context()
def initia... |
from django.urls import path
from django.conf.urls import url
from . import views
app_name = 'main'
urlpatterns = [
path('', views.index, name='index'),
path('<int:nav_id>/', views.nav, name='nav'),
path('subject/<str:code>', views.subject, name='subject'),
path('subject/<str:code>/<int:post_id>', vie... |
from constants import SAVE_DIR
import dill
import os
import pyclbr
import sys
def get_previous_class_name(scene_class):
calling_class_name = scene_class.__class__.__name__
calling_class_module = scene_class.__class__.__module__
module = pyclbr.readmodule(scene_class.__class__.__module__)
classes = sor... |
import configparser
import os
import subprocess
# Set env variable
app_name = os.getenv("INPUT_APP_NAME")
api_endpoint = os.getenv("INPUT_API_ENDPOINT")
# {user}/{project}/{app}
workflow_path = os.getenv("INPUT_WORKFLOW_PATH")
auth_token = os.getenv("INPUT_AUTH_TOKEN")
# Write SBG config
config = configparser.Config... |
#
# 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
# ... |
import os
from os.path import exists
import pytest
from pip.locations import write_delete_marker_file
from pip.status_codes import PREVIOUS_BUILD_DIR_ERROR
from tests.lib.local_repos import local_checkout
def test_cleanup_after_install(script, data):
"""
Test clean up after installing a package.
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provide the basic components for RL algorithms
Dependencies:
- `pyrobolearn.tasks`
- `pyrobolearn.approximators` (e.g. `pyrobolean.policies`, `pyrobolearn.values`, `pyrobolearn.models`,...)
- `pyrobolearn.envs`
"""
import numpy as np
from pyrobolearn.storages im... |
# Generated by Django 2.2.2 on 2019-09-18 18:42
from django.db import migrations, models
import django.db.models.deletion
import email_auth.models
class Migration(migrations.Migration):
dependencies = [("email_auth", "0003_rm_emailaddress_normalizedaddress")]
operations = [
migrations.CreateModel(
... |
import json
import os
import shutil
import numpy as np
import pytest
from sklearn.metrics import mean_absolute_error
from fedot.core.pipelines.node import PrimaryNode, SecondaryNode
from fedot.core.pipelines.pipeline import Pipeline
from fedot.core.pipelines.template import PipelineTemplate, extract_subtree_root
from... |
#===============================================================================
# Copyright 2017-2020 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.apa... |
"""
Defines utility functions for planning in the sorting domain
"""
import copy
from collections import OrderedDict
import itertools
import numpy as np
import random
import time
from core.internal_repr.plan import Plan
from core.util_classes.namo_predicates import dsafe, GRIP_VAL
from core.util_classes.openrave_body ... |
import math
from functools import partial
import numpy as np
class LRSchedulerStep(object):
def __init__(self, fai_optimizer, total_step, lr_phases, mom_phases):
self.optimizer = fai_optimizer
self.total_step = total_step
self.lr_phases = []
for i, (start, lambda_func) in enumera... |
#!/usr/bin/env python
# coding: utf-8
# In[7]:
try:
get_ipython().system('jupyter nbconvert --to script supervisor_test.ipynb')
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
except:
pass
# In[1]:
def updateCanStatus():
for can in cans:
... |
import datetime
import json
import threading
import uuid
from collections import defaultdict
from copy import deepcopy
from dictdiffer import diff
from inspect import signature
from threading import Lock
from pathlib import Path
from tzlocal import get_localzone
from .logger import logger
from .settings import CACHE_... |
import unittest
from src.nirvana.coalesce.coalesce_strategies import coalesce_weighted_mean, coalesce_mean_ignore_api1
class TestCoalesceStrategies(unittest.TestCase):
def test_coalesce_weighted_mean(self):
# Given
mock_insurance_data = {"api1": 20, "api2": 40, "api3": 25}
# When
... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Codebase for the paper: How Many Random Seeds? Statistical Power Analysis in Deep Reinforcement Learning Experiments.
Here we implement five functions:
1) welch_test: performs Welch's t-test at significance level alpha. Wraps around ttest_ind function of scipy. See
function documentation.
2) bootstrap_test: perfo... |
import turtle
polygon = turtle.Turtle()
num_sides = 6
side_length = 70
angle = 360.0 / num_sides
for i in range(num_sides):
polygon.forward(side_length)
polygon.right(angle)
turtle.done()
|
#Author - John and Sean @ Last Mile but its not too many edits away from the Google/OR example here
#https://developers.google.com/optimization/mip/integer_opt
'''
This is when we start to get clever and use the optimization algorithms from Operations Research.
Under the hood, the solvers reduce the solution space clev... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... |
"""
Uses the new generators, which contain the relevant spaces, for both training and holdout,
rather than injecting the spaces from outside.
"""
import argparse
from typing import Tuple, List, Type
from os.path import expanduser as expand
import time
import torch
import numpy as np
from ulfs import file_utils
from t... |
import numpy as np
import pandas as pd
voltages = np.concatenate([
np.arange(0,21),
np.arange(20,-21,-1),
np.arange(-20,1)
])
df = pd.DataFrame({'Voltages': voltages})
df.to_csv('keithley_2400_voltages.csv',index=False)
|
# Generated by Django 3.1.4 on 2020-12-29 00:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20201228_2209'),
]
operations = [
migrations.AlterField(
model_name='user',
name='image',
... |
"""Torch Module for DenseChebConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
class DenseChebConv(nn.Module):
r"""
Description
-----------
Chebyshev Spectral Graph Convolution layer from paper `Convolutional
Neu... |
"""Module handling the application and production log files/"""
import os
import sys
from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
_LOGGER = logging.getLogger('multisma2')
_DEFAULT_LOG_FILE = 'multisma2'
_DEFAULT_LOG_FORMAT = '[%(asctime)s] [%(module)s] [%(leveln... |
import os
import numpy as np
import cv2
import argparse
from multiprocessing import Pool
def image_write(path_A, path_B, path_AB):
im_A = cv2.imread(path_A, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COLOR
im_B = cv2.imread(path_B, 1) # python2: cv2.CV_LOAD_IMAGE_COLOR; python3: cv2.IMREAD_COL... |
from .core import rescale, resize
__all__ = ("resize", "rescale")
|
# -*- coding: utf-8 -*-
import marshmallow as ma
def dict2schema(dct, schema_class=ma.Schema):
"""Generate a `marshmallow.Schema` class given a dictionary of
`Fields <marshmallow.fields.Field>`.
"""
if hasattr(schema_class, "from_dict"): # marshmallow 3
return schema_class.from_dict(dct)
... |
"""
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
from collections import namedtuple
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torchvision import models
from torchvision.models.vgg import model_urls
def init_weights(modules)... |
"""GNN Encoder class."""
from itertools import count
from typing import Any, Dict, NamedTuple, List, Tuple, Optional
import tensorflow as tf
from dpu_utils.tf2utils import MLP
from tf2_gnn.utils.param_helpers import get_activation_function
from .message_passing import (
MessagePassing,
MessagePassingInput,
... |
from django.apps import AppConfig
class CommentsConfig(AppConfig):
name = 'comments'
verbose_name = "Comments"
def ready(self):
"""If django-activity-stream
is installed, register the Comment model for usage."""
try:
from actstream import registry
registry... |
# -*- coding: utf-8 -*-
import data_helper
import word2vec_helpers
import tensorflow as tf
import os ,time, datetime
import numpy as np
from sklearn.model_selection import train_test_split
from URLCNN import *
import tempfile
# Parameters
# =======================================================
# Data loading parame... |
# Copyright 2009-2010 by Ka-Ping Yee
#
# 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 w... |
from .types_ import *
from torch import nn
from abc import abstractmethod
class BaseVAE(nn.Module):
def __init__(self) -> None:
super(BaseVAE, self).__init__()
def encode(self, input: Tensor) -> List[Tensor]:
raise NotImplementedError
def decode(self, input: Tensor) -> Any:
r... |
"""
WSGI config for filterdemoapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANG... |
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'
import warnings
warnings.filterwarnings('ignore')
import ResNetCompleted
import ResNetForUsers
rightModelPath = 'step8/modelInfo/ResNet'
userModelPath = 'step8/userModelInfo/ResNet'
# print(os.path.exists(rightModelPath))
# print(os.path.exists(userModelPath))
# prin... |
import pygame
class Text(pygame.sprite.Sprite):
def __init__(self, type, x, y, font):
self.type = type
self.font = font
self.original_image = font.render(type, True, "red")
self.image = self.original_image
self.x = x
self.y = y
def updateText(self, ty... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
from contextlib import contextmanager
from functools import partial
import warnings
import numpy as np
from jax import device_get, jacfwd, lax, random, value_and_grad
from jax.flatten_util import ra... |
from __future__ import division, print_function, absolute_import
import datetime
import os
import sys
from os.path import join as pjoin
from scipy._lib.six import xrange
if sys.version_info[0] >= 3:
from io import StringIO
else:
from cStringIO import StringIO
import numpy as np
from numpy.testing import (as... |
'''Sources for artifact'''
import os
import re
import shutil
import tempfile
import urllib
import zipfile
import github
class Source(object):
"""Source base class"""
def download(self):
"""Method to download source"""
raise NotImplementedError
def filepath(self):
"""return the p... |
"""
This modules implements the CrawlSpider which is the recommended spider to use
for scraping typical web sites that requires crawling pages.
See documentation in docs/topics/spiders.rst
"""
import copy
import warnings
import six
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http import Reque... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Arab.PNB/Sans_8/udhr_Arab.PNB_Sans_8.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
|
a=int(input())
b=int(input())
S= a+b
print("SOMA = "+str(S)) |
import sys
sys.path.append('../../SourcesEngine/Gugu')
from DatasheetBindingTool import *
# Generates the C++ binding from the xml binding
# > _pathBindingXml : the path to the source xml definition
# > _pathBindingCpp : the destination folder for the C++ files (DatasheetBinding.h and DatasheetBinding.cpp)
... |
import gurobipy as grb
import math
import torch
from itertools import product
from plnn.modules import View, Flatten
from torch import nn
from torch.nn import functional as F
class LinearizedNetwork:
def __init__(self, layers):
'''
layers: A list of Pytorch layers containing only Linear/ReLU/MaxP... |
import os
from datetime import datetime, timedelta
from random import randint
from typing import Optional
import pandas as pd
import pytest
from fastapi.testclient import TestClient
from pytest import fail
from sqlalchemy.orm import Session
from v3io.dataplane import RaiseForStatus
from v3io_frames import CreateError
... |
"""
Band Ratio Measures
===================
Exploring how band ratio measures relate to periodic & aperiodic activity.
"""
###################################################################################################
# Introduction
# ------------
#
# Band ratios measures are a relatively common measure, propose... |
import tensorflow as tf
def L1loss(x, y): # shape(# batch, h, w, 2)
return tf.reduce_mean(tf.reduce_sum(tf.norm(x-y, ord = 1, axis = 3), axis = (1,2)))
def L2loss(x, y): # shape(# batch, h, w, 2)
return tf.reduce_mean(tf.reduce_sum(tf.norm(x-y, ord = 2, axis = 3), axis = (1,2)))
# end point error, each eleme... |
'''OpenGL extension ATI.element_array
This module customises the behaviour of the
OpenGL.raw.GL.ATI.element_array to provide a more
Python-friendly API
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.ATI.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
# For saving the results as gif
import matplotlib
import matplotlib.pyplot as plt
import imageio
# Hyper Parameters
BATCH_SIZE = 32
LR = 0.01
# Greedy policy, sometimes the computer won't choose action ... |
# Generated by Django 2.2.9 on 2020-01-13 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.IntegerField(... |
import numpy as np
from gym.spaces import Box
from metaworld.envs.env_util import get_asset_full_path
from metaworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv, _assert_task_is_set
class SawyerWindowOpenEnv(SawyerXYZEnv):
def __init__(self):
liftThresh = 0.02
hand_low = (-0.5, 0.40, 0.05)... |
"""
Settings for FIESTA are all namespaced in the FIESTA setting.
For example your project's `settings.py` file might look like this:
FIESTA = {
'DEFAULT_SENDER_ID': 'SDMXOPEN',
'DEFAULT_STRING_LENGTH: 31
}
This module provides the `api_setting` object, that is used to access
FIESTA settings, checking for us... |
# 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 ... |
buildroot = '_build'
subdirs = [
'libs/core',
'libs/engine',
'main',
]
buildtypes = {
'debug-gcc' : {
'toolchain' : 'g++',
'cxxflags' : '-fPIC -O0 -g',
'linkflags' : '-Wl,--as-needed',
},
'release-gcc' : {
'toolchain' : 'g++',
'cxxflags' : '-fPIC -O2',
... |
import os
import time
import unittest
from Pegasus.tools import utils
class TestQuoting(unittest.TestCase):
def testQuote(self):
"Quoting should replace non-printing characters with XML character entity references"
self.assertEqual(utils.quote("hello\r\n\t"), "hello%0D%0A%09")
for i in r... |
# Copyright 2019 Mycroft AI 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 or agreed to in writin... |
from rest_framework import serializers
from .models import Comments
class CommentsSerializers(serializers.ModelSerializer):
"""
Creates a serializer for the Comments model
"""
author = serializers.SerializerMethodField()
article_id = serializers.SerializerMethodField()
body = serializers.CharF... |
# Copyright 2015 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 required by applicable law or a... |
# -*- coding: utf-8 -*-
"""
Test Calendar.Inc() routine
"""
import sys
import time
import datetime
import unittest
import parsedatetime as pdt
from parsedatetime.context import pdtContext
from . import utils
class test(unittest.TestCase):
@utils.assertEqualWithComparator
def assertExpectedRes... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ggpo/gui/ui/savestatesdialog.ui'
#
# Created: Tue Aug 25 22:55:14 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.f... |
"""
A store has a dict-like interface to get and set data that a consumer wants to persist between program restarts e.g. the current :mod:`Readings <snsary.models.reading>` in a :mod:`Window <snsary.functions.window>`. This module provides a ``get_storage`` function and a ``HasStore`` trait to make it easy access to pe... |
"""
Short script for running G4TomoSim with or without visualization on
and saving the data automatically with the simulatetomograpy function
"""
# -*- coding: utf-8 -*-
import os
this_directory = os.path.dirname(os.path.realpath(__file__))
import sys
sys.path.insert(0, this_directory + '/../settings')
import tomosi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.