text
string
size
int64
token_count
int64
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This is a tool developed for analysing transposon insertions for experiments using SAturated Transposon Analysis in Yeast (SATAY). This python code contains one function called transposonmapper(). For more information about this code and the project, see https://satay-...
11,042
3,473
# -*- coding: UTF-8 -*- import sys from datatable import datatable def process_file(file_id): print("1.export_data") print("2.generate_code & export_data") choose_idx = input("plase choose : ") if choose_idx == "1": datatable.export_data(file_id) elif choose_idx == "2": datatable...
1,975
639
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.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://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
1,268
391
import json import pytest from buildpg import Values from pytest import fixture from pytest_toolbox.comparison import CloseToNow, RegexStr from shared.actions import ActionTypes from shared.donorfy import DonorfyActor from shared.utils import RequestError from web.utils import encrypt_json from .conftest import Fact...
19,250
6,696
import colorama from lxman.cli import cli if __name__ == "__main__": cli()
85
34
########################################### # EXERCICIO 047 # ########################################### '''CRIE UM PROGRAMA QUE MOSTRE NA TELA TODOS OS NUMEROS PARES DE 1 E 50''' for c in range(1, 51): if c % 2 == 0: print(c, end=' ')
275
95
def handle(automata, result): """ This is a simple handler :param automata: the automata which yielded the result :type automata: :class:`Automata` :param result: the result of the automata :type result: bool """ print(result) if not result: automata.switch("ask m: try again:...
333
99
""" Copyright (C) 2018-2020 Intel Corporation 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 i...
2,090
649
import pygame from app.view.animations import Delay, FadeIn, FadeOut, ChooseRandom, FrameAnimate, MovePosition, DelayCallBack, MoveValue, SequenceAnimation, ParallelAnimation, Timeout from app.resources.event_handler import SET_GAME_STATE from app.resources import text_renderer, colours from app.resources.music import ...
5,470
1,945
import numpy as np import math import functools as fu import cv2 import random as rand def transform_points(m, points): """ It transforms the given point/points using the given transformation matrix. :param points: numpy array, list The point/points to be transformed given the transformation matri...
7,259
2,271
#sys.argv[1] = bin_dir, sys.argv[2] = flye_info, sys.argv[3] = output_dir, sys.argv[3] = output_dir import os, sys bin_name=sys.argv[1] bin_dir = sys.argv[2] output_dir = sys.argv[3] large_circular = [] flye_info = open(bin_dir + '/assembly_info.txt','r') read_info = True while read_info: read_info ...
665
311
LOGGEDOUT_SCSS_MSG = "User Logged out successfully" LOGIN_SCSS_MSG = "User Logged in successfully" INVALID_PASS = "Passowrd not valid" INVALID_USER = "User dose not exsists" INVALID_SESSION = "Session Invalid" INVALID_REQUEST = "Not a valid request" BAD_REQUEST = "Bad request" PASSWORD_EXPIERD = "Password Expier...
322
111
#!/usr/bin/env/python # # 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 # ...
1,611
454
#!/usr/bin/env python # -*- coding: utf-8-unix -*- """ FOO = Register("A:4 B:4", 0x12) BAR = Register("B:4 C:4", 0x23) # evals as int which is a register address print FOO == 0x12 # each field attribute returns a mask for that field print FOO.B == 0b00001111 print BAR.B == 0b11110000 # ERROR: Register definition is ...
7,247
2,327
#!/usr/bin/env python # coding=utf-8 # # Copyright © 2015-2016 VMware, Inc. All Rights Reserved. # # Licensed under the X11 (MIT) (the “License”) set forth below; # # you may not use this file except in compliance with the License. Unless required by applicable law or agreed to in # writing, software distributed under ...
83,916
25,022
import pathlib from django.conf import settings from django.core import mail from django.core.mail import EmailMessage from django.test import TestCase class TestSendMail(TestCase): def _callFUT(self, encoding='utf-8', has_attachment=False): from myapp.utils import my_send_mail my_send_mail(encod...
2,463
906
#! encoding = utf-8 """ Practice French conjugaison """ import sys from os.path import isfile from time import sleep from sqlite3 import Error as dbError from PyQt5 import QtWidgets, QtCore from PyQt5.QtGui import QTextOption, QKeySequence from dictionary import TENSE_MOODS, PERSONS from dictionary import conjug, con...
34,133
11,223
import matplotlib.pyplot as plt, numpy as np, pandas as pd # general functions for plotting # Tim Tyree # 7.23.2021 def PlotTextBox(ax,text,text_width=150.,xcenter=0.5,ycenter=0.5,fontsize=20, family='serif', style='italic',horizontalalignment='center', verticalalignment='center', color='black',use_turnoff_axis=T...
2,515
941
from lambdatest import Operations from unicode1 import convert file_name = "ocr.json" k = Operations() jsonObj = k.load_Json(file_name) dictData = convert(jsonObj) endpoints_list = dictData["endpoints"] enp_path = [] dfp = {} for i in endpoints_list: enp_path.append(i["path"]) try: dfp[i["path"]]=i['result'] excep...
331
128
import requests from decouple import config import datetime from calendar import monthrange import psycopg2 import time def create_db_table(): con = psycopg2.connect(database=config("DB_NAME"), user=config("DB_USER"), password=config("DB_PASSWORD"), host=confi...
4,804
1,486
import numpy as np import pandas as pd import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable def graph(lhs, rhs, support, confidence, lift, data=None, fig_scale=2, fon...
3,446
1,152
import readExcel import modifyFile import sys import time import sendEmail def main (excelFilePath): emailConfigPath = "/tmp/emailConfig" emailFilePath = "/tmp/emails" sys.system ("mkdir -p" + emailConfigPath) sys.system ("mkdir -p" + emailFilePath) #Read excel file excel = readExcel.readExce...
1,833
572
# type: ignore import cv2 import numpy as np TWO_PI = 2 * np.pi def kmeans_periodic(columns, intervals, data, *args, **kwargs): """Runs kmeans with periodicity in a subset of dimensions. Transforms columns with periodicity on the specified intervals into two columns with coordinates on the unit circle...
2,314
703
import torch import torch.nn as nn import torch.nn.functional as F from models.embedding import TokenEmbedding, PositionalEncoding, TransformerEmbedding from models.attention import ScaledDotProductAttention, MultiHeadAttention, FeedForward from models.layers import EncoderLayer, DecoderLayer class Encoder(nn.M...
6,599
2,202
# _*_ coding:UTF-8 _*_ """ 该文件定义了模拟环境中交易动作相关的模型 并非虚拟股市原本的模型,做了一些适应性的调整,取消了全部外键。 """ from django.db import models import uuid from decimal import Decimal import time from .clients import BaseClient from .sim_market import SimMarket from .sim_clients import SimHoldingElem, SimCommissionElem, SimTransactionElem from .s...
23,299
7,613
test = { 'name': 'q3_2_3', 'points': 1, 'suites': [ { 'cases': [ { 'code': '>>> # this test just checks that your classify_feature_row works correctly.;\n' '>>> def check(r):\n' '... t = test_my_features....
906
239
# Copyright (C) 2002-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Base klasa dla MIME type messages that are nie multipart.""" __all__ = ['MIMENonMultipart'] z email zaimportuj errors z email.mime.base zaimportuj MIMEBase klasa MIMENonMultipart(MIMEBase): """Base ...
695
209
from notifications import ImproperlyInstalledNotificationProvider try: from slack_sdk import WebClient except ImportError as err: raise ImproperlyInstalledNotificationProvider( missing_package='slack_sdk', provider='slack' ) from err from notifications import default_settings as settings from . i...
682
189
from django.dispatch import Signal points_awarded = Signal(providing_args=["target", "key", "points", "source"])
114
37
from sympy.functions import exp from symplyphysics import ( symbols, Eq, pretty, solve, Quantity, units, S, Probability, validate_input, expr_to_quantity, convert_to ) # Description ## Ptnl (fast non-leakage factor) is the ratio of the number of fast neutrons that do not leak from the reactor ## core during th...
1,798
609
import re def count_letters(text): return len(re.findall(r"[a-zA-Z]", text)) def count_punctuation(text): return len([x for x in text if x in '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~']) lines = [] with open("text.txt", "r") as f: content = f.readlines() for index, line in enumerate(content): l...
599
232
from flask_wtf import FlaskForm from wtforms import StringField,SubmitField,BooleanField,PasswordField from wtforms.validators import Required,DataRequired,Length class LoginForm(FlaskForm): username = StringField('username', validators=[DataRequired(), Length(1, 32)]) password = PasswordField('Password', vali...
422
116
from django.db import models from . import TimestampedModel class UserAgent(TimestampedModel): """ Representation of HTTP user agent string from reading API request. Exists as a separate model for database normalisation. """ user_agent_string = models.TextField(db_index=True, unique=True, null=Fa...
929
249
def pigeonHoleSort(nums): minNumbers = min(nums) maxNumbers = max(nums) size = maxNumbers - minNumbers + 1 holes = [0] * size for x in nums: holes[x - minNumbers] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 nums[i]...
428
172
# parsers.py from werkzeug.datastructures import FileStorage from flask_restplus import reqparse file_upload = reqparse.RequestParser() file_upload.add_argument('resource_csv', type=FileStorage, location='files', required=True, ...
345
83
# Copyright 2021 The Kubeflow 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 agreed to in...
4,410
1,243
# # Constant Price Market Making Simulator # # simulate different liquidity provision and trading strategies # from typing import Tuple import csv import numpy as np import pandas as pd from numpy.random import binomial, default_rng # TODO: switch to decimal type and control quantization. numeric errors will kill us...
10,548
4,383
""" rave input backend using the SDL2 library. """ import sys import sdl2 import rave.log import rave.events import rave.backends from ..common import events_for from . import keyboard, mouse, touch, controller BACKEND_PRIORITY = 50 ## Module API. def load(): rave.backends.register(rave.backends.BACKEND_INPUT,...
1,184
438
try: from setuptools import setup, find_packages except ImportError as e: from distutils.core import setup dependencies = ['docopt', 'termcolor', 'requests'] setup( name = 'pyDownload', version = '1.0.2', description = 'CLI based download utility', url = 'https://github.com/Dhruv-Jauhar/pyDownload', author = ...
862
309
from django.db import models from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) # it can be left blank created = models.DateTimeField(auto_now_add=True) # this will automatically add date and time and the ...
792
227
class Stuff: def __init__(self): return @staticmethod def print_logo(): print ''' ____ _ _ __ | _ \ ___ ___| |_ ___ _ __ ___ | '_ \| |_) / _ \/ __| __/ _ \| '__/ _ \\ | |_) | _ < __/\__ \ || (_) | | | __/ | .__/|_| \_\___||___/\__\___/|_| \___| |_| ''' cla...
603
227
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import time import json with open("coverage.json", "r") as file: timestamp = str(int(time.time())) data = json.load(file)["data"][0] lines_covered = str(data["totals"]["lines"]["covered"]) lines_valid =...
558
195
import pytest import allure from data.parameters import data_parameters @allure.feature('UI TEST:open page') def test_open_page(app): with allure.step('Открываем страницу калькулятора'): app.open_calculator_page() assert '/calculator' in app.get_path_current_url() @allure.feature('UI TEST: Check ...
1,063
349
import asyncio import json import time from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from diem import AuthKey, testnet, utils from indy import anoncreds, wallet from indy import pool from get_schema import get_schema from diem_txn import create_diem_script, create_diem_raw_txn, sign_a...
6,383
2,308
import pytest from GoogleCloudFunctions import resolve_default_project_id, functions_list_command @pytest.mark.parametrize('project, credentials_json, expected_output,expected_exception', [ ("some-project-id", {"credentials_json": {"type": "service_account", "project_id": "some-project-id"}}, "some-project-i...
2,173
618
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' BATCH_SIZE = 128 MAX_WORDS_IN_REVIEW = 200 # Maximum length of a review to consider EMBEDDING_SIZE = 50 # Dimensions for each word vector stop_words = set({'ourselves', 'hers', 'between', 'yourself', 'again', 'there', 'a...
11,938
3,982
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------- # cssqc/__init__.py # # css quality control # ---------------------------------------------------------------- # copyright (c) 2014 - Domen Ipavec # Distributed under The MIT License, see LICENSE # -------...
3,492
1,112
from abstract.instruccion import * from tools.console_text import * from tools.tabla_tipos import * from storage import jsonMode as funciones from error.errores import * from tools.tabla_simbolos import * class update_st (instruccion): def __init__(self, id1, id2, dato, where, line, column, num_nodo): su...
3,351
1,096
# import sys # sys.path.appenval.'/usr/local/lib/python2.7/site-packages') import dlib import scipy import skimage as io import numpy as np def dlib_selective_search(orig_img, img_scale, min_size, dedub_boxes=1./16): rects = [] dlib.find_candidate_object_locations(orig_img, rects, min_size=min_size) # pro...
1,791
677
# each JSON has: {instructions}, {opt}, {compiler} # MODEL SETTINGS: please set these before running the main # mode = "opt" # Labels of the model: [opt] or [compiler] samples = 3000 # Number of the blind set samples fav_instrs_in = ["mov"] # Set of instructions of which DEST register should be extracted [IN] fav_i...
3,953
1,346
from django.contrib import admin from django.conf.urls import url, include # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ ]
206
56
from jsonlink import JsonLink from globals import read_json_file class Task(JsonLink): def __init__( self, name="", task_description=None, step_groupings=[], global_values={}, global_hooks={}, steps=[], python_dependencies=[], keywords_file_p...
2,266
673
# Copyright © 2020 Siftrics # # 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, ...
5,252
1,504
from django.contrib import admin from .models import Attachment, EmailHeaders, Newsletter admin.site.register(EmailHeaders) admin.site.register(Attachment) admin.site.register(Newsletter)
190
53
fullform = input("Enter a full form: ") words = fullform.split(" ") acro = "" for word in words: acro+=word[0] print("Acronym is ", acro)
145
53
class Usuario: def __init__(self, id, usuario, passw): self.id = id self.usuario = usuario self.passw = passw def autenticar(self, usuario, passw): if self.usuario == usuario and self.passw == passw: print("La autenticación fue correcta") return True...
514
160
from skimage import img_as_int import cv2 import numpy as np from pylab import * import scipy.ndimage.filters as filters #img = cv2.imread('images/profile.jpg', 0) img = cv2.imread('images/moon.jpg',0) sobel_operator_v = np.array([ [-1, 0, 1], [-2, 0 ,2], [-1, 0, 1] ]) sobelX = cv2.Sobel(img, -1...
802
409
# Relative imports from ._estimator import ProphetEstimator from ._predictor import ProphetPredictor, PROPHET_IS_INSTALLED __all__ = ['ProphetEstimator', 'ProphetPredictor', 'PROPHET_IS_INSTALLED']
199
76
""" <Filename> factoids/__init__.py <Purpose> Used to print saesh factoids. It implements the following command: show factoids [number of factoids]/all """ import seash_exceptions import random import os # List which will contain all factoids after fatching from a file. factoids = [] def initiali...
4,995
1,620
import json import os import sys from datetime import date import pytest from dateutil.relativedelta import relativedelta from telegram_bot_calendar import DAY, MONTH, YEAR from telegram_bot_calendar.detailed import DetailedTelegramCalendar, NOTHING myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert...
2,985
1,237
import collections import types from optparse import make_option from django.db.models.loading import get_model from django.core.management.base import BaseCommand, CommandError from django.db.models.fields import EmailField, URLField, BooleanField, TextField def convert(name): return name.replace('_', ' ').capita...
4,964
1,599
"""Gives users direct access to class and functions.""" from logical.logical import\ logical,\ nullary, unary, binary, every,\ nf_, nt_,\ uf_, id_, not_, ut_,\ bf_,\ and_, nimp_, fst_, nif_, snd_, xor_, or_,\ nor_, xnor_, nsnd_, if_, nfst_, imp_, nand_,\ bt_
291
114
import queue import select import socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(False) server.bind(('localhost', 9999)) server.listen(5) inputs = [server] outputs = [] message_queues = {} while inputs: readable, writable, exceptional = select.select( inputs, outputs,...
1,667
514
from .segmentA import SegmentA class Transfer: def __init__(self): self.segmentA = SegmentA() def toString(self): return self.segmentA.content def amountInCents(self): return self.segmentA.amountInCents() def setSender(self, user): self.segmentA.setSenderBank(user.b...
1,118
356
#!/usr/bin/python import sys import codecs import ipaddress as ip import pandas as pd from datetime import datetime as dt class BroLogFile: def doSeparator(self, fields): sep = fields[1] if len(sep) == 1: # a literal? self.separator = sep elif sep[:2] == '\\x': ...
4,689
1,355
# simple_checkboxes.py import logging from os.path import basename from pathlib import Path import jsonschema import pytest # from reportlab.pdfbase import pdfform import yaml from reportlab.pdfgen import canvas uischema = yaml.safe_load(Path("jsonforms-react-seed/src/uischema.json").read_text()) form_schema = yaml....
8,288
2,494
''' Assuming the following tag-separated format: VBP+RB VBP VBZ+RB VBZ IN+DT IN (etc.) ''' class Pos_mapper: def __init__(self, filepath): with open(filepath,'r') as f: lines = f.readlines() self.pos_map = {} self.unknowns = [] for ln in lines: if ln: ...
701
232
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Functions to represent potentially large integers as the shortest possible human-readable and writable strings. The motivation is to be able to take int ids as produced by an :class:`zc.intid.IIntId` utility and produce something that can be written down and typed in by...
4,051
1,260
#!/usr/bin/python3 import argparse, os from collections import defaultdict from lib.data import * from lib.exporters import * from lib.filters import * from lib.parsers import * def parse_arguments(): arg_parser = argparse.ArgumentParser(description='chokitto') arg_parser.add_argument('input', ...
2,882
1,023
# -*- coding: utf-8 -*- """Torrent.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1Uo1_KHGxOe_Dh4-DjQyEb0wROp-tMv0w """ TorrName = 'YOUR TORRENT NAME' FolderPath = f'/content/drive/My Drive/{TorrName}' TorrPath = f'{TorrName}.torrent' def init...
736
281
""" Utilities that help with wrapping various C structures. """ class StructWithDefaults: """ A class which provides a convenient interface to create a C structure with defaults specified. It is provided for the purpose of *creating* C structures in Python to be passed to C functions, where sensible ...
3,197
847
import dash_html_components as html def chart_panel() -> html.Div: return html.Div(className='row', children=[html.Div(id='output', className='column')])
160
49
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- import os, os.path as path, shutil import datetime from .file_match import file_match from .file_util import file_util class dir_util(object): @classmethod def is_empty(clazz, d): return clazz.list(d) == [] @cl...
2,144
684
import os import argparse from struct import pack from twisted.internet import reactor from twisted.application.reactors import Reactor from twisted.internet.endpoints import HostnameEndpoint from twisted.internet.protocol import ClientFactory from pyrdp.core.ssl import ClientTLSContext from pyrdp.mitm.layerset impor...
24,540
10,496
# # # Copyright (c) 2020. Yue Liu # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
8,241
3,039
#!/usr/bin/env python3 import argparse import sys from concurrent.futures import ThreadPoolExecutor import pandas as pd import altair as alt def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-a', '--application', help='Plot only the given application') parser.add_argument('data', hel...
1,993
638
__version__ = '7'
18
9
from rest_framework import generics from rest_framework import filters from bluebottle.utils.permissions import IsAuthenticated, IsOwnerOrReadOnly, IsOwner from rest_framework_json_api.pagination import JsonApiPageNumberPagination from rest_framework_json_api.parsers import JSONParser from rest_framework_json_api.vie...
2,918
827
from gen3_etl.utils.cli import default_argument_parser from gen3_etl.utils.ioutils import JSONEmitter import os import re DEFAULT_OUTPUT_DIR = 'output/default' DEFAULT_EXPERIMENT_CODE = 'default' DEFAULT_PROJECT_ID = 'default-default' def emitter(type=None, output_dir=DEFAULT_OUTPUT_DIR, **kwargs): """Creates a ...
1,646
541
import logging import numpy as np from sklearn.utils import check_random_state from csrank.constants import DISCRETE_CHOICE from csrank.dataset_reader.tag_genome_reader import critique_dist from csrank.dataset_reader.util import get_key_for_indices from ..tag_genome_reader import TagGenomeDatasetReader from ...util i...
6,266
1,801
# coding: utf-8 from geoalchemy2 import Geometry from sqlalchemy import BigInteger, Column, DateTime, Float, Integer, SmallInteger, Table, Text, TEXT, BIGINT from sqlalchemy.dialects.postgresql import HSTORE from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base Base ...
12,614
4,029
import logging from keyvault import secrets_to_environment from twinfield import TwinfieldApi logging.basicConfig( format="%(asctime)s.%(msecs)03d [%(levelname)-5s] [%(name)s] - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO, ) secrets_to_environment("twinfield-test") tw = TwinfieldApi()...
321
132
# Generated by Django 2.1.2 on 2018-10-27 17:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('magicdb', '0001_initial'), ] operations = [ migrations.AlterField( model_name='card', name='number', fie...
397
135
# -*- coding: utf-8 -*- # Copyright © 2017 Taylor C. Richberger <taywee@gmx.com> # This code is released under the license described in the LICENSE file from __future__ import division, absolute_import, print_function, unicode_literals class StorageImage(Instance): def __init__(self, xml): name sfi_name ...
385
123
def prob_14(n): if n < 2: return False for i in range(2, n): if n % i == 0: return False return True
140
50
import numpy as np import matplotlib.pyplot as plt def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False): ''' Very close to numpy.percentile, but supports weights. Note: quantiles should be in [0, 1]! :param values: numpy.array with da...
2,968
1,081
alist = [1,2,3,5,5,1,3] b = set(alist) c = tuple(alist) print(b) print(c) print([x for x in b]) print([x for x in c])
123
65
from ocp_resources.resource import NamespacedResource class KubevirtMetricsAggregation(NamespacedResource): api_group = NamespacedResource.ApiGroup.SSP_KUBEVIRT_IO
170
59
from django.conf.urls import patterns, url from metashare.settings import DJANGO_BASE urlpatterns = patterns('metashare.accounts.views', url(r'create/$', 'create', name='create'), url(r'confirm/(?P<uuid>[0-9a-f]{32})/$', 'confirm', name='confirm'), url(r'contact/$', 'contact', name='contact'), url(...
1,329
443
class ResizingArrayQueue(object): def __init__(self, lst=None, capacity=2): self.capacity = capacity self.lst = [None] * self.capacity self.head = 0 self.tail = 0 self.n = 0 def __len__(self): """ >>> queue = ResizingArrayQueue() >>> len(queue) ...
4,090
1,246
from utilmeta.conf import Env class ServiceEnvironment(Env): PRODUCTION: bool = False OPS_TOKEN: str = '' JWT_SECRET_key: str = '' DATABASE_USER: str = '' DATABASE_PASSWORD: str = '' REDIS_PASSWORD: str = '' PUBLIC_ONLY: bool = True TEST_ENV_SUFFIX: str = '' # be -test when it's ...
366
135
# https://www.geeksforgeeks.org/counting-sort/ def sort(arr): n = len(arr) result = [-1] * n counts = [0] * (max(arr) + 1) for el in arr: counts[el] += 1 for i in range(1, len(counts)): counts[i] += counts[i-1] for i in range(n): result[counts[arr[i]] - 1] = arr[i] counts[arr[i]] -= 1 ...
437
216
import nidaqmx from . import InstrumentException from time import sleep class PCI6281: """ Interface to NI-Data Aquisition PCI-6281. """ def __init__(self, *args, **kwargs): pass def set_voltage(self, value, timeout=None): """ Set voltage on the output channel. ...
1,316
373
""" Unittest. """ import unittest from calculator.standard.operations_model import ( UniOperation, BiOperation, Square, SquareRoot, Reciprocal, Add, Subtract, Multiply, Divide, Modulo ) class OperationsModelTest(unittest.TestCase): """ Operations model test suite. """ ...
1,135
382
from lab.distribution import DistrManager def main(): sizes = [20, 60, 100] rhos = [0, 0.5, 0.9] times = 1000 manager = DistrManager(sizes, rhos, times) for size in sizes: for rho in rhos: mean, sq_mean, disp = manager.get_coeff_stats("Normal", size, rho) print( ...
684
255
import unittest import logging import os import haplotype_plot.genotyper as genotyper import haplotype_plot.reader as reader import haplotype_plot.haplotyper as haplotyper import haplotype_plot.plot as hplot logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) dir_path = os.path.dirname(os.p...
3,010
1,018
from typing import Tuple import numpy as np from docknet.data_generator.data_generator import DataGenerator class ChessboardDataGenerator(DataGenerator): """ The chessboard data generator generates two classes (0 and 1) of 2D vectors distributed as follows: 0011 0011 1100 11...
1,806
615
import cv2 import numpy as np import matplotlib.pyplot as plt __all__ = ['DetectionEngine'] class DetectionEngine(): """ Main Engine Code for detection of feature in the frames and matching of features in the frames at the current stereo state """ def __init__(self, left_frame, right_frame...
5,485
1,478
from .constants import FIELDS, PROPERTIES from .shopify_csv import ShopifyRow
78
27
from decimal import Decimal import xml.etree.ElementTree as ET from .pcexception import * class PcDimension(object): DEFAULT_SCALE = 1. BYTE_1 = 1 BYTE_2 = 2 BYTE_4 = 4 BYTE_8 = 8 BYTES = [BYTE_1, BYTE_2, BYTE_4, BYTE_8] INTERPRETATION_MAPPING = { 'unknown': {}, 'int8_t'...
8,070
2,371