content stringlengths 5 1.05M |
|---|
# Copyright 2017 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... |
"""empty message
Revision ID: d371705de5f2
Revises: 94d2c442fe79
Create Date: 2017-10-01 13:23:19.220477
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd371705de5f2'
down_revision = '94d2c442fe79'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import random
for i in range(20):
print('%05.4f' % random.random(), end=' ')
print()
random.seed(1)
for i in range(20):
print('%05.4f' % random.random(), end=' ')
print()
for i in range(20):
print('%6.4f' %random.uniform(1, 100), end=' ')
print()
for i in range(20):
print(random.... |
from project.hardware.hardware import Hardware
class HeavyHardware(Hardware):
def __init__(self, name: str, capacity: int, memory):
Hardware.__init__(self, name, "Heavy", capacity * 2, memory * 0.75)
|
#Un mago junior ha elegido un número secreto.
#Lo ha escondido en una variable llamada "númeroSecreto".
#Quiere que todos los que ejecutan su programa jueguen el juego Adivina el número secreto,
#y adivinar qué número ha elegido para ellos.
#¡Quienes no adivinen el número quedarán atrapados en un ciclo sin fin para sie... |
import numpy as np
import numba as nb
from .matrices import dict_from_matrix, parasail_aa_alphabet, identity_nb_distance_matrix, tcr_nb_distance_matrix
__all__ = ['nb_running_editdistance',
'nb_running_tcrdist']
"""TODO:
- The way that nndist and neighbors is dynamically expanded when it gets full
is n... |
#!/usr/bin/env python
import os
import sys
import click
from credstash import getSecret, listSecrets
from jinja2 import Environment, FileSystemLoader
def render_with_credentials(file):
"""Render file argument with credstash credentials
Load file as jinja2 template and render it with context where keys are
... |
import datetime
from tkinter import *
from tkinter import ttk
import bq_method
from dateutil.relativedelta import relativedelta
setting = {}
ws = Tk()
ws.title("GUI data olap")
# ws.geometry('500x500')
ws["bg"] = "gray26"
def verify(bqjsonservicefile="polar.json", bqdataset="DB2019", bqtable="ozon_wb_1c"):
set... |
"""
"""
from typing import List, Dict
import time
import random
import requests
from requests_middleware.base import Base
class SmartRequests(Base):
SLEEP_TIME = 30
def __init__(self, proxies: List[Dict[str, str]], use_proxy: bool) -> None:
super().__init__(proxies=proxies)
self.use_proxy = ... |
import pygame
import math
import os
import palletts as p
import accessors as a
class text:
def __init__(self, color=-1, font=a.monoid, fontSize=10, text=-1):
self.color = color
self.font = self.return_font(font)
self.fontSize = fontSize
self.text = text
self.pare... |
import torch.nn as nn
import torch
class SelfTrainLoss(nn.Module):
def __init__(self):
super(SelfTrainLoss, self).__init__()
self.l1_loss = nn.L1Loss()
self.mse_loss = nn.MSELoss()
self.is_train = False
self.iteres = {
'self_supervised_common_mix': 0,
... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import sys
import threading
from ._types import str_cls, type_name
from .errors import LibraryNotFoundError
__version__ = '0.17.2'
__version_info__ = (0, 17, 2)
_backend_lock = threading.Lock()
_module_val... |
import asyncio
import random
import discord
import youtube_dl
from discord import Embed, Colour
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.utils.manage_commands import create_option, create_choice
class Music(commands.Cog):
def __init__(self, client):
"""Initia... |
# -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016 - Sequana Development Team
#
# File author(s):
# Thomas Cokelaer <thomas.cokelaer@pasteur.fr>
# Dimitri Desvillechabrol <dimitri.desvillechabrol@pasteur.fr>,
# <d.desvillechabrol@gmail.com>
#
# Distributed u... |
def save_model(model,nets):
for i in range(nets):
nome_file = str(i+1)+".h5"
model[i].save("../model/"+nome_file)
|
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
from flask import Flask, render_template, request, redirect, url_for, session
import pandas as pd
import time
import pymongo
def getCollectionObject(collectionName):
connection = pymongo.MongoClient("ds127044.mlab.com", 27044)
db = connection['adaptive_web']
status = db.authenticate(username, password)
... |
from django import forms
from core.models import Reserva, Quarto
class QuartoChangeForm(forms.ModelForm):
class Meta:
model = Quarto
fields = (
'name',
'endereco',
'tratar',
'telefone',
'description',
'imagem',
'c... |
# coding=utf-8
#
# Copyright © 2011-2015 Splunk, 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 ... |
#! /usr/bin/env python
import os, errno
import cv
import threading
import winsound
import shutil
from datetime import datetime
import Image
import ImageFont, ImageDraw, ImageOps
import strip_printer
# dependancies:
# python 2.7
# winsound(on windows), on linux change the playSound function to someth... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.test import TestCase
from django.core.urlresolvers import reverse
class CrumbsTest(TestCase):
def setUp(self):
self.view_url = reverse('test_view')
def test_crumbs(self):
response = self.client.get(self.view_url)
s... |
import os
from .base import SourceTestCase
HOST = os.environ.get('MYSQL_HOST', 'localhost')
USER = os.environ.get('MYSQL_USER', '')
PASSWORD = os.environ.get('MYSQL_PASSWORD', '')
class TestCase(SourceTestCase):
generator = 'mysql'
output_name = 'chinook_mysql.json'
def generate(self):
client =... |
import dectate
class App(dectate.App):
pass
class Other(dectate.App):
pass
class R:
pass
@App.directive("foo")
class FooAction(dectate.Action):
def __init__(self, name):
self.name = name
def identifier(self):
return self.name
def perform(self, obj):
pass
@Othe... |
from django.db import models
import datetime
from datetime import date
from django import forms
from django.db import models
from django.http import Http404, HttpResponse
from django.utils.dateformat import DateFormat
from django.utils.formats import date_format
import wagtail
from wagtail.admin.edit_handlers import... |
"""Unit tests for the OWASP Dependency Check Jenkins plugin source."""
from datetime import datetime
from tests.source_collectors.source_collector_test_case import SourceCollectorTestCase
from collector_utilities.functions import days_ago
class OWASPDependencyCheckJenkinsPluginTest(SourceCollectorTestCase):
""... |
import attach
import unittest
class TestKnowValues(unittest.TestCase):
list_of_test_foldernames = (
("hello", "hello_2"),
("hello2", "hello2_2"),
("hello545", "hello545_2"),
("hello904352", "hello904352_2"),
("hello1", "hello1_2"),
("hello53431", "hello53431_2"),
... |
from enum import Enum
class IndicatorType(Enum):
CLEAR_CONTEXT = 1
YES = 2
NO = 3
PLACES_NEARBY = 4
RELATIVE_LANDMARK = 5
EMPTY_AFTER_FILTERING = 6
INDICATORS = {
IndicatorType.CLEAR_CONTEXT:
set(['hm', 'hmm', 'hrm', 'oops', 'sorry', 'actually']),
IndicatorType.YES: {
... |
# write your code here |
# -*- coding: utf-8 -*-
from flask import json
from flask import request
from flask_api import status
from flask_restful import Resource
from app import token_auth, db
from app.models.capsule_model import is_capsule_open, get_capsules_by_id
from app.modules.capsule.serialize.capsule import serialize_capsule
from app.m... |
import os
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('/Users/zhancheng-ibm/anaconda2/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('/Users/zhancheng-ibm/anaconda2/share/OpenCV/haarcascades/haarcascade_eye.xml')
face_recognizer = cv2.face.creat... |
from .logic import AND, NOT, OR, Predicate
from .action import Action
from .utils import TextTree, TypeTree
import re
from .strips import Domain, KnowledgeState, Problem
supported_requirements = {":strips", ":typing", ":disjunctive-preconditions", ":negative-preconditions"}
def load_pddl(domain_file, problem_file):
... |
from libs.datasets import voc as voc
def get_train_dataset(CONFIG, p_split=None):
if CONFIG.DATASET == 'VOC2012' or CONFIG.DATASET=='VOC2012':
train_dataset = voc.VOC(
root=CONFIG.ROOT,
split='trainaug' if p_split is None else p_split ,
image_size=CONFI... |
from urllib.parse import urljoin
import requests
from crosswalk_client.exceptions import BadResponse
from crosswalk_client.objects.entity import EntityObject
from crosswalk_client.validators.entity import (
validate_block_attrs_kwarg,
validate_domain_kwarg,
)
class GetEntities(object):
@validate_block_a... |
"""
vocareum
python3 train.py
local
spark-submit train.py
"""
import json
import os
import platform
import re
import sys
import time
import numpy as np
from pyspark import SparkConf, SparkContext, StorageLevel
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
import support
system_type ... |
""" Exceptions used throughout this package """
class AuthRequiredError(Exception):
""" Error raised when authentication is required """
class InputRequiredError(Exception):
""" Error raised if input is required """
class InvalidComponentError(Exception):
""" Error raised if invalid component is provi... |
from app.utils.safe_dict import safeDict |
"""
## Classes that define the cross section of a pipe or duct.
"""
from typing import Optional, Type
import math
import quantities as qty
from pypeflow.core.pipe_schedules import PipeSchedule
class CrossSection:
"""
Base class from which different shapes of cross sections are derived.
"""
@property
... |
__author__ = 'mpetyx'
from django.contrib import admin
from .models import OpeniNutrition
class NutritionAdmin(admin.ModelAdmin):
pass
admin.site.register(OpeniNutrition, NutritionAdmin)
|
#!/usr/bin/env python3
# Copyright (c) 2015-2021 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
feature_llmq_rotation.py
Checks LLMQs Quorum Rotation
'''
from io import BytesIO
from test_framework.... |
import os
import keras
import tensorflow as tf
import numpy as np
from chord.chord_generator import ChordGenerator
from note.chord_to_note_generator import ChordToNoteGenerator
from keras import backend as K
import pandas as pd
from pandas import DataFrame
from tensorflow.contrib.tensorboard.plugins import projector
... |
from .core import KobotoolboxSeleniumMixin # noqa
|
# -*- coding: utf-8 -*-
import sys
import os
import yaml
from sqlalchemy import Table,literal_column,select
import csv
def importVolumes(connection,metadata,sourcePath):
invVolumes = Table('invVolumes',metadata)
invTypes = Table('invTypes',metadata)
with open(os.path.join(sourcePath,'invVolumes1.csv'), 'r... |
import logging
from datetime import datetime
import dask
import dask.dataframe as dd
import joblib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
logging.basicConfig()
logger = logging.getLogger("Helpers")
logger.setLevel(logging.DEBUG)
class Helpers:
# Returns log file data as a Datafra... |
# -*- coding: utf-8 -*-
'''
@Author : Xu
@Software: PyCharm
@File : tc_test.py
@Time : 2019-05-30 20:05
@Desc : 测试
'''
from Text_auto_correct_v1 import auto_correct_sentence
def test(msg):
print("Test case 1:")
correct_sent = auto_correct_sentence(msg)
print("original sente... |
import tempfile
from collections import defaultdict
from threading import Lock
from PyPDF2 import PdfFileMerger
from PyPDF2.utils import PdfReadError
from telegram import (
ChatAction,
ParseMode,
ReplyKeyboardMarkup,
ReplyKeyboardRemove,
Update,
)
from telegram.ext import (
CallbackContext,
... |
INSTRUMENT_TOPIC_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"active": {
"type": "boolean"
},
"exchangeIds": {
"type": "array",
"items": [
{
"type": "string"... |
import os
import tkinter as tk
from utils.data import *
from utils.utilities import *
from utils.statusbar import StatusBar
from utils.oreoide import OreoIDE
from utils.oreoeditor import OreoEditor
from utils.oreomenu import OreoMenu
from utils.terminal import Terminal
if __name__ == "__main__":
root = OreoIDE()... |
# encoding: utf-8
from .extended import *
from ..models import GoogleAPISettings
# from django import template
# from django.conf import settings
# from django.db.models import Count
# from django.utils import timezone
# from taggit_templatetags.templatetags.taggit_extras import get_queryset
# register = template.Li... |
import mimetypes
from urllib.parse import quote_plus, urljoin, urlencode
import prs_utility as utility
import requests
__all__ = ['hash_request', 'sign_request', 'get_auth_header', 'request']
def hash_request(path, payload, hash_alg='keccak256'):
prefix = 'path={}'.format(quote_plus(path))
sorted_qs = utili... |
#!/usr/bin/env python
from setuptools import setup
import ssha
setup(
name='ssha',
version=ssha.__version__,
description='SSH into AWS EC2 instances',
author='Raymond Butcher',
author_email='ray.butcher@claranet.uk',
url='https://github.com/claranet/ssha',
license='MIT License',
pack... |
"""
copyright bijan shokrollahi
10.06.2021
"""
import unittest
from dynamic_programming_and_greedy_algos.fast_fourier_transformation import *
from random import randint
class MyTestCase(unittest.TestCase):
def test_max_subarray(self):
self.assertEqual(25, maxSubArray([100, -2, 5, 10, 11, -4, 15, 9, 18, -... |
'''
Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.
For example, "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skill... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
class Openloops(Package):
"""The OpenLoops 2 program is a fully automated implementati... |
import bs4, json
soup = bs4.BeautifulSoup(open('text.html'), 'html.parser')
important_bits = soup.findAll(['h3', 'a', 'i'])
count = 0
started = False
data = []
for bit in important_bits:
start_len = len(data)
if bit.name == 'h3':
if bit.text[:3] == 'ACT':
started = True
data.append({
'type': 'act',
... |
"""
"""
from __future__ import absolute_import
import subprocess
from os import makedirs, listdir
from os.path import exists, join, basename
from abc import ABCMeta, abstractmethod
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
import requests
import yaml
from pkg_re... |
## Utilities file for Greenland modelling functions
## 30 Nov 2017 EHU
## 10 Jul 2019 Adding visualization tools
from numpy import *
#from netCDF4 import Dataset
import numpy as np
#from scipy import interpolate
from scipy import spatial
#from scipy.ndimage import gaussian_filter
from shapely.geometry import *
from ... |
#
# Copyright (c) 2015 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 applicable law or agreed to i... |
import requests
import json
requests.packages.urllib3.disable_warnings()
from requests.packages.urllib3.exceptions import InsecureRequestWarning
SDWAN_IP = "10.10.20.90"
SDWAN_USERNAME = "admin"
SDWAN_PASSWORD = "C1sco12345"
class rest_api_lib:
def __init__(self, vmanage_ip, username, password):
self.vm... |
#coding: utf-8
''' mbinary
#######################################################################
# File : fastPow.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-17 21:39
# Description: fast power
##############################... |
import pytest
from pypart.messenger import Email, EmailFormatError
class TestEmail:
@pytest.mark.parametrize(
'email, exception',
[
('username@domain.com', None),
('user.name@domain.com', None),
('user-name@domain.com', None),
('user_name@domain.com'... |
import unittest
import os
import sys
from maskgen import plugins
from maskgen.video_tools import get_shape_of_video
from maskgen import tool_set
from maskgen.cv2api import cv2api_delegate
from tests.test_support import TestSupport
class TestDroneShake(TestSupport):
filesToKill = []
def test_plugin(self):
... |
import numpy as np
import pytorch_lightning as pl
import torch
import torch_geometric.transforms as transforms
from torch_geometric.data import DataLoader
from torch_geometric.datasets import TUDataset
from src import project_dir
class EnzymesDataModule(pl.LightningDataModule):
def __init__(
self,
... |
from tqdm import tqdm
import time
for i in (t:=tqdm(range(1000))):
t.set_description(f'MEDITATING')
time.sleep(1)
|
# Copyright 2017 Google Inc. 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 ag... |
# import
import os
import pandas as pd
import numpy as np
#%%
def get_depth_df(path,subjects):
# Loop through each Testsubject folder
depth_df = pd.DataFrame()
for i,elem in enumerate(subjects):
filepath = os.path.join(path, "TestSubject"+str(elem)+"\\FAP.txt")
depth_df_raw = pd.read_cs... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-15 17:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0044_auto_20160115_1704'),
]
operations = [
migrations.AddField(... |
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.db.models.deletion import ProtectedError
from django.urls import reverse
from .utils import generate_unique_slug
class ExcludeDeletedManager(models.Manager):
def get_queryset(self):
return super(ExcludeDeletedMa... |
# ##### BEGIN MIT LICENSE BLOCK #####
#
# MIT License
#
# Copyright (c) 2022 Steven Garcia
#
# 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 ... |
#!/usr/bin/python3
# -*-coding:Utf-8 -*
import re
import sys
from PIL import Image
tmpPath = "./.tmp"
def getCentroid(line):
line = line.replace("(", "").replace(")", "").split(',')
r = int(line[0])
g = int(line[1])
b = int(line[2])
return (r, g, b)
def getCoor(line):
return (line.split(" "... |
from ..utils import Object
class SendMessage(Object):
"""
Sends a message. Returns the sent message
Attributes:
ID (:obj:`str`): ``SendMessage``
Args:
chat_id (:obj:`int`):
Target chat
reply_to_message_id (:obj:`int`):
Identifier of the message to r... |
class Demo:
a1 = 1
@classmethod
def mymethod1(cls):
cls.c1 = 20
del Demo.a1
print("Only static variable a1 is present")
print(Demo.__dict__)
print("---------------------------")
Demo.mymethod1()
print("static variable a1 is absent and only c1 is present")
print(Demo.__dict__)
|
import joblib
import pandas as pd
from hgtk import text, letter, checker
from .const import ALPHABET_LIST, CHOSUNG_LIST, JONGSUNG_LIST, JUNGSUNG_LIST, NUMBER_LIST, SPECIAL_CHARACTERS_LIST
CHOSUNG = 3
JUNGSUNG = 2
JONGSUNG = 1
class ModelByWord:
def __init__(self):
text.decompose = self.__decompose
... |
no = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10} # 中文数目字
inputs = [] # 输入流
var = [] # 变量流
data = [] # 数据流
regexp = [] # 正则流
state = None # 业务状态
def get():
# 用户输入流
inputs.append(input().split()[-1])
print(inputs)
def get... |
version = '0.19.0b1'
|
import os
from dotenv import load_dotenv
from users import app
load_dotenv()
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
DB_HOST = os.getenv('DB_HOST')
DB_PORT = os.getenv('DB_PORT')
DB_NAME = os.getenv('DB_NAME')
config = {
'app': {
'APP_NAME': os.getenv('APP_NAME', 'app'),
... |
#! /usr/bin/env python
# encoding: utf-8
version = (0, 3, 10)
from .client import VimeoClient # noqa: E402
from . import exceptions # noqa: E402
|
from django.urls import path, include
from . import views
urlpatterns = [
# path('', include('user.urls')),
path('', views.first, name='first'),
path('dashboard', views.home, name='home')
] |
"""
Copyright © 2021 The Johns Hopkins University Applied Physics Laboratory LLC
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,... |
'''
@author Tian Shi
Please contact tshi@vt.edu
'''
import json
import os
import numpy as np
from sklearn.metrics import classification_report
from tqdm import tqdm
from .utils import calculate_COH, calculate_PMI, read_docs, read_vocab
def eval_aspect_coherence(
work_dir='../cluster_results',
file_t... |
import torch
import torch.nn as nn
import numpy as np
def train(model, train_loader, val_loader, device, batch_size=50, epochs=5):
lr = 0.001
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
counter = 0
print_every = 100
clip = 5 # gradient clipping
mode... |
from aioviberbot.api.consts import BOT_API_ENDPOINT
class MessageSender:
def __init__(self, logger, request_sender):
self._logger = logger
self._request_sender = request_sender
async def send_message(self, to, sender_name, sender_avatar, message, chat_id=None):
if not message.validate... |
### TODO: nbuckman Is this actually being used?
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
try:
from reprlib import repr
except ImportError:
pass
class PoseHistory:
# This class is used to store the history of poses and times for each agent
de... |
# Importing the libraries
import pandas as pd
#show all data from all columns
pd.set_option('max_columns', None)
# Importing the dataset
dataset = pd.read_csv('HNSCC_Clinical_data.csv')
#patient information
patient_info = dataset[["Age", "Sex", "Smoking History", "Current Smoker", "HPV status"]]
patient_info = pd.ge... |
# Comentário de linha
# Comentários de várias linhas
# precisam ter '#' no início de todas as linhas
#PRIMEIRO TESTE DO INTERPRETADOR
hello_full = "Hello World!"
#print(hello_full)
#CONCATENANDO
hello = "Hello "
world = "World! "
number1 = 1
number2 = 2
#print(hello + world)
#print(number1 + number2)
#print(hello +... |
"""Basic app config for jobs app."""
from django.apps import AppConfig
class JobsConfig(AppConfig):
"""Config object for the jobs app."""
name = 'jobs'
|
import requests
__all__ = ['requests_negotiate_sspi']
from .requests_negotiate_sspi import HttpNegotiateAuth # noqa
# Monkeypatch urllib3 to expose the peer certificate
HTTPResponse = requests.packages.urllib3.response.HTTPResponse
orig_HTTPResponse__init__ = HTTPResponse.__init__
HTTPAdapter = requests.adapters.HT... |
import copy
import itertools
import re
import pymongo
from collections import defaultdict
from pdb import set_trace
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, InvalidPage
from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponse, Http... |
import base64
import json
import logging
import zlib
from datetime import datetime
from django.conf import settings
from django.db import transaction
from django.http import JsonResponse
from django.utils.encoding import force_str
from django.utils.timezone import make_aware
from pytz import UTC
from gore.auth import... |
import bblfsh_sonar_checks.utils as utils
import bblfsh
import re
def check(uast):
findings = []
format_calls = bblfsh.filter(uast, "//MethodInvocation/"
"Identifier[@roleCall and @roleReceiver and @Name='String']/parent::MethodInvocation/"
"Identifier[@roleCall and @roleCallee and ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 13 10:50:27 2021
@author: hemerson
"""
from setuptools import setup, find_packages
VERSION = '0.0.18'
DESCRIPTION = 'AgentRL'
LONG_DESCRIPTION = 'A package containing several lightweight reinforcement learning agents'
# Setting up
setup(
... |
from django.apps import AppConfig
class TradesiteConfig(AppConfig):
name = 'tradesite'
|
from django.conf import settings
from hashids import Hashids
class ModelHashIdMixin(object):
""" Easy hashids for Django models.
To use in your model, inherit it from this class, in addition to models.Model
Then user obj.hashid property or cls.pk_from_hashid() function
"""
@classmethod
def... |
#!/usr/bin/env python3
from itertools import combinations
import os
from tqdm import tqdm
import re
characters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', ... |
# -*- coding: utf-8 -*-
# (C) shan weijia, 2018
# All rights reserved
'''Description '''
__author__ = 'shan weijia <shanweijia@jiaaocap.com>'
__time__ = '2018/12/14 4:46 PM'
from flask import Blueprint
from base.base_api import BaseApi
from global_reference import app
user_buleprint = Blueprint("user",__name__)
use... |
from unittest import TestCase
import pandas as pd
import pandas.testing as tm
from pytz import UTC
from exchange_calendars.weekday_calendar import WeekdayCalendar
from .test_exchange_calendar import ExchangeCalendarTestBase
class WeekdayCalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_filename... |
from flask import redirect, Blueprint
from werkzeug.contrib.cache import SimpleCache
import os
import sys
import random
import yaml
cache = SimpleCache()
appbp = Blueprint("appbp", __name__, url_prefix=os.environ.get("URL_PREFIX"))
def get_config():
"""Safely returns the config YAML as a Python dict"""
with... |
import os
import argparse
import random
import pickle
from shutil import copyfile
from typing import Optional, Callable, List
from torchvision.datasets import VisionDataset
from torchvision.datasets.folder import pil_loader
import numpy as np
from PIL import Image
import torchvision.transforms.functional as TVF
from t... |
from website import create_app
# This is the entry point for
# lambda. All the whole point is
# to expose a flask app called 'app'
# don't call run!
app = create_app()
|
import numpy as np
from typing import List
from src.traffic_world import TrafficWorld
def IDM_acceleration(bumper_distance: float,
lead_vehicle_velocity: float,
current_speed: float,
desired_speed: float,
idm_params: dict = None) -> ... |
#!/usr/bin/env python
import base64
import gzip
from httplib import BadStatusLine
import os
import urllib2
import sys
import threading
from os.path import basename, splitext
from multiprocessing import Process
from pprint import pprint
sys.path = ["lib", "pytests", "pysystests"] + sys.path
if sys.hexversion < 0x02060... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.