text stringlengths 1 927k |
|---|
# Python program for Bitonic Sort. Note that this program
# works only when size of input is a power of 2.
# The parameter dir indicates the sorting direction, ASCENDING
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
# then a[i] and a[j] are interchanged.
def compAndSwap(a, i, j, dire):
if (dire == ... |
"""
Round-rotor generator model.
"""
import logging
from andes.core.service import VarService
from andes.models.synchronous.genbase import GENBase, Flux0
from andes.models.synchronous.genrou import GENROUData, GENROUModel
logger = logging.getLogger(__name__)
class GENROUOSModel(GENROUModel):
def __init__(self)... |
expected_output = {
"services-accounting-information": {
"flow-aggregate-template-detail": {
"flow-aggregate-template-detail-ipv4": {
"detail-entry": [{
"byte-count": "184",
"input-snmp-interface-index": "1014",
"mpls-la... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import os
import sqlalchemy as db
from werkzeug.security import generate_password_hash
import common.... |
from __future__ import division, print_function
import pyroomacoustics as pra
import numpy as np
try:
from pyroomacoustics import build_rir
build_rir_available = True
except:
print('build_rir not available')
build_rir_available = False
# tolerance for test success (1%)
tol = 0.01
fdl = 81
fs = 16000
... |
import os
from utils import image
from datasets.data_format import yolo
def get_annotation_content(img_path, annotation_objs, classes):
"""
annotation_objs: xmin, ymin, xmax, ymax, obj_name
"""
w, h = image.get_image_size(img_path)
yolo_lines = []
for obj in annotation_objs:
xmi... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib
matplotlib.use('Agg',force=True) # no display
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matp... |
import itertools
import time
from collections import defaultdict
import pytest
from mock import ANY, Mock, create_autospec, patch
from six.moves import queue
from nameko.containers import WorkerContext
from nameko.events import (
BROADCAST, SERVICE_POOL, SINGLETON, EventDispatcher, EventHandler,
EventHandlerC... |
"""
Django settings for webapi project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib im... |
# -*- coding: utf-8 -*-
# Scrapy settings for adzan project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/t... |
# Desafio 78 - Aula 17 : Leia 5 valores adicionando-os em uma lista.
# Mostre o MAIOR e o MENOR em suas respectivas posições
lista = list(int(input(f'Me diga o valor da posição {pos+1}: '))for pos in range(5))
print('='*40)
print(f'O maior valor digitado foi {max(lista)} e aparece nas posições ',end=' ')
for posicao... |
"""This module contains the general information for EquipmentProcessorUnitCapProvider ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class EquipmentProcessorUnitCapProviderConsts():
DELETED_FALSE... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: identity/ids/UserDoctorRec.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import r... |
# Mercurial extension to provide the 'hg children' command
#
# Copyright 2007 by Intevation GmbH <intevation@intevation.de>
#
# Author(s):
# Thomas Arendsen Hein <thomas@intevation.de>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version... |
# Generated by Django 2.2.11 on 2020-03-11 20:49
import django.contrib.postgres.fields.jsonb
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [("api", "0014_reload_azure_map")]
operations = [
migrations.AddField(
model_na... |
import numpy as np
from operator import add, gt
from core import *
def test_binary_function():
expr = "(def (fun x y) (add x y))"
fun = get_function(expr, "fun")
assert fun(4, 3) == 7
def test_multiline_function():
expr = "(def (fun x y) (def a (add y x)) (add a 1))"
fun = get_function(expr, "fun"... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/
# Written by Bastian Schnell <bastian.schnell@idiap.ch>
#
"""Setup idiaptts"""
from itertools import dropwhile
import os
from os import path
from setuptools import find_packages, setup
import glob
def collect_docstring(lines... |
from .modules.tree_filter import MinimumSpanningTree
from .modules.tree_filter import TreeFilter2D |
import util
import pandas as pd
import sys
import re
def rename_param(input_dir, old_name, new_name):
param_pattern = "Parameters_(\d\d*).csv"
param_files = util.find_files_with_regex(input_dir, param_pattern)
for param_file in param_files:
param_df = pd.read_csv(param_file)
if old_name no... |
# -*- coding: utf-8 -*-
#
# SelfTest/Cipher/CAST.py: Self-test for the CAST-128 (CAST5) cipher
#
# =======================================================================
# Copyright (C) 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of... |
from __future__ import unicode_literals
import datetime
import logging
from inspect import isclass
from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist
from django.db.models import Q, ForeignKey
from .fields import SlickReportField
from .helpers import get_field_from_query_text
from .registry i... |
import tensorflow as tf
global_visible = None
class Idx2PixelLayer(tf.keras.layers.Layer):
def __init__(self, visible, trainable=False, shift_multi=1, **kwargs):
"""
:param visible: one dimension of visible image (for this dimension [x,y] will be computed)
"""
super(Idx2PixelLaye... |
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework.response import Response
from app_user.models import User
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated... |
import numpy as np
import itertools
import random
from debugq.envs import random_obs_wrapper, time_limit_wrapper, env_wrapper
from rlutil.envs.tabular_cy import tabular_env
from rlutil.envs.gridcraft import grid_env_cy
from rlutil.envs.gridcraft import grid_spec_cy
from rlutil.logging import log_utils
from rlutil impor... |
#!/usr/bin/env python3
import jafka
consumer = jafka.Consumer('localhost',9092)
offsets = consumer.getoffsetsbefore('demo',0,-2,100)
print('offsets',offsets)
ms = consumer.fetch('demo',0,offsets[0],1024)
for offset,message in ms:
print(offset,message.decode('utf-8')) |
# -*- encoding: utf-8 -*-
"""
12306网爬虫Main
Author: zsyoung
Date: 2019/01/09 15:00
"""
import threading
import stationcrawl.threadpool as threadpool
import time
from stationcrawl import HttpUtils, FileUtils
from stationcrawl.Constants import *
from stationcrawl.TrainSpider import parse_train_no_json
from statio... |
from django.db import migrations
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "todolist-29010.botics.co"
site_params = {
"name": "Todolist",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create... |
# Copyright (c) 2019 PaddlePaddle 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 appli... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 13:37:11 2019
@author: jmc010
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.lines as mlines
import numpy as np
# install at an anaconda command prompt using: conda install -c anaconda dill
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
"requests"
# TODO: put package requirements here
]
test_requirement... |
from pathlib import Path
import sys
sys.path.append(str(Path().absolute()))
import logging
log_level = "INFO"
logging.basicConfig(
filename=str(snakemake.log),
filemode="w",
level=log_level,
format="[%(asctime)s]:%(levelname)s: %(message)s",
datefmt="%d/%m/%Y %I:%M:%S %p",
)
from evaluate.calculator... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import next
from builtins import map
from builtins import range
from builtins import *... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016,小忆机器人
All rights reserved.
摘 要:电视控制
创 建 者:余菲
创建日期:17/2/11
"""
from dict.dict import pronoun, modals, prep, degree, honorific, interj, \
auxiliary, quantifier, numeral, adjective, adverb, prefix_unsual, any_w, stop_words
from nlu.rule... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
#
# @AUTHOR: Rabbir
# @FILE: /root/Github/dmarket-trading-bot/main.py
# @DATE: 2020/12/29 Tue
# @TIME: 16:39:37
#
# @DESCRIPTION: dmarket-trading-bot 主模块
import config_loader
from rab_python_packages import rab_logging
# 日志记录
main_logger = rab_logging.build_rab_logger() |
from setuptools import setup, find_packages
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: APACHE / MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topi... |
import gym
import gym_solventx
from qagent import QAgent
env = gym.make('gym_solventx-v0', goals_list=['Purity', 'Recovery'])
qagent = QAgent(env)
qagent.train_agent()
qagent.show_plots() |
#!/usr/bin/env python
#
# Copyright 2007 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 o... |
#因子覆盖率、半衰期
#计算多个因子间的相关系数矩阵
#不同行业中因子表现
#各种画图,可视化 |
"""Converts MNIST data to TFRecords file format with Example protos."""
import os
import tensorflow as tf
from PIL import Image
import numpy as np
from matplotlib.pyplot import imshow
def gen_image(arr):
try:
two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
img = Image.fromarray(two_d, 'L... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} node
# @return {void} Do not return anything, modify node in-place instead.
def deleteNode(self, node):
if not node:
... |
#!/usr/bin/env python
# Copyright (c) 2007, Google Inc.
# 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 l... |
# flake8: noqa E501
import json
conditional_token_abi = json.loads(
)
market_maker_abi = json.loads(
)
market_maker_factory_abi = json.loads(
'[{"constant":true,"inputs":[],"name":"implementationMaster","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[... |
"""Various debugging functions."""
import sys
import os
import functools
import gc
try:
import resource
def max_mem_usage():
"""
Return the maximum resident memory used by this process and its children so far.
Returns
-------
The max resident memory used by this proce... |
from archivekit.collection import Collection # noqa
from archivekit.archive import Archive # noqa
from archivekit.resource import Resource # noqa
from archivekit.types.source import Source # noqa
from archivekit.ext import get_stores
def _open_store(store_type, **kwargs):
store_cls = get_stores().get(store_type)... |
import pandas as pd
import util_functions as uf
if __name__ == "__main__":
# Connect to AWS
uf.set_env_path()
conn, cur = uf.aws_connect()
# Trips by Date and Operator
df = pd.read_sql("""select distinct
OperatorClean,
count(*) as trips
... |
""" Asked by: Google [Hard].
Given an array of integers where every integer occurs three times except for one integer,
which only occurs once, find and return the non-duplicated integer.
For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.
Do this in O(N) time and O(1) space.
""" |
from concurrent.futures import ProcessPoolExecutor
from functools import partial
import numpy as np
import os
import audio
from hparams import hparams
def build_from_path(in_dir, out_dir, num_workers=1, tqdm=lambda x: x):
'''Preprocesses the LJ Speech dataset from a given input path into a given output directory.... |
# nxt.compass module -- Classes to read Mindsensors Compass sensors
# Copyright (C) 2006 Douglas P Lau
# Copyright (C) 2009 Marcus Wanner
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... |
from .models import *
from .general import *
from .generator import *
from .classification import * |
"""MULTI2 cipher.
Source: Cryptanalysis of the ISDB Scrambling Algorithm (MULTI2)
"""
from cascada.bitvector.core import Constant
from cascada.bitvector.operation import RotateLeft, BvOr
from cascada.bitvector.ssa import RoundBasedFunction
from cascada.primitives.blockcipher import Encryption, Cipher
REFERENCE_VERS... |
# coding: utf8
# ! /usr/env/python
"""Base class for profile constructors."""
from abc import ABC, abstractmethod
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from landlab import Component
from landlab.plot import imshow_grid
from landlab.utils.return_array import return_array_at... |
import sys
from fabric2 import Connection, task
from invoke import Responder
from fabric2.config import Config
PROJECT_NAME = "py-flask"
PROJECT_PATH = "~/PycharmProjects/{}".format(PROJECT_NAME)
REPO_URL = "remote_repo_url"
def get_connection(ctx):
try:
with Connection(ctx.host, ctx.user, connect_kwargs=... |
import tkinter, random, time
from tkinter import messagebox
from threading import Thread
from structs import Crossword, Word
from render import Render
class Generator:
def __init__(self, name):
self.progressbar_pos = [0, 0]
self.progressbar_dir = 'e'
self.name = name
self.progress... |
from Frame.baseFunctions import *
from Frame.gui.Gui import Gui
class Button(Gui):
def __init__(self, function, functionArgs, *args, **kwargs):
super().__init__(*args, **kwargs)
output("Button: Creating " + self.text + " button...", "debug")
self.wasPressed = False
self.function = ... |
#-------------------------------------------------------------------------------
# elftools: dwarf/compileunit.py
#
# DWARF compile unit
#
# Eli Bendersky (eliben@gmail.com)
# This code is in the public domain
#-------------------------------------------------------------------------------
from bisect import bisect_lef... |
from DataStream.ByteReader import ByteReader
from Protocol.Messages.Server.KeepAliveServerMessage import KeepAliveServerMessage
from Logic.Player import Player
from Protocol.Messages.Server.AvailableServerCommandMessage import AvailableServerCommandMessage
class KeepAliveMessage(ByteReader):
def __init__(self, cli... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2011-present MagicStack Inc. and the EdgeDB 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... |
# Copyright 2015 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... |
import unittest
from jackedCodeTimerPY import JackedTiming, _Record, JackedTimingError
class TestCodeTimer(unittest.TestCase):
def test__Record(self):
record = _Record()
record.start()
self.assertTrue(record.started)
record.stop()
self.assertFalse(record.started)
self.assertTrue(len(record.... |
from mapper import mapper
from typing import List
def encode(unencoded_str: str, tree: List) -> str:
letter_map = mapper(tree)
encoded_str = ""
unencoded_str_list = list(unencoded_str)
for i in range(len(unencoded_str_list)):
encoded_value = list(letter_map.keys())[list(letter_map.values()).i... |
# 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 ... |
# -*- coding: UTF-8 -*-
import os
import sys
from subprocess import Popen, PIPE
from multiprocessing import Process, Pipe
import argparse
import json
from datetime import datetime
from enum import Enum
if sys.version_info > (3, 0):
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
c... |
#!/usr/bin/env python
# Copyright 2016 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
import unittest
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from shapash.utils.explanation_metrics import _df_to_array, \
_compute_distance, _compute_similarities, _get_radius, find_neighbors, \
shap_neighbors, get_min_nb_features, get_distance
class TestExplanatio... |
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# disable Invalid constant name pylint warning for mandatory Alembic variables.
"""Helper for updating access_control_roles table with the missing records
"""
import json
from datetime import datetime
imp... |
from __future__ import annotations
from typing import Tuple, NoReturn
import IMLearn.metrics
from ...base import BaseEstimator
import numpy as np
from itertools import product
class DecisionStump(BaseEstimator):
"""
A decision stump classifier for {-1,1} labels according to the CART algorithm
Attributes... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import numpy as np
import torch
from torch import nn
from fsdet.structures import ImageList
from fsdet.utils.logger import log_first_n
from ..backbone import build_backbone
from ..postprocessing import detector_postprocess
from ..pr... |
from enum import Enum
from time import time
import numpy as np
class State(Enum):
"""The status for the timer. This class is inherited from Enum.
Attributes:
activate: int
Let the timer engine start.
deactivate: int
The timer shutdown its engine.
"""
activate =... |
# Example showing how functions, that accept tuples of rgb values,
# simplify working with gradients
import time
from neopixel import Neopixel
numpix = 60
strip = Neopixel(numpix, 1, 1, "GRB")
# strip = Neopixel(numpix, 0, 0, "GRBW")
red = (255, 0, 0)
orange = (255, 50, 0)
yellow = (255, 100, 0)
green = (0, 255, 0)
... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2018 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.data import logger
from lib.core.exception import SqlmapUnsupportedFeatureException
from plugins.generic.enumeration import Enumeration as GenericEnumeration
class ... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Logit'] , ['MovingMedian'] , ['Seasonal_DayOfMonth'] , ['SVR'] ); |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# use closure-compiler to shrink JavaScript file size
import os, sys
compiler = 'java -jar ~/closure-library-read-only/compiler/compiler.jar'
input_bootstrap = '--js templates/js/bootstrap.js'
output_bootstrap_wso = '--js_output_file templates/js/bootstrap-wso.js'
output_... |
import os
import sys
sys.path.append(
os.path.dirname( os.path.dirname( os.path.abspath( __file__ ) ) )
)
from dynamo.entities import itemToVisit # pylint: disable=wrong-import-position
def processPages( dynamo_client, event ):
'''Creates the page and day/week/month/year from a DynamoDB event.
Parameters
----... |
from django.contrib import admin
from .models import Item
# Register your models here.
admin.site.register(Item) |
"""
zeep.wsdl.messages
~~~~~~~~~~~~~~~~~~
The messages are responsible for serializing and deserializing
.. inheritance-diagram::
zeep.wsdl.messages.soap.DocumentMessage
zeep.wsdl.messages.soap.RpcMessage
zeep.wsdl.messages.http.UrlEncoded
zeep.wsdl.mess... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
import sonnet as snt
from PIL import Image, ImageOps
import cv2
import numpy as np
import os
import i3d
import sys
inp1 = sys.argv[1]
inp2 = sys.argv[2]
# In[2]:
# Proprecessing for image(scale and crop)
def reshape_img_pil(img):
wid... |
from pandac.PandaModules import *
from direct.distributed.ClockDelta import *
import math
import random
from pandac.PandaModules import Point3
from direct.directnotify import DirectNotifyGlobal
from toontown.battle import SuitBattleGlobals
import SuitTimings
import SuitDNA
from toontown.toonbase import TTLocalizer
TIME... |
from _qflow_backend.optimizers import * |
# Copyright (c) 2014 VMware, 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outp... |
"""
API Handlers for /policies routes
"""
import connexion
import hashlib
import json
import anchore_engine.apis
import anchore_engine.common
import anchore_engine.common.helpers
from anchore_engine import db
import anchore_engine.services.catalog.catalog_impl
from anchore_engine.subsys import logger
import anchore_... |
'''
# this is the evaluation code. Change the prediction file name to the one from your test step. the precision and recall were calculated as described
Tjong Kim Sang, Erik. F. 2002. Introduction to the CoNLL-2003 Shared Task: Language Independent Named Entity Recognition. In Proc. Conference on Natural Language Lear... |
from setuptools import setup, find_packages
version = '0.4'
setup(
name='py-configuration',
version=version,
packages=find_packages(exclude=['tests*']),
keywords='yaml config parser',
license='MIT',
description='A small python package for using yaml based config files',
long_description=op... |
import os, re
import frappe
from frappe import _
import frappe.sessions
from six import text_type
def get_context(context):
if (frappe.session.user == "Guest" or
frappe.db.get_value("User", frappe.session.user, "user_type")=="Website User"):
frappe.throw(_("You are not permitted to access this page."), frappe.Pe... |
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class BoxPlot:
def __init__(
self,
title,
x_label,
y_label,
):
self.title = title
self.x_label = x_label
self.y_label = y_label
self.data = pd.DataFrame()... |
'''
Source : https://leetcode.com/problems/long-pressed-name/description/
Author : Yuan Wang
Date : 2019-01-12
/**********************************************************************************
*Your friend is typing his name into a keyboard. Sometimes, when typing a character
*c, the key might get long pressed, ... |
# -*- coding: utf-8 -*-
import os
import urllib
import urllib2,json
from datetime import date
from os import path
import sys
import ConfigParser
import platform
reload(sys)
sys.setdefaultencoding('utf-8')
heKey = '和风key'
city = "CN101021200" #上海徐汇天气代码
api_key = "百度语音合成api key"
sec_key = "百度语音合成secret key"
def read... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Utility routines for workflow graphs"""
import os
import sys
import pickle
from collections import defaultdict
import re
from copy import deepcopy
from glob import glob
from pathl... |
from uontypes.units.quantity import Quantity
class Time(Quantity):
pass
class Second(Time):
def __str__(self):
return "s"
def to_binary(self):
return b"\x22"
class Minute(Time):
def __str__(self):
return "min"
def to_binary(self):
return b"\x45" |
#!/usr/bin/env python3
"""
Meerkat Frontend Tests
Unit tests for the Meerkat frontend
"""
from unittest import mock
from flask import g
from meerkat_libs import hermes
import meerkat_frontend as mk
import unittest
import calendar
import os
import time
#from meerkat_frontend.test.test_reports import *
#from meerkat_fr... |
# -*- coding: utf-8 -*-
# Copyright 2012 Loris Corazza, Sakis Christakidis
#
# 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
#
# U... |
# Copyright (c) 2013-2014 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 Cosmin Poieana <cmin@ropython.org>
# Copyright (c) 2014 Vlad Temian <vladtemian@gmail.com>
# Copyright (c) 2014 Arun Pers... |
from lox import expressions
from lox.tokens import Token, TokenType
class AstPrinter(expressions.ExprVisitor):
def print(self, expr: expressions.Expr):
return expr.accept(self)
def parenthesize(self, name: str, *exprs: expressions.Expr) -> str:
content = ' '.join(expr.accept(self) for expr in... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading the file
data=pd.read_csv(path)
print(data.iloc[25, 1])
# df = pd.DataFrame(data)
#Code starts here
loan_status = data['Loan_Status'].value_counts()
loan_status.plot(kind = 'bar')
# # Step 1
#Read... |
from django.db import models
class Announcement(models.Model):
title = models.CharField(max_length=100, null=False)
text = models.TextField(null=False)
date = models.DateTimeField(auto_now_add=True)
@property
def short_id(self):
return self.title
def __str__(self):
return f"{... |
# ICONS GETTER MODULE BY SINIKRAFT #
# Check out : 'github.com/SiniKraft' ! #
# Icons Getter can be used to generate a .png file with the icon of a specified file, including previews. #
# Icons Getter is a java package, and this library add python compatibility #
# Needs a java jdk to be in the same folder, in "jdk" ... |
# Copyright (c) 2012 NetApp, Inc. All rights reserved.
# Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Andrew Ker... |
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
i = len(digits) - 1
while i > -1:
if digits[i] != 9:
digits[i] = digits[i] + 1
return digits
digits[i] = 0
i-=1
return [1] + digits |
from sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("XGBRegressor" , "freidman3" , "db2") |
from __future__ import absolute_import, unicode_literals
import os
import sys
from opencc.clib import opencc_clib
__all__ = ['OpenCC', 'CONFIGS', '__version__']
__version__ = opencc_clib.__version__
_thisdir = os.path.dirname(os.path.abspath(__file__))
_opencc_share_dir = os.path.join(_thisdir, 'clib', 'share', 'op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.