text string | size int64 | token_count int64 |
|---|---|---|
"""
{
"swagger": "2.0",
"info": {
"title": "Python Cookbook\\nChapter 12, recipe 3.",
"version": "1.0"
},
"schemes": "http",
"host": "127.0.0.1:5000",
"basePath": "/dealer",
"consumes": "application/json",
"produces": "application/json",
"paths": {
"/hands": {
... | 5,097 | 1,542 |
frase = str(input('Digite a frase: ')).strip().upper()
palavras = frase.split()
juntarPalavras = ''.join(palavras)
trocar = juntarPalavras[::-1]
print(trocar) | 158 | 68 |
import pytinydiffsim_ad as dp
import autogen as ag
import numpy as np
import math
TIME_STEPS = 20
def func(input_tau):
world = dp.TinyWorld()
world.friction = dp.ADScalar(1.0)
urdf_parser = dp.TinyUrdfParser()
urdf_data = urdf_parser.load_urdf("/root/tiny-differentiable-simulator/data/cartpole.urdf")
print... | 1,345 | 600 |
import tensorflow as tf
import tensorflow_probability as tfp
XAVIER_INIT = tf.contrib.layers.xavier_initializer()
class GRU_cell(tf.keras.Model):
def __init__(self, hidden_unit, output_nodes):
super(GRU_cell, self).__init__()
self.i_to_r = tf.keras.layers.Dense(hidden_unit, activation="sigmoid", ... | 5,923 | 1,993 |
default_app_config = 'docsie_universal_importer.providers.google_drive.apps.GoogleDriveAppConfig'
| 98 | 33 |
import docker, json
VALID_PROFILE = ['volume', 'mariadb']
def backup_list():
client = docker.DockerClient(base_url='unix://var/run/docker.sock')
bck = {}
for ct in client.containers.list(all=True):
is_backup = False
error = []
if 'one.h42.backup.enable' in ct.labels:
if... | 3,312 | 1,036 |
import copy
import os
import random
import numpy as np
sep = os.sep
####################### GLOBAL PARAMETERS ##################################################
############################################################################################
Params = {
'num_channels': 1,
'num_classes': 2,
'ba... | 7,309 | 3,192 |
#!/usr/bin/python3
import MySQLdb
from sys import argv, exit
from random import choice
arr_prefix = [
"sit",
"eiusmod",
"nulla",
"tempor",
"exercitation",
"Lorem",
"consectetur",
"qui",
"aute",
"laborum",
"culpa",
"sunt",
"sunt",
"enim",
"cupidatat",
"ipsum",
"nulla",
"consectetur"... | 3,673 | 1,633 |
import unittest
from mongorm import Database
class DatabaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db = Database(uri='mongodb://localhost:27017/orm_test')
cls.db2 = Database(host='localhost', port=27017, db='orm_test2')
@classmethod
def tearDownClass(cls):... | 1,964 | 660 |
import unittest
import random
from binary_heap import BinaryHeap
class TestBinaryHeap(unittest.TestCase):
def setUp(self):
size = 8
self.random_list = random.sample(range(0, size), size)
print "random list generated: " + str(self.random_list)
self.heap = BinaryHeap(size)
... | 760 | 239 |
"""
Provides elements that make stuff happen.
.. moduleauthor: Johannes Brachem <jbrachem@posteo.de>
"""
from typing import Union
from typing import List
from uuid import uuid4
import cmarkgfm
from cmarkgfm.cmark import Options as cmarkgfmOptions
from emoji import emojize
from ..exceptions import AlfredError
from .... | 22,418 | 6,271 |
def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi)
return tf.reduce_sum(
-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),
axis=raxis)
def compute_loss(model, x):
mean, logvar = model.encode(x)
z = model.reparameterize(mean, logvar)
x_logit = mod... | 598 | 269 |
import gym
from keras.optimizers import Adam
import traceback
import os
from .dqn import DQN
from .agent57 import Agent57
from .model import InputType, DQNImageModel, LstmType
from .policy import AnnealingEpsilonGreedy
from .memory import PERRankBaseMemory, PERProportionalMemory
from .env_play import EpisodeSave, Epi... | 6,147 | 2,149 |
##############################################################
# Program Code for Fred Inmoov #
# Of the Cyber_One YouTube Channel #
# https://www.youtube.com/cyber_one #
# #
# Thi... | 1,473 | 422 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Based on storm.py module from https://github.com/nathanmarz/storm/blob/master/storm-core/src/multilang/py/storm.py, and the examples from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/multilang/resources/splitsentence.py and http://storm.... | 7,019 | 2,102 |
from django.conf.urls import include, url
from django.contrib import admin
from httpproxy.views import HttpProxy
from django.views.generic.base import RedirectView
from django.http import HttpResponse
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^transcripts/', include('nuremberg.transcripts.urls'))... | 1,329 | 521 |
#!/usr/bin/env python
# encoding: utf-8
# author: Vincent
# refer: https://github.com/vc5
import re
import time
from requests import Response
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.touch_actions import TouchActions
from ..chrome import mobile_emulation
from lib.se... | 5,125 | 1,747 |
#!/usr/bin/env python
from __future__ import division
__author__ = "Jose Antonio Navas Molina"
__copyright__ = "Copyright 2013, The Emperor Project"
__credits__ = ["Jose Antonio Navas Molina"]
__license__ = "BSD"
__version__ = "0.9.3-dev"
__maintainer__ = "Jose Antonio Navas Molina"
__email__ = "josenavasmolina@gmail... | 3,046 | 1,317 |
# -*- coding: utf-8 -*-
import os
import vulners
print("---------------------------------------------------------------")
print(""" P4RS Script Hoş Geldiniz
Programı kullanmak için sadece IP adresini yazmanız yeterlidir.
Programı çalıştırmak için; Medusa araçları, searcsploit ve brutespray uygulamaları gerekmekted... | 998 | 393 |
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
"""empty message
Revision ID: a031e26dc1bd
Revises: 8efa45d83a3b
Create Date: 2018-08-06 16:03:36.820890
"""
# revision identifiers, used by Alembic.
revision = 'a031e26dc1bd'
down_revision = '8efa45d83a3b'
def upgrade():
# ### commands au... | 1,276 | 412 |
from pathlib import Path
from tkinter import Frame, Canvas, Entry, Text, Button, PhotoImage, messagebox
import controller as db_controller
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def add_reserva... | 7,048 | 2,465 |
import cv2
import numpy as np
import imutils
from collections import defaultdict
# mouse callback function
def define_points(target_img):
corners = []
refPt = []
def draw_circle(event,x,y,flags,param):
global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(param,(x,y),5,(... | 8,977 | 3,473 |
import argparse
import configparser
import os
import pathlib
import platform
import random
import subprocess as sp
import sys
import typing
import warnings
if platform.system() == 'Windows':
import winsound
try:
from IPython.core import magic
IPYTHON_INSTALLED = True
except ImportError:
IPYTHON_INSTAL... | 8,729 | 2,546 |
import unittest
import os
from dockstream.core.OpenEyeHybrid.Omega_ligand_preparator import OmegaLigandPreparator
from dockstream.core.ligand.ligand_input_parser import LigandInputParser
from dockstream.utils.enums.docking_enum import DockingConfigurationEnum
from dockstream.utils.enums.Omega_enums import OmegaExecu... | 7,733 | 2,830 |
"""Test searching the list of blog posts."""
from typing import List
from rest_framework.test import APITestCase
from blog.factories import PostFactory
from tests.decorators import authenticated
@authenticated
class PostSearchListTest(APITestCase):
"""Test searching on the post list endpoint."""
def setUp... | 1,989 | 613 |
# coding=utf-8
from enum import IntEnum
class NotificationType(IntEnum):
power_down = 1
power_up = 2
resteem = 3
feed = 4
reward = 5
send = 6
mention = 7
follow = 8
vote = 9
comment_reply = 10
post_reply = 11
account_update = 12
message = 13
receive = 14
class ... | 10,641 | 3,105 |
from pymongo.read_concern import ReadConcern
from pymongo.read_preferences import ReadPreference
from pymongo.write_concern import WriteConcern
from pymongo.errors import InvalidOperation
from iu_mongo.errors import TransactionError
__all__ = ['Session', 'TransactionContext']
DEFAULT_READ_CONCERN = ReadConcern('major... | 2,491 | 756 |
import re
import decimal
import optparse
import pandas as pd
from ingredient_phrase_tagger.training import utils
class Cli(object):
def __init__(self, argv):
self.opts = self._parse_args(argv)
self._upstream_cursor = None
def run(self):
self.generate_data(self.opts.count, self.opts.o... | 5,009 | 1,446 |
import sys
number_of_snowballs = int(input())
highest_value = -sys.maxsize
highest_quality = -sys.maxsize
highest_weight = -sys.maxsize
highest_time = -sys.maxsize
for i in range (number_of_snowballs):
weight_of_snowball = int(input())
time_of_reaching = int(input())
quality_of_snowball = int(input())
... | 726 | 263 |
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, Markup, abort, make_response
# import peewee
# import json
api = Flask(__name__)
@api.route('/')
def index():
html = '''
<form action="/iperf3test">
<p><label>iperf3 test: </label></p>
Test Name: <input type="text" name="TestNa... | 1,871 | 633 |
import functools
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
def make_model(level):
return ESAN(level = level)
def initialize_weights(net_l, scale=1):
if not isinstance(net_l, list):
net_l = [net_l]
for net in net_l:
for m in net.modules():
... | 4,212 | 1,616 |
import math
import numpy as np
from scipy.spatial.distance import cdist
from torch.utils.data import Dataset
import torch
import os
import pickle
from problems.tsptw.state_tsptw import StateTSPTWInt
from utils.functions import accurate_cdist
class TSPTW(object):
NAME = 'tsptw' # TSP with Time Windows
@stati... | 3,478 | 1,141 |
"""Defines various classes and definitions that provide assistance for
unit testing Actors in an ActorSystem."""
import unittest
import pytest
import logging
import time
from thespian.actors import ActorSystem
def simpleActorTestLogging():
"""This function returns a logging dictionary that can be passed as
... | 11,089 | 3,207 |
from process import wordlist
import itertools
import time
import os
import re
ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz'
def main():
blacklist_all = wordlist.dict_by_length()
blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5])
combinations = get_combinations(3)
tick = time.t... | 2,454 | 814 |
import numpy as np
import random
import gym
import time
import itertools
from numpy.random.mtrand import gamma
import torch
from torch import nn
from torch._C import dtype
from torch.optim import Adam
from torch.distributions import Categorical
class ExperienceBuffer:
def __init__(self, buffer_size, gamma, lambd)... | 10,400 | 3,602 |
from subprocess import Popen, PIPE
from distutils.util import strtobool
import serial
import sys
import time
import glob
import serial.tools.list_ports_posix
def run_applescript(scpt, args=()):
p = Popen(['osascript', '-'] + list(args), stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate(scpt)
return ... | 4,052 | 1,175 |
import json
import yaml
import dnode
from eave import *
openapi_yaml = open('openapi.yaml').read()
openapi_json = open('openapi.json').read()
yaml_data = yaml.safe_load(openapi_yaml)
json_data = json.loads(openapi_json)
assert yaml_data == json_data
class DNode(dnode.DNode):
def __getattr__(self, item):
... | 4,275 | 1,074 |
import logging as log
import numpy as np
import h5py
import humblerl as hrl
from humblerl import Callback, Interpreter
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
from torch.utils.data import Dataset
from common_utils import get_model_path_if_exists
from third... | 12,939 | 4,067 |
from bs4 import BeautifulSoup
from wagtail.core.fields import StreamField
def extract_text(obj):
"""Extracts data, concatenates and removes html tags
from fields listed in a obj.related_source_fields list.
"""
related_source_fields = getattr(obj._meta.model, 'related_source_fields', None)
if not r... | 761 | 232 |
# coding: utf-8
__author__ = "Lário dos Santos Diniz"
from django.test import TestCase
from model_mommy import mommy
from core.models import Programs
class ProgramsModelTestCase(TestCase):
"""Class Testing Model Pogramas """
def setUp(self):
"""
Initial Test Settings
"""
... | 1,233 | 371 |
import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import rcParams
params = {
# 'text.latex.preamble': ['\\usepackage{gensymb}'],
# 'text.usetex': True,
'font.family': 'Helvetica',
'lines.solid_capstyle'... | 8,002 | 3,465 |
import numpy as np
# Install the library using: pip install -U efficient-apriori
from efficient_apriori import apriori
# Set random seed for reproducibility
np.random.seed(1000)
nb_users = 100
nb_products = 100
if __name__ == "__main__":
# Create the dataset
items = [i for i in range(nb_products)]
t... | 1,164 | 362 |
import numpy as np
def split_ids(args, ids, folds=10):
if args.dataset == 'COLORS-3':
assert folds == 1, 'this dataset has train, val and test splits'
train_ids = [np.arange(500)]
val_ids = [np.arange(500, 3000)]
test_ids = [np.arange(3000, 10500)]
elif args.dataset == 'TRIANGL... | 1,202 | 448 |
import dingus.codec
import utils
import transaction
class BlockHeader(object):
VERSION = 0
def __init__(
self,
) -> None:
raise NotImplementedError
class Block(object):
VERSION = 0
def __init__(
self,
header: BlockHeader,
payload: list[transaction.Trans... | 498 | 149 |
# -*- coding: utf-8 -*-
"""Block reshape functions.
"""
import numpy as np
import numba as nb
from sigpy import backend, config, util
__all__ = ['array_to_blocks', 'blocks_to_array']
def array_to_blocks(input, blk_shape, blk_strides):
"""Extract blocks from an array in a sliding window manner.
Args:
... | 34,609 | 11,460 |
#!/usr/bin/env python3
import os
from aws_cdk import core
from awscdk.app_stack import ApplicationStack
# naming conventions, also used for ACM certs, DNS Records, resource naming
# Dynamically generated resource names created in CDK are used in GitLab CI
# such as cluster name, task definitions, etc.
environment_na... | 1,531 | 499 |
import numpy as np
import logging
from interfacial_transport import compute_one_phase_equilibrium, compute_mass_balance_one_phase
from interfacial_transport import compute_two_phase_equilibrium, compute_mass_balance_two_phase
from numpy.testing import assert_almost_equal
logger = logging.getLogger(__name__)
# Check o... | 4,563 | 2,123 |
#!/usr/bin/python
"""
Build a simple network from scratch, using mininet primitives.
This is more complicated than using the higher-level classes,
but it exposes the configuration details and allows customization.
For most tasks, the higher-level API will be preferable.
"""
import csv
import sys
import time
from mini... | 3,914 | 1,386 |
from teampy.client import APIClient
__version__ = '0.1'
__author__ = 'Edward Wells'
__all__ = ['APIClient'] | 108 | 41 |
# -*- coding: utf-8 -*-
"""
app.housekeeping
~~~~~~~~~~~~~~~~
Provides additional housekeeping endpoints
"""
from flask import Blueprint, redirect, request
from werkzeug.exceptions import HTTPException
from app.helpers import exception_hook
from app.utils import jsonify
blueprint = Blueprint("Housekeepin... | 1,032 | 331 |
from aiplayer import *
from player import *
from gameclasses import *
def setup(countries, countryMap):
print("Setup started!")
#Initialise boni
NA.countries = countries[0:9]
SA.countries = countries[9:13]
AF.countries = countries[13:19]
EU.countries = countries[19:26]
AU.countries = countr... | 10,463 | 3,238 |
import json
import logging
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from pretix.base.models import Event, Order
from pretix.plugins.stripe.payment import Stripe
logger = logging.getLogger('pretix.plug... | 1,678 | 524 |
import logging
def get_logger():
"""Get the logger."""
return logging.getLogger("BLUSE.interface")
log = get_logger()
def set_logger(log_level=logging.DEBUG):
"""Set up logging."""
FORMAT = "[ %(levelname)s - %(asctime)s - %(filename)s:%(lineno)s] %(message)s"
logging.basicConfig(format=FORMAT... | 389 | 142 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OpenApiAppleRequestHeader import OpenApiAppleRequestHeader
class AlipayUserApplepayMerchantauthtokenGetModel(object):
def __init__(self):
self._amount = None
... | 4,749 | 1,305 |
import re
from sloth.grammar import LexicalGrammar
from sloth.token import Token
class LexerError(Exception):
def __init__(self, pos):
self.pos = pos
self.description = 'LexerError at Line {}, Column {}'.format(
self.pos[0], self.pos[1]
)
def __str__(self):
return... | 2,239 | 638 |
from com.huawei.iotplatform.client.dto.DeviceCommandCancelTaskRespV4 import DeviceCommandCancelTaskRespV4
from com.huawei.iotplatform.client.dto.Pagination import Pagination
class QueryDeviceCmdCancelTaskOutDTO(object):
pagination = Pagination()
data = DeviceCommandCancelTaskRespV4()
def __init__(self):
... | 577 | 180 |
# **************************************************************************
# Copyright 2018-2019 eBay Inc.
# Author/Developers: --
# 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:... | 4,872 | 1,398 |
import os
import subprocess
class TestTasks:
""" Test that the tasks work with invoke. """
CMD_KWARGS = dict(
capture_output=True,
encoding="utf-8",
shell=True,
env=os.environ.copy(),
)
def test_unapproved_licenses(self):
""" Should emit table of unapproved lic... | 1,040 | 297 |
import os
from ray import tune
package_dir = os.path.dirname(os.path.abspath(__file__))
identity_dir = os.path.join(package_dir, "..", "data/train_identity.csv")
transaction_dir = os.path.join(package_dir, "..", "data/train_transaction.csv")
data_primary_key = "TransactionID"
label_name = ["isFraud"]
feature_names = [... | 959 | 401 |
from . import guest
from . import pusherauth
from . import admin | 64 | 17 |
import numpy as np
import torch
from offlineExpert.a_star import PathPlanner
class AgentState:
def __init__(self, config):
# self.config = config
# self.num_agents = self.config.num_agents
self.config = config
self.num_agents = self.config.num_agents
# self.FOV = 5
... | 22,481 | 7,876 |
# Space: O(n)
# Time: O(n)
import collections
class Solution():
def findWords(self, board, words):
column = len(board)
if column == 0: return []
row = len(board[0])
if row == 0: return []
target_word = set()
res = set()
# build a trie, this will be used... | 1,713 | 558 |
from typing import Dict, Any, Optional
import pandas as pd
from pytorch_lightning.loggers import LightningLoggerBase
from pytorch_lightning.loggers.base import rank_zero_experiment
from pytorch_lightning.utilities import rank_zero_only
class SimpleLogger(LightningLoggerBase):
def __init__(self):
super().... | 2,101 | 600 |
# Copyright 2021 Spotify AB
#
# 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, so... | 13,225 | 4,284 |
import pytest
def test_test():
hello_world = "Hello World"
assert hello_world == "Hello World"
def test_always_passes():
assert True
#This test will always fail
def test_always_fails():
assert False
| 218 | 68 |
# coding: utf-8
# - We are creating a very simple machine learning model.<br>
# - Using dataset: tic-tac-toe.data.txt with user-defined columns.<br>
# - We are treating this problem as a supervised learning problem.<br>
# In[74]:
# This the rough sketch of the processing that happened in my brain while creating the... | 3,812 | 1,481 |
import torch.nn as nn
import torch
class ControlModule(nn.Module):
def __init__(self, input_size, hidden_size):
super(ControlModule, self).__init__()
self.rnncell = nn.RNNCell(input_size=input_size, hidden_size=hidden_size, nonlinearity='tanh')
def forward(self, input, hidden):
hidd... | 566 | 186 |
# -*- coding: utf-8 -*-
"""
Helpers
=======
The helpers are simple functions to support with:
- Catmull-Rom splines
- Extracting text and named entities from Ink Model
- Iterate over the Ink Tree
"""
__all__ = ['spline', 'text_extractor', 'treeiterator', 'policy']
from uim.model.helpers import ... | 452 | 151 |
import aiohttp
from matrix_traversal.utils import (
traverse_matrix_counterclockwise,
get_formatted_matrix,
check_url)
from typing import List
from aiohttp import ClientError
from asyncio.exceptions import TimeoutError
async def send_request(url: str) -> List[List[int]]:
"""
This function sends a ... | 1,544 | 414 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-02-18 10:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0430_briefofevidencedocument'),
('wildlifecompliance', '0427_merge_202... | 366 | 150 |
print
print 21
print 3
| 23 | 12 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import PyPDF2
length = len(sys.argv)
if length >= 2:
PASSWORD = sys.argv[1]
else:
print('usage: cmd password [path]')
sys.exit(1)
if length == 3:
PATH = sys.argv[2]
else:
PATH = os.curdir
for folder_name, _, filenames in os.walk... | 1,234 | 367 |
import turtle as t
zel = float(input("What is your Zel: "))
for i in range(4):
t.fd(zel)
t.lt(90)
t.done()
| 112 | 53 |
"""
Ashley URLs (that includes django machina urls)
"""
from django.urls import include, path, re_path
from machina import urls as machina_urls
from ashley.api import urls as api_urls
from ashley.views import ChangeUsernameView, ForumLTIView, ManageModeratorsView
API_PREFIX = "v1.0"
urlpatterns = [
path("lti/fo... | 691 | 233 |
#!/usr/bin/env python
#
# Script to generate a cap module and subroutines
# from a scheme xml file.
#
from __future__ import print_function
import os
import sys
import getopt
import xml.etree.ElementTree as ET
#################### Main program routine
def main():
args = parse_args()
data = parse_scheme(args['... | 11,992 | 3,544 |
#!/usr/bin/env python
import certifire
import certifire.plugins.acme
import certifire.plugins.dns_providers
from codecs import open
from setuptools import setup, find_packages
import sys
try:
# for pip >= 10
from pip._internal.req import parse_requirements
except ImportError:
# for pip <= 9.0.3
print(... | 2,457 | 726 |
"""
:mod: `kanka.utils` - Helper functions
"""
from datetime import datetime
from requests_toolbelt.sessions import BaseUrlSession
from dacite import from_dict, Config
from .exceptions import KankaAPIError
API_BASE_ENDPOINT = 'https://kanka.io/api/1.0/'
class KankaSession(BaseUrlSession):
""" Store session data.... | 2,687 | 810 |
######
###BACKGROUND
#Below Section: Imports necessary functions
import numpy as np
import matplotlib.pyplot as graph
import random as rand
import time as watch
import sims
pi = np.pi
######
###PLOTS
#FUNCTION: drawdarts
#PURPOSE: This function is meant to draw the darts for a given simulation within the unit square.... | 3,599 | 1,303 |
#!/usr/bin/env python
"""
Animate demonstration trajectory
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("h5file")
parser.add_argument("--seg")
parser.add_argument("--nopause", action="store_true")
args = parser.parse_args()
import h5py, openravepy,trajoptpy
from rapprentice import ani... | 1,803 | 798 |
import json
import os
from pymatgen.io.vasp import Poscar
def from_path(path):
# TODO: should maybe support .tar.gz or .tar.xz
return StructureDir.from_dir(path)
class StructureDir:
def __init__(self, *, layers, masses, layer_sc_matrices, structure):
self.layers = layers
self.masses = mass... | 1,032 | 332 |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import os
from functools import reduce
import sys
directory_with_mapping_reports = sys.argv[1]
mapping_summary = sys.argv[2]
############################################################
# Reads each file. Add sample name in the column with values
###########... | 891 | 295 |
my_name = "Jan"
my_age = 23
print(f"Age: { my_age }, Name: { my_name }")
| 74 | 38 |
from ast import literal_eval
from performance_metrics import get_performance_metrics
from tensorflow.keras.models import load_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # Ignore tf info messages
import pandas as pd
if __name__ == "__main__":
TASK = "humanitarian"
print("\nLoading in testing... | 1,140 | 385 |
"""
Utility functions relevant to Lindblad forms and projections
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the ... | 9,795 | 3,398 |
import torch
from torch.utils.data import Dataset
import numpy as np
import csv
import random
from config import *
import itertools
import torch
from skimage import io
import os
class QualityDataset(Dataset):
def __init__(self, return_hashes=False):
self.label_count = 3
file = open(QUALITY_DATA_FIL... | 1,490 | 491 |
"""Tests for the Geofency component."""
| 40 | 12 |
from sklearn.preprocessing import OneHotEncoder
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, BatchNormalization, Dropout
from keras.layers import Activation, Reshape
from keras.optimizers import Adam, Adadelta, SGD, RMSprop
from keras.regularizers import... | 5,564 | 1,988 |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import dace.library
from dace.transformation import transformation as xf
import pytest
@dace.library.node
class MyLibNode(dace.nodes.LibraryNode):
implementations = {}
default_implementation = 'pure'
def __init__(self... | 1,070 | 354 |
"""
Functions to manipulate data from PostgreSQL database includes a
parallelise dataframe that runs a function on a pandas data frame
in parallel, as well as a loop_chunks function. This reads a chunk
from the database performs an operation and uploads to a new
table in the database.
"""
import numpy as np
import pa... | 2,390 | 696 |
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
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, including without limitation
the rights to use, copy, modify, merge, publish, distri... | 4,633 | 1,293 |
__all__ = ("ComparsionMixin", "LazyLoadMixin")
class ComparsionMixin(object):
"""
Mixin to help compare two instances
"""
def __eq__(self, other):
"""
Compare two items
"""
if not issubclass(type(other), self.__class__):
return False
if (self.bod... | 2,006 | 554 |
from gherkin_to_markdown.expressions.expression import Expression
class SecondHeaderExpression(Expression):
def to_markdown(self, statement: str):
return f"##{statement.strip().replace(':', '', 1)[len(self.keyword):]}\n\n"
| 237 | 73 |
from __future__ import unicode_literals
from __future__ import absolute_import
import os
from pathlib import Path
class ResourceNotFound(OSError):
pass
DEFAULT_USER_RESOURCES_DIRECTORY = 'runtime_resources'
_default_package_dir = Path(__file__).resolve().parent / 'blobs'
_user_resources_dir = Path(os.getcwd(... | 1,965 | 571 |
from tflearn.data_preprocessing import DataPreprocessing
import numpy as np
import random
class ImagePreprocessing3d(DataPreprocessing):
""" Image Preprocessing.
Base class for applying real-time image related pre-processing.
This class is meant to be used as an argument of `input_data`. When training
... | 7,334 | 2,027 |
import pygame
import pygame.camera
#from pygame.locals import *
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640, 480), 0)
def main():
camlist = pygame.camera.list_cameras()
if camlist:
print('camera {} is detected'.format(camlist[0]))
cam = pygame.camera.Camera(camlis... | 640 | 215 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch.nn as nn
class SimpleRNN(nn.Module):
def __init__(self, num_features, name='LSTM', seq_length=100, hidden_size=128):
super(SimpleRNN, self).__init__()
self.num_features = num_features
self.seq_length = seq_length
self.h... | 1,210 | 461 |
from dataclasses import dataclass
from typing import List
@dataclass
class SystemInfo:
languageDefault: str
hideLoginPinputFields: bool
s3Hosts: List[str]
s3EnforceDirectUpload: bool
useS3Storage: bool
@dataclass
class ActiveDirectoryInfoItem:
id: int
alias: str
isGlobalAvailable: bool... | 573 | 178 |
import csv
import codecs
import StringIO
import cStringIO
import sys
import time
import argparse
from pyspark import SparkContext
parser = argparse.ArgumentParser(description='Count columns and lines existing in file')
parser.add_argument('-df','--DATAFILE', dest="DATAFILE", type=str,
help='the pat... | 3,315 | 1,004 |
# Yunfan Ye 10423172
def Fibonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
# arr = [1,2,3,4,5,6,7,8,9,10]
# for i in arr:
# print(Fibonacci(i))
| 254 | 137 |
'''
Created on July 12, 2016
@author: Huiming Ding
Email: huiming@mit.edu
Description:
This script is implemented for the Content_blobs database/table.
Input: No typical input to define.
Output: No typical output to define.
Example command line:
Log of changes:
'''
#!/usr/bin/env pytho... | 9,415 | 2,525 |