text string | size int64 | token_count int64 |
|---|---|---|
from django.shortcuts import render, redirect
from .forms import SeasonForm, CurrentSeasonForm
from django.contrib import messages
from .functions import InitializeOtherSeasonValues
from StudentManager.models import Seasons, Students, CurrentSeason
from django.contrib.auth.decorators import login_required
from Dashboar... | 2,389 | 616 |
"""
https://leetcode.com/problems/leaf-similar-trees/
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their le... | 1,316 | 403 |
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.exceptions import (
NotFound,
APIException,
PermissionDenied,
)
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
ListAPIView,
UpdateAPIView
)
fro... | 3,797 | 1,213 |
import CapitalizeFile
import os
import sys
import unittest
from unittest.mock import patch
class TestCapitalization(unittest.TestCase):
def testUnitTestAssert(self):
self.assertEqual(1, 1)
def testCapitalizeFile(self):
with open('.inputFile', 'w') as inputFile:
inputFile.write(... | 862 | 256 |
from unittest import (TestCase, skipIf)
import numpy as np
from astropy.time import Time, TimeDelta
from pulses.dsp import DSP
from pulses.dedispersion import DeDisperser, noncoherent_dedispersion
from pulses.preprocess import PreProcesser, create_ellipses
from pulses.search import Searcher, search_shear, search_ell
... | 3,249 | 1,193 |
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin
from django.urls import include
from django.views.generic import RedirectView
from graphene_django.views import GraphQLView
from api.apps.gdrive.views import upload_timetable
urlpatterns = [
#url(r'^$', RedirectView... | 669 | 225 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__version__ 1.0.0
"""
#import operator
import random
#import matplotlib.pyplot
import time
def distance_between(a, b):
""" A function to calculate the distance between agent a and agent b.
Args:
a: A list of two coordinates for orthoganol axes.
... | 5,418 | 1,773 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from flask import Flask, render_template, current_app
from flask_migrate import Migrate
from flask_restful import Api
from config import Config, DevelopmentConfig, TestingConfig
from .database import db
from datetime import datetime
import random
import folium
im... | 13,451 | 4,256 |
import frappe
def validate(doc, method):
customer = frappe.db.get_value('Patient', doc.patient, 'customer')
doc.vc_owner = customer
| 142 | 48 |
from PyObjCTools.TestSupport import *
import os
from Foundation import *
try:
unicode
except NameError:
unicode = str
class TestNSJavaSetup (TestCase):
@max_os_level('10.5')
def testConstants(self):
self.assertIsInstance(NSJavaClasses, unicode)
self.assertIsInstance(NSJavaRoot, unicod... | 2,587 | 787 |
#!/usr/bin/env python
"""
Python source code - replace this with a description of the code and write the code below this text.
"""
from string import Template
g = '''
<div class="gold">
<img src="$url" alt="" height="128" />
<p>$text</p>
</div>
'''
def main():
import sys
output = []
gold = Temp... | 605 | 211 |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='dbtools',
version=open("VERSION.txt").read().strip(),
description='Lightweight SQLite interface',
author='Jessica B. Hamrick',
author_email='jhamrick@berkeley.edu',
url='https://github.com/jhamrick/dbtools',
packages=['dbt... | 807 | 243 |
from typing import List
# ./runmypy cat /usr/local/lib/python3.6/typing.py
def count_plus_first(it: List[int]):
return len(it) + it[0]
print(count_plus_first(list(range(10))))
| 184 | 76 |
import os
import pickle
class CookieInvalidException(Exception):
pass
class CookieRepository(object):
"""
Class to act as a repository for the cookies.
TODO: refactor to use http.cookiejar.FileCookieJar
"""
def __init__(self, cookie_directory=None, validate_fn=None):
self.c... | 1,442 | 402 |
class Gameentry:
"""Represents one entry of a list of high scores"""
def __init__(self,name,score):
self._name = name
self._score = score
def get_name(self):
return self._name
def get_score(self):
return self._score
def __str__(self):
return ' ... | 378 | 132 |
import datetime
from typing import List
from sqlalchemy.orm import ColumnProperty, DeclarativeMeta, class_mapper
from core.combine import AbstractModelCombine
from core.db_primitives import CoreField, CoreModel
from .sa_base import SABase, metadata, sa
class SQLAlchemyModelCombine(AbstractModelCombine):
metacl... | 6,326 | 1,837 |
# Copyright 2017 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... | 5,791 | 1,828 |
INITIAL_GENE_VALUE_LIMIT = 1
MUTATION_PROBABILITY = 0.3
MUTATION_SIZE = 0.2
GENERATION_SIZE = 8
VERBOSE = False
DECIMAL_PRECISION = 3 | 133 | 69 |
"""Providing custom values for oseoserver's settings."""
from django.conf import settings
from . import constants
def _get_setting(parameter, default_value):
return getattr(settings, parameter, default_value)
def get_mail_recipient_handler():
return _get_setting("OSEOSERVER_MAIL_RECIPIENT_HANDLER", None)
... | 6,752 | 1,868 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Core Initiative and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import json
import frappe
import math
import datetime
from frappe.model.document import Document
from inn.inn_hotels.doctype.inn_folio_transaction_ty... | 21,324 | 8,429 |
# stdlib
from typing import Any
# relative
from ...abstract.node import AbstractNodeClient
from ...enums import ResponseObjectEnum
from ..node_service.role_manager.role_manager_messages import CreateRoleMessage
from ..node_service.role_manager.role_manager_messages import DeleteRoleMessage
from ..node_service.role_man... | 1,128 | 310 |
""" iana_if_type
This YANG module defines YANG identities for IANA\-registered
interface types.
This YANG module is maintained by IANA and reflects the
'ifType definitions' registry.
The latest revision of this YANG module can be obtained from
the IANA web site.
Requests for new values should be made to IANA via
e... | 90,700 | 38,749 |
"""
Distances or similarities between time series are functions that computes a
distance measure or similarity measure pairwise and returns a matrix of
distances between each timeserie.
"""
import numpy as np
#import math
def general_comparison(X, method, kwargs={}):
"""Function which acts as a switcher and wr... | 5,307 | 1,495 |
# coding=utf-8
from random import randint
start = 1
end = 100
def check_leve(num_ori):
num = num_ori * 100 / 100
if 0 < num <= 19:
level = 1
elif 19 < num <= 19 + 17:
level = 2
elif 36 < num <= 36 + 15:
level = 3
elif 51 < num <= 51 + 13:
level = 4
elif 64 < num... | 1,381 | 610 |
import subprocess
import time
import matplotlib.pyplot as plt
def get_process_time():
return "%.2f mins" % (time.process_time() / 60)
def savefig(sname, bar=False):
barstr = "_bar" if bar else ""
git_rev_hash = (
subprocess.check_output("git rev-parse HEAD".split()).decode("utf-8").strip()
... | 1,399 | 550 |
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
from rclpy.qos import ReliabilityPolicy, QoSProfile
from messager.msg import Date
class Bootstrap(Node):
def __init__(self):
super().__init__('Bootstrap')
self.publisher_ = self.creat... | 1,792 | 598 |
"""Basic message handler."""
from ...base_handler import BaseHandler, BaseResponder, RequestContext
from ..messages.basicmessage import BasicMessage
class BasicMessageHandler(BaseHandler):
"""Message handler class for basic messages."""
async def handle(self, context: RequestContext, responder: BaseResponde... | 958 | 241 |
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
f... | 3,410 | 1,326 |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
if not "DJANGO_SETTINGS_MODULE" in os.environ:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'make_a_plea.settings.local')
app = Celery('apps.plea')
app.config_from_object('django.conf:settings', namesp... | 390 | 143 |
#
# Copyright (c) 2014-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import divi... | 3,676 | 1,162 |
import csv
import os
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://en.wikipedia.org/wiki/Comparison_of_text_editors")
bsObj = BeautifulSoup(html, "html.parser")
main_table = bsObj.findAll("table", {"class": "wikitable"})[0] #findAll生成列表
rows = main_table.findAll("tr... | 829 | 305 |
import pygame
from CombatSystem import playerEntity
from common import gameConstants as c
from CombatSystem.spriteSheetManager import spriteSheetManager
from pygame import mixer
class combatGame(object):
def __init__(self, size, screen):
self.clock = pygame.time.Clock()
# self.sSManager = spriteSh... | 4,267 | 1,224 |
"""
Binary vectors provide the basis for a representational approach
developed by Pentti Kanerva known as the Binary Spatter Code, with
the following key components:
(1) Randomly generated bit vectors with a .5 probability of a set bit in each component
(2) A *superposition* operator: this combines bit vectors elementw... | 18,337 | 5,982 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kstore', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
... | 2,380 | 698 |
import tensorflow as tf
from tensorflow.keras import backend
from tensorflow.keras.layers import Lambda
from tensorflow.keras import layers
def split(tensor, axis, keep_dims=False):
shape = backend.int_shape(tensor)
tensor_list = []
for i in range(shape[axis]):
sliced_tensor = Lambda(lambda x: x[:,i,:,:])(ten... | 6,194 | 2,101 |
"""Test the internals of a NavigatorConfiguration."""
import os
from copy import deepcopy
from ansible_navigator.configuration_subsystem import Constants
from ansible_navigator.configuration_subsystem import NavigatorConfiguration
from ansible_navigator.initialization import parse_and_update
from .defaults import TE... | 2,126 | 625 |
import discord
from discord.ext import commands
from discord.ext import tasks
import datetime
import asyncio
import decimal
import yaml
import re
import copy
import collections
from utils import juan_checks as checks
from utils import db
from utils import converters
VISITOR_ROLE = 582405430274293770
DEVELOPER_ROLE... | 14,703 | 4,759 |
class MyHTTPHandler(HTTPHandler):
def GET(self):
return "It's worked."
if __name__ == "__main__":
http = HTTPServer()
http.bind(("localhost", 9000))
http.serv("/", MyHTTPHandler)
http.start() | 221 | 78 |
import numpy as np
import cv2
import sys
from utils import *
class LidarModel:
def __init__(self,
img_map,
sensor_size = 21,
start_angle = -120.0,
end_angle = 120.0,
max_dist = 200.0,
):
self.sensor_size = sensor_size
self.start_an... | 2,383 | 969 |
import random,string
from datetime import datetime
from ..views.public import bp as public_bp
def rndChar():
"""随机字母:"""
str = ''
for i in range(4):
str += chr(random.randint(65, 90))
return str
def rndColor():
"""随机颜色1"""
return (random.randint(64, 255), random.randint(64, 255),... | 1,399 | 574 |
import datetime
import sys
sys.path.insert(0, "..")
from aniffinity import __about__ # noqa: E402
year = datetime.datetime.now().year
author = __about__.__author__
project = __about__.__title__
release = __about__.__version__
copyright = "{}, {}".format(year, author)
version = ".".join(relea... | 973 | 381 |
from rest_framework_csv.renderers import CSVStreamingRenderer
class FileRenderCN(CSVStreamingRenderer):
header = [
'staff_name',
'staff_type',
'create_time',
'update_time'
]
labels = dict([
('staff_name', u'员工用户名'),
('staff_type', u'员工类型'),
('create_t... | 716 | 247 |
import pandas as pd
from fastai.tabular.all import *
def get_token_features(df, tokens):
df1 = pd.DataFrame()
for tok in tokens:
df_tok = df[df['Token']==tok]
df_tok = df_tok.drop(['Token', 'Date'], axis=1)
col_names = []
for col in df_tok.columns:
if col == 'Timest... | 3,837 | 1,417 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
import unittest
from xlpo.readers import POFileTranslationsReader
from tests.base import BaseTestCase
class TestPOTranslationsReader(BaseTestCase):
def test_valid_files(self):
po_file = os.pa... | 1,645 | 535 |
# -*- coding: utf-8 -*-
"""Module for interacting with a user's youtube channel."""
import json
import logging
from typing import Dict, List, Optional, Tuple
from pytube import extract, Playlist, request
from pytube.helpers import uniqueify
logger = logging.getLogger(__name__)
class Channel(Playlist):
def __ini... | 6,576 | 1,700 |
from pony.py23compat import basestring
import unittest
from pony.orm import *
from pony import orm
from pony.utils import cached_property
from pony.orm.tests.testutils import raises_exception
class Test(unittest.TestCase):
@cached_property
def db(self):
return orm.Database('sqlite', ':m... | 2,821 | 1,002 |
# Generated by Django 2.2.9 on 2020-06-12 17:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0009_alertstatus_alarming_hosts"),
]
operations = [
migrations.AlterField(
model_name="alertstatus",
name="a... | 423 | 145 |
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Optional
import typer
from datamodel_code_generator import PythonVersion, chdir
from datamodel_code_generator.format import CodeFormatter
from datamodel_code_generator.parser.openapi import OpenAPIParser as OpenAPIModelParser
fro... | 3,545 | 1,074 |
import matplotlib.pyplot as plt
import csv
import time
x = []
y = []
# Draw a point based on the x, y axis value.
def draw_point(a,b):
# Draw a point at the location (3, 9) with size 1000
plt.scatter(a, b, s=1000)
# Set chart title.
plt.title("Square Numbers", fontsize=19)
# Set x axis label.
... | 752 | 283 |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
LedPin = 26 # pin26
def Switch_setup():
# GPIO.setmode(GPIO.BCM) # Numbers pins by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set pin mode as output
GPIO.output(LedPin, GPIO.HIGH) # Set pin to high(+3.3V) to off the led
def Swi... | 1,086 | 433 |
from src.encode_program import (
encode_program_as_number,
encode_label,
encode_var,
convert_instruction,
)
from .test_utils.constants import BASIC, GOTO, VARIABLES
from .test_utils.test_utils import read_program
import pytest
def test_encode_program_basic():
"""Encode program with NOOP, ADD, MONUS to program ... | 3,371 | 1,150 |
from django.contrib import admin
from .models import Publisher, Article
@admin.register(Publisher)
class PublisherAdmin(admin.ModelAdmin):
list_display = ["name", "domain"]
search_fields = ["name", "domain"]
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ["title", "publish... | 477 | 148 |
import _route
VINCENTY = 1
HAVERSINE = 2
def distance(lat1, lng1, lat2, lng2, formula=VINCENTY, iterlimit=20):
"""
Calculate distance between two points.
:param lat1: latitude of point 1 in degrees
:param lng1: longitude of point 1 in degrees
:param lat2: latitude of point 2 in degrees
:param... | 1,457 | 537 |
"""
Make sure that the content type cache (see ContentTypeManager) works correctly.
Lookups for a particular content type -- by model or by ID -- should hit the
database only on the first lookup.
First, let's make sure we're dealing with a blank slate (and that DEBUG is on so
that queries get logged)::
>>> from d... | 1,335 | 395 |
from . import requestform
from .requestform import RequestForm
| 63 | 15 |
import pandas as pd
import shutil as sh
langs = {
"name": ["Go", "Python", "TypeScript", "PHP"],
"score": [10, 9, 10, 6]
}
df = pd.DataFrame(langs, index = ["lang1", "lang2", "lang3", "lang4"])
print(df.loc["lang2"]) # Retorna um Pandas Series.
print("-" * sh.get_terminal_size().columns)
print(df.loc[["lang3... | 334 | 139 |
from __future__ import division
import json
from math import pi, sin
__version__ = '1.1.0'
WGS84_RADIUS = 6378137
def rad(value):
return value * pi / 180
def ring__area(coordinates):
"""
Calculate the approximate _area of the polygon were it projected onto
the earth. Note that this _area will... | 2,563 | 805 |
## based on OWASP risk rating
# clculates impact or likihood
def calc_scores(_dict):
# set Numerical Score
_dict["Numerical Score"] = int(0)
for key,value in _dict:
if "Score" in key:
continue
else:
_dict["Numerical Score"] = value + _dict["Numerical Score"]
... | 1,958 | 695 |
import os
from base64 import b64decode
from binascii import hexlify, unhexlify
from functools import reduce
from random import SystemRandom
from Crypto.Cipher import AES
def split_by_n(seq, n):
"""A generator to divide a sequence into chunks of n units."""
while seq:
yield seq[:n]
seq = seq[... | 4,760 | 1,767 |
import numpy as np
class Box:
def __init__(self, minCoords, maxCoords):
self.min = minCoords
self.max = maxCoords
self.planes = [*((i,self.min[i]) for i in range(3)),
*((i,self.max[i]) for i in range(3))]
self.size = [c2 - c1 for c1,c2 in zip(self.min,... | 3,739 | 1,338 |
from pymongo import MongoClient
# pprint library is used to make the output look more pretty
from pprint import pprint
import datetime
# connect to MongoDB
#To establish a connection to MongoDB with PyMongo you use the MongoClient class
client = MongoClient('mongodb://localhost:27017/')
#create a database object refer... | 1,032 | 257 |
import json
import os
from locust import HttpUser, task, between
from appian_locust import AppianTaskSet
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class GetFrontPageTaskSet(AppianTaskSet):
@task
def get_front_page(self):
self.client.get('/suite/tempo')
class GetAdminPageTaskSet(App... | 1,912 | 584 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from numpy.testing import assert_allclose
from ...stats import Stats
def test_Stats():
n_on, n_off, a_on, a_off = 1, 2, 3, 4
stats = Sta... | 612 | 242 |
# Generated by Django 2.1.8 on 2019-07-18 21:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('clothes', '0005_clothe_prepared_to_order'),
]
operations = [
migrations.AlterField(
model_name=... | 506 | 178 |
# encoding: utf-8
# (c) 2016-2022 Open Risk, all rights reserved
#
# ConcentrationMetrics is licensed under the MIT license a copy of which is included
# in the source distribution of concentrationMetrics. This is notwithstanding any licenses of
# third-party software included in this distribution. You may not use thi... | 1,235 | 432 |
# -*- encoding:utf-8 -*-
import re
## Path Config in here
readTargetFolder = 'My Path'
outTargetFolder = readTargetFolder + 'conv_'
headNumber = range(4,9)
indexNumber = range(1,100)
fileCategory = ['CM','CK','CL']
contentReg = r'<s n=\d+>(.*?)<\/s>'
def remove_tag(content):
cleanr = re.compile('... | 1,537 | 515 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 06:19:09 2020
@author: virati
Simple PMP buildup script
"""
import scipy.signal as sig
import matplotlib.pyplot as plt
import numpy as npo
import jax.numpy as np
from jax import grad, jit, vmap, jvp
from numpy import ndenumerate
import matplotlib... | 626 | 292 |
"""
pktperf provides pktgen helper scripts functions for pps
performance test.
"""
__version__ = "0.1.9"
__author__ = "junka"
__maintainer__ = "junka"
__license__ = "BSD"
| 171 | 70 |
from http import HTTPStatus
from typing import Iterable, Any
from flask_restful import Resource, fields, marshal_with, reqparse
from search_service.proxy import get_proxy_client
table_fields = {
"name": fields.String,
"key": fields.String,
# description can be empty, if no description is present in DB
... | 3,639 | 1,033 |
import logging
from typing import Tuple
import numpy as np
from dask import delayed
logger1 = logging.getLogger("cidan.LSSC.SpatialBox")
class SpatialBox:
def __init__(self, box_num: int, total_boxes: int, image_shape: Tuple[int, int],
spatial_overlap: int):
logger1.debug(
"... | 6,370 | 2,232 |
# ---
# jupyter:
# jupytext:
# formats: py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
from argparse impo... | 6,252 | 2,302 |
#this program doesn't use inbuild list functions except append
def insertion(arr): #inserting an element at a particular index of the list
global n
x = int(input("postion :"))
y = int(input("element :"))
arr.append(arr[-1])
for i in range(n-1,x,-1):
arr[i] =arr[i-1]
arr[x] = y
n = n+1 #incrementing the list ... | 502 | 195 |
n = 1260
coin_count = 0
coin_types = [500,100,50,10]
for coin in coin_types:
if n%coin != 0:
coin_count += n/coin
n %= coin
print(int(coin_count))
| 170 | 86 |
#!/usr/bin/env python
import random
from operator import itemgetter
import math
from datetime import datetime
import numpy
from sklearn import linear_model
from sklearn import cross_validation
from sklearn import metrics
from sklearn import ensemble
from model import Basic
from mkhtml import *
from utils import *
... | 5,283 | 2,078 |
import os
from pathlib import Path
from typing import Optional
import win32com.client
from pythoncom import com_error
from django.conf import settings
from django.utils import timezone
_PYTHON_PATH = str(Path(os.environ.get("VIRTUAL_ENV")) / "Scripts" / "python.exe")
LOCAL_SYSTEM = "NT Authority\\LocalSystem"
LOCAL... | 4,652 | 1,395 |
import json
import os
import os.path
from typing import List, Optional
import flask
from flask import Flask, Response, jsonify, request
import api
import corpus
import correct_runs_suggestor
import filestorage
import firestore_storage
import storage
import word_suggestor
app = Flask(__name__)
if os.environ.get("GA... | 5,777 | 1,920 |
"""High-level coding using python syntax to build HDL structures."""
import inspect
import ast
import textwrap
import sys
import re
from collections import deque
from hdltools.abshdl import HDLObject
from hdltools.abshdl.expr import HDLExpression
from hdltools.abshdl.signal import HDLSignal, HDLSignalSlice
from hdltoo... | 24,332 | 6,491 |
import numpy as np
import train_variants
a = np.arange(15)
print('a =', a)
print()
# ---------------------------------------
print('train_variants.create_sets(4, a, a)')
imgs, labs = train_variants.create_sets(4, np.copy(a), np.copy(a))
print(imgs)
assert len(imgs) == 4
assert len(labs) == 4
assert all([np.array_equ... | 1,085 | 469 |
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
#
# Simple example asset builder that processes *.foo files
#
import azlmbr.math
import azlmbr.asset.builder
imp... | 4,876 | 1,448 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import copy
import glob
import time
import tarfile
from io import BytesIO
from ruamel import yaml
from datetime import datetime, timedelta
from exceptions import AutocertError
from utils.dictionary import merge, head, body, head_body, keys_ending
from utils.ya... | 12,112 | 3,606 |
# coding: utf-8
"""
Canopy.Api
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa:... | 33,527 | 9,027 |
# -*- coding: utf-8 -*-
"""Brewtils Logging Utilities
This module streamlines loading logging configuration from Beergarden.
Example:
To use this just call ``configure_logging`` sometime before you initialize
your Plugin object:
.. code-block:: python
from brewtils import configure_logging, get_... | 9,994 | 2,885 |
from .read_from_file import read_from_csv, read_from_json_lines
| 64 | 23 |
import numpy as np
import acc_image_utils as acc
import time
t1 = time.time()
size=128
shape = (size,size,size,size)
n1 = np.zeros(shape, dtype=np.float32)
n2 = acc.gpu_rot4D(n1,55)
t2 = time.time()
print(t2 - t1)
| 216 | 101 |
import os
x = set()
with open(os.environ['PBS_NODEFILE'], 'r') as fh:
lines = fh.readlines()
for line in lines:
x.add(line)
name = 'machine-' + xxxMACHINExxx
with open(name, 'w') as fh:
for xi in x:
fh.write(xi)
| 228 | 103 |
import requests
from pysimplestorageservice.auth import AuthSigV4
class AmazonAWSManager(object):
"""
"""
def __init__(self, access_key, secret_key):
self.access_key = access_key
self.secret_key = secret_key
def get(self, prefix, filename, bucket):
"""
GET
"""... | 2,212 | 655 |
# @ based on InfoCAm
import torch
import torch.nn as nn
import torch.nn.functional as F
class CAM(nn.Module):
def __init__(self, model, feature, linear, factor, ksize, padding):
super().__init__()
self.model = model
self.feature = feature
self.linear = linear
self.factor = ... | 1,834 | 585 |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['add', 'multiply', 'subtract', 'divide']
# Cell
def add(x, y):
"Add x and y"
return x+y
def multiply(x, y):
"Multiply x and y"
return x*y
def subtract(x, y):
"Subtract y from x"
return add(x, -... | 376 | 157 |
"""
PYTHON driver for the ADXL-345 (3 axes accelerometer from Analog Device)
This driver use the I2C protocol to communicate (see README)
"""
import smbus
import adxl345.base
class ADXL345(adxl345.base.ADXL345_Base):
STD_ADDRESS = 0x1D
ALT_ADDRESS = 0x53
def __init__(self, alternate=False, port=1):
""" In... | 1,007 | 385 |
modulename = "Hex"
creator = "YtnomSnrub"
sd_structure = {
"activated": True
}
| 85 | 39 |
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
from fun... | 39,383 | 10,795 |
from rest_framework import serializers
from .models import Transaction,Sections
class TransactionSerializer(serializers.ModelSerializer):
class Meta:
model = Transaction
fields = '__all__'
def create(self, data):
print(100*"%")
print(data)
return Transaction.objects.cr... | 456 | 124 |
from django.db import models
class Company(models.Model):
name = models.CharField(max_length=200)
class Job(models.Model):
date = models.DateTime(auto_now_add=True)
city = models.ForeignKey(City)
company = models.ForeignKey(Company)
subject = models.ForeignKey(Subject)
| 295 | 94 |
import random
from typing import Any, Dict, List
def generate_match(
event: str,
comp_level: str,
set_number: int,
match_number: int,
red_teams: List[int],
blue_teams: List[int],
) -> Dict[str, Any]:
key = f"{event}_{comp_level}{set_number}m{match_number}"
if comp_level == "qm":
... | 4,601 | 1,698 |
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class BindNetworkModel(object):
"""Implementation of the 'bindNetwork' model.
TODO: type model description here.
Attributes:
config_templat... | 2,160 | 564 |
from the_bank import Account, Bank
if __name__ == "__main__":
bank = Bank()
print("==> [Bank] Adding not an account.")
bank.add(1)
print("\n==> [Bank] Adding a corrupted account.")
william_john = Account(
'William John',
zip='100-064',
value=6460.0,
ref='58ba2b9954c... | 1,571 | 591 |
# $Id$
#
# Copyright (C) 2004-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
from rdkit import RDC... | 5,219 | 2,055 |
import os
import sys
import subprocess
import shlex
from machine import *
class pdfCreator():
# declare and define all variables in the constructor
def __init__(self,dn,fn,inv):
self.invention = inv
self.file = self.create_TeX_file(dn,fn)
self.title = self.create_title()
self.a... | 3,188 | 967 |
# -*- coding: utf-8 -*-
#
# Copyright 2021 Nitrokey Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... | 3,099 | 934 |
from .data import DataModule # noqa: F401
| 43 | 17 |