content stringlengths 5 1.05M |
|---|
import os
from glob import glob
from typing import List, Tuple
import albumentations as A
import cv2
import numpy as np
import torch
import torch.utils.data as data
from albumentations.pytorch import ToTensorV2 as ToTensor
class Transform:
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
def __init__(self, ... |
"""
448. 找到所有数组中消失的数字
"""
def findDisappearedNumbers(nums):
n = len(nums)
for v in nums:
t = (v - 1) % n
nums[t] += n
res = [x+1 for x in range(n) if nums[x] <= n]
return res
print(findDisappearedNumbers([4,3,2,7,8,2,3,1])) # [5, 6]
"""
442. 数组中重复的数据
"""
def findDuplicates(nums):
... |
def alive(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("Yes", "utf-8"))
def bad_request(self, error):
self.send_response(400)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(byt... |
import falcon
import os
from wsgiref import simple_server
from peach import WebHandler
def int_to_falcon_status(status):
http_code_name = "HTTP_{}".format(int(status))
return getattr(falcon, http_code_name)
class FalconHandler(WebHandler):
def __init__(self, api_factory=None):
from .api import ... |
print('='*20)
pt = int(input('Primeiro termo: '))
r = int(input('Razão: '))
"""décimo = pt + (10 - 1) * r"""
for c in range(pt, pt + (r*10), r):
print('{}'.format(c), end=' -> ')
print('ACABOU')
|
inventario = {
'itens': {'hp_potion': {5}, 'flechas': {21}, 'tomo_feitico-fireball': {1}},
'armas': {'principal': {'Espada de Aço Forjado (Ótimo)'}, 'secundaria': {'Adaga de Aço Polido'}, 'ranged': {'Arco de Caça Reforçado'}},
'armadura': {'cabeca': {'Elmo de Aço (Ótimo)'}, 'peitoral': {'Peitoral de Ferro'}, 'calca': {... |
"""flint format command
:copyright: Copyright 2021 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
import flint
def format_statements(srcdirs, includes=None, excludes=None):
proj = flint.parse(*srcdirs, includes=includes, excludes=excludes)
for src... |
import re
def StringChallenge(strParam):
encoder = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
decoder = {
**{str_i: idx for idx, str_i in enumerate(encoder)},
"plus": "+", "minus": "-"
}
operator = {
'+': lambda a, b: a + b,
'-': lam... |
import pathlib
from panditas.models import DataFlow, DataSet, MergeMultipleRule
from panditas.transformation_rules import ConditionalFill, ConstantColumn, PivotTable
fixtures_path = "{0}/fixtures".format(pathlib.Path(__file__).parent)
def test_insurance_agency_experience():
data_flow = DataFlow(
name="A... |
from azure_utils.machine_learning import create_model
if __name__ == '__main__':
create_model.main()
|
"""Read a GO Annotation File (GAF) and store the data in a Python object.
Annotations available from the Gene Ontology Consortium:
http://current.geneontology.org/annotations/
"""
import sys
import os
import re
import collections as cx
import datetime
from goatools.anno.annoreader_base import AnnoReaderBa... |
# WARNING: This is an automatically generated file and will be overwritten
# by CellBlender on the next model export.
import os
import shared
import mcell as m
from parameters import *
# ---- subsystem ----
MODEL_PATH = os.path.dirname(os.path.abspath(__file__))
vm = m.Species(
name = 'vm',
diffus... |
##
## bund message interface
##
import time
import uuid
import msgpack
import socket
import rsa
from collections import UserDict
class Message(UserDict):
def __init__(self, **data):
UserDict.__init__(self)
if '_data' in data:
self.load(data['_data'])
if '_keys' in data:
... |
from utils import backend_is_non_db, check_can_migrate, get_models_for_db, get_model_by_name
class BackendRouter(object):
"""
A router to send all non-db models to the correct backend
"""
def db_for_read(self, model, **hints):
return getattr(model, 'any_backend', None)
def db_for_write(sel... |
# -*- coding: utf-8 -*-
# Learn more: https://github.com/kennethreitz/setup.py
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='bloom',
version='0.1.0',
description='Design Experiments for Bloo... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
regex_nodes = r"(?P<itemname>\S+)\n|((?P<name>\S+) = (?P<value>(.+\n?)))"
regex_status = r"(?P<name>[^,]+)=(?P<value>([^,]*))"
regex_gpu = (r"gpu\[(?P<gpu_num>\d+)\]=(?P<gpu_status>[^,]+)|"
r"(?P<name>[^,]+... |
from __future__ import absolute_import
from django.contrib.auth import get_user_model
from django.test import TestCase
from ..forms import PostForm
from ..models import Blog, Post, Section
from .tests import randomword
class TestForms(TestCase):
def setUp(self):
super().setUp()
self.user = get... |
import decouple
from abc import ABC
class Settings(ABC):
def __init__(self):
self.is_local = None
self.root_path = None
self._setup()
def _setup(self):
self.is_local = Settings._load_variable(variable='IS_LOCAL', default=False, cast=bool)
self.root_path = '.' if self.... |
from qtpy import QtWidgets, QtCore
from pyqtgraph.widgets.SpinBox import SpinBox
from pyqtgraph.parametertree.parameterTypes.basetypes import WidgetParameterItem
from pymodaq.daq_utils.daq_utils import scroll_log, scroll_linear
import numpy as np
class SliderSpinBox(QtWidgets.QWidget):
def __init__(self, *args, s... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 19 22:23:19 2013
@author: Belli
"""
from __future__ import division
from math import exp
n=[0,
0.125335479355233e-1, #[1]
0.78957634722828e1, #[2]
-0.87803203303561e1, #[3]
0.31802509345418, #[4]
-0.26145533859358, #[5]
-0.78199751687981e-2, #[6]
0.... |
import dynamic_tensor
model = Model()
model_input_shape = [1, 2, 2, 1]
dynamic_layer = dynamic_tensor.DynamicInputGenerator(model, model_input_shape)
test_node_input = dynamic_layer.getTestNodeInput()
perms = Parameter("perms", "TENSOR_INT32", "{4}", [0, 2, 1, 3])
model_output = Output("output", "TENSOR_FLOAT32", "{... |
try:
import concurrent.futures as futures
except ImportError:
try:
import futures
except ImportError:
futures = None
import zipfile
import shutil
import tempfile
import requests
from os import path
# --- Globals ----------------------------------------------
PLUGINS = """
ack.vim https://... |
#!/usr/bin/env python
__author__ = 'Will Kamp'
__copyright__ = 'Copyright 2013, Matrix Mariner Inc.'
__license__ = 'BSD'
__email__ = 'will@mxmariner.com'
__status__ = 'Development' # 'Prototype', 'Development', or 'Production'
'''Downloads noaa product catalog xml by region name and retrieves listing of chart files ... |
# coding=utf-8
# Copyright 2022 The Uncertainty Baselines 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 ap... |
# -*- coding: utf-8 -*-
"""
| '_ \ / _` |_____ / __/ _ \| '_ ` _ \| '_ \ / _` | '__/ _ \
| |_) | (_| |_____| (_| (_) | | | | | | |_) | (_| | | | __/
| .__/ \__, | \___\___/|_| |_| |_| .__/ \__,_|_| \___|
|_| |___/ |_|
This is used to compare two databases. Takes two connection strin... |
from .Confirm import verify
from django.urls import path
urlpatterns = [
path('<str:token_type>/<str:email_token>', verify)
]
|
"""
Queries that list admin and resolve them individually
"""
import graphene
from django.contrib.auth import get_user_model
from graphql_jwt.decorators import superuser_required
from accounts.models import Admin
from accounts.types import AdminType
class AdminsQuery(graphene.AbstractType):
"""Used to read or fet... |
from discord.ext import commands, tasks
from discord import Intents, User, Reaction, Message, TextChannel, NotFound
from discord.ext.commands import CommandNotFound, Context, CommandInvokeError
from emojis import decode
from discord import Embed
from discord.utils import get
from persistent import server_config, sql
... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Like)
admin.site.register(Comment)
admin.site.register(FriendRequest)
admin.site.register(Post)
admin.site.register(Inbox)
admin.site.register(ExternalServer)
class SignUpConfirmAdmi... |
"""Vera tests."""
from unittest.mock import MagicMock
import pyvera as pv
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
from homeassistant.core import HomeAssistant
from .common import ComponentFactory, new_simple_controller_config
async def test_lock(
hass: HomeAssistant, vera_component_factory... |
#!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
import logging
from geocoder.location import BBox
from geocoder.base import OneResult, MultipleResultsQuery
class GisgraphyResult(OneResult):
@property
def lat(self):
return self.raw.get('lat')
@property
def lng(se... |
"""
import bk_typing
"""
import typing as tp
from typing import Union, List, Tuple, Dict, Sequence, Iterable, TypeVar, Any
TV = TypeVar('TV')
# __t New Number Subtypes, and functions to cast to them
NonNegInt = tp.NewType('NonNegInt', int)
NonNegFloat = tp.NewType('NonNegFloat', float)
Probability = tp.NewType('... |
"""
Provisioning
============
The Provisioning module includes classes to manage the provisioning of a
node.
.. Copyright:
Copyright 2020 Wirepas Ltd under Apache License, Version 2.0.
See file LICENSE for full license details.
"""
from .events import (
ProvisioningEvent,
... |
#!/usr/bin/env python3
""" 音声情報処理 n本ノック !! """
# MIT License
# Copyright (C) 2020 by Akira TAMAMORI
# 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... |
import numpy as np
from sklearn import metrics
def uncertain_label(n):
# Constructing the transfer matrix, n is the number of classes
transfer_matrix = np.zeros((n, n))
for i in range(n):
for j in range(n):
if i == j:
transfer_matrix[i, j] = i
s = n
... |
from django.shortcuts import render
from django.http import HttpResponse
from requestHandler.models import User, Song, SystemSetting
from .forms import updateForm
import json
fields = ['FirstName',
'LastName',
'Email',
'passWord']
def requestInfo(request):
# API that returns all the nec... |
import json
import sys
from cluster_clients import *
import logging
STATUS = b'UNKNOWN'
def diff_hub_IDs_and_opssight_IDs(hub_IDs, opssight_IDs):
hub_IDs_set = set(hub_IDs)
opssight_IDs_set = set(opssight_IDs)
IDs_hub_only = hub_IDs_set.difference(opssight_IDs_set)
IDs_both = hub_IDs_set.inters... |
#
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 app import db
from flask import Blueprint
from flask import render_template
from werkzeug.exceptions import BadGateway
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import InternalServerError
from werkzeug.exceptions import MethodNotAllowed
from werkzeug.exceptions import NotFound
from werkze... |
from .constraints import *
from .variables import *
from .relaxation import *
from .utils import * |
from builtins import ValueError, isinstance
import json
import math
import os
from os.path import exists, join
from time import time, sleep
import ipdb
import torch
from torch.nn import functional as F
from utils.logger import LOGGER, TB_LOGGER, RunningMeter, add_log_to_file
from utils.distributed import (all_reduce_... |
import eventlet
import socketio
import os
import sys
import sshtunnel
import time
sio = socketio.Server(async_mode='eventlet')
app = socketio.Middleware(sio)
#temp
import apps.streetdownloader.server as srv
srv_handle=srv.handler()
node_thread_number =4
if __name__ == '__main__':
port = 30021
... |
import asyncio
import urllib.parse as urlparse
import discord
import aiohttp
import lxml.html
import lxml.etree
from discord.ext import commands
import avaconfig as cfg
from .common import Cog
class AvaRSS(Cog):
"""Updates users when new Ava's Demon pages are released"""
def __init__(self, bot):
super().__... |
from jumper.entity import Entity
from jumper.game_helper import show_text
from jumper.timer import parse_time
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
class StageInfo(Entity):
def __init__(self, counter):
self.counter = counter
def render(self, screen):
bound = screen.get_size()
... |
#Software para gestion
#@author Tomas Vargas
import os
print('## Facturacion ##\n====================\n')
name=input('Nombre: ')
Ci=input('CI: ')
fecha=input('Fecha: ')
print('====================')
print('## Compra ##')
prod=[]
op='y'
while(op=='y'):
print('====================')
p=[]
p.append(input('Id ... |
import numpy as np
from keras_pretrained_models.imagenet_utils import preprocess_input
from keras.models import Model
from keras.preprocessing import image
from keras_pretrained_models.vgg19 import VGG19
base_model = VGG19(weights='imagenet')
model = Model(input=base_model.input, output=base_model.get_layer('fc2').ou... |
import datetime
import logging
import os
import sys
import time
from collections import namedtuple
import click
from dateutil.parser import parse
import requests
from mutualfunds import DailyNAVPS
LOGFILE = 'runtime.log'
TIMEOUT = 5
OUTDIR = 'Reports'
def stringify_date(date):
"""Convert datetime object into hu... |
# This file is part of the Indico plugins.
# Copyright (C) 2002 - 2021 CERN
#
# The Indico plugins are free software; you can redistribute
# them and/or modify them under the terms of the MIT License;
# see the LICENSE file for more details.
import re
from flask_multipass import IdentityRetrievalFailed
from indico.c... |
"""Translation constants."""
import pathlib
PROJECT_ID = "130246255a974bd3b5e8a1.51616605"
DOCKER_IMAGE = "b8329d20280263cad04f65b843e54b9e8e6909a348a678eac959550b5ef5c75f"
INTEGRATIONS_DIR = pathlib.Path("homeassistant/components")
|
import random
from collections import deque, namedtuple, Iterable
import numpy as np
import torch
from serpentrain.reinforcement_learning.memory.replay_buffer import ReplayBuffer
Experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
class SimpleReplayBuffer(ReplayBu... |
from __future__ import annotations
from django.db import transaction
from django.http import HttpRequest
from request_token.models import RequestToken, RequestTokenLog
from request_token.settings import DISABLE_LOGS
def parse_xff(header_value: str) -> str | None:
"""
Parse out the X-Forwarded-For request he... |
from .Instrumentable import Instrumentable
from .Instrumentation import Instrumentation
from .Measurement import Measurement
from .Configuration import Configuration
from .ActivationRate import ActivationRate
from .Error import Error
from .ClassificationError import ClassificationError
from .Parameters import Parameter... |
from __future__ import print_function
import json
import sys
import traceback
import warnings
from functools import partial
from importlib import import_module
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
from dj... |
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2017 PyMeasure Developers
#
# 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 limit... |
# todo: Import libraries
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
# todo: Load DataSet
df = pd.read_csv('homeprices.csv')
print(df)
# todo: plotting graph on train dataset
plt.xlabel('area')
plt.ylabel('price')
plt.scatter(df.area, df.price, color='red', marker='+')
# todo... |
import os
from unittest import TestCase
from musurgia.pdf.pdf import Pdf
from musurgia.pdf.table import Table
path = os.path.abspath(__file__).split('.')[0]
# todo
class Test(TestCase):
def test_1(self):
pass
# pdf_path = path + '_test_1.pdf'
# pdf = Pdf()
# table = Table(number_... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2020 OSGeo
#
# 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 ... |
import random
import torch
import torch.nn.functional as F
from kornia.filters import laplacian, canny
from kornia.morphology import erosion
from itertools import product
def get_feature_representation(feature_map_sequence: torch.Tensor,
keypoint_coordinates: torch.Tensor,
... |
# 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, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... |
import os
__author__ = 'Ollie Bennett | http://olliebennett.co.uk/'
LOG_PATH_TWITTER = "logs" + os.sep + "twitter.log"
LOG_PATH_TEMPERATURE = "logs" + os.sep + "temperature.log"
LOG_PATH_TORRENT = "logs" + os.sep + "torrents.log"
LOG_PATH_SERVER = "logs" + os.sep + "server.log"
|
import simplejson as json
from elasticsearch import Elasticsearch
from elasticsearch import helpers
from flask import Flask, request
from flask_restful import Api, Resource
from threading import Thread
from dateutil import parser
import logging
from senml import senml
import os
elastic_host = os.environ.get('ELASTIC_H... |
#!/usr/bin/env python
#-*- coding=utf-8 -*-
#
# Copyright 2012 Jike Inc. All Rights Reserved.
# Author: liwei@jike.com
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()
server_address = ("", 8000)
handler = CGIHTTPServer.CGIHTTPRequestHandler
handler.cgi_directories = [""]
httpd = BaseHTTPServer... |
import os
from fn_is_ableton_project import fn_is_ableton_project
# Creates a master list of all samples in a folder and its subfolders
# -the program assumes that the folder being searched is a user's "master samples folder"
# where they've stored all their saved samples
# -if an Ableton project folder is encounte... |
from jsonbender import K, S
from jsonbender.string_ops import Format, ProtectedFormat
class TestFormat:
@staticmethod
def test_format():
bender = Format("{} {} {} {noun}.", K("This"), K("is"), K("a"), noun=K("test"))
assert bender.bend(None) == "This is a test."
class TestProtectedFormat:
... |
#!/usr/bin/python
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test suite for tree_status.py"""
import os
import sys
import urllib
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirn... |
import pytest
from django.contrib.sites.models import Site
from django.test import RequestFactory
from cdhweb.pages.templatetags import cdh_tags
def test_url_to_icon():
assert cdh_tags.url_to_icon("/people/staff/") == "ppl"
assert cdh_tags.url_to_icon("/projects/") == "folder"
assert cdh_tags.url_to_icon... |
class Nodo(object):
def __init__(self, datos):
self.datos = datos
self.primaria = datos[0]
if type(self.primaria) is str:
self.tipo = 'str'
else:
self.tipo = 'int'
class Tabla(object):
def __init__(self, nombre, columnas):
self.nombre = nombre
... |
"""Plate analysis."""
from contextlib import suppress
from functools import lru_cache
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
from scipy.signal import argrelmin, argrelmax
from . import conf, error, field, phyvars
from ._helpers import saveplot, list_of_vars
from ._step impor... |
import sys
class AbundCSV2NOAPlugin:
def input(self, inputfile):
csvfilename = inputfile
csvfile = open(csvfilename, 'r')
# Read entire abundance file first
firstline = csvfile.readline()
self.bacteria = firstline.split(',')
self.bacteria.remove(self.bacteria[0])
self.abund... |
import os
from vcflat.HeaderExtraction import VcfHeader
def get_input():
test_data_dir = os.path.join(os.path.dirname(__file__), "..", "test_data")
i = os.path.join(test_data_dir, "test.snpeff.vcf")
vcfh = VcfHeader(i)
output = vcfh.extract_header()
return output
def test_1():
""" checks th... |
import configparser
import foss_finder.utils.validators
from .strings import *
###############################################################
# First, define variables by using the INI configuration file #
###############################################################
# Path of the INI configuration file (relati... |
"""
Template App - constants used throughout all files
"""
import numpy as np
# ----------------------------------------------------------------- #
###################################
# colors #
###################################
# basic colors
c_black = "#333333"
c_blue = "#3070b3"
c_white... |
# Escreva um programa para aprovar um empréstimo bancário para o comprador de uma casa.
# Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# A prestação mensal, não pode execeder 30% do salário ou então o empréstimo será negado.
casa = float(input('Valor da casa: '))
salario = float(in... |
import json
from flask.ext.presst import fields, resource_method, Reference
from tests import PresstTestCase, TestPresstResource
class TestResourceMethod(PresstTestCase):
def setUp(self):
super(TestResourceMethod, self).setUp()
class Citrus(TestPresstResource):
items = [{'id': 1, 'nam... |
#!/usr/bin/env python
__author__ = 'Florian Hase'
#========================================================================
from Communicator.ChatBot.bot import Bot
from Communicator.SlackInterface.slack import SlackCommunicator
from Utilities.misc import Printer
#==================================================... |
#!/usr/bin/env python
"""
demonstrate NavigationToolbar with GTK3 accessed via pygobject
"""
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.backends.backend_gtk3 im... |
# -*- coding: utf-8 -*-
import re
from urllib.parse import urlparse
from esmigrate.commons import (
Command,
is_valid_json,
JSON_HEADER,
is_valid_ndjson,
NDJSON_HEADER,
http_verbs,
)
from esmigrate.commons.helpers import construct_path
from esmigrate.contexts import ContextConfig
from esmigrate... |
import discord, random
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.utils.manage_commands import create_option, create_choice
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_slash(name="rps", description="Jouer au rock scroll sci... |
import json
from dataclasses import dataclass, field
from typing import List, Optional
import stringcase
from taegis_sdk_python.services.common_types import Epoch, Time
from taegis_sdk_python.services.investigations.enums import InvestigationProcessingState, InvestigationStatusEnum, \
InvestigationTypes, Priority... |
from machine import UART, Pin
import time
uart1 = UART(1, baudrate=9600, tx=Pin(8), rx=Pin(9))
uart0 = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
button_1 = Pin(2, Pin.IN, Pin.PULL_DOWN)
button_2 = Pin(3, Pin.IN, Pin.PULL_DOWN)
while True:
if button_1.value():
uart1.write(b'Front\n\r')
... |
import numpy as np
import matplotlib.pyplot as plt
from components.utilities.misc import print_orthogonal
from components.utilities.load_write import read_image, load
from components.utilities.VTKFunctions import render_volume
from components.processing.clustering import kmeans_opencv
from joblib import Parallel, dela... |
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Copyright (c) 2020 Baidu, 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... |
phrase = "Sanidhya Academy"
print(phrase.lower())
|
import json
import docutils
import docutils.core
import docutils.frontend
from docutils import nodes
from docutils.parsers.rst import states
def json_safe_dict(d):
"""Deep copy a dict and stringify JSON incompatible values."""
result = {}
for k, v in d.items():
if isinstance(v, dict):
... |
from django.urls import path
from django.contrib import admin
from payments.mpesaApi.views import LNMCallbackAPIView
urlpatterns = [
path('lnm/', LNMCallbackAPIView.as_view(), name="lnm_callbackurl"),
]
|
# Generated by Django 3.1.4 on 2021-01-18 16:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_post_nickname'),
]
operations = [
migrations.AlterField(
model_name='post',
name='thumb',
... |
VPN_SWITCH_RETRY_ATTEMPTS = 3
VPN_SWITCH_RETRY_BACKOFF = 2 # multiplier for the attempt number
VPN_THREAD_QUIT_RETRY_ATTEMPTS = 3
VPN_THREAD_QUIT_RETRY_BACKOFF = 2 # multiplier for the attempt number
VPN_MANAGE_CONNECTION_POLLING_SECONDS = 2
VPN_TRACK_CONNECTIONS_POLLING_SECONDS = 1
VPN_TRACK_PREFERENCES_POLLING_SE... |
"""
Authors: David K. Duvenaud, Dougal MacLaurin, Matt J. Johnson (Harvard
Intelligent & Probabilistic Systems Group)
Packaged by: Eric J. Ma (MIT)
"""
try:
import autograd.numpy as np
except ImportError:
import numpy as np
from operator import itemgetter
def flatten(value):
"""value can be any nesting o... |
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.contrib import messages
from django.db.models import Q
from .models import Image
from .forms import (ImageEditForm, ImageUploadForm)
_lr = loader.render_to_string
def index(req):
qs = req.GET.get('q'... |
from __future__ import absolute_import
import six
from datetime import timedelta
from rest_framework.response import Response
from rest_framework.exceptions import ParseError
from sentry import features
from sentry.api.bases import OrganizationEventsEndpointBase, OrganizationEventsError, NoProjects
from sentry.api.e... |
#!/usr/bin/python
import sys
import csv
import heapq, random
import operator
def mapper():
reader = csv.reader(sys.stdin, delimiter='\t')
writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
mylist = []
dict = {}
index = 0
for line in reader:
mylist.a... |
"""
Copyright (c) 2020 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import, unicode_literals
class Labels(object):
"""
Provide access to a set of labels which have sp... |
# DARC lib
# Compiles and decompiles .darc file archives
# Compiled files have 1:1 parity to the ones produced by Nintendo
# Written by Jaames
# github.com/jaames | jamesdaniel.dev
import struct
class DarcEntry:
def __init__(self, name='', data=bytes(0)):
self.name = name
self.data = data
class DarcGroup:
... |
from django.urls import path
from .views import *
urlpatterns = [
path("", api_overview),
path('list-api/', task_list_api),
path('create-task/', create_task_api),
path('update-task/<int:pk>/', update_task_api),
path('partially-task/<int:pk>/', partially_task_api),
path('delete-task/<int:pk>/', ... |
'''
Utils/Masstools/formula
_______________________
Tools for calculating theoretical peptide formulas and masses.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
# load future
from __future__ import print_funct... |
# -*- coding: utf-8 -*-
# TODO(@sobolevn): write docs for each error, remove ignore from setup.cfg
"""
All style errors are defined here.
They should be sorted by ``_code``.
"""
from ast import AST
from typing import Tuple
class BaseStyleViolation(object):
"""
This is a base class for all style errors.
... |
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import UserRating, Strain
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializer... |
import pytest
from clean import remove_punctuation
@pytest.mark.parametrize("input_argument, expected_return", [
('Hello, I am Tim.', 'Hello I am Tim'),
(';String. with. punctuation characters!',
'String with punctuation characters'),
('Watch out!!!', 'Watch out'),
('Spaces - should - ... |
def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
|
class Leapx_org():
mul_num = 1.20
count= 0
def __init__(self,first,last,pay):
self.f_name = first
self.l_name = last
self.pay_amt = pay
self.full_name = first+" "+last
Leapx_org.count = Leapx_org.count+1
def make_email(self):
return self.f_name+ "."+self.l_name+"@xyz.com"
def incrementpay(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.