content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python2.7
'''
Copyright 2018 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 t... |
# python src/chapter11/chapter11note.py
# python3 src/chapter11/chapter11note.py
'''
Class Chapter11_1
Class Chapter11_2
Class Chapter11_3
Class Chapter11_4
Class Chapter11_5
'''
from __future__ import division, absolute_import, print_function
import sys as _sys
import math as _math
import random as _random
imp... |
from dataclasses import dataclass, field
from itertools import product as product_
from typing import (Callable, Dict, Iterable, Iterator, List, Optional, Tuple,
Union)
import pandas as pd
from ivory.common.context import np
from ivory.common.dataset import Dataset
from ivory.core.model import Mod... |
from __future__ import annotations
import pytest
import resist
class TestUser:
@pytest.fixture()
def client(self) -> resist.WebSocketClient:
return resist.WebSocketClient("REVOLT_TOKEN")
def test_attributes(self, client: resist.WebSocketClient) -> None:
user = resist.User(client, {"_id"... |
# -*- coding: utf-8 -*-
# @Time : 18/12/10 上午10:35
# @Author : Edward
# @Site :
# @File : DynamicPool.py
# @Software: PyCharm Community Edition
import time
from threading import Thread
from multiprocessing import Process
class Pool(object):
'''
阻塞动态线程池。
创建完线程池后,可以动态地往里面丢任务。不用预先构建完要执行的任务,可以边执行边... |
try:
import json
except ImportError:
import simplejson as json
from createsend import CreateSendBase, BadRequest
from utils import json_to_py
class Administrator(CreateSendBase):
"""Represents an administrator and associated functionality."""
def __init__(self, email_address=None):
self.email_address = em... |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import json
import random
import logging
from datetime import datetime
gm_logger = logging.getLogger('grounding_mapper')
gm_logger.setLevel(logging.WARNING)
sm_logger = logging.getLogger('sitemapper')
s... |
from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import DirectObject
from toontown.minigame import ToonBlitzGlobals
from toontown.minigame import TwoDSection
from toontown.minigame import TwoDSpawnPointMgr
from toontown.minigame import TwoDBlock
from... |
import numpy as np
"""
Solve the standard linear programming problem:
maximize c^{T}x
s. t. Ax <= b and x >= 0
by the simplex method.
Remind, enter A, b as usually, but enter -c into the varible c.
For example, try to minimize
x_{1} + x_{2}
s. t. ([1, 2], [3, 4])x <= (5, 6) and x >= 0
then
A = np.array([
... |
# -*- coding: utf-8 -*-
# Copyright 2018 Whitestack, LLC
# *************************************************************
# This file is part of OSM Monitoring module
# All Rights Reserved to Whitestack, LLC
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
from dataclasses import dataclass
from .flipper_output import FlipperOutput
@dataclass
class Paddle:
x: int = 0
y: int = 0
direction: int = 0
def update(self, output: FlipperOutput):
if self.x > output.x:
self.direction = -1
elif self.x < output.x:
self.direction... |
"""
Zendesk Proxy Configuration
"""
from django.apps import AppConfig
from edx_django_utils.plugins import PluginURLs, PluginSettings
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
class ZendeskProxyConfig(AppConfig):
"""
AppConfig for zendesk proxy app
"""
name = ... |
# Copyright 2014 Emmanuele Bassi
#
# SPDX-License-Identifier: MIT
#
# 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, cop... |
#!/usr/bin/python2.5
# Copyright (C) 2007 Google 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 la... |
from Session import Session
from Letter import Letter
from Word import Word
from Grid import Grid
from ApiException import ApiErrorCode, ApiException |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Venue.website'
db.alter_column(u'venues_venue', 'website', self.gf('django.db.models.fiel... |
import asyncio
import os
import fastapi
# noinspection PyPackageRequirements
import pytest
from jinja2.exceptions import TemplateNotFound
from starlette.requests import Request
import fastapi_jinja as fj
here = os.path.dirname(__file__)
folder = os.path.join(here, "templates")
fake_request = Request(scope={'type': ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 17:02:33 2020
@author: lenovo
"""
# AdaBoost
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.ensemble import AdaBoostClassifier
X, y = load_iris(return_X_y=Tru... |
# native packs
import requests
import json
# installed packs
import pandas as pd
from pandas import json_normalize
auth_endpoint = "https://auth.emsicloud.com/connect/token" # auth endpoint
# replace 'your_client_id' with your client id from your api invite email
client_id = "5f379hywuvh7fvan"
# replace 'your_clien... |
from collections import Counter
def duplicate_sandwich(arr):
check=Counter(arr)
temp1=arr.index(check.most_common()[0][0])
temp2=arr[temp1+1:].index(check.most_common()[0][0])
return arr[temp1+1:temp2+temp1+1]
|
import math
from django.urls import reverse
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from .utils import escape_reserved_characters
MAIN_INDEX_NAME = 'main_index'
PAGE_SIZE = 10
class Elastic:
def __init__(self):
self.es = Elasticsearch(['http://elasticsearch... |
"""Module for storing coinchoose data in the database."""
import coinchoose
from datetime import datetime
from datetime import timedelta
from decimal import Decimal
import os
import psycopg2 as pg2
import psycopg2.extras as pg2ext
import random
import unittest
# Configuration variables
batchLimit = 1000
tables = {
... |
# ROS imports
import roslib; roslib.load_manifest('freemovr_engine')
import scipy.optimize
import imageio
from pymvg.camera_model import CameraModel
from pymvg.util import get_rotation_matrix_and_quaternion
import freemovr_engine.simple_geom as simple_geom
import numpy as np
import os
import cv2
PLOT=int(os.environ.g... |
# Generated by Django 2.2.20 on 2021-10-04 09:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deeds', '0008_deed_target'),
]
operations = [
migrations.AddField(
model_name='deed',
name='enable_impact',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
from .property import Property
from .util import text, unicode_obj
from .propertymapping import ConstantPropertyMapping, DirectPropertyMapping, ConcatPropertyMapping
__author__ = "nebula"
variable_meta_registry = dict(... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
from glob import glob
import imp
SQLALCHEMY_TRACK_MODIFICATIONS = False
plugins = []
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManag... |
import gdb
def format_plan_tree(tree, indent=0):
'formats a plan (sub)tree, with custom indentation'
# if the pointer is NULL, just return (null) string
if (str(tree) == '0x0'):
return '-> (NULL)'
# format all the important fields (similarly to EXPLAIN)
retval = '''
-> %(type)s (cost=%(startup).3f...%(total).... |
# ptext module: place this in your import directory.
# ptext.draw(text, pos=None, **options)
# Please see README.md for explanation of options.
# https://github.com/cosmologicon/pygame-text
from __future__ import division, print_function
from math import ceil, sin, cos, radians, exp
from collections import namedtup... |
#it2.py
import json
import argparse
import funcy
import os, shutil
from sklearn.model_selection import train_test_split
'''
#train_dir = '/home/data/130/train_split.json'
#os.makedirs('train2017', exist_ok=True)
#test_dir = '/home/data/130/test_split.json'
#os.makedirs('test2017', exist_ok=True)
parser = argparse.Argu... |
import os.path, sys, re, cv2, glob, numpy as np
import os.path as osp
from tqdm import tqdm
from IPython import embed
import scipy
import matplotlib.pyplot as plt
from skimage.transform import resize
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import auc
from matplotlib.patches import Circle
import to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2015,掌阅科技
All rights reserved.
摘 要: __init__.py
创 建 者: zhuangshixiong
创建日期: 2015-10-10
'''
if __name__ == '__main__':
pass
|
# Copyright (c) 2018 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 required by app... |
import os
from foliant.preprocessors.apireferences.classes import BadConfigError
from foliant.preprocessors.apireferences.classes import WrongModeError
from foliant.preprocessors.apireferences.classes import get_api
from unittest import TestCase
def rel_name(path: str):
return os.path.join(os.path.dirname(__file... |
"""
translatory.py
Takes either english or french phrase and converts to french and english
"""
import json
from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import os
from dotenv import load_dotenv
load_dotenv()
"""translator_instance"""
apikey_lt = os.envir... |
from Crypto.Util.number import bytes_to_long, getPrime, inverse
m = b'flag{4cce551ng_th3_subc0nsc10us}'
p = getPrime(512)
q = getPrime(512)
N = p*q
e = 0x10001
d = inverse(e,(p-1)*(q-1))
c = pow(bytes_to_long(m),e,N)
print(f'Modulus: {N}\nOne factor of N: {p}\nPublic key: {e}\nCiphertext: {c}')
|
# BSD 2-Clause License
# Copyright (c) 2020, Allen Cheng
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
... |
import random
import pytest
import geomstats.backend as gs
from geomstats.geometry.hyperbolic import Hyperbolic
from geomstats.geometry.hyperboloid import Hyperboloid
from tests.data_generation import _LevelSetTestData, _RiemannianMetricTestData
# Tolerance for errors on predicted vectors, relative to the *norm*
# o... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from mocker.endpoints import grpc_endpoint_pb2 as mocker_dot_endpoints_dot_grpc__endpoint__pb2
class MockServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Con... |
# Description:
# Functions that deal with data generation/manipulation
# Imports:
import game_mechanics as gm
import GUI
import numpy as np
from keras.utils.np_utils import to_categorical
from _collections import deque
import os
# Constants:
board_len = 30
# Functions:
def moves_to_board(moves... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
import numpy as np
import pandas as pd
import tensorflow as tf
import sys
import csv
import random
import os
from io import StringIO
import keras
from keras.layers import Input,Dense,concatenate,Dropout,LSTM
from keras.models import Model,load_model
from keras.optim... |
from django.test import TestCase
from hknweb.academics.tests.utils import ModelFactory
class QuestionModelTests(TestCase):
def setUp(self):
question = ModelFactory.create_question()
self.question = question
def test_basic(self):
pass
|
from modules.module_base import ModuleBase
import urllib.request
import json
from tools.limitator import Limitator, LimitatorLimitted, LimitatorMultiple
class ModuleAss(ModuleBase):
def __init__(self, bot):
ModuleBase.__init__(self, bot)
self.name = "ModuleAss"
self.Url = "http://api.obut... |
# @AUTHOR: Piplopp <https://github.com/Piplopp>
# @DATE: 05/2017
#
# @DESC This script generates a blank template for translation of the fire emblem
# heroes unit names, weapons, assit, special and passive skills for the
# feh-inheritance-tool <https://github.com/arghblargh/feh-inheritance-tool>.
#
# It will parse the ... |
from . import *
class AWS_OpsWorksCM_Server_EngineAttribute(CloudFormationProperty):
def write(self, w):
with w.block("engine_attribute"):
self.property(w, "Value", "value", StringValueConverter())
self.property(w, "Name", "name", StringValueConverter())
class AWS_OpsWorksCM_Server(CloudFormationRe... |
#!/usr/bin/env python
from PIL import Image, ImageDraw
import random as pyrandom
import sys
import os.path
import shutil
import re
import subprocess
import numpy as np
from glob import glob
import argparse
# from matplotlib.pyplot import imread
from scipy.ndimage import filters, interpolation, morphology, measurements... |
# Copyright 2017 Insurance Australia Group 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
GROUPS_OF = """
CREATE OR REPLACE FUNCTION cognition.groupsof(username text)
RETURNS setof text AS $$
DECLARE rolename pg_roles.rolname%TYPE;
BEGIN
FOR rolename IN
SELECT a.rolname FROM pg_authid a
WHERE pg_has_role(username,... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import os
import random
import numpy as np
import torch
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# import splitfolders #only needed for train/test split folder creation
# In[3]:
#here's the line of code I... |
import unittest
import os
import spreadsheet
from Exceptions import *
from Cell import Cell
class ReadTests(unittest.TestCase):
def setUp(self):
spreadsheet.spreadsheet = {}
def test_read_command__malformatted_arg(self):
with self.assertRaises(InputException):
spreadsheet.read_c... |
# -*- coding: utf-8 -*-
"""INK system utilities module.
"""
from base64 import b64encode
import hashlib
import sys
from ink.sys.config import CONF
def verbose_print(msg: str):
"""
Verbose Printer.
Print called message if verbose mode is on.
"""
if CONF.debug.verbose and CONF.debug.verbose_leve... |
import discord
import asyncio
import MyClient
from threading import Thread
print("Discord.py Voice Recorder POC")
DISCORD_TOKEN = ""
client = MyClient.MyClient()
client.run(DISCORD_TOKEN)
|
import asyncio
import copy
import functools
from contextlib import contextmanager
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
List,
Optional,
Reversible,
Tuple,
Type,
TypeVar,
Union,
)
from telethon.client.updates import EventBuilderDict
from tele... |
# -*- coding: utf-8 -*-
""" Manifest Decorator Tests
"""
from django.urls import reverse
from tests.base import ManifestTestCase
class DecoratorTests(ManifestTestCase):
"""Tests for :mod:`decorators <manifest.decorators>`.
"""
def test_secure_required(self):
"""Should redirect to secured versio... |
# Operadores aritmeticos
22 + 22 # Suma
22 - 2 # Resta
22 / 2 # Divison
22 // 2 # Divison entera
22 * 2 # Multiplicacion
22 % 2 # Modulo
22 ** 2 # Exponente
# Operadores de asignacion
numero = 0
numero += 2
numero -= 1
numero *= 9
numero /= 3
# Operadores de comparacion
numero1 = 5
numero2 = 3
print(numero1 ==... |
from sqlalchemy import *
import testbase
class SingleInheritanceTest(testbase.AssertMixin):
def setUpAll(self):
metadata = BoundMetaData(testbase.db)
global employees_table
employees_table = Table('employees', metadata,
Column('employee_id', Integer, primary_key=True),
... |
import pytest
from hypothesis import given
from tests.strategies import med_ints, small_floats
from tinytorch import module
class ModuleA1(module.Module):
def __init__(self):
super().__init__()
self.p1 = module.Parameter(5)
self.non_param = 10
self.a = ModuleA2()
self.b = ... |
import sys
sys.path.append('../')
from pycore.tikzeng import *
import math
network = []
f = open("./arch_yolov3.txt", "r")
for x in f:
layer = {}
input_1 = x.split()
layer["id"] = input_1[0]
layer["type"] = input_1[1]
if("->" in x):
input_2 = x.split("->")[1].split()
layer["height... |
import os
from mkmapi.exceptions import MissingEnvVar
def _get_env_var(key):
try:
return os.environ[key]
except KeyError:
raise MissingEnvVar(key)
def get_mkm_app_token():
return _get_env_var('MKM_APP_TOKEN')
def get_mkm_app_secret():
return _get_env_var('MKM_APP_SECRET')
def ge... |
import argparse
import uuid
import sys
import socket
import eventlet
import eventlet.event
import eventlet.greenpool
from localtunnel import util
from localtunnel import protocol
from localtunnel import __version__
def open_proxy_backend(backend, target, name, client, use_ssl=False, ssl_opts=None):
proxy = event... |
# MP3
import selenium
import pygame
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('c:/Users/wmarc/OneDrive/Documentos/UNIVESP/Curso em Video/Desafio_021.mp3')
pygame.mixer.music.play()
pygame.event.wait() |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import argparse
import os.path
import re
import sys
import tarfile
import os
import datetime
import math
import random, string
import base64
import json
import time
from time import sleep
from time i... |
#
# Copyright (c) SAS Institute, Inc.
#
# 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, modify, merge, publish, di... |
from magicbot import StateMachine, state, timed_state
from components.cargo import CargoManipulator, Height
from components.vision import Vision
class CargoManager(StateMachine):
cargo_component: CargoManipulator
vision: Vision
def on_disable(self):
self.done()
def intake_floor(self, force... |
import os
import pandas
import geopandas
from shapely.geometry import Polygon, LineString
from shared import print_
geopandas.io.file.fiona.drvsupport.supported_drivers["KML"] = "rw"
COLUMNS_TO_DROP = ["Description"]
def generate_regions(**kwargs):
print_("GENERATE REGIONS", title=True)
print_("Parameters... |
# -*- coding: utf-8 -*-
import unittest
from copy import deepcopy
from openregistry.lots.core.tests.base import snitch
from openregistry.lots.bargain.tests.base import (
LotContentWebTest
)
from openregistry.lots.core.tests.blanks.json_data import test_loki_item_data
from openregistry.lots.bargain.tests.blanks.it... |
# -*- coding: utf-8 -*-
import re
from datetime import timedelta
from django.contrib.auth.models import Group
from django.contrib.auth import authenticate
from django.core.validators import EMPTY_VALUES
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext_lazy a... |
import unittest
from tests.refactor.utils import RefactorTestCase
from unimport.constants import PY38_PLUS
class TypingTestCase(RefactorTestCase):
include_star_import = True
@unittest.skipIf(
not PY38_PLUS, "This feature is only available for python 3.8."
)
def test_type_comments(self):
... |
# Copyright 2012 Google Inc. All Rights Reserved.
"""Simulator state rules for the build system.
Contains the following rules:
compile_simstate
"""
__author__ = 'benvanik@google.com (Ben Vanik)'
import io
import json
import os
import sys
import anvil.async
from anvil.context import RuleContext
from anvil.rule imp... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 14:32:57 2020
@author: Administrator
"""
"""
回文字符串是指一个字符串从左到右与从右到左遍历得到的序列是相同的.例如"abcba"就是回文字符串,而"abcab"则不是回文字符串.
"""
def AddSym2Str(s):
if len(s) == 0:
return '*'
return ('*' + s[0] + AddSym2Str(s[1:]))
def GetPalLen(i , s):
lens... |
from bson import ObjectId
from db.db import Database
from db.security import crypt
import datetime
class Users(Database):
_id: str
name: str
cpf: str
email: str
phone_number: int
created_at: str
updated_at: str
def __init__(self):
super().__init__()
def create_user(self, ... |
binomski_slovar = {(1, 1): 1}
for n in range(2, 101):
for r in range(n + 1):
if r == 0:
binomski_slovar[(n, r)] = 1
elif r == 1:
binomski_slovar[(n, r)] = n
elif r == n:
binomski_slovar[(n, r)] = binomski_slovar[(n - 1, r - 1)]
else:
... |
# -*- coding: utf-8 -*-
'''
@Time : 4/20/2022 4:36 PM
@Author : dong.yachao
''' |
'''Crie uma classe para implementar uma conta corrente.
A classe deve possuir os seguintes atributos: número da conta,
nome do correntista e saldo. Os métodos são os seguintes:
alterarNome, depósito e saque; No construtor, saldo é opcional,
com valor default zero e os demais atributos são obrigatórios.'''
class ... |
from dataclasses import dataclass
from bindings.csw.abstract_coordinate_system_type import AbstractCoordinateSystemType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class ObliqueCartesianCstype(AbstractCoordinateSystemType):
"""A two- or three-dimensional coordinate system with straight axes that
... |
from dataclasses import dataclass, field
from typing import Optional
from serde import deserialize
from metaphor.common.filter import DatasetFilter
from metaphor.snowflake.auth import SnowflakeAuthConfig
from metaphor.snowflake.utils import DEFAULT_THREAD_POOL_SIZE
@deserialize
@dataclass
class SnowflakeRunConfig(S... |
# -*- coding: utf-8 -*-
#####################################################################
# Peach - Python para Inteligência Computacional
# José Alexandre Nalon
#
# Este arquivo: demo07.py
# Demonstração e teste, Mapeamento de uma função não linear.
################################################################... |
from django.conf.urls import url
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.home_teamlead),
url(r'^index_teamlead$', views.index_teamlead, name='index_teamlead'),
url(r'^holidays_teamlead$', views.holidays_teamlead, name='... |
from base64 import b64decode
from zlib import decompress
from os import system
inputFile = "handcrafted-pyc.py_bc552f58fe2709225ca0768c131dd14934a47305"
magicHeader = b"\x03\xf3\x0d\x0a\xfb\x1c\x32\x59"
outputPycFile = "dump.pyc"
outputSrcFile = "output.py"
uncompyleExe = "uncompyle6"
code = 'eJyNVktv00AQXm/eL0igiaFA... |
import numpy as np
from scipy.signal import find_peaks
import os
import pycst_ctrl
class PyCstDataAnalyser:
""" Used to analyse data exported by CST"""
def __init__(self, opts):
# Initialize attributes
# Polarization indicator
self.pol_ind = opts.get('pol_ind', 'lin_dir')
#... |
# -*- coding:utf-8 -*-
"""
@description:
"""
import os
import sys
import numpy as np
import torch
from jiwer import wer
import sacrebleu
sys.path.append('..')
import config
from data_reader import load_word_dict
from seq2seq_model import Seq2SeqModel
from utils.logger import logger
device = torch.device("cuda" if t... |
# Copyright 2016, 2017 John J. Rofrano. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
"""Helper neural network training module."""
from collections import OrderedDict
from pathlib import Path
from time import time
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from ..datasets import IMAGE_SHAPES, get_loader
from ..models import fit_to_dataset, get_model
from ..mod... |
from PyQt5 import QtWidgets
from otter.OListView import OListView
class TemplatesTab(QtWidgets.QWidget):
"""
List of recent file that show on the MainWindow
"""
def __init__(self, parent):
super().__init__(parent)
main_layout = QtWidgets.QVBoxLayout()
main_layout.setContentsM... |
import string
def alphabetSubsequence(s):
seen = -1
for i in s:
index = string.ascii_lowercase.find(i)
if index > seen:
seen = index
else:
return False
return True
s = "effg"
print(alphabetSubsequence(s))
|
import os
import sys
import inspect
import string
import numpy as np
PycQED_py3_dir = "D:\\Github\\PycQED_py3"
AssemblerDir = PycQED_py3_dir + \
"\\instrument_drivers\\physical_instruments\\_controlbox"
currentdir = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()... |
val = input().split()
a, b, c = val
a = float(a)
b = float(b)
c = float(c)
if a < (a+b) and b < (c+a) and c < (a+b):
per = a + b + c
print('Area = %.2f' %per)
|
import pandas
import numpy
import filepaths
import utils
def fetch_ng_inflation_cpi():
stats_metadata = utils.read_stats_metadata()
url = stats_metadata['NG']['inflation']['CPI']['url']
tmp_filepath = utils.download_file(url)
df = pandas.read_excel(tmp_filepath, sheet_name='Table1', header=None)
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import datetime
UNIQUE_REDIS_KEY_PREFIX = 'celery_unique'
class UniqueTaskMixin(object):
abstract = True
unique_key = None
redis_client = None
def apply_asyn... |
from . import hist, quality
|
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Node.js st module Directory Traversal''',
"description": '''A directory traversal vulnerability in the st module before 0.2.5 for Node.js allows remote attackers to read arbitrary files via a %2e%2e (e... |
__copyright__ = "Copyright 2015 Contributing Entities"
__license__ = """
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 re... |
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy.matcher import Matcher, PhraseMatcher
from spacy.tokens import Span
import string
from nltk.corpus import stopwords
import pandas as pd
def phrase_template():
'''
This function returns a list of all the possible technical terms that has high possibilit... |
# Import the agent class
#from .agenttemplate import AgentTemplate
|
# Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
# SPDX-License-Identifier: MIT
"""
Contains functions specific to decoding and processing inference results for YOLO V3 Tiny models.
"""
import cv2
import numpy as np
def iou(box1: list, box2: list):
"""
Calculates the intersection-over-union... |
from xml.etree.ElementTree import tostring
from f1_telemetry.server import get_telemetry
from kusto.ingest import ingest_kusto
from datetime import datetime
batch_freq_high = 9 # 20 cars per packet * batch_freq_high(x) packets
batch_freq_low = 2
ingest_cartelemetrydataCnt = 0
ingest_cartelemetryBuffer = ""
ingest_ses... |
"""Integration test for pytype."""
from __future__ import print_function
import csv
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
from pytype import config
from pytype import main as main_module
from pytype import utils
from pytype.pyi import parser
from pytype.py... |
#!/usr/bin/env python
import argparse
def main(args):
"""
This is some doc
"""
print(args)
def sub_function():
"""
Here is some doc about this sub function
"""
pass
def parse_arguments():
parser = argparse.ArgumentParser(description="")
parser.add_argument("-t", "--type", d... |
while (True):
print("mohammed uddin made changes")
print(":D")
|
# logic.py to be
import random
global actual_score
def start_game():
# declaring an empty list then
# appending 4 list each with four
# elements as 0.
mat = []
for i in range(4):
mat.append([0] * 4)
# calling the function to add
# a new 2 in grid after every step
add_new_2(ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.