content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import sys
import os
import logging
import time
import gdb
# https://pro.arcgis.com/en/pro-app/latest/help/data/geodatabases/manage-oracle/rebuild-system-table-indexes.htm
if __name__ == '__main__':
geodatabase = gdb.Gdb()
timestr = time.strftime("%Y%m%d-%H%M%S")
targetlog = os.path.join(os.environ['T... | nilq/baby-python | python |
#!/usr/bin/python
import sys
import getopt
import random
import writer
# Increase maximum recursion depth
sys.setrecursionlimit(100 * sys.getrecursionlimit())
# Generate CNF, order, and schedule files to compare two trees of xor's over a common set of inputs
def usage(name):
print("Usage: %s [-h] [-v] [-f] [-... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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, overload
from . import ... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. 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
# noti... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import tkinter
def affiche_touche_pressee():
root.event_generate("<<perso>>", rooty=-5)
def perso(evt):
print("perso", evt.y_root)
root = tkinter.Tk()
b = tkinter.Button(text="clic", command=affiche_touche_pressee)
b.pack()
root.bind("<<perso>>", perso) # on intercepte un é... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy #importar ros para python
from std_msgs.msg import String, Int32 # importar mensajes de ROS tipo String y tipo Int32
from geometry_msgs.msg import Twist # importar mensajes de ROS tipo geometry / Twist
class Printer(object):
def __init__(self, args):
super(Printer, self).__init_... | nilq/baby-python | python |
import os
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 6):
print(sys.stderr, "{}: need Python 3.6 or later.".format(sys.argv[0]))
print(sys.stderr, "Your Python is {}".format(sys.version))
sys.exit(1)
ROOT_DIR = os.path.dirname(__file__)
setup(
name="py-pdf-pars... | nilq/baby-python | python |
"""
Copyright (C) king.com Ltd 2019
https://github.com/king/s3vdc
License: MIT, https://raw.github.com/king/s3vdc/LICENSE.md
"""
import tensorflow as tf
def _session_config() -> tf.ConfigProto:
"""Constructs a session config specifying gpu memory usage.
Returns:
tf.ConfigProto -- session config.
... | nilq/baby-python | python |
"""Runtimes manager."""
import logging
from contextlib import suppress
from importlib import import_module
from types import ModuleType
from typing import Dict, Optional, Set, Type
from .runtime import Process
logger = logging.getLogger(__name__)
class RegisteredRuntimes:
"""A list of registered base python pro... | nilq/baby-python | python |
# use lists as stack, LIFO (last-in-first-out)
stack = [1, 2, 3, 4, 5]
print(stack)
print('LIFO stack')
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)
print("\n")
# use lists as FIFO (first-in-first-out)
print('FIFO stack')
stack.append(6)
stack.app... | nilq/baby-python | python |
from constance import config
from django.http import Http404
from impersonate.decorators import allowed_user_required
from impersonate.views import impersonate, stop_impersonate
from bitcaster.models import User
def queryset(request):
return User.objects.exclude(id=request.user.id).exclude(is_superuser=True).ord... | nilq/baby-python | python |
import numpy as np
class LogisticRegression(object):
# setting learning rate and iteration times
def __init__(self, alpha=0.0005, lamb=0.1, iters=100):
self.iters = iters
self.alpha = alpha
self.lamb = lamb
# add one line for intercept
self.theta = np.array([0.0] * (X.sh... | nilq/baby-python | python |
import pickle
def load( path ):
with open(path, 'rb') as ff :
model = pickle.load(ff)[0]
return model
| nilq/baby-python | python |
#!/usr/bin/env python36
# -*- coding: utf-8 -*-
"""
Created on 2018/10/6 11:48 AM
@author: Tangrizzly
"""
from __future__ import print_function
from collections import OrderedDict
import datetime
import cPickle
import os
from public.GeoIE import GeoIE
from public.Global_Best import GlobalBest
from public.Load_Data_Ge... | nilq/baby-python | python |
import abc
import rospy
import numpy as np
import matplotlib.pyplot as plt
import math
class JointTrajectoryPlanner(object):
def __init__(self, time_i = 0.0, time_step = 0.1, time_f = None,
movement_duration = None):
self._time_step = time_step
self._time_i = time_i
self._... | nilq/baby-python | python |
from pymongo import MongoClient
import datetime
def collect_validated_input(prompt, error_msg, validator):
user_input = input(prompt)
validated = validator(user_input)
while not validated:
user_input = input(error_msg)
validated = validator(user_input)
return user_input
if __name... | nilq/baby-python | python |
import json
import unittest
# from mayday.utils import query_util, ticket_util
from mayday import helpers
from mayday.objects import Query, Ticket
USER_ID = 12345678
USERNAME = 'Mayday'
class Test(unittest.TestCase):
def test_init_ticket(self):
ticket = Ticket(user_id=USER_ID, username=USERNAME).to_dic... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name,missing-docstring,broad-except
# Copyright 2018 IBM RESEARCH. 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
#
# ... | nilq/baby-python | python |
from setuptools import setup, find_packages
import byte_api
setup(
name='byte-api',
version=byte_api.__version__,
author=byte_api.__author__,
url='https://github.com/byte-api/byte-python',
download_url='https://github.com/byte-api/byte-python/archive/v{}.zip'.format(
byte_api.__version__... | nilq/baby-python | python |
'''Provides access to a subset of the NAM-NMM dataset.
The North American Mesoscale Forecast System (NAM) is one of the
major weather models run by the National Centers for Environmental
Prediction (NCEP) for producing weather forecasts. Dozens of weather
parameters are available from the NAM grids, fr... | nilq/baby-python | python |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.conf import settings
from operator import itemgetter
from datetime import datetime, timedelta
import json
import urllib2
import re
# Get API user and token from settings
user = se... | nilq/baby-python | python |
# ここから表面データの処理
import numpy as np
# import matplotlib.pyplot as plt
import pandas as pd
# import os
# import itertools
# from scipy import signal
# import time
class Analysis_surface():
def __init__(self,k0) -> None:
self.sampling_num_surface = int(1023) # 表面粗さや2DFFTを計算したりする点数
if k0 == 1:
... | nilq/baby-python | python |
"""
An unofficial native Python wrapper for the LivePerson Messaging Operations API.
Documentation:
https://developers.liveperson.com/data-messaging-operations-overview.html
The Messaging Operations API extracts data according to the search query. The API allows agent managers to extract
information about their call ... | nilq/baby-python | python |
# Generated by Django 2.2.1 on 2019-05-28 11:15
import jsonfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('internet_nl_dashboard', '0030_auto_20190515_1209'),
]
operations = [
migrations.AddField(
model_name='account',
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : zerlous
# @File : index.py
# @Time : 2019-08-26 18:20
# @Desc :
print "aaaaa"
print ('你好')
flag = False
if flag:
print 'true'
else:
print 'false'
| nilq/baby-python | python |
# coding: utf-8
# CarND-Behavioral-Cloning-P3
# In[3]:
#Importing Dependencies when required
import os
import csv
samples=[]
with open('./data/driving_log.csv') as csvfile:
has_header = csv.Sniffer().has_header(csvfile.read(1024))
csvfile.seek(0) # Rewind.
reader=csv.reader(csvfile)
if has_header... | nilq/baby-python | python |
import sys
sys.path.insert(1, '../')
from selenium.webdriver.common.keys import Keys
import random
from random import randint
from functions import fetchLists, wait, chanceOccured, cleanNumber, updateLists
from bot import Bot
class ProcessAccountsBot(Bot):
def __init__(self, account: str = None):
super().... | nilq/baby-python | python |
from flask import g
def transform(ugc):
if not g.netanyahu:
return ugc
new_ugc = []
for u in ugc:
new_u = {
'censored': u.get('censored', False),
'ugcdocid': u['ugcdocid'],
'pages': u['pages'],
'summary': u.get('summary', '').strip(),
... | nilq/baby-python | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from erpnext import get_company_currency, get_default_company
from erpnext.accounts.report.utils import get_currency, convert_to_pre... | nilq/baby-python | python |
from string import ascii_lowercase
def destroyer(input_sets):
"""
takes in a tuple with 1 or more sets of characters and replaces the alphabet with letters that are in the sets
First gets the candidates of the alphabets and gets the letters to knock out into a list
:param input_sets:
:return: str... | nilq/baby-python | python |
import mysql.connector
from contextlib import closing
with closing(mysql.connector.connect(
host="localhost",
port=3306,
user="root",
password="sql!DB123!",
database="app"
)) as db:
with closing(db.cursor(dictionary=True)) as cur:
sql = "select closing_date, currency_symbol, " \
... | nilq/baby-python | python |
# Copyright 2016 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... | nilq/baby-python | python |
from pathlib import Path
import torch
import torch.nn as nn
from torch.autograd import Variable
from mnist_efficientnet import io
from mnist_efficientnet.network import Network, extract_result
root = Path("../input/digit-recognizer")
train_x, train_y = io.load_train_data(root)
test = io.load_test_data(root)
net = ... | nilq/baby-python | python |
"""
Tests for the pynagios package.
"""
class TestPyNagios(object):
pass
| nilq/baby-python | python |
import pwndbg.color.theme as theme
import pwndbg.config as config
from pwndbg.color import generateColorFunction
config_prefix = theme.Parameter('backtrace-prefix', '►', 'prefix for current backtrace label')
config_prefix_color = theme.ColoredParameter('backtrace-prefix-color', 'none', 'color for prefix of c... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class network1(nn.Module):
def __init__(self):
super().__init__()
self.cnn1 = nn.Sequential(
nn.ReflectionPad2d(1),
nn.Conv2d(1, 4, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2... | nilq/baby-python | python |
#!/usr/bin/python
#
# Chrome - Profile Launcher for Chrome
# @see http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
# https://pygobject.readthedocs.io/en/latest/getting_started.html
# https://lazka.github.io/pgi-docs/
# http://www.programcreek.com/python/example/9059/gtk.IconView
impo... | nilq/baby-python | python |
import unittest
import os.path
import os
import sys
sys.path.append(".")
#from pywinauto.timings import Timings
#Timings.Fast()
excludes = ['test_sendkeys']
def run_tests():
testfolder = os.path.abspath(os.path.split(__file__)[0])
sys.path.append(testfolder)
for root, dirs, files in... | nilq/baby-python | python |
import torch
from torch import nn
from torch.utils.data import DataLoader
import os
from abc import ABC
from ssl_eval import Evaluator
from typing import Tuple
from .. import pkbar
from ..logger import Logger, EmptyLogger
from ..utils import AllReduce, after_init_world_size_n_rank
from ..scheduler import Scheduler
c... | nilq/baby-python | python |
"""Domain classes for fulltext extraction service."""
from typing import NamedTuple, Optional, Any
from datetime import datetime
from pytz import UTC
from backports.datetime_fromisoformat import MonkeyPatch
from enum import Enum
MonkeyPatch.patch_fromisoformat()
class Extraction(NamedTuple): # arch: domain
"... | nilq/baby-python | python |
import bmesh as bm
import bpy
from bpy_extras import object_utils
from mathutils import Matrix
import numpy as np
from smorgasbord.common.io import get_scalars
from smorgasbord.common.mat_manip import make_transf_mat
from smorgasbord.common.transf import transf_pts
def combine_meshes(obs):
"""
Returns the me... | nilq/baby-python | python |
import time
time.perf_counter()
from game_mechanics import Player, Simulator
from strategies import make_turn_strat
import numpy as np
import matplotlib.pyplot as plt
# A bot plays Incan Gold in single-player mode.
# The bot leaves when the turn reaches the Turn Threshold value.
# The game is simulated many times for... | nilq/baby-python | python |
import logging
_logger = logging.getLogger(__name__)
import sys
#import random
import numpy as np
from .agent import Agent
from .ataristatebuffer import AtariStateBuffer
class AtariAgent(Agent):
""" This class is an implementation of an Atari agent.
The agent interacts with the given environment, organizes ... | nilq/baby-python | python |
r"""
Optimizing noisy circuits with Cirq
===================================
.. meta::
:property="og:description": Learn how noise can affect the optimization and training of quantum computations.
:property="og:image": https://pennylane.ai/qml/_images/noisy_circuit_optimization_thumbnail.png
.. figure:: ../de... | nilq/baby-python | python |
#!/usr/bin/env python
# coding=utf-8
import argparse
import os
import re
#功能:输入一个只包含tree文件的目录,不加“/”,以及输入一个label map关系表,原来的标签必须非冗余,即不能一对多映射。然后在当前目录输出所有relabel后的tree文件。
#获取树目录下所有文件名
parser=argparse.ArgumentParser(description = "功能:批量修改nwk文件的label注释。输入一个包含tree文件的目录,和一个tree中老label和要替换的label的对应两列表。在当前目录输出relabel后的各个tree文件"... | nilq/baby-python | python |
from os import path
from sys import modules
from fabric.api import sudo
from fabric.contrib.files import upload_template
from pkg_resources import resource_filename
def restart_systemd(service_name):
sudo("systemctl daemon-reload")
if sudo(
"systemctl status -q {service_name} --no-pager --full".forma... | nilq/baby-python | python |
from machine import Pin
import utime
from ssd1306 import SSD1306_I2C
#I/O Configuration
led = Pin(28, Pin.OUT)
onboard_led = Pin(25, Pin.OUT)
button = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_DOWN)
#Set Initial Conditions
led.low()
onboard_led.high()
fast_blink = False
# attach the interrupt to the buttonPin... | nilq/baby-python | python |
import os
from setuptools import find_packages, setup
with open(os.path.join('.', 'VERSION')) as version_file:
version = version_file.read().strip()
setup(
name='mavelp',
version=version,
long_description=open('README.md').read(),
package_dir={'': 'src'},
packages=find_packages(where='src'),
)
| nilq/baby-python | python |
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime,
QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent)
from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase,
... | nilq/baby-python | python |
__author__ = 'Thomas Kountis'
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
* Created by PyCharm.
* Project: catalog
* Author name: Iraquitan Cordeiro Filho
* Author login: pma007
* File: api
* Date: 2/26/16
* Time: 11:26
* To change this template use File | Settings | File Templates.
"""
from flask import Blueprint, jsonify
from catalog.models import Categ... | nilq/baby-python | python |
#
# copied from
#
# https://scikit-learn.org/stable/auto_examples/covariance/plot_lw_vs_oas.html#sphx-glr-auto-examples-covariance-plot-lw-vs-oas-py
#
#
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, cholesky
from sklearn.covariance import LedoitWolf, OAS
np.random.seed(0)
n_... | nilq/baby-python | python |
import json
import logging
import time
import datetime as dt
from bitbot import services, strategy
import pandas as pd
class Bot:
"""
A trading bot that executes a certain strategy
Attributes:
config (dict[str, any]): the loaded configuration
next_action (services.OrderDirection): the nex... | nilq/baby-python | python |
import rospy
import sys
import tf
import tf2_ros
import geometry_msgs.msg
if __name__ == '__main__':
if len(sys.argv) < 8:
rospy.logerr('Invalid number of parameters\nusage: '
'./static_turtle_tf2_broadcaster.py '
'child_frame_name x y z roll pitch yaw')
sy... | nilq/baby-python | python |
# Generated by Django 3.2.12 on 2022-03-27 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20220328_0004'),
]
operations = [
migrations.RenameField(
model_name='predication',
old_name='avg_... | nilq/baby-python | python |
""" Module for time series classification using Bayesian Hidden Markov Model
-----------------
Version : 0.2
Date : December, 11th 2019
Authors : Mehdi Bennaceur
Phase : Development
Contact : _
Github : https://github.com/DatenBiene/Bayesian_Time_Series_Classification
"""
__version__ = "... | nilq/baby-python | python |
# Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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, publ... | nilq/baby-python | python |
import re
from num2words import num2words
from word2number.w2n import word_to_num
from pycorenlp import StanfordCoreNLP
class PostProcess:
month_map = {
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
##################################################################################
# File: c:\Projects\KENYA ONE PROJECT\CORE\engines\values.py #
# Project: c:\Projects\KENYA ONE PROJECT\CORE\engines #
# Created Date: Thur... | nilq/baby-python | python |
from .jxa_loader import *
| nilq/baby-python | python |
import math
import numpy as np
import torch
from torch import nn
class MultiheadAttention(nn.Module):
"""General purpose multihead attention implementation."""
def __init__(self, input_dim, proj_dim, n_heads=1, dropout=0.0,
attn_type='cross', initializer='xavier_uniform'):
assert pr... | nilq/baby-python | 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
# distributed under th... | nilq/baby-python | python |
# Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | nilq/baby-python | python |
"""
Shutterstock CLI
"""
import click
from .images import images
from .videos import videos
from .audio import audio
from .editorial import editorial
from .cv import cv
from .ai_audio import ai_audio
from .editor import editor
from .contributors import contributors
from .user import user
from .test import te... | nilq/baby-python | python |
try:
from SmartFramework.serialize.tools import serializejson_, authorized_classes
from SmartFramework.serialize import serialize_parameters
except:
from serializejson import serialize_parameters
from serializejson.tools import serializejson_, authorized_classes
import array
def serializejson_array(i... | nilq/baby-python | python |
import collections
import copy
import json
import os
import sys
import unittest
from ethereum import utils
from ethereum import config
from ethereum.tools import tester as t
from ethereum.utils import mk_contract_address, checksum_encode
import rlp
import trie
import trie.utils.nibbles
from test_utils import rec_hex,... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 09:26:03 2022
@author: thejorabek
"""
'''son=10
print(son,type(son))
son=3.14
print(son,type(son))
son='Salom Foundationchilar'
print(son,type(son))
son=True
print(son,type(son))
son=int()
print(son,type(son))
print("Assalom",123,3.14,True,sep='... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: 17.py
@time: 2019/5/29 22:07
@desc:
'''
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) < 1:
return []
str... | nilq/baby-python | python |
# Copyright (C) 2014-2017 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET ... | nilq/baby-python | python |
from os import stat
from re import VERBOSE
from request_api.services.commentservice import commentservice
from request_api.services.notificationservice import notificationservice
from request_api.models.FOIRawRequests import FOIRawRequest
from request_api.models.FOIMinistryRequests import FOIMinistryRequest
from reque... | nilq/baby-python | python |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import argparse
from unittest import mock
from unittest.mock import MagicMock, patch
import pytest
from pytube import cli, StreamQuery, Caption, CaptionQuery
parse_args = cli._parse_args
@mock.patch("pytube.cli.YouTube")
def test_download_when_itag_not_found(youtube):
youtube.streams = ... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# cssyacc/block.py
#
# class for block
# ----------------------------------------------------------------
# copyright (c) 2014 - Domen Ipavec
# Distributed under The MIT License, see LICENSE
# ------------... | nilq/baby-python | python |
# liberate - Add the specified block to the list of available blocks. As part
# of the liberation process, check the block's buddy to see if it can be
# combined with the current block. If so, combine them, then recursively
# call liberate.
# @param block The block to be liberated
def liberate(block):
... | nilq/baby-python | python |
import os
import json
import yaml
import time
import flask
import distro
import psutil
import random
import string
import threading
import jinja2.exceptions
from flask import request
from turbo_flask import Turbo
from datetime import datetime
try:
from mcipc.query import Client
except: # server offline
pass
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'scanwindow.ui'
#
# Created: Sun Jun 5 22:23:54 2016
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Att... | nilq/baby-python | python |
import argparse
import datetime
import json
import logging
import os
import subprocess
import tempfile
import arcpy
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger(__name__)
def get_args():
parser = argparse.ArgumentParser()
parser.add_argu... | nilq/baby-python | python |
import requests
from src.models import Company
from bs4 import BeautifulSoup as bs
import time
import asyncio
class Scrap:
def __init__(self):
self.headers={
"Host":"www.nepalstock.com",
"User-Agent":"Mozilla/5.0 (X11; Linux aarch64; rv:78.0) Gecko/20100101 Firefox/78.0",
... | nilq/baby-python | python |
from common_fixtures import * # NOQA
import jinja2
import os
if_upgrade_testing = pytest.mark.skipif(
os.environ.get("UPGRADE_TESTING") != "true",
reason='UPGRADE_TESTING is not true')
pre_upgrade_namespace = ""
post_upgrade_namespace = ""
pre_port_ext = ""
post_port_ext = ""
@pytest.fixture(scope='session... | nilq/baby-python | python |
from backdoors.backdoor import *
class Perl(Backdoor):
prompt = Fore.RED + "(perl) " + Fore.BLUE + ">> " + Fore.RESET
def __init__(self, core):
cmd.Cmd.__init__(self)
self.intro = GOOD + "Using Perl module"
self.core = core
self.options = {
"port" : Optio... | nilq/baby-python | python |
pow2 = []
for x in range(1, 10):
pow2.append(2 ** x)
print(pow2)
new_pow2 = [2 ** x for x in range(1,10)] # Comprehensions
print(new_pow2)
new_pow3 = [2 ** x for x in range(1,10) if x % 2 == 0] # Comprehensions with IF
print(new_pow3)
power = lambda x: 2 ** x
conditional_values = [1,2,3,4,5]
new_pow4 = [power(... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
A module which implements the MergeSort algorithm.
"""
import sys
def parseInput(input):
"""
Converts an input string of integers into an array of integers.
"""
return [int(num) for num in input.split(',')]
def mergeSort(a):
"""
Sorts and array of numbers into asc... | nilq/baby-python | python |
"""
У каждой статьи указаны авторы (их несколько) и темы (их тоже
несколько). Определите самую частую пару автор-тема. Если несколько
пар встретились одинаковое число раз, то выведите обе (каждую на
новой строчке).
Формат ввода
На каждой строчке сначала указаны фамилии авторов через пробел, потом
запятая, потом темы (... | nilq/baby-python | python |
# Listing_20-1.py
# Copyright Warren & Csrter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Minimum code for a PyQt program
import sys
from PyQt4 import QtCore, QtGui, uic # Import the Qt libraries we need
form_cla... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
# from sensor_msgs.msg import Temperature
from django_interface.msg import SilviaStatus
from django_interface.srv import SilviaStatusRequest, SilviaStatusRequestResponse
class StatusServer:
"""
Store machine status through subscription to status topic
Respond to service r... | nilq/baby-python | python |
# Importing the Kratos Library
import KratosMultiphysics as KM
# CoSimulation imports
import KratosMultiphysics.CoSimulationApplication.factories.solver_wrapper_factory as solver_wrapper_factory
def Create(settings, models, solver_name):
input_file_name = settings["input_file"].GetString()
settings.RemoveValu... | nilq/baby-python | python |
from flask import render_template, redirect
from flask_login import login_required
from . import home
from .. import db
@home.route('/')
@home.route('/index')
def homepage():
"""
Handles requests to `/` and `/index` routes
It's the landing page, index page, homepage or whatever you like to call it
"""... | nilq/baby-python | python |
'''
Blind Curated 75 - Problem 40
=============================
Reverse Bits
------------
Reverse the bits of a given 32-bit unsigned integer.
[→ LeetCode][1]
[1]: https://leetcode.com/problems/reverse-bits/
'''
def solution(n):
'''
Working inwards from both ends, use bitwise logic to swap each pair of bits.
'... | nilq/baby-python | python |
from collections import namedtuple
from collections import defaultdict
import spacy
import warnings
import numpy as np
connection = namedtuple('connection', 'node weight')
Index = namedtuple('Index', 'pid, sid, wid')
nlp = spacy.load('en')
# nlp = spacy.load('en_core_web_lg')
# nlp = spacy.load('en_vectors_web_lg', ... | nilq/baby-python | python |
import praw
import pdb
import re
import os
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
#GET request url
coin_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
reddit = praw.Reddit('BTC9KBABY') #selects reddit... | nilq/baby-python | python |
"""
3D IoU Calculation and Rotated NMS
Written by Shaoshuai Shi
All Rights Reserved 2019-2020.
"""
import torch
import numpy as np
from opencood.utils.common_utils import check_numpy_to_torch
from opencood.pcdet_utils.iou3d_nms import iou3d_nms_cuda
def boxes_bev_iou_cpu(boxes_a, boxes_b):
"""
Args:
... | nilq/baby-python | python |
#! /usr/bin/env python
import rospy
from time import time, sleep
from datetime import datetime
from ar_track_alvar_msgs.msg import AlvarMarkers
from controlmulti import *
from callback_alvar import *
if __name__ == '__main__':
# try:
rospy.init_node('control_node', anonymous= False)
rate = rospy... | nilq/baby-python | python |
from enum import auto
import graphene
from serflag import SerFlag
from handlers.graphql.types.access import create_access_type
class VMActions(SerFlag):
attach_vdi = auto()
attach_network = auto()
rename = auto()
change_domain_type = auto()
VNC = auto()
launch_playbook = auto()
changing... | nilq/baby-python | python |
import numpy as np
from typing import Tuple, Union
from .values_generator import ValuesGenerator
class UniformGenerator(ValuesGenerator):
def __init__(
self,
bounds: Tuple[Union[int, float], Union[int, float]],
resolution: int = 1_000,
seed: int = None,
):
super(UniformGenerator, self).__init__(bounds... | nilq/baby-python | python |
from mimesis import Person
from tests.base import BaseTestCase
from tests.utils import add_user, add_group, add_user_group_association
class TestGroupModel(BaseTestCase):
"""
Test Group model
"""
# Generate fake data with mimesis
data_generator = Person('en')
def test_model_group_add_group(s... | nilq/baby-python | python |
'''
Usage:
python remove_from_env.py $PATH $TO_BE_REMOVED
returns $PATH without paths starting with $TO_BE_REMOVED
'''
import sys
ENV = sys.argv[1]
REMOVE = sys.argv[2]
new_path = []
for path in ENV.split(':'):
if path.startswith(REMOVE):
continue
new_path.append(path)
print ':'.join(n... | nilq/baby-python | python |
"""
{This script calculates spread in velocity dispersion (sigma) from mocks for
red and blue galaxies as well as smf for red and blue galaxies. It then
calculates a full correlation matrix using sigma and smf of both galaxy
populations as well as a correlation matrix of just sigma
measurements of both galaxy po... | nilq/baby-python | python |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | nilq/baby-python | python |
A, B, X = map(int, input().split())
print("YES" if 0 <= X-A <= B else "NO") | nilq/baby-python | python |
from content.models import PopularQuestion
from ..loader import dp
from aiogram import types
from ..utils.filters import starts_with
from ..keyboards.inline import generic
from ..utils.helpers import get_message_one_button
@dp.callback_query_handler(starts_with('FAQ_element'))
async def send_faq_carousel(callback_que... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.