text stringlengths 2 999k |
|---|
class Foo:
def qux2(self):
z = 12
x = z * 3
self.baz = x
for q in range(10):
x += q
lst = ["foo", "bar", "baz"]
lst = lst[1:2]
assert len(lst) == 2, 201
def qux(self):
self.baz = self.bar
self.blah = "hello"
self._priv = 1
self._prot = self.baz
def _prot2(self):
... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.facebook.com/")
bsObj = BeautifulSoup(html.read(), "html.parser")
dom = open('facebook.html', "w")
dom.write(bsObj.prettify())
#print(bsObj.h1)
print(bsObj.prettify())
|
from application import handlers, Application
import os
app = Application(handlers, os.environ, debug=True)
db = app.db
celery = app.celery()
import tasks
login_session = app.login_session
client_id = app.google_client_id |
def put_char(position, max_positions, large_ok, spec_ok, num_ok):
global temp_txt
global text_file
global combs
my_chars = list(chars_small)
my_large_ok = large_ok
my_specs_ok = spec_ok
my_nums_ok = num_ok
if my_large_ok: my_chars.extend(chars_large)
if my_specs_ok: my_chars.extend(... |
# 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 ... |
#!/usr/bin/env python
import argparse
import pandas as pd
import numpy as np
from math import floor
import tqdm
def main():
parser = argparse.ArgumentParser(description='Pairwise distances between MLST alleles')
parser.add_argument('infile', type=str, help="Tab separated file containing alleles")
parser.... |
#!/usr/bin/env python
from ecies.utils import generate_eth_key
import ecies
privKey = generate_eth_key()
privKeyHex = privKey.to_hex()
pubKeyHex = privKey.public_key.to_hex()
def encrypt(plaintext=None):
return ecies.encrypt(pubKeyHex, plaintext)
def decrypt(ciphertext=None):
return ecies.decrypt(privKeyH... |
import functools
import numpy as np
from garage.experiment import deterministic
from garage.sampler import DefaultWorker
from iod.utils import get_np_concat_obs
class OptionWorker(DefaultWorker):
def __init__(
self,
*, # Require passing by keyword, since everything's an int.
... |
# -*- coding: utf8 -*-
import json
import random
import socket
from collections import OrderedDict
from time import sleep
import requests
from fake_useragent import UserAgent
import TickerConfig
from agency.agency_tools import proxy
from config import logger
def _set_header_default():
header_dict = OrderedDict()
... |
# MIT License
#
# Copyright (c) 2017 Matt Boyer
#
# 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, p... |
#!/bin/python3
"""Main CI job script."""
import os
import subprocess
import time
from datetime import datetime
from github import Github
from kubeinit_ci_utils import remove_label, upload_logs
#
# We only execute the e2e jobs for those PR having
# `whitelist_domain` as part of the committer's email
#
def main():... |
from __future__ import absolute_import
import difflib
from functools import wraps, partial
import re
from flask import request, url_for, current_app
from flask import abort as original_flask_abort
from flask.views import MethodView
from flask.signals import got_request_exception
from werkzeug.exceptions import HTTPExce... |
from django.test import TestCase
from .models import Project
from django.contrib.auth.models import User
# Create your tests here.
class TestProject(TestCase):
def setUp(self):
self.user=User(username='jefferson')
self.user.save()
self.project=Project(user=self.user, title='test', descripti... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_sslify import SSLify
import config
db = SQLAlchemy()
login_manager = LoginManager()
def create_app() -> Flask:
"""Create an application factory with SQLAlchemy, Login, and
SSLify
... |
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, REGISTRY
from apiclient.discovery import build
from apiclient.errors import HttpError
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
import time, httplib2, os, bios, h... |
# Copyright (c) 2018, Toby Slight. All rights reserved.
# ISC License (ISCL) - see LICENSE file for details.
import argparse
import os
from pdu import du
def chkpath(path):
"""
Checks if a path exists.
"""
if os.path.exists(path):
return path
else:
msg = "{0} does not exist.".form... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import time
import pytest
from sasctl.core import request_link
from sasctl.services import sentiment_analysis as sa
pytestmark = pytest.mark.usefixtures('sess... |
#-*- coding:utf-8 -*-
# Author:longjiang
from scrapy.spiders import CrawlSpider,Rule
import re
import requests
from scrapy_redis.spiders import RedisSpider
from scrapy.selector import Selector
from scrapy.http import Request
import logging
import time
from bs4 import BeautifulSoup
import json
import sys
reload(sys)
... |
from panther import lookup_aws_account_name
from panther_base_helpers import deep_get
def rule(event):
return (event['eventName'] == 'ConsoleLogin' and
deep_get(event, 'userIdentity', 'type') == 'Root' and
deep_get(event, 'responseElements', 'ConsoleLogin') == 'Success')
def title(event)... |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print("You have %d cheeses!" % cheese_count)
print("You have %d boxes of crackers" % boxes_of_crackers)
print("Man that's enough for a party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_an... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# We disable pylint because we need python3 compatibility.
from six.moves import xrange # pylint: disable=redefined-builtin
from six.moves import zip # pylint: disable=redefined-builtin
from tensorflow.pytho... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
__version__ = '2.1.0-alpha.8'
"""HanLP version"""
|
# GenomicRangeQuery - Find the minimal nucleotide from a range of sequence DNA.
# A DNA sequence can be represented as a string consisting of the letters A, C, G and T,
# which correspond to the types of successive nucleotides in the sequence.
# Each nucleotide has an impact factor, which is an integer.
# Nucleoti... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTilt(self, root: TreeNode) -> int:
result = 0
def getSum(node):
... |
# Copyright 2017, OpenCensus 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 w... |
from datetime import datetime, timedelta, tzinfo
from http import cookies as http_cookies
import re
import pytest
import falcon
import falcon.testing as testing
from falcon.util import http_date_to_dt, TimezoneGMT
from _util import create_app # NOQA
UNICODE_TEST_STRING = 'Unicode_\xc3\xa6\xc3\xb8'
class Timezon... |
#!/usr/bin/python
# Support for python2
from __future__ import print_function
#Modify system path
import sys
sys.path.append('../pycThermopack/')
# Importing pyThermopack
from pyctp import cubic
# Importing Numpy (math, arrays, etc...)
import numpy as np
# Importing Matplotlib (plotting)
import matplotlib.pyplot as plt... |
#Задание 4
from random import choices
from collections import Counter
#1. Напишите функцию (F): на вход список имен и целое число N; на выходе список
#длины N случайных имен из первого списка (могут повторяться, можно взять значения:
#количество имен 20, N = 100, рекомендуется использовать функцию random);
list_1 = ... |
"""
Binner functions for grouping numeric variables into
bins
"""
import re
import math
import numpy as np
import pandas as pd
def cutpoints(
x,
qntl_cutoff=[0.025,0.975],
cuts='linear',
ncuts=10,
sig_fig=3,
**kwargs):
'''
Function to return cut points and bin labels for a numeric 1-D... |
import numpy
import gzip
import os
import config
substitution_rate_directory = '%s/substitution_rates/' % (config.data_directory)
intermediate_filename_template = '%s/%s/%s.txt.gz'
def load_substitution_rate_map(species_name, prev_cohort='all'):
intermediate_filename = intermediate_filename_template % ... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('default_documents', '0012_auto_20151202_1413'),
]
operations = [
migrations.AddField(
model_name='contractordeliverable',
name='document_number',
field=m... |
import unittest
import rx3
from rx3 import operators as ops
from rx3.testing import TestScheduler, ReactiveTest
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.dispo... |
#!/usr/bin/env python
# T. Carman, Jan 20 2021 (Biden inauguration!)
# A quick stab at setting up an ensemble of runs.
import os
import argparse
import textwrap
import sys
import subprocess
import json
import numpy as np
import netCDF4 as nc
def setup_for_driver_adjust(exe_path, input_data_path, N=5):
'''
Work ... |
import asyncio
from asyncio.streams import StreamReader, StreamWriter
from concurrent.futures import TimeoutError
from os import urandom
from hashlib import sha1
from base64 import b64decode
from io import BytesIO
from struct import pack, unpack
from Auth.Constants.AuthStep import AuthStep
from Auth.Handlers.LoginChal... |
# -*- 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 ------------------------------------------------------------... |
from nanome._internal._util._serializers import _StringSerializer
from nanome.util import FileError
from nanome._internal._util._serializers import _TypeSerializer
class _Get(_TypeSerializer):
def __init__(self):
self.__string = _StringSerializer()
def version(self):
return 0
def name(s... |
#!/usr/bin/env python
########
# NOTE: this may not be used at all at this point.
#
# The code in here is now in teh py_gnome repository anyway
#######
"""
hazmatPy module
This module contains assorted functions and classes that are useful
for NOAA/HAZMAT stuff.
It currently contains:
read_bna(filename,polytype = ... |
import choraconfig, glob
batch = choraconfig.clone_batch("nrec-new")
batch["toolIDs"] = ["chorafull","icra2019","ua","utaipan","viap"]
|
import pandas as pd
def result1(print_table=True):
# building table for result 1
shs27_bfs = pd.read_csv('save_test_results/SHS27k_bfs', sep=',', header=None)
shs27_dfs = pd.read_csv('save_test_results/SHS27k_dfs', sep=',', header=None)
shs27_random = pd.read_csv('save_test_results/SHS27k_random', se... |
def pot(x, n):
if (n == 0):
return(1)
if (n == 1):
return(x)
if (n % 2 == 0):
half = pot(x, n / 2)
return(half * half)
else:
half = pot(x, (n - 1) / 2)
return(half * half * x)
x, n = map(int, input().split())
print(pot(x, n))
def compare(x... |
"""
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates... |
class ConfigurationReloadInfo(object,IDisposable):
"""
This object contains information returned by a reload of the fabrication configuration.
ConfigurationReloadInfo()
"""
def Dispose(self):
""" Dispose(self: ConfigurationReloadInfo) """
pass
def GetConnectivityValidation(self):
"""
GetC... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import boto3
from botocore import config
import tarfile
import os
import json
from io import BytesIO
from MediaInsightsEngineLambdaHelper import MediaInsightsOperationHelper
from MediaInsightsEngineLambdaHel... |
# Non-parametric optimization.<br>
# Find interesting bits. Combine them. Repeat.<br>
# [home](http://menzies.us/bnbab2) :: [lib](http://menzies.us/bnbad2/lib.html) ::
# [cols](http://menzies.us/bnbad2/tab.html) :: [tbl](http://menzies.us/bnbad2/grow.html)<br>
# <hr>
# <a href="http://github.com/timm/bnbad2"><i... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
import subprocess
import numpy as np
import pytest
from jina import Document, DocumentArray, Flow
from jina.executors.metas import get_default_metas
from ...faiss_searcher import FaissSearcher
def _get_d... |
"""Tests for `vivit.extensions.firstorder.batch_grad`."""
|
# Generated by Django 3.2 on 2021-05-08 08:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('example', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='calendar',
name='public',
fie... |
from .construct_workloads import *
|
from locust import HttpLocust, TaskSet, between, task, seq_task
from locust.events import request_failure
import requests
import json
import random
class WebsiteTasks(TaskSet):
@task(1)
def get_data_1(self):
self.client.get("http://localhost:8000/api/v1/projectsss/")
@task(1)
def get_d... |
def notas(*num, sit=False):
"""
Retorna um dicionário com a quantidade de notas, a maior nota, a menor nota, a média e a situação(opcional)
:param num: Notas dos alunos
:param sit: Situação. Se true,, mostra a situação conforme a média. Se false, não mostra a situação.
:return: dicionário com a quan... |
from __future__ import annotations
import logging
import typing as t
import typing_extensions as tx
from prestring.python import Module, Symbol, FromStatement
InputData = t.Dict[str, t.Any]
if t.TYPE_CHECKING:
from swagger_marshmallow_codegen.resolver import Resolver
logger = logging.getLogger(__name__)
class Co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: pkuyouth_server/reply.py
from lxml import etree
import time
__all__ = ['TextMsg','ImageMsg','SystemMsg','ArticleMsg']
class Message(object):
def __init__(self, toUser, fromUser):
self.tree = etree.Element('xml')
self._update({
'ToUserName': toUse... |
# coding: utf-8
"""
syntropy-controller
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
imp... |
# _*_coding:utf-8_*_
# @auther:FelixFu
# @Date: 2021.4.16
# @github:https://github.com/felixfu520
import torch
from torchvision.models.densenet import densenet169
from torchvision.models.densenet import densenet121
from torchvision.models.densenet import densenet161
from torchvision.models.densenet import densenet201
... |
from django.apps import AppConfig
class ChatConfig(AppConfig):
name = 'chat'
def ready(self):
import chat.signals |
#!python3
"""
Implementation of the classic cut-and-choose protocol
for fair cake-cutting among two agents.
References:
Abram, Genesis 13:8-9.
Programmer: Erel Segal-Halevi
Since: 2019-11
"""
from fairpy.agents import *
from fairpy import Allocation
from typing import *
import logging
logger = logging.getLogge... |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... |
#!/usr/bin/env python3
import math
import torch
from .kernel import Kernel
from ..functions import add_jitter
from ..lazy import DiagLazyTensor, LazyTensor, MatmulLazyTensor, PsdSumLazyTensor, RootLazyTensor
from ..distributions import MultivariateNormal
from ..mlls import InducingPointKernelAddedLossTerm
class Indu... |
import datetime
import json
import locale
import logging
import os
import random
import shutil
from typing import Dict, List
import numpy as np
import pandas as pd
import pytest
from freezegun import freeze_time
from ruamel.yaml import YAML
import great_expectations as ge
from great_expectations import DataContext
fr... |
ROOT_SCOPE_METHOD( MD( 'FlatmapObjective', 'FLATMAP_FACTORY_single()' ) )
REGISTER_FLAG( 'map_evaluation', 'evaluation uses something similar to a buffered map' )
FUNCTION( 'void nom_phrase_flatten( ANY context, ANY phrase, ANY scope )', """
$ENABLED( map_evaluation,
JUMP__return_ANY( context, context, nom... |
# -*- coding: utf-8 -*-
from django.contrib import admin
class TipoImpostoAdmin(admin.ModelAdmin):
list_display = ('codigo','nome')
list_display_links = ('codigo','nome')
search_fields = ['nome','codigo']
fieldsets = (
('', {
'fields': (('nome',),)
}),
) |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
# @copyright@
# Copyright (c) 2006 - 2018 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import os
import stack.commands
class Plugin(stack.commands.Plugin):
"""
Generate a UEFI specific configuration file
"""
def provides(sel... |
#
# 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... |
#
# Copyright (c) 2018-2019 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 agre... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
import discretize
# from SimPEG import Maps
# from SimPEG.EM import FDEM
from scipy.constants import mu_0, epsilon_0
from geoana.em im... |
import os
import re
import io
import wx
from html import escape
import sys
import math
from math import radians, degrees, sin, cos, asin, sqrt, atan2, exp, modf, pi
import random
import bisect
import datetime
import getpass
import socket
from Version import AppVerName
from Animation import GetLapRatio
import Utils
from... |
from collections import deque
import random as rand
import math as math
import time
# the default weight is 1 if not assigned but all the implementation is weighted
class DirectedGraph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles ... |
# 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 ... |
from setuptools import setup, find_namespace_packages
setup(
name='embit',
version='0.1.1',
license='MIT license',
url='https://github.com/diybitcoinhardware/embit',
description = 'yet another bitcoin library',
long_description="A minimal bitcoin library for MicroPython and Python3 with a focus... |
import cv2
import numpy as np
import random
face_cascade = cv2.CascadeClassifier('/usr/share/opencv4/haarcascades/haarcascade_frontalface_default.xml')
class FaceDetect():
clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(4,4))
min_count = 10
interval = 10
def __init__(self):
self.... |
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
num = 0
base = 1
while X * base < Y:
num += 1
base <<= 1
diff = X * base - Y
while diff:
num += diff // base
diff %= base
base >>= 1
return num
cl... |
# Copyright (c) 2020
# Author: xiaoweixiang
import glob
import os
import subprocess
import sys
from distutils import log
from distutils.errors import DistutilsError
import pkg_resources
from setuptools.command.easy_install import easy_install
from setuptools.extern import six
from setuptools.wheel import Wheel
fro... |
"""
Ory Kratos API
Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the admini... |
# pylint: disable=W0231,E1101
import collections
from datetime import timedelta
import functools
import gc
import json
import operator
from textwrap import dedent
import warnings
import weakref
import numpy as np
from pandas._libs import Timestamp, iNaT, properties
import pandas.compat as compat
from pandas.compat im... |
# -*-coding:utf-8-*-
import random
import torch
from torch.utils import data
from torch import nn #nn:神经网络缩写
import numpy as np
from d2l import torch as d2l
#构造人造数据集
def synthetic_data(w,b,num_examples):
"""生成y = Xw + b + 噪声"""
'''
使用线性模型参数 𝐰=[2,−3.4]⊤ 、 𝑏=4.2
和噪声项 𝜖 生成数据集及其标签:
'''
X = torc... |
import asyncio
import aioredis
async def main():
# Redis client bound to single connection (no auto reconnection).
redis = await aioredis.create_redis(
'redis://localhost')
await redis.set('my-key', 'value')
val = await redis.get('my-key')
print(val)
# gracefully closing underlying co... |
# AUTOGENERATED FILE - DO NOT MODIFY!
# This file was generated by Djinni from my_enum.djinni
from djinni.support import MultiSet # default imported in all files
from djinni.exception import CPyException # default imported in all files
from djinni import exception # this forces run of __init__.py which gives cpp opti... |
from typing import List
from PyQt5.QtCore import QRectF
from actor.text_actor import TextActor
from config.hot_key import KeyCombo, HotKey
from observer.base_observer import BaseObserver
from observer.event.events import CustomEvent
from observer.vector_map_reprojector import VectorReprojector
from vector.vector impo... |
# Standard Library
import ast
from collections import defaultdict
from copy import copy
# Local Modules
import saplings.utilities as utils
import saplings.tokenization as tkn
from saplings.entities import ObjectNode, Function, Class, ClassInstance
# import utilities as utils
# import tokenization as tkn
# from entitie... |
from json import loads, dump
import os
class MStore:
_data = {}
_is_changed = False
filename = ""
indent = None
sort_keys = False
def __init__(self, *args, **kwargs):
"""Manipulate a file as python dict:
- use load and save to manipulate file
- make dict operat... |
import random
from PIL import Image, ImageDraw
image = Image.open("../roof.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()
for x in range(width):
for y in range(height):
r = round(pix[x, y][0]/2)
g = round(pix[x, y][1]/2)
... |
from rest_framework import permissions
# based on https://www.django-rest-framework.org/api-guide/permissions/#examples
class IsOwner(permissions.BasePermission):
"""Object-level permission to only allow owners of an object to interact with it."""
# pylint: disable=no-self-use,unused-argument
def has_obj... |
from django.contrib import admin
from tinymce.widgets import TinyMCE
from .models import Video
from django.db import models
##admin.site.register(Item)
admin.site.register(Video)
# Register your models here.
|
from ale.base.base import Driver
|
import lab as B
from gpcm.sample import ESS
from stheno import Normal
import numpy as np
from .util import approx
def test_ess():
# Construct a prior and a likelihood.
prior = Normal(np.array([[0.6, 0.3], [0.3, 0.6]]))
lik = Normal(
np.array([[0.2], [0.3]]),
np.array([[1, 0.2], [0.2, 1]])... |
from bs4 import BeautifulSoup
import requests
import csv
def writetoCsv(filename,url,dynamicurl):
out=open(filename, 'w+',encoding='gb18030',newline = '')
csv_write=csv.writer(out)
csv_write.writerow(['评分','评论题目','用户名','时间','评论内容'])
dynamiCrawl(url,dynamicurl,csv_write)
writeto... |
# Copyright 2022 AI Singapore
#
# 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 in writing... |
#
# K2HDKC DBaaS based on Trove
#
# Copyright 2020 Yahoo Japan Corporation
#
# K2HDKC DBaaS is a Database as a Service compatible with Trove which
# is DBaaS for OpenStack.
# Using K2HR3 as backend and incorporating it into Trove to provide
# DBaaS functionality. K2HDKC, K2HR3, CHMPX and K2HASH are components
# provide... |
import json
import tqdm
import jsonlines
from kss import split_sentences
with open('train_summary.json', 'r') as data:
data = json.load(data)
article_original = []
abstractive = []
category = []
extractive = []
for example in tqdm.tqdm(data):
try:
original = split_sentence... |
# File name: controlbar.py
import kivy
kivy.require('1.9.0')
from kivy.uix.behaviors import ButtonBehavior, ToggleButtonBehavior
from kivy.uix.image import Image
from kivy.lang import Builder
Builder.load_file('controlbar.kv')
class VideoPlayPause(ToggleButtonBehavior, Image):
pass
class VideoStop(ButtonBehav... |
import logging
from PyQt5.QtWidgets import QPlainTextEdit, QGroupBox, QVBoxLayout
from ..python_core.appdirs import get_app_log_dir
import pathlib as pl
import time
import sys
# solution copied from https://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt
class QPlainTextEditLogger(QPlainTextEdit... |
from rest_framework import serializers
from core.models import Booking, Restaurant
from django.db.models import Sum
from restaurant.serializers import RestaurantSerializer
# this is an example for modifying the serializer data
class BookingSerializer(serializers.ModelSerializer):
restaurant = serializers.Prima... |
# -*- coding: utf-8 -*-
"""
datetime package.
"""
from pyrin.packaging.base import Package
class DateTimePackage(Package):
"""
datetime package class.
"""
NAME = __name__
COMPONENT_NAME = 'globalization.datetime.component'
DEPENDS = ['pyrin.configuration',
'pyrin.security.sess... |
"""
This module contains all expressions and classes needed for lazy computation/ query execution.
"""
import os
import shutil
import subprocess
import tempfile
import typing as tp
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Type, Union
try:
from polars.polars import PyExpr, PyLazyFrame, PyL... |
"""
SparseArray data structure
"""
from __future__ import division
# pylint: disable=E1101,E1103,W0231
from numpy import nan, ndarray
import numpy as np
import pandas as pd
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas import compat, lib
from pandas.compat import range
from p... |
"""
Custom loaders for different datasets
"""
|
# 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
# d... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package contains functions for reading and writing HDF5 tables that are
not meant to be used directly, but instead are available as readers/writers in
`astropy.table`. See :ref:`table_io` for more details.
"""
import os
import warnings
import nu... |
"""
Tests the data transformation module.
"""
# Author: Alex Hepburn <ah13558@bristol.ac.uk>
# Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
import pytest
import numpy as np
import fatf.utils.data.transformation as fudt
from fatf.exceptions import IncorrectShapeError
# yapf: disable
NUMERICAL_NP_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.