text stringlengths 2 999k |
|---|
S = input()
s = list(S)
result = 0
sorted = False
while not sorted:
sorted = True
for i in range(len(S) - 1):
if s[i] > s[i + 1]:
t = s[i]
s[i] = s[i + 1]
s[i + 1] = t
result += 1
sorted = False
print(result)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import stat
import errno
import fuse
import os
import urllib
from io import BytesIO
from routefs import RouteFS
from routes import Mapper
from pymongo import MongoClient
from bson import SON, Code
from expiringdict import... |
# Copyright 2008 Google 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, ... |
import os
import re
import sys
import argparse
import djangae.sandbox as sandbox
from djangae.utils import find_project_root
# Set some Django-y defaults
DJANGO_DEFAULTS = {
"storage_path": os.path.join(find_project_root(), ".storage"),
"port": 8000,
"admin_port": 8001,
"api_port": 8002,
"automati... |
# Copyright (c) 2012-2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2013-2014 Google, Inc.
# Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Eevee (Alex Munroe) <amunroe@yelp.com>
# Copyright (c) 2015-2016 Ceridwen <ceridwenv@gmail.com>
# Copyright (c) 2015 Dmit... |
#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Sradbot (sradbot@yahoo.co.jp)
# Released under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# shebang のオプション -u: 標準出力をバッファリングしない。
# 標準出力がコンソールでない場合は、バッファリングされるが、
# 例えば systemd から起動する場合、このために実行完了まで journal に
# 書き込まれず、途中でハングアップするとロ... |
"""
DataFrame
---------
An efficient 2D container for potentially mixed-type time series or other
labeled data series.
Similar to its R counterpart, data.frame, except providing automatic data
alignment and a host of useful data manipulation methods having to do with the
labeling information
"""
from __future__ import... |
#!/usr/bin/env python
# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
"""
Description: Build a STIX Document with Tool Information
"""
# stdlib
from pprint import pprint
# python-cybox
from cybox.common import ToolInformationList, ToolInformation
# python-stix
... |
# -*- coding: utf-8 -*-
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
length = len(data)
sort_data = []
for i in range(length):
for j in range(i, length):
if data[j]['price'] > data[i]['price']:
high = data[i]
... |
import unittest
import havok
class Test(unittest.TestCase):
def test_it_decompiles_binary_files_to_a_havok_object(self):
""" @test it decompiles binary files to a Havok object
Given the file 12-16.hktmrb
When the file path is passed to the Havok class
Then the file should be decomp... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
#
# Copyright 2018 Analytics Zoo 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... |
class UnoError(Exception):
def __init__(self,valor):
self.valorError = valor
def __str__(self):
print("no se puede dividir entre 1 el numero",self.valorError)
print("Hola")
e= 5
h=1
n=2
try:
print(0/n)
if(n==2):
raise UnoError(e) #Lanzar el error creado
except ... |
MIN_TAU = 0.01
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
"""TensorFlow interface for third-party optimizers.
Code below is taken from https://github.com/tensorflow/tensorflow/blob/v1.15.2/tensorflow/contrib/opt/python/training/external_optimizer.py,
because the ``tf.contrib`` module is not included in TensorFlow 2.
Another solution is using TensorFlow Probability, see the ... |
from __future__ import print_function
from numpy import linspace, sin
from chaco.api import ArrayPlotData, Plot
from enable.api import BaseTool
from enable.component_editor import ComponentEditor
from traits.api import Enum, HasTraits, Instance
from traitsui.api import Item, View
class CustomTool(BaseTool):
def... |
from rest_framework import serializers
from common.serializers import AuditMixin, LikesMixin, TagMixin
from .models import Question, Set
class QuestionSerializer(AuditMixin, LikesMixin, TagMixin, serializers.ModelSerializer):
class Meta:
model = Question
fields = (
'id',
... |
#!/usr/bin/python3
"""
We are given two sentences A and B. (A sentence is a string of space separated
words. Each word consists only of lowercase letters.)
A word is uncommon if it appears exactly once in one of the sentences, and does
not appear in the other sentence.
Return a list of all uncommon words.
You may ... |
# -*- coding: utf-8 -*-
"""
Importing this module installs support for 16-bit images in PIL.
This works by patching objects in the PIL namespace; no files are
modified.
"""
from PIL import Image
if Image.VERSION == '1.1.7':
Image._MODE_CONV["I;16"] = ('%su2' % Image._ENDIAN, None)
Image._fromarray_typemap[((1... |
"""Uploads apk to rollout track with user fraction."""
import sys
import socket
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import subprocess
import xml.etree.ElementTree as ET
import os
from pathlib import Path
TRACK = 'beta'
USER_FRACTION = 1
APK_FILE = '... |
import tracker.views.project.record
from tracker.views.project.project import *
|
# Global Imports
import json
from collections import defaultdict
# Metaparser
from genie.metaparser import MetaParser
# =============================================
# Collection for '/mgmt/tm/sys/file/ssl-cert' resources
# =============================================
class SysFileSslcertSchema(MetaParser):
s... |
import os.path as osp
try:
import bytejection
_MODULE_INSTALLED = True
except ImportError as ex:
# Fallback to import from source directory
_MODULE_INSTALLED = False
import sys
sys.path.insert(0, osp.abspath(osp.join(osp.dirname(__file__), '..')))
from bytejection import COManipulator
from byt... |
# main code for the agent
import sys
# from utils import utils_capture
import threading
from time import time, sleep
from agents import usis
import keyboard
# from app import client
import os
import config
config = config.Config()
def train_model():
#training
agent = usis.USIS()
agent.build_model()
p... |
"""
A ``TextField`` represents a string of text, the kind that you might want to represent with
standard word vectors, or pass through an LSTM.
"""
import IPython as ipy
from typing import Dict, List, Optional, Iterator
import textwrap
from overrides import overrides
from spacy.tokens import Token as SpacyToken
impor... |
#!/usr/bin/env python
"""Utilities for documentation.
See Also
--------
RELATED : {}
Notes
-----
Docstring formats adapted from [1]_.
TODO : To-do items are flagged with 'TODO:'.
See Also : Sets of related objects, categorized by `CALLS`, `CALLED_BY`, `RELATED`.
References
----------
.. [1] https://github.com/numpy/... |
import contextlib
from tempfile import TemporaryDirectory
from typing import Any
from typing import Dict
from typing import Generator
from typing import List
from typing import Optional
from typing import TYPE_CHECKING
from typing import Union
from unittest import mock
import warnings
from lightgbm import log_evaluati... |
# Copyright (c) 2018-2022 Micro Focus or one of its affiliates.
# Copyright (c) 2018 Uber Technologies, 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/licen... |
#!/usr/bin/env python3
import serial
import re
from flask import Flask
app = Flask(__name__)
@app.route('/')
def return_heartbeat():
try:
data = readHeartbeat()
except Exception as err:
app.logger.error("Error: %s",err)
data = {'heartbeat': 'UNK', 'color': '#007fbf'}
return '''
<h... |
import os
import sys
import threading
import time
from contextlib import contextmanager
import pytest
from dagster import DagsterInstance, Field, Int, Materialization, pipeline, repository, seven, solid
from dagster.core.origin import PipelineGrpcServerOrigin, RepositoryGrpcServerOrigin
from dagster.grpc.server impor... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Pose
from std_msgs.msg import String
from math import pow,atan2,sqrt
from comp313p_reactive_planner_controller.planned_path import PlannedPath
from comp313p_reactive_planner_controller.controller_base import Controlle... |
""" Module that handles the like features """
import random
import re
from re import findall
from .time_util import sleep
from .util import format_number
from .util import add_user_to_blacklist
from .util import click_element
from .util import is_private_profile
from .util import is_page_available
from .util import up... |
# Copyright 2021 Apex.AI, 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... |
"""
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False
# https://docs.djangoproject.com/en/dev/ref/settings/#se... |
'''
NER example for CoNLL 2003
'''
import argparse
import random
import numpy as np
import torch
from edcnlp.dataloader.feature import Example
from edcnlp.dataloader.loader import examples_to_dataloader
from edcnlp.model.taskModel import TokenClassification
from edcnlp.utils.utils import display, build_pretrained_mode... |
# Generated by Django 3.0.7 on 2020-07-04 19:49
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('websites', '0028_auto_20200703_2123'),
]
operations = [
migrations.RemoveConstraint(
model_name='gr... |
#coding:utf-8
'''
服务进程(taskManager.py)(linux版)
import random,time,Queue
from multiprocessing.managers import BaseManager
#实现第一步:建立task_queue和result_queue,用来存放任务和结果
task_queue=Queue.Queue()
result_queue=Queue.Queue()
class Queuemanager(BaseManager):
pass
#实现第二步:把创建的两个队列注册在网络上,利用register方法,callable参数关联了Queue对象,
# 将... |
from __future__ import print_function
class MigrationStatusPrinter(object):
"""
Print migration status in an attractive way during a Django migration run.
In particular, you get output that looks like this
Running migrations:
Applying users.0005_set_initial_contrib_email_flag...
... |
#!/usr/bin/python3
import argparse
import os
import threading
import time
import RPi.GPIO
import paho.mqtt.client as mqtt
import birdwatch_constants as bwc
import birdwatch as bw
class BirdwatchCamera:
mqttClient = None
host = "undefined"
topic = "undefined"
tmpPath = "undefined"
lastShutdownRequestTime... |
# =========================================================================== #
# LEARNING RATE SCHEDULES #
# =========================================================================== #
# =========================================================================== #
... |
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from typing import List
def numberOfSubarrays(nums: List[int], k: int) -> int:
"""前缀和+map"""
length = len(nums)
if length <= 0: return -1
count = 0
#枚举左右边界
# for i in range(0, length):#left
# for j in range(i, length):#right
# ... |
import logging
import jwt
import pytest
from prefect.engine.signals import FAIL
from prefect.tasks.cubejs import CubeJSQueryTask
import responses
class TestCubeJSQueryTask:
def test_construction_no_values(self):
cubejs_task = CubeJSQueryTask()
assert cubejs_task.subdomain is None
assert ... |
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2:
return s
rowStr = ["" for _ in range(numRows)]
goDown = False
rowIdx = 0
for c in s:
rowStr[rowIdx] += c
if rowIdx == 0 or rowIdx == numRows - 1:
... |
from oslo_log import log as logging
from oslo_config import cfg
from fuel_agent.utils import utils
from fuel_additive.drivers.os.bootstrap import Bootstrap as Driver
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class Bootstrap(object):
def __init__(self, data):
self.config = utils.get_driver(CONF.d... |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
"""Parse (absolute and relative) URLs, tweaked to work with CircuitPython
==========================================================================================
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. M... |
"""
This Module handles all the CyberCaptain exceptions.
"""
import logging
logger = logging.getLogger("CyberCaptain")
class Error(Exception):
"""
Base class for exceptions in this module.
**Parameters**:
message : str
The message why it did not validate.
"""
def __init__(self... |
# Copyright (c) OpenMMLab. All rights reserved.
import math
import os
import shutil
import urllib
import warnings
import cv2
import mmcv
import numpy as np
import torch
from matplotlib import pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import mmocr.utils as utils
def overlay_mask_img(img, mask):
"... |
from __future__ import unicode_literals
class CitiesLightException(Exception):
""" Base exception class for this app's exceptions. """
pass
class InvalidItems(CitiesLightException):
"""
The cities_light command will skip item if a city_items_pre_import signal
reciever raises this exception.
... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... |
import sys
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk, GObject
import numpy as np
from plotter.gtk3_plotter import PlotSelector
def create_to_plot():
mat = np.random.random((100, 100))
trace = np.random.random(100)
to_plot = [
{"title": "Matrix", "type": "mat... |
# Generated by Django 2.2.18 on 2021-02-12 04:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
... |
from flask import Flask
from config.config import config_by_name
def create_app(config_name):
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
app.config.from_object(config_by_name[config_name])
from app.highlight.controllers.controllers import api as textdetect_route
from app.highlight.... |
"""评价指标"""
import torch
from torch import Tensor
def mape(hat_y, y, masked_value=torch.tensor(0.)):
"""MAPE
Args:
hat_y: 预测值
y: 真实值
masked_value: 遮掩运算过程中会异常的值,默认为0
Return:
('mape', mape): 评价指标名称,评价结果
"""
masked_val_mtx = torch.ones_like(y) * masked_value
mask ... |
from __future__ import absolute_import
import scrapy
from collections import defaultdict
from scrapy.loader.processors import Join, MapCompose, Identity
from w3lib.html import remove_tags
from .utils.processors import Text, Number, Price, Date, Url, Image
class PortiaItem(scrapy.Item):
fields = defaultdict(
... |
# external imports
import unittest
# local imports
import nautilus.models as models
from nautilus.contrib.graphene_peewee import PeeweeObjectType
from ...util import MockModel
class TestUtil(unittest.TestCase):
def setUp(self):
# the base model to test
TestModel = MockModel()
# the objec... |
# Copyright (c) 2019, NVIDIA CORPORATION.
import numbers
import pickle
import warnings
from collections.abc import Sequence
import cupy
import numpy as np
import pandas as pd
import cudf
from cudf.core.column import column
from cudf.core.index import Index, as_index
class MultiIndex(Index):
"""A multi-level or... |
from client.models import Client
import pytest
from rest_framework.reverse import reverse
from engagement.api.serializers import EngagementSerializer
from engagement.models import Engagement
class TestEngagementEndpoints:
pytestmark = [pytest.mark.system, pytest.mark.django_db]
def test_list_engagements(sel... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, VHRS and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestBWJobForm(unittest.TestCase):
pass
|
import phonenumbers
from tese import number
from phonenumbers import geocoder
ch_number=phonenumbers.parse(number,"CH")
print(geocoder.description_for_number(ch_number,"en"))
from phonenumbers import carrier
service_number=phonenumbers.parse(number,"RO")
print(carrier.name_for_number(service_number,"en"))
|
from django.db import models
# Create your models here.
# http://api.soundcloud.com/tracks/13158665.json?client_id=a43d27e75fbd64533f57428dd7be3ba5
from django.db import models
from wham.fields import WhamTextField, WhamIntegerField
from wham.models import WhamModel
class SoundcloudMeta:
base_url = 'http://api... |
################################################################################
# Justin Schoenfeld & Jorge Rojas
# ExifMapper
# Maps GPS data from JPG files using the Google Maps Static API and exiftool.exe
################################################################################
import string,sys,os
import s... |
#
# Copyright (C) 2021 Vaticle
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed ... |
from cradmin_legacy.acemarkdown.widgets import AceMarkdownWidget
class Default(AceMarkdownWidget):
template_name = 'devilry_cradmin/devilry_acemarkdown.django.html'
extra_css_classes = ''
def get_context(self, *args, **kwargs):
context = super(Default, self).get_context(*args, **kwargs)
c... |
import graphene
import pytest
from remote_works.graphql.menu.mutations import NavigationType
from remote_works.menu.models import MenuItem
from tests.api.utils import get_graphql_content
from .utils import assert_no_permission
def test_menu_query(user_api_client, menu):
query = """
query menu($id: ID, $menu... |
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(name='get_first_char')
def get_first_char(value):
"""
Returns the first char of the given string
:param value:
:return:
"""
return value[:1]
@re... |
#!/usr/bin/env python
#encoding=utf-8
import httplib
import time
import string
import sys
import random
import urllib
headers = {}
payloads = 'abcdefghijklmnopqrstuvwxyz0123456789@_.'
print '[%s] Start to retrive MySQL User:' % time.strftime('%H:%M:%S', time.localtime())
user = ''
for i in range(1, 25):
for payl... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 3
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_0
from isi... |
# -*- coding: utf-8 -*-
# Copyright 2019 Google 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 ... |
import logisticreg
import csv
import numpy as np
n_test = 100
X = []
y = []
# Data: https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/
with open("wdbc.data") as fp:
for row in csv.reader(fp):
if row[1] == "B":
y.append(0)
else:
y.append(1)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9b1 on 2015-11-21 12:44
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('items', '0007_auto_20151115_1733'),
]
operations = [
migrations.RemoveField(
... |
import os
import sys
import argparse
import numpy as np
from collections import Counter,defaultdict
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
#Color_scheme=["#0277BD",]
Color_scheme=['#42A5F5','#66BB6A','#FFEB3B','#EF5350','#FF00FF']
#Color_scheme=["#F0A3FF", "#0075DC", "#993F00","#4C005... |
from services.proto import article_pb2
from services.proto import general_pb2
from utils.articles import md_to_html
class PreviewServicer:
def __init__(self, md_stub, logger):
self._md_stub = md_stub
self._logger = logger
def PreviewArticle(self, req, context):
self._logger.info('Rec... |
import pytest
from noscrapy.selectors import HtmlSelector
GET_DATA = {
'single':
(HtmlSelector('a', css='p', many=False), '<p>a<b>b</b>c</p><p>d<b>e</b>f</div>',
[{'a': 'a<b>b</b>c'}]),
'many':
(HtmlSelector('a', css='p'), '<p>a<b>b</b>c</p><p>d<b>e</b>f</div>',
[{'a': 'a<b>b... |
# Copyright The IETF Trust 2019, All Rights Reserved
# Copyright 2018 Cisco and its affiliates
#
# 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... |
from ftp_data import *
import os
from client_database import *
from node import *
import time
print('getting code...')
a = 0
while True:
time.sleep(2)
a=a+1
try:
sql = "SELECT code_name FROM node_code where node_id = '"+node_id +"'"
mycursor.execute(sql)
myresult... |
#!/usr/bin/env python
"""
The Resource Expert Droid Fetcher.
RedFetcher fetches a single URI and analyses that response for common
problems and other interesting characteristics. It only makes one request,
based upon the provided headers.
See droid.py for the main RED engine and webui.py for the Web front-end.
"""
... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase
from spark_auto_mapper_fhir.base_types.fh... |
#!/usr/bin/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
# "Licens... |
import math
class WebMercator(object):
@staticmethod
def lon_to_x(lon: float) -> float:
# return lon * 6378137.0 * math.pi / 180.0
return lon * 111319.490793274
@staticmethod
def lat_to_y(lat: float) -> float:
sin = math.sin(lat * math.pi / 180.0)
return 3189068.5 * ma... |
def _encode_int(value: int) -> bytes:
return value.to_bytes(length=4, byteorder="little")
def _decode_int(data: bytes) -> int:
return int.from_bytes(data, byteorder="little", signed=True)
class Message:
def __init__(self, *, packet_id: int, message_type: int, body: str) -> None:
self.message_typ... |
# -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') 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 "Lice... |
"""
BSD 3-Clause License
Copyright (c) 2018, NVIDIA Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of c... |
from .models import *
from .data import *
from .ner.data import entities_from_gmb, entities_from_conll2003, entities_from_txt, entities_from_df, entities_from_array
from .ner.models import sequence_tagger, print_sequence_taggers
from .eda import get_topic_model
from .textutils import extract_filenames, load_text_files,... |
# Copyright 2019 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... |
# Copyright (c) 2014 The Bitcoin Core developers
# Copyright (c) 2014-2015 The Dash developers
# Copyright (c) 2015-2017 The PIVX developers
# Copyright (c) 2017 The GITS developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.ph... |
# if you change credits, you get anal cancer and get murdered by russians in 3 days.
"""
Support chatbox for pmpermit.
Used by incoming messages with trigger as /start
Will not work for already approved people.
Credits: written by xditya {@xditya}
"""
import asyncio
import io
import telethon.sync
from telethon.tl.func... |
from model import GiverReceiverLink
from .AbstractDAO import AbstractDAO
class GiverReceiverLinkDAO(AbstractDAO):
def __init__(self, file_path, participant_dao):
super().__init__(file_path)
self.participant_dao = participant_dao
def get(self, giver):
raw_links = super().read... |
import sys
from multiprocessing import Pool, Queue, Value, Lock
import pyarrow as pa
import time
import random
from util import *
HOST = "localhost"
PORT = 9000
MAX_TASK = cpu_count()
FILE_NUM = 10000
FILE_SIZE = 10
queue = Queue()
finish = Value('i', 0)
lock = Lock()
letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM... |
# encoding:utf-8
class UserAgentMiddleware(object):
def process_request(self,request,spider):
agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"
request.headers['User-Agent'] = agent
|
import RPi.GPIO as GPIO
import curses
import time
TRIG = 24
ECHO = 26
def move(char):
if char == curses.KEY_UP:
screen.addstr(0,0, 'up ')
GPIO.output(7, False) # makes sure that nothing else
GPIO.output(11, False) # is running when this runs
GPIO.output(13, Fal... |
from django.apps import AppConfig
class PrTemplateMetricConfig(AppConfig):
name = 'pr_template_metric'
|
from .topology import TopologyMember
from .netdev import NetDev
from .xfrm import Xfrm
class Tunnel(TopologyMember):
REF = 'tunnel'
TUNNEL_MODE = None
NOARP = True
DEV_SCHEMA = {
'type': 'object',
'additionalProperties': False,
'properties': {
'mode': {'type': 'stri... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Akram Mutaher and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestViolence(unittest.TestCase):
pass
|
import datetime
import textwrap
import sxml
import pytest
from freezegun import freeze_time
UTC = datetime.timezone.utc
UTC4 = datetime.timezone(datetime.timedelta(hours=4))
UTC_4 = datetime.timezone(datetime.timedelta(hours=-4))
def test_strftime():
parse = sxml.HtmlPipeline.from_string(textwrap.dedent(r'''
... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA 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... |
from django.utils.translation import gettext_lazy as _
from rest_framework import HTTP_HEADER_ENCODING, authentication
from .exceptions import AuthenticationFailed, InvalidToken, TokenError
from .models import TokenUser
from .settings import api_settings
from .state import User
AUTH_HEADER_TYPES = api_settings.AUTH_H... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home_view, name='home')
] |
from .utils.label_map import convert_label_map_to_categories, load_labelmap, create_category_index
from .utils.visualize import *
import os
from django.conf import settings
import numpy as np
import sys
import tarfile
import tensorflow.compat.v1 as tf
import zipfile
from pathlib import Path
from collections import defa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.