content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from confluent_kafka import Producer import rest import json class BusProducer: def __init__(self): # Pre-shared credentials self.credentials = json.load(open('bus_credentials.json')) # Construct required configuration self.configuration = { 'client.id': 'bus_producer...
nilq/baby-python
python
"""ApacheParser is a member object of the ApacheConfigurator class.""" import fnmatch import itertools import logging import os import re import subprocess from letsencrypt import errors logger = logging.getLogger(__name__) class ApacheParser(object): """Class handles the fine details of parsing the Apache Con...
nilq/baby-python
python
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib __author__ = 'ipetrash' """Пример отсылки письма, содержащего обычный текст и html, "самому себе".""" # http://www.tutorialspoint.com/python/python_sending_email.htm # https://docs.python.org/3.4/library/email-example...
nilq/baby-python
python
#!/usr/bin/env python import os import pyfwk from pyfi.entity.entity.db import EntityDB # -----------------------------EXCHANGE-MODEL-----------------------------# class TypeModel(pyfwk.Model): model = None dbase = None table = None columns = None @staticmethod def instance(): if no...
nilq/baby-python
python
"""Sensitive Field Type""" # standard library import logging from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union # first-party from tcex.input.field_types.exception import InvalidEmptyValue, InvalidLengthValue, InvalidType if TYPE_CHECKING: # pragma: no cover # third-party from pydantic.fi...
nilq/baby-python
python
""" License ------- Copyright (C) 2021 - David Fernández Castellanos You can use this software, redistribute it, and/or modify it under the terms of the Creative Commons Attribution 4.0 International Public License. Explanation --------- This module contains the statistical model of the COVID-19 vaccination ca...
nilq/baby-python
python
import torch import torch.fx.experimental.fx_acc.acc_ops as acc_ops import torch.nn as nn from torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec class TestSizeConverter(AccTestCase): def test_size(self): class Size(nn.Module): def forward(self, x): bs = ...
nilq/baby-python
python
from authlib.oauth2.rfc8414 import AuthorizationServerMetadata
nilq/baby-python
python
# db_util.py from datetime import datetime import sqlite3 import os import inspect import uuid #uuid4() --> cookie from utils import err, done,log try: # log(os.environ['GATEWAY_INTERFACE']) if 'cgi' in os.environ['GATEWAY_INTERFACE'].lower(): DATABASE = 'csci4140.db' else: DATABASE = "csci4...
nilq/baby-python
python
from django.db.models import Choices class ValueTypes(Choices): PERCENTAGE = 'percentage' FIXED_AMOUNT = 'fixed amount' FREE_SHIPPING = 'free shipping'
nilq/baby-python
python
import logging from .builder import TargetBuilder from .config import YAMLParser from .device import RunnerFactory from .testcase import TestCaseFactory class TestsRunner: """Class responsible for loading, building and running tests""" def __init__(self, targets, test_paths, build=True): self.target...
nilq/baby-python
python
from base import PMLM from models import EDMM, MLMM, MEMM, DCSMM, DEDMM, DKLMM import utils
nilq/baby-python
python
from JumpScale import j import sys import fcntl import os import time class Empty(): pass class AAProcessManagerCmds(): ORDER = 100 def __init__(self, daemon=None): self._name = "pm" self.daemon = daemon self._reloadtime = time.time() if daemon is not None: ...
nilq/baby-python
python
import pandas as pd import datetime import pandas_datareader.data as web import matplotlib.pyplot as plt from matplotlib import style start = datetime.datetime(2015, 1, 1) #Dato for onsket aksjekurs end = datetime.datetime.now() df = web.DataReader("ORK.OL", "yahoo", start, end) # Verdien av Orkla aksjen fra 2015 t...
nilq/baby-python
python
""" Implementation of geo query language """
nilq/baby-python
python
# 第3章: 正規表現 import json import gzip def extract(title): with gzip.open('jawiki-country.json.gz', 'rt', encoding='utf8') as fin: for line in fin: jsd = json.loads(line) if jsd['title'] == title: return jsd['text'] return '' def main(): article = extract('イギリス...
nilq/baby-python
python
t = int(input()) for i in range(t): s = str(input()) w = s.split() s1 = 'not' if(s1 in w): print('Real Fancy') else: print("regularly fancy")
nilq/baby-python
python
#!/usr/bin/python3 import pytest from brownie import network, Contract, Wei, chain, reverts @pytest.fixture(scope="module") def requireMainnetFork(): assert (network.show_active() == "mainnet-fork" or network.show_active() == "mainnet-fork-alchemy") @pytest.fixture(scope="module") def iUSDC(accounts, LoanTokenL...
nilq/baby-python
python
from .database import * def password_is_valid(password): if len(password) < 5: return False return True class Login(): def __init__(self, data_set): self.db = self.db_create(data_set) def db_create(self, data_set): db = Database(data_set) db.up_database() ret...
nilq/baby-python
python
ls = [] for i in range(100): if i%3==0: ls.append(i) print(ls) ls = [i for i in range(100) if i%3==0] # list comprehension print(ls) dict1 = {i:f"item{i}" for i in range(1, 12) if i%2==0} # dictionary comprehension print(dict1) dict1 = {value:key for key,value in dict1.items()} # can cha...
nilq/baby-python
python
# Copyright 2017 Eun Woo Song # 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, so...
nilq/baby-python
python
import json import os import hashlib import getpass def main(): FileStructureSetUp().set_up_files() class ScheduleTable: # Describes a schedule table class Row: def __init__(self, block_type: str = "NA", day: str = "NA", place: str = "NA", time: str = "NA"): """ Describes...
nilq/baby-python
python
import pytest import python_jsonschema_objects as pjo @pytest.fixture def arrayClass(): schema = { "title": "ArrayVal", "type": "object", "properties": { "min": { "type": "array", "items": {"type": "string"}, "default": [], ...
nilq/baby-python
python
import pytesseract import settings def img_to_text(): pytesseract.pytesseract.tesseract_cmd = settings.WORKSPACE_DIR + r'/etc/Tesseract-OCR/tesseract.exe' text = pytesseract.image_to_string(settings.WORKSPACE_DIR + r'/screenshots_temp/screenshot.png', lang=settings.get_language()) text = text.replace("\n"...
nilq/baby-python
python
import multiprocessing import numpy as np from basetrainer import BaseTrainer from solvers import LeastSquares from scorers import MeanAbsolute from parallelworker import Worker, Task # Feature selection + linear regression training and validation toolkit class ParallelTrainer(BaseTrainer): def __init__(self, x, ...
nilq/baby-python
python
from stack_and_queue.stack_and_queue import Node, Stack, PseudoQueue import pytest
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from pyup.updates import Update, RequirementUpdate, InitialUpdate, SequentialUpdate, ScheduledUpdate from unittest import TestCase from pyup.requirements import RequirementFile from pyup.errors import UnsupportedScheduleErr...
nilq/baby-python
python
""" Generates JSON file that composes the game interactions """ import json, os, errno, random from queue import * from collections import defaultdict from generation.world import ATTRIBUTES, OBJECT_TYPES, ITEMS, ROOMS, OUTSIDE, LOWER_FLOORS from generation.notes import Notes from generation.event import Event def wri...
nilq/baby-python
python
# -*- coding: utf-8 -*- """An HTTP server as training storage browser.""" from .cli import * from .server import * from .snapshot import *
nilq/baby-python
python
from .base import BaseComponent class KojiBuilder(BaseComponent): componentName = "koji_builder" deploymentConfigName = "koji-builder" def create_build(self): self.state.apply_object_from_template( "general/imagestream.yml", imagename="koji-builder", ) self...
nilq/baby-python
python
from django.db import models class Page(models.Model): title = models.CharField(max_length=255) path = models.SlugField(unique=True) body = models.TextField()
nilq/baby-python
python
# coding=utf8 """ @author: Yantong Lai @date: 09/26/2019 @code description: It is a Python3 file to implement cosine similarity with TF-IDF and Word Embedding methods. """ from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwi...
nilq/baby-python
python
import datetime import os if __name__ == '__main__': # 列出当前目录文件文件夹 files = [file for file in os.listdir('.')] print(files) # 操作系统 print(os.name) # print(os.uname().__str__()) # 环境变量 path=os.environ.get('path') print('path is: ',path) defaultEnv=os.environ.get('test','test') ...
nilq/baby-python
python
'''Expcontrol functionality that depends on psychopy.''' import collections import numpy import psychopy.core import psychopy.visual import psychopy.logging import psychopy.event from psychopy.hardware.emulator import SyncGenerator class Clock(object): ''' Time-keeping functionality for expcontrol by wrapping ...
nilq/baby-python
python
class CEPlayground(): pass def main(): return 0
nilq/baby-python
python
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, in_data, out_attributes, user_options, num_cores, outfile): import StringIO import arrayio from genomicode import arrayplatf...
nilq/baby-python
python
import pathlib import setuptools # The directory containing this file TOPLEVEL_DIR = pathlib.Path(__file__).parent.absolute() ABOUT_FILE = TOPLEVEL_DIR / "pokejdr" / "_version.py" README = TOPLEVEL_DIR / "README.md" # Information on the omc3 package ABOUT_POKEJDR: dict = {} with ABOUT_FILE.open("r") as f: exec(f...
nilq/baby-python
python
# !/usr/bin/python3 # -*- coding: utf-8 -*- # https://stackoverflow.com/a/11236372/1576803 import datetime import pytz def get_hora_feliz_dia(): tz = pytz.timezone("America/Argentina/Buenos_Aires") now = datetime.datetime.now(tz).date() midnight = tz.localize(datetime.datetime.combine(now, datetime.time...
nilq/baby-python
python
#!/usr/bin/env python #-*- coding:utf-8 -*- """ disable highlight focused widget Tested environment: Mac OS X 10.6.8 http://stackoverflow.com/questions/1987546/qt4-stylesheets-and-focus-rect """ import sys try: from PySide import QtCore from PySide import QtGui except ImportError: from PyQt4 import Q...
nilq/baby-python
python
#!/usr/bin/env python import mysql.connector from mysql.connector import errorcode from ConfigParser import SafeConfigParser __author__ = 'catalyst256' __copyright__ = 'Copyright 2014, Honeymalt Project' __credits__ = [] __license__ = 'GPL' __version__ = '0.1' __maintainer__ = 'catalyst256' __email__ = 'catalyst256@...
nilq/baby-python
python
#!/usr/bin/env python3 import sys,os,io,base64 import pandas as pd import psycopg2,psycopg2.extras DBHOST = "localhost" DBPORT = 5432 DBNAME = "refmet" DBUSR = "www" DBPW = "foobar" dsn = (f"host='{DBHOST}' port='{DBPORT}' dbname='{DBNAME}' user='{DBUSR}' password='{DBPW}'") dbcon = psycopg2.connect(dsn) #dbcon.curs...
nilq/baby-python
python
""" Reading and Writing of meteorological data """ def __clean_HDF5_PLUGIN_PATH(): """ if the libraries from hdf5plugin are in HDF5_PLUGIN_PATH, then remove them """ import os import logging if "HDF5_PLUGIN_PATH" in os.environ: paths = os.environ["HDF5_PLUGIN_PATH"].split(":") k...
nilq/baby-python
python
from enum import Enum from aoc2019.shared.intcode import IntCode class Direction(Enum): NORTH = 1 SOUTH = 2 WEST = 3 EAST = 4 class MoveResult(Enum): WALL = 0 SUCCESS = 1 OXYGEN_SYSTEM = 2 def calculateMinutesToFullOxygen(oxygenSystemLocation, shipMap): currentMinute = 0 oxygen...
nilq/baby-python
python
''' Created on 19 okt. 2013 @author: Juice ''' from constraints.constraint import Constraint class NonogramConstraint(Constraint): def __init__(self, group, initialValues): super(NonogramConstraint, self).__init__(group, initialValues) # def notify(self, cell): # pass def setAd...
nilq/baby-python
python
from typing import Dict, Union import pyomo.environ as pyo from oogeso import dto from oogeso.core.devices.base import Device class HeatPump(Device): """ Heat pump or electric heater (el to heat) """ carrier_in = ["el"] carrier_out = ["heat"] serial = [] def __init__( self, ...
nilq/baby-python
python
__all__ = ["Assembly", "Collection", "Extraction", "GetSubs", "Jelly", "QFix", "Setup", "Stages", "Support"]
nilq/baby-python
python
from dataclasses import dataclass from collections import Counter from math import ceil from queue import Queue from typing import Dict from aocd import data @dataclass class Recipe: output_reagent: str output_amount: int inputs: Counter def __repr__(self): return f"{self.inputs} => {self.ou...
nilq/baby-python
python
#!/usr/bin/env python from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_auth_client from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import h...
nilq/baby-python
python
import os import gzip import pickle import h5py import numpy as np import theano from utils.misc import get_file_names_in_dir from utils.vocab import UNK class Loader(object): def __init__(self, argv): self.argv = argv def load(self, **kwargs): raise NotImplementedError @staticmethod ...
nilq/baby-python
python
from unittest2 import TestCase from os import chdir, pardir, environ from os.path import join, dirname, exists from shutil import rmtree, copyfile from subprocess import check_call, PIPE, STDOUT, CalledProcessError #, check_output import sys from tempfile import mkdtemp from .venvtest import VirtualenvTestCase class...
nilq/baby-python
python
from django.db import transaction from django.db.models.functions import Lower from record_label.models import Band, BandLabel, MusicFestival, RecordLabel from record_label.serializers import RecordLabelSerializer def restructure_data(festivals_api_data): """A helper function to restructure the data from the fes...
nilq/baby-python
python
# visualize the networkx DiGraph using a Dash dashboard # General warning: Note that with this dashboard, the edge arrows drawn are infact symmetrical and angled correctly. # And are all the same distance/size they just don't always look that way because the scaling of the x-axis # isn't the same scaling of the y-axi...
nilq/baby-python
python
#!/usr/bin/python import sys from socket import socket, AF_INET, SOCK_STREAM import pymouse import time import numpy as np import matplotlib.pyplot as plt def main(): if len(sys.argv) != 3: print "\nusage : python tcp_client.py #host #port\n" else: host = sys.argv[1] port = int(sys.argv[2]) s = socket(AF_I...
nilq/baby-python
python
"""Test the particle swarm optimisation class""" import copy import pytest import numpy as np from pracopt.optimiser import ParticleSwarm from pracopt.objective import Shubert, ObjectiveTest from pracopt.utils import evaluate # PSO with test objective functions @pytest.fixture def new_test_pso(): """Return a new i...
nilq/baby-python
python
import untangle import os from os.path import join class DroneCommandParser: def __init__(self): # store the commandsandsensors as they are called so you don't have to parse each time self.command_tuple_cache = dict() # parse the command files from XML (so we don't have to store ids and ca...
nilq/baby-python
python
import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import SGD from keras.utils import np_utils import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf batch_size = 1...
nilq/baby-python
python
''' Created on Aug 9, 2018 @author: fan Generate mean, and variance covariance of key state variables from data ''' import logging import numpy as np logger = logging.getLogger(__name__) def gen_mean(df, mean_var_list, short_mean_var_list=None, group_by_var_list=None, conditi...
nilq/baby-python
python
# Example module - finance.py __all__ = ['tax1', 'tax2'] #defines the names to import when '*' is used tax1 = 5 tax2 = 10 def cost(): return 'cost' # Imported into code using from finance import * print tax1 print tax2
nilq/baby-python
python
class Image: def __init__(self, source_ref, image_shape, class_map=None, instance_nb=0, scene_type=None, weather_condition=None, distractor=None): """ :param source_ref: :pa...
nilq/baby-python
python
# This program launches Google in the browser using text from the cmd or clipboard # 1. Figure out the URL # The website I want to go on is formatted like this https://google.com/search?q= # 2. Handle the command line arguments import webbrowser, sys import pyperclip if len(sys.argv) > 1: # Get addre...
nilq/baby-python
python
from django.db import models from django.utils import simplejson as json from jsonate.utils import jsonate from jsonate.widgets import JsonateWidget from jsonate.form_fields import JsonateFormField class JsonateField(models.TextField): __metaclass__ = models.SubfieldBase def to_python(self, value): if...
nilq/baby-python
python
import re def is_valid_name(name): regex = re.compile(r"^(?!_$)(?![-])(?!.*[_-]{2})[a-z0-9_-]+(?<![-])$", re.X) if not re.match(regex, name): return False return True
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Setup file for automatic installation and distribution of AMfe. Run: 'python setup.py sdist' for Source Distribution Run: 'python setup.py install' for Installation Run: 'python setup.py bdist_wheel' for Building Binary-Wheel (recommended for windows-distributions) Attention: For eve...
nilq/baby-python
python
""" Cli Copyright (C) 2021 Netpro Project RepoSync """ import logging import socket from pathlib import Path import click from .client import Client from .core_op import apply as core_apply from .core_op import fop from .core_op import show as core_show from .server import Server logging.basicConfig() _LOG = loggin...
nilq/baby-python
python
# Generated by Django 2.0.4 on 2019-03-27 12:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('protein', '0005_proteingproteinpair_g_protein_subunit'), ] operations = [ migrations.RemoveField( model_name='proteinconformation', ...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 """ Created by 'bens3' on 2013-06-21. Copyright (c) 2013 'bens3'. All rights reserved. """ import pylons def is_ldap_user(): """ Help function for determining if current user is LDAP user @return: boolean """ return 'ckanext-ldap-user' in pylons.session
nilq/baby-python
python
import os LOG_FILE_PATH = os.path.join(os.getcwd(), "log.log") DATABASE_PATH = os.path.join(os.getcwd(), "database.db") ICONS_PATH = os.path.join(os.getcwd(), "icons") CHAT_SETTINGS_PATH = os.path.join(os.getcwd(), "chat_settings") BOTS_TXT_PATH = os.path.join(os.getcwd(), "bots.txt") DEVICES_PATH = os.path.join(os.ge...
nilq/baby-python
python
from .enemy import Enemy from .gnat import Gnat from .laser import Laser from .player import Player from .patroller_gnat import PatrollerGnat
nilq/baby-python
python
# Copyright (C) 2009-2012 - Curtis Hovey <sinzui.is at verizon.net> # This software is licensed under the GNU General Public License version 2 # (see the file COPYING)."""Text formatting features for the edit menu.""" __all__ = [ 'FormatPlugin', ] from gettext import gettext as _ from gi.repository import G...
nilq/baby-python
python
from django.urls import path from survey import views from rest_framework import routers from rest_framework.urlpatterns import format_suffix_patterns urlpatterns=[ path('',views.index,name="index"), path('constructor/',views.Constructor,name="constructor"), path('egresados/',views.Egresados,name="egresados"), pat...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .pickleable_gpt2bpe_encoder import ( PickleableGPT2BPEEncoder, ) __all__ = [ "PickleableGPT2BPEEncoder", ]
nilq/baby-python
python
import pytest import os from click.testing import CliRunner @pytest.mark.usefixtures("session") @pytest.fixture() def cli_runner(pushd): # this will make sure we are back at `cwd` # after this test is finished pushd(os.getcwd()) yield CliRunner(mix_stderr=False)
nilq/baby-python
python
#Copyright (c) 2021 Kason Suchow import pygame import imageManager import data class BaseCard(object): def __init__(self): self.x = -500 self.y = -500 self.pos = (self.x, self.y) self.color = '' self.name = '' self.description = '' self.attack = 0 ...
nilq/baby-python
python
"""Tests for reviewboard.diffviewer.managers.DiffCommitManager.""" from __future__ import unicode_literals from dateutil.parser import parse as parse_date from kgb import SpyAgency from reviewboard.diffviewer.models import DiffCommit, DiffSet from reviewboard.testing.testcase import TestCase class DiffCommitManage...
nilq/baby-python
python
from tensorflow.keras import layers, models # (Input, Dense), (Model) from tensorflow.keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt class AE(models.Model): def __init__(self, x_nodes=784, h_dim=36): x_shape = (x_nodes,) x = layers.Input(shape=x_shape) h = l...
nilq/baby-python
python
"""Find and filter files. Supports BIDSPath objects from `mne-bids`.""" from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Sequence, Union import mne_bids from pte.filetools.filefinder_abc import DirectoryNotFoundError, FileFinder def get_filefinder( datatype: str, h...
nilq/baby-python
python
import chex import jax import jax.numpy as jnp from typing import Callable, Optional, Tuple from .moment import MomentTransform, MomentTransformClass from chex import Array, dataclass import tensorflow_probability.substrates.jax as tfp dist = tfp.distributions class UnscentedTransform(MomentTransformClass): def ...
nilq/baby-python
python
""" Core contributors is the cardinality of the smallest set of contributors whose \ total number of commits to a source code repository accounts for 80% or more of \ the total contributions. """ from pydriller import Repository def core_contributors(path_to_repo: str) -> int: """ Return the number of develo...
nilq/baby-python
python
import numpy as np from scipy.stats import pearsonr import argparse import data import logging, sys logger = logging.getLogger(__name__) logger.setLevel(10) ch = logging.StreamHandler(sys.stdout) ch.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s - %(message)s")) logger.addHandler(ch) def main(): par...
nilq/baby-python
python
from cocoa.web.main.utils import Messages as BaseMessages class Messages(BaseMessages): ChatCompleted = "Great, you reached a final offer!" ChatIncomplete = "Sorry, you weren't able to reach a deal. :(" Redirect = "Sorry, that chat did not meet our acceptance criteria." #BetterDeal = "Congratulations, ...
nilq/baby-python
python
class Book: def __init__(self, content: str): self.content = content class Formatter: def format(self, book: Book) -> str: return book.content class Printer: def get_book(self, book: Book, formatter: Formatter): formatted_book = formatter.format(book) return formatted_boo...
nilq/baby-python
python
import math import numpy as np import torch import torch.nn as nn def default_conv(in_channels, out_channels, kernel_size=3, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2), bias=bias) class MeanShift(nn.Conv2d): def __init__(self, rgb_range, rg...
nilq/baby-python
python
from calendar import timegm from datetime import datetime, timedelta import jwt import pytest from oauthlib.oauth2 import ( InvalidClientError, InvalidGrantError, InvalidRequestFatalError, ) from h.services.oauth._errors import ( InvalidJWTGrantTokenClaimError, MissingJWTGrantTokenClaimError, ) fr...
nilq/baby-python
python
import logging from django.core.management import BaseCommand from oldp.apps.laws.models import LawBook LAW_BOOK_ORDER = { 'bgb': 10, 'agg': 9, 'bafog': 9, } # Get an instance of a logger logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Assign predefined order values to la...
nilq/baby-python
python
# -*- coding: utf-8 -*- from faker.providers import BaseProvider class CustomProvider(BaseProvider): sentences = ( 'Hello world', 'Hi there', 'Ciao Bello', ) def greeting(self): return self.random_element(self.sentences)
nilq/baby-python
python
from dcgan import * from resnet import *
nilq/baby-python
python
import socket, os, json, tqdm import shutil SERVER_PORT = 8800 SERVER_HOST = "0.0.0.0" BUFFER_SIZE = 1024 root_dir = "/home/hussein/dfs_dir" def connect_to_name_server(sock, command, name_server): print(f"[+] Connecting to {name_server[0]}:{name_server[1]}") sock.connect(name_server) print("[+] Connecte...
nilq/baby-python
python
from rest_framework import serializers, status from rest_framework.exceptions import APIException from projects.serializers.base_serializers import ProjectReferenceWithMemberSerializer from users.serializers import UserSerializer from teams.serializers import TeamSerializer from teams.models import Team from .base_seri...
nilq/baby-python
python
from django.conf import settings from django.urls import include, path, re_path from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from django.views import defaults as default_views # CVAT engine.urls is redirecting 'unknown url' to /dashboard/ whi...
nilq/baby-python
python
# -*- coding:utf-8 -*- import re def parse(s): l = re.sub(r'\s+', ', ', (' '+s.lower()+' ').replace('(', '[').replace(')', ']'))[2:-2] return eval(re.sub(r'(?P<symbol>[\w#%\\/^*+_\|~<>?!:-]+)', lambda m : '"%s"' % m.group('symbol'), l)) def cons(a, d): if atom(d): return (a, d) return (lambda...
nilq/baby-python
python
from flatland.envs.agent_utils import RailAgentStatus from flatland.envs.malfunction_generators import malfunction_from_params from flatland.envs.observations import GlobalObsForRailEnv from flatland.envs.rail_env import RailEnv from flatland.envs.rail_generators import sparse_rail_generator from flatland.envs.schedule...
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 # distribu...
nilq/baby-python
python
# Generated by Django 3.2.12 on 2022-03-31 23:23 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='LFPost', fields=[ ('id', m...
nilq/baby-python
python
from hamcrest import * from utils import * from vinyldns_context import VinylDNSTestContext from vinyldns_python import VinylDNSClient class ListGroupsTestContext(object): def __init__(self): self.client = VinylDNSClient(VinylDNSTestContext.vinyldns_url, access_key='listGroupAccessKey', ...
nilq/baby-python
python
#!/usr/bin/env python3 # Hackish script to automatically generate some parts of JSON file required for android-prepare-vendor # Requires 4 arguments: # (1) device name # (2) module-info.json from build (3) below, can be found under out/target/product/<device>/module-info.json # (3) listing of extracted files from a bu...
nilq/baby-python
python
import csv from math import * class Point: def __init__(self, x, y, z, mag=0): self.x = x self.y = y self.z = z self.mag = mag class Polar: def __init__(self, r, theta, vphi, mag=0): self.r = r self.theta = theta # 0 < theta < pi self.vphi = vphi # -pi < vphi < pi self.mag = mag def get_polar_...
nilq/baby-python
python
""" The MIT License (MIT) Copyright (c) 2014 NTHUOJ team 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, ...
nilq/baby-python
python
from tests.utils import W3CTestCase class TestBottomOffsetPercentage(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'bottom-offset-percentage-'))
nilq/baby-python
python
from collections import defaultdict def top_3_words(text): text = text.lower().strip(',').strip('.').strip('"') print(text) counter = defaultdict(int) for word in text.split(): counter[word] += 1 return sorted( counter.keys(), reverse=True, key = lambda item : counte...
nilq/baby-python
python
# Q. Take input from the user to get fibonacci series till the number entered # Ex - input:3 # Ouput: 0, 1, 1 nterms = int(input("How many terms do you want? ")) # first two terms n1, n2 = 0, 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") # if there i...
nilq/baby-python
python