text string | size int64 | token_count int64 |
|---|---|---|
from extras.plugins import PluginConfig
from django.utils.translation import gettext_lazy as _
class NetBoxSecretStore(PluginConfig):
name = 'netbox_secretstore'
verbose_name = _('Netbox Secret Store')
description = _('A Secret Storage for NetBox')
version = '1.0.8'
author = 'NetBox Maintainers'
... | 600 | 198 |
import pandas as pd
def loadRespDiseaseSheet(sheet_name):
filepath = "data/respiratory_disease/IHME_USA_COUNTY_RESP_DISEASE_MORTALITY_1980_2014_NATIONAL_Y2017M09D26.XLSX"
orig_data = pd.read_excel(filepath,
sheet_name = "Chronic respiratory diseases",
... | 722 | 251 |
# pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling... | 111,647 | 38,130 |
import os
import numpy as np
import urllib
from absl import flags
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
flags.DEFINE_float(
"learning_rate", default=0.001, help="Initial learning rate.")
flags.DEFINE_integer(
"epochs", default=100, help="Numb... | 9,319 | 3,187 |
class UrlPath:
@staticmethod
def combine(*args):
result = ''
for path in args:
result += path if path.endswith('/') else '{}/'.format(path)
#result = result[:-1]
return result | 227 | 64 |
from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.engine.create import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
CONNECTION_STRING = "sqlite+pysqlite:///data/db.sqlite"
engine = create_engine(CONNECTION_STRING)
Sess... | 5,229 | 1,983 |
import random
from enum import Enum, auto
class Result(Enum):
BINGO = auto()
HIGH = auto()
LOW = auto()
class GuessNumber:
"""The class randomly chooses an integer
and then tells a human player if a guess is higher or lower than the number
"""
def __init__(self):
"""
A... | 3,436 | 882 |
import asyncio
import sys
import contextlib
@asyncio.coroutine
def show_remaining(dots_task):
remaining = 5
while remaining:
print('Remaining: ', remaining)
sys.stdout.flush()
yield from asyncio.sleep(1)
remaining -= 1
dots_task.cancel()
print()
@asyncio.coroutine
def d... | 706 | 242 |
from nexpose_rest.nexpose import _GET
def getPolicies(config, filter=None, scannedOnly=None):
getParameters=[]
if filter is not None:
getParameters.append('filter=' + filter)
if scannedOnly is not None:
getParameters.append('scannedOnly=' + scannedOnly)
code, data = _GET('/api/3/polici... | 6,372 | 1,985 |
#!/usr/bin/python
# --------------------------------------------------------------------------
#
# MIT License
#
# --------------------------------------------------------------------------
from cybld import cybld_helpers
# --------------------------------------------------------------------------
class CyBldComma... | 3,785 | 1,051 |
import zope.interface
class IFoldable(zope.interface.Interface):
"""Marker interface for a block which can be callapsed."""
| 130 | 37 |
from django.conf import settings
def google_analytics(request):
return {'GOOGLE_ANALYTICS': settings.GOOGLE_ANALYTICS}
def debug_state(request):
return {'DEBUG': settings.DEBUG}
| 190 | 69 |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
from aws_xray_sdk.core import patch_all
patch_all()
from flask import Flask
from flask import request
from fla... | 4,256 | 1,257 |
# check for duplicate detections
import numpy as np
def iou(box1, box2):
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
xB = min(box1[2], box2[2])
yB = min(box1[3], box2[3])
# compute the area of intersection rectangle
... | 1,605 | 547 |
from django.conf.urls import url
from django.conf.urls import patterns
from django.views.generic import TemplateView
view = TemplateView.as_view(template_name='dummy.html')
urlpatterns = patterns('',
url(r'^nl/foo/', view, name='not-translated'),
)
| 256 | 83 |
from rest_framework import serializers
from .models import Subscriber
class SubscriberSerializer(serializers.ModelSerializer):
class Meta:
model = Subscriber
fields = (
'email',
)
| 222 | 57 |
# Copyright 2020-2021 OpenDR Project
#
# 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... | 4,592 | 1,423 |
import collections
try:
stringtype = basestring # python 2
except:
stringtype = str # python 3
def coerce_to_list(x):
if isinstance(x, stringtype):
return x.replace(',', ' ').split()
return x or []
def namedtuple(name, args=None, optional=None):
args = coerce_to_list(args)
optiona... | 799 | 272 |
from capture_monitor import CaptureMonitor
from face_lib import FaceSystem
from visualizer import Visualizer #MainWindow
#from PyQt5 import QtCore, QtGui, QtWidgets
import os
monitor = CaptureMonitor(bb=(0, 0, 600, 480))
face_system = FaceSystem(os.path.abspath("./bio/bio.json"))
def thread_process():
frame = monito... | 632 | 228 |
import fudge
from armstrong.apps.embeds.mixins import TemplatesByEmbedTypeMixin
from .support.models import Parent, Child, TypeModel
from ._utils import TestCase
class TemplateCompareTestMixin(object):
def path_opts(self, obj, use_fallback=False, use_type=False):
return dict(
base=obj.base_la... | 4,454 | 1,530 |
from fastapi import APIRouter
from app.api.auth import router as auth
from app.api.v1 import router as v1
router = APIRouter(prefix='/api')
router.include_router(auth)
router.include_router(v1)
| 196 | 64 |
import requests
import urllib
import os
import re
from bs4 import BeautifulSoup
import json
# save_path = "./foul/"
save_path = "./non_foul/"
url="https://images.api.press.net/api/v2/search/?category=A,S,E&ck=public&cond=not&crhPriority=1&fields_0=all&fields_1=all&imagesonly=1&limit=2000&orientation=both&page=1&q=foo... | 1,439 | 532 |
from twitchchatbot.lib.commands.parsing import commands
import json
def addcom(user, args):
# Concatenate a list of strings down to a single, space delimited string.
queueEvent = {}
if len(args) < 2:
queueEvent['msg'] = "Proper usage: !addcom <cmd> <Text to send>"
else:
commandHead = ... | 785 | 244 |
from distutils.core import setup
import py2exe
# if py2exe complains "can't find P", try one of the following workarounds:
#
# a. py2exe doesn't support zipped eggs - http://www.py2exe.org/index.cgi/ExeWithEggs
# You should give the --always-unzip option to easy_install, or you can use setup.py directly
# $ python s... | 858 | 281 |
import os
import shutil
import argparse
import torch
from torch import nn
from torchvision.utils import save_image, make_grid
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
import utils.utils as utils
from utils.constants import *
class GenerationMode(enum.Enum):
SINGLE_IMAGE = 0,
INT... | 16,807 | 5,462 |
from direct.gui.DirectGui import OnscreenText, DirectButton
from panda3d.core import *
from direct.interval.IntervalGlobal import *
from direct.showbase.DirectObject import DirectObject
from toontown.toonbase import ToontownGlobals
class DMenuDisclaimer(DirectObject):
notify = directNotify.newCategory('DisclaimerS... | 2,207 | 802 |
import torch
from .utils import log_dens, pyramid, upsample, softmin_grid
from .sinkhorn_divergence import epsilon_schedule, scaling_parameters
from .sinkhorn_divergence import sinkhorn_cost, sinkhorn_loop
def extrapolate(f_ba, g_ab, eps, damping, C_xy, b_log, C_xy_fine):
return upsample(f_ba)
def kernel_trunca... | 7,012 | 2,335 |
"""a module solely for finding how add_a_list and add_tuple_list compare.
it's effectively the empirical proof for how LongIntTable.add() chooses
the fastest method with it's get_fastest_method() function."""
from __future__ import print_function
from math import log10
import time
import random
from os import getcwd
... | 31,947 | 10,461 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2020, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2020. UChicago Argonne, LLC. This ... | 14,814 | 4,530 |
from os import path
from unittest import mock
from common_for_tests import make_test_raster
from tornado.testing import gen_test, AsyncHTTPTestCase
from tornado.concurrent import Future
import telluric as tl
from telluric.util.local_tile_server import TileServer, make_app, TileServerHandler
tiles = [(131072, 131072, ... | 2,891 | 1,055 |
class Error():
def __init__(self):
print("An error has occured !")
class TypeError(Error):
def __init__(self):
print("This is Type Error\nThere is a type mismatch.. ! Please fix it.") | 208 | 59 |
"""
This module contains methods that model the intrinsic properties of galaxy
populations.
"""
__all__ = [
'schechter_lf',
]
from . import luminosity # noqa F401,F403
from . import morphology # noqa F401,F403
from . import redshift # noqa F401,F403
from . import spectrum # noqa F401,F403
from . import stella... | 437 | 176 |
from tests.parser import *
from tests.formatter import *
from tests.utils import *
| 84 | 24 |
from appshell.base import View
from appshell.templates import confirmation, message
from flask import request, flash, redirect
from flask_babelex import Babel, Domain
mydomain = Domain('appshell')
_ = mydomain.gettext
lazy_gettext = mydomain.lazy_gettext
class ConfirmationEndpoint(View):
methods = ("GET", "POST"... | 853 | 240 |
from flask import g, request
from flask_restful import reqparse
from werkzeug import datastructures
from ..exceptions.system_error import SystemError
from ..exceptions.system_exception import SystemException
from ..exceptions.service_error import ServiceError
from ..exceptions.service_exception import ServiceException... | 2,679 | 778 |
import itertools
class ParentFinder(object):
'''
Finds which parent an item should go under
'''
def __init__(self):
self.__parents = {}
def hash(self, item):
if item.prefix:
return item.prefix
else:
return item.group_name
def add(self, parent... | 3,422 | 939 |
from algernon.memory import Memory
import pytest
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import sgd
class MockModel:
def __init__(self, output_dims, input_dims):
self.w = np.random.random(size=(output_dims, input_dims))
def pre... | 2,385 | 860 |
"""
m2critic.parse
~~~~~~~~~~~~~~~
Scrape page.
@author: z33k
"""
from pathlib import Path
from typing import List, Tuple
from bs4 import BeautifulSoup
from bs4.element import Tag
from m2critic import BasicUser
FORBIDDENSTR = "403 Forbidden"
class PageParser: # abstract
"""Abstract page p... | 4,235 | 1,237 |
from .loco_dialogue_object import LocoBotCapabilities
__all__ = [LocoBotCapabilities] | 86 | 31 |
from .._common import *
from yo_fluq import *
Queryable = lambda *args, **kwargs: FlupFactory.QueryableFactory(*args, **kwargs)
T = TypeVar('T')
TOut = TypeVar('TOut')
TKey = TypeVar('TKey')
TValue = TypeVar('TValue')
TFactory = TypeVar('TFactory') | 248 | 87 |
import bpy
import mathutils
from src.main.Module import Module
from src.utility.BlenderUtility import check_intersection, check_bb_intersection, get_all_mesh_objects
class ObjectPoseSampler(Module):
"""
Samples positions and rotations of selected object inside the sampling volume while performing mesh and
... | 7,423 | 1,968 |
from core import app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# user table
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String(50), unique=True)
name = db.Column(db.String(50))
... | 872 | 320 |
# First make the vocabulary, etc.
import os
import pickle as pkl
import random
import simplejson as json
from allennlp.common.util import get_spacy_model
from allennlp.data import Instance
from allennlp.data import Token
from allennlp.data import Vocabulary
from allennlp.data.dataset import Batch
from allennlp.data.f... | 6,285 | 2,054 |
import numpy as np
def CalcEnergy(m_amu,Px_au,Py_au,Pz_au):
amu2au = 1836.15
return 27.2*(Px_au**2 + Py_au**2 + Pz_au**2)/(2*amu2au*m_amu)
| 148 | 91 |
from time import clock
import logging
#~ class Timer(object):
#~
#~ def start(self,s):
#~ self.s = s
#~ self.started = clock()
#~
#~ def stop(self):
#~ self.stopped = clock()
#~ t = self.stopped - self.started
#~ self.log(t)
#~
#~ def log(self, t):
#~ line = self.s + ',... | 357 | 149 |
from .imagenet_dataset import ImageNetDataset, RankedImageNetDataset # noqa
from .custom_dataset import CustomDataset # noqa
from .imagnetc import ImageNet_C_Dataset
| 173 | 58 |
import setuptools
from distutils.core import setup
setup(
name = 'electricityLoadForecasting',
version = '0.1.dev0',
packages = setuptools.find_packages(),
scripts = ['scripts/main_forecasting.py',
'scripts/preprocessing_eCO2mix.p... | 1,457 | 360 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v3/proto/services/shopping_performance_view_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from go... | 5,966 | 2,270 |
# vim: set encoding=utf-8
#
# Copyright (c) 2015 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.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | 18,930 | 6,081 |
#!/usr/bin/env python
import unittest
import rospy
import rostest
from sound_play.libsoundplay import SoundClient
class TestCase(unittest.TestCase):
def test_soundclient_constructor(self):
s = SoundClient()
self.assertIsNotNone(s)
if __name__ == '__main__':
rostest.rosrun('sound_play', 'test... | 377 | 128 |
#!python
"""This module is for messing with input characters."""
import os
import sys
unicurses_path = os.path.dirname(os.path.abspath(__file__)) + '/../libs/unicurses'
sys.path.insert(0, unicurses_path)
import unicurses as curses
def key_info(key):
try:
_ord = ord(key)
except:
_ord = -1
t... | 2,308 | 775 |
class Node(object):
def __init__(self, value, next=None, prev=None):
self.value = value
self.next = next
self.prev = prev
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push(self, value):
new_node... | 1,598 | 468 |
import unittest
import sys
sys.path.append("../../src/")
from supervisors.bitWiseSupervisor import BitWiseSupervisor
from senders.scapySender import ScapySender
from simulations.randomSimulation import RandomSimulation
class testArgParser(unittest.TestCase):
def testApplyBER(self):
sender = ScapySender... | 879 | 287 |
from selenium import webdriver
def _options_factory():
"""Produces a selenium.webdriver.ChromeOptions object. Used to force "headless" on invocation. You shouldn't call this function."""
ret = webdriver.ChromeOptions()
ret.add_argument("headless")
return ret
def get_driver(*varargs,args=[]):
"""Creates headless ... | 949 | 283 |
# -*- coding: utf-8 -*-
"""
LemonSoap - headers scent.
Deals with column headers.
"""
import pandas as pd
import inflection
import re
import logging
from ..lemon_bar import LemonBar
from .scent_template import ScentTemplate
class ColumnsScent(ScentTemplate):
"""
Manages headers issue identification and fixi... | 2,677 | 747 |
import pandas as pd
from os.path import join as pjoin
import numpy as np
import matplotlib.pyplot as plt
DATA_DIR = "../../../data/codex"
data = pd.read_csv(pjoin(DATA_DIR, "codex_mrl_expression.csv")) # , nrows=200)
marker_names = data.columns.values[1:-8]
sample_names = data.sample_Xtile_Ytile.str.split("_").str[0... | 2,347 | 1,035 |
import pie
@pie.eventhandler('pie.PlayerChat')
async def onLoad():
pass | 78 | 28 |
import collections
import csv
from io import StringIO
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from rest_framework import permissions
from rest_framework import statu... | 4,853 | 1,365 |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
import math
from utils.model_utils import *
from utils.ri_utils import *
from models.vrcnet import Linear_ResBlock
class PCN_encoder(nn.Module):
def __init__(se... | 10,031 | 3,875 |
from scripts.helpful_scripts import (
LOCAL_BLOCKCHAIN_ENVIRONMENTS,
get_account,
fund_with_link,
get_contract,
)
from brownie import Game, accounts, config, network, exceptions
from scripts.deploy_game import deploy_game
from web3 import Web3
import pytest
# if network.show_active() not in LOCAL_BLOC... | 4,267 | 1,525 |
#
# Escrevendo arquivos com funções do Python
#
def escreveArquivo():
arquivo = open('NovoArquivo.txt', 'w+')
arquivo.write('Linha gerada com a função Escrevendo Arquivo \r\n')
arquivo.close()
#escreveArquivo()]
def alteraArquivo():
arquivo = open('NovoArquivo.txt', 'a+') # a de append que dizer e... | 466 | 185 |
def params_create_rels_unwind_from_objects(relationships, property_identifier=None):
"""
Format Relationship properties into a one level dictionary matching the query generated in
`query_create_rels_from_list`. This is necessary because you cannot access nested dictionairies
in the UNWIND query.
UN... | 1,150 | 375 |
# Generated by Django 3.2.3 on 2021-10-19 18:54
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userprofile',
... | 477 | 157 |
#python -m marbles test_semantic_columns.py
import unittest
from marbles.mixins import mixins
import pandas as pd
import requests
from pyspark.sql import SparkSession
import psycopg2 as pg
import pandas as pd
import marbles
from pyspark.sql.types import StructType, StructField, StringType
import psycopg2 as pg
#from s... | 6,239 | 1,628 |
import math
class polygon:
def __init__(self, arr):
self.original_arr = arr
self.size = len(self.original_arr)
self.__set_min_max_by_original__()
self.__refactor_original_seq__()
self.sorted_arr.append(self.sorted_arr[0])
self.size += 1
def __set_min_max_by_ori... | 6,572 | 2,418 |
# coding: utf-8
# In[20]:
import numpy as np
import pydensecrf.densecrf as dcrf
import os
import cv2
import random
from tqdm import tqdm
# In[21]:
from skimage.color import gray2rgb
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score, accuracy_score
from pyden... | 20,352 | 7,876 |
import random
from django.core.management.base import BaseCommand
from django.contrib.admin.utils import flatten
from django_seed import Seed
from lists import models as list_models
from users import models as user_models
from rooms import models as room_models
NAME = "lists"
class Command(BaseCommand):
help =... | 783 | 241 |
# $Id$
#
# Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" unit testing code f... | 4,181 | 1,713 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('classroom', '0002_assignment_description'),
]
operations = [
migrations.AddField(
model_name='assignment',
... | 1,678 | 485 |
import numpy as np
import matplotlib.pyplot as plt
import os
from pyburst.grids import grid_analyser, grid_strings, grid_tools
# resolution tests
y_factors = {'dt': 3600,
'fluence': 1e39,
'peak': 1e38,
}
y_labels = {'dt': '$\Delta t$',
'rate': 'Burst rate',
... | 6,484 | 2,234 |
# -*- encoding: utf-8 -*-
import urllib
import hashlib
import logging
import choices
import caching.base
from scielomanager import tools
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from django.db import (
models,
transaction,
IntegrityError,
... | 47,267 | 13,770 |
from datetime import timedelta
from django import forms
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.http import HttpRequest
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .models imp... | 7,323 | 2,072 |
# Copyright (c) 2020-present, Assistive Robotics Lab
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from transformers.training_utils import fit
from transformers.transformers import (
InferenceTransformerEncoder,
... | 6,971 | 1,948 |
from typing import Collection
from typing import Sequence
from glassio.initializable_components import InitializableComponent
from glassio.logger import InitializableLogger
from amocrm_asterisk_ng.scenario import IScenario
__all__ = [
"Integration",
]
class Integration:
__slots__ = (
"__scenario"... | 3,226 | 764 |
from typing import Tuple
import torch
import torch.nn as nn
from pyro.distributions.util import broadcast_shape
from pyro_util.modules.weight_scaling import GammaReLU, WSLinear
T = torch.Tensor
def make_ws_fc(*dims: int) -> nn.Module:
"""Helper function for creating a fully connected neural network.
This v... | 1,685 | 584 |
#!/usr/bin/env python
'''
catalog_harvesting/util.py
General utilities for the project
'''
import random
def unique_id():
'''
Return a random 17-character string that works well for mongo IDs
'''
charmap = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return ''.join([random.cho... | 356 | 137 |
from WeatherScreens.RingScreen import RingScreen
from WeatherScreens.QuadrantScreen import QuadrantScreen
from WeatherScreens.ImageScreen import ImageScreen
from WeatherScreens.ScreenBase import ScreenBase
from datetime import datetime, timedelta
from suntime import Sun, SunTimeException
from dateutil import tz
import ... | 10,442 | 5,153 |
from django.conf.urls import url, include
from django.conf import settings
from . import views
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'manage/', views.index),
]
| 254 | 75 |
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from algos.dpg import eval_policy, collect_experience
from algos.dpg import ReplayBuffer
class TD3():
def __init__(self, actor, q1, q2, a_lr, c_lr, discount=0.99, tau=0.001, center_reward=False, policy_n... | 9,563 | 3,466 |
# This code is generated automatically by ClointFusion BOT Builder Tool.
import ClointFusion as cf
import time
cf.window_show_desktop()
cf.mouse_click(int(cf.pg.size()[0]/2),int(cf.pg.size()[1]/2))
try:
cf.mouse_click(*cf.mouse_search_snip_return_coordinates_x_y(r'C:\Users\mrmay\AppData\Local\Temp\cf_log_5fa2... | 2,021 | 887 |
#!/usr/bin/env nemesis
"""
This script creates a spatial database for the initial stress and state
variables for a Maxwell plane strain material.
"""
sim = "gravity_vardensity"
materials = ["crust","mantle"]
import numpy
import h5py
from spatialdata.spatialdb.SimpleIOAscii import SimpleIOAscii
from spatialdata.geoco... | 4,524 | 1,624 |
from random import randint
import numpy as np
import random
class BehaviorPolicy:
def __init__(self):
self.lastAction = 0
self.i = 0
self.ACTIONS = {
'forward': "move 1",
'back': "move -1",
'turn_left': "turn 1",
'extend_hand':"attack 1"
}
def policy(self, state):
se... | 923 | 320 |
# Check if the value is in the list?
words = ['apple', 'banana', 'peach', '42']
if 'apple' in words:
print('found apple')
if 'a' in words:
print('found a')
else:
print('NOT found a')
if 42 in words:
print('found 42')
else:
print('NOT found 42')
# found apple
# NOT found a
# NOT found 42 | 311 | 120 |
import datetime
import typing
from . import enums, tools
class CatalogueAPIWrapper:
"""Methods for listing objects"""
def __init__(
self, username: str, password: str, language: enums.Language = enums.Language.GERMAN
):
"""Create a new Wrapper containing functions for listing different o... | 46,445 | 11,896 |
# coding: utf-8
"""加密算法:公钥(私钥)加密,私钥解密"""
from Crypto.PublicKey import RSA
from Crypto import Random
DATA = 'Hello, word!'
PRIVATE_KEY_PEM = """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDB3c0nwVs6koPkpt6REeT07jK7m9qE9BmDw1Zl55T66rGfKM3g
1DFBq7jtcZ+xcgYAGgvJWPW16nylag/1lVNUxMShm2jlp3MwuBNKRvrXP2u29j9v
AAlM9lMLXzt0... | 2,440 | 1,379 |
from django.contrib.auth import get_user_model
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from users.serializers import UserSerializer
class UserViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
queryset = get_user_model().objects.all()
seria... | 375 | 111 |
print("Hello, World!")
print("This uses the MIT Licence!")
| 59 | 21 |
import numpy as np
import torch
import torch.nn as nn
import torchtestcase
import unittest
from survae.transforms.bijections.conditional.coupling import *
from survae.nn.layers import ElementwiseParams, ElementwiseParams2d, scale_fn
from survae.tests.transforms.bijections.conditional import ConditionalBijectionTest
c... | 5,597 | 1,788 |
# Generated by Django 3.0.3 on 2020-02-28 15:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='product',
name='photo',
fiel... | 408 | 135 |
# Generated by Django 2.2.3 on 2019-07-21 01:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Device',
fields=[
... | 4,812 | 1,408 |
__author__ = 'renderle'
class OpenWeatherParser:
def __init__(self, data):
self.data = data
def getValueFor(self, idx):
return self.data['list'][idx]
def getTemperature(self):
earlymorningValue = self.getValueFor(0)['main']['temp_max']
morningValue = self.getValueFor(1)['... | 813 | 255 |
# Convert examples in this folder to their corresponding .md files in docs/examples
import re
import inspect
import textwrap
import datetime
import yaml
from pathlib import Path
def hide(line):
return ":hide:" in line
def build_examples():
current = Path(__file__)
folder = current.parent
for fname... | 8,300 | 2,719 |
import numpy as np
from scipy.stats import norm
from .mixed_optimiser import MVO
from scipy.optimize import shgo, differential_evolution, dual_annealing
import scipy as stats
class MVMOO(MVO):
"""
Multi variate mixed variable optimisation
"""
def __init__(self, input_dim=1, num_qual=0, num_obj=2, bound... | 21,017 | 7,014 |
import numpy
import chainer
from chainer.backends import cuda
from chainer.functions.activation import sigmoid
from chainer.functions.activation import tanh
from chainer.functions.array import concat
from chainer.functions.math import linear_interpolate
from chainer import link
from chainer.links.connection import lin... | 2,306 | 789 |
"""
Project: flask-rest
Author: Saj Arora
Description: Initializes the rest app
"""
from collections import OrderedDict
import flask
from api.v1 import Api
class _SageRest(flask.Flask):
_api = None
__modules = []
_modules = {}
_ordered_modules = OrderedDict()
_auth_module = None
def __init_... | 2,920 | 713 |
from __future__ import absolute_import
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchreid.metrics import compute_distance_matrix
import scipy.linalg
def adjoint(A, E, f):
A_H = A.T.conj().to(E.dtype)
n = A.size(0)
M = torch.zeros(2*n, 2*n, dty... | 1,575 | 629 |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Member, Band
from rockband.serializers import MemberSerializer
MEMBERS_URL = reverse('rockband:member-l... | 4,460 | 1,349 |
from slave.playground.bots import BotInformation
from slave.lib.bots import BotBasic, BotV2
config = {
'host': 'chat.freenode.net',
'port': 6667,
'channel': "#slavebotpool666",
'boss_name': 'boss666',
'bot_prefix': "SLAVEBOT"
}
BotInformation.read_config_from_dict(config)
BotInformation.use_other... | 372 | 148 |
X = []
Y = []
cont = 0
n = True
while n:
a,b = input().split(" ")
a = int(a)
b = int(b)
if a == b:
n = False
cont-=1
else:
X.append(a)
Y.append(b)
cont+=1
i = 0
while i < cont:
if X[i] > Y[i]:
print('Decrescente')
elif X[i] < ... | 363 | 168 |
##############################################################################
# Copyright (c) 2017 Luke Hinds <lhinds@redhat.com>, Red Hat
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... | 1,482 | 435 |