content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# 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... | python |
#!/usr/bin/env python
#############################################################
# ubi_reader/ubi_io
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# 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 Founda... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from codegen.spec import *
from codegen.mir_emitter import *
from codegen.isel import *
from codegen.x64_def import *
from codegen.matcher import *
class X64OperandFlag(IntFlag):
NO_FLAG = auto()
# GOT_ABSOLUTE_ADDRESS - On a symbol operand = auto() this represe... | python |
import pathlib
from setuptools import setup, find_packages
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name='pylateral',
version='1.0.0',
description='Intuitive multi-threaded task processing in python.',
long_description=README,
long_description_content_t... | python |
import numpy as np
class BaseAgent:
def __init__(self, name, environment=None):
self.name = name
self.environment = environment
def choose_action(self):
action = np.random.choice(self.environment.valid_actions)
pawn_actions = [a for a in self.environment.valid_actions if a < 1... | python |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Updates ExtensionPermission2 enum in histograms.xml file with values read
from permission_message.h.
If the file was pretty-printed, the updated version ... | python |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict
import pkg_resources
import pytest
import torch
from flsim.common.pytest_helper i... | python |
import click
import json
from pathlib import Path
from PIL import Image
import pycountry
import re
import shlex
import subprocess
import time
import traceback
import youtube_dl
SUB_LANGUAGES = ['en', 'en-US', 'en-UK', 'en-us', 'en-uk', 'de', 'de-DE', 'de-de', 'un']
ytops = {
'outtmpl': '{}.%(ext)s',
'hls_pref... | python |
from dataclasses import dataclass
@dataclass
class SpotifyConfig:
client_id: str
client_secret: str
refresh_token: str
| python |
"""
Application load balancer stack for running ConsoleMe on ECS
"""
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_elasticloadbalancingv2 as lb
from aws_cdk import core as cdk
class ALBStack(cdk.NestedStack):
"""
Application load balancer stack for running ConsoleMe on ECS
"""
def __ini... | python |
# --------------------------------------------------
# Gene class
# Authors: Thomas Schwarzl, schwarzl@embl.de
# --------------------------------------------------
import gzip
import logging
from collections import OrderedDict, defaultdict
from HTSeq import GenomicArray, GenomicArrayOfSets, GenomicPosition, GenomicF... | python |
from __future__ import print_function
import os
import subprocess
import shlex
from getpass import getuser
from distutils.command.build import build # type: ignore
from setuptools import (
find_packages,
setup,
Command
)
import numpy as np
CUSTOM_COMMANDS = [
shlex.split(command_line) for command... | python |
# Copyright 2004-present, Facebook. All Rights Reserved.
from django.contrib.auth.decorators import login_required
from django.urls import path
from . import views
urlpatterns = [
# products
path(
"store/<int:storeId>/products/create",
login_required(views.createProduct),
name="createP... | python |
from detective import functions
import math
MOCK_ATTRIBUTE = {
"battery_level": 61,
"unit_of_measurement": "°C",
"friendly_name": "Living room sensor temperature",
"device_class": "temperature",
}
def test_device_class():
"""Test get_device_class"""
assert functions.get_device_class(MOCK_ATTR... | python |
from argparse import ArgumentParser
import examples.example02.tasks
from cline.cli import ArgumentParserCli, RegisteredTasks
class ExampleCli(ArgumentParserCli):
def make_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument("a", help="first number", nargs="?")
par... | python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from pandas.compat import StringIO
import sys
import re
import os
import ntpath
def file_to_df(filename):
with open(filename, 'r') as file:
contents = file.read()
# Read run configurations
sta... | python |
import os
import socket
import struct
import sys
import select
os.system("")
UDP_PORT = 13117
MESSAGE_LEN = 1024
GAME_TIME = 10
sockUDP = None
sockTCP = None
# Colors for prints
class Colors:
GREEN = '\033[32m'
BLUE = '\033[34m'
PINK = '\033[35m'
def printMessageOrRead():
# wait for read or write ... | python |
from tests.testcases import TestCaseUsingRealAPI
from vortexasdk import Products, Geographies, Corporations, Vessels
endpoints_and_searchterms = [
(Products(), "Gasoil"),
(Geographies(), "China"),
(Corporations(), "Oil"),
(Vessels(), "Ocean"),
]
class TestSearchReal(TestCaseUsingRealAPI):
def tes... | python |
from app import app
from flask import request, session
from helpers.database import *
from helpers.hashpass import *
from helpers.mailer import *
from bson import json_util, ObjectId
import json
def checkloginusername():
username = request.form["username"]
check = db.users.find_one({"username": username})
... | python |
"""Hyperparameters from paper """
import numpy as np
import torch.optim as optim
from .model import DQN, DuelingDQN
class AtariHyperparams:
ALGO = "DQN"
SEED = 2
LOG_DISPLAY_FREQ = 10
# Image sizing
WIDTH = 84
HEIGHT = 84
# Number of most recent frames given as input to Q-network
A... | python |
"""
Queue backend abstraction manager.
"""
import json
import logging
import sched
import socket
import time
import uuid
from typing import Any, Callable, Dict, List, Optional, Union
from pydantic import BaseModel, validator
import qcengine as qcng
from qcfractal.extras import get_information
from ..interface.data ... | python |
import logging
from importlib import import_module
from .groups import Groups
log = logging.getLogger(__name__)
class ConfigHelper:
@classmethod
def cog_name(cls, key):
return ''.join(map(str.capitalize, key.split('_')))
CONFIG_GROUP_MAPPINGS = [
('sudo', 'user', 'sudo'),
('sysb... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.apps import apps, AppConfig
class PanopticonConfig(AppConfig):
name = "panopticon.django"
label = "panopticon"
verbose_name = "Panopticon"
def ready(self):
package_names = (a.module.__name__ for a in ... | python |
import numpy as np
from numba import jit
from scipy.sparse.construct import random
from ..tools import compute_dist
from ._utils import _CheckInputs
from .base import IndependenceTest, IndependenceTestOutput
from scipy.stats import rankdata
class HHG(IndependenceTest):
r"""
Heller Heller Gorfine (HHG) test s... | python |
from django.contrib import admin
from spaweb.models import Customer, ProductCategory, City
from spaweb.models import Product, Order, OrderItem
from spaweb.models import BusinessDirection, Topic
admin.site.register(ProductCategory)
admin.site.register(City)
admin.site.register(BusinessDirection)
admin.site.register(To... | python |
# -*- coding: utf-8 -*-
"""Pype custom errors."""
class PypeError(Exception):
"""Custom error."""
pass
| python |
"""
ipython -i --pdb scripts/train_model.py -- --model cropped_jan02 --data 128_20151029 --use_cropped --as_grey --overwrite --no_test
"""
import numpy as np
from lasagne.layers import dnn
import lasagne as nn
import theano.tensor as T
import theano
from utils.nolearn_net import NeuralNet
from nolearn.lasagne.handle... | python |
from __future__ import annotations
import abc
import datetime
import decimal
import typing as t
import zoneinfo
# region: Bases
class SpecialValue(abc.ABC):
"""Represents a special value specific to an SQL Type."""
def __init__(self, python_value: t.Any, sql_value: str):
self._py_value = python_val... | python |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from obscmd import compat
def init():
global _global_dict
_global_dict = {}
def use_lock(key):
lock_key = key + '_lock'
if lock_key not in _global_dict:
_global_dict[lock_key] = compat.Lock()
return lock_key
def set_value(key, value):
_... | python |
from hill import Hill
from numpy.linalg.linalg import norm
from jumper import Jumper
from jump_result import JumpResult
from physics_simulator import PhysicsSimulator
import numpy as np
import random
angles = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44]
kw_pts = [... | python |
"""
Implements a simple HTTP/1.0 Server
"""
import socket
# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 7777
# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST... | python |
# coding=utf-8
#-----------------------------------------------------------
# IMPORTS
#-----------------------------------------------------------
import enigmus
import messages
import random
from entities import Entity, Player, Room
#-----------------------------------------------------------
# CLASSES
#----------... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-23 21:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('problems', '0040_auto_20161123_2106'),
]
operations... | python |
# Ultroid - UserBot
# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
#
# Ported by @AyiinXd
# FROM Ayiin-Userbot <https://github.com/Ayiin... | python |
# encoding:utf-8
from flask import Flask,request
import json
import time
import sys
import sqlite3
import os
app=Flask(__name__)
####回复文本格式##########
re={}
result={}
result["type"]="text"
result["content"]=""
re["error_code"]=0
re["error_msg"]=""
re["result"]=result
dic={'温度':'temperature','湿度':'humid... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#1 - Normalize vector:
def normalize_v(V):
m = 0
for x in V: m += x**2 #Sum of the elements powered to the 2
m = sqrt(m) #Get vector's norm
return [x/m for x in V] #Divide each element of vector by its norm
#2 - Find D, euclidian distance
def euclid_dis(V... | python |
from spaceone.inventory.manager.pricing_manager import PricingManager
| python |
#!/usr/bin/env python
import sys
import dnfile
from hashlib import sha256
filename = sys.argv[1]
sha256hash = ''
with open(filename, 'rb') as fh_in:
sha256hash = sha256(fh_in.read()).hexdigest()
pe = dnfile.dnPE(filename)
#tbl = pe.net.mdtables.MemberRef
tbl = pe.net.mdtables.TypeRef
tbl_num_rows =\
pe.ge... | python |
import pandas as pd
fname = "LBW_dataset.csv"
df = pd.read_csv(fname)
#cleaning data
df = df.drop(columns=['Education'])
df = df.interpolate()
df['Community'] = df['Community'].round()
df['Delivery phase'] = df['Delivery phase'].round()
df['IFA'] = df['IFA'].round()
#df = df.round()
mean_weight = df['... | python |
"""
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
distri... | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
from astropy.io import fits
from astropy.table import Table
from gammapy.data import GTI
from gammapy.maps import MapCoord, Map
from gammapy.estimators.core import FluxEstimate
from gammapy.estimators.flux_point import Flu... | python |
from flask import Flask
from driver import get_final_kmeans
app = Flask(__name__)
@app.route("/")
def hello():
return get_final_kmeans() | python |
from typing import Any, Dict, List, Optional, Union
from interactions.ext.paginator import Paginator
from thefuzz.fuzz import ratio
from interactions import Client, CommandContext, DictSerializerMixin, Embed, Extension
from .settings import AdvancedSettings, PaginatorSettings, TemplateEmbed, typer_dict
class RawHe... | python |
import numpy as np
from sklearn.cluster import MeanShift# as ms
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
centers = [[1,1], [5,5]]
X,y = make_blobs(n_samples = 10000, centers = centers, cluster_std = 1)
plt.scatter(X[:,0],X[:,1])
plt.show()
ms = MeanShi... | python |
# Copyright 2020 Arthur Coqué, Valentine Aubard, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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 ... | python |
from tkinter import *
root = Tk()
root.geometry('225x230')
root.resizable(False, False)
root.title('Learning English')
def showMenu():
menu1.pack()
menu2.pack()
def hideMenu():
menu1.pack_forget()
menu2.pack_forget()
menu1 = Button(text = 'Can you translate?\nENG --> RUS', width = 300, height = 7)
m... | python |
import numpy as np
from time import time
import xorshift
rng = xorshift.Xoroshiro()
rng2 = xorshift.Xorshift128plus()
def output(name, start, end):
elapsed = (end - start) * 1000
per_iter = elapsed / iters
per_rv = per_iter / count * 1e6
print '%s took %.2f ms/iter, %.2f ns per float' % (name, per_ite... | python |
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QHBoxLayout, QLabel, QSlider
from traitlets import HasTraits, Unicode, Int, observe
from regexport.views.utils import HasWidget
class LabelledSliderModel(HasTraits):
label = Unicode()
min = Int(default_value=0)
max = Int()
value = I... | python |
'''
Configure web app settings. Updating or removing application settings will cause an app recycle.
'''
from .... pyaz_utils import _call_az
def list(name, resource_group, slot=None):
'''
Get the details of a web app's settings.
Required Parameters:
- name -- name of the web app. If left unspecified,... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bandit Algorithms
This script follows Chapter 2 of Sutton and Barto (2nd) and simply reproduces
figures 2.2 to 2.5.
Author: Gertjan van den Burg
License: MIT
Copyright: (c) 2020, The Alan Turing Institute
"""
import abc
import math
import matplotlib.pyplot as plt
... | python |
import unittest
import pandas as pd
from tests.test_utils import TestUtils
from enda.ml_backends.sklearn_estimator import EndaSklearnEstimator
try:
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.ensemble import AdaBoostRegressor, RandomForestRegressor
from sklearn.svm import S... | python |
""" Generate new files from templates. """
import argparse
import sys
from typing import Optional
from contextlib import contextmanager
import os
import shlex
from itertools import chain
from cjrh_template import Template
import biodome
__version__ = '2017.10.3'
@contextmanager
def file_or_stdout(args, filename: Op... | python |
import os
import paramiko
def get_private_key():
# or choose the location and the private key file on your client
private_key_file = os.path.expanduser("/home/ubuntu/.ssh/id_rsa")
return paramiko.RSAKey.from_private_key_file(private_key_file, password='')
def get_ssh(myusername, myhostname, myport):
... | python |
import json
from unittest.mock import patch
from ddt import ddt
from django.test import tag
from django.urls import reverse
from requests.exceptions import HTTPError
from rest_framework import status
from .test_setup import TestSetUp
@tag('unit')
@ddt
class ViewTests(TestSetUp):
def test_get_catalogs(self):
... | python |
import sys
stack = []
def recursion(stack, last):
if stack:
now = stack.pop()
else:
return -1
s = 0
while now != -last:
foo = recursion(stack, now)
if foo == -1:
return -1
s += foo
if stack:
now = stack.pop()
else:
... | python |
from chaco.api import ArrayPlotData
from enable.component_editor import ComponentEditor
from traits.api import (
List, Instance, Either, Str, on_trait_change, Tuple, Any,
Property)
from traitsui.api import (
TabularEditor, View, UItem, VGroup, EnumEditor, HGroup, Item)
from traitsui.tabular_adapter import T... | python |
from .device import (ORTDeviceInfo, get_available_devices_info,
get_cpu_device_info)
from .InferenceSession import InferenceSession_with_device
| python |
#!/usr/bin/env python3
import sys
import numpy as np
with open(sys.argv[1]) as infile:
rows = [a.strip() for a in infile]
def do_round(cube):
x, y, z = cube.shape
new_cube = np.zeros(cube.shape, dtype=bool)
for i in range(x):
for j in range(y):
for k in range(z):
... | python |
"""bsw URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... | python |
from pandas import DataFrame
from typing import List, Tuple, Dict
from models.team_stats import TeamSkeletonStats
def get_opponents_in_given_fixture_list(team_id: int, fixtures: DataFrame) -> List[int]:
home_opponents = fixtures.loc[fixtures['team_a'] == team_id, 'team_h']
away_opps = fixtures.loc[fixtures['t... | python |
#!/usr/bin/env python3
# coding:utf-8
from pickle import load
with open("banner.p", "rb") as f:
print(load(f))
| python |
#!/usr/bin/env python
import re
from setuptools import setup
def get_version(filename):
f = open(filename).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", f).group(1)
version = get_version('flake8_assertive.py')
description = open('README.rst').read() + "\n\n" + open('CHANGELOG.rst').read()
g... | python |
import modules.weapon as weapon
basic_sword = weapon.Weapon("Sword", "A sword you found somewhere.", 10, 0.5, 10, "slash", 1 , "You took the sword.", "You dropped the sword.")
big_axe = weapon.Weapon("Axe", "A big axe you found somewhere.", 20, 0.5, 10, "slash", 1 , "You took the axe.", "You dropped the axe.") | python |
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import cache_page
from .forms import CommentForm, PostForm
from .models import Follow, Group, Post, User
from .settin... | python |
from numpy import random
from impl.distribution import distribution
class triangular(distribution):
def __init__(self, mini, mode, maxi):
self.mini = float(mini)
self.mode = float(mode)
self.maxi = float(maxi)
def generate(self):
return int(random.triangular(self.mini, self.m... | python |
from .multiagent_particle_env import RLlibMultiAgentParticleEnv as MultiAgentParticleEnv
__all__ = [
"MultiAgentParticleEnv"
]
| python |
from flask import abort, Flask, jsonify, request
import os
import asyncio
import pyjuicenet
import aiohttp
from prettytable import PrettyTable
from pytz import timezone
import datetime
import requests
import database_helper
import html_renderer
app = Flask(__name__)
@app.route("/")
def show_all_chargers():
datab... | python |
import pytest
import networkx as nx
from ..pyfastg import add_node_to_digraph
def test_basic():
def check_asdf(g):
assert "asdf" in g.nodes
assert g.nodes["asdf"]["cov"] == 5.2
assert g.nodes["asdf"]["gc"] == 4 / 6.0
assert g.nodes["asdf"]["length"] == 6
def check_ghjasdf(g):
... | python |
from rest_framework import serializers
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import PatientConsultation, PatientRegistration, Facility
from care.facility.models.prescription_supplier import Pre... | python |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure_devtools.perfstress_tests import PerfStressTest
from azure.identity import ClientSecretCredential, TokenCachePersistenceOptions
from azure.identity.aio impor... | python |
import re, hashlib, random, json, csv, sys
from datetime import datetime, timedelta, tzinfo
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import caches
from django.core.exceptions i... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-21 08:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0005_photolikes'),
]
operations = [
migrations.RemoveField(
... | python |
class Record:
vdict = dict()
count = 0
record = dict()
reclen = 0
fd = None
# The constructor opens the Record Defenition File and sets
# the record defenition
def __init__(self, recName, fileName, mode="r", encoding="Latin-1"):
defstr = self.recordDef(recName)
self.vdic... | python |
import os
import posixpath
import sys
import docker
import json
from unittest import TestCase, skipUnless
from unittest.mock import Mock, call, patch, ANY
from pathlib import Path, WindowsPath
from parameterized import parameterized
from samcli.lib.build.build_graph import FunctionBuildDefinition, LayerBuildDefinit... | python |
import requests
import json
coin_market_cap = requests.get(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false",
headers = {"accept": "application/json"})
print("Enter the number of top cryptocurrencies by market capitalization: ")... | python |
"""
"""
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class BaseAgent:
"""
"""
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def agent_init(self, agent_info= {}):
""" """
@abstractmethod
def agent_start(self, obser... | python |
import torch
import gpytorch
from torch.nn.functional import softplus
from gpytorch.priors import NormalPrior, MultivariateNormalPrior
class LogRBFMean(gpytorch.means.Mean):
"""
Log of an RBF Kernel's spectral density
"""
def __init__(self, hypers = None):
super(LogRBFMean, self).__init__()
if hypers is not No... | python |
# python
import lx, lxifc, lxu, modo
import tagger
from os.path import basename, splitext
CMD_NAME = tagger.CMD_SET_PTAG
def material_tags_list():
res = set(tagger.scene.all_tags_by_type(lx.symbol.i_POLYTAG_MATERIAL))
for type, tag in tagger.items.get_all_masked_tags():
if type == "material":
... | python |
import turtle
'''this makes a circle by building many squares'''
def draw_square(tom):
for _ in range(4):
tom.forward(100)
tom.right(90)
def draw_flower():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.speed(0)
brad.color("blue")
for i in rang... | python |
class Solution:
def maxProfit(self, prices):
index = 0
flag = False
ans = 0
i = 1
n = len(prices)
while i < n:
if prices[i] > prices[i - 1]:
flag = True
else:
if flag:
ans += prices[i - 1] - p... | python |
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
from lxml import etree
import requests
import re
def get_links(who_sells=0):
# urls = []
list_view = 'http://bj.58.com/pbdn/{}/'.format(str(who_sells))
print(list_view)
wb_data = requests.get(list_view, headers=h... | python |
# -*- coding: utf-8 -*-
import os
import json
from logging import getLogger
from six import string_types, text_type
from collections import OrderedDict
from ckan import logic
from ckan import model
import ckan.plugins as p
from ckan.lib.plugins import DefaultDatasetForm
try:
from ckan.lib.plugins import Default... | python |
# coding=utf-8
# IP地址取自国内髙匿代理IP网站:http://www.xicidaili.com/nn/
# 仅仅爬取首页IP地址就足够一般使用
import telnetlib
from bs4 import BeautifulSoup
import requests
import random
URL = 'http://www.xicidaili.com/nn/'
HEADERS = {
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.... | python |
import struct
__all__ = ['AbstractEnumValue', 'IntValue', 'KnobModeEnum', 'PadModeEnum', 'SusModeEnum']
class AbstractEnumValue (object):
_VALUES = {}
def __init__(self, val):
if isinstance(val, int):
try:
self._value = next(k for k, v in self._VALUES.items() if v == val)... | python |
s = input().strip()
n = int(input().strip())
a_count = s.count('a')
whole_str_reps = n // len(s)
partial_str_length = n % len(s)
partial_str = s[:partial_str_length]
partial_str_a_count = partial_str.count('a')
print(a_count * whole_str_reps + partial_str_a_count)
| python |
import asyncio
import math
import networkx as nx
from ccxt import async_support as ccxt
import warnings
__all__ = [
'create_multi_exchange_graph',
'create_weighted_multi_exchange_digraph',
'multi_graph_to_log_graph',
]
def create_multi_exchange_graph(exchanges: list, digraph=False):
"""
Returns a ... | python |
"""Methods for creating, manipulating, and storing Teradata row objects."""
import csv
from claims_to_quality.lib.qpp_logging import logging_config
from claims_to_quality.lib.teradata_methods import deidentification
import teradata
logger = logging_config.get_logger(__name__)
def csv_to_query_output(csv_path):
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | python |
# Copyright 2021 AIPlan4EU project
#
# 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 wri... | python |
preco = float(input('Qual o valor do produto ? R$ '))
porcentagem = float(input('Qual a porcentagem ? '))
calculo = preco - (preco * porcentagem / 100)
print(f'O produto que custava R${preco}, na promoção com desconto de {porcentagem}% vai custar {calculo:.2f}') | python |
import json
import logging
from unittest import mock
from django.test import TestCase
from djenga.logging.formatters import JsonFormatter, JsonTaskFormatter
__all__ = [ 'JsonFormatterTest', ]
log = logging.getLogger(__name__)
class JsonFormatterTest(TestCase):
def test_json_formatter(self):
formatter = ... | python |
#!/usr/bin/env python3
'''
booksdatasource.py
Jeff Ondich, 21 September 2021
For use in the "books" assignment at the beginning of Carleton's
CS 257 Software Design class, Fall 2021.
'''
#Revised by Thea Traw
import csv
class Author:
def __init__(self, surname='', given_name='', birth_year=None,... | python |
/home/wai/anaconda3/lib/python3.6/copy.py | python |
import pytest
from ergaster import add
data = (
(1, 2, 3),
(2, 2, 4),
(3, 2, 5),
)
@pytest.mark.parametrize("x, y, res", data)
def test_add(x, y, res):
assert add(x, y) == res
| python |
def grafoSimples(matriz):
result = ""
l = 0
am = 0
for linha in range(len(matriz)):
for coluna in range(len(matriz[linha])):
if(linha == coluna and matriz[linha][coluna] == 2):
result+=("Há laço no vertice %s\n" %(linha+1))
l = 1
if (linha... | python |
# coding=UTF-8
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from product.models import TaxClass
from l10n.models import AdminArea, Country
#from satchmo_store.shop.models import Order
#from satchmo_store.sho... | python |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import colorcet as cc
import datashader as ds
import datashader.utils as utils
import datashader.transfer_functions as tf
sns.set(context="paper", style="white")
data_dir = os.path.abspath("./data")
data_fname = ... | python |
# -*- coding: utf-8 -*-
from .base_settings import *
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
FOP_EXECUTABLE = "C:/U... | python |
import json
from dagster import ModeDefinition, execute_solid, solid
from dagster_slack import slack_resource
from mock import patch
@patch("slack.web.base_client.BaseClient._perform_urllib_http_request")
def test_slack_resource(mock_urllib_http_request):
@solid(required_resource_keys={"slack"})
def slack_so... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.