content stringlengths 5 1.05M |
|---|
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def retrieve_ref(variableName):
ref_path = os.path.join( 'metadata')
ref_file = os.path.join(ref_path, 'ref.csv')
df = pd.read_csv(ref_file)
variableNames = list(df['name'])
variableVal... |
#!/usr/bin/env python
from kafka import KafkaConsumer, TopicPartition
consumer = KafkaConsumer('my_favorite_topic', group_id='my_favorite_group')
for msg in consumer:
print(msg)
|
#
# 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 us... |
#!/usr/bin/env python
from setuptools import setup
setup(
name="django-dynamic-filenames",
py_modules=["dynamic_filenames"],
use_scm_version=True,
)
|
# Generated by Django 2.2 on 2019-08-06 15:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('commun... |
from sklearn.preprocessing import LabelEncoder
import tensorflow as tf
def print_runtime(text: str, runtime: float) -> None:
"""
Print runtime in seconds.
:param text: Message to print to the console indicating what was measured.
:param runtime: The runtime in seconds.
:return: None.
"""
p... |
import pandas as pd
from gensim.models.doc2vec import Doc2Vec
import numpy as np
from sklearn.tree import DecisionTreeClassifier
import csv
texts = []
f = open('classifier/2_tunning_shuffled_pre_review_rhino_1203.csv', 'r')
for line in f.readlines():
oneline = line.replace("\n", "").split(",")
oneline = list(f... |
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
from argparse import Namespace
import os
import contextlib
def Renormalize(similarity,
metric = "carbo",
customrange = None,
):
"""
Renormalizes a similarity metric to the range [0:1]
:param similarity:... |
"""imdb - Read and search IMDb plain text data files.
http://www.imdb.com/interfaces
ftp://ftp.fu-berlin.de/pub/misc/movies/database/
ftp://ftp.funet.fi/pub/mirrors/ftp.imdb.com/pub/
ftp://ftp.sunet.se/pub/tv+movies/imdb/
"""
import heapq
import re
import os
from chunkedfile import ChunkedFile
from utils import Time... |
import xml.etree.ElementTree as ET
from programy.parser.template.nodes.resetlearn import TemplateResetLearnNode
from programy.parser.exceptions import ParserException
from programy.parser.template.nodes.base import TemplateNode
from programy.context import ClientContext
from programy.bot import Bot
from programy.confi... |
'''
Roisin Fallon 20 March 2019
Write a program that outputs today’s date and time in the format “Monday,January 10th 2019 at 1:15pm”.
Adapted from https://docs.python.org/3.4/library/datetime.html?highlight=weekday
'''
import datetime as dt ... |
import enoki as ek
import pytest
import gc
@pytest.fixture(scope="module", params=[ek.cuda.ad, ek.llvm.ad])
def m(request):
gc.collect()
gc.collect()
if 'cuda' in request.param.__name__:
if not ek.has_cuda():
pytest.skip('CUDA mode is unsupported')
else:
if not ek.has_llvm(... |
from pathlib import Path, PosixPath, WindowsPath
import pytest
from cloudpathlib.anypath import AnyPath
from cloudpathlib.cloudpath import CloudPath
from cloudpathlib.exceptions import AnyPathTypeError
def test_anypath_path():
path = Path("a/b/c")
assert AnyPath(path) == path
assert AnyPath(str(path)) =... |
import argparse
from flask import Flask, request, Response, current_app, json
from crawler.twitter import Twitter
from model.model import Model
import time
from datetime import date
def parse_arguments():
parser = argparse.ArgumentParser(description='Starts a server that queries a pretrained model.')
group = p... |
import pickle
import os
import neat
import pygame
from base import Base
from bird import Bird
from pipe import Pipe
pygame.font.init()
GEN = 0
WIN_WIDTH = 500
WIN_HEIGHT = 800
BG_IMAGE = pygame.transform.scale2x(pygame.image.load(os.path.join("images", "bg.png")))
STAT_FONT = pygame.font.SysFont('comicsans', 50)... |
"""instantiate global Messenger object"""
__all__ = ['messenger']
import Messenger
messenger = Messenger.Messenger()
|
from excel_io import get_original_data
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
from scipy.signal import savgol_filter
import pickle
#from sklearn.linear_model import LinearRegression
# Filtering
def move_average_filtering(data,kernel_size=3,stride=1):
n=np.ones(ke... |
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
max_profit = 0
min_price = float('Inf')
for p in prices:
if p < min_price:
min_price = p
else:
profit = p - min_price
... |
# This directory is a Python package.
from .build import *
from .cpp import *
from .java import *
from .io import *
from .tc_gcc import *
from .tc_clang import *
from .tc_msvc import *
from .tc_nvcc import *
from .tc_android import *
from .tc_javac import *
from .user import *
from .deploy import *
from .root_paths im... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-04 19:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0028_auto_20160702_1713'),
]
operations = [
migrations.AddField(
... |
import os
import sys
import random
import numpy as np
import tensorflow as tf
#import xml.etree.elementtree as et
import xml.etree.ElementTree as et
#There are only two definitions of my tags, depending on my own pictures
VOC_LABELS = {
'none': (0, 'Background'),
'headphone': (1, 'headphone'),
'earphone'... |
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from write_log import write_log
from time import sleep
from random import randint, choice
from driver_actions import type_text, click_element
import pyauto... |
from enum import Enum
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils.timezone import now
from core.models import UL_CONS_STAFF, UL_ORG_ADMIN, USER_LEVEL_CHOICES, User
class Validity(Enum):
VALID = "valid"
FUTURE = "future"
OUTDATED = "outda... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : jackeroo
# @Time : 2019/11/12
# @File : UserRegisterValidator.py
# @Contact : jackeroo@qq.com
# @Software : PyCharm
# @Desc : 角色权限绑定参数验证
from app.extensions.BaseValidator import BaseValidator
class RolePermissionsBindingValidator(BaseValid... |
# Copyright 2019 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, ... |
import siliconcompiler as sc
from siliconcompiler.package import Sup
import pytest
import shutil
import os
import sys
def test_sup():
''' SUP basic test
'''
registry = 'test_registry'
builddir = 'test_build'
cachedir = 'test_cache'
os.environ['SC_HOME'] = cachedir
os.makedirs(f"{cachedir}/... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9b1 on 2015-11-16 09:44
from __future__ import unicode_literals
from django.db import migrations, models
def populate_type_field(apps, schema_editor):
from takeyourmeds.reminders.enums import TypeEnum
Reminder = apps.get_model('reminders', 'Reminder')
for ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 5 15:00:34 2018
@author: James Jiang
"""
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
grid = [[i for i in line] for line in all_lines]
for y_corners in [0, 99]:
for x_corners in [0, 99]:
grid[y_corners][x_corners] = '#'
grid_num_neighbors =... |
# Copyright 2021 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... |
# pylint: disable=missing-function-docstring, missing-module-docstring/
import user_mod
import user_mod2
test = user_mod.user_func(1.,2.,3.) + user_mod2.user_func(4.,5.)
print(test)
|
# True Price
import sys
from itertools import combinations
from collections import defaultdict
T_IN = 0.5
# SP = 2 # hard-coded, mostly for efficiency
# dictionary type that returns zero for missing values
# used here in 'edges' dictionary
class zerodict(dict):
def __missing__(self, k):
return 0
def ipca(filename... |
from flask import Flask, render_template, request, session
from flask_session import Session
app = Flask(__name__)
notes = list()
# Aplicação para receber um formulário e adicionar a uma lista de notas,
# que será exibida na tela
# Main Program
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = 'fil... |
from flask import request
from app.main.extensions import cache
def clear_cache(key_prefix):
keys = [key for key in cache.cache._cache.keys() if key.startswith(key_prefix)]
cache.delete_many(*keys)
def cache_json_keys():
json_data = tuple(sorted(request.get_json().items()))
return json_data
|
"""Application Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
from .Priority import Priority
from .TicketCategory import TicketCategory
from .Status import Status
class Filter(BaseSchema):
# Lead swagg... |
class Node:
def __init__(self, string=None, location=None, tokens=None):
# We want to handle instantiation from a pyparsing expression, or just
# passing in a token like: `Node('foo')`
if location == None:
self.token = string or self.TOKEN
else:
# create from ... |
#!/usr/bin/python
import cgi
import glob
import os
import sys
import json
import ssl
import shutil
from http.server import BaseHTTPRequestHandler,HTTPServer
PortNumber = 8090;
u = "user";
p = "password";
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.... |
import numpy as np
import random
import pickle
import os
from utils import utils
import torch
import torch.backends.cudnn as cudnn
import argparse
from torch.nn import functional as F
import torchvision.transforms as transforms
import models
from PIL import Image
class ImageNetDataset(torch.utils.data.Dataset):
... |
from enum import IntEnum
from .components import *
__all__ = (
"InteractionResponseType",
"InteractionResponse"
)
class InteractionResponseType(IntEnum):
PONG = 1
CHANNEL_MESSAGE = 4
DEFERRED = 5
DEFERRED_MESSAGE_UPDATE = 6
UPDATE_MESSAGE = 7
APPLICATION_COMMAND_AUTOCOMPLETE_RESULT ... |
"""Evaluates the model"""
import argparse
import logging
import os
import numpy as np
import torch
import utils
from model.x2net import x2Net
from model.x3net import x3Net
from model.x4net import x4Net
from model.loss_fn import loss_fn
from model.metrics import metrics
import model.data_loader as data_loader
parser... |
from typing import Dict
import numpy as np
from gym import spaces
from stable_baselines3.common.vec_env import VecEnv, VecEnvWrapper
class ObsDictWrapper(VecEnvWrapper):
"""
Wrapper for a VecEnv which overrides the observation space for Hindsight Experience Replay to support dict observations.
:param e... |
# @Author: yican, yelanlan
# @Date: 2020-06-16 20:36:19
# @Last Modified by: yican.yc
# @Last Modified time: 2020-06-16 20:36:19
# Standard libraries
import os
import gc
from time import time
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
# Third party libraries... |
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
class EventAPITestCase(APITestCase):
def test_evet_type_list_view(self):
response = self.client.get(reverse('rest_api:event-type-list'))
self.assertEqual(response.stat... |
# coding:utf-8
# Copyright (c) 2019 PaddlePaddle 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 req... |
from __future__ import absolute_import
from kafka.serializer.abstract import Serializer, Deserializer
|
#!/usr/bin/python3
import sys
import socket
# Server function
def server(ServerIPAddress, ServerPortNumber) :
# Server's IPAddress and PortNumber
ServerPair = (ServerIPAddress, ServerPortNumber)
# Create a listening socket
ListenSocket = socket.socket()
# Bind the listening socket to that pair... |
import time
def rq_mock_job():
time.sleep(0.1)
return "rq_mock_job result"
def rq_mock_job_2():
time.sleep(0.2)
return "rq_mock_job_2 result"
|
import types
import inspect
import cypher_utils
from exceptions import PermissionDenied, InvalidValueError, NodeTypeNotFoundError
class Allows(object):
"""
Default permissions definitions
"""
@staticmethod
def creator(self, graph, actor_id, node_id, tx):
creator_id = graph.request_subgrap... |
from nonebot import on_regex, require, on_keyword
from nonebot.adapters.cqhttp import Bot, MessageEvent
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State
from .genshin_handle import genshin_draw, update_genshin_info, reset_count
from .prts_handle import update_prts_info, prts_draw, reload... |
"""."""
from collections import defaultdict as dd
class Graph(object):
def __init__(self):
self.graph = dd(list)
def add_node(self, data):
self.graph[data]
def add_edge(self, start, end, weight):
self.graph[start].append((end, weight))
self.graph[end].append((start, weig... |
from __future__ import print_function, division
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import random
import numpy as np
ACTION_UP = "W"
ACTION_DOWN = "S"
ACTION_LEFT = "A"
ACTION_RIGHT = "D"
ACTION_UP_DOWN_NONE = "~WS"
ACTION_LEFT_RIGHT_NONE = "~AD"
ACTIONS_UP_DOWN = [AC... |
import glob
import os
from sacred import Ingredient
import tensorflow as tf
data_ingredient = Ingredient('dataset')
@data_ingredient.config
def data_config():
dataset_name = "clic2019"
return_img_name = True
dataset_base_path = "/scratch/gf332/datasets/"
training_patch_size = None
if datas... |
"""
MSG91 Client
"""
import requests
from urllib.parse import quote
class Client(object):
""" A client for accessing the MSG91 API. """
API_ENDPOINT = "http://api.msg91.com"
TRANSACTIONAL_URL = "/api/v2/sendsms"
TRANSACTIONAL_ROUTE = "4"
def __init__(self, authkey):
"""
Initializ... |
from .MNet import *
import pdb
class AF2(nn.Module):
def __init__(self, att_out=False):
super(AF2, self).__init__()
with torch.no_grad():
self.MNet = MNet(False)
self.MNet.init_w()
for param in self.MNet.parameters():
param.requires_grad = False
... |
from flask import Flask, Blueprint
from goods import goods
app = Flask(__name__)
user_bp = Blueprint('user', __name__)
app.register_blueprint(user_bp)
app.register_blueprint(goods)
@user_bp.route('/user')
def user_profile():
return 'user_profile'
@app.route('/')
def index():
return 'index'
if __name__ ==... |
"""@author: Kartikei Mittal
@email: kartikeimittal@gmail.com
Testing Dynamic Array"""
__author__ = "Kartikei Mittal"
import unittest
from parameterized import parameterized_class, parameterized
from Data_Structure import Heap
from utility import UDTfT, Comparator, InverseComparator
@parameterized_class([{
"type_... |
from pepy.pe import PEFile
from pycns import save_icns
import sys
if __name__ == '__main__':
if len(sys.argv) < 4 or len(sys.argv) > 5:
print ('image_tools <command> <args>\n'
' commands: save_icns input_file output_file\n'
' replace_icon input_exe icon_path [outpu... |
import logging
import numpy as np
from autolens import exc
from autolens.data.array.util import array_util, grid_util
logging.basicConfig()
logger = logging.getLogger(__name__)
class ArrayGeometry(object):
shape_arc_sec = None
origin = None
@property
def shape_arc_seconds(self):
return se... |
from distutils.core import setup
import ast
import os
import codecs
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Lang... |
from lxml import html
def parse_game_url_paths(page):
tree = html.fromstring(page)
games = tree.xpath('//td[contains(@class, "gamelink")]/a')
return list(map(lambda game: game.attrib['href'], games))
|
__copyright__ = 'Copyright (C) 2019, Nokia'
class TestPythonpath3(object):
ROBOT_LIBRARY_SCOPE = "GLOBAL"
def __init__(self):
self.name = 'Tiina'
self.age = 10
def get_name3(self):
return self.name
|
import pymongo
import logging
import numpy as np
import pandas as pd
from scipy.stats import entropy
from config import Configuration
from utils.bot_utils import is_bot
from tasks.collectors.edit_type import CollectEditTypes
from utils.date_utils import parse_timestamp
from tasks.collectors.revision import CollectRevis... |
from django.contrib.auth.tokens import PasswordResetTokenGenerator
class EmailVerificationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return str(user.pk) + str(timestamp) + str(user.profile.is_email_verified)
email_verification_token = EmailVerificationToken... |
import typing
import csv
from pathlib import Path
import pandas as pd
import time
import matchzoo
import os
from typing import List, Set, Tuple, Dict
from tqdm import tqdm
import torch
import numpy as np
import itertools
from handlers.output_handler import FileHandler
import torchvision
import torch_utils
def load_d... |
# :coding: utf-8
# Project Modules
from kid.core import KObject
from kid.io.kio import KIO
from kid.io.kjson import Kjson
# Python Modules
import getpass
# Maya Modules
import maya.cmds as cmds
class KSLData(KObject):
def __str__(self):
return self.str_formatter(**self.as_dict())
class KSLReference(K... |
from itertools import chain
from textwrap import dedent
from .utils import string_types
shared_queries = dict(
datacl=dedent("""\
WITH grants AS (
SELECT
(aclexplode(datacl)).grantee AS grantee,
(aclexplode(datacl)).privilege_type AS priv
FROM pg_catalog.pg_database
WHERE da... |
# Generated by Django 3.0 on 2020-09-09 05:08
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gyms', '0002_auto_20200903_1750'),
]
operations = [
migrations.AlterField(
model_name='gym',
... |
from __future__ import annotations
from enum import IntEnum
import typing
_T = typing.TypeVar('_T')
class STATE(IntEnum):
EXTEND1 = 0
EXTEND2 = 1
ENDING = 2
class Decoder:
def __init__(self) -> None:
self.first = 0
self.second = 0
BIT_END = 0b_0100_0000
def decode(encoded: list[int]... |
# python3 imports
from re import compile as compile_regex
## UK Postcode Class
# @summary This class represents the parsed form of a UK postcode.
class Postcode(object):
## The type of postcode represented by this object
# @param this should be overriden in derived classes.
PostcodeType = 'unspecified'... |
from bootstrapvz.base import Task
from bootstrapvz.common import phases
from bootstrapvz.common.tasks import grub
class ConfigureGrub(Task):
description = 'Change grub configuration to allow for ttyS0 output'
phase = phases.system_modification
successors = [grub.WriteGrubConfig]
@classmethod
def ... |
import numpy as np
import matplotlib.pyplot as plt
__all__ = ['track']
freqs_metadata = list(440 * np.array([2**(k/12) for k in range(12)]))
pitch_metadata = ['A3', '#A3', 'B3', 'C4', '#C4', 'D4', '#D4', 'E4', 'F4', '#F4', 'G4', '#G4', 'A4']
class TrackData:
def __init__(self, audio, freq, tracking):
sel... |
from construct import *
from construct.lib import *
nested_types__subtype_a__subtype_c = Struct(
'value_c' / Int8sb,
)
nested_types__subtype_a = Struct(
'typed_at_root' / LazyBound(lambda: nested_types__subtype_b),
'typed_here' / LazyBound(lambda: nested_types__subtype_a__subtype_c),
)
nested_types__subtype_b = S... |
# -*- coding: utf-8 -*-
# quotequail
# a library that identifies quoted text in email messages
import re
from . import _internal
__all__ = ['quote', 'quote_html', 'unwrap', 'unwrap_html']
def quote(text, limit=1000):
"""
Takes a plain text message as an argument, returns a list of tuples. The
first arg... |
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from rwb.lib.decorators import cached_property
import urllib2
class RobotLog(object):
def __init__(self):
self.path = None
self.suites = []
self.statistics = None
def parse(self, pa... |
from telethon import events
from userbot import CMD_HELP, CMD_HANDLER as cmd
from userbot.utils import flicks_cmd
PRINTABLE_ASCII = range(0x21, 0x7F)
def aesthetify(string):
for c in string:
c = ord(c)
if c in PRINTABLE_ASCII:
c += 0xFF00 - 0x20
elif c == ord(" "):
... |
# Generated by Django 2.0.7 on 2018-08-15 21:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0013_auto_20180815_1445'),
]
operations = [
migrations.RenameField(
model_name='blog',
old_name='name',
... |
"""Custom component used to export ZHA Zigbee devices to a JSON file."""
import logging
import os
from homeassistant.util.json import save_json
import voluptuous as vol
ATTR_OUTPUT_DIR = "output_dir"
DOMAIN = "zha_device_exporter"
CONFIG_OUTPUT_DIR_NAME = "zha-device-export"
SERVICE_EXPORT_DEVICES = "export_devices"... |
#!/usr/bin/env python3
import argparse
import csv
from collections import defaultdict, OrderedDict
from concurrent.futures import ProcessPoolExecutor
from sklearn.metrics import adjusted_rand_score
from sklearn.metrics import homogeneity_score, completeness_score, v_measure_score
parser = argparse.ArgumentParser(des... |
#!/usr/bin/env python3
import sys
import os
import ctypes
if __name__ == '__main__':
if len (sys.argv) < 2:
print("Usage: test.py <JContainers DLL filepath>")
sys.exit(1)
elif len (sys.argv) == 2:
argv = ('', '--gtest_filter=*.*')
else:
argv = tuple ([''] + sys.argv[1:])
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-18 23:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mapdata', '0061_space_based_route_descriptions'),
]
operations = [
migrations.Renam... |
import torch
from mpl_toolkits.axes_grid1 import ImageGrid
import torch.nn as nn
from matplotlib import pyplot as plt
import numpy as np
import torchviz
class classifier(nn.Module):
def __init__(self,in_features,out_features,features):
super(classifier, self).__init__()
self.cls1=nn.Linear... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman
# Purpose: package definition file
# Created: 08.09.2010
#
# Copyright (C) 2010 Manfred Moitzi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# th... |
"""
Configuration for block_structure djangoapp
"""
from django.apps import AppConfig
class BlockStructureConfig(AppConfig):
"""
block_structure django app.
"""
name = 'openedx.core.djangoapps.content.block_structure'
def ready(self):
"""
Define tasks to perform at app loading t... |
#!/usr/local/lib/mailinabox/env/bin/python
# WDK (Web Key Directory) Manager: Facilitates discovery of keys by third-parties
# Current relevant documents: https://tools.ietf.org/id/draft-koch-openpgp-webkey-service-11.html
import pgp, utils, rtyaml, mailconfig, copy, shutil, os, re
from cryptography.hazmat.primitives ... |
# STRINGS METHODS
string = " this is a STRING"
print(string.strip()) # The strip() method removes any leading and trailing characters (space is the default leading character to remove)
print(len(string)) # The len() function returns the number of characters in the string.
print(string.lower()) # The lower() met... |
# Placeholder for so test suite can run
|
# Copyright (c) 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# -*- coding: utf-8 -*-
"""
Tensorflow
Training samples: 170
Validation samples: 44
RNN with 32 units
Optimizer: Adam
Epoch: 35
Loss: Cross Entropy
Activation function: Relu for network and Soft-max for regression
Regularization: Drop-out, keep_prob = 0.6
Accuracy of Validation set: 36.36%
"""
from __future__ import di... |
import numpy as np
import os
import math
from . import ur
from . import rq
from . import simenv
################################################################
## configures the simulated robot and environment
################################################################
class SimEnv(simenv.SimEnv):
# from urd... |
from .channel import *
from .command_processor import *
from .channels import *
from .client_channel import *
|
from pymatting import *
import os
import numpy as np
def test_cutout():
output_path = "test_cutout.png"
cutout("data/test/test.png", "data/test/test_trimap.png", output_path)
cutout_img = load_image(output_path)
os.remove(output_path)
foreground = cutout_img[:, :, :3]
alpha = cutout_img[:,... |
"""
Plotting functions for Bicorr project
Moving them here to keep the bicorr.py file cleaner
PFS, March 2018
Changelog:
2018_03_15: Move a few functions here
"""
import matplotlib
#matplotlib.use('agg') # for flux
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.pyplot import cm
fro... |
from flask import Flask
from .config import Config
# If you have db:
# from .models import db
# Initialize your extensions here:
# login_manager = LoginManager()
def create_app(config=Config):
# Init app
app = Flask(__name__)
app.config.from_object(config)
# Init extensions
# Init app for your ex... |
#!/usr/bin/env python
import json
import sys
from pymongo import MongoClient
if len(sys.argv) < 2:
print 'usage: python read.py filepath'
sys.exit(1)
f = open(sys.argv[1], 'r')
results = json.loads(f.read())
f.close()
numrows = results['numberOfRows']
planets = [{} for i in range(numrows)]
for col, values in r... |
from django.conf.urls import url
from files import views
urlpatterns = [
url(r'^api/files$', views.file_list),
url(r'^api/files/(?P<pk>[0-9]+)$', views.file_detail)
] |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
# https://docs.djangoproject.com/en/3.0/topics/auth
# /customizing/#using-a-custom-user-model-when-starting-a-project
class UserAdmin(BaseUserAdm... |
##import pygame
##import math
##import random
##
##pygame.init()
##dwidth = 1280
##dheight = 720
##gameDisplay = pygame.display.set_mode((dwidth, dheight))
##pygame.display.set_caption('Arrow Game')
##
#### add collision detection, varying arrow speeds, background graphics, music, homing arrows, levels, stage... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
sys.path.append("..")
sys.path.append("../../../../..")
import os
import math
import time
import argparse
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.... |
from libavg import avg
from configs.visual_data import VisDefaults as defaults
from data_models.data_enums import DataSelectionState
from data_models.data_enums import DataType
from data_models.data_object import DataObject
from libavg_charts.aid_lines.aid_line_controller_base import AidLineControllerBase
from libavg_... |
import os
from distutils.spawn import find_executable
from conans import ConanFile, ConfigureEnvironment
from conans.tools import cpu_count, vcvars_command, os_info, SystemPackageTool, download, untargz
from multiprocessing import cpu_count
class QtBaseConan(ConanFile):
""" Qt Base Conan package """
name = "Q... |
from django_filters import rest_framework as filters
from driver.models import Driver, GPSDevice, GPSDeviceProvider
class DriverFilter(filters.FilterSet):
id = filters.NumberFilter(name="id", label="ID", lookup_expr="exact")
id_range = filters.RangeFilter(name="id", label="ID Between")
name = filters.Cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.