text stringlengths 2 999k |
|---|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lab.environments import LocalEnvironment, MaiaEnvironment
from downward.reports.compare import ComparativeReport
from common_setup import IssueConfig, IssueExperiment, is_test_run
BENCHMARKS_DIR = os.environ["DOWNWARD_BENCHMARKS"]
REVISIONS = ["issue717... |
import os
#import numpy as np
import pyqmc.mc as mc
import sys
import h5py
import jax
import jax.numpy as jnp
import numpy as np
from functools import partial
def limdrift(g, tau, acyrus=0.25):
"""
Use Cyrus Umrigar's algorithm to limit the drift near nodes.
Args:
g: a [nconf,ndim] vector
t... |
# PRIMITIVE DATA TYPES
# str - string
# bool - boolean
# int - integer
# float
# COMPLEX DATA TYPES
# list
# dict
attendees = ['sara', 'alex', 'justin', 'ryan']
for attendee in attendees:
# print(attendee)
pass
# print(attendees[0])
# key = value
employees = {
'sara': 'csa',
'alex': 'it stupport t... |
from __future__ import absolute_import
try:
# use relative import for installed modules
from .vtkIOParallelXMLPython import *
except ImportError:
# during build and testing, the modules will be elsewhere,
# e.g. in lib directory or Release/Debug config directories
from vtkIOParallelXMLPytho... |
# This module contains abstractions for the input stream. You don't have to
# looks further, there are no pretty code.
#
# We define two classes here.
#
# Mark(source, line, column)
# It's just a record and its only use is producing nice error messages.
# Parser does not use it for any other purposes.
#
# Reader(so... |
from rest_framework import viewsets, request
from rest_framework.response import Response
from rest_framework.decorators import action
from posthog.models import Event, Filter
from posthog.utils import request_to_date_query, dict_from_cursor_fetchall
from django.db.models import OuterRef
from django.db import connectio... |
"""Preprocessing of MALDI-TOF spectra."""
from .generic import SubsetPeaksTransformer
from .normalization import TotalIonCurrentNormalizer
from .normalization import ScaleNormalizer
from .topological import TopologicalPeakFiltering
__all__ = [
'ScaleNormalizer',
'SubsetPeaksTransformer',
'TopologicalPeak... |
# -*- coding: utf-8 -*-
"""Command line scripts to launch a `Q2rCalculation` for testing and demonstration purposes."""
from aiida.cmdline.params import options as options_core
from aiida.cmdline.params import types
from aiida.cmdline.utils import decorators
import click
from . import cmd_launch
from ..utils import la... |
# Copyright 2021 Christophe Bedard
#
# 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 wri... |
"""Test suite for our JSON utilities.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#-... |
import requests
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib.error import HTTPError
import re
import json
from base64 import b64encode
def get_playlists(spotify_url):
with open('MY_SECRETS.json', 'r') as f:
spotify_key = json.load(f)['SPOTIFY_KEY']
pl... |
# -*- coding: utf-8 -*-
from collective.solr.interfaces import ISolrConnectionManager
from collective.solr.interfaces import IZCMLSolrConnectionConfig
from collective.solr.local import getLocal
from collective.solr.local import setLocal
from collective.solr.solr import SolrConnection
from collective.solr.utils import g... |
import sys, os, shutil
import h5py
import time
import io
import random
import tempfile
from tqdm import tqdm
from absl import app, flags, logging
from ray.util.multiprocessing import Pool
import gcsfs
import numpy as np
from pathlib import Path
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble ... |
"""
Provides a cross-platform way to figure out the system uptime.
Should work on damned near any operating system you can realistically expect
to be asked to write Python code for.
If this module is invoked as a stand-alone script, it will print the current
uptime in a human-readable format, or display an error messa... |
import numpy as np
from . import dtypes, nputils, utils
from .duck_array_ops import _dask_or_eager_func, count, fillna, isnull, where_method
from .pycompat import dask_array_type
try:
import dask.array as dask_array
except ImportError:
dask_array = None
def _replace_nan(a, val):
"""
replace nan in a... |
import random
import os
def move_all(data_type, shape):
dirpath = os.path.join(data_type, shape)
os.makedirs(dirpath, exist_ok=True)
for filename in os.listdir(shape):
if filename.endswith('.png'):
os.rename(os.path.join(shape, filename),
os.path.join(data_type, sh... |
import torch
#from imsitu_encoder_verbq import imsitu_encoder
from imsitu_encoder_roleqverbq_embdhz import imsitu_encoder
from imsitu_loader import imsitu_loader_roleq_updated
from imsitu_scorer_log import imsitu_scorer
import json
import model_verbq_working
import os
import utils
import time
import random
#from torchv... |
import pytest
from app import create_app
@pytest.fixture
def request_header_secret():
return "dev"
@pytest.fixture
def request_body_positive():
return {"query": "I am having a great day!"}
@pytest.fixture
def request_body_negative():
return {"query": "I am feeling sad today"}
@pytest.fixture
def htt... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2018, Simon Dodsley (simon@purestorage.com)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',... |
# Code generated by protoc-gen-twirp_python v7.1.0, DO NOT EDIT.
# source: service.proto
try:
import httplib
from urllib2 import Request, HTTPError, urlopen
except ImportError:
import http.client as httplib
from urllib.request import Request, urlopen
from urllib.error import HTTPError
import json
f... |
#!/usr/bin/python
"""
Robert Ramsay <robert.alan.ramsay@gmail.com>
Packing your Dropbox
When you're working with petabytes of data, you have to store files wherever they can fit. All of us here at Dropbox are always searching for more ways to efficiently pack data into smaller and more manageable chunks. The fun begins... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
"""
Basic progressbar example script
adapted for use on MagTag.
"""
import time
import board
import displayio
import digitalio
from adafruit_progressbar.progressbar import HorizontalProgressBar
# use built in display (PyPort... |
#!/usr/bin/env python
"""NbConvert is a utility for conversion of .ipynb files.
Command-line interface for the NbConvert conversion utility.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import logging
import sys
import... |
#!/usr/bin/env python3
from pathlib import Path
def get_file(fname):
return Path(__file__).resolve().parent / fname
|
def bytes_to_human(n):
symbols = ('KB', 'MB', 'GB', 'TB', 'PB', 'EB')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return '%sB... |
import spartan
from spartan import expr, core
import numpy as np
from sys import stderr
def qr(Y):
''' Compute the thin qr factorization of a matrix.
Factor the matrix Y as QR, where Q is orthonormal and R is
upper-triangular.
Parameters
----------
Y: Spartan array of shape (M, K).
Notes
----------
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Server.samba_base_folder'
db.add_column(u'servers_server', 'samba_base_folder',
... |
# -*- coding: utf8 -*-
from ssh_config import ConfigParser
from exceptions import StormValueError
from operator import itemgetter
import getpass
__version__ = '0.5.2'
class Storm(object):
def __init__(self, ssh_config_file=None):
self.ssh_config = ConfigParser(ssh_config_file)
self.ssh_config... |
from __future__ import absolute_import
from __future__ import print_function
from functools import wraps
from django.core.cache import cache as djcache
from django.core.cache import caches
from django.conf import settings
from django.db.models import Q
from django.core.cache.backends.base import BaseCache
from typin... |
#! /usr/bin/env python3
from SWEET import *
from mule.postprocessing.JobsData import *
from mule.postprocessing.JobsDataConsolidate import *
from mule.plotting.Plotting import *
sys.path.append('../')
import pretty_plotting as pp
sys.path.pop()
#
# Load data
#
j = JobsData('job_bench_*', verbosity=0)
#
# Create g... |
import setuptools
import re
with open("README.md", "r") as fh:
long_description = fh.read()
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('mrtopo/__main__.py').read(),
re.M
).group(1)
setuptools.setup(
name='mrtopo',
version=version,
packages=setuptools.find_packages(),
u... |
from setuptools import setup
def get_version(filename):
"""
Parse the value of the __version__ var from a Python source file
without running/importing the file.
"""
import re
version_pattern = r"^ *__version__ *= *['\"](\d+\.\d+\.\d+)['\"] *$"
match = re.search(version_pattern, open(filena... |
"""Plotting module for SymPy.
A plot is represented by the ``Plot`` class that contains a reference to the
backend and a list of the data series to be plotted. The data series are
instances of classes meant to simplify getting points and meshes from SymPy
expressions. ``plot_backends`` is a dictionary with all th... |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OSMnx documentation build configuration file.
Created by sphinx-quickstart on Sun Feb 4 13:53:34 2018.
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 fi... |
import os
import sys
from unittest import mock
import pytest
from praw.config import Config
from praw.exceptions import ClientException
class TestConfig:
@staticmethod
def _assert_config_read(environment, mock_config):
mock_instance = mock_config.return_value
Config.CONFIG = None # Force co... |
#! /usr/bin/env python
#Script to
#1-check for cmsScimarkLaunch (infinite loop) scripts
#2-kill them
#3-report their results using cmsScimarkParser.py
from __future__ import print_function
import subprocess,os,sys
def main():
#Use ps -ef to look for cmsScimarkLaunch processes
ps_stdouterr=subprocess.Popen("ps... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#from pylab import plot, show, xlim,figure,hold, ylim,legend, boxplot, setup, axes
import seaborn as sns
# Is this a personal or work computer
# Are you graphing for hood or no hood
Computer = 'personal' #or 'personal' or 'work'
Hood_o... |
"""Test torch algo utility functions."""
import numpy as np
import pytest
import tensorflow as tf
import torch
import torch.nn.functional as F
import metarl.tf.misc.tensor_utils as tf_utils
import metarl.torch.algos._utils as torch_algo_utils
from tests.fixtures import TfGraphTestCase
def stack(d, arr):
"""Stack... |
"""
Projective plane curves over a general ring
AUTHORS:
- William Stein (2005-11-13)
- David Joyner (2005-11-13)
- David Kohel (2006-01)
- Moritz Minzlaff (2010-11)
"""
#*****************************************************************************
# Copyright (C) 2005 William Stein <wstein@gmail.com>
#
# ... |
# Demo with a few examples of using OpenCV functions and UI
# packages: opencv-python
# uses lena: https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png
import numpy as np
import cv2
print("Hello World OpenCV")
print("OpenCV Version:", cv2.__version__)
image = np.ones((256, 256), dtype="uint8")
i... |
# Copyright 2016 - Nokia
#
# 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, sof... |
"""posts table
Revision ID: 5c80010c853a
Revises: 6ca7139bbbf2
Create Date: 2018-06-25 17:18:29.165993
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5c80010c853a'
down_revision = '6ca7139bbbf2'
branch_labels = None
depends_on = None
def upgrade():
# ##... |
def problem255():
pass
|
"""API router
"""
from django.conf.urls import url
from django.urls import path
from rest_framework.routers import DefaultRouter
from vision_on_edge.azure_app_insight.api import views as app_insight_views
from vision_on_edge.azure_parts.api import views as azure_part_views
from vision_on_edge.azure_settings.api impor... |
# orm/exc.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""SQLAlchemy ORM exceptions."""
from __future__ import annotations
from .. import exc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# soco documentation build configuration file, created by
# sphinx-quickstart on Mon Sep 14 08:03:37 2015.
#
# 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
# autog... |
#!/usr/bin/env python3
"""
Main module for the deployable project.
"""
# Bootstrap to be able to perform absolute imports as standalone code
if __name__ == "__main__":
from absolute_import import absolute_import
absolute_import(file=__file__, name=__name__, path=__path__)
# Normal imports
from argparse import Argu... |
import numpy as np
from collections import deque
import pickle
import torch
from utils import collect_trajectories, random_sample
from PPO import PPO
import matplotlib.pyplot as plt
from parallelEnv import *
import gym
env = gym.make("CartPole-v0")
env.reset()
env.seed(2)
obs_dim = env.observation_space.shape[0]
n_ac... |
import numpy as np
from sklearn.preprocessing import LabelEncoder
from lightgbm import LGBMClassifier, LGBMRegressor
def infer_model(df, features, y, n_jobs):
model_class = LGBMRegressor
if len(np.unique(y)) == 2:
y = LabelEncoder().fit_transform(y)
model_class = LGBMClassifier
categorica... |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="dns-prefetch" href="https://assets-cdn.github.com">
<link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
<link rel="dns-prefetch" href=... |
import os
import re
import codecs
from utils import create_dico, create_mapping, zero_digits
from utils import iob2, iob_iobes
def load_sentences(path, lower, zeros):
"""
Load sentences. A line must contain at least a word and its tag.
Sentences are separated by empty lines.
"""
sentences = []
... |
import numpy as np
from vispy.scene.visuals import Compound, Line, Mesh, Text
from vispy.visuals.transforms import STTransform
from ...layers.shapes._shapes_utils import triangulate_ellipse
from ...utils.colormaps.standardize_color import transform_color
from ...utils.theme import get_theme
from ...utils.translations ... |
import os
import random
import numpy as np
import pandas as pd
import tensorflow as tf
from augment import Augment
AUTO = tf.data.experimental.AUTOTUNE
def set_dataset(task, data_path):
trainset = pd.read_csv(
os.path.join(
data_path, 'imagenet_trainset.csv'
)).value... |
#!/usr/bin/python
#coding:utf-8
import numpy as np
import logging
import mylog
import mykmeans as ml
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
def str2num(s):
a = ['very_low', 'Low', 'Middle', 'High']
for i in range(0, len(a)):
if a[i] == s:
return float(i)
if __name__ == '__mai... |
"""
Generalized linear models optimized with online gradient descent from :mod:`creme.optim`.
"""
from .fm import FMRegressor
from .lin_reg import LinearRegression
from .log_reg import LogisticRegression
from .pa import PAClassifier
from .pa import PARegressor
from .softmax import SoftmaxRegression
__all__ = [
'F... |
import json
import os
from astropy.table import Table, Column
from ..config import exporters
from ..qt.widgets import ScatterWidget, HistogramWidget
from ..core import Subset
def save_page(page, page_number, label, subset):
""" Convert a tab of a glue session into a D3PO page
:param page: Tuple of data vie... |
# -*- coding: utf-8 -*-
#
# dedupe documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 10 11:27:59 2014.
#
# 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.
#
# Al... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
from netcdf2geotiff import rgb_geotiff, singleband_geotiff
rgb_geotiff("test3.nc", "test3.tif", "RED", "GREEN", "BLUE", "lat", "lon")
singleband_geotiff("test3.nc", "tests3.tif", "IDEPIX_SNOW_ICE", "lat", "lon") |
from collections import defaultdict
from aoc.util import load_input
def turn(d, fun, sxy, exy):
sx, sy = map(int, sxy.split(","))
ex, ey = map(int, exy.split(","))
for x in range(sx, ex + 1):
for y in range(sy, ey + 1):
d[(x, y)] = fun(d[(x, y)])
def run(data, toggle, turn_on, turn_... |
from sly import Parser
from sly.yacc import _decorator as _
from .domas_lexer import DomasLexer
from .domas_quadruples import Quadruple
from .domas_errors import *
from . import domas_semantic_cube as sm
import json # to debug only
import os
import copy
os.system('color')
class DomasParser(Parser):
# Parser dir... |
# Copyright 2022 Accenture Global Solutions Limited
#
# 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 ... |
#!/usr/bin/env python3
import os
import sys
import random
import numpy as np
src = open("input.txt", "r").readlines()
example = """
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec... |
# -*- coding: utf-8 -*-
"""
@date Created on Thu May 18 14:35:34 2017
@copyright (C) 2015-2016 EOMYS ENGINEERING.
@author: pierre_b
"""
from os.path import join, isfile
from os import remove
import sys
from unittest import TestCase
from ddt import ddt, data
import mock # for unittest of raw_input
from PyQt5 import Q... |
import datetime
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from core.permissions import DjangoModelPermissions
from core.visits.serializer import PopulatedVisitSerializer
from core.models import Visit, FrontDeskEvent,... |
def open_input():
with open("input.txt") as fd:
array = fd.read().splitlines()
array = list(map(int, array))
return array
def part_one(array):
lenght = len(array)
increased = 0
for i in range(0, lenght - 1):
if array[i] < array[i + 1]:
increased += 1
print("part... |
# 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, overload
from ... import _utilities
fro... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import collections
##from ansible.errors import AnsibleOptionsError, AnsibleModuleError##, AnsibleError
####from ansible.module_utils._text import to_native
from ansible.module_utils.six import iteritems, string_types
from ansi... |
import unittest
from okapi.proto.okapi.security.v1 import CreateOberonKeyRequest, CreateOberonTokenRequest, CreateOberonProofRequest, \
VerifyOberonProofRequest, UnBlindOberonTokenRequest, BlindOberonTokenRequest
from okapi.wrapper import Oberon
class KeyTests(unittest.TestCase):
def test_oberon_demo(self):
... |
import numpy, random
class Individual:
def __init__(self,genome, llimits =[], ulimits=[], type=[], LEN = 1,fitness_func = None):
if genome is None:
self.genome = numpy.zeros(LEN,dtype=float)
for gene in range(LEN):
if type[gene] == "integer":
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.19.15
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
f... |
from django.conf.urls.defaults import *
urlpatterns = patterns(
'splango.views',
url(r'^confirm_human/$', 'confirm_human', name="splango-confirm-human"),
url(r'^admin/$', 'experiments_overview', name="splango-admin"),
url(r'^admin/exp/(?P<expname>[^/]+)/$', 'experiment_detail', name="splango-experimen... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import random
import numpy as np
import pandas as pd
import h5py
import matplotlib.pyplot as plt
from math import cos, sin, atan2, sqrt, pi, radians, degrees, ceil, isnan
from skimage import io, transform
BASE_DIR = os.path.dirname(os.path.abspath(__f... |
"""
Premium Question
"""
from collections import deque
__author__ = 'Daniel'
class HitCounter(object):
def __init__(self):
"""
Initialize your data structure here.
calls are being made to the system in chronological order.
It is possible that several hits arrive roughly at the sa... |
'''
Manage yum packages and repositories. Note that yum package names are case-sensitive.
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from . import files
from .util.packaging import ensure_packages, ensure_rpm, ensure_yum_repo
@operation
def key(state, host, key):
'''
Add ... |
from cx_Freeze import setup, Executable
setup(name = "Server" ,
version = "1.0" ,
description = "" ,
executables = [Executable("server.py")])
|
import os
import platform
from collections import OrderedDict
from itertools import chain
from conans.client import defs_to_string, join_arguments
from conans.client.build.cppstd_flags import cppstd_flag
from conans.client.tools import cross_building
from conans.client.tools.oss import get_cross_building_settings
fro... |
import urllib.parse
import requests
class ERMSError(Exception):
pass
class ERMS(object):
"""
Possible queries:
/object?id=eq.574
/object?id=in.(574,575)
"""
# endpoints
EP_OBJECT = 'object'
EP_IDENTITY = 'identity'
EP_CONSORTIUM = 'consortium'
EP_CONSORTIUM_MEMBER = ... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Code(Component):
"""A Code component.
Code is a wrapper for the <code> HTML5 element.
For detailed attribute info see:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code
... |
"""
Train a language model to generate SMILES.
"""
import argparse
import os
import numpy as np
import pandas as pd
import random
import sys
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
# suppress Chem.MolFromSmiles error output
from rdki... |
"""Code for checking and inferring types."""
import collections
import logging
import re
import subprocess
from typing import Any, Dict, Union
from pytype import abstract
from pytype import abstract_utils
from pytype import convert_structural
from pytype import debug
from pytype import function
from pytype import met... |
""" pickle can serialized python objects into a stream of bytes and
deserialize bytes back into objects.
Note:
by design, pickle is unsafe!
"""
import pickle
state_path = 'game_state.bin'
class GameState(object):
def __init__(self):
self.level = 0
self.lives = 4
def save_game(state):
... |
"""Camera platform that receives images through HTTP POST."""
from __future__ import annotations
import asyncio
from collections import deque
from datetime import timedelta
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components import webhook
from homeassistant.comp... |
import os
import sys
import subprocess
import hydra
from omegaconf import DictConfig
from hydra import slurm_utils
@hydra.main(config_path='/h/nng/conf/robust/config.yaml')
def gen_neighborhood_labels(cfg: DictConfig):
base_path = '/h/nng/data'
model_data_path = os.path.join(base_path, cfg.data.task, cfg.eval... |
# 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 may ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: trainer.py
# Author: Qian Ge <geqian1001@gmail.com>
import os
import numpy as np
import tensorflow as tf
def display(global_step,
step,
scaler_sum_list,
name_list,
collection,
summary_val=None,
... |
"""NDG XACML ndg namespace package
NERC DataGrid
This is a setuptools namespace_package. DO NOT place any other
code in this file! There is no guarantee that it will be installed
with easy_install. See:
http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
... for details.
"""
__author__ = "P J K... |
import os
import torch, torchvision, torchtext
from torch import nn, cuda, backends, FloatTensor, LongTensor, optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import Dataset, TensorDataset
from torch.nn.init import kaiming_uniform, kaiming_normal
from torchvision.transform... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .sprin import GlobalInfoProp, SparseSO3Conv
import numpy as np
class ResLayer(torch.nn.Module):
def __init__(self, dim_in, dim_out, bn=False) -> None:
super().__init__()
assert(bn is False)
self.fc1 = torch.nn.Linear(d... |
import argparse
import json
import numpy as np
import os
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from params_conf import N_MODULES, MIN_NUM_MODULES, STIFF_TABLE
from utils import parse_robot_string
def convert_h_to_arch(h_file, morph_file, best_funct... |
"""
pyexcel_xlsw
~~~~~~~~~~~~~~~~~~~
The lower level xls file format handler using xlwt
:copyright: (c) 2016-2021 by Onni Software Ltd
:license: New BSD License
"""
import datetime
import xlrd
from xlwt import XFStyle, Workbook
from pyexcel_io import constants
from pyexcel_io.plugin_api import IW... |
from typing import List, Tuple, Optional
import aiosqlite
from ethgreen.types.blockchain_format.sized_bytes import bytes32
from ethgreen.util.db_wrapper import DBWrapper
class WalletInterestedStore:
"""
Stores coin ids that we are interested in receiving
"""
db_connection: aiosqlite.Connection
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 14/01/2018 01:04 AM
# @Project : BioQueue
# @Author : Li Yao
# @File : gunzip.py
def get_sub_protocol(db_obj, protocol_parent, step_order_start=1):
steps = list()
steps.append(db_obj(software='gunzip',
parameter='{{InputFil... |
import altair as alt
import pandas as pd
from .visitor import visit
from .aggregate import AGG_REPLACEMENTS
@visit.register(alt.JoinAggregateTransform)
def visit_joinaggregate(
transform: alt.JoinAggregateTransform, df: pd.DataFrame
) -> pd.DataFrame:
transform = transform.to_dict()
groupby = transform.ge... |
# 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 os
from typing import Any, List, Optional
import attr
from cv2 import log
import numpy as np
from gym import spaces
from habitat.config... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.23.6
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except Im... |
_game_fields = [
'cover.image_id',
'first_release_date',
'genres.name',
'involved_companies.developer',
'involved_companies.publisher',
'involved_companies.company.country',
'involved_companies.company.name',
'name',
'platforms.name',
'screenshots.image_id',
'slug',
'summ... |
from flask import Flask, render_template, request, jsonify
from pyecharts import options as opts
from pyecharts.charts import Graph
import json
import redis
from flask_cors import *
r = redis.Redis(host="127.0.0.1", port=6379)
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route("/dockermsg", method... |
# Generated by Django 3.0.3 on 2020-06-09 08:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0009_user_username'),
]
operations = [
migrations.CreateModel(
name='RequestLogs',
fields=[
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.