content stringlengths 5 1.05M |
|---|
from django.test import TestCase
from .models import *
# Create your tests here.
class ProfileTest(TestCase):
def setUp(self):
self.user = User(username='Keller', email='kell@kell.com', password='passwadd')
self.user.save()
self.ras = Profile(bio='A python Programmer', contact='054234444',... |
import faiss
import sqlite3
import numpy as np
import pickle
conn = sqlite3.connect('database/reddit.db')
c = conn.cursor()
queries = []
idx = []
for row in c.execute('SELECT * from queries'):
query_embd = np.frombuffer(row[-1], dtype=np.float32)
queries.append(query_embd)
idx.append(str(row[0]))
querie... |
import argparse
import os
import pandas as pd
# For simon: Change file paths here
def main(path_csv, output_dir):
base_image_dir = r'C:\Users\mfarj\Documents\ss_data\snapshotserengeti-unzipped\snapshotserengeti-unzipped'
# Read input csv
species_df = pd.read_csv(path_csv)
print(f"Len of images with ... |
from random import shuffle
from ic_dice_tools import display_dice
class Character:
def __init__(self):
self.name = ""
self.race = ""
self.body = 0
self.speed = 0
self.mind = 0
self.will = 0
self.careers = {}
self.skills = {}
self.gifts = {}
... |
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
def get_model(props):
return basic_model(props)
def basic_model(props):
maxlen, chars = props['maxlen'], props['chars']
model = Sequential()
model.add(LSTM(512, return... |
"""
test bridge pattern
"""
import pytest
from dpatterns_python.structural import bridge
def test_main():
"""
call the main
:return:
"""
bridge.main()
@pytest.mark.parametrize(('inputs'), ([1, 2, 3], [2, 3, 4]))
def test_draw(inputs):
"""
test one circle at a time
:param inputs:
... |
"""
Wrapper around calling dep through a subprocess.
"""
import logging
LOG = logging.getLogger(__name__)
class ExecutionError(Exception):
"""
Exception raised in case binary execution fails.
It will pass on the standard error output from the binary console.
"""
MESSAGE = "Exec Failed: {}"
... |
# 3/23/18 Zebra Print Macro
# This program opens the correct label and obtains the last Lockoff serial number from a txt file
# which then proceeds to edit the label with the correct values. It will then update the associated txt file
# with the new last number
# Developed by Evan Aguilar @ AWS
# imports os system c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2017-12-27 15:37
from __future__ import unicode_literals
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migra... |
import ccxt
import pandas as pd
import time
import sys
from pandas.core.indexes import base
from func_get import get_json, get_time, get_currency, get_bid_price, get_ask_price, get_last_price, get_position, get_base_currency_value, get_cash_value, get_total_value, get_order_fee, get_available_cash_flow
from f... |
import pyroute2
import logging
logging.basicConfig(level=logging.INFO)
ip = pyroute2.IPDB()
try:
default_iface = ip.interfaces[ip.routes['default']['oif']]['ifname']
finally:
if ip._stop:
ip.release()
print(default_iface)
|
#!/usr/bin/python3
# Creates a 3D Unit Axis model
# Ben Smith
# benjamin.coder.smith@gmail.com
#
# Based heavily on: sphereworld.cpp
# OpenGL SuperBible
# Program by Richard S. Wright Jr.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import time
E... |
import megengine as mge
import megengine.functional as F
import megengine.module as M
import numpy as np
from megengine.autodiff import GradManager
from meg_networks import FullyConnectedLayer
batch_size = 2
in_channels = 512
w_dim = 512
lr = 0.1
# activation = 'linear'
# activation = 'lrelu'
# activation = 'relu'
#... |
# Generated by Django 4.0.2 on 2022-03-02 06:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0009_alter_hose_type'),
]
operations = [
migrations.AlterField(
model_name='hose',
name='type',
... |
import ctypes
import collections
import fcntl
import ioctl_opt
BUS_USB = 0x03
BUS_HIL = 0x04
BUS_BLUETOOTH = 0x05
BUS_VIRTUAL = 0x06
class _hidraw_report_descriptor(ctypes.Structure):
_fields_ = [
('size', ctypes.c_uint),
('value', ctypes.c_ubyte * 4096),
]
class _hidraw_devinfo(ctypes.Struct... |
from dartcms.apps.modules.functions import get_current_module
def modules_data(request):
if not request.is_ajax() and request.user.is_authenticated and request.user.is_staff:
modules = request.user.module_set.all()
module_groups = [m.group for m in modules]
module_groups_set = set(module_... |
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2019 Western Digital Corporation or its affiliates. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code mu... |
import os
import nose
from monstro.conf import settings
from monstro.core.constants import TEST_ENVIRONMENT_VARIABLE
from monstro.management import Command
class Test(Command):
def add_arguments(self, parser):
parser.add_argument('modules', nargs='*')
def execute(self, arguments):
os.envir... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Runs unittest.
Automatically adds ../src as a source directory.
If --remote-debug is specified and pydevsrc exists within the project it will
try to connect to the PyDev debug server on the specified IP address.
"""
from argparse import ArgumentParser
from sys import p... |
import time
from promisedio import promise, loop, timer
print("start", time.time())
async def func1():
print("func1", time.time())
def f(_):
print("HERE1", time.time())
print("#ALLOCSTAT")
return timer.sleep(1)
await timer.sleep(1).then(f)
promise.exec_async(func1())
loop.run_fo... |
# coding=utf-8
import time
def test(a, b):
return a + b
def sleep(n):
time.sleep(n)
|
import rdflib
from rdflib import plugin
plugin.register(
'sparql', rdflib.query.Processor,
'rdfextras.sparql.processor', 'Processor')
plugin.register(
'sparql', rdflib.query.Result,
'rdfextras.sparql.query', 'SPARQLQueryResult')
#Get a Graph object
g = rdflib.Graph()
# pull in an RDF document from Ne... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import six
if six.PY3:
from html.parser import HTMLParser
else:
from HTMLParser import HTMLParser
htmlparser = HTMLParser()
from lxml.etree import XMLSyntaxError
import logging
log = logging.getLogger('confluence-tool.page')
class Page(object):
def __init__(self, api, data, expand=None):
self.a... |
from django.shortcuts import render
# Create your views here.
def homepage_view(request):
return render(request, "homepage/homepage.html", {}) |
import yaml
from klaxer.models import Severity
from klaxer.errors import ServiceNotDefinedError, ConfigurationError
class Rules:
def __init__(self):
self._classification_rules = {}
self._exclusion_rules = {}
self._enrichment_rules = {}
self._routing_rules = {}
self._config ... |
from os import path
import requests
import time
from .HTMLparsers import getSchiHubPDF, SciHubUrls
import random
from .NetInfo import NetInfo
def setSciHubUrl():
r = requests.get(NetInfo.SciHub_URLs_repo, headers=NetInfo.HEADERS)
links = SciHubUrls(r.text)
found = False
for l in links:
try:
... |
from ..ConstrainedSketchBase import ConstrainedSketchBase
class ConstrainedSketchParameterModel(ConstrainedSketchBase):
"""A ConstrainedSketch object contains the entities that are used to create a sketch. The
objects include ConstrainedSketchGeometry objects contained in the ConstrainedSketchGeometry Reposit... |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
image = mpimg.imread('exit-ramp.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Define a kernel size for Gaussian smoothing / blurring
# Note: this step is optional as cv2.Canny() applies a 5x5 Gaussian internall... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for filter commands """
from asyncio import sleep
from re import fullmatch, IGNORECASE, escape
from... |
'''
Generate signal-response reprogramming input-output examples
'''
import argparse
def main():
parser = argparse.ArgumentParser(description="Generate input/output examples for the contextual-signal problem.")
parser.add_argument("--signals", type=int, help="How many input signal types are there?")
args ... |
# proxy module
from __future__ import absolute_import
from etsdevtools.developer.features.dock_control_feature import *
|
import numpy as np
def test_exercise_2_I(read_products):
products_data = read_products("products.csv")
assert len(products_data) == 13
assert "Iogurt" in products_data
iogurt = products_data["Iogurt"]
assert iogurt["idx"] == 3
assert iogurt["category"] == "dairy"
np.testing... |
# Copyright (c) 2016 Will Thames <will@thames.id.au>
#
# 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, mer... |
from flask import request
from flask_restplus import Resource
from ..dto.user_dto import UserDto
from ..service.auth_service import Auth
from ..service.user_service import save_new_user, get_all_users, get_a_user, change_user_password, get_roles, update_user
api = UserDto.api
user = UserDto.user
user_roles = UserDto.... |
###########################################################################
#
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org... |
# Copyright 2019 The DMLab2D Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
from django.apps import AppConfig
class BodaJusticeConfig(AppConfig):
name = 'boda_justice'
|
from app.models import definitions
swagger_config = {
"headers": [
],
"specs": [
{
"endpoint": 'swagger',
"route": '/swagger.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_ur... |
from datasets import fashion200k
from datasets import fashion_iq
from datasets import shoes
from datasets import vocabulary
import numpy as np
import tensorflow as tf
# python read_glove.py --dataset='fashion_iq' --data_path='datasets/fashion_iq/image_data'
# python read_glove.py --dataset='shoes' --data_path=''
# py... |
#!/usr/bin/python
import sys
import os
if __name__ == "__main__":
maker_executable = os.getenv("MAKER_EXECUTABLE")
if maker_executable:
from pip._vendor.distlib.scripts import ScriptMaker
ScriptMaker.executable = maker_executable
from pip._internal.cli.main import main
sys.exit(main())... |
"""Find the maximum intraday price impact during each month,
and calculate monthly average price impacts.
"""
import time
import pandas as pd
import jdatetime
for file_number in range(1, 76):
start = time.time()
# Read price impact data sets
spread_file_path = f'C:/Users/behnood/Desktop/'\
... |
import argparse
import time
arg_parser = argparse.ArgumentParser(description="")
arg_parser.add_argument("--benchmark_file", type=str, default="bench.txt")
arg_parser.add_argument("--program", type=str, default="vertex_cover_original")
args = arg_parser.parse_args()
host_cnt = 0
def load_config():
fin = open("hos... |
import os
import json
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import pickle
import numba
from run_script import data_prep
from sklearn.svm import SVC, LinearSVC
from sklearn.model_selection import StratifiedKFold, LeaveOneOut
from sklearn.neighbors import KNeighborsClassifier, Nea... |
"""
Get current version, status, and useful initialization info of the supported
network(s).
"""
from textwrap import indent
from typing import Any, Dict, List, Optional, NamedTuple
import requests
from .models import (
MetadataRequest,
NetworkIdentifier,
NetworkRequest,
NetworkOptionsResponse,
Ne... |
from unsupervised_learning.clustering.dbscan import DBScan
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import numpy as np
def main():
X, y = make_blobs(n_samples=100, cluster_std =2, random_state=42)
model = DBScan(min_samples = 5, eps= 2)
model.fit(X)
core_mask = np.zero... |
#!/usr/local/bin/python
import json
import glob
import os
f = open('unicode2gardiner.json', 'r')
data = json.load(f)
for k, v in data.items():
file_to_rename = glob.glob('svg/u{}_NotoSansEgyptianHieroglyphs.svg'.format(k))
new_filename = 'svg/{}.svg'.format(v.lower())
if len(file_to_rename):
pr... |
from abc import ABC, abstractmethod
class Model(ABC):
def __init__(self):
self.is_fited = False
@abstractmethod
def fit(self, dataset):
raise NotImplementedError
@abstractmethod
def predict(self, x):
raise NotImplementedError
def cost(self):
raise NotImplemen... |
from transformers import Wav2Vec2CTCTokenizer
from transformers import Wav2Vec2FeatureExtractor
from transformers import Wav2Vec2Processor
def createTokenizer():
model_name_or_path = "m3hrdadfi/wav2vec2-large-xlsr-persian-v2"
tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(model_name_or_path)
return token... |
from selenium import webdriver
import time
import random
browser = webdriver.Firefox()
name_list = open("male.txt", "r")
name = name_list.read()
name = name.split()
browser.get('file:///home/arjun/Desktop/Workshop/index.html')
elem = browser.find_element_by_id('inputName')
elem2 = browser.find_element_by_id('inputEma... |
import pandas as pd
import matplotlib.pyplot as plt
import errno
import os
from pathlib import Path
import data_helper as dh
if __name__=='__main__':
# Create path to experiments directory
experiments_path = Path(Path().cwd().parents[0] / 'experiments')
# Loop through all training directories
for tra... |
# Generated by Django 2.2 on 2020-12-18 13:54
from django.db import migrations, models
import users.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('... |
"""
Desafio 026
Problema: Faça um programa que leia uma frase pelo teclado
e mostre quantas vezes aparece a letra "A", em que
posição ela aparece a primeira vez e em que posição
ela aparece a última vez."""
# Solicitando uma frase
f = str(
input('Digite uma frase:')).strip().lower().re... |
#!/usr/bin/env python3
""" Import comunity modules. """
import os
import sys
import jinja2
import re
HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, f"{HERE}")
def string_is_latest_or_version(check_string):
prog = re.compile("^(\d+\.)?(\d+\.)?(\*|\d+)$")
result = prog.match(check_stri... |
import tensorflow as tf
from keras.layers import Dense, Input, Conv1D, MaxPooling1D, LSTM, Flatten, Dropout
from keras.models import Model
from keras.optimizers import Adam, RMSprop
from keras import backend as K
#------------------------------------------------------------------
import threading
import datetime
from c... |
from domain.ErrorTypes import ErrorTypes
from validity import IncomingEdgeValidityChecker, DataSourceValidityChecker
from utils import CodeGenerationUtils
import os
def generate_code(args):
node = args["node"]
requireds_info = args["requireds_info"]
edges = args["edges"]
checklist={"df_count": {0}, "... |
# coding=utf-8
# Copyright (c) 2015 EMC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... |
import os
import sys
from io import StringIO
from types import SimpleNamespace
from urllib.parse import urlparse
import django
from django.conf import settings
from django.core.management import call_command
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
location = urlparse('...')
engine = {
# 'sqlite3': 'dja... |
from quick_sort import __version__
from quick_sort.quick_sort import QuickSort
def test_version():
assert __version__ == '0.1.0'
def test_reverse_sorted():
arr = [5,12,7,5,5,7]
left = 0
right = len(arr) - 1
QuickSort(arr, left, right)
assert arr == [5, 5, 5, 7, 7, 12]
def test_few_uniques(... |
from urllib.parse import urlparse
import boto3
from boto3_type_annotations import s3
from botocore.paginate import PageIterator
from typing import Iterator, Optional
from sorted.sorted import Sorted
from platonic import Iterable
def is_not_a_directory(url: str):
return not url.endswith('/')
class S3RecursiveK... |
import numpy as np
import os
import tensorflow as tf
from rllab.misc.overrides import overrides
from sandbox.rocky.tf.algos.trpo import TRPO
import hgail.misc.utils
class GAIL(TRPO):
"""
Generative Adversarial Imitation Learning
"""
def __init__(
self,
critic=None,
... |
from ...expressions import Symbol, Constant
from .chart_parser import (
Grammar,
DictLexicon,
Rule,
RootRule,
Quote,
CODE_QUOTE,
STRING_QUOTE,
)
S = Symbol("S")
SL = Symbol("SL")
NP = Symbol("NP")
PN = Symbol("PN")
VP = Symbol("VP")
V = Symbol("V")
DET = Symbol("DET")
N = Symbol("N")
PRO =... |
import argparse
import requests
import os
import sys
from pathlib import PurePath
sys.path.insert(1, str(PurePath(os.getenv('VIRTUAL_ENV') + '/../')))
from src.elastic.elastic import Elastic
from src.elastic.elastic_indices import get_factor_recommendation_index_id, get_statement_recommendation_index_id
def health_... |
#
# cs1media.py
#
# Environment for manipulating Images
#
# 2010/03/24 Otfried Cheong
# 2010/09/02: Convert image to RGB on loading
#
# Inspired and using some code from picture.py by Mark Guzdial.
#
# On Linux, need packages python-tk, python-imaging-tk
#
import sys as _sys
import PIL.Image as _Image
import PIL.Imag... |
from django.conf.urls import patterns, include, url
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
direct_to_template, {'template': 'index.html'},
name='index',
),
url(r'^submissao/', inclu... |
from setuptools import setup, find_packages
setup(
name='snipsowm',
version='0.2.1',
description='OpenWeatherMap weather skill for Snips',
author='Michael Fester',
author_email='michael.fester@gmail.com',
url='https://github.com/snipsco/snips-skill-owm',
download_url='',
license='MIT',
... |
from django.db import models
from django.db.models.deletion import CASCADE
from django.utils import timezone
from twitteruser.models import Uzer
# Create your models here.
class Tweets(models.Model):
tweet = models.TextField(max_length=140)
user = models.ForeignKey(Uzer, on_delete=CASCADE)
time_posted = ... |
#!/usr/bin/env python3
# mc_poly_lj_module.py
#------------------------------------------------------------------------------------------------#
# This software was written in 2016/17 #
# by Michael P. Allen <m.p.allen@warwick.ac.uk>/<m.p.allen@bristol.ac.uk> ... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from apps.index.models import New
class User(AbstractUser):
"""自定义用户模型类"""
CHOICE = (
('1', '男'),
('2', '女')
)
mobile = models.CharField(max_length=11, unique=True, verbos... |
# -*- coding: utf-8 -*-
from numpy import array
def comp_height_opening(self, Ndisc=200):
"""Compute the height of the opening area (Hslot - Hactive)
Parameters
----------
self : Slot
A Slot object
Ndisc : int
Number of point to discretize the lines
Returns
-------
Hw... |
num1 = 3
num2 = 4
if num1<num2:
print("num1 is less than num2")
name="BIT is an intresting class"
if len("BIT") is in name:
print("the name is found")
nam=kato:
print |
#
# PySNMP MIB module BIANCA-BRICK-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-RADIUS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:38:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DATABASE = os.path.join(app.root_path, 'flaskr.db'),
SECRET_KEY = 'development key',
USERNAME = 'admin',
PASSWORD... |
import librosa
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def magnitude_db_and_phase_to_audio(frame_length, fft_hop_length, magnitude_db, phase):
amplitude = librosa.db_to_amplitude(magnitude_db, ref=1.0)
return... |
import sys
import pytest
@pytest.mark.skipif(
sys.version_info < (3, 4),
reason="requires python3.4+")
def test_aio_compat():
""" can patch old asyncios """
import asyncio
import mytb.aio.compat
mytb.aio.compat.patch()
assert asyncio.run
assert asyncio.all_tasks
patched = mytb.... |
msg_size = 1000
|
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
if __name__ == '__main__':
s = input()
plus = s.count('+')
minus = s.count('-') * -1
print(plus + minus)
|
'''Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de
Futebol, na ordem de colocação. Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time da Chapecoense.'''
times = ('Palmeiras', 'Atlético - MG', 'Forta... |
# Import
from and_gate import AND
from or_gate import OR
from nand_gate import NAND
# Global Variables
samples = [(0,0), (1,0), (0,1), (1,1)]
# Classes
# Functions
def XOR(x1, x2): # multi-layer perceptron
s1 = NAND(x1, x2) # layer 1
s2 = OR(x1, x2) # layer 1
y = AND(s1, s2) # layer 2
return y
def main():
f... |
import click
from hardware_usage_notifier.cli.options.option import Option
class ConfigFile(Option):
def __init__(self, config):
Option.__init__(self,
short_name='-c',
long_name='--config-file',
required=True,
... |
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import Client, TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from ...acl.useracl import get_user_acl
from ...conf.dynamicsettings import DynamicSettings
from ... |
#!/usr/bin/python3
from argparse import ArgumentParser
from os import system
from time import sleep
delay = 5
# Parses the input arguments.
parser = ArgumentParser(description="Generates the GoldenEye pcap file")
parser.add_argument("--app", default="goldeneye-post-2.1", help="the name of the application")
parser.add... |
# *- coding: utf-8 -*
from __future__ import absolute_import
from django.utils.translation import ugettext as _
import datetime, sys
from celery import shared_task
from django.db import transaction
from .models import ParcelForceImportJob, ParcelForceOrder
from .parcel_force import extract_order_info
@shared_task
def... |
# coding: utf-8
"""
Hydrogen Proton API
Financial engineering module of Hydrogen Atom # noqa: E501
OpenAPI spec version: 1.9.2
Contact: info@hydrogenplatform.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import... |
"""
Applies to many other data structures dictionaries and things like tuples and generators all of which we will see later.
Understanding these is imp.
Cool shorthand which allows us to make new lists that are direct copies of other lists or are tweaked version of source list.
Syntax : Syntax is bizzare but try ... |
from torch.nn.modules.sparse import Embedding
from tasks.add.env import AdditionEnv
from tasks.add.core import StateEncoder, program_embedding
import torch
from torch import optim, tensor
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules import activation
from tasks.add.config import config
im... |
import subprocess, time, sys, threading
import logging, logging.handlers
import mesh.generic.gpio as GPIO
#try: # This library only available on BBB
# import Adafruit_BBIO.GPIO as GPIO
#except ImportError:
# pass
def getTimeOffset(offsetType='standard'):
if offsetType == 'pps':
# Parse ntpq -p comma... |
import requests
import json
import datetime,os,sys
try:
url = "https://samples.openweathermap.org/data/2.5/forecast/hourly?q=London,us&appid=b6907d289e10d714a6e88b30761fae22"
response = requests.get(url = url)
print(response.status_code)
w_list = response.json()
#to check if response contains 4 days data = 4 days... |
# Copyright 2014 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 sys
import unittest
from telemetry.core import exceptions
from telemetry.unittest import gtest_progress_reporter
from telemetry.unittest import simpl... |
from unittest import mock
import pytest
from atlas.modules.resource_data_generator.generators import (
exceptions,
ProfileResourceDataGenerator,
resource_constants as constants,
settings
)
class TestProfileResourceDataGenerator:
"""
Test normal working of Profile Resource Generator
"""
... |
ERROR_PLATFORM_NOT_SUPPORTED = '''
Platform not supported.
If you are using Alexa, you must pass the request trough the Alexa Skills Kit.
If you are using Google Assistant you must use an API gateway and create a route named /googleAssistantDialogflowV1
If you are using Bixby you must use an API gateway and create a ro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Pierre Schönbeck'
class Player:
def __init__(self, name, uid, isMod = False):
self.uid = uid
self.name = name
self.isMod = isMod
def __repr__(self):
return "%s : %s : %s" % (self.name, self.uid, self.isMod) |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#! /usr/bin/python
import argparse
import bibtexparser
from bibtexparser.bwriter import BibTexWriter
from bibtexparser.bparser import BibTexParser
from pathlib import Path
from io import StringIO
from sys import stderr
def load_uniq(fn):
with Path(fn).open() as f:
parser = BibTexParser()
parser.i... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
""" Code Wars Exercises
.. moduleauthor:: Timothy Helton <timothy.j.helton@gmail.com>
"""
from collections import defaultdict
from itertools import chain, zip_longest
from operator import add
import string
from typing import Dict, List, Union
import numpy as np
def al... |
import math, re
#from vincenty import vincenty
def get_number_of_stations(filename):
f = open(filename)
lines = f.readlines()
f.close()
return len(lines)
def read_table(jbtab):
#open time table
f = open(jbtab)
#store all lines in file (for processing)
lines = []
for line in f:
line = ... |
# from system
import logging, time
# from pylons
from pylons import request, url, session as web_session, tmpl_context as c
from pylons.controllers.util import abort, redirect
from routes import url_for
from kascfg.lib.base import BaseController, render
from kascfg.lib.config import load_master_config, save_master_con... |
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2020
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular software products
# made up of hu... |
#-*-coding:utf8;-*-
import os
import sys
import time
#Internal memory size definition
MEMSIZE = 30000
#This class provides internal memory access
class Memory:
def __init__(self):
#internal pointer
self.ptr = 0
#internal memory
self.stk = [0] * MEMSIZE
def increase(self):... |
# -*- coding: utf-8 -*-
from typing import Optional
from pydantic import BaseModel
from pydantic import EmailStr, UrlStr
from .misc import ObjectIdStr
from .dbmodel import DBModelMixin
from .rwmodel import RWModel
class UserBase(RWModel):
username: str
email: EmailStr
name: Optional[str] = None
bio:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.