text stringlengths 2 999k |
|---|
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj |
import io
import sys
import unittest
from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))
def input_value(fun: callable):
"""Recebe função que imprime algo na tela e retorna impressao.
"""
capturedOutput = io.StringIO()
sys.stdout = capturedOutput
f... |
__author__ = 'patras'
from domain_chargeableRobot import *
from timer import DURATION
from state import state
DURATION.TIME = {
'put': 2,
'take': 2,
'perceive': 2,
'charge': 2,
'move': 2,
'moveToEmergency': 2,
'moveCharger': 2,
'addressEmergency': 2,
'wait': 2,
}
DURATION.COUNTER =... |
import logging
from datetime import datetime
from logging import CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARN
from threading import Lock
TRACE = 5
_levelToName = {
CRITICAL: "critical",
ERROR: "error",
WARN: "warning",
INFO: "info",
DEBUG: "debug",
TRACE: "trace",
NOTSET: "none",
}
_nameToLev... |
from __future__ import print_function
"""
pie - Python Interactive Executor
Enables a user to execute predefined tasks that may accept parameters and options from the command line without any other required packages.
Great for bootstrapping a development environment, and then interacting with it.
"""
__VERSION__='0.3.0... |
import socket, struct, json
def feed_inputs(server_addr, server_port, gamepad_id, device, keymap_file, server_protocol):
addr = server_addr + ":" + str(server_port)
with open(keymap_file, "r") as kmf:
keymap = json.load(kmf)
print(keymap)
return
if server_protocol == "udp":
sock... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organization', '0003_organization_color'),
]
operations = [
migrations.AddField(
m... |
'''
Defines the link functions to be used with GLM families.
'''
import numpy as np
import scipy.stats
#TODO: are the instance actually "aliases"
# I used this terminology in varfuncs as well -ss
class Link(object):
"""
A generic link function for one-parameter exponential family.
`Link` does nothing, ... |
from .GaussianDistribution import Gaussian
from .BinomialDistribution import Binomial
from .BernoulliDistribution import Bernoulli
from .PoissonDistribution import Poisson
from .ExponentialDistribution import Exponential
from .UniformDistribution import Uniform |
# -*- coding: utf-8 -*-
# For PyCharm to recognize libraries in {% load foo %} there needs to be
# a settings file defined that includes the apps containing the template tags.
INSTALLED_APPS = [
# 'dkforms',
# 'dkdj',
# 'dkdjango',
# 'sekizai',
'django.contrib.staticfiles',
'dkjason',
]
|
# Python Native
from pathlib import Path
from shutil import copy
import glob
import logging
import os
import re
# BDC DB
from bdc_catalog.models import Item
# BDC Scripts
from ...config import Config
from ..models import RadcorActivity
from ..nbar import process_NBAR
from ..utils import load_img
def load_landsat_an... |
#!/usr/bin/env python
# test_green.py - unit test for async wait callback
#
# Copyright (C) 2010-2011 Daniele Varrazzo <daniele.varrazzo@gmail.com>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Fou... |
import RPi.GPIO as GPIO
import time
LED_PIN = 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED_PIN, GPIO.OUT)
try:
while True:
print("LED is on")
GPIO.output(LED_PIN, GPIO.HIGH)
time.sleep(1)
print("LED is off")
GPIO.output(LED_PIN, GPIO.LOW)
time.sleep(1)
except KeyboardInterrupt:
print("Exception: KeyboardInt... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... |
import time, heapq
from itertools import count
import networkx as nx
from pymongo import MongoClient
from Common import MONGO_URL, USER_NODE_PREFIX, BUSINESS_NODE_PREFIX, construct_graph, path_length
def topk_naive2(G, s, R, K):
"""
finds all business in the region and returns an iterator of K shortest path... |
# $Id: io.py 8228 2018-09-09 18:57:00Z grubert $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
I/O classes provide a uniform API for low-level input and output. Subclasses
exist for a variety of input/output mechanisms.
"""
__docformat__ = 'reStructur... |
##########DEPENDENCIES#############
from dronekit import connect,VehicleMode,LocationGlobalRelative,APIException
#import dronekit
import time
import socket
import math
import argparse
from pymavlink import mavutil
import dronekit_sitl
################Outros imports############
import threading
from click import except... |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import requests, sys, bs4
from googlesearch import search
from bs4 import BeautifulSoup
from urllib.request import urlopen
##################
depth = 5
##################
print("fricc")
if len(sys.argv) > 1:
term = ' '.join(sys.argv[1:])
#creates list of... |
"""
SiliconLife Eyeflow
Class for log batch of extracted images from detection
Author: Alex Sobral de Freitas
"""
import os
import json
import datetime
import pytz
import random
import cv2
import importlib
from pymongo import MongoClient
from bson import ObjectId
from eyeflow_sdk.file_access import FileAccess
from... |
# -*- coding: utf-8 -*-
#
# sample documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 16 21:22:43 2012.
#
# 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 ... |
from collections import namedtuple
from dagster import check
from dagster.core.types.runtime.runtime_type import RuntimeType, resolve_to_runtime_type
from .utils import check_valid_name
class InputDefinition(object):
'''Defines an argument to a solid's compute function.
Inputs may flow from previous so... |
import json
with open('sunless.dat', 'w') as f:
for name in ['areas', 'events', 'exchanges', 'personas', 'qualities']:
with open(f'{name}_import.json') as g:
data = json.loads(g.read())
for line in data:
entry = {'key': f'{name}:{line["Id"]}', 'value': li... |
__author__ = 'maartenbreddels'
import logging
import pyarrow as pa
import pyarrow.parquet as pq
import vaex.dataset
import vaex.file.other
from .convert import column_from_arrow_array
logger = logging.getLogger("vaex_arrow")
class DatasetArrow(vaex.dataset.DatasetLocal):
"""Implements storage using arrow"""
... |
#!/usr/bin/env python
import os
import re
import fnmatch
import toml
import collections
from googletrans import Translator
# set the language
# set whether to use google translate or not
lang = "es"
translator = Translator()
# this function does regex match to convert three toml fields into comment fields
def add_c... |
from pathlib import Path
import pandas as pd
from .scrape import get_listings, listings_to_df
from .notify import email, text
LISTINGS_CSV = Path(Path(__file__).parent.parent, 'data', 'csv',
'listings.csv')
URL = r"https://www.ebay.com/sch/i.html?_dcat=261186&_fsrp=1&_from=R40&_armrs=1&_sacat=0&_nkw=andrzej+sapkowsk... |
'''
Created on Jul 26, 2017
@author: Michael Pradel
'''
import math
from os import getcwd
from os.path import join
import sys
import time
import json
from gensim.models import Word2Vec
nb_tokens_in_context = 20
kept_tokens = 10000
embedding_size = 200
class EncodedSequenceReader(object):
def __init__(self, dat... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class UsersConfig(AppConfig):
name = "vbb.users"
verbose_name = _("Users")
def ready(self):
try:
import vbb.users.signals # noqa F401
except ImportError:
pass
|
from enums.enums import MediusEnum, CallbackStatus
from utils import utils
from medius.mediuspackets.channelinforesponse import ChannelInfoResponseSerializer
class ChannelInfoSerializer:
data_dict = [
{'name': 'mediusid', 'n_bytes': 2, 'cast': None},
{'name': 'message_id', 'n_bytes': MediusEnum.MES... |
# -*- coding: utf-8 -*-
# Copyright 2018 New Vecotr Ltd
#
# 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 la... |
"""
This package contains default deserializers. You can override the
deserialization process of a particular type as follows:
``jsons.set_deserializer(custom_deserializer, SomeClass)``
"""
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
from generate import generate
Int32 = "Int32"
Double = "Double"
Boolean = "Boolean"
Int64 = "Int64"
Int16 = "In... |
#copied heavily from "https://pythonprogramming.net/pygame-python-3-part-1-intro/"
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
car_width = 73
block_color = (53, 115, ... |
# Generated by Django 2.0.3 on 2018-03-22 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('restAPI', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='body',
),
... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019-2020 Fortinet, Inc.
#
# 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
# the Free Software Foundation, either version 3 of th... |
import argparse
import sys
import time
import math
import torch.nn as nn
import torch.optim as optim
from drnn import DRNN
from char_rnn.utils import *
from char_rnn.model import DRNN_Char
import warnings
warnings.filterwarnings("ignore") # Suppress the RunTimeWarning on unicode
parser = argparse.ArgumentParser... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sys
from os.path import dirname
sys.path.append(dirname("../src/"))
from PhaseIdentification.common import *
from PhaseIdentification.powerBasedPhaseIdentification import *
from PhaseIdentification.integratedPhaseIdentification import *... |
from web_framework.api.type_parsing import TextTypeAdapter
class IntegerTextAdapter(TextTypeAdapter[int]):
def __init__(self):
super().__init__(int)
def decode(self, data: bytes) -> int:
return int(data.decode())
def encode(self, data: int) -> bytes:
return str(data).encode()
c... |
import json
import boto3
from datetime import datetime
from boto3.dynamodb.conditions import Key
# Get the service resource.
dynamodb = boto3.resource('dynamodb')
#Get Table Objects
Child_Table = dynamodb.Table('Child_Tasks')
#Mark Child Instance As Complete
def CompleteTask(params):
#Parameters
dueDate = p... |
#
# Copyright (C) 2016 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#
import time
import logging
from functools import partial
from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QAction
from... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of feefilter messages."""
from test_framework.mininode import *
from test_framework.te... |
"""
This module contains various utility functions
"""
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str... |
# SPDX-License-Identifier: Apache-2.0
from collections import defaultdict
import inspect
from textwrap import dedent
from typing import Dict, Text, List, Tuple, Type, Sequence, Any
import numpy as np # type: ignore
def process_snippet(op_name: Text, name: Text, export: Any) -> Tuple[Text, Text]:
snippet_name =... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_fontawesome import FontAwesome
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
# from flask_cors import CORS
from config import config
import logging
logging... |
import os
import shutil
import subprocess
from cookiecutter.main import cookiecutter
from pathlib import Path
import click
import yaml
from ctfcli.utils.challenge import (
create_challenge,
lint_challenge,
load_challenge,
load_installed_challenges,
sync_challenge,
)
from ctfcli.utils.config import... |
import numpy as np
from akg.utils import kernel_exec as utils
from tests.common.tensorio import compare_tensor
from tests.common.test_op.col2im_compute import col2im_manual_schedule
from tests.common.gen_random import random_gaussian
def col2im_benchmark(data, kernel, pad, stride, output_H_W):
N, C1, KH, KW, OH,... |
###########################################################################
#
# 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/l... |
"""Plot rewards vs. norms.
Attributes
----------
EXAMPLE_USAGE : str
Example call to the function, which is
::
python ./visualizer_rllib.py /tmp/ray/result_dir 1
parser : ArgumentParser
Command-line argument parser
"""
import argparse
import gym
import numpy as np
import os
imp... |
from flask import request
from flask_restx import Resource
from flask_babel import gettext
from modules.LoginModule.LoginModule import LoginModule
from modules.FlaskModule.FlaskModule import service_api_ns as api
from opentera.db.models.TeraParticipant import TeraParticipant
from modules.DatabaseModule.DBManager import... |
""" Constant variables used by this library """
DOMAIN = "rgw.5878-e94b1c46.eu-gb.apiconnect.appdomain.cloud"
ROOT = "metoffice/production/1.0.0"
|
import time
from django.conf import settings
def attach_ex(code, data):
"""
New version of attach for new protocol, simplified
@param code: Unique phone code
@type code: str
@param data: Dictionary data for the phone, passed from client in the 'data' request field
@type data: dict
"""
... |
"""Support for getting the service banner of a web server."""
import requests
import urllib3
from remediar.helper import Check
urllib3.disable_warnings()
class CheckHttpIsPoweredPresent(Check):
"""Representation of a HTTP banner check."""
def __init__(self, server, **kwargs):
"""Initialize the chec... |
from api.modules.systems.auth import Login, Logout, Refresh, Check
from api.modules.systems.menus import Side_navigation_menu, Customize_menu, Bookmarks_menu
from api.modules.serve.serve import Serve_static, Default
def register_routes(api):
# Serving static files
default = [
'/',
'/login'
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import ast
from dataframe_expressions.utils_ast import CloningNodeTransformer
from typing import Optional
import pytest
from dataframe_expressions import (
DataFrame, ast_Callable, ast_DataFrame, ast_Filter, render, render_context,
render_callable)
def test_render_easy():
d = DataFrame()
expr, _ = r... |
# Seesar Sifer :)
def encrypt(text, shf):
text = str(text)
shf = int(shf)
r = ''
for i in text:
if (ord(i) >= 97 and ord(i) <= 122):
r += chr(((ord(i) + shf - 97) % 26) + 97)
elif (ord(i) >= 65 and ord(i) <= 90):
r += chr(((ord(i) + shf - 65) % 26) + 65)
else:
r += i
return r
def decrypt(text, sh... |
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from symposion.conference.models import Section
from symposion.schedule.models import (
Presentation,
Slot,
SlotKind,
Schedule,
Day,
)
from symposion.proposals.models import ProposalKind
from symposi... |
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
## Find_moveo ##
from UM.Mesh.MeshData import MeshData
from cura.Scene.CuraSceneNode import CuraSceneNode
from cura.Settings.ExtruderManager import ExtruderManager
from UM.Application import Application #To modify the maxim... |
from django.contrib.messages.storage.base import LEVEL_TAGS
from factory import SubFactory, Faker, RelatedFactory
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyChoice
from demo.user_factories import UserFactory
from drf_messages.models import Message, MessageTag
class MessageTagFactory... |
"""Logging utilities."""
import asyncio
from asyncio.events import AbstractEventLoop
from functools import partial, wraps
import inspect
import logging
import threading
import traceback
from typing import Any, Callable, Coroutine, Optional
from .async_ import run_coroutine_threadsafe
class HideSensitiveDataFilter(lo... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2016, 2017, 2018
# --------------------------------------------------------------------------
# Generated... |
import os
def generate_file_path(input_file_path: str, file_extension: str, output_file_path: str = None) -> str:
"""
Generate file path given given some input parameters.
:param input_file_path: Input file path to use as a base for generate the output.
:param file_extension: Output file extension.
... |
# flake8: noqa: F401
from .initialize import Initialize
|
import ctypes
import faulthandler
import io
import itertools
import logging
import multiprocessing
import os
import pickle
import sys
import textwrap
import unittest
from importlib import import_module
from io import StringIO
from django.core.management import call_command
from django.db import connections
from django... |
from multiprocessing import Process
from datetime import datetime
from zdiscord.util.general.Agent import Agent
# Represents a currently running agent process
class AgentProcess:
def __init__(self, ttl: int = 1800):
# Default 30 minutes as time to live
self.time_to_live_seconds: int = ttl
self.spin_up_... |
"""www 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')
Class-based vie... |
from cryptography.fernet import Fernet
import json
import cryptocode
key = Fernet.generate_key()
fernet = Fernet(key)
def savecred(username, fullname):
savefile = open('credentials.dat', 'w')
tempdict = {"username": username, "name": fullname}
tempstring = str(tempdict)
encoded = cryptocode.encrypt(... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.15.7
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class V2beta2Res... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
from HelperFuncs import *
class LinkedInJob:
def __init__(self, ID, posting):
self.id = ID
self.posting = posting
self.platform = "LinkedIn"
self.setTitle()
self.setCompany()
if not checkJobsToIgnore(self):
self.valid = False
... |
import json
import numpy as np
def pack(request):
data = request.get_json()
furniture = data['furniture']
orientations = []
'''
Test TEST TTEESSTT
'''
##################################################################
####### Preliminary Functions
##############... |
"""empty message
Revision ID: 5674286baf3e
Revises: 356a0effa031
Create Date: 2017-08-21 13:34:38.213253
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5674286baf3e'
down_revision = '356a0effa031'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# Copyright 2019 Alibaba Cloud 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 la... |
print("Mary had a little lamb.")
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("." * 10) # what'd that do?
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch thar comma at th... |
import tensorflow as tf
from kerastuner.engine import hyperparameters as hp_module
from tensorflow.python.util import nest
from autokeras.hypermodel import block
from autokeras.hypermodel import graph
from autokeras.hypermodel import hyperblock
from autokeras.hypermodel import node
def assemble(inputs, outputs, data... |
import functools
import generic
from abc import ABCMeta, abstractmethod
from typing import Tuple, List, Optional, Generator
from enum import Enum
class CheckStatus(Enum):
OK = 1
WARNING = 2
CRITICAL = 3
def combine_statuses_and(s1: CheckStatus, s2: CheckStatus):
if s1 == CheckStatus.CRITICAL or s2 ==... |
"""
Provides metadata version information.
"""
# This file is auto-generated! Do not edit!
# Use `python -m incremental.update metadata` to change this file.
from incremental import Version
__version__ = Version("metadata", 0, 9, 0, dev=6)
__all__ = ["__version__"]
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
Copyright (c) 2018-2021 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 in wri... |
# Generated by Django 1.9.12 on 2017-02-21 08:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('formidable', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='access',
name='display',
),
... |
from django.apps import AppConfig
class CommonAppConfig(AppConfig):
name = "cctool.common"
verbose_name = "Common"
def ready(self):
try:
import common.signals # noqa F401
except ImportError:
pass
|
from zerver.lib.test_classes import WebhookTestCase
class TaigaHookTests(WebhookTestCase):
STREAM_NAME = "taiga"
TOPIC = "subject"
URL_TEMPLATE = "/api/v1/external/taiga?stream={stream}&api_key={api_key}"
WEBHOOK_DIR_NAME = "taiga"
def setUp(self) -> None:
super().setUp()
self.url... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... |
#!/usr/bin/env python3
# ------------------------------------------------------------------------------
#
# Copyright 2021 Fetch.AI Limited
#
# 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 Licens... |
#!/usr/bin/env python
# usage ./refresh_token.py {auth-server client secret} {current keycloak grant}
import sys
import base64
import json
import jwt
import time
import requests
import os
auth_server_client_secret = sys.argv[1]
grant_raw = base64.standard_b64decode(sys.argv[2])
grant = json.loads(grant_raw)
access... |
# Our main gamedata class.
from src.static import *
from src.player import Player
from src.dungeon import Dungeon
import pygame
class GameData(object):
def __init__ (self):
self.running = True
self.updatePositions = True
self.acceptInput = True
self.currentRoomsPos = (1, 2) # Magic ... |
_base_ = [
'../_base_/models/deeplabv3plus_r50-d16.py',
'../_base_/datasets/cityscapes_custom.py',
'../_base_/default_runtime.py',
'../_base_/schedules/schedule_80k.py'
]
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='ParallelEncoderDecoder',
pretrained='open-mmlab://resn... |
import tkinter as tk
from tkinter.constants import BOTH, FLAT
import tkinter.font as tkFont
import os
COMMANDS = {'cmd': 'start cmd',
'chrome': 'start chrome',
'browser': 'start chrome',
'music': 'start spotify',
'spotify': 'start spotify',
'discord': 'start ... |
import argparse
import logging
import os
import pwd
import sys
import traceback
import psycopg2
from . import log
from .config import load_config
from .errors import GitlabArtifactsError
from .gitaly import GitalyClient
from .projects import list_projects, projects_from_paths
from .artifacts import list_artifacts, re... |
# coding: utf-8
from .echarts_plot import kline_pro, heat_map
from .kline_generator import KlineGeneratorBy1Min, KlineGeneratorByTick
from .ta import KDJ, MACD, EMA, SMA
|
from subprocess import call
from tempfile import NamedTemporaryFile
from jinja2 import Environment, BaseLoader, PackageLoader
from axju.generic.execution import ExecutionWorker
class TemplateWorker(ExecutionWorker):
"""This worker can work with steps like:
{
'info': '....',
'template': 'templa... |
import eodslib
import os
from pathlib import Path
import pytest
import os
@pytest.mark.skip_real()
def test_create(set_output_dir, modify_id_list, unique_run_string):
output_dir = set_output_dir
conn = {
'domain': os.getenv("HOST"),
'username': os.getenv("API_USER"),
'access_token': os.... |
#
# Copyright 2017, Couchbase, 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 l... |
# ///////////////////////////////////////////////////////////////
#
# BY: WANDERSON M.PIMENTA
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any information in the visual
# interface ... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class CreateGaussMySqlInstanceRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (d... |
import unittest
from six import text_type, u, b, PY2, PY3
from nose.tools import raises
from expects import *
import httpretty
import textwrap
import json
import datetime
import pytz
from .validate_jwt import validate_jwt_header
from opentok import (
OpenTok,
Archive,
ArchiveList,
OutputModes,
Open... |
from __future__ import print_function
import qt
import shutil
import sys
import os
import time
from constants import *
def adjustPower(DR, k, delta):
pw = DR + 10*np.log10(1+4*(delta**2)/(k**2))
if pw >=13:
return 13
else:
return pw
def generate_meta_file():
metafile = open('%s.meta.txt... |
# aion/reservations/deep_fried_forms.py
from crispy_forms.layout import LayoutObject, Layout, ButtonHolder, Submit, HTML, Field
from crispy_forms.utils import TEMPLATE_PACK
from django import forms
from captcha.fields import CaptchaField
class DeepFriedForm(LayoutObject):
'''Custom crispy layout object.
T... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'zh-tw',
'!langname!': '台灣中文',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%... |
# 扫描此局域网的所有IP地址
import platform
import os
import time
import _thread
def get_os():
os = platform.system()
if os == 'Windows':
return 'n'
else:
return 'c'
def ping_ip(ip_str):
cmd = ['ping','-{op}'.format(op=get_os()),'1',ip_str]
output = os.popen(' '.join(cmd)).readlines()
for line in list(outpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.