content stringlengths 5 1.05M |
|---|
# Copyright 2018, 2019 IBM Corp.
#
# 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 django.contrib import admin
from .models import Attendee, Event
# Register your models here.
admin.site.register(Attendee)
admin.site.register(Event)
|
from features import addFeature
from lib import implants
from lib import globals
import tableprint
import timeago
import sys
import time
global lastImplantCount
lastImplantCount = 0
def delLast(num):
return
num += 4
ERASE_LINE = '\x1b[2K'
CURSOR_UP_ONE = '\x1b[1A'
CURSOR_DOWN_ONE = '\x1b[1B'
print((CURS... |
# Copyright (C) 2016 Red Hat, 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... |
# Generated by Django 2.2.4 on 2019-09-07 07:08
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('systems', '0009_auto_20190907_0708'),
('conditions', '0008_auto_20190907_0340'),
]
operatio... |
import numpy as np
import unittest
import ray
from ray.rllib.policy.sample_batch import SampleBatch
class TestSampleBatch(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_dict_properties... |
import pytest
from eth_utils import keccak
from eth_tester.exceptions import TransactionFailed
from plasma_core.constants import NULL_ADDRESS, NULL_ADDRESS_HEX, MIN_EXIT_PERIOD
from plasma_core.transaction import Transaction, amend_signature
from plasma_core.utils.eip712_struct_hash import hash_struct
from plasma_core.... |
#!/usr/local/bin/python3.7
import re
import sys
from Bio import SeqIO
from Bio.Seq import Seq
# Get path for fasta file containing sequence
def get_sequence():
path = input('File Path: ')
try:
# Parse fasta file into Biopython Seq object
for sequence in SeqIO.parse(path, "fasta"):
... |
from __future__ import print_function
import argparse
import paddle
from data import cfg_mnet, cfg_re50
from models.retinaface import RetinaFace
from paddle.static import InputSpec
parser = argparse.ArgumentParser(description='Test')
parser.add_argument('-m', '--trained_model', default='./weights/mobilenet0.25_Final.... |
from datetime import datetime
def detect():
return (0 <= datetime.now().second <= 10)
# def detect():
# return (25 <= datetime.now().minute <= 35)
# def detect(bytes):
# return (0 <= datetime.now().second <= 10)
# def detect(bytes):
# return (33 <= datetime.now().minute <= 55)
|
# Copyright © VASP Software GmbH,
# Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import pytest
import types
from py4vasp.data import InternalStrain, Structure
@pytest.fixture
def Sr2TiO4(raw_data):
raw_internal_strain = raw_data.internal_strain("Sr2TiO4")
internal_strain ... |
from typing import Optional
from utils import request_get
import os
REST_BASE_URI = os.getenv("BASE_URI_REST") or "http://164.132.169.19:5002"
def get_blocks(limit: Optional[int] = 200):
return request_get("/get_blocks", base_uri=REST_BASE_URI, params={"limit": limit})
def get_all_validators():
return requ... |
from sacred.run import Run
def get_run_params(_run):
report_dir = None
if _run.observers:
for o in _run.observers:
if hasattr(o, 'dir'):
report_dir = o.dir
break
return {'report_dir': report_dir}
__all__ = [
'Run',
'get_run_params',
]
|
import re
class Telefone:
padrao = "([0-9]{2,3})?([0-9]{2})([0-9]{4,5})([0-9]{4})"
def __init__(self, telefone):
if self.valida_telefone(telefone):
self._numero = telefone
else:
raise ValueError("Número Incorreto!")
def __str__(self):
return self.format_n... |
#- Converted from:
#- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
#- (excluding vnd. tree types)
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2011-2013, University of Oxford"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
FileMimeTypes = (
{ (... |
# coding: utf-8
from django.conf import settings
def store_access_token_in_session(token, request):
request.session[ACCESS_TOKEN_SESSION_KEY] = token
REQUEST_TOKEN_SESSION_KEY = getattr(
settings, 'UPWORK_OAUTH_REQUEST_TOKEN_SESSION_KEY', '_ort')
u"""OAuth _request token_ will be stored in user's session u... |
import pytest
from ordered_set import OrderedSet
from sentence2pronunciation.lookup_cache import get_empty_cache
from text_utils.language import Language
from text_utils.pronunciation.main import (EngToIPAMode, __get_arpa_oov,
__get_eng_ipa, __get_ger_ipa,
... |
# ==============================================================================
# Authors: Patrick Lehmann
#
# Python functions: A streaming VHDL parser
#
# Description:
# ------------------------------------
# TODO:
#
# License:
# ===============================================================... |
def make_nCr_mod(max_n=2 * 10**5, mod=10**9 + 7):
max_n = min(max_n, mod - 1)
fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1)
fact[0] = 1
for i in range(max_n):
fact[i + 1] = fact[i] * (i + 1) % mod
inv_fact[-1] = pow(fact[-1], mod - 2, mod)
for i in reversed(range(max_n)):
... |
'''
Return data to a redis server
This is a VERY simple example for pushing data to a redis server and is not
necessarily intended as a usable interface.
Required python modules: redis
'''
import json
try:
import redis
has_redis = True
except ImportError:
has_redis = False
__opts__ = {'redis.db': '0',
... |
import logging
from datetime import datetime
from config import LOGGING_LEVEL
logging.basicConfig(filename='Logs/{:%Y-%m-%d}.log'.format(datetime.now()),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=LOGGING_LEVEL)
log = logging.getLogger(__name__)
|
from collections import defaultdict
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = defaultdict(list)
for u, v in prerequisites: graph[u].append(v)
visited = [0] * numCourses
def dfs(i):
if visited[i] == 1: return... |
# RoboRIO pins for Flash/Poncho
RIGHT_MAIN_DRIVE = 0
LEFT_MAIN_DRIVE = 9
FRONT_STRAFE = 2
BACK_STRAFE = 5 |
"""
Usage:
ansible-fsm [options] run <fsm.yml> [<channels.yml>] [<uuid>]
ansible-fsm [options] install <uuid> <output>
ansible-fsm [options] diff <fsm.yml> <uuid>
ansible-fsm [options] merge <fsm.yml> <uuid> [<output>]
ansible-fsm [options] push <fsm.yml> [<uuid>]
Options:
-h, --help Sh... |
################################################################################
# System dependencies
################################################################################
import os
import time
import numpy as np
from scipy.stats import pearsonr
#############################################################... |
import yaml
from asyncio import get_event_loop, coroutine
import configuration
from gestionaleimmobiliare.sync_agenzia.agent import SyncAgenziaAgent
@coroutine
def main():
verona_agent = SyncAgenziaAgent(configuration.get().agencies_configuration[0])
verona_agent.synchronize_wordpress()
print(verona_a... |
import time
from typing import Callable
def timing(f: Callable) -> None:
def timing_wrapper(*args, **kw):
print(f'Start function {f.__name__}, begin timing...')
begin_time = time.time()
result = f(*args, **kw)
end_time = time.time()
print(f'Finished function {f.__name__},... |
from mmcv.cnn import build_model_from_cfg
from mmcv.utils import Registry
MODELS = Registry('models', build_func=build_model_from_cfg)
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
POSENETS = MODELS
MESH_MODELS = MODELS
def build_backbone(cfg):
"""Build backbone."""
return BACKBONES.build... |
arr = list(map(int,input().split()))
count = 0
for day in range(arr[0],arr[1]+1):
if (day-int(str(day)[::-1]))%arr[2] == 0:
count += 1
print(count)
|
from datetime import date, datetime
from typing import overload, Literal, Union, Any, Mapping, Optional
from arago.hiro.model.graph.attribute import ATTRIBUTE_T
from arago.hiro.model.graph.dict import GraphDict
from arago.hiro.model.graph.vertex import Vertex, VERTEX_T_co, HIRO_BASE_CLIENT_T_co
from arago.hiro.utils.c... |
#!/usr/bin/env python
from Annotation import Annotation,tokenize_sv
from sv2_backend import format_chrom
from collections import OrderedDict
from pybedtools import BedTool
import sys
class VCF():
def __init__(self,fh=None):
self.fh=fh
self.Annotations=None # Annotation object
self.genotypes={} # [(c,s,e,cl)]=[ge... |
#!/usr/bin/python3
import time
from web3 import Web3, KeepAliveRPCProvider, IPCProvider
web3 = Web3(KeepAliveRPCProvider(host='127.0.0.1', port='8545'))
# Global Declarations
global true
global false
global snm_account_0_a
global snm_account_1_a
global snm_account_2_a
global snm_account_3_a
global snm_accou... |
from promval.extractor import AggregationGroupExtractor
def test_aggregation_group_extractor():
expr = """
avg by (first, second)(metric{label='thing'})
"""
extractor = AggregationGroupExtractor()
items = extractor.extract(expr)
assert items == [["first", "second"]]
def test_aggregation_... |
import itk
import numpy as np
im=itk.imread('data/KitwareITK.jpg', itk.UC)
arr = itk.array_from_image(im)
arr[0,0]
print("Pixel in array: %f"%arr[0,0])
arr[0,0]=125
print("Pixel in array: %f"%arr[0,0])
print("Pixel in image: %f"%im.GetPixel([0,0]))
|
# -------------------------------------------------------------------------
#
# FuriosaAI CONFIDENTIAL
# __________________
#
# FuriosaAI Incorporated, All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains
# the property of FuriosaAI and its suppliers,
# if any. The intellectual and techni... |
import os
import json
from datetime import datetime
import pandas as pd
from catboost.core import CatBoost
def create_submit_files(result: pd.DataFrame, meta_info: dict=None, name: str=None):
creation_time = "_".join(str(datetime.now()).split())
folder_name = f"{creation_time}_{name}"
os.mkdir(f"submits/{folder_... |
#!/usr/bin/env python
from sexp_io import parse, serialize
from desugar import desugar
from cps_transform import cps_transform, curry
from primitives import wrap, PRIMITIVE_NAMES
from parse_tree import structure, Variable, If, Begin, Application, Lambda, \
Literal, SetBang
from lift import rename, find_lambdas... |
from numpy import zeros,sqrt,linspace,unique
from scipy import linalg
#======================================================================
# python function to calculate element mass and stiffness matrices for
# vertical bending given beam mass per unit span "m" (mass/length) and
# flexural stiffness "EI" (Force l... |
repo_name = '{{ cookiecutter.repo_name }}'
if hasattr(repo_name, 'isidentifier'):
assert repo_name.isidentifier(), 'Repo name should be valid Python identifier!'
|
from django.db.models import QuerySet
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.urls import path
from django.http import HttpRequest, HttpResponse
from django.core.signing import BadSignature, SignatureExpired
from django.contrib.auth import ge... |
# Copyright 2019 The ASReview 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 applicabl... |
import pytest
from smokeyfeet.minishop.models import Product
@pytest.mark.django_db
def test_product_str(product_factory):
product = product_factory(name="quux")
assert str(product) == "quux"
@pytest.mark.django_db
def test_in_stock(product_factory):
p0 = product_factory(num_in_stock=0)
assert not ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .hash_sha3_512 import hash_sha3_512_encode, hash_sha3_512_check
class TestHashSHA3512(unittest.TestCase):
def test_hash_sha3_512_encode(self):
s = 'hello,world!'
r = hash_sha3_512_encode(s)
print('hash sha3_512 encode:', r... |
#!/usr/bin/env python2.5
import cgi
import os
import shutil
import sys
import sqlite3
SCREENS = 5
COLUMNS = 4
ROWS = 4
HOTSEAT_SIZE = 5
CELL_SIZE = 110
DIR = "db_files"
AUTO_FILE = DIR + "/launcher.db"
INDEX_FILE = DIR + "/index.html"
def usage():
print "usage: print_db.py launcher.db -- prints a launcher.db"
p... |
from argparse import ArgumentParser
import numpy as np
import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from atc.models import MlpModel, ATCEncoder
from atc.utils import update_state_dict
from tom.datasets import *
class BCMLP(pl.LightningModule):
... |
# # -*- coding: utf-8 -*-
# # Part of Odoo. See LICENSE file for full copyright and licensing details.
from unittest.mock import patch
from odoo.tests import common
@common.tagged('post_install','-at_install')
class base_automation_test(common.TransactionCase):
def setUp(self):
super(base_automation_tes... |
import urllib2
import json
# Automatically geolocate the connecting IP
f = urllib2.urlopen('http://freegeoip.net/json/')
json_string = f.read()
f.close()
location = json.loads(json_string)
#print(location)
location_city = location['city']
print 'City : ' + location_city
location_state = location['region_name']
print '... |
from __future__ import print_function
import os
import sys
import click
import tarfile
import tempfile
from fnmatch import fnmatch
from distutils.version import LooseVersion
import requests
import yaml
from cibuildwheel.__main__ import main as cibuildwheel
from .numpy import MIN_NUMPY
from .config import PYTHON_TA... |
"""This module includes functionality to work with Movies nodes."""
import logging
from neo4j import exceptions
from elasticsearch import ElasticsearchException
from app import NEO4J_DRIVER, APP_CONFIG
from app.es import ElasticSearchDriver
from app.exceptions import DatabaseError, DBNoResultFoundError
from app.util... |
from .thin_edge_client import SenseHatThinEdgeClient |
# Copyright 2017 NTT Corporation. 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 ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pyoneer.activations.activations_impl import swish
__all__ = ["swish"]
|
from __future__ import unicode_literals
from django.db import models
class Tag(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
id = models.IntegerField(primary_key=True)
title ... |
from datetime import datetime
from entities import Greeting, storage
greeting_foo = {"name": "foo", "time": datetime(2000, 1, 1)}
greeting_bar = {"name": "bar", "time": datetime(2018, 2, 13)}
def test_format():
assert repr(Greeting.create_greeting(greeting_bar)) == \
"<Greeting to bar at 2018-02-13 00:00... |
import os
import unittest
import tempfile
import time
from fase_lib import fase
from fase_lib.fase_model import fase_model
import fase_client
import fase_resource_manager
class ClientTestService(fase.Service):
def OnStart(self):
screen = fase.Screen(self)
screen.AddText(id_='text_name_id', hint='Enter Na... |
from aiohttp_apispec_plugin.aiohttp_plugin import AioHttpPlugin
|
"""
Package setup
"""
import setuptools
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
setuptools.setup(
name="python-rclone",
version="0.0.2",
author="Dragos Dascalita Haut",
author_email="ddragosd@gmail.com",
description="Rclone wrapper for python",
long_description=LONG... |
# Generated by Django 3.2.8 on 2021-10-09 19:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='HourlyData',
fields=[
('id', models.BigAuto... |
from pyfar import Orientations
import numpy as np
import numpy.testing as npt
import pytest
from unittest.mock import patch
from pyfar.testing.stub_utils import stub_str_to_type, stub_is_pyfar_type
import os.path
import pathlib
import scipy.io.wavfile as wavfile
from pyfar import io
from pyfar import Signal
from pyfa... |
DATA = [ '210.153.84.0/24',
'210.136.161.0/24',
'210.153.86.0/24',
'124.146.174.0/24',
'124.146.175.0/24',
'202.229.176.0/24',
'202.229.177.0/24',
'202.229.178.0/24']
|
import os
import json
import numpy as np
from keras.models import load_model
from azureml.core.model import Model
from azureml.monitoring import ModelDataCollector
def init():
global model
global inputs_dc, prediction_dc
try:
model_name = 'MODEL-NAME' # Placeholder model name
print('Lo... |
# Copyright 2018 The TensorFlow Probability 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 applicable law o... |
from __future__ import absolute_import
import torch
import torch.nn as nn
from torch.autograd import Variable
import lpips
from . import pretrained_networks as pn
def spatial_average(tensors, keepdim=True):
return torch.mean(tensors, [2, 3], keepdim=keepdim)
def upsample(tensors, output_size=(64, 64)): # ass... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# GridVCS repos
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import numpy as np
from io import StringIO
from filterpy.kalman import KalmanFilter
class TrajectoryFilter(KalmanFilter):
""" A KalmanFilter implementation for a trajectory
TrajectoryFilter is a base class to track an object that leaves a trajectory.
... |
#!/usr/bin/env python3
import sys
import pylxd
import random
import string
import urllib
import subprocess
import re
import os
import netifaces
import docker
if len(sys.argv) != 2:
print("Usage:",sys.argv[0],"<test-bed name>")
sys.exit(1)
if os.geteuid() != 0:
print("You need root permissions to set-up ... |
# Copyright 2017 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Copyright 2022 Hoshea Jiang
#
# 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... |
#!/usr/bin/env python
#from difflib import SequenceMatcher
import discord
import numpy as np
from joblib import dump, load
import sys
import os
import math
helpText = "Tell me the sizes of two of your gems and i will calculate the optimal size of the third gem based on the current ritual bonus. If running a ritual wi... |
import os
import maya.cmds as cmds
import pyblish.api
import openpype.api
def is_subdir(path, root_dir):
""" Returns whether path is a subdirectory (or file) within root_dir """
path = os.path.realpath(path)
root_dir = os.path.realpath(root_dir)
# If not on same drive
if os.path.splitdrive(path... |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Saurav new BCCI president and this is UAT env"
|
from pyruicore.field import Field
from pyruicore.model import BaseModel
__all__ = ["BaseModel", "Field"]
|
import graphene
from graphene_django import DjangoObjectType
from .models import ClientProfile, StylistProfile
class ClientProfileModel(DjangoObjectType):
class Meta:
model = ClientProfile
class StylistProfileModel(DjangoObjectType):
class Meta:
model = StylistProfile
class Query(graphene... |
'''
Description: 使用最小二乘法求解一元线性回归方程 y(x,w) = w0 + w1 * x 系数
Author: xuzf
Date: 2021-03-21 07:56:48
FilePath: \algorithm-toy\Gradient-descent\Least-squares-method.py
'''
import numpy as np
def least_squares_fit(X, Y):
X_array = np.array(X)
Y_array = np.array(Y)
n = len(X)
w1 = n * np.dot(X_array, Y_arr... |
# -*- coding: utf-8 -*-
import numpy as np
import multiprocessing as mp
from functools import partial
from statistics import mode, StatisticsError
from math import radians, sin, cos, sqrt, tan, atan2, floor, pi, degrees
__all__ = ["make_point_cloud", "rel2abs", "project_point_cloud", "rotation_matrix", "point_cloud2... |
"""
MicroPython 74HC595 8-Bit Shift Register
https://github.com/mcauser/micropython-74hc595
MIT License
Copyright (c) 2021 Mike Causer
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 rest... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
import seaborn as sns
import librosa
import librosa.display
from string import ascii_lowercase, ascii_uppercase
from numpy import in1d
from matplotlib import rcParams
from mpl_toolkits.axes_grid1.axes_... |
import shutil
import os
from napkinxc.datasets import load_dataset
from napkinxc.models import BR, PLT
from napkinxc.measures import precision_at_k
model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test-eurlex-model")
data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test-data... |
"""The WaveBlocks Project
Function for plotting complex matrices with the
phase of the entries encoded into the usual color code.
@author: R. Bourquin
@copyright: Copyright (C) 2011 R. Bourquin
@license: Modified BSD License
"""
from matplotlib.pyplot import gca
from matplotlib import ticker
from color_map import c... |
def HarmonicRestraintPositions (atom_indices=None, K=None, positions=None):
#2.5 * unit.kilocalories_per_mole/unit.angstrom**2
from openmm import CustomExternalForce
from openmm.unit import md_unit_system
harmonic_restraint_potential = "0.5*K*((x-xo)^2 + (y-yo)^2 + (z-zo)^2)"
force = CustomExterna... |
# Copyright 2002-2009, Distributed Systems Architecture Group, Universidad
# Complutense de Madrid (dsa-research.org)
#
# 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 ... |
# coding=utf-8
import os
import sys
try:
from HTMLParser import HTMLParser
except:
from html.parser import HTMLParser
import requests
sess = requests.session()
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.strict = False
self.convert_charrefs = True
... |
import os
import sys
min_seed = 5
max_seed = 15
filename = "test_agents.py"
for i in range(min_seed,max_seed):
print("running script " + filename + " with seed " + str(i))
os.system('python3 ' + filename + " " + str(i))
|
import os,sys
import h5py,csv
from pyspark import SparkContext
import read
# read multiple hdf5 files
def test_h5sparkReadmultiple():
#import read
#print lib_path
if(len(sys.argv)!=4):
print "arguments: csv_file_path number_partitions_csv number_partitions_hdf5"
print len(sys.argv)
sys.ex... |
from world.meat import Meat
def eat(context):
being = context.being
world = context.world
position = being.position
item = world.get(position)
if item != None and isinstance(item, Meat):
q = item.quantity
being.gain_strength(q)
remaining = item.consume(q)
if remaining == 0: world.remove... |
#!/usr/bin/env python
# Copyright New York University and the in-toto contributors
# SPDX-License-Identifier: Apache-2.0
"""
<Program Name>
test_common.py
<Author>
Santiago Torres-Arias <santiago@nyu.edu>
<Started>
Sept 26, 2017
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test the Signa... |
"""Main script to scrape and aggregate data.
"""
from requests.sessions import Session
import requests
import json
import pandas as pd
import scrape
def main():
""" Tags JSON structure:
[{
Id: string,
TagName: string,
Count: string
(sometimes more attribut... |
import pip
def main():
pip.main(['install', '-r', 'requirements.txt'])
if __name__ == "__main__":
main()
|
"""
Entity and aggregate base classes.
This file is part of the everest project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Created on May 12, 2011.
"""
from everest.constants import RELATIONSHIP_DIRECTIONS
from everest.constants import RELATION_OPERATIONS
from everest.entities.inter... |
nums = [
[59],
[73, 41],
[52, 40, 9],
[26, 53, 6, 34],
[10, 51, 87, 86, 81],
[61, 95, 66, 57, 25, 68],
[90, 81, 80, 38, 92, 67, 73],
[30, 28, 51, 76, 81, 18, 75, 44],
[84, 14, 95, 87, 62, 81, 17, 78, 58],
[21, 46, 71, 58, 2, 79, 62, 39, 31, 9],
[56, 34, 35, 53, 78, 31, 81, 18, 90, 93, 15],
[7... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Lab ISO request mapper.
"""
from sqlalchemy.orm import relationship
from everest.repositories.rdb.utils import mapper
from thelma.entities.experiment import... |
def find_even_len_words():
return [x for x in input().split() if len(x) % 2 == 0]
word_list = find_even_len_words()
[print(x) for x in word_list] |
from rest_framework import serializers
from . import models
from damstagram.users import serializers as user_serializers
from damstagram.images import serializers as image_serializers
class NotificationSerializer(serializers.ModelSerializer):
notification_from = user_serializers.ListUserSerializer()
notifica... |
import os
import pkg_resources
import tempfile
from cc.i18n import util
def test_get_all_trans_stats():
"""
Test the get_all_trans_stats utility function.
"""
temp_dir = tempfile.mkdtemp()
# write a fake CSV file
transstats = os.path.join(temp_dir, 'transstats.csv')
ts_file = file(transs... |
#-*- coding: utf-8 -*-
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.au... |
from random import random, sample
from trains import Task
# define random search space,
# This is a simple random search
# (can be integrated with 'bayesian-optimization' 'hpbandster' etc.)
space = {
'batch_size': lambda: sample([64, 96, 128, 160, 192], 1)[0],
'layer_1': lambda: sample(range(128, 512, 32), 1)... |
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import numpy.fft as fft
import scipy.signal as sig
# In[1]:
def noisyrk4(s,t,tau,derivsRK,i,vN0,vN1,vN2):
"""modified RK4 integrator including noise
DEPENDENCIES
none
INPUTS
s - initial state vector [delta]
... |
# Create Phantom container via REST GET
import requests
import json
import csv
phantom_host = 'xx.xx.xx.xx'
AUTH_TOKEN = 'xxxx'
headers = {"ph-auth-token": token}
# disable certificate warnings for self signed certificates
requests.packages.urllib3.disable_warnings()
list_id = 7
ep = '/rest/decided_list/{}'.format(l... |
from taskplus.core.serializers.user_serializer import UserEncoder
from taskplus.core.serializers.user_role_serializer import UserRoleEncoder
from taskplus.core.serializers.task_status_serializer import TaskStatusEncoder
from taskplus.core.serializers.task_serializer import TaskEncoder
|
from sys import path
path.append("../src")
from utilities.algorithm.general import check_python_version
check_python_version()
import sys
from algorithm.parameters import params, set_params
from operators.subtree_parse import get_NT_from_str, get_num_from_str, \
generate_key_and_check, check_snippets_for_soluti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.