text stringlengths 2 999k |
|---|
import ctypes
import copy
import vector3
class BinaryFileReader(object):
""" BinaryFileReader is a class to help ease the reading of binary data from a file
With easy method to read Bytes, Ints, Longs, Floats and Strings
"""
def __init__(self, filePath=None):
""" Constructor
A... |
"""Tools for managing streams"""
import sys
import subprocess
from threading import Thread
from queue import Queue, Empty
class NonBlockingStreamReader(object):
def __init__(self, stream):
"""A non-blocking stream reader
Parameters
----------
stream: the stream to read from.
... |
# Generated by Django 3.1.2 on 2020-10-23 13:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Vault', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='clip',
old_name='YoutubeId',
new_n... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import FileField, StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, Length, Optional, URL
class EditProfileForm(FlaskForm):
name = StringField("Name", validators=[
Length(min=0, max=32)])... |
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Use .apply(str.upper)
cars['COUNTRY'] = cars['country'].apply(str.upper) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenMiniInnerappPluginuseconfigOnlineModel(object):
def __init__(self):
self._app_origin = None
self._bundle_id = None
self._mini_app_id = None
self._plugin_... |
#-------------------------------------------------------------------------------
# elftools: dwarf/structs.py
#
# Encapsulation of Construct structs for parsing DWARF, adjusted for correct
# endianness and word-size.
#
# Eli Bendersky (eliben@gmail.com)
# This code is in the public domain
#-----------------------------... |
print("This is a second test")
|
from django.test import Client
from django.test import TestCase
from populate import *
class StudentHomeErrorTestCase(TestCase):
def setUp(self):
add_course("Systems Programming 3", "SP3", "Introduction to Systems Programming using C and C++")
add_student("Bob", "3015244", "Bob@bob.bob", "Bob", 0,... |
#!/usr/bin/python3
#
# Copyright 2017, Intel Corporation
#
# 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
# notice, this list of conditions... |
import unittest
from yo_ds import *
class KrakenMethodsTests(unittest.TestCase):
def test_invoke(self):
obj = dict(ctor=dict,a=1,b=2)
result = kraken.invoke(obj)
self.assertDictEqual(dict(a=1,b=2),obj['instance'])
self.assertEqual('dict',obj['name'])
def test_extract_id(self):
... |
# A part of NonVisual Desktop Access (NVDA)
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
# Copyright (C) 2021 NV Access Limited
"""
Required types and defines from Windows SDK's hidpi.h
(Public Interface to the Windows HID parsing library).
"""
import enum
from ct... |
"""
Proszę napisać funkcję wstawiającą na koniec listy nowy element. Do funkcji należy przekazać
wskazanie na pierwszy element listy oraz wstawianą wartość.
"""
class Node:
def __init__(self, value):
self.value = value
self.next = None
def add_last_element(head, value):
if head is None:
... |
from django.conf import settings
if 'reversion' in settings.INSTALLED_APPS: # pragma: no cover
from reversion.admin import VersionAdmin as BaseModelAdmin
else:
from django.contrib.admin import ModelAdmin as BaseModelAdmin
class BaseAdmin(BaseModelAdmin):
history_latest_first = True
|
#
# PySNMP MIB module Fore-E3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-E3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:03:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
"""
=======
三数之和
=======
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。注意:答案中不可以包含重复的三元组。
"""
def basic(nums, target):
nums.sort()
i = 0
while i < len(nums) - 2:
j = i + 1
k = len(nums) - 1
while j < k:
s = nums[i] + nums[j] + nums[k... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import sys... |
"""
Canonical path locations for zipline data.
Paths are rooted at $ZIPLINE_ROOT if that environment variable is set.
Otherwise default to expanduser(~/.zipline)
"""
from errno import EEXIST
import os
from os.path import exists, expanduser, join
import pandas as pd
def hidden(path):
"""Check if a path is hidden... |
from datetime import datetime
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, no_translations
from note.models import NoteIndexPage
from note.models import NotePage
class Command(BaseCommand):
help = 'Create note page'
def add_arguments(self, parser):
... |
from argparse import ArgumentParser
from typing import Any, Dict, Tuple, List
from pathlib import Path
import os
import numpy as np
import pytorch_lightning as pl
import torch
from skimage.metrics import peak_signal_noise_ratio as psnr
from skimage.metrics import structural_similarity as ssim
from skimage.metrics impo... |
import os
import designer
from designer.helper_functions import ignore_proj_watcher
from kivy.config import ConfigParser
from kivy.properties import ObjectProperty
from kivy.uix.settings import Settings
PROJ_DESIGNER = '.designer'
PROJ_CONFIG = os.path.join(PROJ_DESIGNER, 'config.ini')
class ProjectSettings(Settin... |
#!/usr/bin/env python2
# Copyright (c) 2015-2016 The Readercoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Test script for security-check.py
'''
from __future__ import division,print_function
import subproc... |
from copy import copy
from decimal import Decimal
from typing import TYPE_CHECKING, Any, List, Optional, Union
from django.db.models import QuerySet
from django_countries.fields import Country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from . import ConfigurationTypeField
from .models import Pl... |
#!/usr/bin/env python
"""
ROS node to track objects using DEEP_SORT TRACKER and YOLOv3 detector (darknet_ros)
Takes detected bounding boxes from darknet_ros and uses them to calculated tracked bounding boxes
Tracked objects and their ID are published to the sort_track node
For this reason there is a little delay in th... |
# coding=utf-8
# Copyright 2019 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# 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... |
'''
Tests 304 responses
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0... |
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, create_engine
metadata = MetaData()
infaWorkflows = Table('infaWorkflows', metadata,
Column('workflowId', Integer, primary_key=True),
Column('workflowName',String(100)),
Column('workflowParamId',In... |
import math
from src.car import car
from src.controllers.car_controller import car_controller
from src.globals import M_PER_PIXEL
from src.car_command import car_command
from src.l2race_utils import my_logger
logger = my_logger(__name__)
MAX_SPEED = 5.0
WB = 2.9 # [m] wheel base of vehicle
LFC = 3.0 # [m] look ahea... |
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# 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... |
import os
import re
import shutil
import sys
PHOTO_PATH = os.path.dirname(__file__) + '/../photos/'
def is_image_path(path):
return re.search(r'\.(jpe?g|png)$', path)
def get_min_path(path):
return re.sub(r'\.(png|jpe?g)$', '.min.\g<1>', path)
def get_placeholder_path(path):
return re.sub(r'\.(png|jp... |
#!/usr/bin/env python3
# Copyright 2020 Stanford University
#
# 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 applicab... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
# My zip file!
lighter = "Zippo"
says = "coo-coo cachoo"
|
from pythonforandroid.toolchain import CompiledComponentsPythonRecipe
class SQLAlchemyRecipe(CompiledComponentsPythonRecipe):
name = 'sqlalchemy'
version = '1.0.9'
url = 'https://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-{version}.tar.gz'
depends = [('python2', 'python3'), 'setupto... |
"""create build_data table
Revision ID: 4a5bef3702b
Revises: 9593a123e7c5
Create Date: 2017-12-15 21:15:17.884404
"""
# revision identifiers, used by Alembic.
revision = '4a5bef3702b'
down_revision = '9593a123e7c5'
branch_labels = None
depends_on = None
from alembic import op
from drydock_provisioner.statemgmt.db ... |
#encoding:utf8
#!/usr/bin/env python2
from psychopy import data,visual,event,core,gui
import time
import math
#配置变量##############################################
extraInfo= {'name':'input your name','participantID':1,'session':1,'gender':['male','female'],'age':20,'hand':['left','right']}
paraList=['score','fscore1... |
class Solution:
def frequencySort(self, s):
freqs = {}
for c in s:
if c not in freqs:
freqs[c] = 1
else:
freqs[c] += 1
ans = ""
for k, v in sorted(freqs.items(), key=lambda x: x[1]):
ans += k * v
return ans[... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import torch
class Accuracy():
def __init__(self, num_classes, num_entries):
self.num_classes = num_classes
self.correct = torch.empty(self.num_classes)
self.num_entries = num_entries
def calculate_accuracy(y_pred, y_label):
pred_conditions = y_pred[:,:-2]
label_conditi... |
"""
Default weights for integer in email address. These weights are used to randomly
generate the integer type to use within a Fake Email object in order to
generate an email address
Copyright (c) 2019 Julien Kervizic
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and as... |
from dof_conf.core.tests import TestCase
from . import factories
class TestSpeaker(TestCase):
def setUp(self):
self.speaker = factories.SpeakerFactory(name="John Doe")
def test__str__(self):
self.assertEqual(self.speaker.__str__(), "John Doe")
class TestScheduleItem(TestCase):
def se... |
import collections
import pygal
import json
import os
import collections as col
#This script intends to graph favourites accumulation through 3200 tweets.
def plot(read_dir):
filelist = os.listdir(read_dir)
result = col.Counter()
for file in filelist:
with open('%s%s' % (read_dir,file),"r",encoding... |
# coding: utf-8
"""
Grafeas API
An API to insert and retrieve annotations on cloud artifacts.
OpenAPI spec version: 0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in co... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
"""
Copyright 2020 InfAI (CC SES)
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... |
"""Logic for alerting the user on possibly problematic patterns in the data (e.g. high number of zeros , constant
values, high correlations)."""
from enum import Enum, unique
from typing import List
import numpy as np
from pandas_profiling.config import config
from pandas_profiling.model.base import Variable
@uniqu... |
"""
Created by howie.hu at 2022-04-12.
Description: 验证装饰器中间件
Changelog: all notable changes to this file will be documented
"""
from functools import wraps
from flask import request
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from src.api.common.flask_tools import response_han... |
import logging
import sys
import json
import reconcile.queries as queries
from reconcile.utils.aws_api import AWSApi
from reconcile.utils.defer import defer
from reconcile.utils.ocm import OCMMap
from reconcile.utils.terraform_client import TerraformClient as Terraform
from reconcile.utils.terrascript_client import ... |
# Copyright (c) 2021 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 appli... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from backbone import EfficientNetBackbone, ResNetBackbone, VGGBackbone, ResNetBackboneGN, DarkNetBackbone
from math import sqrt
import torch
# for making bounding boxes pretty
COLORS = ((244, 67, 54),
(233, 30, 99),
(156, 39, 176),
(103, 58, 183),
( 63, 81, 181),
... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
from datastore.reader.flask_frontend import FlaskFrontend
from datastore.reader.services import register_services
from datastore.shared import create_base_application
def create_application():
register_services()
return create_base_application(FlaskFrontend)
application = create_application()
|
# string_basics.py
# Declare FIVE variables with strings that describe yourself.
# Print the five variables.
|
import logging
import os
import sys
import time
import inspect
import shutil
import threading
import traceback
import uuid
from functools import partial
from numbers import Number
from ray.tune.registry import parameter_registry
from six.moves import queue
from ray.util.debug import log_once
from ray.tune import Tune... |
# coding=utf-8
from commands import VoidCommand
from slack_channel.abstract_event_handler import AbstractEventHandler
command_symbol = "test"
class TestEventHandler(AbstractEventHandler):
@property
def command(self) -> VoidCommand:
return VoidCommand()
@property
def name(self)... |
#! /usr/bin/env python
# Copyright (c) 2008-2009, PediaPress GmbH
# See README.rst for additional licensing information.
"""
TODO:
* add license handling
* implement missing methods: Imagemap, Hiero, Timeline, Gallery
More Info:
* http://books.evc-cit.info/odbook/book.html
* http://opendocumentfellowship.com/projec... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-16 12:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
# -*- coding: utf-8 -*-
"""
LaunchDarkly REST API
# Overview ## Authentication All REST API resources are authenticated with either [personal or service access tokens](https://docs.launchdarkly.com/home/account-security/api-access-tokens), or session cookies. Other authentication mechanisms are not supporte... |
from typing import Tuple
from gym.envs.registration import register
from gym import GoalEnv
import numpy as np
from numpy.core._multiarray_umath import ndarray
from highway_env.envs.common.abstract import AbstractEnv
from highway_env.envs.common.observation import MultiAgentObservation
from highway_env.road.lane impo... |
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='prometheus-mysql-exporter',
version='0.5.0',
description='MySQL quer... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pandas_for_everyone-2_3_the_series.py
2.3.The Series
"""
import pandas as pd
##################
# 2.3.The Series #
##################
# Create our example dataframe with a row index label
scientists = pd.DataFrame(
data = {'Occupation': ['Chemist','Statistic... |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import logging
import traceback
from datetime import datetime
import requests
from .config import DefaultConfig
logger = logging.getLogger(__name__)
class TCloud(object):
def __init__(self, task_id, device_id, monkey_id, tcloud_url, process=0):
sel... |
import shippo
"""
In this tutorial we have an order with a sender address,
recipient address and parcel information that we need to ship.
"""
# Replace <API-KEY> with your key
shippo.config.api_key = "<API-KEY>"
# Example address_from object dict
# The complete reference for the address object is available here: htt... |
# coding: utf-8
"""
Preprocess dataset
usage: preprocess.py [options] <name> <in_dir> <out_dir>
options:
--num_workers=<n> Num workers.
--hparams=<parmas> Hyper parameters [default: ].
--preset=<json> Path of preset parameters (json).
-h, --help Show help message.
"... |
"""
Funds API For Digital Portals
Search for mutual funds and ETFs using one single consolidated API, including a criteria-based screener. The API provides also base data, key figures, and holdings. A separate endpoint returns the possible values and value range for the parameters that the endpoint /fund/nota... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- coding: utf-8 -*-
#BEGIN_HEADER
import logging
import os
from installed_clients.KBaseReportClient import KBaseReport
#END_HEADER
class HelloWorld_abbyjerger:
'''
Module Name:
HelloWorld_abbyjerger
Module Description:
A KBase module: HelloWorld_abbyjerger
'''
######## WARNING FOR G... |
"""
see https://eth.wiki/en/fundamentals/rlp
"""
from __future__ import annotations
import typing
from ctc import spec
from . import formats
def rlp_encode(data: typing.Any) -> str:
try:
import rlp # type: ignore
except ImportError:
raise Exception(
'the rlp package is required ... |
import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
from DCGAN import *
import pickle
def generate():
G = Generator()
G.load_state_dict(torch.load('./Gmodel.pth'))
ginputdata = Variable(torch.randn((50,1,100)))
goutput = G(ginputdata)
if o... |
from io import StringIO
from pprint import pprint
from typing import Any
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
import py
from _pytest._code.code import ExceptionChainRepr
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import ReprEnt... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 01:50:56 2020
@author: Ayse
"""
import cv2
video = cv2.VideoCapture(r'...video.mp4')
result = cv2.VideoWriter('vid.avi',
cv2.VideoWriter_fourcc(*'DIVX'),
20, (640,640), 0)
while True:
ret, frame = video.read()
gray = cv2.... |
from recordclass import recordclass
FAKE_TAGS = {
'db_name': 'fake_db_name'
}
FAKE_CREDENTIAL = {
"provider":"gce",
"region": "fake_region",
"service_account":{
"type":"service_account",
"project_id":"fake-proj-id",
"private_key_id":"fake_pvt_key_id",
"private_key":'--... |
from numpy import *
from joelib.constants.constants import cc, mp
from joelib.physics.afterglow_properties import normT, adabatic_index
def sound_speed(gam, beta): # Sound speed prescription following LMR18
TTs = normT(gam, beta)
ada = adabatic_index(TTs)
return cc*(ada*(ada-1.)*(gam-1.)/(1+ a... |
import os,sys,time
import time
def RunPlaylist():
path = '/home/pi/Desktop/majestic-pi/current.txt'
file = open(path,'r')
files = file.readlines()
file.close()
global cinema
for file in files:
filename = file.strip()
if '.mp4' in... |
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, BooleanField, SelectField,\
SubmitField
from wtforms.validators import Required, Length, Email, Regexp
from wtforms import ValidationError
from flask_pagedown.fields import PageDownField
from ..models import Role, User
class NameForm(... |
# Generated by Django 3.2.5 on 2021-11-08 22:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sermar', '0012_auto_20211108_2144'),
]
operations = [
migrations.AddField(
model_name='locality',
name='protected_ar... |
# -*- coding: utf-8 -*-
import socket
import os, os.path
from sklearn.externals import joblib
from sklearn import datasets
import cPickle as pickle
#import io
import time
########## Prepare SVC computation #########################################################
''' Loading model '''
''' Pickle try '''
#fd = open('... |
from cmdstanpy import CmdStanModel
from tarpan.cmdstanpy.histogram import save_histogram
def run_model():
model = CmdStanModel(stan_file="eight_schools.stan")
data = {
"J": 8,
"y": [28, 8, -3, 7, -1, 1, 18, 12],
"sigma": [15, 10, 16, 11, 9, 11, 10, 18]
}
fit = model.sampl... |
import os, datetime
from glob import glob
import pandas as pd
import numpy as np
from datetime import timedelta
pd.options.mode.chained_assignment = None # default='warn'
PROB_WEAR = 'PROB_WEAR'
PROB_SLEEP = 'PROB_SLEEP'
PROB_NWEAR = 'PROB_NWEAR'
MHEALTH_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
def mhealth_timestam... |
# coding=utf-8
import json
import time
from ccws import Exchange
class Binance(Exchange):
ExchangeId = 'Binance'
def collect_data(self):
self.connect_redis()
self.run_websocketapp(
url_append=self.Config['url_append']
)
def process_order_data(self):
input_key... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
#!/usr/bin/python
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
from command_utils_base import FormattedParameter, CommandWithParameters,\
CommandWithPositionalParameters, PositionalParameter
from command_utils import CommandWithSubCommand
class DaosCommandBa... |
import sys
import random
import pickle
from tqdm import tqdm
try :
import numpy as np
except ModuleNotFoundError as error:
numpy = None
print("numpy module not found")
try :
import scipy.spatial.transform
except ModuleNotFoundError as error:
scipy = None
print("scipy module not found")
try :
... |
# Copyright 2016 Ifwe Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
# 3 examples of recursion
def factorial(n):
"""
Returns the factorial of the input integer
Time complexity: O(n)
Space complexity: O(n)
"""
assert n >= 0, f"Input value {n} is not a positive integer."
if n <= 1:
return 1
return n * factorial(n - 1)
def fibonacci(n):
"""
Returns ... |
# Check For Vowel in a sentence....
s = input("Enter String: ")
s = s.lower()
f = 0
for i in range(0, len(s)):
if(s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print("Yes, Present")
else:
print("No, Not Present")
|
import torch
from torch import nn
import torch.nn.functional as F
import model.resnet as models
class PPM(nn.Module):
def __init__(self, in_dim, reduction_dim, bins, BatchNorm):
super(PPM, self).__init__()
self.features = []
for bin in bins:
self.features.append(nn.Sequential(... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import sys
import json
import sqlite3
import subprocess
# SQLite3 aggregate 类
class Concatenate():
def __init__(self):
self.itemList = []
def step(self, value):
# print 'step(%r)' % value
self.itemList.append(value)
def finaliz... |
#
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobuf.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refl... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairs... |
from tkinter import *
from tkinter import ttk, Tk
from tkinter.font import Font
import tkinter
from PIL import Image,ImageTk
from tkinter import messagebox
from mystudent import Student
import os
from time import strftime
from datetime import datetime
from mystudent import Student
from mytrain import Train
from myface_... |
# -*- coding: utf-8 -*-
from datetime import datetime
import numpy as np
import pytest
from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
from pandas import (
Categorical, CategoricalIndex, DatetimeIndex, Index, Inter... |
# qubit number=3
# total number=31
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from... |
"""TODO(reclor): Add a description here."""
from __future__ import absolute_import, division, print_function
import json
import os
from pathlib import Path
import nlp
# TODO(reclor): BibTeX citation
_CITATION = """\
@inproceedings{yu2020reclor,
author = {Yu, Weihao and Jiang, Zihang and Dong, Yanfei and Fe... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ###... |
""" Reviews URLs """
# Django REST Framework
from rest_framework.routers import DefaultRouter
# Django imports
from django.urls import path, include
# Views
from .views import reviews as reviews_views
router = DefaultRouter()
router.register(r'reviews/(?P<service>[0-9]+)/service', reviews_views.ReviewViewSet, base... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.