content stringlengths 5 1.05M |
|---|
from functools import reduce
from manimlib.imports import *
class OpeningQuote(Scene):
def construct(self):
words = TextMobject([
"Lisa:",
"Well, where's my dad?\\\\ \\\\",
"Frink:",
"""Well, it should be obvious to even the most
dimwitted indi... |
import click
from regparser.commands.annual_editions import annual_editions
from regparser.commands.annual_version import annual_version
from regparser.commands.diffs import diffs
from regparser.commands.fill_with_rules import fill_with_rules
from regparser.commands.import_notice import import_notice, parse_notice
fro... |
import json
import logging
from django.apps import apps
from django.conf import settings
from django.test import TestCase
from hierarchy.models import SubHeading, Heading, Section, Chapter
from hierarchy.helpers import create_nomenclature_tree
logger = logging.getLogger(__name__)
logging.disable(logging.NOTSET)
logger... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Background tasks for mail module."""
from __future__ import absolute_import, prin... |
import torch._C as C
from torch.testing._internal.common_utils import TestCase, run_tests
import itertools
import unittest
# TODO: Expand the dispatcher API to be a generic API for interfacing with
# the dispatcher from Python!
#
# These are exhaustive tests for commutativity of dispatch behavior. If you're
# lookin... |
def porcentagem(valor,taxa):
if taxa >100 or taxa <0:
return -1
else:
return valor *taxa /100
print(porcentagem(1000,5))
class MinhaExcecao(Exception):
pass
def funcao(x):
if x<0 or x>100:
raise MinhaExcecao("Valor invalido") #Um problema criado pelo programador com uma linguag... |
import os
import six
import uuid
import unittest
import tempfile
import shutil
import itertools
import flaky
from yggdrasil.components import ComponentMeta, import_component
from yggdrasil import runner, tools, platform
from yggdrasil.examples import (
get_example_yaml, get_example_source, get_example_languages,
... |
from django.urls import path
from hitcount.views import HitCountDetailView
from .views import category_views
from .views.category_views import CategoryListView, CategoryDetailView, load_subCat
from .views.item_views import(ItemCreateView, ItemDeleteView,
ItemDetailView, RecentItemListView... |
#!/usr/bin/env python
import os
import arcpy
from arcpy import env
class GenericToolsBatchConvertMXERaster(object):
"""This class has the methods you need to define
to use your code as an ArcGIS Python Tool."""
def __init__(self):
"""Define the tool (tool name is the name of the cla... |
# Exercise: while loop 2
# (5/5 points)
# ESTIMATED TIME TO COMPLETE: 5 minutes
# 2. Convert the following into code that uses a while loop.
# prints Hello!
# prints 10
# prints 8
# prints 6
# prints 4
# prints 2
num = 10
print("Hello!")
while num > 0:
print(num)
num -= 2
|
"""
File utilities.
"""
# Copyright (c) 2016 University of Edinburgh.
from __future__ import (nested_scopes, generators, division,
absolute_import, with_statement,
print_function, unicode_literals)
import json
import yaml
def load_yaml(file_name):
"""Load the con... |
import requests
import re, json
def getStartingIndex(input_str):
m = re.finditer("http://", str(input_str))
ret = set()
for i in m:
# print(i.start())
ret.add(i.start())
return ret
def getSingleUrl(input_str, startIndex):
i = startIndex
while(input_str[i] is not "'"):
... |
# Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
g = str(input('Digite a letra correspondente ao seu genero '))
if g in 'f':
print('Você escolheu F - Feminino')
elif g in 'm':
print('Você escolher M - Masculino')
elif ... |
#!/usr/bin/env python3
"""
A example script to automatically send messages based on certain triggers.
The script makes uses of environment variables to determine the API ID,
hash, phone and such to be used. You may want to add these to your .bashrc
file, including TG_API_ID, TG_API_HASH, TG_PHONE and optionally TG_SES... |
from typing import Any, Dict, List, Optional, Tuple, Type, Union, get_args, get_origin
import asyncpg
from pypika.queries import QueryBuilder
from pypika.terms import BasicCriterion, ContainsCriterion, Criterion, Equality, NullValue, Parameter, RangeCriterion
def record_to_kwargs(record: asyncpg.Record) -> Dict[str,... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from yandex.cloud.datatransfer.v1 import transfer_pb2 as yandex_dot_cloud_dot_datatransfer_dot_v1_dot_transfer__pb2
from yandex.cloud.datatransfer.v1 import tran... |
# File: orbit.py
# Creation: Tuesday January 12th 2021
# Author: Arthur Dujardin
# ------
# Copyright (c) 2021 Arthur Dujardin
# Basic imports
import numpy as np
import gpstime as gpst
import gnsstoolbox.orbits as orbits
# GNSS ToolBox
from gnsstools.const import mu, F
from gnsstools.logger import logger
class Orb... |
from django.contrib import admin
from api.models import Page, ActivationKey
# Add the Page and ActivationKey models to the admin interface.
class PageAdmin(admin.ModelAdmin):
list_display = ('id', 'author', 'title')
list_filter = ('author', 'created')
search_fields = ('title', 'body')
class ActivationKey... |
import logging
from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb.model import EndpointsModel, EndpointsAliasProperty
class ProjectModel(EndpointsModel):
name = ndb.StringProperty() |
# -*- coding: utf-8
import string
from character import *
from bounty import *
from character import *
def msg_line(text, cols_total):
text_len = len(text.translate(None, string.punctuation + ' '))
half_of_columns = ' ' * ( (cols_total - ( text_len / 2) - 2) // 2 )
if text_len == 3 :
li_half_of_columns = ... |
# -*- coding: utf-8 -*-
import asyncio
import logging
import pytest
import websockets
from collections import namedtuple
from asynctest.mock import CoroutineMock
from asynctest.mock import patch
from asynctest.mock import PropertyMock
from poke_env.exceptions import ShowdownException
from poke_env.player.player_netwo... |
from dash import dcc
import dash_bootstrap_components as dbc
from dse_do_dashboard.do_dash_app import DoDashApp
from dse_do_dashboard.visualization_pages.visualization_page import VisualizationPage
from dse_do_utils.plotlymanager import PlotlyManager
class PlannedProductionPage(VisualizationPage):
def __init__(s... |
import flask
import casparser
from flask import jsonify
from flask import request
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return "<h1>This is CAS PDF Parser API</h1><p>POST to api/parsecasfile with the file location and password to get parsed JSON resp... |
import sys
from refid2bib import refid2bib
oid = sys.argv[1]
print( '\n')
print( refid2bib(oid) )
|
import pytest
RED_DOT = """data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="""
BLUE_DOT = """data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA
oAAAAKAQMAAAC3/F3+AAAACXBIWXMAAA7DAAAOwwHHb6hkAA
AAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8Y... |
# This is code is developed started from
# https://www.geeksforgeeks.org/convert-csv-to-json-using-python/
import csv
import json
import os
from dotenv import load_dotenv
import pycountry_convert as pc
CONTINENTS = {
'AQ': 'Antarctica',
'NA': 'North America',
'SA': 'South America',
'AS': 'Asia',
... |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np
import matplotlib.ticker as ticker
from get_data import Planet
class Spectrum:
def __init__(self, pname):
self.planet = Planet(pname)
def plot_spectrum(self):
"""
Function ... |
# -*- coding: utf-8 -*-
"""
test_util_inspect
~~~~~~~~~~~~~~~
Tests util.inspect functions.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from unittest import TestCase
import sys
from six import PY3
import functools
from textwrap impo... |
"Core exceptions raised by the Redis client"
class RedisError(Exception):
pass
class AuthenticationError(RedisError):
pass
class ConnectionError(RedisError):
pass
class ResponseError(RedisError):
pass
class InvalidResponse(RedisError):
pass
class DataError(RedisError):
pass
class P... |
import pytest
import serial as pyserial
@pytest.fixture
def serial():
"""The serial interface to Zissou."""
# N.B. Everything after the yield is teardown
with pyserial.Serial("/dev/zissouserial") as s:
yield s
def test_loopback(serial):
"""Current behaviour - will change."""
test_str =... |
# python3 -m manim --sound --leave_progress_bars -pl ./Ag/MyCode/musicTian.py MusicMai
from manimlib.imports import *
from Ag.MyCode.debugTexPoints import debugPoints
from Ag.MyCode.debugTexPoints import debugTeX
import fractions
import colorsys
class ImageShift(Scene):
def construct(self):
us_image = Imag... |
from collections import namedtuple
from . import devtools_protocol, remote_debug_javascript
from pagewalker.analyzer import initial_actions
from .browser import browser_factory
from pagewalker.utilities import error_utils
from pagewalker.config import config
class RemoteDebug(object):
def __init__(self):
... |
#!/usr/bin/env python
# coding=utf-8
from socket import socket, AF_INET, SOCK_DGRAM
from fstlib import easyip
from carrot.messaging import Publisher
from carrot.connection import BrokerConnection
conn=BrokerConnection(hostname='localhost', port=5672,
userid='test', password='test',
virtual_ho... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright 2011 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... |
# functions are defined in python using the def keyword
def pauls_function():
print("Hello! This is Paul's function!")
def whose_function(name):
print(f"Hi, {name}! Nice function!")
def greeting(yourname, myname):
print(f"Hi {yourname}! My name is {myname}")
def interaction(yourname, myname, ... |
from math import log
from collections import deque
from sys import stdin
readline = stdin.readline
N = int(readline())
root = -1
children = [[] for _ in range(N + 1)]
parent = [[-1] * (N + 1) for _ in range(18)]
for i in range(1, N + 1):
p = int(readline())
parent[0][i] = p
if p == -1:
root = i
... |
# -*- coding: utf-8 -*-
from django.db import models
from .base import BaseManager
from .misc import Media
class CustomerManager(BaseManager):
def get_all_customer(self, order='title', count=10):
"""
获取所有客户信息
:return:
"""
return self.query().all().order_by(order)[0:count]
... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~... |
values = list(range(10))
evens = values[::2]
|
from ckanext.os import model.spatial_data as spatial_model
|
import sqlite3
from .db import DB
class TestingTable(DB):
def __init__(self):
self.table_name = 'WB_testing'
self.table_desc = 'West Bengal testing snapshot'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
'date': 'DATE NOT NULL PRIMARY KEY',
... |
import numpy as np
# -------------------------------------------------------------
class MeshData:
"""
Convenience class for reading Wavefront .obj files.
"""
def __init__(self, obj):
vertices = []
uv = []
faces = []
fuv = []
with open(obj, "r") as f:
... |
import SBCcode.MonteCarlo.PICOcalGlobalLikelihood_v2_jz as pcgl
import numpy as np
from iminuit import Minuit, describe, Struct
from iminuit.util import make_func_code
# import sys
import ipdb
# Minuit target functions can only take scalar arguments, so fake the function signature
class Chi2Functor:
def __init__(... |
from tox_ansible.utils import use_docker
def test_docker_present(mocker):
use_docker.cache_clear()
rc = mocker.Mock()
rc.returncode = 0
mocker.patch("tox_ansible.utils.subprocess.run", return_value=rc)
assert use_docker()
def test_docker_absent(mocker):
use_docker.cache_clear()
mocker.pa... |
import collections
import json
import re
import typing
from pathlib import Path
from typing import Optional
known_types_to_construct = {
"bool": "construct.Flag",
"float": "common_types.Float",
"float32": "common_types.Float",
"int": "common_types.Int",
"unsigned": "common_types.UInt",
"unsigne... |
from .user import User
from .posts import Post
from app.extensions import db
# 创建一个收藏中间表
collections = db.Table('collections',db.Column('user_id',db.Integer,db.ForeignKey('users.id')),
db.Column('posts_id',db.Integer,db.ForeignKey('post.id')))
|
# Python Standard Modules
import os
import sys
import argparse
import requests
try:
# Import 3rd-party Modules/Libraries
from github import Github
import github
import pygit2
except ModuleNotFoundError:
print("Required Modules Not Installed...")
print("(Run): pip install -r requirements.txt")
... |
from django.forms import ModelForm, CharField, CheckboxInput
from .models import Declaracaodesaude, Profile
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
class Declaracaode... |
import csv
import json
import pandas as pd
import numpy as np
import pickle
import re
from time import sleep # So we don't request too much from the server
from collections import Counter # Keep track of counts
from selenium import webdriver
from selenium.webdriver.common import action_chains, keys
from selenium.comm... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from todo_app import models
admin.site.register(models.User, UserAdmin)
admin.site.register(models.Todo)
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
# CubETL
# Copyright (c) 2013-2019 Jose Juan Montes
# 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... |
from rest_framework.permissions import BasePermission
class IsOwner(BasePermission):
def has_permission(self, request, view):
try:
allowed = request.user.id == view.get(request).data['id']
except Exception as e:
allowed = e and False
return bool(request.user.is_auth... |
# Python Standard Library Imports
import hashlib
# Third Party (PyPI) Imports
import qrcode
from PIL import Image
# Django Imports
from django.http import HttpResponse
from django.http import HttpResponseForbidden
# HTK Imports
from htk.utils import htk_setting
def qrcode_image_response(data=''):
"""Returns a ... |
''' unit tests ONTAP Ansible module: na_ontap_quotas '''
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import pytest
from ansible_collections.netapp.ontap.tests.unit.compat import unittest
from ansible_collections.netapp.ontap.tests.unit.compat.mock import patch
f... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def eval(objs, **input_dict):
memo = {}
return [obj.eval(memo, input_dict) for obj in objs]
|
'''
Created on 11 Dec 2017
@author: dstaines
'''
import os
from ensembl_prodinf.config import load_config_yaml
config_file_path = os.environ.get('HANDOVER_CORE_CONFIG_PATH')
file_config = load_config_yaml(config_file_path)
dc_uri = os.environ.get("DC_URI",
file_config.get('dc_uri', "http://... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from telegram.ext import Updater, MessageHandler, Filters
import time
import os
import traceback as tb
from telegram_util import getDisplayUser, log_on_fail, getTmpFile, autoDestroy, matchKey
import yaml
import pytesseract
try:
from PIL import Image
except ImportError... |
"""Lambda function handler."""
# must be the first import in files with lambda function handlers
import lambdainit # noqa: F401
import lambdalogging
import config
import cloudformation
import repo
from distutils.version import LooseVersion
LOG = lambdalogging.getLogger(__name__)
REPO_STACK_PREFIX = 'serverlessrepo'... |
'''
Created by auto_sdk on 2019.07.01
'''
from dingtalk.api.base import RestApi
class OapiEduTeacherListRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.class_id = None
def getHttpMethod(self):
return 'POST'
def getapiname(self):
return 'dingtalk.oapi.edu.teacher.list'
|
import tensorflow as tf
def einsum_bi_ijk_to_bjk(a,b):
batch_size = tf.shape(a)[0]
shp_a = a.get_shape()
shp_b = b.get_shape()
b_ = tf.reshape(b,(int(shp_b[0]), int(shp_b[1]) * int(shp_b[2])))
ab_ = tf.matmul(a,b_)
ab = tf.reshape(ab_,(batch_size,int(shp_b[1]),int(shp_b[2])))
return ab
d... |
import imp
import os
import re
from setuptools.sandbox import run_setup
from . import *
_DEV_VERSION_RE = re.compile(r'\d+\.\d+(?:\.\d+)?\.dev(\d+)')
def test_update_git_devstr(package_template, capsys):
"""Tests that the commit number in the package's version string updates
after git commits even without... |
import pygame
from classes import Player
class Man():
def __init__(self,x,y,CameraX,CameraY):
self.x = x
self.y = y
self.CameraX = CameraX
self.CameraY = CameraY
self.vel = 5
self.idle = False
#self.standing = pygame.image.load('018.png')
self.standin... |
"""Implementations of installation abstract base class searches."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and inc... |
# coding: utf-8
n,x=map(int,input().split())
m=[int(input()) for i in range(n)]
print(n+(x-sum(m))//min(m))
|
versions = [
'0.0.0-foo',
'0.0.0',
'0.0.0',
'0.0.1',
'0.9.0',
'0.9.9',
'0.10.0',
'0.10.0',
'0.10.0',
'0.99.0',
'0.99.0',
'1.0.0',
'1.0.0',
'1.2.3-4',
'1.2.3-4',
'1.2.3-5',
'1.2.3-5',
'1.2.3-4-foo',
'1.2.3-5-Foo',
'1.2.3-5-foo',
'1.2.3... |
import arrow
def last_month(date):
"""get the name of last month"""
date = str(date)
date = date[:4] + '-' + date[4:]
date0 = arrow.get(date)
lastmon = date0.shift(months=-1)
lastmon = lastmon.format('YYYYMM')
return lastmon
def base_a(data, start_date, end_date):
"""get the base of ... |
#!/usr/bin/env python
import rospy
import os
import subprocess
import time
# Psutil 5.8.0
import psutil
from std_msgs.msg import UInt64, UInt64MultiArray, String
def monitor():
# Init node and rate
rospy.init_node('robot_monitor', anonymous=True)
rate = rospy.Rate(1)
# Publishers
pub_network = ros... |
"""
@author: Dipson Shahi
"""
from CLASSES.ParserXML import ParserXML
from CLASSES.LogTraceability import LogTraceability
from CLASSES.Connection import Connection
from CLASSES.FileManagement import FileManagement
from datetime import datetime
import json
"""
- Start the process of parsing the list of XML... |
# Copyright 2020-present Kensho Technologies, LLC.
import io
from nltk.stem.snowball import SnowballStemmer
import scipy.sparse
import joblib
import pandas as pd
import numpy as np
global_objects = {
"stemmer": SnowballStemmer("english"),
}
# Make loading safe vs. malicious input
PICKLE_KWARGS = dict(allow_pick... |
from django.contrib import admin
from django.contrib.sites.models import Site
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount, SocialApp, SocialToken
admin.site.unregister(Site)
admin.site.unregister(EmailAddress)
admin.site.unregister(SocialApp)
admin.site.unreg... |
# -*- coding: utf-8 -*-
# (C) Copyright IBM Corp. 2020.
#
# 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 l... |
"""
While loops are called condition controlled iteration.
The condition is tested before the loop executes.
This means that the loop may never execute if the condition is false at the start.
Each time the loop has executed the condition is re checked before the next iteration.
It is important that you use a variable ... |
# BOJ 13460 (구슬 탈출2)
import sys
from collections import deque
sys.stdin = open('../input.txt', 'r')
si = sys.stdin.readline
dy = [-1, 1, 0, 0]
dx = [0, 0, -1, 1]
def move(y, x, d):
cnt = 0
while graph[y + dy[d]][x + dx[d]] != "#" and graph[y][x] != "O":
y += dy[d]
x += dx[d]
cnt += 1
... |
'''
Author: Lenny Khazan
Created:
Description:
A GameStateChange represents a state transition for the GameState. This class
defines all the possible legal transitions between two GameStates that comply with
the rules of Monopoly. They are implemented as static methods that return
an instance of GameStateChange.... |
# -*- coding: utf-8 -*-
'''
Created on 1983. 08. 09.
@author: Hye-Churn Jang, CMBU Specialist in Korea, VMware [jangh@vmware.com]
'''
import sys
import importlib
import manifest
sys.path.insert(0, '../../common')
_module = importlib.import_module(manifest.sdk)
for exportObject in _module.exportObjects: __bu... |
from rental_data_handler import RentalDataHandler
from form_data_handler import FormDataHandler
rentalHandlerObj = RentalDataHandler()
formHandlerObj = FormDataHandler()
property_prices, property_addresses, property_links = rentalHandlerObj.get_rental_properties()
for price, address, link in zip(property_prices, prop... |
import sys
from os.path import basename, splitext
try:
from importlib.util import spec_from_file_location, module_from_spec # pylint:disable=import-error,no-name-in-module
def _import(name, path):
spec = spec_from_file_location(name, path)
module = module_from_spec(spec)
spec.loader.ex... |
import logging
from urllib.parse import unquote
from flask import (
render_template
)
from puppetboard.core import get_app, get_puppetdb, environments
from puppetboard.utils import (get_or_abort, get_db_version, check_env, metric_params)
app = get_app()
puppetdb = get_puppetdb()
logging.basicConfig(level=app.co... |
from lgsvl.agent import VehicleControl
def _print_sensor_state(sensors):
for sensor in sensors:
print("{} ({}): {}".format(sensor.name, type(sensor), "Enabled" if sensor.enabled else "Disabled"))
def _generate_control_command() -> VehicleControl:
control = VehicleControl()
control.throttle = 0.1... |
import time
import unittest
from libraries.graphs_util import _preprocess_chartex_data, print_candlestick, print_simple_chart
from pprint import pprint
from libraries.models.token import TokenMetadata
from libraries.models.supported_chains import SupportedChains
class GraphTest(unittest.TestCase):
example_chart... |
from dlhalos_code import CNN
from dlhalos_code import custom_regularizers as reg
import dlhalos_code.data_processing as tn
from pickle import load, dump
import numpy as np
import tensorflow as tf
import random as python_random
import sys
import os
if __name__ == "__main__":
########### CREATE GENERATORS FOR TRAINING... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
"""
MIT License
Copyright (c) 2022 Bruno Hautzenberger
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, pub... |
import re
from cs50 import get_string
def coleman_lieu_index(string):
letters = len(re.sub(r"[\.\!\?\ \'\,]+", "", string))
words = len(string.split())
sentences = len(re.split(r'[.!?]+', string))-1
L = letters * 100 / words
S = sentences * 100 / words
idx = round(0.0588 * L - 0.296 * S - 1... |
def run():
my_diccionario = {
'llave1': 1,
'llave2': 2,
'llave3': 3
}
# print(my_diccionario['llave3'])
# print(my_diccionario['llave1'])
# print(my_diccionario['llave2'])
poblacion_pais = {
'Argentina': 4567890,
'Brasil': 210456738,
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: alameda_api/v1alpha1/operator/server.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.... |
"""
Book: Building RESTful Python Web Services
Chapter 1: Developing RESTful APIs with Django
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from datetime import datetime
from django.utils import timezone
from django.utils.six import BytesIO
from rest_... |
import os
import PySide2
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
import sys
import DemoAppQrc # this module is generated from my qrc
from MyOperationPanel import MyOperationPanel
from PySide2.QtWidg... |
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import pandas as pd
import os
import logging
logging.basicConfig()
logger = logging.getLogger('Plot1stDimTrajectory')
logger.setLevel('INFO')
class Plot1stDimTrajectory:
def __init__(self, data, benchmark, path, show=False):
se... |
class Kid:
def __init__(self, name = "NO NAME", age = -1):
self.name = name
self.age = age
class Family:
def __init__(self):
self.parents = []
self.kids = []
|
from rest_framework import routers
from api.views import DriversViewSet, StationViewSet, TripViewSet, CountryViewSet, ProvinceViewSet, DistrictViewSet, \
RegisterAPI
router = routers.DefaultRouter()
router.register("drivers", DriversViewSet, basename="drivers"),
router.register("stations", StationViewSet, basename... |
from .shublang import *
from .parser import StatementParser
|
#
# PySNMP MIB module ASCEND-MIBOC3ATMNET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBOC3ATMNET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:27:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
'''
process_all.py
Script to call many image processing functions on a set of images.
Author: S.T. Castle
Created: 20150226
'''
import fileinput
import numpy as np
import cv2
# Custom modules.
from smooth-write-image import smooth
def main():
count = 1 # Count the number of images.
# Process files.
fo... |
# Copyright 2019 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 by applicable law or a... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("DQMOnlineSimData")
#process.MessageLogger = cms.Service(
# "MessageLogger",
# debug_txt = cms.untracked.PSet( threshold = cms.untracked.string('DEBUG') ),
# destinations = cms.untracked.vstring('debug_txt'),
# #debugModules = cms.untracked.vs... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Sep-06-20 11:33
# @Author : Kelly Hwong (dianhuangkan@gmail.com)
# @Link : http://example.org
import os
def main():
class_indices = {
"airplane": 0,
"automobile": 1,
"bird": 2,
"cat": 3,
"deer": 4,
"do... |
from myscripts.projects.thesis import plotdir
plotdir = plotdir + 'ch6_tropopause/'
|
import logging; _L = logging.getLogger('openaddr.ci.webapi')
import os, json, hmac, hashlib
from urllib.parse import urljoin, urlencode, urlunparse
from datetime import datetime, timedelta
from dateutil.tz import tzutc
from base64 import b64encode
from functools import wraps
from random import randint
from flask impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.