text string | size int64 | token_count int64 |
|---|---|---|
import bpy
def derive_image_path():
filename = bpy.path.basename(bpy.context.blend_data.filepath)
filename = "//output/" + filename.replace(".blend", ".png")
return filename
if __name__ == "__main__":
bpy.context.scene.render.engine = "CYCLES"
bpy.context.scene.render.resolution_x = 1920
bpy.... | 941 | 341 |
#app名称标记,不能设置为中文
APP_NAME="baiduphone"
#业务逻辑日志记录,True:开启,False:关闭
LOGIC_DEBUG=True
#业务逻辑日志输出的文件,空字符串表示输出到控制台,不记录到日志文件中
LOGIC_DEBUG_FILE=""
#短信通道的用户名和密码
SMS_URL='http://xxx.xxx.xxx:xxx/xxxx'
SMS_USERNAME='test'
SMS_PASSWD='test' | 230 | 162 |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance
# {"feature": "Education", "instances": 85, "metric_value": 0.9975, "depth": 1}
if obj[1]<=2:
# {"feature": "Distance", "instances": 70, "metric_value": 0.9787, "depth": 2}
if obj[3]<=2:
# {"feature": "Coupon", "ins... | 1,992 | 1,016 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 5,657 | 1,591 |
import topologies as top
import rules as rules
import starting_patterns as sp
from Game import Game
import os
import time
import numpy as np
def run_game(topology, rule, starting_pattern, start_pos, iterations):
starting_pattern_instance = starting_pattern(topology.n_rows, topology.n_cols, start_pos)
game = G... | 2,959 | 1,191 |
def data_type(data):
"""Returns a specific result based on the
data type of the argument supplied
"""
if type(data) == str:
return len(data)
elif data == None:
return 'no value'
elif data == True or data == False:
return data
elif type(data) == int:
if data < 100:
return 'less th... | 548 | 197 |
import emoji
print(emoji.emojize(' Ola mundo :sunglasses:', use_aliases=True))
| 95 | 44 |
# !/usr/bin/env python3
# for linux. exestiert -> program can be executed by terminal without "Python 3" in command
# does not exist for windows
'''
Main.py for Error TicketTool_v001
this tool aims to help Quality tester to create tickets and show some simple diagramm with often to use data
th... | 3,850 | 1,245 |
#!/usr/bin/env python3
"""This unit test proves that event values are immutable.
An event with a global-scope array is declared.
A simple state machine event handler modifies the value
of the event it is given.
The state machine is called with the global-scope array
and the framework is stopped.
The test passess if the... | 1,688 | 546 |
import requests
import json
from jinja2 import Template
import urllib.request
import re
class GrafanaHelper(object):
def __init__(self, grafana_server_address, grafana_token):
self.grafana_token = grafana_token
self.grafana_server_address = grafana_server_address
def get_dashboards(self, tag=... | 7,771 | 2,176 |
# Generated by Django 4.0.3 on 2022-03-23 11:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0005_alter_customer_doc_num'),
]
operations = [
migrations.AlterField(
model_name='cust... | 504 | 176 |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 21:28:32 2016
@author: thasegawa
"""
import cv2
import numpy as np
# ============================================================================
INPUT_WIDTH = 160
INPUT_HEIGHT = 120
OUTPUT_TILE_WIDTH = 10
OUTPUT_TILE_HEIGHT = 12
TILE_COUNT = OUTPUT_TILE_WIDTH * O... | 1,392 | 542 |
import pandas as pd
import numpy as np
from snsynth.pytorch.nn import DPCTGAN, PATECTGAN
from snsynth.preprocessors import DPSSTransformer
eps = 3.0
batch_size = 20
size = 100
pd_data = pd.DataFrame(columns=["A"], data=np.array(np.arange(0.0, size)).T)
np_data = np.array(np.arange(0.0, size)).astype(np.double)
clas... | 1,878 | 612 |
__author__ = 'olesya'
import unittest
from engine.api_request import ApiRequest
from engine.sources_wrapper import SearchEventsUsingAPI
from engine.eventbrite_api import EventbriteApi
import json
from google.appengine.ext import ndb
from google.appengine.ext import testbed
try:
from google.appengine.... | 3,337 | 1,103 |
# python
import atexit
import logging
import subprocess
import urllib3
from collections import namedtuple
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool
from typing import List, Dict, Callable, Optional, Any
# libs
import influxdb
from cloudcix.conf import settings
# Suppress Insec... | 4,037 | 1,220 |
from django.test import TestCase
from fedireads import models
from fedireads import status as status_builder
class Review(TestCase):
''' we have hecka ways to create statuses '''
def setUp(self):
self.user = models.User.objects.create_user(
'mouse', 'mouse@mouse.mouse', 'mouseword')
... | 3,223 | 970 |
from unittest.mock import Mock, PropertyMock
import pytest
from django.contrib.auth import get_user_model
from django_oac.backends import OAuthClientBackend
from django_oac.exceptions import NoUserError
from ..common import USER_PAYLOAD
UserModel = get_user_model()
@pytest.mark.django_db
def test_get_user_does_no... | 1,273 | 427 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Dlg_lvbo.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Dlg_lvbo_class(object):
def setupUi(self, Dialog):
... | 10,725 | 4,035 |
from hfo import MOVE_TO, DRIBBLE_TO, KICK_TO
from actions_levels import BaseActions
class DiscreteActions:
actions = ["MOVE_UP", "MOVE_DOWN", "MOVE_LEFT", "MOVE_RIGHT",
"KICK_TO_GOAL",
"DRIBBLE_UP", "DRIBBLE_DOWN", "DRIBBLE_LEFT", "DRIBBLE_RIGHT"]
def get_num_actions(self):... | 1,520 | 502 |
#!/usr/bin/env python3
import json
import os
import sys
import asyncio
import websockets
import logging
import sounddevice as sd
import argparse
import queue
from vosk import Model, KaldiRecognizer
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except Valu... | 2,946 | 878 |
# Copyright 2021 Efabless 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 required by applicable law or agreed to in... | 10,955 | 3,560 |
from abc import ABC # abstract base class
from collections.abc import MutableSequence
from number import Complex
class Playlist(MutableSequence):
pass
filmes = Playlist()
num = Complex(1, 2)
| 201 | 58 |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import time
from typing import Any, Callable, Dict, Iterable, Iterator, List, ... | 32,467 | 10,040 |
import torch.nn.functional as F
import torch
# --- losses
def masked_nll_loss(preds, targets):
return F.nll_loss(preds[targets.mask], targets.data[targets.mask])
def masked_TOP_loss(preds, targets):
"""
Top One Probability(TOP) loss,from <<Learning to Rank: From Pairwise Approach to Listwise Approach>>
... | 575 | 223 |
from typing import Tuple, Union
import numpy as np
from scipy.special import erf
class RectifiedGaussianDistribution(object):
"""Implementation of the rectified Gaussian distribution.
To see what is the rectified Gaussian distribution, visit:
https://en.wikipedia.org/wiki/Rectified_Gaussian_distribu... | 9,101 | 2,765 |
from telegram.ext import ConversationHandler
from telegram.ext import CommandHandler
from telegram.ext import Filters, MessageHandler
from telegram.ext import Updater
def start(bot, update):
update.message.reply_text(
"Привет. Пройдите небольшой опрос, пожалуйста!\n"
"Вы можете прервать опр... | 2,138 | 750 |
from fastapi import APIRouter, Request
from src.utils import best_saved_model
router = APIRouter()
@router.put("/update", name="update-best-model")
async def update_best_model(request: Request):
request.app.state.best_model = best_saved_model(request.app.state.run_id)
| 277 | 88 |
import sys
import unittest
from typing import NamedTuple, Optional, Dict
from xrpc.const import SERVER_SERDE_INST
from xrpc.serde.abstract import SerdeSet, SerdeStepContext
from xrpc.serde.types import CallableArgsWrapper
class Simple2(NamedTuple):
y: Optional[str] = 'asd'
class Simple(NamedTuple):
x: Opt... | 1,693 | 641 |
print("Hello from file 1")
pr | 30 | 12 |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... | 8,873 | 2,446 |
default_app_config = 'coberturas_medicas.apps.CoberturasMedicasConfig' | 70 | 24 |
"""Change orders.service_id to String
Revision ID: 650_change_service_id_datatype
Revises: 640_add_orders_table
Create Date: 2016-07-01 13:15:29.629574
"""
# revision identifiers, used by Alembic.
revision = '650_change_service_id_datatype'
down_revision = '640_add_orders_table'
from alembic import op
import sqlalc... | 948 | 346 |
from django.urls import include, path, re_path
from rest_framework import routers
from . import views
from .utils import *
router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'organizations', views.OrganizationViewSet)
router.regi... | 1,254 | 374 |
#!/usr/bin/env python
# coding: utf-8
##########################################################################################
#### Import libraries
import requests
import os
from zipfile import ZipFile
import xml.etree.ElementTree as ET
import pandas as pd
import glob
import numpy as np
import re
import shutil
###... | 9,241 | 2,869 |
"""Test the execution engines."""
import copy
import amici
import cloudpickle as pickle
import numpy as np
import pypesto
import pypesto.optimize
import pypesto.petab
from ..petab.petab_util import folder_base
from ..util import rosen_for_sensi
def test_basic():
for engine in [
pypesto.engine.SingleCo... | 3,777 | 1,297 |
#! /usr/bin/env python
"""
************
Test Objects
************
"""
import os
import sys
import copy
import pickle
import optparse
import numpy
from mvn import Mvn
from mvn.matrix import Matrix
from mvn.helpers import randint
(fileDir, _) = os.path.split(os.path.abspath(__file__))
pickleName = os.path.join(... | 5,214 | 1,696 |
import traceback
import time
import base64
import ssl
import google_wrapper.common as gwc
PUBSUB_SCOPES = ["https://www.googleapis.com/auth/pubsub"]
def get_full_subscription_name(project, subscription):
"""Return a fully qualified subscription name."""
return gwc.fqrn("subscriptions", project, subscriptio... | 5,868 | 1,675 |
__import__("pkg_resources").declare_namespace(__name__) # type: ignore[attr-defined]
| 86 | 28 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.sitemaps import Sitemap
from booksite.book.models import Book
class BookSitemaps(Sitemap):
changefreq = 'hourly'
priority = 0.5
def items(self):
return Book.objects.order_by("-last_update").filter(last_update__isnu... | 397 | 137 |
from playsound import playsound
from renit import reinit_app
from shape_creators import *
from testbrain import TestBrain
from tkinter import ttk
from ttkthemes import ThemedTk
import math
REC_WIDTH = 600
REC_HEIGHT = 200
RECTANGLE_COLOUR = "#3fc1c9"
RECTANGLE_TEXT_COLOUR = "#364f6b"
BACKGROUND_COLOUR = "#f5f5f5"
RE... | 7,411 | 2,434 |
"""python vast module
Example:
Disclaimer: `await` does not work in the python3.7 repl,
use either python3.8 or ipython.
Create a connector to a VAST server:
> from pyvast import VAST
> vast = VAST(app="/opt/tenzir/bin/vast")
Test if the connector works:
> await vast.connect()
Extract ... | 1,687 | 516 |
# Generated by Django 3.0.3 on 2020-09-06 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wallet', '0021_auto_20200905_0845'),
]
operations = [
migrations.AddField(
model_name='position',
name='total_divide... | 458 | 167 |
from electric_field import *
from physics_engine import *
import math
# Constant variables
scene.width = 1600
scene.height = 800
# Create field
my_field = electric_field()
my_charge = point_charge(0.001, -1E-9, 10, 10, 10)
while True:
# Set frame rate
rate(20)
# This allows the charge to bounce around... | 633 | 247 |
from oo.pessoa import Pessoa
p = Pessoa()
print(type(p)) | 58 | 28 |
# -*- coding: utf-8 -*-
import sys
from odoo.tools import convert
convert.csv.field_size_limit(sys.maxsize)
| 110 | 44 |
from abc import ABCMeta
from abc import abstractmethod
from unittest import TestCase
from typing import Iterable
from typing import List
from opwen_email_client.domain.email.store import EmailStore
class Base(object):
class EmailStoreTests(TestCase, metaclass=ABCMeta):
page_size = 10
@abstractme... | 17,733 | 5,691 |
import time
from src.objs import *
#: Flood prevention
def floodControl(message, userLanguage):
userId = message.from_user.id
if userId == config['adminId']:
return True
#! If the user is not banned
if not dbSql.getSetting(userId, 'blockTill', table='flood') - int(time.time()) > 0:
... | 1,513 | 447 |
from datetime import datetime
from airflow import DAG, AirflowException
from datetime import datetime
from airflow.operators.python_operator import PythonOperator
from airflow.utils.trigger_rule import TriggerRule
def print_1():
return 'Step 1'
def print_2():
#raise AirflowException('Oops!') #Uncomment to m... | 1,138 | 348 |
#!/bin/env python
"""
Module simtk.unit.basedimension
BaseDimension class for use by units and quantities.
BaseDimensions are things like "length" and "mass".
This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structur... | 3,449 | 1,034 |
from sqlalchemy import create_engine
import pandas as pd
import psycopg2
class EngineConnect:
def __init__(
self,
uri: str
):
self.engine = create_engine(uri)
self.conn = self.engine.connect()
def create(self, data, schema, table):
df = pd.json_normalize(d... | 3,224 | 960 |
# -*- coding: utf-8 -*-
# Copyright 2021, CS GROUP - France, http://www.c-s.fr
#
# This file is part of EODAG project
# https://www.github.com/CS-SI/EODAG
#
# 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... | 21,743 | 7,401 |
# 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 ... | 1,962 | 547 |
'''
This module contains all the functions that will parse a particular dataset
into a `target_extraction.data_types.TargetTextCollection` object.
Functions:
1. semeval_2014
'''
import json
from pathlib import Path
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
from xml.etree.ElementTree... | 30,432 | 8,408 |
class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
max_acc = 0
for account in accounts:
sum_acc = 0
for num in account:
sum_acc += num
if max_acc < sum_acc:
max_acc = sum_acc
return max_acc | 309 | 87 |
from __future__ import unicode_literals
import logging
import json
import requests
from django.template import Context
from django.conf import settings
from django.urls import reverse
from django.contrib.sites.models import Site
from django import template
from campaign.backends.base import BaseBackend
from campaign.c... | 6,973 | 1,920 |
import tkinter as tk
class GUI:
def __init__(self,master):
self.master=master #penceremin ustundeki configler icin master tanımımı kullandım
self.label_name=tk.Label(master,text='Adı soyadı:',font=('Arial',10))
self.label_name.place(x=10,y=10)
#text fieldlerdan tkinter uygulamala... | 1,444 | 565 |
from flask import Blueprint, jsonify
bp = Blueprint("api", __name__, url_prefix="/api")
@bp.route("/hello")
def hello():
return jsonify("Hello, World!")
| 160 | 54 |
#Import modules
import numpy as np
from sklearn.linear_model import ElasticNetCV
import pandas as pd
import time
from joblib import Parallel, delayed
import multiprocessing
#Define functions
def make_weights(E_dist, theta):
w = [np.exp(-1 * theta * E_dist[i] / np.mean(E_dist)) for i in range(E_dist.shape[0])]
... | 4,053 | 1,537 |
# ! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2020 NVIDIA. 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
#... | 16,634 | 5,508 |
from sympycore import *
P = PolynomialRing
def test_default_ring():
r = repr(P.convert(0))
assert r=="PolynomialRing('0')", r
assert P.zero==P.convert(0)
assert str(0)=='0'
assert `P.convert(2)`=="PolynomialRing('2')",repr(P.convert(2))
def test_X():
X = PolynomialRing['x']
C = X.convert... | 2,314 | 1,215 |
# Label the Z position
values = grid.points[:, 2]
# Create plotting class and add the unstructured grid
plotter = pv.Plotter()
# color mesh according to z value
plotter.add_mesh(grid, scalars=values,
scalar_bar_args={'title': 'Z Position'},
show_edges=True)
# Add labels to points on ... | 594 | 206 |
#!/usr/bin/env python
import argparse
import sys
import time
from time import sleep
from typing import Optional
from typing import Sequence
from typing import Tuple
from paasta_tools import mesos_tools
from paasta_tools.frameworks.native_scheduler import create_driver
from paasta_tools.frameworks.native_scheduler impo... | 5,676 | 1,695 |
'''
weakref
weakref.WeakValueDictionary
'''
import logging
a = logging.getLogger('foo')
b = logging.getLogger('bar')
print( a is b )
c = logging.getLogger('foo')
print( a is c ) #True.same name logger is same instance
# The class in question
class Spam:
def __init__(self, name):
self.name = name
# Caching... | 1,070 | 379 |
from setuptools import setup, find_packages
setup(name='my_friend',
version='0.1',
description="Python library to make my days better",
long_description='just 4 lulz',
classifiers=[],
keywords='',
author='Daniel Kanzel',
author_email='danersow@gmail.com',
url='',
l... | 841 | 258 |
from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'inventory',
'USER': 'inventory',
'PASSWORD': 'inventory',
'HOST': 'localhost',
'PORT': '',
}
}
#KEY_PREFIX = 'prod'
#KEY_FUNCTION = 'testsite.common.cachi... | 1,254 | 490 |
import subprocess
import platform
from os import linesep
from time import sleep
from pyspectator.convert import UnitByte
CLEAR_CMD = 'cls' if platform.system() == 'Windows' else 'clear'
def clear():
subprocess.call(CLEAR_CMD, shell=True)
def print_hr(space_before=False, space_after=False):
before = linese... | 3,986 | 1,148 |
def main():
assert 1 / 2 == 0
print('success')
if __name__ == "__main__":
main()
| 95 | 39 |
#!/usr/bin/env python
# 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 ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Li... | 11,500 | 3,905 |
from django.contrib import admin
from django.contrib.gis.admin import OSMGeoAdmin
from rgd.admin.mixins import MODIFIABLE_FILTERS, TASK_EVENT_FILTERS, TASK_EVENT_READONLY, reprocess
from rgd_imagery.models import ProcessedImage, ProcessedImageGroup
class ProcessedImageAdmin(admin.StackedInline):
model = Processed... | 1,065 | 374 |
n = int(input('Digite um número: '))
print('O dobro é {}.\nO triplo é {}.\nA raiz quadrada é {:.2f}'.format(n * 2, n * 3, n ** (1/2)))
| 137 | 67 |
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
"""
C4705586 - Altering connections on graph nodes appropriately updates component properties
C22715182 - Compo... | 7,755 | 2,155 |
import csv
with open('int.csv') as my_file:
read = csv.reader(my_file)
for row in read:
print(row)
| 115 | 42 |
#imports
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
#variables
#these variables will be
#changed by the input funcation
Timer = 3
link = ''
views = 10
print('''____________________________________________________
... | 1,657 | 544 |
#coding=utf-8
#graphpipe官网的一个例子
#https://oracle.github.io/graphpipe/#/guide/user-guide/quickstart
#pip install graphpipe
#pip install pillow # needed for image manipulation
'''
#服务器端启动方式为:
docker run -it --rm \
-e https_proxy=${https_proxy} \
-p 9000:9000 \
sleepsonthefloor/graphpipe-tf:cpu \
--mo... | 835 | 346 |
class Group:
def __init__(self,name = None, header = None, footer = None):
Group.name = name
Group.header = header
Group.footer = footer | 164 | 45 |
import math
def is_prime(n):
if (math.factorial(n-1)+1) % n!=0:
print ("NO")
else:
print ("YES")
print(is_prime(13))
| 142 | 59 |
#!/usr/bin/env python
#
# Basic: 1 topic, 50 consumer/producer clients
# - Each consumer writes 10 messages
# - Each consumer gets all 10 messages
# - 1 consumer unsubs
# - 1 more message sent
# - Only the remaining 9 clients get the msg
#
import time
import helper
from radiator import Broker
consumers =... | 2,170 | 813 |
# 设计一个验证用户密码程序,用户只有三次机会输入错误,不过如果用户输入的内容中包含"*"则不计算在内。#设计一个验证用户密码程序,用户只有三次机会输入错误,不过如果用户输入的内容中包含"*"则不计算在内。
# 次数
count = 3
# 密码
password = "fishc"
while count:
Password = input("请输入密码:")
if Password == password:
print("密码输入正确")
break
elif '*' in Password:
print("密码中不能包含'*',请重新输入,您还有",cou... | 429 | 276 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
#... | 2,567 | 704 |
"""!
@brief Cluster analysis algorithm: MBSAS (Modified Basic Sequential Algorithmic Scheme).
@details Implementation based on paper @cite book::pattern_recognition::2009.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.core.mbsas_wrapper import mbsas ... | 4,126 | 1,226 |
from ._cpools import TopPool, BottomPool, LeftPool, RightPool
from ._cpools_lines import HorizontalLinePool, VerticalLinePool
| 126 | 40 |
import pandas as pd
# system vars
path_to_usim = '/home/mgardner/src/bayarea_urbansim/'
usim_data_dir = 'data/'
usim_output_dir = 'output/'
usim_h5_file = '2015_09_01_bayarea_v3.h5'
path_to_asim = '/home/mgardner/src/activitysim/'
asim_data_dir = 'example/data/'
asim_h5_file = 'mtc_asim.h5'
# load both data stores
us... | 2,306 | 970 |
import torchvision
from torch.utils.data import DataLoader
from torchvision import transforms
from PIL import Image
from config import cfg
from loader.cifar10 import get_cifar10
from loader.cifar100 import get_cifar100
from loader.imagenet import get_imagenet
def get_loader():
pair = {
'cifar10': get_cif... | 433 | 164 |
import time
################
# DECORATORS #
################
def simple_time_tracker(method):
"""Time tracker to check the fitting times when training the models."""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if "log_time" in kw:
... | 970 | 337 |
import gym
from gym.envs.registration import register
from bark_ml.environments.single_agent_runtime import SingleAgentRuntime
from bark_ml.environments.blueprints.highway.highway import DiscreteHighwayBlueprint
from bark_ml.environments.blueprints.merging.merging import DiscreteMergingBlueprint
from bark_ml.environm... | 2,712 | 727 |
"""OpenAPI core security schemes models module"""
from openapi_core.schema.security_schemes.enums import (
SecuritySchemeType, ApiKeyLocation, HttpAuthScheme,
)
class SecurityScheme(object):
"""Represents an OpenAPI Security Scheme."""
def __init__(
self, scheme_type, description=None, name=N... | 805 | 245 |
# gotten from https://pbpython.com/improve-pandas-excel-output.html
"""
Show examples of modifying the Excel output generated by pandas
"""
import pandas as pd
import numpy as np
from xlsxwriter.utility import xl_rowcol_to_cell
df = pd.read_excel("../in/excel-comp-datav2.xlsx")
# We need the number of rows in order... | 3,589 | 1,178 |
import numpy as np
import numpy.testing as npt
import riip
from riip.formulas import formulas_cython_dict, formulas_numpy_dict
def test_cython_formulas():
rid = riip.RiiDataFrame()
fbps = {
1: ("MgAl2O4", "Tropf"),
2: ("Ar", "Borzsonyi"),
3: ("methanol", "Moutzouris"),
4: ("Ba... | 895 | 392 |
def cost_fun_generator(avoidCurbs=True, uphill=0.083, downhill=-0.1):
def cost_fun(u, v, d):
# No curb ramps? No route
if d["footway"] == "crossing" and not d["curbramps"]:
return None
# Too steep?
if d["incline"] is not None:
if d["incline"] > uphill or d["in... | 470 | 162 |
#!/usr/bin/env python3
import sys
import requests
import hashlib
import random
import re
import functools
import time
import json
import pathlib
import base64
import traceback
import PIL.Image
from io import BytesIO
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA25... | 6,823 | 2,491 |
import pytest
from plenum.common.throughput_measurements import RevivalSpikeResistantEMAThroughputMeasurement
from plenum.test.helper import get_key_from_req
nodeCount = 7
@pytest.fixture(scope="module")
def tconf(tconf):
old_throughput_measurement_class = tconf.throughput_measurement_class
old_throughput_m... | 1,569 | 513 |
import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge
from oolearning.model_wrappers.HyperParamsBase import HyperParamsBase
from oolearning.model_wrappers.ModelExceptions import MissingValueError
from oolearning.model_wrappers.ModelWrapperBase import ModelWrapperBase
from oolearning.model_wrapp... | 1,929 | 582 |
n = int(input())
b = list(map(int, input().split()))
ans = [0] * n
ans[0] = b[0]
ans[1] = b[0]
for i in range(1, n - 1):
ans[i] = min(ans[i], b[i])
ans[i + 1] = b[i]
print(sum(ans))
| 190 | 100 |
from google_spreadsheets import GoogleSpreadsheetsClient
| 59 | 17 |
from django.test import TestCase
from django.contrib.auth.models import User
from orcamentos.crm.models import Employee, Occupation
from .data import USER_DICT # , SELLER_DICT
# class SellerTest(TestCase):
# def setUp(self):
# self.user = User.objects.create(**USER_DICT)
# self.occupation = Occu... | 801 | 259 |
import os
POCAPI_URL = os.getenv("POCAPI_URL", "http://localhost:6666")
| 73 | 33 |
# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
from typing import List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def levelOrderBottom(self,... | 692 | 218 |
a_set = {'red', 'blue', 'green'}
print(type(a_set)) | 51 | 23 |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import SalesViewSet
urlpatterns = [
path('', SalesViewSet.as_view({'get': 'listcode'})),
path('forecast/', SalesViewSet.as_view({'get': 'forecast'})),
path('product_factor/', SalesViewSet.as_view({'get': ... | 393 | 135 |
"""
Note: This is a updated version from my previous code,
for the target network, I use moving average to soft replace target parameters instead using assign function.
By doing this, it has 20% speed up on my machine (CPU).
Deep Deterministic Policy Gradient (DDPG), Reinforcement Learning.
DDPG is Actor Critic ba... | 5,453 | 2,116 |