text stringlengths 2 999k |
|---|
"""
Contains I/O functions
"""
import numpy
import theano
import logging
import sys
import tempfile
from collections import defaultdict
def build_character_dictionary(path, chars = {}):
with open(path, 'r') as fin:
lineno = 0
for line in fin:
lineno += 1
line = line.str... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.biomass import biomass
def test_biomass():
"""Test module biomass.py by downloading
biomass.csv and testing shape of
extracted data has 15... |
#!/usr/bin/python
# Filename: monitor-example.py
import os
import sys
# Import MobileInsight modules
from mobile_insight.monitor import OnlineMonitor
from mobile_insight.analyzer import MsgLogger
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Error: please specify physical port name and baudrate... |
"""Adds repostories/archives."""
########################################################################
# DO NOT EDIT THIS FILE unless you are inside the
# https://github.com/3rdparty/bazel-rules-curl repository. If you
# encounter it anywhere else it is because it has been copied there in
# order to simplify adding... |
from __future__ import absolute_import, unicode_literals
from setuptools import setup, find_packages
VERSION = '0.1.0'
NAME = 'pinsage-pytorch'
DESCRIPTION = 'This is a PinSage pytorch library.'
URL = 'https://github.com/rlji/pinsage-pytorch'
EMAIL = 'me@example.com'
AUTHOR = 'rlji'
# What python versions are suppor... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import logging
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Tuple, Optional, Union, List
import git
import yaml
from ogr.parsing import RepoUrl, parse_git_repo
from packit.exceptions import Packi... |
# def yetki_sorgula(page):
# def inner(role):
# if role == "admin" :
# print("{0} rolü {1} sayfasına ulaşabilir." .format(page, role))
# else:
# print("{0} rolü {1} sayfasına ulaşamaz." .format(page, role))
# return inner
# user1 = yetki_sorgula('arayüz')
# print(user1("... |
import numpy as np
import pandas as pd
import os
import joblib
def preparedata(df):
x=df.drop("y",axis=1)
y=df["y"]
return x,y
def save_model(model,filename):
model_dir="model"
os.makedirs(model_dir,exist_ok=True)
filepath=os.path.join(model_dir,filename)
joblib.dump(model,filepath) |
import random
import numpy as np
from typing import Dict, List
from flask import Flask
from flask_restx import Resource, Api
# from numpy import genfromtxt
from ubatch import ubatch_decorator
# from keras.models import load_model
from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import t... |
from api.caching.caching_shared import getDatabase
__author__ = 'Michael Pryor'
if __name__ == '__main__':
db = getDatabase()
db.place.remove()
db.geocode.remove() |
"""
Test for Bradley & Fayyad 1998 initialisation algorithm
"""
import unittest
import numpy as np
from datasets import testloader
from initialisations import bradley as bfinit
import kmeans
# pylint: disable=R0201,W0212
class BfTestSuite(unittest.TestCase):
"""Test suite for B&F"""
def test_code_runs(se... |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2 # noqa: E501
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class ItemRevguard(object):
... |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... |
import datetime
import logging
import os
import random
import re
import sys
import threading
import time
import traceback
from codalab.objects.permission import check_bundles_have_read_permission
from codalab.common import PermissionError
from codalab.lib import bundle_util, formatting, path_util
from codalabworker.fi... |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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... |
import gron
def test_version():
assert hasattr(gron, '__VERSION__')
|
# Copyright 2016-2019 California Institute of Technology.
#
# 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... |
from rply import ParserGenerator
from poketype.ast import Number, Boolean, NegNumber
class DataTypes():
def __init__(self, pg: ParserGenerator) -> None:
@pg.production('expression : NUMBER')
def expression_number(p):
return Number(int(p[0].getstr()))
@pg.production('expression : BOOLEAN')
def expressio... |
#!/usr/bin/env python
un='BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
pw='BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08'
import bz2
print bz2.BZ2Decompressor().decompress(un)
# huge
print bz2.BZ2Decompressor().decom... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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.apa... |
"""
Membrane test routines for voltage clamp experiments.
creates abf.MTs[sweep]={} #with keys like Ih, Ra, Rm, etc
Example usage:
abf=swhlab.ABF('../abfs/group/16701010.abf')
swhlab.memtest.memtest(abf) #performs memtest on all sweeps
swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did
p... |
import numpy as np
from lenstronomy.Cosmo.background import Background
from lenstronomy.LensModel.profile_list_base import ProfileListBase
import lenstronomy.Util.constants as const
__all__ = ['MultiPlaneBase']
class MultiPlaneBase(ProfileListBase):
"""
Multi-plane lensing class
The lens model deflecti... |
# The Plotly^^^plotly^^^ package
import plotly
# Importing ^^^numpy^^^
import numpy
def sigmoid(x):
return (1 + numpy.exp(-x)) ** -1
samplesPerDimension = 500
# Using numpy.linspace to create x and y values is from somewhere on ^^^plotly^^^'s website, most
# likely. It is a convenient way to do this, ... |
import maya.mel as mel
import maya
import maya.cmds as cmds
import sys
class TselectionWin(object):
"""
Base class for a dialog which works on the user's selection
"""
def __del__(self):
pass
def __init__(self, title, selectionFilter='<function <lambda>>', objects=[... |
# Copyright (c) 2020 Julian Bernhard, Klemens Esterle, Patrick Hart and
# Tobias Kessler
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from bark.world.opendrive import *
from bark.world import *
from bark.geometry import *
from bark.runtime impor... |
# -*- coding: utf-8 -*-
"""
Many aspects of the salt payload need to be managed, from the return of
encrypted keys to general payload dynamics and packaging, these happen
in here
"""
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import gc
# import sys ... |
# flake8: noqa
# -*- 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):
# Adding field 'Enquiry.is_published'
db.add_column('enquiry_enquiry', 'is_published',
... |
from gym.envs.mujoco import HalfCheetahEnv
import rlkit.torch.pytorch_util as ptu
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.envs.wrappers import NormalizedBoxEnv
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector import MdpPathCollector
from r... |
def reverseLists(list1) :
"""
原地用递归的方法反转list
:param list1:
:return:
"""
def helper(list1,left,right) :
if left < right :
list1[left] , list1[right] = list1[right] , list1[left]
helper(list1,left + 1 , right -1)
helper(list1,0,len(list1) - 1)
if __name__ == "... |
"""A module for the websockets-based Client for Jina."""
from typing import Callable, Optional
from contextlib import nullcontext, AsyncExitStack
from ..helper import callback_exec
from .helper import WebsocketClientlet
from ...importer import ImportExtensions
from ..base import BaseClient, InputType
from ...logging.p... |
import pickle
pranjal = {
'first_name': 'Pranjal',
'last_name': 'Patra',
'age': 35,
'NetWorth': 420.69,
'Vaccinated': True
}
with open("pranjal.bin", 'wb') as pranjal_file:
pickle.dump(pranjal, pranjal_file)
with open('pranjal.bin', 'rb') as pranjal_file:
pranjal_from_bin_file = pickle.lo... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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')
Clas... |
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2020/11/01
# @Author : Oscar Chen
# @Email : 530824679@qq.com
# @File : ops.py
# Description :base operators.
# --------------------------------------
import tensorflow as tf
def leaky_relu(x):
return tf.nn.leaky_relu(x, alpha=0.1... |
from __future__ import absolute_import
import six
from rest_framework.response import Response
from social_auth.models import UserSocialAuth
from django.conf import settings
from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.utils.html import format_html
from sentry.api.serial... |
# Copyright 2014 IBM Corporation. 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 ... |
"""Model Predictive Control with a Gaussian Process model.
Based on:
* L. Hewing, J. Kabzan and M. N. Zeilinger, "Cautious Model Predictive Control Using Gaussian Process Regression,"
in IEEE Transactions on Control Systems Technology, vol. 28, no. 6, pp. 2736-2743, Nov. 2020, doi: 10.1109/TCST.2019.2949757.
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Public Library of Science
#
# 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 limitat... |
# dataset settings
data_source = 'ImageNet'
dataset_type = 'RotationPredDataset'
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline = [
dict(type='RandomResizedCrop', size=224),
dict(type='RandomHorizontalFlip'),
]
test_pipeline = [
dict(type='Resize', size=256),
d... |
import argparse
from xml.etree import ElementTree as ET
import os
from pickle import dump
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("dir")
parser.add_argument("save")
args = parser.parse_args()
path = os.path.join(args.dir)
classes_nums = {"cat" : 0 , "dog" : 1}
keys = list(classe... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 4 2020
@Author: PouyaRZ
____________________________________________________
Plots to produce:
1. LCC of equipment for each scenario for all the individuals
2, SCC of equipment for each scenario for all the individuals
3. SCC vs LCC scatter plot.
4. SCC vs chiller typ... |
import logging
import os
import re
import shutil
from urllib.error import HTTPError
from markupsafe import escape
from sqlalchemy import (
and_,
false,
or_,
)
from sqlalchemy.orm import joinedload
from galaxy import util
from galaxy import web
from galaxy.tool_shed.util import basic_util
from galaxy.util.... |
import pandas as pd
from itertools import groupby
from operator import itemgetter
class SequenceGenerator:
def __init__(self, csvfile, jsThreshold):
self.datafile = csvfile
self.jsThreshold = jsThreshold
"""
Convert the input csv file into dataframe
"""
def _csv2df(self):
... |
from lib import action
class VaultReadAction(action.VaultBaseAction):
def run(self, path, kv_version, mount_point, version):
value = None
if kv_version == 1:
value = self.vault.kv.v1.read_secret(path=path, mount_point=mount_point)
elif kv_version == 2:
value = self... |
#!/home/zhuqingjie/env/py3_tf_low/bin/python
'''
@Time : 07.26 0026 下午 01:19
@Author : zhuqingjie
@User : zhu
@FileName: control.py
@Software: PyCharm
'''
'''
总的控制逻辑
1,control只向外部暴露一个端口,外部向control发请求,control根据mode来去调用其他server模块
2,同时还解决了外部不能直接访问ai节点的问题。主服务跑在ai节点,control服务跑在登陆节点,这样外部就能访问了
'''
import json, os, r... |
#coverage:ignore
""" Drivers for various PySCF electronic structure routines """
from typing import Tuple, Optional
import sys
import h5py
import numpy as np
from pyscf import gto, scf, ao2mo, mcscf, lo, tools, cc
from pyscf.mcscf import avas
def stability(pyscf_mf):
"""
Test wave function stability and re-op... |
r"""Importing this file must **not** initialize CUDA context. test_distributed
relies on this assumption to properly run. This means that when this is imported
no CUDA calls shall be made, including torch.cuda.device_count(), etc.
torch.testing._internal.common_cuda.py can freely initialize CUDA context when imported.... |
'''OpenGL extension EXT.robustness
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.robustness to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/EXT/robustness.txt
'''
from OpenGL import platform, constant, arrays
... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import sys
def check_hosts(contrib, plugin):
contrib_hosts = sorted(contrib['_meta']['hostvars'].keys())
plugin_hosts = sorted(plugin['_meta']['hostvars'].keys())
assert contrib_host... |
from __future__ import print_function
from builtins import str
from builtins import object
from lib.common import helpers
import threading
class Module(object):
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-Mimikatz extract kerberos tickets.',
'Author': [... |
CODEOWNERS = ["@esphome/core"]
|
from micromouse import mouse, maze
def begin():
"""
:return: None. This function begins micromouse operation.
"""
some_maze = maze.Maze(16)
some_mouse = mouse.Mouse(0, 0, some_maze)
print "Mouse initialized at (%d, %d)" % (some_mouse.x, some_mouse.y)
while some_mouse.maze.map[some_mouse.... |
"""
Copyright (c) 2017 Cyberhaven
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, distribute, sub... |
#
# Copyright (C) 2013-2015 eNovance SAS <licensing@enovance.com>
#
# Author: Frederic Lepied <frederic.lepied@enovance.com>
#
# 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://ww... |
"""Webhook handlers for mobile_app."""
from functools import wraps
import logging
import secrets
from aiohttp.web import HTTPBadRequest, Request, Response, json_response
from nacl.secret import SecretBox
import voluptuous as vol
from openpeerpower.components.binary_sensor import (
DEVICE_CLASSES as BINARY_SENSOR_... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#------- Profile, Student, Teacher Model -------
## TODO Refactor CharField To Text Field Modify HTMl maxlength. WRONG USAGE!!! ALLL WRONG
class Profile(models.M... |
import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name='y',
parent_name='scattergeo.marker.colorbar',
**kwargs
):
super(YValidator, self).__init__(
plotly_name=plotly_name,
... |
import sys
import tensorflow as tf
import numpy as np
import pydicom
from PIL import Image
import weights
#takes the root folder path and returns a list of pictures
def collect_pictures(path):
pic_list = []
full_path_list = []
for dirName, subdirList, fileList in os.walk(path):
# print('test')
for... |
from ibis.backends.pandas.execution.arrays import * # noqa: F401,F403
from ibis.backends.pandas.execution.decimal import * # noqa: F401,F403
from ibis.backends.pandas.execution.generic import * # noqa: F401,F403
from ibis.backends.pandas.execution.join import * # noqa: F401,F403
from ibis.backends.pandas.execution.... |
import logging
import os
import platform
import shutil
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
def ensure_wkhtmltopdf(): # pragma: no cover
if shutil.which("wkhtmltopdf") is None:
if platform.system() == "Windows":
wkhtmltopdf_path = _find_wkhtmltopdf_path()
... |
from django.shortcuts import redirect
from django.shortcuts import render
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from article.forms import ArticleForm
from article.models import Article
from block.models import Block
from comment.models import Comment
de... |
#!/usr/bin/env python
# import cte_calculator
from geometry_msgs.msg import PoseStamped
import rospy
from std_msgs.msg import Bool
from styx_msgs.msg import Lane
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from geometry_msgs.msg import TwistStamped
import math
from twist_controller i... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
"""
*aces-dev* Reference Config Generator
=====================================
Defines various objects related to the generation of the *aces-dev* reference
*OpenColorIO* config:
- :func:`opencolorio_config_aces.generate_c... |
from kivy.lang import Observable
import gettext
from constants import LOCALE_DIR
class Lang(Observable):
observers = []
lang = None
def __init__(self, defaultlang, transalte=None):
super(Lang, self).__init__()
self.ugettext = None
self.lang = defaultlang
self._translate =... |
import inspect
import os
import sys
import unittest
from processflow.lib.mailer import Mailer
from processflow.lib.util import print_line
class TestMailer(unittest.TestCase):
def test_send_mail_valid(self):
print '\n'
print_line(
'---- Starting Test: {} ----'.format(inspect.stack()[... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("CompareGeometryTest")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.MessageLogger = cms.Service(
"MessageLogger",
statistics = cms.untracked.vstring('c... |
# 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, software
# distributed under th... |
import logging
from mmcv.utils import get_logger
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Get root logger.
Args:
log_file (str, optional): File path of log. Defaults to None.
log_level (int, optional): The level of logger.
Defaults to logging.INFO.
Retu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Gabriel Fernandes <gabrielfernndss@gmail.com>
# Héricles Emanuel <hericles.me@gmail.com>
if __name__ == '__main__':
print('easter_egg!')
|
from django.db import models
from django.utils import timezone
category_choices = (
("Essential Services Pass", "Essential Services Pass"),
("Emergency Services Pass", "Emergency Services Pass"),
)
subcategory_choices = (
("ATM/Banking", "ATM/Banking"),
("Delivery Worker", "Delivery Worker"),
... |
# -*- coding: utf-8 -*-
import doctest
from datetime import date
import scippnexus
html_show_sourcelink = True
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'sphinx_autodoc_typehi... |
# Generated by Django 2.2 on 2019-04-18 13:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("images", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="image",
n... |
import unittest
from app.main.models import Pitches
from app import db
class PitchesModelTest(unittest.TestCase):
def setUp(self):
self.new_pitch=Pitches(pitch='new',comment='I love darkness', category='sports',user_id = 123)
def tearDown(self):
Pitches.query.delete()
def test __init__(s... |
string = input()
string_length = len(string)
print(string_length)
string = input()
if len(string) < 5:
print("Ошибка! Введите больше пяти символов!")
string = input()
if not string:
print("Ошибка! Введите хоть что-нибудь!")
string = input()
if len(string) == 0:
print("Ошибка! Введите хоть что-нибудь!")
|
# Natural Language Toolkit: Dependency Grammars
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Jason Narad <jason.narad@gmail.com>
# Steven Bird <stevenbird1@gmail.com> (modifications)
#
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
#
"""
Tools for reading and writing dependency tree... |
import os, sys
sys.path.append("C:\\BERTVision\\code\\torch")
import torch
import models.args
def get_args():
# retreive the general models.args and attach them here
parser = models.args.get_args()
# set search specific args
parser.add_argument('--model',
type=str,
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
#display records of students of roll no. 22 and 23.
import pickle
stu = {} #declare empty dictionary object; it will hold record
found = False
finObj = open('Stu.dat',"rb") #open binary file in read mode
searchKeys = [22,23]
#read from the file
try:
print("File Stu.dat store these records")
while True: #it wi... |
from hipchat import HipChatManager
import time
import configparser
_MAX_SLEEP_TIME = 5
_MIN_SLEEP_TIME = 2
_SPAM_EODBOT_URL = 3500
class HipChatMonitor:
def __init__(self, eodBotParser):
print("Initializing HipChatMonitor with eodBotParser: ",eodBotParser)
self.sleepTime = _MIN_SLEEP_TIME
self.lastIdChecked = ... |
# Copyright (c) 2013-2014 by California Institute of Technology
# 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,... |
class Solution:
def findNumbers(self, nums: List[int]) -> int:
bkt =[]
for n in nums:
count = str(n).count('')-1
print (str(n), count)
if count%2 == 0 :
bkt.append(count)
count =0
count =0
return len(bkt)
... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
from http import HTTPStatus
from deepdiff import DeepDiff
import pytest
from .utils.config import get_method, patch_method
def get_job_staff(job, tasks, projects):
job_staff = []
job_staff.append(job['assignee'])
tid = job['task_id']
... |
# Generated by Django 3.0.3 on 2020-02-11 20:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='choice',
name='votes',
fiel... |
import numpy as np
from pymoo.core.survival import Survival
from pymoo.util.nds.non_dominated_sorting import NonDominatedSorting
from pymoo.util.randomized_argsort import randomized_argsort
# ---------------------------------------------------------------------------------------------------------
# Survival Selection... |
from unittest import TestCase, skipIf
class TestAll(TestCase):
def test_passing(self):
pass
def test_erroring(self):
raise Exception("Ima broke")
def test_failing(self):
self.assertEquals(2 + 2 * 2, 8)
@skipIf(2 > 1, "Skip everytime")
def test_skipped(self):
pass... |
# 6851
# ^[a-zA-Z0-9]+(([_][a-zA-Z0-9])?[a-zA-Z0-9]*)*$
# EXPONENT
# nums:4
# EXPONENT AttackString:"a"+"0"*32+"!1 __NQ"
import re
from time import perf_counter
regex = """^[a-zA-Z0-9]+(([_][a-zA-Z0-9])?[a-zA-Z0-9]*)*$"""
REGEX = re.compile(regex)
for i in range(0, 150000):
ATTACK = "a" + "0" * i * 1 + "!1 __NQ"
... |
"""
This must be run only after seed_permissions_roles.py!
Creates default roles for all users currently in the database. Just runs through
Enrollments.
"""
from django.core.management.base import BaseCommand
from common.djangoapps.student.models import CourseEnrollment
from openedx.core.djangoapps.django_comment_c... |
import imgaug as ia
from imgaug import augmenters as iaa
import numpy as np
from scipy import misc
import imageio
import cv2
import imgaug as ia
import imgaug.augmenters as iaa
from imgaug.augmentables import Keypoint, KeypointsOnImage
ia.seed(1)
image = ia.quokka(size=(256, 256))
kps = KeypointsOnImage([
Keypo... |
from typing import Optional
import gym
import pytest
from ray.rllib.env.wrappers.moab_wrapper import _MoabBaseWrapper
from ray.tune.registry import ENV_CREATOR, _global_registry
@pytest.mark.parametrize("env_name, iterations",
[
("MoabMoveToCenterSim-v0", 10),
... |
"""
Functions related to ctf.
Currently only few that allow running ctffind from console or notebook.
Work in progress.
# Author: Vladan Lucic (Max Planck Institute for Biochemistry)
# $Id$
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from builtins... |
from multiprocessing import cpu_count
TEMP_DIRECTORY = "temp/data"
TRAIN_FILE = "train.tsv"
TEST_FILE = "test.tsv"
DEV_RESULT_FILE = "dev_result.tsv"
DEV_EVAL_FILE = 'dev_eval.txt'
RESULT_FILE = "result.csv"
SUBMISSION_FOLDER = "transformers"
SUBMISSION_FILE = "transformers"
MODEL_TYPE = "xlmroberta"
MODEL_NAME = "xlm... |
from .module import * # noqa
from .models import Trail, Hop # noqa
|
import logging
log = logging.getLogger(__name__)
import threading
import numpy as np
from atom.api import (Unicode, Float, Bool, observe, Property, Int, Typed,
Long, Value)
from enaml.core.api import Declarative, d_
from psi.core.enaml.api import PSIContribution
from ..util import copy_declara... |
"""Models for final hackbright project """
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app = Flask(__name__)
class Legislator(db.Model):
""" Info on current legislators. """
__tablename__ = "current_legislators"
legislator_id = db.Column(db.Integer, autoincrement=T... |
"""clothes_shop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... |
"""
@file setup.py
@brief Build and install the pycvm
@author The SCEC/UCVM Developers - <software@scec.usc.edu>
"""
from setuptools import setup
NAME = "ucvm_plotting"
FULLNAME = "ucvm_plotting with pycvm"
AUTHOR = "The SCEC/UCVM Developers"
AUTHOR_EMAIL = "software@scec.usc.edu"
MAINTAINER = AUTHOR
MAINTAIN... |
from flask_login import UserMixin
from . import db
#run the creat_all() command to create the database
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
last_name = db.Column(db.String(100))
first_name = db.Column(db.String(100))
email = db.Column(db.String(100), unique=True)
password... |
# -*- coding: utf-8 -*-
"""Scan service.
This module implements uploading a scan file to XNAT and adding a scan to the database.
Todo: Maybe the public method should be called add, and that should kick off an upload procedure, rather than the
other way around.
Todo: do we want to infer file type from extension? Or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.