text stringlengths 2 999k |
|---|
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# Copyright 2019 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
csp = {
'default-src': '\'self\'',
'style-src': [
'\'self\''
],
'script-src': [
'\'self\'',
'\'strict-dynamic\'',
'www.google-analytics.com',
'www.googletagmanager.com',
'\'unsafe-inline\''
],
'font-src': [
'\'self\''
],
'connect-sr... |
# 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, software
# distributed under the Li... |
#!/usr/bin/env python
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Script to integrate CARLA and SUMO simulations
"""
# ====================... |
# 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... |
# Generated by Django 3.1.2 on 2020-10-09 17:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0003_auto_20201008_0000'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='phone',
... |
"""
Auto-generated class for NodeMount
"""
from . import client_support
class NodeMount(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(device, fstype, mountpoint, opts):
"""
:type device: str
:type fstype: str
:type mountpoint: str
... |
from datetime import datetime
from decimal import Decimal
import uuid
import ipdb
class Signal(object):
def __init__(self, *, name, category, symbol=None, trend=None, signaled_at=datetime.now()):
# caategory: marco, sector , assert, technical, fundmental,
self.id = uuid.uuid1()
self.name ... |
"""Google Cloud Function to launch a Terra workflow."""
import os
from typing import Any, Dict
from utils import prepare_and_launch
def launch_workflow(data: Dict[Any, Any], context: Any):
"""Entry point for execution via a Cloud Function.
This Cloud Function reads configuration from environment variables... |
from sciapp import Manager
import numpy as np
ColorManager = Manager()
import matplotlib.pyplot as plt
for i in plt.colormaps()[::-1]:
cm = plt.get_cmap(i)
if i[-2:] == "_r":
continue
vs = np.linspace(0, cm.N, 256, endpoint=False)
lut = cm(vs.astype(np.int), bytes=True)[:, :3]
ColorManager... |
from machine import ADC , Pin
from Blocky.Pin import getPin
class Light :
def __init__ (self , port , sensitive = 4):
pin = getPin(port)
if (pin[2] == None):
from machine import reset
reset()
self.adc = ADC(Pin(pin[2]))
if (sensitive == 1): self.adc.atten(ADC.ATTN_0DB)
elif (sensitive == 2): self.a... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import math
from itertools import combinations
from collections import defaultdict
from ._summarizer import AbstractSummarizer
class TextRankSummarizer(AbstractSummarizer):
"""Source... |
from program import *
from pcfg import *
from collections import deque
from heapq import heappush, heappop
import time
def bounded_threshold(G : PCFG, threshold = 0.0001):
'''
A generator that enumerates all programs with probability greater than the threshold
'''
frontier = deque()
initial_non_t... |
import logging
import os
import logstash
LOGLEVEL = os.getenv('LOGLEVEL', 'DEBUG')
LOG_HUMAN_READABLE = bool(os.getenv('LOG_HUMAN_READABLE', False))
LOG_FILE = bool(os.getenv('LOG_FILE', False))
LOG_FILE_NAME = str(os.getenv("LOG_FILE_NAME", "app.log"))
class AppLogger:
def __init__(self, logger_name):
gl... |
from unittest import TestCase
from capstoneproject.content_rating.algorithm.content_rating import isalphanum
from capstoneproject.content_rating.algorithm.content_rating import ContentRatingAlgorithm
from django.contrib.auth.models import AnonymousUser, User
from django.test import RequestFactory
class TestIsalphanum(... |
# Copyright 2021 Google Research.
#
# 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 writ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
def replace(fileName, replaceDic):
f = open(fileName, 'r')
s = f.read()
keys = replaceDic.keys()
for key in keys:
s = s.replace(key, replaceDic[key])
f.close()
f = open(fileName, 'w')
f.write(s)
f.cl... |
my_name='Zed A.Show'
my_age=35#not a line
my_height=74 # inches
my_weight=180 #lbs
my_eyes='Blue'
my_teeth='White'
my_hair='Brown'
print(f"Let's talk about { my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} ey... |
import re
import sys
import threading
import time
import os
import syncplay
from syncplay import constants
from syncplay import utils
from syncplay.messages import getMessage
from syncplay.utils import formatTime, isURL
class ConsoleUI(threading.Thread):
def __init__(self):
self.promptMode = threading.E... |
import argparse
import math
import random
import numpy
import time
from hill_climbing import HillClimbing
from hill_climbing_restart import HillClimbingRestart
from simulated_annealing import SimulatedAnnealing
from genetic_algorithm import GeneticAlgorithm
from graficos import Graficos
from graficos_geracao import G... |
"""Basic implementations of functionality that can be provided by external tools."""
|
import re
def isNice(a):
if str(a).find("ab") > -1:
return False
if str(a).find("cd") > -1:
return False
if str(a).find("xy") > -1:
return False
if str(a).find("pq") > -1:
return False
ca = str(a).count("a")
ce = str(a).count("e")
ci = str(a).count("i")
... |
import asyncio
import inspect
import logging
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union
from fastapi import params
from fastapi.dependencies.models import Dependant
from fastapi.dependencies.utils import (
get_body_field,
get_dependant,
get_parameterless_sub_dependan... |
import sphinx_copybutton
|
from algo.apex.func import disable_info_logging, ray_remote_config, \
create_learner, create_monitor, create_evaluator
def create_worker(
Worker, worker_id, config,
env_config, buffer_config):
config = config.copy()
env_config = env_config.copy()
buffer_config = buffer_config.copy()
... |
#!/usr/bin/env python3
# encoding: utf-8
import dis
class MyObject:
"""Example for dis."""
CLASS_ATTRIBUTE = 'some value'
def __str__(self):
return 'MyObject({})'.format(self.name)
def __init__(self, name):
self.name = name
dis.dis(MyObject)
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#Agent based model to simulate transmission of ESBL Klebsiella pneumoniae and E. coli on a hospital ward
#Tom Crellen, MORU Postdoc. Started January 2019. tomcrellen@gmail.com
#! /usr/bin/env python
import itertools
import random
import numpy
import sys
import argparse
#Argparse
parser = argparse.ArgumentParser(desc... |
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
import numpy
from flowket.callbacks.monte_carlo import TensorBoardWithGeneratorValidationData, \
default_wave_function_stats_callbacks_factory, MCMCStats
from flowket.machines import RBMSym
from flowket.operators import Heisenberg... |
# Copyright 2020 Google LLC
#
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from typing import Dict, List, Optional
from yach.rpc.rpc_client import RpcClient
from yach.types.blockchain_format.sized_bytes import bytes32
class FarmerRpcClient(RpcClient):
"""
Client to Yach RPC, connects to a local farmer. Uses HTTP/JSON, and converts back from
JSON into native python objects befor... |
import datetime
import logging
import sys
import time
from threading import Thread
import flask
from flask_babel import lazy_gettext as _
from .circulation_exceptions import *
from .config import Configuration
from core.cdn import cdnify
from core.config import CannotLoadConfiguration
from core.mirror import MirrorUp... |
import re
import socket
import asyncio
import warnings
from math import sqrt
from html import unescape
from base64 import b64decode
from urllib.parse import unquote, urlparse
import aiohttp
from .errors import *
from .utils import (log, get_headers, resolve_host,
IPPattern, IPPortPatternGlobal)
... |
#!! Has not been tested
from pysnptools.snpreader import SnpReader
from pysnptools.pstreader import _MergeRows
class _MergeIIDs(_MergeRows,SnpReader):
def __init__(self, *args, **kwargs):
super(_MergeIIDs, self).__init__(*args, **kwargs)
|
## SA + PSO + GA + boundary(GA)
import numpy as np
import random
import time
from hps.algorithms.HPOptimizationAbstract import HPOptimizationAbstract
from hps.algorithms.ga.SimulatedAnnealing_3 import SimulatedAnnealing
from hps.algorithms.ga.GeneticAlgorithm import GeneticAlgorithm
class ParticleSwarmOptimization(... |
import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.metrics import sparse_categorical_accuracy
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.re... |
# -*- coding: utf-8 -*-
import logging
import openerp
import openerp.modules.registry
from openerp.modules import get_module_resource
from openerp.tools.translate import _
from openerp import http
from openerp.http import request, serialize_exception as _serialize_exception
_logger = logging.getLogger(__name__)
##... |
from typing import Dict, List, Any, TypeVar, Generic, Iterable
import attr
from ics.utils import check_is_instance
from ics.valuetype.base import ValueConverter
from ics.valuetype.generic import URIConverter, BooleanConverter
from ics.valuetype.text import RawTextConverter
T = TypeVar('T')
@attr.s(frozen=True)
cla... |
# Copyright 2018 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... |
import unittest
from credential import Credential
class TestUser(unittest.TestCase):
"""
Test class defining the user credentials
"""
# noinspection PyTypeChecker
def setUp(self) -> object:
"""
Setup method that runs before each test case
"""
self.new_credential = ... |
r"""
Bialgebras with basis
"""
# ****************************************************************************
# Copyright (C) 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# Copyright (C) 2008-2011 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public L... |
import abc
import logging
import typing
import numpy as np
import torch
import mantrap.environment
class OptimizationModule(abc.ABC):
def __init__(self, t_horizon: int, weight: float = 0.0,
env: mantrap.environment.base.GraphBasedEnvironment = None,
has_slack: bool = False, s... |
"""
This file offers the methods to automatically retrieve the graph Candidatus Moranbacteria bacterium RIFOXYA2_FULL_43_15.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
tit... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
import re
import subprocess
from collections import namedtuple
from corehq.apps.app_manager.xpath_validator.config import (
get_xpath_validator_path,
)
from corehq.apps.app_manager.xpath_validator.exceptions import (
XPathValidationError,
)
XpathValidationResponse = namedtuple('XpathValidationResponse', ['is_... |
# Copyright (c) 2016 AT&T Corp
# 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... |
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'wysiwyg_img'
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
WYSISWYG_IMG_UPLOAD_TO = 'test_folder'... |
# -*- coding: utf-8 -*-
from datetime import date
from dateutil.relativedelta import relativedelta
from lotus_core.utils import dbutil
def choose():
cursor = dbutil.get_connection().cursor()
trade_date = str(date.today() + relativedelta(days=-1))
stock_codes_on_pe = _choose_on_pe(cursor, trade_date)
... |
# Project: Finish.
print("The Advanced Calculator | By EndangeredBubs")
Equation1=" "
Equation2=" "
Equation3=" "
Equation4=" "
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CountriesConfig(AppConfig):
name = "country_manager.countries"
verbose_name = _("Countries")
|
from talk import custom_conversation
from talk import speak
import speech_recognition as sr
import pywhatkit
import datetime
import wikipedia
import pyjokes
import subprocess
import webbrowser
import os
import smtplib
import ctypes
import time
import shutil
import pyautogui
from urllib.request import urlopen
listener ... |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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/lice... |
import time
from datetime import date, datetime
from io import StringIO
from django.test import TestCase, override_settings
from pytz import timezone
from search.elasticsearch_helpers import ElasticsearchTestsMixin
from v1.documents import (
EnforcementActionFilterablePagesDocumentSearch,
EventFilterablePage... |
import os
import csv
import pandas as pd
path="../datasets/Companies/"
companies=[]
for file in os.listdir(path):
if file[0]!='.':
companies.append(file.split('.')[0].upper())
columnTitleRow = ['Symbol','Name','LastSale','MarketCap','IPOyear','Sector','industry','Summary Quote']
with open("stocks.csv", 'a... |
#! /opt/stack/bin/python
# @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import crypt
import os
import random
import time
import string
class Password:
def get_rand(self, num_bytes=16, choi... |
import os
import numpy as np
import copy
import colorsys
from timeit import default_timer as timer
from keras import backend as K
from keras.models import load_model
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw
from gaussion_yolo3.gaussian_yolo3 import yolo_body, yolo_eval
from utils.utils... |
# -*- coding: utf8 -*-
from console.factory import db
from console.models.base import BaseObject, BaseRepository
class TaskInter(BaseObject, db.Model):
__tablename__ = 'task_inter'
id = db.Column(db.VARCHAR(64), primary_key=True, autoincrement=False)
gmt_create = db.Column(db.DateTime)
gmt_modified ... |
# Copyright 2020 The Magenta 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 ... |
"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os, r... |
__author__ = 'felixshaw'
import pymongo
from bson import ObjectId
from django.conf import settings
def get_collection_ref(collection_name):
return settings.MONGO_CLIENT[collection_name]
def get_mongo_client():
MONGO_CLIENT = pymongo.MongoClient(host=settings.MONGO_HOST, maxPoolSize=settings.MONGO_MAX_POOL_... |
import commands
import os
def conclude_result():
totalBlastHits=commands.getoutput("grep '' matched2DB.query -c")
count_photo=int(commands.getoutput("tail -n+6 prediction.csv |cut -d',' -f3|grep '1:photo' -c"))
count_nonphoto=int(commands.getoutput("tail -n+6 prediction.csv |cut -d',' -f3|grep '2:non_photo' -c"))
... |
# coding=utf-8
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
import argparse
import json
import multiprocessing
imp... |
import gensim
import logging
import re
import json
import multiprocessing
import os
dataPath = "/fs/clip-scratch/shing/webbase_all/"
phraseDir = "/fs/clip-scratch/shing/phrase/"
savePath = "/fs/clip-scratch/shing/output/"
class MySentences(object):
def __init__(self, dirname, phraseDir, concatenate=True, dirList... |
from maze_lib.tesselations.orthogonal import Orthogonal
|
# %% [markdown]
# # sklearn-porter
#
# Repository: [https://github.com/nok/sklearn-porter](https://github.com/nok/sklearn-porter)
#
# ## DecisionTreeClassifier
#
# Documentation: [sklearn.tree.DecisionTreeClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html)
# %%
import... |
from pyderman.drivers import chrome, firefox, opera, phantomjs, edge
all_drivers = [chrome, firefox, opera, phantomjs, edge]
|
# -*- test-case-name: txdav.carddav.datastore.test -*-
##
# Copyright (c) 2010-2017 Apple 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/l... |
from project import app
from flask import render_template, redirect, request, url_for, session
from project.com.dao.LoginDAO import LoginDAO
from project.com.vo.LoginVO import LoginVO
from project.com.dao.BankDAO import BankDAO
from project.com.vo.BankVO import BankVO
from project.com.dao.BranchDAO import BranchDAO
fro... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'andyguo'
import importlib
import os
from collections import defaultdict
import nuke
NUKE_FITMENT_ROOT_PATH = os.path.sep.join([os.environ.get('MY_CUSTOM_FITMENT', ''), 'nuke'])
def add_callbacks():
callback_folder = os.path.sep.join([NUKE_FITMENT_R... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
TrueSkill
~~~~~~~~~
An implementation of the TrueSkill algorithm for Python. TrueSkill is a rating
system among game players and it is used on Xbox Live to rank and match
players.
.. sourcecode:: python
from trueskill import Rating, quality_1vs1, rate_1vs1
alice, bob = Rating(25), ... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2019-present MagicStack Inc. and the EdgeDB 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... |
# -*- coding: utf-8 -*-
#
# cinetflow documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 configuration values have... |
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","exam")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M'... |
#
# Copyright 2019 The FATE 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 appli... |
# -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,wcshen1994@163.com
"""
from tensorflow.python.keras.layers import Layer, Concatenate
class NoMask(Layer):
def __init__(self, **kwargs):
super(NoMask, self).__init__(**kwargs)
def build(self, input_shape):
# Be sure to call this somewhere... |
from concurrent.futures import ThreadPoolExecutor
import re
from keystoneauth1 import identity
from keystoneauth1 import session
from novaclient import client
METRIC_NAME_PREFIX = "openstack."
NOVA_HYPERVISOR_PREFIX = "nova.hypervisor."
NOVA_SERVER_PREFIX = "nova.server."
NOVA_LIMIT_PREFIX = "nova.limit."
DEFAULT_NO... |
# Copyright (C) 2015-2021 Virgil Security, Inc.
#
# 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 must retain the above copyright
# notice, this li... |
#!/usr/bin/env python3
################################################################
# This test can be used to get the information of the current
# version which is running on the target address.
#
# This file is part of Qvain project.
#
# Author(s):
# Juhapekka Piiroinen <juhapekka.piiroinen@csc.fi>
#
# Copyri... |
import pandas as pd
from opinion import config, utils
def transform_url(df):
df['media_source'] = df['media_source'].apply(
lambda x: x.replace('https', 'http')
)
return df
def process_url(url):
try:
domain, path = utils.parse_url(url)
return domain
except ValueError as ... |
import argparse
import gc
import hashlib
import logging
import os
import sys
import unicodedata
from collections import Counter
from time import strftime, localtime
from datetime import datetime
import psutil
from hurry.filesize import size
import numpy as np
import torch
from traitlets.config.loader import KeyValueC... |
from urllib.parse import parse_qs
class Request:
GET = {}
POST = {}
def __init__(self, environ: dict):
self.build_get_params_from_dict(environ.get('QUERY_STRING'))
self.build_post_params_dict(environ.get('wsgi_input').read())
def build_get_params_from_dict(self, raw_params: str):
... |
import os
import site
# Resolve version conflict from one of the files
site_packages = site.getsitepackages()
for site in site_packages:
vggface_model_path = os.path.join(site,'keras_vggface/models.py')
if os.path.exists(vggface_model_path):
text = open(vggface_model_path).read()
open(vggface_mo... |
import timeit
from reg import dispatch
from reg import DictCachingKeyLookup
def get_key_lookup(r):
return DictCachingKeyLookup(r)
@dispatch(get_key_lookup=get_key_lookup)
def args0():
raise NotImplementedError()
@dispatch("a", get_key_lookup=get_key_lookup)
def args1(a):
raise NotImplementedError()
... |
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 VMware, 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
#
# ... |
import time
import os
last_time = time.time()
while True:
if time.time()-last_time > 30:
last_time = time.time()
os.system('curl http://localhost/cron.php') |
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
# Copyright 2013 Red Hat, 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... |
"""profiles_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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')
Cl... |
from builder import buildIRFromCache
import llvmlite.binding as llvm
from ctypes import CFUNCTYPE, c_int
from argparse import ArgumentParser
def create_execution_engine():
"""
Create an ExecutionEngine suitable for JIT code generation on
the host CPU. The engine is reusable for an arbitrary number of
modules.
"""... |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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 ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
import os, sys
from flask import request, jsonify
from flask_httpauth import HTTPBasicAuth
sys.path.append(os.path.abspath(os.getcwd()))
from utils.gets import set_user, get_user
from utils.login_manager import LoginManager
from enviroment.enviroment import db
auth = HTTPBasicAuth()
def get_token():
return reques... |
"""Collection of imbalanced datasets.
This collection of datasets has been proposed in [1]_. The
characteristics of the available datasets are presented in the table
below.
ID Name Repository & Target Ratio #S #F
1 ecoli UCI, target: imU 8.6:1 336 7
2 ... |
from __future__ import unicode_literals, print_function
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.http import QueryDict
from django.template.defaulttags im... |
# Define a class to receive the characteristics of each line detection
class Line():
def __init__(self):
# was the line detected in the last iteration?
self.detected = False
# x values of the last n fits of the line
self.recent_xfitted = []
#average x values of the fitted ... |
#!/usr/bin/python3
# Author: Emmanuel Odeke <odeke@ualberta.ca>
# Provides a decorator function that times a function
# The speed ups of caching are also demonstrated if this
# module's main function is invoked
import time
cache = dict() # Mapping n to n! [ its factorial value ]
def profiled(funct):
def decor... |
"""
Basic Q-learning implementation
"""
from __future__ import division, print_function, absolute_import
import theano.tensor as T
from lasagne.objectives import squared_error
from .helpers import get_end_indicator, get_action_Qvalues
from ..utils.grad import consider_constant
import numpy as np
def get_reference_Qva... |
from __future__ import annotations
import collections
from datetime import datetime
from typing import DefaultDict, Dict, List, Optional, TYPE_CHECKING
from tarkov.notifier.models import MessageNotification, MessageNotificationData
if TYPE_CHECKING:
# pylint: disable=cyclic-import
from tarkov.profile.profile ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.