content stringlengths 5 1.05M |
|---|
""" oslockedaction.py implements "one-at-a-time" process execution by creating
a lock file during execution of a method.
(c) 2007 Scott Stafford
"""
class LockFileExists(RuntimeError): pass
class OSLockedAction:
def __init__(self, target, args = (), kwargs = {}, lockfile = None, timeoutDelay = 7.0, retryPeriod... |
# Generated by Django 3.0.3 on 2020-09-08 19:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog_app', '0022_fileadmin'),
]
operations = [
migrations.AlterField(
model_name='fileadmin',
name='fileupload',
... |
""" https://www.dndbeyond.com/monsters/orc"""
import unittest
import colors
from pycs.arena import Arena
from pycs.gear import Javelin
from pycs.gear import Hide
from pycs.gear import Greataxe
from pycs.constant import MonsterType
from pycs.monster import Monster
######################################################... |
import pytest
class TestProxy:
# Test our the core proxying behavior and our additions to it
def test_we_can_proxy_a_page(self, proxied_content):
assert "upstream content" in proxied_content
def test_client_embed_is_in_the_page(self, proxied_content):
assert (
'embed_script.s... |
from django.apps import AppConfig
class FoodmaxConfig(AppConfig):
name = 'FoodMax'
|
__version__ = "0.17.3" |
from django.views.generic import TemplateView
class XmlView(TemplateView):
content_type = 'text/xml'
template_name = 'p3p/p3p.xml'
class P3PView(TemplateView):
content_type = 'text/xml'
template_name = 'p3p/policy.p3p'
|
# https://leetcode.com/problems/longest-substring-without-repeating-characters
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
lss = set()
rv = 0
i = j = 0
while i < len(s):
if s[i] not in lss:
lss.add(s[i])
rv = max(r... |
import sys,os,re
import MySQLdb
import config
import argparse
from neo4j.v1 import GraphDatabase,basic_auth
#takes arguement of user id and article set name
#neo4j
auth_token = basic_auth(config.user, config.password)
driver = GraphDatabase.driver("bolt://"+config.server+":"+config.port,auth=auth_token)
session = dri... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Eric Radman <ericshane@eradman.com>
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.unit import skipIf, TestCase
from tests.support.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON,
)
# I... |
'''
Create sample files to move
Created on Aug 30, 2018
@author: bhoff
'''
import synapseclient
import argparse
import json
import os
import tempfile
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
if __name__ == '_... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup
from setuptools import find_packages
from setuptools.command.develop import develop as _develop
from setupto... |
import pickle
import random # for shuffling the dataset at the start of an epoch
"""
This version of the NN can also create arbitrary architectures, using the Relu activation and Dropout for
regularization.
"""
# Import SHVN DATASET
with open("Datasets/processed/pickled_shvt_full_data.pkl", "br") as fh:
... |
from datetime import datetime, date
from django.test import TestCase
from robber import expect
import pytz
from officers.indexers import OfficerCoaccusalsIndexer
from data.factories import AllegationFactory, OfficerFactory, OfficerAllegationFactory
class OfficerCoaccusalsIndexerTestCase(TestCase):
def extract_... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import datetime
import re
import md5 # imports the md5 module to generate a hash
app = Flask(__name__)
app.secret_key = "ThisIsSecret!"
mysql = MySQLConnector(app,'project_board_db')
EMAIL_REGEX = re... |
# Copyright (c) 2016-2017 Haggai Eran, Gabi Malka, Lior Zeno, Maroun Tork
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright not... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
from python_ne.core.model_adapters.model_adapter import ModelAdapter
from python_ne.core.model_adapters.default_dense_layer_adapter import DefaultDenseLayerAdapter
from python_ne.core.neural_network import activations
from python_ne.core.neural_network.dense_layer import DenseLayer
from python_ne.core.neural_network.ne... |
import os, datetime, sys, argparse
import cv2
import numpy as np
import json
import time
import tensorflow as tf
from builder import ModelBuilder
print(tf.__version__)
if tf.__version__ == '1.14.0':
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
tf_config... |
import traceback
from fastapi import status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import HTTPException, RequestValidationError
from loguru import logger
from starlette.responses import JSONResponse, Response
from contaxy.config import settings
from contaxy.schema.auth import OAuth2Erro... |
import random
from alttprbot.database import srl_nick_verification, srlnick
from alttprbot_srl.bot import srlbot
async def send_key(discord_user_id, srl_nick):
nickinfo = await get_irc_user(srl_nick)
if nickinfo is None:
return False
key = random.randint(0, 999999999999999999)
await srl_nic... |
from django.urls import path, include
app_name = "metadata"
urlpatterns = [
path('', include("cotidia.metadata.urls.admin.metadata")),
]
|
import asyncio
from unittest.mock import MagicMock
class AsyncMock(MagicMock):
"""
..deprecated:: 0.45
Use: :class:`MagicMock` with meth:`~.async_return_value`.
"""
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
def coroutine_mock():
... |
# generated by appcreator
from django.conf.urls import url
from . import dal_views
app_name = 'gn_places'
urlpatterns = [
url(
r'^geonamesplace-autocomplete/$',
dal_views.GeoNamesPlaceAC.as_view(),
name='geonamesplace-autocomplete'
),
]
|
#!/bin/env python
import logging
import os
from vc3remotemanager.ssh import SSHManager
from vc3remotemanager.gsissh import GSISSHManager
from vc3remotemanager.cluster import Cluster
from vc3remotemanager.bosco import Bosco
# Added to support running module as script from arbitrary location.
from os.path import dirna... |
'''Convert items list to split lists based on type.
Use Python 3.
'''
import argparse
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('input_file')
arg_parser.add_argument('output_file_prefix')
args = arg_parser.parse_args()
files = {}
for line in sorted(... |
"""Contains class used to represent a Task State that integrates with Step Functions"""
from typing import Dict, Set
from fluxio_parser.states.tasks.base import TaskState
class StateMachineTaskState(TaskState):
"""Task state for executing a nested State Machine.
This currently only supports the sync invocat... |
def print_row(star_count):
for _ in range(star_count, size - 1):
print(' ', end='')
for _ in range(star_count):
print('*', end=' ')
print('*')
size = int(input())
for star_count in range(size):
print_row(star_count)
for star_count in range(size - 2, -1, -1):
print_row(star_count... |
#!/usr/bin/env python3
C_MAJOR = [60, 62, 64, 65, 67, 69, 71, 72]
CS_MAJOR = [61, 63, 65, 66, 68, 70, 72, 73]
D_MAJOR = [62, 64, 66, 67, 69, 71, 73, 74]
DS_MAJOR = [63, 65, 67, 68, 70, 72, 74, 75]
E_MAJOR = [64, 66, 68, 69, 71, 73, 75, 76]
F_MAJOR = [65, 67, 69, 70, 72, 74, 76, 77]
FS_MAJOR = [66, 68, 70, 71, 73, 75, ... |
from extensions.base.burpextensionapi import BurpExtensionApi
class ProxyListener(BurpExtensionApi):
NAME = 'some proxy listener (changeme)'
def __init__(self):
super().__init__()
self.register_target_url_path = '/register/proxylistener'
self._process_msg_callback_url = self._build_c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Main script to launch the GUI."""
from __future__ import absolute_import
from dnazip.interface import Interface
def main() -> None:
"""Launches the GUI."""
GUI = Interface()
GUI.main()
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
import requests
import scrapy
from scrapinghub import ScrapinghubClient
API_KEY = '11befd9da9304fecb83dfa114d1926e9'
PROJECT_ID = '252342'
class JavdetailSpider(scrapy.Spider):
name = 'javdetail'
start_urls = []
def __init__(self):
client = ScrapinghubClient(API_KEY, use... |
# Derive the inertia of a uniform density torus
from sympy import Matrix, symbols, collect, integrate, pi
from pydy import *
Int = integrate
a, b, c, r1, r2, rho, m = symbols('a b c r1 r2 rho m')
# Volume of a torus
V = 2*pi**2*r1*r2**2
# A is the frame fixed in the torus, think of these as the global coordinates
# A... |
import requests
import random
from .comic import Comic
class XKCDFetcher:
def get_comic_by_id(self, comic_id: int) -> Comic:
"""returns a Comic object of an xkcd comic given its id"""
response = requests.get(f"https://xkcd.com/{comic_id}/info.0.json")
if response.status_code != 200:
# xkcd API did not retur... |
#
# Generated with RollerBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.namedobject import NamedObjectBlueprint
class Rol... |
import json
from django import template
from django.conf import settings
from django.urls import reverse
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def js_config_object(context):
# When adding stuff here, don't forget to update the corre... |
import torch.nn.functional as F
from . import BaseTask, register_task
from ..dataset import build_dataset
from ..utils import Evaluator
@register_task("recommendation")
class Recommendation(BaseTask):
"""Recommendation tasks."""
def __init__(self, args):
super(Recommendation, self).__init__()
... |
# Copyright 2015 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 ... |
from abc import ABC, abstractmethod
from typing import List, Dict, Type, Union, Optional
from airflow import LoggingMixin
from airflow.models import BaseOperator
from openlineage.facet import BaseFacet
from marquez.dataset import Dataset
class StepMetadata:
def __init__(
self,
name,
... |
# ! /usr/bin/python
# -*- coding: utf-8 -*-
# =============================================================================
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... |
#!/usr/bin/python
#-*- coding: UTF-8 -*-
'''
STUN(RFC5389) client demo by Chris <nodexy@gmail>
USAGE:
\t%s <STUN_server_ip> [STUN_server_port | 3478] [ <local_ip> <local_port | 7878>]
'''
#
# 2012-2-25 AT Shenzhen, China
# 2012-2-27 version 0.1
#
# TODO:
# - send binging request again
#
## parse CLI
from s... |
#---------------------------------------------------------------------------------
# Lambda function to migrate existing customers from Transit VPC to Transit Gateway
# Version: 1.0
#---------------------------------------------------------------------------------
from botocore.client import Config
from xml.dom import... |
"""
Constants used in protocol design, specification, and checking
:copyright: 2020 by The Autoprotocol Development Team, see AUTHORS
for more details.
:license: BSD, see LICENSE for more details
"""
from .unit import Unit
SBS_FORMAT_SHAPES = {
"SBS24": {"rows": 4, "columns": 6},
"SBS96": {"r... |
# Generated by Django 3.0.6 on 2020-05-30 07:37
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('server', '0009_auto_20200425_1231'),
]
operations = [
migrations.AlterField(
model_name='predictio... |
from __future__ import absolute_import
from contextlib import contextmanager
import zlib
import io
import logging
from socket import timeout as SocketTimeout
from socket import error as SocketError
try:
import brotli
except ImportError:
brotli = None
import h11
from .._collections import HTTPHeaderDict
from ... |
import json
import random
import logging
import spacy
import sys
import re
import tqdm
import glob
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
import g... |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
import os
from graph_notebook.authentication.iam_credentials_provider.credentials_provider import CredentialsProviderBase, \
Credentials
ACCESS_ENV_KEY = 'AWS_ACCESS_KEY_ID'
SECRET_ENV_KEY = 'AWS_SECRET... |
from unittest import TestCase
import pandas as pd
from core.conditional_index import ConditionalIndex
from core.interaction_index import InteractionIndex
from core.interaction_mapper import InteractionMapper
import numpy as np
class TestInteractionIndex(TestCase):
def test_knn_interaction_query(self):
im... |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.models.opload.opload_integration_test.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Class for testing operating load integrations."""
# Thir... |
# import gevent.monkey
# gevent.monkey.patch_socket()
from pyEtherCAT import MasterEtherCAT
import time
import os
#============================================================================#
# C95用の簡易EtherCATパッケージです。
# 本来は細かいパケットに付いて理解を深めた上で仕組みを構築していきますが、
# 説明も実験も追いつかず、ひとまずGPIOで高速にON/OFF出来る部分だけを纏めました。
# 動作は Linux(R... |
def prefix_sums(a):
n = len(a)
p = [0]*(n + 1)
print(p, n)
for k in range(1, n + 1):
p[k] = p[k - 1] + a[k - 1]
return p
a_list = [4, 2, 2, 5, 1, 5, 8]
print(prefix_sums(a_list))
|
# Generated by Django 3.2.13 on 2022-04-27 18:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("core", "0001_initial"),
]
operations = [
migrations.DeleteModel(
name="DateRangeTest",
),
migrations.DeleteModel(
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.tools.translate import _
from odoo.exceptions import UserError
class HrTimesheetSheet(models.Model):
_inherit = "hr_timesheet_sheet.sheet"
attendances_ids = field... |
#
# Test module for seqgibbs.
#
# This file is part of SEQGIBBS
# (https://github.com/I-Bouros/seqgibbs.git) which is released
# under the MIT license. See accompanying LICENSE for copyright
# notice and full license details.
#
# To run all tests, use ``python -m unittest discover``.
#
# To run a particular test, use e... |
import json
import sqlite3
from sql.queries import GetMsr
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from simulation.constants import R_E_ND, R_M_ND, MU_EARTH_MOON
from simulation.stations import CR3BPEarthStn
def draw_sphere(ax, radius, center, color, mesh=False):
... |
"""Provides OSS compatibility layer with internal FB macros."""
def fb_xplat_cxx_library(name, **kwargs):
"""Compatibility adapter for internal FB cxx_library macros."""
# Prune values specific to fb code
if "allow_jni_merging" in kwargs:
kwargs.pop("allow_jni_merging")
# Add standard if none... |
class Solution:
def count(self, S, m, n):
# Initialize the DP table
table = [[0 for _ in range(n+1)] for _ in range(m+1)]
# Initialize the first column to 1's
for i in range(m+1) :
table[i][0] = 1
for i in range(1, m+1) :
for j in range(1, n+1) :
... |
# Kroftig backend kroftig/git_utils.py
#
# Copyright © 2017 Sean Bolton.
#
# 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 us... |
import os
from tfplus.utils import cmd_args, OptionBase, Factory, BatchIterator
_factory = None
def get_factory():
global _factory
if _factory is None:
_factory = Factory()
pass
return _factory
def register(name, cls):
return get_factory().register(name, cls)
def create(_clsname,... |
from tradesys.client import TradingSystem
# Import Dataset Models.
from azure.mgmt.datafactory.models import DataFlowSink
from azure.mgmt.datafactory.models import DatasetFolder
from azure.mgmt.datafactory.models import DataFlowSource
from azure.mgmt.datafactory.models import MappingDataFlow
from azure.mgmt.datafactor... |
import numpy as np
import matplotlib.pyplot as plt
import h5py as py
hdf5_file = py.File("..\\Build\\TestsWithGL\\t2d_mpm_chm_t_bar_conference_geo - grid.hdf5", "r")
frame_id = 100
inv_num = 10
frame_dset = hdf5_file['TimeHistory']['geostatic']['frame_%d' % frame_id]['ParticleData']
node_id = []
variables = []
node_... |
import os
import SimpleITK as sitk
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn.functional as F
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import Module, Conv3d, ConvTranspose3d, Linear, ReLU, Seque... |
##########################################################################
# CAPSUL - Copyright (C) CEA, 2013
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
########... |
import requests
import sys
def main():
url = "http://ip-api.com/json/"
if len(sys.argv) > 1:
# getting address from command line.
address = ''.join(sys.argv[1:])
url += address
response = requests.request("GET", url)
response = response.json()
if response['status'] == 'fa... |
#!/usr/bin/env python
from model1 import *
def model2_train_f2e(bitext, opts):
q = defaultdict(float)
t = model1_train_f2e(bitext, opts)
for ff, ee in bitext:
l, m = len(ee), len(ff)
for j, e in enumerate(ee):
for i, f in enumerate(ff):
#q[(j, i, l, m)] = rando... |
{
"targets": [
{
"target_name" : "yuv",
'include_dirs': [
"<!(node -p \"require('node-addon-api').include_dir\")",
"external/libyuv/include"
],
'sources' : [
"src/init.cc",
"src/version.cc",
... |
class ModelEvaluator:
pass |
from flask import Flask, request, abort
from flask_cors import CORS
import json
app = Flask(__name__)
CORS(app)
oui_json = {}
with open('oui.json', 'r') as fp:
oui_json = json.load(fp)
@app.route("/apiv3/hwaddress/search/<hwaddr>")
def hwaddr_search(hwaddr):
referrer = request.headers.get("Referer")
if ... |
"""
Various shapes for arcade games.
"""
# pylint: disable=too-many-arguments, too-many-locals, too-few-public-methods
from arcade.color import GREEN
from arcade.draw_commands import draw_rectangle_filled
from arcade.draw_commands import draw_ellipse_filled
from arcade.draw_commands import draw_circle_filled
from ar... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scikitplot.metrics import plot_roc, plot_precision_recall
from sklearn.metrics import (f1_score, precision_score, average_precision_score, roc_auc_score,
classification_report, accuracy_score, make_scorer, recall_s... |
from collections import abc as ca
from collections import defaultdict
from typing import (
Any,
AnyStr,
ByteString,
Container,
DefaultDict,
Dict,
Iterable,
List,
Mapping,
Optional,
Sequence,
Set,
Text,
Type,
Union,
cast,
overload,
)
import attr
from ... |
import os, time, json, sys, gc
import numpy as np
import nltk, pandas
import torch
from scipy.sparse import csr_matrix, lil_matrix, save_npz, load_npz
from torch_geometric.data import Data, DataLoader, GraphSAINTRandomWalkSampler, GraphSAINTNodeSampler, GraphSAINTEdgeSampler
from torch_geometric.data.cluster import Clu... |
import datetime
import json
import logging
import re
from html import unescape
from typing import Union, List
from urllib.parse import quote
from Crypto.Util import Padding
from .exceptions import IncorrectJson
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
def _get_l(d): return d['L']
class Util:... |
#!/usr/bin/python
"""Radiative transfer solver using the Toon matrix method.
Here the ice/impurity optical properties and illumination conditions
are used to calculate energy fluxes between the ice, atmosphere and
underlying substrate.
Typically this function would be called from snicar_driver() because
it takes as i... |
from django.db import models
class Applications_Index_Cards(models.Model):
"""The Django Database Model for HTML Cards meant to be displayed on the App
Index Page.
This class contains all the fields that contain the data necessary to construct
an html bootstrap card on the front-end using Django's te... |
"""
molecool
A python package for analyzing and visualizing pdb and xyz files. For MolSSI May webinar series.
"""
# Add imports: here (.) is look in same directory
# import everything = * : bad practice since imports libraries like np
from .functions import *
from .molecule import build_bond_list, calculate_molecular_... |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import os
import cv2
import random
def makaPoisonData(csv_file):
data = np.loadtxt(csv_file,dtype='str')
data = np.delete(data, [0,3], 1)
random.seed(0)
normal = []
pneumonia = []
covid19 = []
poison_label = [1]*219 ... |
"""
Colorizers
A set of functions to apply colorization to a graphable dataset.
"""
from MLVisualizationTools.backend import GraphData
from MLVisualizationTools.types import ColorizerModes
from typing import Optional
import warnings
def _valid_colorization_call(data: GraphData, colorkey: str, apply_to_model: bool, a... |
import gym
import unittest
import numpy as np
from connect_four.evaluation.victor.rules.highinverse import HighinverseManager, HighinverseColumn, \
highinverses_given_column
from connect_four.game import Square
from connect_four.evaluation.board import Board
from connect_four.evaluation.victor.rules import Highi... |
'''
Description:
Implementation of GoBang rules (e.g. win rules)
Author:
Jingkai Zhang (jz544@cornell.edu)
Version:
1.0
Update history:
1.0 -Add basic judging rules
Last modified:
2021.11.4 -add basic content
'''
# from GoBang.Config import * # get all th... |
"""Define 2FA tests."""
# pylint: disable=unused-argument
import aiohttp
import pytest
from simplipy.api import API, AuthStates
from simplipy.errors import InvalidCredentialsError, Verify2FAError, Verify2FAPending
from .common import TEST_PASSWORD, TEST_SMS_CODE, TEST_USERNAME
@pytest.mark.asyncio
async def test_2f... |
import json
data = '''
[
{
"name":"Alena",
"count":100
},
{
"name":"Levon",
"count":97
},
{
"name":"Shakira",
"count":96
},
{
"name":"Keerah",
"count":95
},
{
"name":"Anesu",
"count":92
},
{
"name":"Zishan",
... |
# -*- coding: utf-8 -*-
from graphene import Field, ObjectType
from graphene_django.debug import DjangoDebug
from .recipes.mutations import RecipesMutation
from .users.mutations import UsersMutation
class Mutation(ObjectType, RecipesMutation, UsersMutation):
debug = Field(DjangoDebug, name='__debug')
|
import pkg_resources
import pytest
import sys
import time
import unittest
from unittest import mock
from kinto_http.session import Session, create_session
from kinto_http.exceptions import KintoException, BackoffException
from kinto_http.session import USER_AGENT
from .support import get_200, get_503, get_403, get_htt... |
import tkinter as tk
from tkinter import filedialog
import numpy as np
import cv2
import matplotlib
root = tk.Tk()
root.title('Triumvirate')
frame = tk.Frame(root)
frame.pack()
def giveFile():
filename = filedialog.askopenfilename(initialdir=".",title="Choose a picture",filetypes=(("JPG","*.jpg"),("JPEG","*.jpe... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# author:张江
from django.conf.urls import url
from . import views
# 添加命名空间
app_name = 'polls' #关键的是这行
urlpatterns = [
# url都有四个参数
# 参数1:描述匹配的字符串或者url
# 参数2:view指当前处理url请求的视图函数
# 参数3:kwargs 任意数量的关键字参数可以作为一个字典传递给目标视图
# 参数4:name对url命名,在模板内部显式的引用它,反向解析的... |
"""Spam cleanup command module for Zinnia"""
from django.contrib import comments
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import NoArgsCommand
from zinnia.models.entry import Entry
class Command(NoArgsCommand):
"""
Command object for removing comments
ma... |
import sys
from os import getenv
from typing import List
def parse_input() -> (list, int, bool, str, str):
args: List[str] = sys.argv
if len(args) != 5:
input_string = ' '.join(args)
expected_string = f'{args[0]} ignore_branches last_commit_age_days dry_run_yes_no'
raise RuntimeError(... |
"Alcance global"
productos = []
ventas = []
def ingresar_productos():
"Alcance local"
menu_secundario = """
Desea usted agregar un producto??
(1) agregar
(2) VOLVER
"""
opcion = 0
while opcion != 2 :
print(menu_secundario)
opcion = int(input("Seleccione una opcion "))
... |
import unittest
import logging
from testfixtures import LogCapture
from logger import get_logger
class TestLogger(unittest.TestCase):
def test_get_logger(self):
logger = get_logger('LOG NAME', logging.DEBUG)
INP = [
"some debug",
"some info",
"MY MESSAGE",
... |
import cv2
import numpy as np
import tensorflow as tf
from utils import ssd_utils, textboxes_utils, one_hot_class_label, augmentation_utils
from time import time
class TBPP_DATA_GENERATOR(tf.keras.utils.Sequence):
""""""
def __init__(
self,
samples,
config,
shuffle,
ba... |
# -*- coding: utf-8 -*-
"""
HTTP agent logic
~~~~~~~~~~~~~~~~
:author: Sam Gammon <sg@samgammon.com>
:copyright: (c) Sam Gammon, 2014
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
the root of the project.
"... |
from atados_core.models import (Nonprofit, Volunteer, Project, Availability, Cause,
Skill, State, City, Address, Work, Role,
Apply, Recommendation, Job, User, Subscription)
from rest_framework import serializers
class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
f... |
import fnmatch
import os
import stringmanipulation
def fileexist( file_name ):
return os.path.isfile(file_name)
def pathexist( path ):
return os.path.exists(path)
def fixpath( path ):
return_value = path
if( return_value[len(return_value) - 1] != '/'):
return_value = return_value + '/'
re... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
from scrapy.http import Response
import random
import logging
logger = logging.getLogger(__name__)
class RandomUserAgentMid... |
# Yılan duvarın içine geçiyor kendi üzerinde yem oluşuyor .
# batch_size 500 dene
# her ilk hareket random
# Highscore grafiği
# Her Skorda kaç adım atmış pie grafiği ya da heatmap grafiği dot grafiğin alternatifi
# Keras plot model loss (https://machinelearningmastery.com/display-deep-learning-model-training-hist... |
import datetime
from typing import List
import requests
from src.settings import POCKET_URL, ACCESS_TOKEN, CONSUMER_KEY
def get_articles(days: int = 7) -> List:
pocket_url = '{}?consumer_key={}&access_token={}'.format(POCKET_URL, CONSUMER_KEY, ACCESS_TOKEN)
ts = (datetime.datetime.now() - datetime.timedelta... |
from pinax.badges.base import Badge as BadgeBase
from pinax.badges.base import BadgeAwarded
from pinax.badges.registry import badges
from lib.brabeion_utils import BadgeDetail
class MinionBadge(BadgeBase):
slug = "minion"
levels = [BadgeDetail("Teerace Minion", "Teerace staff member", 200)]
events = ["lo... |
"""Defines built-in attribute summarizers."""
from deepmatcher.models.core import AttrSummarizer
from deepmatcher.models.word_comparators import Attention as ComparatorAttention
class SIF(AttrSummarizer):
"""The attribute summarizer for the SIF (Smooth Inverse Frequency) model.
Args:
word_contextual... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.