content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# Test for CVE-2018-xxxxx.
from mosq_test_helper import *
import signal
def write_config(filename, port, per_listener):
with open(filename, 'w') as f:
f.write("per_listener_settings %s\n" % (per_listener))
f.write("port %d\n" % (port))
f.write("password_file %s\n" %... |
import os
import torch
import argparse
import TD3
import OurDDPG
import DDPG
import random
import numpy as np
import torch.nn.functional as F
from sac import SAC
from utils import make_env
from pytorch_sac.agent.sac import SACAgent as PytorchSAC
from pytorch_sac.agent.random_noise_sac import RandomNoiseSACAgent
from py... |
cumprimentos = ['Oi', 'Olá', 'Bom dia']
for cumprimento in cumprimentos:
print(cumprimento)
|
#
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import json
from random import randint
import pytest
from ote_sdk.entities.id import ID
from ote_sdk.entities.label import Color, Domain, LabelEntity
from ote_sdk.entities.label_schema import (
LabelGraph,
LabelGroup,
... |
# get_url_text.py
"""A script to download the html source at a URL as text file
The file will be placed in a folder.
Usage: get_url_text.py url foldername filename
"""
import os, sys, requests, bs4
print(f"{sys.argv=}")
url = sys.argv[1]
foldername = sys.argv[2]
filename = sys.argv[3]
headers = {'User-Agent': '... |
#!/usr/bin/env python
"""
server.py
Copyright 2018. All Rights Reserved.
Created: April 13, 2017
Authors: Toki Migimatsu
"""
from __future__ import print_function, division
import threading
from multiprocessing import Process
from argparse import ArgumentParser
import json
import os
import shutil
import sys
WEB_DIR... |
"""Clean Code in Python - Chapter 3: General Traits of Good Code
"""
import unittest
from unittest.mock import Mock, patch
from exceptions_1 import DataTransport, Event
class FailsAfterNTimes:
def __init__(self, n_times: int, with_exception) -> None:
self._remaining_failures = n_times
self._exc... |
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(len(arr) - i - 1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
arr = [1, 13, 5, 2, 4, -1, 2, 2, 4]
# print(bubbleSort(arr))
def mergeS... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-25 17:50
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import djangosige.apps.login.models
class Migration(migrations.Migration):
initi... |
import matplotlib.pyplot as plt
import cv2
import numpy as np
import csv
import tensorflow
import keras
from keras.models import Sequential
from keras.layers import Flatten, Dense, Conv2D, ELU, Activation
from keras.layers import Lambda, Dropout, Cropping2D, SpatialDropout2D
from keras.optimizers import Adam
from sk... |
from common.stream_consumer.dummy_stream_consumer import DummyStreamConsumer
from common.stream_consumer.factory import InvalidStreamConsumerException
from common.stream_consumer.factory import StreamConsumerFactory
from common.stream_consumer.stream_consumer import StreamConsumer
__all__ = [
'InvalidStreamConsume... |
"""
A simple scrape-and-BSOUP parse on my own website.
Angles: compute, single-core threading.
Works: Python 3.
"""
from timeit import default_timer as timer
from concurrent.futures import ThreadPoolExecutor
"""
Make request to jackhales.com, print out response + page len
and use BeautifulSoup to compute into a clas... |
"""
Compute the differences for each block
using the centroids
"""
# -- python --
import sys
import torch
import torchvision
import numpy as np
from einops import rearrange,repeat
from numba import jit,njit,prange
# -- clgen --
sys.path.append("/home/gauenk/Documents/experiments/cl_gen/lib/")
from pyutils import ge... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-31 05:13
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezon... |
import venv
import logging
import json
from typing import Dict, Any, Optional
from tempfile import TemporaryDirectory
from subprocess import CalledProcessError, run
class TapCreateError(Exception):
...
class TapRuntimeError(Exception):
...
class Tap:
def __init__(
self,
tap: str,
... |
from flask import Flask, request, jsonify
from string import ascii_uppercase
from random import choice
# Mock Data Store
LICENSE_KEY_STORE = {
"PRIVATE_LICENSE_KEY": {
"renewal": True,
"discord": "DISCORD_ID",
"expire": "2022-01-01 00:00 UTC",
"plan": "Lifetime"
},
"PRIVATE... |
import requests
import smtplib
import urllib
import geopy
import json
import numpy
import matplotlib.pyplot as plt
import smopy
import Config
def get_location(geocode):
lonlat=open('/home/popschool/projects/Coordonnée/lonlatonly.txt', 'r')
for line in lonlat:
(lon, lat)=line.split(',')
... |
from discord.ext import commands
import json
import aiohttp
import asyncio
with open('tokens.json') as f:
tokens = json.load(f)
class dbl(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.session = self.bot.session
self.token = tokens["botlists"]["dbl"]
sel... |
# Generated by Django 3.1.2 on 2020-11-20 17:24
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Todo',
fields=[
... |
from typing import List
def parse(instr: str) -> List:
return [x.replace("\n", " ") for x in instr.strip().split("\n\n")]
|
"""Caching utilities for the merge-counts command line tool."""
import glob
import os
import json
import tempfile
from pathlib import Path
from typing import Dict, Optional
from logzero import logger
from . import errors
CACHE_POINTER_LOCATION = Path.home() / ".mergecounts-cache"
class DNAnexusFileCache:
"""A... |
class UnpopulatedPropertyError(Exception):
pass
class UnknownGranteeTypeError(Exception):
pass
|
# Generated by Django 3.2.7 on 2021-09-12 18:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20210912_2131'),
]
operations = [
migrations.RemoveField(
model_name='post',... |
from p2pserver import *
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
try:
from tkinter import messagebox
import tkinter as tk
except ImportError:
import Tkinter as tk
import tkMessageBox as messagebox
s = Server()
global client_socket
global BUFSIZ
global msg_list
failu... |
""""
date: 06-10-2020
author: Poulomi Chatterjee
""""
import pandas as pd
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import seaborn as sns
sns.set(s... |
_base_ = ['../actnn/repvggA0_b256x8_imagenet.py']
actnn = False
|
import numpy as np
import os
from six.moves.urllib import request
import unittest
from chainer import testing
from chainercv.evaluations import eval_detection_coco
try:
import pycocotools # NOQA
_available = True
except ImportError:
_available = False
@unittest.skipUnless(_available, 'pycocotools is n... |
import flask
import base64
from portal.utils import get_vc3_client
from portal import app
from portal.decorators import authenticated
@app.route('/rest/virtual_cluster/<name>', methods=['GET'])
@authenticated
def virtual_cluster(name):
"""
Get information for a specified cluster and return
it in as json... |
# -*- coding: utf-8 -*-
"""
Island with single jungle cell, first herbivores only, later carnivores.
"""
__author__ = 'Hans Ekkehard Plesser, NMBU'
import textwrap
from src.biosim.biosim import BioSim
geogr = """WWW
WLW
WWW"""
geogr = textwrap.dedent(geogr)
ini_herbs = [{'loc': (2, 2),
... |
#t Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch, data
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import sparseconvnet a... |
from __future__ import (
annotations,
)
import logging
from asyncio import (
TimeoutError,
)
from collections.abc import (
AsyncIterator,
Iterable,
)
from functools import (
partial,
)
from typing import (
Optional,
)
import aiopg
from aiopg import (
Connection,
Cursor,
)
from psycopg2... |
#! /usr/bin/python
# -*- coding:utf-8 -*-
import datetime
from django.template import Template, Context
raw_template = """
<p>Dear {{ person_name }},</p>
<p>Thanks for placing an order from {{ company }}. It's scheduled to
ship on {{ ship_date|date:"F j, Y" }}.</p>
{% if ordered_warranty %}
<p>Your warranty informat... |
# 参考
# https://ikatakos.com/pot/programming/python/packages/numba
# >>> numba compile >>>
import sys
import numpy as np
def numba_compile(numba_config):
import os, sys
if sys.argv[-1] == "ONLINE_JUDGE":
from numba import njit
from numba.pycc import CC
cc = CC("my_module")
for... |
import os
import sys
from django.db.backends import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'psql'
def runshell(self):
settings_dict = self.connection.settings_dict
args = [self.executable_name]
if settings_dict['DATABASE_USER']:
args... |
# Fazer um conversor de binário, hexadecimal e octal
num = int(input('Digite um número inteiro: '))
conversao = int(input('Para qual base de conversão:\n[1] - BINÁRIO\n[2] - HEXADECIMAL\n[3] - OCTAL\nQual opção:'))
if conversao == 1:
#converter para binário
convertido = bin(num)
print('o número convertid... |
import re
class ServiceResolver():
def __init__(self, application):
self.application = application
def resolve_services(self, service_name):
return self.resolve_services_from_array([service_name])
def resolve_services_from_array(self, services):
services_to_start = []
se... |
from abc import abstractmethod
from typing import List, Union
from requests import Response
from .manga import Manga
from manga_py.libs.http import Http
class Abstract:
def __init__(self):
super().__init__()
@abstractmethod
def get_main_page_url(self) -> str:
"""
Returns manga m... |
# @PascalPuchtler
# 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
# dis... |
#!/bin/python3
import logging
import os
import fcntl
import struct
import hexdump
from argparse import ArgumentParser
from datetime import datetime, timedelta
from scapy.all import *
from pyopenvpn import Client, Settings
class TunClient:
def __init__(self, args):
self.host = args.host
self.inited... |
#!/usr/bin/env python
"""
provide mock objects in order to develop locally
"""
from PIL import Image, ImageTk, ImageFilter
import time
import tty
import sys
PADDING = 10
class Keyboard:
def __init__(self):
tty.setcbreak(sys.stdin)
def getch_generator(self, debug=False, timeout=None):
while ... |
# -*- coding: utf-8 -*-
"""
sphinx.environment.managers
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Manager components for sphinx.environment.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
if False:
# For type annotation
from typing import An... |
import subprocess
import tarfile
import docker
import time
import os
from io import BytesIO
client = docker.from_env()
containers = set()
def get_ssh_key(name, algo, email, password, id):
file_path = f'/keys/{name}'
if not os.path.exists(file_path + '.pub'):
print(f"\tGenerating {algo} SSH key for {... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-03-28 01:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... |
#!/usr/bin/env python3
"""Recipe for doing ASR with phoneme targets and joint seq2seq
and CTC loss on the TIMIT dataset following a knowledge distillation scheme as
reported in " Distilling Knowledge from Ensembles of Acoustic Models for Joint
CTC-Attention End-to-End Speech Recognition", Yan Gao et al.
To run this r... |
import glob
path = 'search_queries/prepped/hw/*'
new_path = 'search_queries/prepped/hw_nice/'
paths = glob.glob(path)
print(paths)
for x in paths:
out = ""
with open(x, 'r') as f:
lines = f.readlines()
for line in lines:
if line == "\n":
out += line
else:
ou... |
def number_of_carries(a, b):
|
import secrets
from urllib.parse import urlencode, urlparse
import pytest
import requests
from django.http.response import HttpResponseRedirect
from django.urls.base import reverse
from djangito_client.views import login_handler
@pytest.fixture
def mock_response(monkeypatch):
class MockResponse:
text = ... |
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import escargot
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
... |
from PyQt5 import QtCore, QtGui, QtWidgets
sitecol = {'id': 0, 'name': 1, 'x': 2, 'y': 3, 'desc': 4, 'id_units': 5}
datacol = {'id': 0, 'id_sites': 1, 'id_struct': 2, 'azi': 3, 'inc': 4, 'struct': 5, 'desc': 6, 'tags': 7}
structurecol = {'id': 0, 'structure': 1, 'planar': 2, 'desc': 3, 'scode': 4, 'gcode': 5}
unitcol ... |
from django.db import models
import uuid
from django.contrib.auth.models import User
from django.core.validators import int_list_validator
from django.urls import reverse
# from django.dispatch import receiver
# from django.db.models.signals import pre_save
CONTENT_TYPE = {
('text/plain', 'Plain Text'),
('text... |
from django.apps import AppConfig
class PreumsConfig(AppConfig):
name = 'preums'
|
import io
import requests
import sys
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.forms import AuthenticationForm
from django.contr... |
### build a class for the 2D-Ising Model system
### import libraries
import numpy as np
import Hamiltonian
from Hamiltonian import Hamiltonian as Hamil
class Configuration:
"""A configuration of Ising spins with four-body interaction terms."""
def __init__(self, spins, L, J, K, T):
self.size ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from qdarkstyle import qt_bindings, qt_abstractions, information, __version__
import qdarkstyle
from example import example
import argparse
import sys
from os.path import abspath, dirname
sys.path.insert(0, abspath(dirname(abspath(__file__)) + '/..'))
def print_list_md(... |
# 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.
import logging
from telemetry.timeline import importer
from telemetry.timeline import trace_data as trace_data_module
class TraceBufferOverflowException(Ex... |
# coding=utf-8
from datetime import date, datetime
from django.utils.translation import ugettext_lazy as _
from django.core.management import BaseCommand
from django.conf import settings
from support.models import Issue
DEFAULT_NOTE = _("Generated automatically on {}\n".format(date.today()))
class Command(BaseCom... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import math
import operator
def calculateShannonEntropy(dataset):
# [[0, 0, 0, 0, 'N'], [0, 0, 1, 1, 'Y']]
instance_number = len(dataset)
# {'Y': 1, 'N': 1}
label_number_map = {}
for instance in dataset:
label = instance[-1]
if label not in label_nu... |
import unittest
import pandas as pd
from runpandarun.dataset import Dataset, RESAMPLE_METHODS, RESAMPLE_INTERVALS
from runpandarun.store import Datastore
from runpandarun.storage import Storage
class Test(unittest.TestCase):
def setUp(self):
self.store = Datastore('./example/config.yml')
def test_i... |
from flask import Flask
from flask import request
from threading import Thread
import json
import sys
from pprint import pprint
from handlers import *
import os
import requests
import ast
PING_RESPONSE = {"id": 1}
DATANODE_ADDRESSES = set()
NAMENODE = ''
app = Flask(__name__)
class DataNodePropagate(Thread):
# ... |
import glob
import os
import sys
import requests
from PIL import Image
from configparser import ConfigParser
os.chdir(os.path.dirname(sys.argv[0])) # Place de répertoire de travail dans le même dossier que le script
# try: # Permet de renvoyer l'erreur peut importe où elle se trouve dans le programme, sans le quit... |
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='bitoolbox',
version='0.5.2',
author='Thiago MadPin',
author_email='madpin@gmail.com',
description="A toolbox for BI purpouses",
p... |
from __future__ import division
import os
import sys
import random
if not '/home/blakeb/.local/lib/python2.7/scikit_learn-0.11-py2.7-linux-x86_64.egg' in sys.path:
if os.path.exists('/home/blakeb/.local/lib/python2.7/scikit_learn-0.11-py2.7-linux-x86_64.egg'):
sys.path.append('/home/blakeb/.local/lib/python... |
from polars.datatypes import *
|
import pyautogui
from time import sleep
def __write__(key):
pyautogui.typewrite(key)
def __hotkey__(key1,key2):
pyautogui.hotkey(key1,key2)
def __click__(x1,y1,click):
pyautogui.click(x=x1,y=y1,button=click)
__click__(355, 1060, 'left')
sleep(4)
__write__(['r', 'e', 'w'])
sleep(1)
__write__(['es... |
#contar todos os numeros pares no intervalo de 1 a 50
for c in range(1, 50,2):
print(c+1, end=" ")
print("funcionou!") |
"""
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
"""
# Definition for singly-linked list.... |
import socket
UDP_IP = "192.168.1.6"
UDP_PORT = 8080
MESSAGE = "Hello, World!"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT)) |
"""
Django settings for posthog project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
# isort: skip... |
#!/usr/bin/env python
# Copyright (C) 2013 Intel Corporation
#
# Released under the MIT license (see COPYING.MIT)
# Tag filter module used by testrunner
# This provides tag based filtering function for test case set.
"""Tag Filter Module"""
import unittest
TAG_PREFIX = "tag__"
def tag(*args, **kwargs):
"""tag de... |
# -*- coding: utf-8 -*-
import torch
from supar.utils.common import MIN
from supar.utils.fn import pad
def kmeans(x, k, max_it=32):
r"""
KMeans algorithm for clustering the sentences by length.
Args:
x (list[int]):
The list of sentence lengths.
k (int):
The number... |
# Interval class which converts
class Interval:
def __init__(self, interval_=[0, 0]):
self.start = interval_[0]
self.end = interval_[1]
def __repr__(self):
return '[{}, {}]'.format(self.start, self.end)
class Solution:
def merge(self, intervals):
intervals = [Interval(i) f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2022 Busana Apparel Group. All rights reserved.
#
# This product and it's source code is protected by patents, copyright laws and
# international copyright treaties, as well as other intellectual property
# laws and treaties. The product is licensed, not s... |
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest, chi2
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
class DataSet:
DIM_REDUCTION_METHODS = ["pca", "select_k_best... |
import os
import logging
from datetime import datetime, timedelta
from flask import Flask, request, abort, jsonify , render_template
import requests
def temp_token():
import binascii
temp_token = binascii.hexlify(os.urandom(24))
return temp_token.decode('utf-8')
logFormatter = logging.Formatter("%(asctime... |
# -*- coding: utf-8 -*-
from pyspark.sql import SparkSession
def basic_datasource_example(spark):
# generic load/save functions
df = spark.read.load("users.parquet")
df.select("name", "favorite_color").write.save("namesAndFavColors.parquet")
# 分区可以用在save和saveAsTable方法上当用dataset API时
df.write.part... |
# -*- coding: utf-8 -*-
# Apache Software License 2.0
#
# Copyright (c) 2018, Christophe Duong
#
# 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
#... |
a = int(input('Digite um Valor:'))
for c in range(1, 11):
print(f'{a} x {c} = {a*c}')
|
# Brythonで警告を出さないためのダミーヘッダー
# preprocessor.pyで、このファイルはhtmlに埋め込まない。
from typing import Callable
class Touch:
@property
def clientX(self)->int:
return 0
@property
def clientY(self)->int:
return 0
@property
def identifier(self)->int:
return 0
# addEventListener... |
import datetime
import random
# the single space to to create visual seperation
# so, that I know which are built into the standard library (datetime, random)
# and which are my own custom ones.
from questions import Add, Multiply
class Quiz:
"""Creates and runs quiz with 10 questions. Run .take_quiz() to start ... |
# -*- coding: utf-8 -*-
"""
Create Date: 20-03-2019
Author: Marc Enthoven
"""
# Imports of modules
import numpy as np
import random
class bsn:
def __init__(self):
pass
#Function to define whether random generated number satisfies bsn algorithm
def validate_bsn(self,bsn_number):
bsn_positi... |
"""
pals.py - Common functions for launching applications with PALS
MIT License
(C) Copyright [2020] Hewlett Packard Enterprise Development LP
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 wit... |
import serial
"""
# VE.Direct parser inspired by https://github.com/karioja/vedirect/blob/master/vedirect.py
"""
class Vedirect:
# The error code of the device (relevant when the device is in the fault state).
#
# Error 19 can be ignored, this condition regularly occurs during start-up or shutdown of the ... |
import requests
from bs4 import BeautifulSoup
from preprocessing.enums import Modifiers
def get_modifier_list_from_eu4_wiki(with_default_value=False):
req = requests.get('https://eu4.paradoxwikis.com/Modifier_list')
if not req.ok:
raise ConnectionError
html = req.text
soup = BeautifulSoup(ht... |
from django.conf.urls import url
from calaccess_website import views, sitemaps
from django.views.generic.base import RedirectView
urlpatterns = [
# The homepage
url(
r'^$',
RedirectView.as_view(url='https://www.californiacivicdata.org/'),
name="home",
),
#
# Downloads
... |
"""SCons.Defaults
Builders and other things for the local site. Here's where we'll
duplicate the functionality of autoconf until we move it into the
installation procedure or use something like qmconf.
The code that reads the registry to find MSVC components was borrowed
from distutils.msvccompiler.
"""
#
# Copyri... |
"""Loading a report from JSON
This manual marshalling/de-marshalling is not awesome.
"""
import json
import logging
import uuid as U
from pbcommand.models.report import (Report, Plot, PlotGroup, Attribute,
Table, Column, ReportSpec, PlotlyPlot)
from pbcommand.schemas import valida... |
import re
from collections import defaultdict
PATTERN = re.compile(r'#(?P<id>\d+) @ (?P<x>\d+),(?P<y>\d+): (?P<w>\d+)x(?P<h>\d+)')
def get_cells(x_s, y_s, w, h):
for x in range(x_s, x_s + w):
for y in range(y_s, y_s + h):
yield (x, y)
def build_cells(data):
cells = defaultdict(lambda: t... |
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
# python version 2.7.6
from snakebite.client import Client
import glob
'''
使用snakebite可以读取hdfs中数据的信息
目前没有发现往HDFS中写入数据的方法
url:https://github.com/spotify/snakebite
'''
def display():
client = Client("study", 9000, use_trash=False)
for x in client.ls(['/data/gz']):
prin... |
import websocket
websocket.enableTrace(True)
ws = websocket.create_connection("ws://127.0.0.1:8888/websocket")
ws.send('Hello, Tornado')
result = ws.recv()
print(result)
ws.close()
# import socket
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# host =... |
from setuptools import setup
setup(
name='flask_microservices_builder',
version='0.0.1',
packages=['flask_microservices_builder'],
url='https://github.com/invana/flask-microservice-builder',
license='MIT License',
author='Ravi Raja Merugu',
author_email='ravi@invanalabs.ai',
description... |
# ------------------------------------
# CODE BOOLA 2015 PYTHON WORKSHOP
# Mike Wu, Jonathan Chang, Kevin Tan
# Puzzle Challenges Number 6
# ------------------------------------
# Let's go back to the basics.
# ------------------------------------
# INSTRUCTIONS:
# Write a function that takes a single
# input to... |
budget = float(input())
season = input()
money = 0
if budget <= 100:
if season == "winter":
money = budget * 0.70
print(f"Somewhere in Bulgaria")
print(f"Hotel - {money:.2f}")
elif season == "summer":
money = budget * 0.30
print(f"Somewhere in Bulgaria")
print(f... |
#pip install newspaper3
from newspaper import Article
#pip install beautifulsoup4
from bs4 import BeautifulSoup
import urllib.request
import urllib.parse
#네이버 뉴스 주소
url = "https://news.naver.com"
#페이지 정보 불러오기
response=urllib.request.urlopen(url)
soup=BeautifulSoup(response,'html.parser')
#네이버 뉴스의 헤더뉴스 정보 불러오기
result... |
from atlas.modules.commands.base import BaseCommand
from atlas.modules.resource_creator.creators import AutoGenerator
class Generate(BaseCommand):
help = "Auto generate resources from Swagger file and update Res Mapping and Swagger File"
def handle(self, **options):
gen = AutoGenerator()
gen... |
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
import os.path
if 'TOOLBOX_PATH' in os.environ:
sys.path.append(os.path.join(os.environ['TOOLBOX_PATH'], 'python'))
else:
raise EnvironmentError(f"BART TOOLBOX_PATH not set. Please set TOOLBOX_PATH environment variable")
import cfl
import s... |
# -*- coding: utf-8 -*-
import os
from datetime import timedelta
from enum import IntEnum
from peewee import *
from playhouse.hybrid import hybrid_property
from typing import List
from botlistbot import helpers
from botlistbot import settings
from botlistbot import util
from botlistbot.models.basemodel import BaseMode... |
import streamlit as st
# Analysis packages
import pandas as pd
import numpy as np
import pickle
import joblib
import sklearn
from sklearn.preprocessing import StandardScaler
# Geo Pkgs
import folium
import geopandas as gpd
import json
#__________main page_________________
st.title("toddler-town")
st.subheader("est... |
from django.apps import AppConfig
class TreasurySSConfig(AppConfig):
name = "treasurySS"
verbose_name = "treasury segments"
|
from kissom.storeManager import StoreManager
from kissom.appExceptions import (
KissomException,
TableNameDoesNotExistException,
TableNameNotDefinedException,
ObjectNotProvidedException,
PrimaryKeyNotProvidedException,
ObjectAttributeValueException,
)
from kissom.utils.conditions import getCond... |
from django.shortcuts import render
from account.models import Account
def earl_list_view(request):
queryset = Account.objects.all()
context = {
"earl_list": queryset,
"users": queryset.filter(is_user=True),
"ficthist": queryset.filter(is_user=False),
"active_page": "browse",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.