content stringlengths 5 1.05M |
|---|
import pymel.core as pm
import pulse.joints
from pulse.buildItems import BuildAction, BuildActionError
class CleanupJointsAction(BuildAction):
def validate(self):
if not self.rootJoint:
raise BuildActionError('rootJoint must be set')
def run(self):
if self.removeEndJoints:
... |
##################################################################
#
# Imports
#
from enum import Enum
from coventreiya.morphology.affix.infix import Consonant as Cons_affix_abc
from coventreiya.morphology.affix.infix import Cons_infix_matcher
from coventreiya.morphology.affix.infix import Vowel as Vol_a... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# python argparse11.py 4
# python argparse11.py 4 -v
# python argparse11.py 4 -vv
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbose", action="count", default=0)
args = pa... |
import pytest
from treehugger.s3 import split_s3_url
def test_split_s3_url():
test_s3_url = 's3://bucket/key?versionId=7'
assert split_s3_url(test_s3_url) == ('bucket', 'key', '7')
def test_no_version_split_s3_url():
test_s3_url = 's3://bucket/key'
with pytest.raises(SystemExit):
split_s3_u... |
from sqlalchemy import create_engine, Column, Integer, String, DATETIME, TEXT, and_, or_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
# TODO: db_uri
# dialect+driver://username:password@host:port/database?charset=utf8
DB_URI = 'mysql+pymy... |
import os
from setuptools import find_packages, setup
NAME = 'wagtail_gallery'
DESCRIPTION = 'A simple gallery app built for Wagtail CMS and Django'
URL = 'https://gitlab.com/dfmeyer/wagtail_gallery'
EMAIL = 'me3064@gmail.com'
AUTHOR = 'Daniel F. Meyer'
REQUIRES_PYTHON = '>=3.5'
VERSION = '0.1.1'
LICENSE = 'MIT'
KEYW... |
"""Defines the Riemann language"""
from sympy import Matrix, Symbol
class Conserved (Symbol):
"""Represents a conserved variable
For multi-dimension variables, the dimension can be set with fields
or with dim.
The given a list of expressions, jacobian will compute the jacobian of the
expressions... |
from django.contrib.staticfiles.finders import BaseStorageFinder
from .storage import SassFileStorage
class CssFinder(BaseStorageFinder):
"""
Find static *.css files compiled on the fly using templatetag `{% sass_src "" %}`
and stored in configured storage.
"""
storage = SassFileStorage()
def... |
"""This script analyzes the signal of a sensor device"""
import itertools
import os
from pathlib import Path
from typing import List, Union, Tuple
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import find_peaks
from tqdm.contrib import tqdm
DATA_PATH = "DATA.bin"
def plot_... |
#coding:utf8
import logging
logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)
#exception
from exceptions import ApplicationException
from django.http import Http404
from django.http import HttpResponseBadRequest
#crypt
from itsdangerous import TimedJSONWebSignatureSerializer as Seri... |
# Copyright (c) 2016-2021, Thomas Larsson
# 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
# list of con... |
#!/usr/bin/env python2.7
import flask
import time
from flask import request
from flask import Flask, jsonify, Response
from apiJson import getJsonValues,getJsonValuesFromSingleProcesser
from multiprocessing import Pool
from flask import Flask
app = Flask(__name__)
_pool = None
def matrix_function(content):
respons... |
# coding: utf-8
import json
from django.conf import settings
from django.core import serializers
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from datetime import datetime
class UserProfile(models.Model):
# This field is required.
us... |
"""This module contains the general information for SystemIOController ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class SystemIOControllerConsts:
pass
class SystemIOController(ManagedObject):
"""This is SystemIOC... |
import re
def striptags(text):
return re.compile(r'<[^>]*>').sub('', text)
def strip_toplevel_anchors(text):
return re.compile(r'\.html#.*-toplevel').sub('.html', text)
|
# Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
# Copyright: (c) <spug.dev@gmail.com>
# Released under the AGPL-3.0 License.
import json
from .utils import AttrDict
# 自定义的解析异常
class ParseError(BaseException):
def __init__(self, message):
self.message = message
# 需要校验的参数对象
class... |
# Copyright 2017 The Forseti Security 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 ap... |
import os
import argparse
from os.path import expanduser
import numpy as np
import configparser
import shutil
import pandas as pd
def get_file_names(dataset_path):
"""
get_file_names(str) -> list of HGG files , LGG files
It return the paths of the LGG and HGG files present in BraTS dataset
"""
... |
"""Constants used in regular expressions."""
# Sentinel value.
# Useful to differentiate between an argument that has not been provided, and an
# argument provided with the value `None`.
SENTINEL_VALUE = object()
UNQUOTED_STRING = r'[^\s]+'
CAPTURE_UNQUOTED_STRING = r'[^\s]+'
ESCAPED_QUOTED_STRING = r""""(?:[^"\\]|... |
data = {'GoqMLRDAbGWn': 'LKSHL{th1s_is_a_trivial_t4sk_on_a_CTF_lmpFmMCm}', 'FChsdhyFoJb7': 'LKSHL{th1s_is_a_trivial_t4sk_on_a_CTF_OuEgWt8G}', 'cxjQDMhRaGEi': 'LKSHL{th1s_is_a_trivial_t4sk_on_a_CTF_OnKirjt3}', '6R9gh04xijvL': 'LKSHL{th1s_is_a_trivial_t4sk_on_a_CTF_KOodydBm}', '6XNGpyFKD8UI': 'LKSHL{th1s_is_a_trivial_t4s... |
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import IsAuthenticated
from app.viewsets import AppViewSet
from homework.api.filtersets import AnswerFilterSet
from homework.api.permissions import (
MayDeleteAnswerOnlyForLimitedTime, ShouldBeAnswerAuthorOrReadOnly, ShouldHaveP... |
import pickle
from intersim.datautils import *
from intersim.graph import InteractionGraph
from intersim.collisions import *
import torch
LOCATIONS = ['DR_USA_Roundabout_FT',
'DR_CHN_Roundabout_LN',
'DR_DEU_Roundabout_OF',
'DR_USA_Roundabout_EP',
'DR_USA_Roundabout_S... |
import matplotlib.pyplot as plt
import numpy as np
def fgairing(n):
from math import factorial
f = [0]*(n+1)
for j in range(1, n+1):
t1 = 1./((n-1)*factorial(n-1))
t2 = sum([1./factorial(e) for e in range(j, n)])
t3 = sum([1./factorial(e) for e in range(1, n)])
f[j] = factor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 13:35:44 2018
@author: charlie
Script to export study subcatchment attribute table to .csv
"""
from grass.pygrass.modules.shortcuts import database as db
basins = 'all_unique_wsheds_info'
csv_name = 'basins_data_with_intra_relief.csv'
db.out_o... |
#!/usr/bin/python
# Apple II Chat server program
import struct, socket, select, time
import xml.etree.ElementTree as ET
HOST = '' # Symbolic name meaning all available interfaces
PORT = 0x6502 # Apple II Chat non-privileged port
VERSION = 1
client_list = {}
chat_files = {}
chat_vers = []
... |
'''
Created on Oct 30, 2015
@author: kashefy
'''
from nose.tools import assert_equal, assert_false, \
assert_list_equal, assert_true
from mock import patch, PropertyMock
import os
import tempfile
import shutil
import numpy as np
from numpy.testing import assert_array_equal
import h5py
import nideep.eval.inference ... |
import PIL
from PIL import Image
import math
def changeColorDepth(image, colorCount):
# taken from ufp.image
if image.mode == 'RGB' or image.mode == 'RGBA':
ratio = 256 / colorCount
change = lambda value: math.trunc(value/ratio)*ratio
return PIL.Image.eval(image, change)
e... |
"""This class may be better inside dataClay [contrib] code.
However, I was having some issues regarding model registration and general
usability of the classes and splits. So that ended up here.
"""
import numpy as np
from dataclay import DataClayObject, dclayMethod
try:
from pycompss.api.task import task
fr... |
"""High-level plotly interface.
This module contains functions for creating various graphical components such
as tables, vectors, 3d polygons, etc. It also contains functions for nicely
formatting numbers and equations. The module serves as a high-level interface
to the expansive plotly visualization package.
"""
__a... |
from setuptools import setup
setup(
name='setup_case_py',
version='1',
packages=[''],
url='',
license='',
author='sarambl',
author_email='s.m.blichner@geo.uio.no',
description=''
)
|
import pylab
import numpy as np
import re
data = [i.split() for i in open('cluster_members.csv').readlines()]
print [len(i) for i in data]
nClusters = len(data)
nCols = 3
nRows = (nClusters+(nCols-1))/nCols
print nClusters, nRows, nCols
def getGroupPrefix(runPrefix):
groupPrefix = runPrefix.split('run')[0].strip... |
from __future__ import print_function
import os
import shlex, shutil, getpass
#import subprocess
import FWCore.ParameterSet.Config as cms
process = cms.Process("SiPixelInclusiveBuilder")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.cerr.enable = False
process.MessageLogger.cout = dic... |
#!/usr/bin/python3
"""
# Author: Scott Chubb scott.chubb@netapp.com
# Written for Python 3.7 and above
# No warranty is offered, use at your own risk. While these scripts have been
# tested in lab situations, all use cases cannot be accounted for.
"""
def list_cluster_details_payload():
payload = ({"me... |
def _apply_entities(text, entities, escape_map, format_map):
def inside_entities(i):
return any(map(lambda e:
e['offset'] <= i < e['offset']+e['length'],
entities))
# Split string into char sequence and escape in-place to
# preserve index positions.... |
"""
getCameraFeature.py
Demonstrates how to get some information about a camera feature.
Note that there are two places to get information about a feature:
1) getCameraFeatures
2) getFeature
getCameraFeatures can be used to query (generally) static information about
a feature. e.g. number of parameters, i... |
#!/usr/bin/env python3
#
# Import needed libraries
from mcpi.minecraft import Minecraft
import mcpi.block as block
import time
mc = Minecraft.create() # Connect to Minecraft, running on the local PC
# Create a monolith around the origin
mc.setBlocks(-1, -20, -1, 1, 20, 1, block.GLOWING_OBSIDIAN.id)
# A while loop t... |
def minSubArrayLen(target, nums):
min_window_size = 2 ** 31 - 1
current_window_sum = 0
window_start = 0
flag = False
for window_end in range(len(nums)):
current_window_sum += nums[window_end]
while current_window_sum >= target:
min_window_size = min(min_window_siz... |
import numpy as np
import chainer
from chainer import cuda,Function,gradient_check,report,training,utils,Variable
from chainer import datasets,iterators,optimizers,serializers
from chainer import Link,Chain,ChainList
from chainer import functions as F
from chainer import links as L
from chainer.training import ex... |
# Copyright (C) 2020 University of Oxford
#
# 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 t... |
# Copyright 2016 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 django.urls import path
from rest_framework.authtoken.views import obtain_auth_token
from api import views
app_name = 'api'
urlpatterns = [
path('feed/detail/', views.FeedDetailView.as_view(), name='feed-detail'),
path('feed/detail/no-auth/', views.FeedDetailAllowAnyView.as_view(), name='feed-detail-no-... |
from datetime import datetime
import numpy as np
inputs = open('../input.txt', 'r')
data = inputs.readlines()
guards = dict()
class SleepSession:
def __init__(self, falls_asleep_time):
self.asleep_time = falls_asleep_time
self.awake_time = None
def wake(self, wakes_up_time):
self.aw... |
from __future__ import annotations
from ._base import TelegramObject
class CallbackGame(TelegramObject):
"""
A placeholder, currently holds no information. Use BotFather to set up your game.
Source: https://core.telegram.org/bots/api#callbackgame
"""
|
# Generated by Django 3.1.4 on 2021-01-15 14:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dubitoapp', '0019_auto_20210115_0037'),
]
operations = [
migrations.AddField(
model_name='game'... |
# coding=utf-8
# Copyright 2020 The Trax 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 applicable law or a... |
class Solution:
def get_sub_XXX(self, root):
if root == None: return 0
if root.left == None and root.right == None:
return 1
return 1 + max(self.get_sub_XXX(root.left), self.get_sub_XXX(root.right))
def XXX(self, root: 'TreeNode') -> 'int':
return self.get_sub_XXX(r... |
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompany... |
#!/usr/bin/python
import sys
def gcd(a,b):
"""Compute the greatest common divisor of a and b"""
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
"""Compute the lowest common multiple of a and b"""
return a * b / gcd(a, b)
class Place(object):
def __init__(self, name, populari... |
import numpy as np
from numpy.testing import assert_allclose
from openamundsen.tridiag import solve_tridiag
from scipy.sparse import diags
def test_solve_tridiag():
N = 100
a = np.append([0], np.random.rand(N - 1))
b = np.random.rand(N)
c = np.append(np.random.rand(N - 1), [0])
x = np.random.rand... |
"""
Parsing ASN1_flat format files from dbSNP
Currently no used for loading dbsnp data, using dbsnp_vcf_parser instead.
Chunlei Wu
"""
from __future__ import print_function
import re
import glob
import os.path
from utils.common import anyfile
from utils.dataload import rec_handler
assembly_d = {
'GRCh38': 'hg38... |
# -*- coding: utf-8 -*-
"""
1985. Find the Kth Largest Integer in the Array
https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/
Example 1:
Input: nums = ["3","6","7","10"], k = 4
Output: "3"
Explanation:
The numbers in nums sorted in non-decreasing order are ["3","6","7","10"].
The 4th largest i... |
"""
file helpers
~~~~~~~~~~~~~
A set of various filesystem helpers.
:copyright: (c) 2016 by Dusty Gamble.
:license: MIT, see LICENSE for more details.
"""
__version__ = '1.0.2'
import os
import shutil
import hashlib
from natsort import natsorted
def file_extension(filepath):
filename, fi... |
import os
import configparser
class Config(object):
def __init__(self, filename):
self.__conf = configparser.ConfigParser()
self.__conf.read(filename, encoding='GBK')
def getConfig(self, section, item):
try:
itemDict = dict(self.__conf.items(section))
if item in... |
# Author: OMKAR PATHAK
# This program illustrates a simple Python encryption example using the RSA Algotrithm
# RSA is an algorithm used by modern computers to encrypt and decrypt messages. It is an asymmetric
# cryptographic algorithm. Asymmetric means that there are two different keys (public and private).
# For i... |
#This is a template code. Please save it in a proper .py file.
import rtmaps.types
import numpy as np
from rtmaps.base_component import BaseComponent # base class
from sklearn.utils import shuffle
import cv2
import pickle
import os
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import pandas as p... |
import frappe
from frappe.utils import getdate, cint, cstr, random_string, now_datetime
import datetime
def response(message, status_code, data=None, error=None):
"""This method generates a response for an API call with appropriate data and status code.
Args:
message (str): Message to be shown depend... |
import tempfile
import time
import os
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
def cap_to_file(capsys, write_to):
out = capsys.readouterr().out
with open(write_to, "a") as f:
f.write(out)
def test_barrier(capsys):
"""Verify that barrier blocks ... |
keyboard.send_keys("<shift>+<escape>") |
from django.db import models
import uuid
from django.contrib.auth.models import User
# When create a new model, run migration as follow:
# python3 manage.py makemigrations
# python3 manage.py migrate
class Author(models.Model):
# https://docs.djangoproject.com/en/2.1/topics/db/examples/one_to_one/
# https://... |
from jinja2 import Markup
def inertia(page_data, app_id="app"):
"""Inertia view helper to render a div with page data required by client-side
Inertia.js adapter."""
return Markup("<div id='{0}' data-page='{1}'></div>".format(app_id, page_data))
|
import io
import json
import shutil
import zipfile
from django.core import mail
from django.test import SimpleTestCase
from rest_framework.reverse import reverse
from rest_framework.test import APIClient
from config.settings.base import OSF_TEST_USER_TOKEN
from presqt.api_v1.utilities import hash_tokens
from presqt.a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author Christopher Wingard
@brief Load the PCO2W data from the uncabled, Coastal Endurance Surface
Moorings and processes the data to generate QARTOD Gross Range and
Climatology test limits
"""
import dateutil.parser as parser
import os
import pandas as pd
impo... |
# Copyright 2019-2020 Spotify AB
#
# 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 writin... |
from .plugins import plugins
from itsdangerous import TimedJSONWebSignatureSerializer
from datetime import datetime
from flask import current_app
# plugins = create_plugins()
db, migrate, bcrypt, login_manager = plugins
class User(db.Model):
id = db.Column(db.Integer, primary_key=True, nullable=False)
email ... |
"""phish_manager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
from django.db import models
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
#from django.db.models import Max
from oscar.apps.payment.abstract_models import AbstractSource
from web_payments.django.models import BasePayment
from web_... |
import unittest
from application.run import app
class ApiTest(unittest.TestCase):
def test_fake_request(self):
client = app.test_client(self)
response = client.get('/api/v1/demo')
assert response.status_code == 200, "Should return status code 200"
if __name__ == '__main__':
unittest.m... |
Паша очень любит кататься на общественном транспорте, а получая билет,
сразу проверяет, счастливый ли ему попался. Билет считается счастливым,
если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета.
Однако Паша очень плохо считает в уме, поэтому попросил вас написать
программу, которая про... |
import fire
import imageio
letter2morse = {"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
... |
from django.db import models
# Create your models here.
class AdminPage(models.Model):
name = models.CharField(max_length=20)
age = models.PositiveSmallIntegerField()
address = models.CharField(max_length=30)
def __str__(self):
return f'{self.name} {self.age} {self.address}' |
"""
============================================
Generate ROC Curves for all the classifiers.
============================================
We consider all the 31 features for classification.
For more details about IIITBh-keystroke dataset goto: https://github.com/aroonav/IIITBh-keystroke
For more details about CMU's da... |
# Generated by Django 3.1.3 on 2020-11-26 16:19
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0014_auto_20201126_1943'),
]
operations = [
migrations.AddField(
model_name='reservation',
n... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
setup(
name='project',
version='1.0',
description="This is a test project",
author="Ashley Camba",
author_email='ashwoods@gmail.com',
url='https://github.com/ashwoods/pywhale',
packages=find_packages(),
package... |
import json
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.stats.stats import pearsonr
from scipy.stats.stats import spearmanr
from sklearn.model_selection import train_test_split
from sklearn import ensemble
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LinearRegr... |
import logging
import pathlib
import pkg_resources
import re
from mopidy import config, ext
from tornado.web import StaticFileHandler
from .file_server import FileServer
__version__ = pkg_resources.get_distribution("Mopidy-Mowecl").version
logger = logging.getLogger(__name__)
class ConfigColor(config.String):
... |
from kivy.uix.widget import Widget
class TicTacToeBoard(Widget):
pass
|
from astropy.io import ascii
import numpy as np
import matplotlib.pyplot as plt
from astropy.time import Time
from astropy.table import Table
photbl = ascii.read('phot.dat')
#------------------------------------------------------------
bandlist = []
for inim in photbl['obs']:
bandlist.append(inim.split('-')[5])
photb... |
import configparser
import os
from kakao.common import fill_str_with_space
def is_in_range(coord_type, coord, user_min_x=-180.0, user_max_y=90.0):
korea_coordinate = { # Republic of Korea coordinate
"min_x": 124.5,
"max_x": 132.0,
"min_y": 33.0,
"max_y": 38.9
}
try:
... |
# Copyright 2022 DeepMind Technologies 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 agre... |
import aiohttp
from aiomodrinth.common import BASE_URL
async def get(way: str, headers=None, **kwargs) -> aiohttp.ClientResponse:
async with aiohttp.ClientSession(headers=headers) as s:
resp = await s.get(url=f"{BASE_URL}{way}", **kwargs)
return resp
async def post(way: str, payload: dict | lis... |
import numpy as np
import pytest
import scipy.sparse as ss
import scipy.special as sp
import scipy.stats as st
import scmodes.ebpm.sgd
import torch
import torch.utils.data as td
from .fixtures import *
def test__nb_llik(simulate_gamma):
x, s, log_mu, log_phi, oracle_llik = simulate_gamma
llik = scmodes.ebpm.sgd._... |
import yaml as _yaml
import pathlib as _pathlib
from importlib import import_module
from opics.libraries.catalogue_mgmt import download_library, remove_library
import sys
_curr_dir = _pathlib.Path(__file__).parent.resolve()
# read yaml file for available libraries in the catalogue
with open(_curr_dir / "catalogue.yam... |
from .schema import Schema, RootSchema |
"""
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumR... |
from colorthief import analyse_image
def test_analyse_image_not_fancy(capsys):
imgpath = 'images/sunset.jpg'
analyse_image(imgpath, do_print_fancy=False)
expected_stdout = """(163, 143, 178)
(9, 6, 5)
(99, 35, 32)
(246, 222, 171)
(151, 82, 64)
"""
captured = capsys.readouterr()
assert captured.out... |
# Write a function that reverses a string. The input string is given as an array of characters s.
# You must do this by modifying the input array in-place with O(1) extra memory.
# Example 1:
# Input: s = ["h","e","l","l","o"]
# Output: ["o","l","l","e","h"]
# Example 2:
# Input: s = ["H","a","n","n","a","h"]
#... |
import enum
class Locale(enum.Enum):
ENGLISH_AU = "en-AU"
ENGLISH_CA = "en-CA"
ENGLISH_GB = "en-GB"
ENGLISH_IN = "en-IN"
ENGLISH_US = "en-US"
ENGLISH_ES = "en-ES"
GERMAN = "de-DE"
SPANISH_ES = "es-ES"
SPANISH_MX = "es-MX"
FRENCH_CA = "fr-CA"
FRENCH_FR = "fr-FR"
ITALIAN ... |
"""
Conditional
===========
Rules can be applied conditionally using the `If` statement. These will make
more sense when you can define variables.
Examples::
If $dosub {
Substitute a -> b;
}
"""
import fontFeatures
from .util import compare
from . import FEZVerb
PARSEOPTS = dict(use_helpers=True)
... |
import numpy as np
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
from sklearn import svm
import os.path as p
current_dir = p.dirname(p.realpath(__file__))
# 2x500 matrix. value is random
matrix = np.random.randn(500, 2)
"""
calculate xor by each row, and get 1 or -1 convert from T... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
"""
@file RSNPUnitConnector.py
@brief send data to Unit and recieve data from Unit
@date $Date$
"""
import sys
import time
import json
sys.path.append(".")
# Import RTM module
import RTC
import OpenRTM_aist
import MQTTClient
# Import Service imple... |
#
# Copyright (c) 2020 Expert System Iberia
#
"""Credibility reviewer for a "query" sentence. I.e. a sentence that
may not be in the co-inform database yet. Produces a `QSentCredReview`
This assessment is done based on a reference credibility review for a
sentence in the co-inform DB, along with a similarity review be... |
from typing import Dict
from core.coordinate import Coordinate
class Edge:
destination: 'Node'
source: 'Node'
def __init__(self, source: 'Node', destination: 'Node'):
self.destination = destination
self.source = source
def __hash__(self):
return hash(f"{self.de... |
from .dialogue import * |
##
# See the file COPYRIGHT for copyright information.
#
# 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... |
# expected: fail
"""Tests for distutils.
The tests for distutils are defined in the distutils.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
from test import test_support
import distutils.tests
def test_main():
test_support.run_unittest(distutils.tests.test_suite... |
#!/usr/bin/env python3.7
import sys
from os.path import dirname, join, abspath
from CeTests import *
test = greaterThan()
test.run()
test = greaterThanOrEqual()
test.run()
test = lessThanOrEqual()
test.run()
test = lessThan()
test.run()
test = equal()
test.run()
test = notEqual()
test.run()
test = between()
test... |
############################################################################
# //KEYSTROKE// #
# //By Arvindcheenu.// #
# //2014-15.All rights reserved.// #
########... |
import pytest
import numpy as np
from flare.struc import Structure
from flare.env import AtomicEnvironment
def test_species_count():
cell = np.eye(3)
species = [1, 2, 3]
positions = np.array([[0, 0, 0], [0.5, 0.5, 0.5], [0.1, 0.1, 0.1]])
struc_test = Structure(cell, species, positions)
env_test = ... |
from flask import url_for
from meowbot.triggers import SimpleResponseCommand
from meowbot.conditions import IsCommand
from meowbot.context import CommandContext
class Homepage(SimpleResponseCommand):
condition = IsCommand(["homepage", "home"])
help = "`homepage`: link to Meowbot homepage"
def get_messa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.