content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
# -*- coding: utf-8 -*-
import argparse
import pandas as pd
from zvt import init_log, zvt_env
from zvt.api.quote import get_stock_factor_schema
from zvt.contract import IntervalLevel
from zvt.contract.api import df_to_db
from zvt.contract.recorder import FixedCycleDataRecorder
from zvt.recorders.joinquant.common import... | python |
import sys, re
def alphaprint(code):
r = "^(abcdefghijklmnopqrstuvwxyz)*(a(b(c(d(e(f(g(h(i(j(k(l(m(n(o(p(q(r(s(t(u(v(w(x(y(z?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?$"
if re.match(r, code, re.I):
last=""
for i in range(len(code)):
if code[i].isupper():
print(end=chr(i % 256))
... | python |
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from .common import *
class User(AbstractUser):
#Boolean fields to select the type of account.
is_job_hunter = models.BooleanField(default=False)
is_company = models.Bo... | python |
#!/bin/python
"""
Title: The DISEMVOWLER
Author: Maxwell Haley
Description: Takes in a line of text from stdin, strips it of all vowles,
then prints the mangled text and it's vowel remains. Done for
/r/DailyProgrammer challenge #149.
You can invoke this script in two ways. First, call the script with no arguments
and ... | python |
import unittest
from pulsar.apps.test.wsgi import HttpTestClient
from pulsar.utils.httpurl import HttpParser, CHttpParser
class TestPyParser(unittest.TestCase):
__benchmark__ = True
__number__ = 1000
@classmethod
async def setUpClass(cls):
http = HttpTestClient()
response = await htt... | python |
from . import ash
from . import grm
from . import rdi
from . import srf
from . import sxn
from . import tnl
from . import ubx
# jaykaron
from . import adb
from . import tnt
| python |
from quiche.egraph import EGraph
from quiche.analysis import MinimumCostExtractor
from .prop_test_parser import PropParser, PropTree, PropTreeCost
from .test_egraph import verify_egraph_shape # , print_egraph
def make_rules():
rules = [
# x -> y ===> ~x | y
PropTree.make_rule("(-> ?x ?y)", "(| ... | python |
import math
import time
import random
# Print the Main Menu
def menu():
print("---- Public Key Cryptography, RSA ----\n")
print("1) Extended Euclidean Algorithm.")
print("2) Fast Modular Exponentiation.")
print("3) Miller-Rabin Test (True=Composite).")
print("4) Prime Number Generator.")
print... | python |
from source_hunter import hunter
from source_hunter.hunter import hunt
__all__ = [
'hunter', 'hunt'
]
| python |
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from collections import namedtuple
from difflib import get_close_matches
from warnings import warn
from pytest import mark
from tests.utils import PY34, PY35, PY33, PY26, PY27, PYPY, PY2, PY3
try:
from collections import OrderedDict
exc... | python |
##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import _
from odoo.http import request, route
from odoo.addons.... | python |
#! /usr/bin/env python
# Author: Nuha Nishat
# Date: 1/30/20
import rospy
import sys, os
import math
import geometry_msgs.msg
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import JointState
import tf, math
import tf.transformations
import pdb
import moveit_commander
import moveit_msgs.msg
import geom... | python |
"""Activation Functions Module.
"""
import numpy as np
class Activation:
"""Base class for the activation function.
Warning: This class should not be used directly.
Use derived classes instead.
"""
def f(self, x):
"""Compute the activation function on x.
Warning: Overrides th... | python |
#
# This file is part of Orchid and related technologies.
#
# Copyright (c) 2017-2020 Reveal Energy Services. All Rights Reserved.
#
# LEGAL NOTICE:
# Orchid contains trade secrets and otherwise confidential information
# owned by Reveal Energy Services. Access to and use of this information is
# strictly limited and... | python |
from django import forms
class AgendaForm(forms.Form):
date=forms.DateField()
lc=forms.CharField(max_length=50)
| python |
info = input()
animal_food = {}
areas = {}
while True:
if info == 'Last Info':
break
tokens = info.split(':')
command = tokens[0]
name = tokens[1]
number = int(tokens[2])
area = tokens[3]
if command == 'Add':
if name in animal_food:
animal_food[name] += number
... | python |
from typing import Any, Callable, Dict, Type
from marshmallow import Schema, fields, post_load
from typing_extensions import Protocol
from .dataclasses import Picture, Product, ProductPage, Size, StockItem
class Dataclass(Protocol):
def __init__(self, **kwargs):
...
def get_dataclass_maker(cls: Type[D... | python |
from typing import List
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
flag = False
for i in range(0, len(nums)-1):
if nums[i] > nums[i+1]:
if flag:
return False
if i == 0:
nums[i] = nums[i+1]... | python |
from tpdataset import RawDataSet, DataDownloader
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from pyctlib import vector, path, fuzzy_obj
import math
import torch
from ..download_googledrive import download_file_from_google_drive
from functools import par... | python |
"""Model for blog."""
from django.db import models
from django.utils import timezone
from django.conf import settings
class Post(models.Model):
"""Post model for blog."""
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
title = models.CharField(max_len... | python |
"""Números
Faça um programa que produza o resultado abaixo (sendo N fornecido pelo
utilizador). O exercício deve ser resolvido utilizando recursão.
1
1 2
1 2 3
...
1 2 3 ... N
"""
def show(n: int) -> None:
if n > 0:
show(n - 1)
i = 1
while i < n + 1:
print(f'{i:>3} ', end='')
i +=... | python |
from django.contrib import admin
from website.models import (Category, SubCategory, WebsiteRecommendation,
WebsiteComment, BookRecommendation, BookComment,
VideoRecommendation, VideoComment)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug... | python |
"""
Created on 9 Dec 2020
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
The A4CalibratedDatum is designed to provide a model training data set that encapsulates the calibration of the
electrochemical sensor - the fields we_v_cal, ae_v_zero_cal and cal_x_v have no meaning beyond this.
cal_x_v is only rele... | python |
from application.domain.application import Application
from application.domain.iBaseWatcher import IBaseWatcher
from application.domain.iCerebrum import ICerebrum
from application.infrastructure.championshipBaseWatcher import ChampionshipBaseWatcher
from application.infrastructure.remoteBaseWatcher import RemoteBaseWat... | python |
'''
Author : MiKueen
Level : Medium
Company : Google
Problem Statement : Count Unival Subtrees
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival s... | python |
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import {{cookiecutter.project_name}}.parameters as P
class Animation:
'''
A matplotlib window containing an animation for the system. There are
no parameters for initialization, as the Animation object can directly
... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 13:15:23 2018
@author: sshekhar
"""
from nseurls import *
import six
from nsecommons import *
from nseconstants import *
from datetime import date, timedelta
from bs4 import BeautifulSoup
import pandas as pd
import six
import inspect
dd_mmm_yyyy = StrDate.default_fo... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google Inc. 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 ... | 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
# "License"); you may not... | python |
# -*- coding: utf-8 -*-
import numpy as np
top = 4000000
fibo1 = 2
fibo2= 1
cumSum = 2
while fibo1 < top:
temp = fibo1
fibo1 = fibo1+fibo2
fibo2 = temp
if fibo1%2==0 and fibo1<top:
print fibo1
cumSum=cumSum+fibo1
print cumSum
| python |
from django.http import request
from django.shortcuts import render
from . import regresion
import json
def fit(f_type, xvalues, yvalues):
if f_type == 'cuadratic':
print(f_type)
return
# Create your views here.
def RegresionCuadratica(request):
if request.method == 'POST':
xvalues = reque... | python |
import gym
from baselines import ampi
from baselines import bench
from baselines.ampi import mlp_policy
from baselines import logger
def callback(lcl, _glb):
# stop training if reward exceeds 199
is_solved = lcl['t'] > 100 and sum(lcl['episode_rewards'][-101:-1]) / 100 >= 199
return is_solved
LOG_DIR="/h... | python |
"""Test suite for pytorch_ranking."""
| python |
#!/usr/bin/env python
'''
File name: do_color_propagation.py
Author: Varun Jampani
'''
# ---------------------------------------------------------------------------
# Video Propagation Networks
#----------------------------------------------------------------------------
# Copyright 2017 Max Planck Society
# ... | python |
import argparse
import PIL.Image as pil_image
import numpy as np
from utils import AverageMeter, calc_psnr, calc_ssim, convert_rgb_to_y, denormalize,calc_psnr_for_eachimg,calc_ssim_for_eachimg
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--lr_image_file', type... | python |
import warnings
from typing import Any, Callable, Dict, List, Optional, Union
from cognite.client import utils
from cognite.client._api.assets import AssetsAPI
from cognite.client._api.data_sets import DataSetsAPI
from cognite.client._api.datapoints import DatapointsAPI
from cognite.client._api.entity_matching import ... | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import time
# 专注于 IO多路复用 可以实现一个可并发的服务器
import select
# 用于类的序列化和反序列化
import json
from master import *
import server_pool
from master2 import *
import socket
class EventLoop(object):
def __init__(self):
self._stopping = False
# 创建一个sock... | python |
"""Timers Tests"""
from datetime import datetime, timedelta
from itertools import starmap
from operator import sub
from time import time
import pytest
from circuits import Component, Event, Timer, sleep
from circuits.six.moves import map, zip
@pytest.fixture
def app(request, manager, watcher):
app = App().reg... | python |
from django.apps import AppConfig
class Lab1Config(AppConfig):
name = 'lab1'
| python |
#######################################################################
# Name: test_semantic_action_results
# Purpose: Tests semantic action results passed to first_pass call
# Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2014 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
... | python |
from pathlib import Path
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from zelt.kubernetes import deployer
from zelt.kubernetes.manifest import Manifest
from zelt.kubernetes.manifest_set import ManifestSet
from zelt.kubernetes.storage.configmap import ConfigmapStorage
@pytest.fi... | python |
from DB_Tables.Comments_Table import Comment_Table
from DB_Tables.InlineComment_Table import InlineComment_Table
from DB_Tables.PatchDetail_Table import PatchDetail_Table
from DB_Tables.Patch_Table import Patch_Table
from DB_Tables.People_Table import People_Table
from DB_Tables.RequestDetail_Table import RequestD... | python |
# flake8: noqa F401
from wagtailregulations.models.django import (
EffectiveVersion,
Part,
Section,
Subpart,
sortable_label,
)
from wagtailregulations.models.pages import RegulationPage, RegulationPageMixin
| python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.chat,
name='chatRoom'
),
url(r'^new/$', views.new_room, name='new_room'),
url(r'^(?P<label>[\w-]{,5... | python |
__author__ = """Romain Picard"""
__email__ = 'romain.picard@oakbits.com'
__version__ = '0.1.0'
from .types import NamedObservable, Update, Updated
from . import pullable
| python |
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from swagger_client.api.aliens_api_api import AliensApiApi
from swagger_client.api.games_api_api import GamesApiApi
from swagger_client.api.logs_api_api import LogsApiApi
from swagger_client.api.scoreboard_api_api import ScoreboardAp... | python |
import uuid
from django.conf import settings
from django.test import TestCase
from mock import patch
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from corehq.apps.userreports.models import DataSourceConfiguration, ReportConfiguration
from corehq.apps.userreports.pillow import Configu... | python |
"""
Model class for Message.
Refer: https://developers.facebook.com/docs/graph-api/reference/message
"""
from dataclasses import dataclass
from typing import List, Optional
from dataclasses_json import config
from pyfacebook.models.base import BaseModel, field
@dataclass
class Tag(BaseModel):
"""
... | python |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 Peter Williams and collaborators.
# Licensed under the MIT License.
"""Various properties of plasma oscillations.
Most equation references are to Stix (1992), "Waves in Plasmas".
"""
from __future__ import absolute_import, division, print_function
__all__ = '''... | python |
from smtplib import SMTPException
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MinLengthValidator
from django.core.mail.message import EmailMultiAlternatives
from django.conf import settings
from django.template.loader import render_to_string
... | python |
import logging
import sys
import pyModeS as pms
from pyModeS.extra.rtlreader import RtlReader
class RtlSdrSource(RtlReader):
def __init__(self):
super(RtlSdrSource, self).__init__()
def handle_messages(self, messages):
if self.stop_flag.value is True:
self.sdr.close()
... | python |
import numpy
verbose = False
def ride_of_fortune(artifact, explorers):
artifact_object = Artifact(artifact)
if verbose:
print(artifact_object.artifact)
results = []
for explorer_start_row in explorers:
if verbose:
print("====")
explorer_object = Explorer(y=explorer... | python |
# Copyright 2018 eShares, Inc. dba Carta, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | python |
# SPDX-FileCopyrightText: 2021 Genome Research Ltd.
#
# SPDX-License-Identifier: MIT
from main.service import AssemblyService
from main.swagger import AssemblySwagger
from .base import BaseResource, setup_resource
api_assembly = AssemblySwagger.api
@setup_resource
class AssemblyResource(BaseResource):
class M... | python |
import unittest
import numpy
import tempfile
from pyscf import lib, gto
class KnowValues(unittest.TestCase):
def test_save_load_mol(self):
mol = gto.M(atom=[['H', (0,0,i)] for i in range(8)],
basis='sto3g')
fchk = tempfile.NamedTemporaryFile()
lib.chkfile.save_mol(mol, f... | python |
import sqlite3
from message import Message
from friend import Friend
'''
Created on Nov 14, 2013
@author: andyisaballa
'''
STICKERS_ENABLED = 0
STICKERS_DISABLED = 1
STICKERS_ONLY = 2
def getMessagesByFriend(db, name, stickers=STICKERS_DISABLED):
conn = sqlite3.connect(db)
cursor = conn.cursor()
if is... | python |
# The MIT License (MIT)
#
# Copyright (c) 2016 Russell Barlow III
#
# 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, co... | python |
from abc import ABC, abstractmethod
from boltons.cacheutils import cachedproperty
class BaseEnv(ABC):
"""
Abstract base class used for implementing new environments.
"""
def __init__(self):
self.env = self._create_env()
def __str__(self):
return "<{}>".format(type(self).__name__)... | python |
# -------------------------------------------------------------------------------
# (c) 2020 Siemens AG
# All Rights Reserved.
# Author: thomas.graf@siemens.com
#
# Licensed under the MIT license.
# SPDX-License-Identifier: MIT
# -------------------------------------------------------------------------------
import s... | python |
# Generated by Django 2.2.5 on 2019-12-02 00:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0012_auto_20191202_0038'),
]
operations = [
migrations.RenameField(
model_name='boleto',
old_name='user_id',
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 8 16:58:10 2020
@author: nephilim
"""
import keras
import numpy as np
import my_Im2col
from matplotlib import pyplot,cm
import skimage.transform
import T_PowerGain
import DataNormalized
import Reshape2Encoder
def GetPatch(Image,patch_size,sliding... | python |
# Copyright 2018 Telefonica
#
# 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 ... | python |
r"""
Utils are utils.
"""
from sys import version_info as v
import subprocess
from datetime import datetime
def run_cmd(cmd: str) -> str:
r"""Executes and returns custom command output.
"""
return subprocess.getoutput(cmd)
def get_gpu_usage() -> str:
r"""Returns current gpu usage.
"""
cmd_u... | python |
import sys
import glob
import serial
import datetime
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
... | python |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
import popart
import numpy as np
import torch
import onnx
from onnx import numpy_helper
import math
import pytest
# `import test_util` requires adding to sys.path
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.... | python |
# Generated by Django 3.1.5 on 2021-01-14 08:31
import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.db import migrations, models
def parse_description_json_to_string(description):
string = ""
blocks = description.get("blocks")
if not blocks or not isinstance(blocks, l... | python |
from .concat_dataset import ConcatDataset
from .dataset_wrapper import DatasetWrapper
from .image_collection_dataset import ImageCollectionDataset
from .segmentation_dataset import SegmentationDataset
from .sampler import MinForegroundSampler
| python |
# Generated by Django 2.0.4 on 2019-07-17 11:36
from django.core.management import call_command
from django.db import migrations
from events.helpers.permissions import (
create_organizer_group_migrations_wrapped,
remove_organizer_group
)
def update_permissions(schema, group):
call_command('update_permiss... | python |
# PLASMA is a software package provided by:
# University of Tennessee, US,
# University of Manchester, UK.
from __future__ import print_function
# standard python modules
import os
import sys
import re
import shlex
import subprocess
from subprocess import PIPE
# local modules
from environment import Environment
... | python |
from .code import Code
from .docstring import DocString
from .value import NamedValue, UnnamedValue
from .function import Function
from .proptypes import PropTypes
from .klass import Class
from .module import Module
| python |
#!/usr/bin/env python
from setuptools import setup, find_packages
"""
Documentation can be found at https://docs.python.org/2/distutils/index.html,
but usually you only need to do the following steps to publish a new package
version to PyPI::
# Update the version tag in this file (setup.py)
python setup.py sd... | python |
# Program to automatically send email when something goes down
# by calling the function email()
# like this --> email(["example@somewhere.com","somewhereelse@other.com"])
import smtplib # Necessary modules
from email.mime.text import MIMEText
xhoni = "xhp1@pitt.edu"
def sendMail(recievers,content,subject="Alert"):
... | python |
src = Split('''
src/mbedtls_net.c
src/mbedtls_alt.c
src/mbedtls_auth.c
''')
aos_global_config.set("DEBUG", "yes")
component = aos_component('itls', src)
component.add_global_includes('include')
component.add_macros('CONFIG_PLAT_AOS')
component.add_macros('CONFIG_KEY_OTP_ENABLED')
if aos_global_config.g... | python |
import boto3
from os import walk
from datetime import datetime
client = boto3.client('s3')
# Create s3 bucket
now = datetime.now()
date_time = now.strftime("%m-%d-medium-datasets")
response = client.create_bucket(
Bucket=date_time
)
print(response)
#
s3 = boto3.resource('s3')
# Upload files to bucket
mypath =... | python |
from clinical_records import settings
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Layout, Submit
from django import forms
from django.forms import DateField
from django.forms import ModelForm
from patients.models import CIE10
from patients.models import ClinicalHistory
from pa... | python |
import os
import unittest
from io import StringIO
from datetime import timedelta
from urllib.parse import quote
from django.conf import settings
from django.contrib import auth
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from oauth2_provider.mode... | python |
import pytest
from pyroll.core import Transport
class Specs:
@Transport.hookspec
def hook1(self, transport):
""""""
Transport.plugin_manager.add_hookspecs(Specs())
def test_hook_not_present():
transport = Transport(time=1)
with pytest.raises(AttributeError):
print(transport.does_... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from delivery import deli, tasks
urlpatterns = [
url(r'^$', deli.delivery_list, name='delivery'),
url(r'^add/$', deli.delivery_add, name='delivery_add'),
url(r'^ist/$', deli.delivery_list, name='delivery_list'),
url... | python |
from distutils.core import setup
import os
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.md')) as f:
CHANGES = f.read()
setup(name='django-cli',
packages=['django-cli'],
version='0.0.1',
... | python |
# -*- coding: utf-8 -*-
from irc3.testing import BotTestCase, MagicMock
from irc3.plugins.autojoins import AutoJoins
class TestAutojoin(BotTestCase):
def test_autojoin_without_diese(self):
bot = self.callFTU(autojoins=['foo'])
bot.notify('connection_made')
bot.dispatch(':hobana.freenode.... | python |
"""
My fun little python script to autoclick in cookie clicker
#Only functions on Windows right now
"""
from ctypes import windll, Structure, c_long, byref, wintypes
import keyboard
import time
import sys
from msvcrt import kbhit, getch
click = False
pressed = False
running = True
setx = 0
sety = 0
offstr = "OFF"
o... | python |
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def run_in_executor(method):
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, method)
return result | python |
from time import sleep
from loguru import logger
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import Selec... | python |
# _*_ coding: utf-8 _*_
import json
import uuid
from datetime import datetime
from multiprocessing import Process
import redis
__author__ = 'Arun KR (@kra3)'
class SimpleJobQueue(object):
SCHEDULED, IN_PROGRESS, DONE, FAILED = (
'SCHEDULED', 'IN_PROGRESS', 'DONE', 'FAILED')
TIMESTAMP, PAYLOAD, STATU... | python |
l=[]
for i in range(int(input())):
l.append(input().split())
ans=[]
for i in l:
if i[1]=='rat':
ans.append(i[0])
for i in l:
if i[1]=='woman' or i[1]=='child':
ans.append(i[0])
for i in l:
if i[1]=='man':
ans.append(i[0])
for i in l:
if i[1]=='captain':
ans.append(i[0... | python |
#! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Tue Feb 2 21:18:10 CET 2010
import cStringIO
import syncless.coio
import socket
import unittest
# TODO(pts): Test reverse lookup without canonical name.
# TODO(pts): Test for IPv6 addresses:
# print syncless.coio.dns_resolve_ipv6('www.ipv6.org')
#: <dnsresult ... | python |
from pygraphblas import Matrix, BOOL, lib
def rpq(g, r):
kron = g.get_intersection(r)
closure_matrix = Matrix.sparse(BOOL, kron.size, kron.size)
for label in kron.matrices:
if kron.matrices[label].nrows < kron.size:
kron.matrices[label].resize(kron.size, kron.size)
closure_mat... | python |
'''
This file implements the Schlaufen Detection algorithm in the paper:
Testing Strategic Interaction in Networks
'''
from ugd.schlaufen_construction.di_schlaufen_construction_util import mark_edge, mark_node, cycle_found, random_draw
from ugd.help_function.util import rand_element_of_set, del_nodes_mark
def add... | python |
import pytest
from asynctest import (
mock as async_mock,
TestCase as AsyncTestCase,
)
from aries_cloudagent.messaging.request_context import RequestContext
from aries_cloudagent.messaging.responder import MockResponder
from aries_cloudagent.transport.inbound.receipt import MessageReceipt
from aries_cloudagent... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 07:06:38 2020
@author: daskalot
"""
#from doc_embedders import TfIdfTransformer as tfidf
from sklearn.feature_extraction.text import CountVectorizer
import string
from sklearn import preprocessing
import graphvite as gv
import numpy as np
from... | python |
from streamlit.components.v1 import html
try:
from keywords import SHARE_KEYWORD
from keywords import check_keyword
except:
from .keywords import SHARE_KEYWORD
from .keywords import check_keyword
def share_parser(lines):
"""Parses a list of lines into a dictionary with the parsed values.
:p... | python |
"""
This file demonstrates writing tests using the pytest module. These will pass
when you run "./bin/pytest app/tests.py".
Replace this with more appropriate tests for your application.
"""
# -*- coding: utf-8 -*-
import pytest
class TestSuite(object):
def test_run(self):
pytest.skip('todo')
| python |
import textwrap
import uuid
from moviepy.editor import *
TITLE_FONT_SIZE = 30
FONT_SIZE = 30
TITLE_FONT_COLOR = 'white'
BGM_PATH = 'assets/bgm.mp3'
STATIC_PATH = 'assets/static.mp4'
SIZE = (1280, 720)
BG_COLOR = (16,16,16)
VIDEO_PATH = ""
FONT = 'Amiri-regular'
def generate_title(text, audio_path):
color_clip = C... | python |
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'password']
def create(self, validated_data):
user = User(username=validated_data.get('usern... | python |
from anet.utils.format import MultiObssPreprocessor
from anet.utils.log import configure_logging
from anet.utils.optimizer import load_optimizer, save_optimizer
| python |
import sys
import pandas as pd
import numpy as np
import re
import pickle
import nltk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem imp... | python |
class ListSecure(list):
def get(self, index, default=None):
try:
return self.__getitem__(index)
except IndexError:
return default
| python |
"""common functions for client and server"""
def send_msg(socket, msg):
"""send message to a socket"""
socket.send(bytes(str(msg), 'utf8'))
def recv_msg(socket):
"""receive a message from a socket"""
return socket.recv(4096).decode('utf8')
| python |
# -*- coding: utf-8 -*-
import pickle
import os
import string
import numpy as np
import tempfile
import pandas as pd
import sys
import hashlib
import errno
import time
import shutil
from sklearn.datasets.base import Bunch
TRANS = str.maketrans('', '', string.punctuation.replace('-', ''))
TEMP = tempfile.gettempdir()
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.