text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
"""
ParseScrapeGenerate. Parse, scrape, and generate feeds.
Usage: parsescrapegenerate <config_path>
Arguments:
config_path Path to a feed config file
Options:
-h --help Show help
--version Show version
Once invoked, parsescrapegenerate will load config_path, scrape the g... |
from typing import Iterator
from .base import Fork
from .byzantium import Byzantium
from .constantinople import Constantinople
from .frontier import Frontier
from .homestead import Homestead
from .istanbul import Istanbul
from .muir_glacier import MuirGlacier
from .petersburg import Petersburg
from .spurious_dragon im... |
import collections
import operator
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.tests.extension import base
from .array import JSONArray, JSONDtype, make_data
@pytest.fixture
def dtype():
return JSONDtype()
@pytest.fixture
def data():
"""Length-100 PeriodArray for semantics ... |
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'nest_el',
'type': 'static_library',
'sources': [ '../file.c', ],
'postbuilds': [
{
... |
import json
from django.contrib.contenttypes.models import ContentType
from flag.exceptions import FlagBadRequest
class ContentTypeMixin:
def dispatch(self, request, *args, **kwargs):
try:
data = json.loads(request.body.decode('utf-8'))
except json.decoder.JSONDecodeError:
... |
"""api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
# Copyright 2018 Datawire. 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 required by applicable law or agr... |
import re
try:
from Config import config
from Logger import logger
loggerError = logger.error
REQUIREMENTS = config.path + config.Depend.path + config.Depend.file
except:
import os
loggerError = print
REQUIREMENTS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/requirement... |
from abc import ABC, abstractmethod
from functools import lru_cache
import numpy as np
from vispy.app import Canvas
from vispy.gloo import gl
from vispy.visuals.transforms import STTransform
class VispyBaseLayer(ABC):
"""Base object for individual layer views
Meant to be subclassed.
Parameters
-----... |
"""
Used from https://github.com/orcasgit/python-fitbit
"""
#!/usr/bin/env python
import cherrypy
import sys
import threading
import traceback
import webbrowser
from base64 import b64encode
from fitbit.api import Fitbit
from oauthlib.oauth2.rfc6749.errors import MismatchingStateError, MissingTokenError
port = 8088
... |
import os,sys,time,re,fnmatch
import numpy as np
import ase.units as au
def timer(start,end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print(("Time elapsed: {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds)))
return
def cmdout(cmd):
return os.popen(cmd... |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
impor... |
import abc
from robot.libraries.BuiltIn import BuiltIn
from cumulusci.utils.classutils import get_all_subclasses
"""
FIXME: Something that still needs to be resolved is what to do about
name clashes. What if a project imports two different libraries and
each library implements a handler for the same tag and/or a handl... |
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.forms import ModelForm, modelformset_factory
from django.forms.models import BaseModelFormSet
class BaseGenericInlineFormSet(BaseModelFormSet):
"""
A formset for generic inline objects to a parent.
... |
from module.Configuration import Configuration
from dask.distributed import Client
import logging
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import pandas as pd
from module.Evaluation import Evaluation
# from module.Cluster import Cluster
def main():
c = Client()
... |
class NetworkError(Exception):
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
|
# pylint: disable=no-self-use,unsubscriptable-object
import re
from uuid import uuid4
import pytest
from pyramid.testing import DummyRequest
from .test_treegroup import TestTreeGroup
@pytest.fixture(scope="function")
@pytest.mark.usefixtures("dbsession", "transact")
def oauth2_clients_test_data(dbsession, transact... |
# Generated by Django 2.1.5 on 2019-04-21 08:34
from django.db import migrations
from django.db.models import Q
def year_of_birth_to_four_digits(apps, schema_editor):
Athlete = apps.get_model('rankings', 'Athlete')
current_year = 19
for athlete in Athlete.objects.filter(~Q(year_of_birth=None)):
... |
from random import randint
import pytest
from round_robin_generator.matchup_generation_circle import apply_offset
@pytest.mark.parametrize(
"p,expected", [(2, 7), (3, 8), (4, 2), (5, 3), (6, 4), (7, 5), (8, 6)]
)
def test_apply_offset(p, expected):
assert apply_offset(p, 8, 2) == expected
@pytest.mark.par... |
from flask import (
Blueprint, request, jsonify
)
from .api_code import code_get_msg, return_encode
from .api_auth import role_required
from core.user import RegisterUser
from core.error import ArcError, PostError
from server.sql import Connect
from server.sql import Sql
import time
import web.webscore
import serv... |
import pywt as pw
def execute(context):
if not context.data is None:
context.cA6, context.cD5, context.cD4, context.cD3, context.cD2, context.cD1 = pw.wavedec(context.data, 'db5', level=5)
context.prev = __name__ |
"""login URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... |
#!/usr/bin/env python
"""
This is a small demo, showing how to make an object that can be moved around.
"""
import wx
#ver = 'local'
ver = 'installed'
if ver == 'installed': ## import the installed version
from wx.lib.floatcanvas import NavCanvas, Resources
from wx.lib.floatcanvas import FloatCanvas as FC
... |
import os
import graphene
import confhttpproxy
from gtmcore.configuration import get_docker_client
from gtmcore.imagebuilder import ImageBuilder
from gtmcore.dispatcher import Dispatcher, jobs
from gtmcore.inventory.inventory import InventoryManager
from gtmcore.container.container import ContainerOperations
from gtm... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttentionLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
sel... |
# -*- coding: utf-8 -*-
import scipy as sp
from pylufia.signal.spectral import *
def _make_bark_filterbank(fs, framesize):
"""
Calculate Bark-band filterbank
"""
f_centers = sp.array([50,150,250,350,450,570,700,840,1000,1170,1370,1600,1850,2150,2500,2900,3400,4000,4800,5800,7000,8500,10500,13500])
... |
#!/usr/bin/env python3
import argparse
import sys
import os
import subprocess
import re
import shutil
import multiprocessing as mp
from functools import partial
def UniqueQuartet(q):
if q[0] < q[1]:
return False
if q[2] < q[3]:
return False
#if ( q[0] + q[1] ) < ( q[2] + q[3] ):
# return False
... |
import pytest
from graphene import Node
from saleor.checkout import calculations
from saleor.checkout.models import Checkout
from ..utils import get_graphql_content
FRAGMENT_PRICE = """
fragment Price on TaxedMoney {
gross {
amount
currency
}
net {
amount
currenc... |
# Copyright 2015 The TensorFlow Authors. 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 required by applica... |
# -*- coding: utf-8 -*-
#
# gs.core documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 29 09:00:52 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... |
# vim:ts=4:sw=4:et:
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# no unicode literals
from __future__ import absolute_import, division, print_function
import os
import pywatchman
imp... |
import asyncio
import uvloop
from secret_sdk.client.localsecret import AsyncLocalSecret
async def with_sem(aw, sem):
async with sem:
print(sem)
return await aw
async def main():
async with AsyncLocalSecret(chain_id="pulsar-2") as secret:
validators = await secret.staking.validators... |
#!/usr/bin/env python3
# Oneplus Decrypter (c) V 1.4 B.Kerler 2019-2021
# Licensed under MIT License
"""
Usage:
opscrypto.py --help
opscrypto.py encryptfile <filename>
opscrypto.py decryptfile <filename>
opscrypto.py decrypt <filename>
opscrypto.py encrypt <directory> [--projid=value] [--firmwaren... |
from random import randint
import torch
import torch.nn as nn
import torch.nn.functional as f
import math
from extra_utils import get_padding_period, get_padding
from src.meldataset import mel_spectrogram
class Conv1dRechanneled(nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, st... |
# Copyright 2021 The Flax 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 wri... |
from abc import ABC, abstractmethod
from typing import Any, OrderedDict, Union, Dict, List
import numpy as np
import inspect
class LatteMetric(ABC):
def __init__(self):
self._buffers = OrderedDict()
self._defaults = OrderedDict()
def add_state(self, name: str, default: Union[list, np.ndarray... |
#!/usr/bin/env python3
import asyncio
from mavsdk import System
async def run():
drone = System(mavsdk_server_address='localhost', port=50051)
await drone.connect(system_address="serial:///dev/ttymxc2:921600")
print("Waiting for drone to connect...")
async for state in drone.core.connection_state()... |
# coding: utf-8
# Author: Leo BRUNEL
# Contact: contact@leobrunel.com
# This file is part of Wizard
# MIT License
# Copyright (c) 2021 Leo brunel
# 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 So... |
from django import forms
from main.models import a03Estados, a04Municipios, a05Bairros, a06Lograds, a10CatsInsumos, b01Empresas
class formCadastrarEmpresa(forms.Form):
juridica = forms.BooleanField(required=False)
razao = forms.CharField(max_length=255)
fantasia = forms.CharField(max_length=255)
codi... |
def tam(frs):
if len(frs) < 10:
return str(len(frs))
else:
return str(10)
frase_1 = input()
frase_2 = input()
frase_3 = input()
frStp_1 = frase_1.strip()
frStp_2 = frase_2.strip()
frStp_3 = frase_3.strip()
print('{}{}{}'.format(frStp_1, frStp_2, frStp_3))
print('{}{}{}'.format(frStp_2, frStp_3... |
#!/usr/bin/python3 -i
#
# Copyright (c) 2019-2020 Valve Corporation
# Copyright (c) 2019-2020 LunarG, 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/licens... |
from unittest import mock
from django.contrib.contenttypes.models import ContentType
from django.core import serializers
from django.core.exceptions import ValidationError
from django.db import IntegrityError, connection, models
from django.test import RequestFactory, SimpleTestCase, TestCase
from django.test.utils im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_also_strings(self):
string =... |
#!/usr/bin/env python3
import json
import locale
import sys
# import emails
import os
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, letter
def load_data(filename):
"""Loads the contents of filename as a JSON file."""
with open(filename) as json_file:
data = json.load(json_file)
... |
"""
ALGORITHM
If list is empty return None
Check element in the middle of the list
if element is target element return element position
if element is larger than the element we are looking for
perform a binary search on the first half
if element is smaller than the element we are looking for
... |
from __future__ import absolute_import
from .cnn import extract_cnn_feature
from .cnn import extract_part_feature
from .database import FeatureDatabase
__all__ = [
'extract_cnn_feature',
'FeatureDatabase',
'extract_part_feature'
]
|
import sys
import cv2
import time
import datetime
import threading
from PyQt5 import uic
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
class MainWindow(QMainWindow):
global frame
global faces
global smiles
d... |
from flask import Flask, request, jsonify, current_app, render_template
from .process_data import *
from .models import *
from .user import user
from .book import book
from .rent import rent
import logging
logging.basicConfig(level=logging.INFO)
def create_app():
app = Flask(__name__)
app.register_blueprint... |
import numpy as np
import numba
from numba import njit, jitclass, float64, bool_, int64
# Need to specify types for numba's @jitclass
spec = [
('representation', bool_[:, :]),
('lowest_free_rows', int64[:]),
('changed_lines', int64[:]),
('pieces_per_changed_row', int64[:]),
('landing_height_bonus'... |
class Product(object):
def __init__(self,item_name,price, weight,brand):
self.item_name = item_name
self.price = price
self.weight = weight
self.brand = brand
self.status = "for sale"
def sell(self):
self.status = "sold"
return self
def add_tax(self,... |
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
import pyspark.sql as sql
from pyspark.sql.functions import *
from pyspark.sql.types import *
from collections import defaultdict
from pyspark.sql import functions as F
NUMBER_PRECISION = 2
def addSampleLabel(ratingSamples):
ratingS... |
import requests
# http://host:port/context/rest/api-name/api-version/path/to/resource
username = input("Please enter your admin username: ")
password = input("Please enter your admin password: ")
jira_url = "http://localhost:8080/JIRA/rest/api/2/project"
bitbucket_url = "http://localhost:7990/Bitbucket/rest/api/1.0/... |
from .srec_view import SRECView
from .ihex_view import IHexView
from .ti_txt_view import TiTxtView
SRECView.register()
IHexView.register()
TiTxtView.register() |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Joy
from std_msgs.msg import UInt8, Int16, Char, Bool
class ArmControlLogic:
roll_threshold = 0.4
tilt_threshold = 0.1
spin_threshold = 0.1
gripper_threshold = 0.5
open_command = chr(43)
close_command = chr(45)
def __init__(s... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
import json
from ccxt.base.errors import ExchangeError
from ccxt.base.err... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from Journal.auth_accounts.models import Profile
from Journal.web_posts.models import Post
UserModel = get_user_model()
class TestProfileDetails(TestCase):
VALID_USER_DATA = {
'email': 'kolev7... |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
from urllib.parse import urlparse
from urllib.request import urlopen, Request
import urllib
import bs4
import requests
import html5lib
def weather_search(area):
input_area = area
enc_area = urllib.parse.quote(input_area+'날씨')
url = 'https://search.naver.com/search.naver?ie=utf8&query='+enc_ar... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
#import json
from scrapy.exceptions import DropItem
class WriterPipeline(object):
def open_spider(self, spider):
... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
UserBio = models.TextField(max_length=100)
ProfileImage = models.ImageField(upload_to='ProfilePics', blank=True)... |
from pathlib import Path
from typing import List
import pytest
from jina import Document, DocumentArray, Executor
from sentence_encoder import TransformerSentenceEncoder
_EMBEDDING_DIM = 384
@pytest.fixture(scope='session')
def basic_encoder() -> TransformerSentenceEncoder:
return TransformerSentenceEncoder()
... |
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation
test with: resilient-circuits selftest -l fn_outbound_email
"""
import smtplib
import logging
from resilient_lib.components.resilient_common import valida... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from spark_auto_mapper_fhir.fhir_types.boolean import FhirBoolean
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_ba... |
"""
distributional_nbd.py
------
Distributional Non-backtracking Spectral Distance.
"""
import numpy as np
import networkx as nx
import scipy.sparse as sp
from scipy.spatial.distance import euclidean, chebyshev
from ..utilities.graph import unweighted
from .base import BaseDistance
class DistributionalNBD(BaseDis... |
import os
import socket
import struct
import yaml
from subprocess import (
check_call,
check_output,
)
import netifaces
from charmhelpers.core.hookenv import (
config,
log,
in_relation_hook,
status_set,
unit_get,
related_units,
relation_ids,
relation_get,
relation_set,
WA... |
from datetime import datetime, date, timedelta
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
fr... |
import typing
import mesh_tensorflow as mtf
import tensorflow as tf
from .activation import activate
from .backend import linear, linear_from_features, linear_to_features
from .basic import activated_linear
from .embedding import embed, gather_embed, Gather
from .frontend import block_part_fn
from .momentumnet import... |
import os
import math
from PIL import Image
import requests
from io import BytesIO
from torchvision import transforms, utils
class DataLoader():
def __init__(self):
pass
def load(self, url, size):
try:
response = requests.get(url)
img = Image.open(BytesIO(resp... |
#!/usr/bin/python
'''
(C) Copyright 2018-2019 Intel Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... |
# The model produced by the flowobjspace
# this is to be used by the translator mainly.
#
# the below object/attribute model evolved from
# a discussion in Berlin, 4th of october 2003
import py
from pypy.tool.uid import uid, Hashable
from pypy.tool.descriptor import roproperty
from pypy.tool.sourcetools import PY_IDEN... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, laugusto and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class OrdemServicoInterna(Document):
pass
|
config = {
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PostgreSQL Database
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# PostgreSQL is used as the database to store data such as candles.
# # # # # # # # # # # # # # # # # # # # # # # # # # #... |
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... |
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; -*-
"""Module providing class for judges classification.
Attributes:
Judge (class):
class for merging judgments of different classifiers
"""
##################################################################
# Imports
from __future__ import absolute_import,... |
""" Video Dataset """
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
import os
from typing import List
from fractions import Fraction
from PIL import Image
import torchvision
from torchvision import datasets
from torchvision import io
try:
import av
AV_AVAILABLE = True
except Im... |
from .models import Shop
import logging
import requests
import time
logger = logging.getLogger('storelocator')
def update_shops():
limit = 2500
for shop in Shop.objects.filter(latitude=None, longitude=None)[:limit]:
location = "%s %s %s" % (shop.city, shop.postalcode, shop.street)
try:
... |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from vvpages.views import PageRestView, SitemapRestView, PageWizardView, AddPagePostView
urlpatterns = [
#url(r'^map/$', SitemapView.as_view(), name="vvpages-map"),
url(r'^sitemaprest/$', SitemapRestView.as_view(), name="vvpages-map-rest"),
url(r'^... |
# -*- coding: utf-8 -*-
import urllib2
import re
from bs4 import BeautifulSoup
from src.tools.match import Match
SinaBlog_author_id = 1287694611
href_article_list = 'http://blog.sina.com.cn/s/articlelist_{}_0_1.html'.format(SinaBlog_author_id)
href_index = 'http://blog.sina.com.cn/u/{}'.format(SinaBlog_author_id)
hr... |
# 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
# "License"); you may not u... |
from django.contrib.auth.models import User
from django.test import TestCase
from ...models import Profile
class TestProfileModel(TestCase):
def setUp(self):
self.user_test = User.objects.create(username='borko')
def test_create_profile(self):
pr = Profile.objects.create(user=self.user_test,... |
"""Activations for TensorFlow.
Parag K. Mital, Jan 2016."""
import tensorflow as tf
def lrelu(x, leak=0.2, name="lrelu"):
"""Leaky rectifier.
Parameters
----------
x : Tensor
The tensor to apply the nonlinearity to.
leak : float, optional
Leakage parameter.
name : str, optiona... |
from core.agent.rnd_ppo import RND_PPO
from .utils import check_interact, check_save_load, check_sync_in_out
def test_discrete_rnd_ppo(MockEnv):
state_size, action_size, action_type = 2, 3, "discrete"
episode_len = 10
env = MockEnv(state_size, action_size, action_type, episode_len)
hidden_size, batch... |
import cv2
import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as layers
from data_generator import DataGenerator
base_directory = './'
# function used to read video data and save normal or transit blocks to folder
def save_data(fromarray=transcriptions, he... |
from django.conf.urls import url
from django.urls import path
from .views import challenges, flagsubmit, completed
from django.conf import settings
from django.conf.urls.static import static
from django.views.static import serve
from django.conf.urls import url
urlpatterns = [
# path('', challenges, name='challeng... |
# Generated by Django 3.1.4 on 2020-12-25 22:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0011_auto_20200410_2229'),
]
operations = [
migrations.AlterField(
model_name='user',
name='first_name',
... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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 t... |
from unittest import TestCase, mock
from pycmakeserver.protocol import CmakeProtocol
import json
class CmakeProtocolTest(TestCase):
def setUp(self):
self.handler = mock.Mock(['handle', 'connection_lost'])
self.proto = CmakeProtocol(self.handler)
self.hello = b'''\n[== "CMake Server" ==[\n
... |
import comp_dataset
import preproc
import feature_extraction
import experiment1
import experiment2
import experiment3
import experiment4
build_dataset.main()
preprocessing.main()
feature_extraction.main()
experiment1.main()
experiment2.main()
experiment3.main()
experiment4.main() |
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations
from collections import namedtuple
def electric_power(voltage: float, current: float, power: float) -> tuple:
"""
This function can calculate any one of the three (voltage, current, power),
fundamental value of e... |
""" Grid Search for Hyperparameters """
import pandas as pd
import matplotlib.pyplot as plt
# https://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Wisconsin+(Diagnostic)
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import roc_auc_s... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(label="ایمیل")
class Meta:
model = User
fields = ['username', 'email', 'pa... |
from flask import request
from flask_restful import Resource
from helpers.decorator import validate_schema, permission_required
from managers.auth import auth
from managers.document_managers import DocumentManaagers
from models import UserType
from schemas.request.doc_request import DocRequest
class DocumentResourse... |
import mock
import unittest
from xlcalculator.xlfunctions import (
xl,
xlerrors,
func_xltypes,
date,
financial
)
class FinancialModuleTest(unittest.TestCase):
def test_IRR(self):
self.assertAlmostEqual(
financial.IRR(
func_xltypes.Array([[-100, 39, 59, 55,... |
# Copyright 2017-2021 R.A. Stern
#
# 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, ... |
"""
.. currentmodule:: modlit.types
.. moduleauthor:: Pat Daburu <pat@dabru.net>
This module contains custom GeoAlchemy/SQLAlchemy types.
"""
# pylint: skip-file
from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID
import uuid
class GUID(TypeDecorator):
"""
This i... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'pt-br',
'!langname!': 'Português (do Brasil)',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de u... |
from typing import Dict, Tuple
from rsocket.frame_helpers import parse_type, serialize_128max_value
from rsocket.helpers import serialize_well_known_encoding
from rsocket_broker.well_known_keys import WellKnownKeys
def parse_key_value_map(buffer: bytes, offset: int) -> Tuple[Dict[bytes, bytes], int]:
key_value_... |
import tensorflow as tf
import numpy as np
from tensorflow.python.layers import core as layers_core
from baseline.utils import lookup_sentence, beam_multinomial
import os
def _find_files_by_type(model_file, filetype):
"""Find all files by type, removing suffix
we rely on the fact that vocab files end in .voc... |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
from parser.utils import get_metadata
def test_get_metadata(response):
expected = "\nFetched 9414 results in Achat > Paris > Appartement."
expected += "\n\t- commodites: balcon"
expected += "\n\t- situation: belleVue, sansVisAVis"
expected += "\n\t- budget: [300000, 700000]"
expected += "\n\t- sur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.