content stringlengths 5 1.05M |
|---|
'''
You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving.
bouncingBall(initialHeight, bouncingProporti... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance
# {"feature": "Bar", "instances": 34, "... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# -*- coding: utf-8 -*-
from .fpn import FPN
from .hrfpn import HRFPN
__all__ = ['FPN', 'HRFPN']
|
#!/usr/bin/python
from django import forms
# Local model Shop application
from .models import TeslaCar
class TeslaForm(forms.ModelForm):
class Meta:
model = TeslaCar
fields = ('title', 'author', 'image', 'slug', 'price', 'description', 'car_type', 'engine_power', 'publication_date')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from apiclient import discovery
import logging
from oauth2client import client
import httplib2
from datetime import datetime, timedelta
import tools
from constants import SECURE_BASE
from settings.secrets import GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
from oauth2client.client i... |
import numpy as np
import requests
import telebot
import torch
from PIL import Image
import os
import configs
import time
model = torch.hub.load('pytorch/vision:v0.6.0', 'densenet121', pretrained=False)
import torchvision
weights_path = configs.path_to_weights
bot = telebot.TeleBot(configs.token, threa... |
import copy
import numpy as np
import os
import random
import math
from sklearn.metrics import classification_report, confusion_matrix
import csv
import torch.nn as nn
import torch
import torch.nn.functional as F
def weights_init(module):
if isinstance(module, nn.BatchNorm2d):
module.weigh... |
#if elif else
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Lets check if they pressed the right keys
def check_keys(key):
if key == "1":
spk("Great, you are correct!")
elif key == "return" or key == "space":
spk("This is also correct!")
elif key == "f2":
spk("And you f... |
class Person:
count = 0
"""Represents a generic Person."""
def __init__(self, first, last, weight, height, age=0, gender=''):
self.first_name = first
self.last_name = last
self.weight_in_lbs = weight
self.height_in_inches = height
self.this_age = age
self.th... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
class PWNet(nn.Module):
def __init__(self, size, kernel_num, init_='random'):
"""
Params:
size: tuple or int, output size
kernel_num: int, number of kernels in pivots
init_: str, ... |
from typing import Dict
import torch
from nets import VotingNet
from evaluator.evaluators import LinemodEvaluator
from utils.io_utils.inout import save_dict_to_txt
def main():
# Load the network
net = VotingNet()
last_state = torch.load('/home/ryan/Codes/VotingNet6DPose/log_info/models/linemod_cat_fps_debug_epoc... |
# -*- coding: utf-8 -*-
"""
onami.features.shell
~~~~~~~~~~~~~~~~~~~~~~~~
The onami shell commands.
:copyright: (c) 2021 Devon (Gorialis) R
:license: MIT, see LICENSE for more details.
"""
from nextcord.ext import commands
from onami.codeblocks import Codeblock, codeblock_converter
from onami.cog import build, ve... |
print('11111w')
print('22222w')
print('33333.zzzzz')
print('44444') |
"""
Atmosphere api email
"""
from rest_framework.response import Response
from rest_framework import status
from django.template.loader import render_to_string
from django.template import Context
from threepio import logger
from django_cyverse_auth.protocol.ldap import lookupEmail
from core.models import AtmosphereU... |
"""
__FileCreationDate__ : 2/5/2020
__Author__ : CodePerfectPlus
__Package__ : Python 3
__GitHub__ : https://www.github.com/codeperfectplus
"""
from Algorithms import insertionSort
sortedArray = insertionSort([4, 2, 6, 5, 9, 8])
print(sortedArray)
|
import requests
from requests.auth import HTTPBasicAuth
import json
import logging
from typing import List
from togglcmder.toggl.endpoints.api import API
from togglcmder.toggl.types.project import Project
from togglcmder.toggl.encoders.project_encoder import ProjectEncoder
from togglcmder.toggl.decoders.project_decod... |
# Built-int imports
import os
# External imports
import cv2 as cv
import numpy as np
# My Own imports
import sample_class_1 as sc1
import get_path_assests_folder as gpaf
# Get assets folder in repo for the samples
ASSETS_FOLDER = gpaf.get_assets_folder_path()
"""TOPICS (7-24-2021):
* How to use the click-mouse eve... |
import sqlite3
from .db import DB
class DistrictInfo(DB):
def __init__(self):
super().__init__()
self.table_name = 'MP_district_info'
self.table_desc = 'District level information'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
'date': 'DATE... |
# -*- coding: utf-8 -*-
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
md_text = '''```python
import dash
print('hello, world!')
```'''
def test_msmh001_no_window_variable(dash_dcc):
app = dash.Dash(__name__)
app.layout = html.... |
import pandas as pd
import re
import twitter as tw
TWEET_STARTING_WITH = "Liczba zakażonych koronawirusem"
TWEET_MIDDLE = "/"
TWEET_ENDING_WITH = "\(wszystkie pozytywne przypadki/w tym osoby zmarłe\)"
def total_cases_and_deaths(t: tw.Twitter) -> pd.DataFrame:
# Most of the code below is copy-pasted from https://... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
"""
from .NVD3Chart import NVD... |
# -*- coding: utf-8 -*-
"""
Package for calculating radiation from relativistic trajectories.
"""
__version__ = '0.1.0'
|
#!/usr/bin/env python
import webapp2
from google.appengine.api import app_identity, mail, memcache
from google.appengine.ext import ndb
from conference import ConferenceApi
from conference import MEMCACHE_FEATURED_SPEAKER_KEY
from models import Session
class SetAnnouncementHandler(webapp2.RequestHandler):
def get... |
# NACA_volume_compute.py
#
# Created: April 2018, W. Maier
# Modified:
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import SUAVE
from SUAVE.Core import Data
import numpy as np
from SUAVE.Methods.Geomet... |
# -*- coding: utf-8 -*-
"""
utils/strava.py
=================
Utility class to Strava API
"""
import json
import time
from configparser import ConfigParser, NoOptionError
from datetime import datetime
from pathlib import Path
from typing import Tuple
from loguru import logger
from stravalib import Client, exc
from ut... |
import torch
import torch.nn
class FC(torch.nn.Module):
def __init__(self, in_features, out_features, act=torch.nn.ReLU(inplace=True)):
super().__init__()
self.linear = torch.nn.Linear(in_features, out_features, bias=True)
self.act = act
def forward(self, input):
output = self.linear(input)
o... |
import numpy as np
from mirdata.datasets import small_4mula
from tests.test_utils import run_track_tests
TEST_DATA_HOME = "tests/resources/mir_datasets/small_4mula"
def test_track():
default_trackid = "3ade68b6g3429fda3"
dataset = small_4mula.Dataset(TEST_DATA_HOME)
track = dataset.track(default_trackid... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$|^index$', views.index, name='index'),
url(r'^process/([0-9]+)$', views.run_process, name='run'),
url(r'^report/([0-9]+)$', views.report, name='report')
]
|
#!/usr/bin/env python
"""
simple SVM example
"""
from sklearn.svm import SVC
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import f1_score, fbeta_score, make_scorer
rs=42
X, y = make_classification(n_samples=3000, n_featur... |
def write_job(sweep, run, config_list, prev=0, line_per_file=1):
f = open("tasks_{}.sh".format(prev), "w")
count = 0
for config in config_list:
for s in range(sweep):
for r in range(run):
f.write("./main -config {} -run {} -sweep {}\n".format(config, r, s))
... |
"""Contains argument validating stuff."""
from functools import partial
from pathlib import Path
from typing import Dict, Any, Callable, Iterable, cast, Union, Optional
ValidationReturn = Union[bool, Dict[str, bool]]
class Validator:
"""
Provides utility methods to easily validate arguments / variables.
... |
import matplotlib.pyplot as plt
import matplotlib
from descartes import PolygonPatch
import numpy as np
from shapely.geometry import box, Polygon, Point
import bezier
def plot_geom(ax, geom, x_lim=[-2, 12], y_lim=[-2, 12], shell_color=[]):
polygon_patch = PolygonPatch(Polygon(geom.exterior))
ax.add_patch(poly... |
"""Constants used in test fixtures and setup."""
TEST_DATABASE_URL = (
"postgresql://gafaelfawr:INSECURE-PASSWORD@127.0.0.1/gafaelfawr"
)
"""The URL used for the test database.
This must match the ``tox.ini`` configuration for the PostgreSQL container.
"""
TEST_HOSTNAME = "example.com"
"""The hostname used in AS... |
"""
Django settings for ozp project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths in... |
import HONHelpers as hon
import caffe
import google.protobuf.text_format
import os
from datetime import datetime
import argparse
def check_base_lr(solver_in):
solver = caffe.io.caffe_pb2.SolverParameter()
with open(solver_in) as f:
google.protobuf.text_format.Merge(f.read(), solver)
return solver.b... |
# Copyright (c) 2014 Mirantis, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
import numpy as np
import matplotlib.pyplot as plt
import os
from PIL import Image
from gloria.datasets.visualization_utils import pyramid_attn_overlay
def np_to_jpg(directory):
for file in os.listdir(directory):
if file.endswith('.npy'):
image = np.load(file)
if image.shape[0] != 2... |
"""
[4/16/2014] Challenge #158 [Intermediate] Part 1 - The ASCII Architect
https://www.reddit.com/r/dailyprogrammer/comments/236va2/4162014_challenge_158_intermediate_part_1_the/
#Description
In the far future, demand for pre-manufactured housing, particularly in planets such as Mars, has risen very high. In
fact, th... |
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def check_char(value):
print(value)
if len(value) < 300:
return ""
else:
return "continue reading"
|
def chek_digit_sum(n):
if n > 9:
s = 0
while(n != 0):
s += n % 10
n //= 10
return s
return n
for _ in range(int(input())):
n,d = [int(x) for x in input().split()]
dp = {}
calculated_states = [(n,0)]
final_ans, final_steps = n , 0
timer = 100000
while(len(calculated_states) > 0 and timer > 0):
tim... |
import numpy as np
import math
import sys
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.linear_model import LinearRegression
from ..Config.config_handler import read_config
config_vals = read_config("Footfall_API")
# Time Serie... |
import numpy as np
import os
import glob
import random
import torch
from pickle import load, dump
SAVED_RUNS_PATH = 'saved_data/'
EXP_PATH = 'exps_setup/'
def save_run(suffix, run):
if not os.path.isdir(SAVED_RUNS_PATH):
os.mkdir(SAVED_RUNS_PATH)
file = SAVED_RUNS_PATH + suffix + '.pickle'
with ... |
__all__ = ["search"] |
'''
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# 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. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
im... |
import FWCore.ParameterSet.Config as cms
#--------------------------------------------------------------------------------
# parametrization of MET x/y shift vs. sumEt
pfMEtSysShiftCorrParameters_2011runAvsSumEt_data = cms.PSet(
px = cms.string("-3.365e-1 + 4.801e-3*sumEt"),
py = cms.string("+2.578e-1 - 6.124e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Get history from http://www.taifex.com.tw/chinese/3/3_1_3.asp
merge to K bar csv data
http://www.taifex.com.tw/DailyDownload/Daily_`date +%Y_%m_%d`.zip
"""
import urllib2
import datetime
import zipfile
import csv
import string
import sys
import shutil
import os
import c... |
"""Measure the runtime of the propagators."""
from timeit import repeat
import itertools
import numpy as np
import pandas as pd
from wave_2d_fd_perf_gpu.cuda import (VCuda1, VCuda2, VCuda3, VCuda4, VCuda5)
from wave_2d_fd_perf_gpu.numba import (VNumba1)
from wave_2d_fd_perf_gpu.pytorch import (VPytorch1, VPytorch2)
fro... |
import numpy as np
from utils import finite
from scipy import fftpack, optimize
from utils import large_float
from compat import irange
def variance_bandwidth(factor, xdata):
r"""
Returns the covariance matrix:
.. math::
\mathcal{C} = \tau^2 cov(X)
where :math:`\tau` is a correcting factor t... |
# Copyright (c) 2013 - 2016 by pyramid_fullauth authors and contributors <see AUTHORS file>
#
# This module is part of pyramid_fullauth and is released under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""Additional tools used in pyramid_fullauth."""
import string
from random import choice
from pyrami... |
# Generated by Django 2.0.7 on 2018-07-26 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(aut... |
#!/usr/bin/env python3
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... |
#!/usr/bin/env python3
import os
import mpi4py
mpi4py.rc.threaded = True
mpi4py.rc.thread_level = "funneled"
from mpi4py import MPI
from mpi_lib import Distributed
os.makedirs('vis/', exist_ok=True)
# Main program
def main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
d... |
import asyncio
from asyncio_dispatch import Signal
@asyncio.coroutine
def callback(**kwargs):
print('callback was called!')
loop = asyncio.get_event_loop()
# create the signal
signal = Signal(loop=loop)
# connect the callback to the Signal - This is a coroutine!
loop.run_until_complete(signal.connect(callback... |
import logging
import os
import shutil
import tempfile
from fnmatch import fnmatch
import hyperscan
from .base_scanner import BaseScanner, ResultHandler
logger = logging.getLogger(__name__)
class FileScanner(BaseScanner):
def __init__(self, rules):
""" Create the scanner for a local directory or file.
... |
from django.apps import apps
from django.conf import settings
from django.db.models.signals import post_save, m2m_changed
from django.contrib.auth import get_user_model
from mighty.apps import MightyConfig
from mighty.applications.tenant.apps import TenantConfig
from mighty.applications.tenant import get_tenant_model
... |
import unittest
import os
from rest_tester.function import TestFunctionBuilderFactory, TestFunctionBuilder
from rest_tester.function.single import SingleTargetTestFunctionBuilder
from rest_tester.function.multiple import MultipleTargetsTestFunctionBuilder
from rest_tester.options import Options
from rest_tester.setti... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Created on 19/01/12 08:18:27
@author: Changzhi Sun
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphConvoluation(nn.Module):
def __init__(self,
input_dim: int,
output_dim: int,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
from resilient_sdk.cmds import CmdExtPackage
def test_setup():
# TODO
pass
def test_execute_command():
# TODO
pass |
from antlr4 import InputStream, CommonTokenStream
from .ASLLexer import ASLLexer
from .ASLParser import ASLParser
from .asl_type import ASLType
def asl_to_lang(string, fields, LangVisitor):
"""Converts the given processed ASL string into a code snippet
For instance the following ASL code::
integer b... |
from output.models.ms_data.element.qfe1700g_xsd.qfe1700g import (
E1,
Root,
)
__all__ = [
"E1",
"Root",
]
|
# kaggle.py module
import csv
import numpy as np
#Save prediction vector in Kaggle CSV format
#Input must be a Nx1, 1XN, or N long numpy vector
def kaggleize(predictions,file):
if(len(predictions.shape)==1):
predictions.shape = [predictions.shape[0],1]
ids = 1 + np.arange(predictions.shape[0])[None].T
kaggle_p... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python [conda env:PROJ_irox_oer] *
# language: python
# name: conda-env-PROJ... |
#!/usr/bin/env python3
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
from luma.core.error import DeviceNotFoundError
import os
import time
import signal
import sys
import socket
from PIL import ImageFont, ImageDraw
def ge... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 James Beedy <jamesbeedy@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is... |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import json
import os
import shutil
import sys
import common
BLINK_TOOLS_DIR = os.path.join(common.SRC_DIR, 'third_party', 'blink', 'tools')
... |
# Copyright 2012-2013 OpenStack Foundation
#
# 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 la... |
# CÁLCULO DE IMPOSTO CONFORME REGRA DESCRITA NO REAME
income = float(input("Enter the annual income: "))
if income == 0:
tax = 0
tax = round(tax, 0)
print("The tax is:", tax, "thalers")
elif income <= 85528:
PIT = 0.18
tax = (income * PIT)- 556.02
tax = round(tax, 0)
print("The t... |
from direct.fsm import ClassicFSM, State
from toontown.shtiker.OptionsPageGUI import OptionButton
from toontown.toonbase.TTLocalizer import Controls, RemapPrompt, RemapPopup
from toontown.toonbase.ToontownGlobals import OptionsPageHotkey
from toontown.toontowngui import TTDialog
class ControlRemap:
UP = 0
LEFT... |
from django.urls import path
from . import views
urlpatterns = [
path("encontrar_jobs/", views.encontrar_jobs, name="encontrar_jobs"),
]
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation.
# 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.... |
import sys, os, random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing i... |
import csv
import json
import os
import re
from collections import defaultdict
from django.conf import settings
alias_json = os.path.join(settings.STRING_DIR, 'alias.json')
interaction_json = os.path.join(settings.STRING_DIR, 'interaction.json')
ORGANISM_TO_ALIAS_FILE = dict()
for organism, path in [
('Homo sapi... |
# -*- coding:utf-8 -*-
# Copyright (c) 2014,
# Karlsruhe Institute of Technology, Institute of Telematics
#
# This code is provided under the BSD 2-Clause License.
# Please refer to the LICENSE.txt file for further information.
#
# Author: Mario Hock
from collections import defaultdict
from operator import itemgette... |
from itertools import chain, combinations
from re import search
from urllib.parse import urlparse
from pymongo.errors import BulkWriteError
from tweepy import OAuthHandler, API
from yaml import load as yaml_load, BaseLoader
from objects.article import Article
from objects.hashtag import Hashtag
from objects.tweet imp... |
class Netlist:
instances = []
connection = []
bram_cols = [2*2, 3*2, 7*2, 12*2, 14*2, 19*2, 20*2, 25*2, 27*2, 32*2, 34*2, 41*2, 49*2, 50*2]
height = 160 # 0, 2, 5, 7
# how mamy BRAMs? 80 blocks * 8 each = 640
# we have 14 columns, we can put 48 brams each.
fixed_brams = [] # store bram na... |
import pandas as pd
from datetime import timedelta, date as Date
from scipy import signal
from scipy.stats import pearsonr, spearmanr
import gzip
import matplotlib.pyplot as plt
import seaborn as sns
from pandas.plotting import autocorrelation_plot
from event_study_analysis import *
sns_palette = sns.color_palette()
... |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. 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 requir... |
# #########################################
# This is for multiple client implementation
# #########################################
import base64
import asyncio
import argparse
import binascii
import json
import logging
import os
import sys
import json
from urllib.parse import urlparse
from aiohttp import web, Client... |
import os
from typing import List, Optional
from backends.model import Model
class SoftwarePackage(Model):
"""A software package."""
# name: str
# vendor: str
# alternative_names: list
def __init__(self, name: str, vendor: str, alternative_names: Optional[List] = None):
self.name = name... |
from hashlib import sha256
import pytest
from crypto.configuration.network import set_network
from crypto.constants import TRANSACTION_HTLC_LOCK, TRANSACTION_TYPE_GROUP
from crypto.networks.devnet import Devnet
from crypto.transactions.builder.htlc_lock import HtlcLock
set_network(Devnet)
def test_htlc_lock_transat... |
from cProfile import label
import os
import pandas as pd
import torch
import torch.nn.functional as F
import numpy as np
import time
from featurization.data_utils import load_data_from_df, construct_loader_gf_pressurever, construct_dataset_gf_pressurever, data_prefetcher, load_real_data, construct_dataset_real
from mod... |
from graph import Graph
from collections import deque
def get_edge(graph, cities):
q = deque()
price = 0
for city in cities:
q.appendleft(city)
while q:
current = q.pop()
for edge in current.neighbors:
tracker = 0
for city in cities:
... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import sys
from mo.subprocess_main import setup_env
def test_frontends():
setup_env()
args = [sys.executable, '-m', 'pytest',
'frontend_ngraph_test_actual.py', '-s']
status = subproc... |
def order_square(a):
right = 0
while right < len(a) and a[right] < 0:
right +=1
left = right-1
output = []
while left >= 0 and right < len(a):
if a[left]**2 < a[right]**2:
output.append(a[left]**2)
left -=1
else:
output.append(a[... |
from authors.apps.articles.models import Article
from .serializers import EscalationSerializer
from .exceptions import ArticleNotFound
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framewor... |
# Training model
# If module executes successfully, you should see .gzbin model and
# speakers.txt in your ~/jasper/ i.e where jasper.py sits.
"""
NOTE:
Even though you can train model by calling jasper modules, it is not an efficient way to do it.
Train model separately and just copy-paste the .gzbin model and speak... |
import copy
import typing
import splendor_sim.interfaces.coin.i_coin_reserve as i_coin_reserve
import splendor_sim.interfaces.coin.i_coin_type as i_coin_type
import splendor_sim.interfaces.coin.i_coin_type_manager as i_coin_type_manager
class CoinReserve(i_coin_reserve.ICoinReserve):
def __init__(
self,
... |
#!/usr/bin/env python3
""" unit test for artifact
"""
import copy
import pytest
from paddleflow.pipeline import Artifact
from paddleflow.common.exception.paddleflow_sdk_exception import PaddleFlowSDKException
from .mock_step import Step
class TestArtifact(object):
""" test Artifact
"""
@pytest.mark.tpl
... |
"""Module for an example Flake8 plugin."""
from .on_by_default import ExampleOne
from .off_by_default import ExampleTwo
__all__ = (
'ExampleOne',
'ExampleTwo',
)
|
import os
from ... import helper
from ..core.Simple import Simple
FORM83 = "13"
FORM82 = "9"
FORM81 = "7"
class Form8x(Simple):
ver = ''
folder = "Формы"
def __init__(self):
super().__init__()
self.form = None
self.elements = None
def decode_object(self, src_dir, uuid, dest_... |
import unittest
from turing_machine.implementations import CopyMachineFactory
class TestCopyMachine(unittest.TestCase):
def _get_machine_printable_output(self, *args, **kwargs):
machine = CopyMachineFactory.create(*args, **kwargs)
machine.run(verbosity=0)
return machine.printable_output
... |
import time
class Chrono:
def __init__(self, *args):
pass
def __enter__(self):
self.start = time.time()
self.end = 0
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
return self
@property
def val(self):
ret... |
from .base import IVTCircuit
__all__ = ["IVTCircuit"]
|
# Copyright (c) 2021. Berlin Institute of Health (BIH) and Deutsches Krebsforschungszentrum (DKFZ).
#
# Distributed under the MIT License. Full text at
#
# https://gitlab.com/one-touch-pipeline/weskit/api/-/blob/master/LICENSE
#
# Authors: The WESkit Team
import logging
import tempfile
from datetime import dat... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 20:04:48 2018
@author: rubenmanrique
# Ruben Manrique 2017-08-24
# Modified: 2018-01-24
"""
from SPARQLWrapper import SPARQLWrapper, JSON
import configparser
import math
class SemRefD:
# Function Indicator
fun_indi = " define input:default-graph-uri <http... |
# -*- coding: utf-8 -*-
###############################################################################
#
# ByFoursquare
# Retrieves weather and UV index data based on coordinates returned from a Foursquare recent check-in.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache... |
from __future__ import unicode_literals
from django.db import models
import re
# Create your models here.
class UserManager(models.Manager):
def validate_registration(self, data):
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$')
PASS_REGEX = re.compile(r'\d.*[A-Z]|[A-Z].... |
from typing import Iterator, List, Dict
import torch
import torch.optim as optim
import numpy as np
from allennlp.data import Instance
from allennlp.data.fields import TextField, SequenceLabelField
from allennlp.data.dataset_readers import DatasetReader
from allennlp.common.file_utils import cached_path
from allennlp.d... |
try:
import json
except:
import simplejson as json
from mongrel2 import tnetstrings
class Request(object):
def __init__(self, sender, conn_id, path, headers, body):
self.sender = sender
self.path = path
self.conn_id = conn_id
self.headers = headers
self.body = bod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.