content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from typing import Any, AsyncGenerator from dependency_injector.wiring import Provide, inject from graphql import GraphQLResolveInfo from containers import SDContainer from models import OnPathway from .subscription_type import subscription @subscription.source("onPathwayUpdated") @inject async def on_pathway_updated...
nilq/baby-python
python
import sys import tableauserverclient as TSC rob = TSC.RequestOptions.Builder() ro = rob.file("==", "MyFile").project("==", "Default")._sort("foo", "desc")._pagesize(50)._build() print ro.filters
nilq/baby-python
python
# -*- coding: utf-8 -*- # Detect tissue regions in a whole slide image. ############################################################################# # Copyright Vlad Popovici <popovici@bioxlab.org> # # Licensed under the MIT License. See LICENSE file in root folder. #################################################...
nilq/baby-python
python
numbers = [] posbetter = [] poslower = [] for c in range(0, 5): numbers.append(float(input('Type a number: '))) for pos, value in enumerate(numbers): if value == max(numbers): posbetter.append(pos) if value == min(numbers): poslower.append(pos) print(f'The better number typed was {max(number...
nilq/baby-python
python
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import statsmodels.formula.api as smf import statsmodels.api as sm import pickle #df = pd.read_pickle('sav.txt') X = pd.read_pickl...
nilq/baby-python
python
from numbers import Number import numpy as np import sympy from collections.abc import Mapping from sympy import Symbol from sympy.core.relational import Relational from toy.unit import DIMENSIONLESS, parse_unit_msg from toy.utils import as_dict, is_numeric from toy.core.value import Value base_model = None class ...
nilq/baby-python
python
import cv2 import time import csv import os import picamera import picamera.array import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(36, GPIO.OUT) GPIO.setup(33, GPIO.OUT) GPIO.setup(10, GPIO.OUT) GPIO.setup(11, GPIO.OUT) def gpio_fun(): val = "" if GPIO.input(36) == 1: ## ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Module with utility functions to call the GPT translation API""" import json import requests # ============================================================================== # CONSTANT DEFINITION # ============================================================================== API_EXCEPTIO...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 14:33:34 2019 """ import os def walklevel(some_dir, level=1): some_dir = some_dir.rstrip(os.path.sep) assert os.path.isdir(some_dir) num_sep = some_dir.count(os.path.sep) for root, dirs, files in os.walk(some_dir): yield root, dirs,...
nilq/baby-python
python
import urequests class InfluxDBClient(): def __init__(self,url, token, org, bucket): self.url=url self.token=token self.org=org self.params={"bucket":bucket ,"org":org} self.headers={"Authorization":"Token {}".format(token)} self.conveq=lambda x: ["{}={}".format(k,v)...
nilq/baby-python
python
''' Calculate astrometric motion of star over given time frame using JPL Horizons ephermerides and SIMBAD proper motion and parallax ''' from __future__ import print_function import matplotlib matplotlib.use('agg') import csv import jplephem import de421 from jplephem.spk import SPK kernel = SPK.open('de430.bsp') imp...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ @Project : activationFunction @Author : Xu-Shan Zhao @Filename: activationFunction202003121138.py @IDE : PyCharm @Time1 : 2020-03-12 11:38:55 @Time2 : 2020/3/12 11:38 @Month1 : 3月 @Month2 : 三月 """ import torch import matplotlib.pyplot as plt x_data = torch.arange(-6, 6, 0.01) y_...
nilq/baby-python
python
with open('day1_input.txt') as file: input = file.read() # Part 1 sum = 0 for i in range(len(input) - 1): if input[i] == input[i + 1]: sum += int(input[i]) if input[len(input) - 1] == input[0]: sum += int(input[0]) print(sum) # Part 2 sum = 0 forward = len(input) / 2 for i in range(forward): ...
nilq/baby-python
python
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import pytest from datadog_checks.dev.testing import requires_py3 from ..utils import get_check pytestmark = [ requires_py3, pytest.mark.openmetrics, pytest.mark.openmetrics_transformers, ...
nilq/baby-python
python
# CSV to JSON # 1. run the following from the root of project directory: `cd data/achievements; python3 achievements-gen.py` # 2. commit and push changes # 3. website will automatically update import csv, json with open("./achievements.csv", encoding='utf-8', mode='r') as fin: with open("./achievements.json", mode=...
nilq/baby-python
python
""" CODE ADAPTED FROM: https://github.com/sjblim/rmsn_nips_2018 Treatment Effects with RNNs: Common routines to use across all training scripts """ import logging import numpy as np import pandas as pd import tensorflow as tf import treatments.RMSN.configs import treatments.RMSN.libs.net_helpers as helpers from t...
nilq/baby-python
python
##################################### # ColumnRelationships.py ##################################### # Description: # * Map all relationships between columns. from abc import abstractmethod, ABC from enum import Enum from itertools import combinations, product import numpy as np from pandas import DataFrame from sorte...
nilq/baby-python
python
from collections import OrderedDict from elasticsearch.exceptions import RequestError from elasticsearch_dsl import Search import settings from core.cursor import decode_cursor, get_next_cursor from core.exceptions import (APIPaginationError, APIQueryParamsError, APISearchError) from core...
nilq/baby-python
python
from setuptools import setup, find_packages import sys import platform # python version check python_min_version = (3, 6, 2) python_min_version_str = '.'.join(map(str, python_min_version)) if sys.version_info < python_min_version: print( f"You are using Python {platform.python_version()}. At least Python >...
nilq/baby-python
python
import pytest from spacy.lang.ja import Japanese def test_ja_morphologizer_factory(): pytest.importorskip("sudachipy") nlp = Japanese() morphologizer = nlp.add_pipe("morphologizer") assert morphologizer.cfg["extend"] is True
nilq/baby-python
python
from base import CodeTyper, SNIPPETS_ROOT, COMMAND import panel as pn pn.extension(sizing_mode="stretch_width") CodeTyper( title="# Cross Filtering with hvPlot, Holoviews and PANEL", value=SNIPPETS_ROOT/"holoviews_linked_brushing_app.py", command="$ pip install panel holoviews hvplot shapely\n" + ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2008, Frank Scholz <coherence@beebits.net> ''' Transcoder classes to be used in combination with a Coherence MediaServer, using GStreamer pipelines for the actually work and feeding the output into a...
nilq/baby-python
python
import posix_ipc import utils params = utils.read_params() try: posix_ipc.unlink_message_queue(params["MESSAGE_QUEUE_NAME"]) s = "message queue %s removed" % params["MESSAGE_QUEUE_NAME"] print (s) except: print ("queue doesn't need cleanup") print ("\nAll clean!")
nilq/baby-python
python
import keywords as kw import pca_tsne as pt import math import re import numpy as np from collections import Counter from sklearn.cluster import KMeans def conventional_kmeans(data, tfidf, kmeans_size_keywords, k): matrix = tfidf.fit_transform(data.setting_value) fit = KMeans(n_clusters=k, random_state=20)....
nilq/baby-python
python
from yunionclient.common import base class CdnDomain(base.ResourceBase): pass class CdnDomainManager(base.StandaloneManager): resource_class = CdnDomain keyword = 'cdn_domain' keyword_plural = 'cdn_domains' _columns = ["ID", "Name", "Status", "Cloudaccount_id", "External_id", "Cname", "Origins", "...
nilq/baby-python
python
import simplejson import urllib2 import feedparser import logging from datetime import timedelta from django.http import Http404, HttpResponse from django.template import loader, TemplateDoesNotExist, RequestContext from django.shortcuts import render_to_response from django.core.cache import cache from molly.utils.v...
nilq/baby-python
python
from rpy import r import os.path # find out where the temp directory is tempdir = r.tempdir() # write its name into a file f = open('tempdir','w') f.write(tempdir) f.close() # put something there.. r.postscript(os.path.join(tempdir,"foo.ps")) r.plot(1,1) r.dev_off()
nilq/baby-python
python
import os from math import ceil from fastapi import FastAPI, Form from fastapi.responses import FileResponse from fastapi.middleware.cors import CORSMiddleware from app.aws_s3 import S3 from app.mongo import MongoDB API = FastAPI( title='DocDB DS API', version="1.0.0", docs_url='/', ) API.db = MongoDB() ...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Analyse des efforts statiques dans un treillis (assemblage de barres et de pivots) Le problème est traité en 2D (dans un plan) Pierre Haessig — Mars 2013 """ from __future__ import division, print_function, unicode_literals import numpy as np import matplotlib.pyplot as p...
nilq/baby-python
python
import logging from datetime import datetime from enum import Enum import ntplib from scapy.layers.ntp import NTPHeader from ntp_raw import RawNTP _PCK_1_YEAR = 1995 _PCK_2_YEAR = 2000 class CP3Mode(Enum): """ In CP3 an NTP package can be marked as a type 1, or 2 package or as nothing. This class represent...
nilq/baby-python
python
from helusers.oidc import ApiTokenAuthentication as HelApiTokenAuth from django.conf import settings class ApiTokenAuthentication(HelApiTokenAuth): def __init__(self, *args, **kwargs): super(ApiTokenAuthentication, self).__init__(*args, **kwargs) def authenticate(self, request): jwt_value = se...
nilq/baby-python
python
from inquire_sql_backend.semantics.embeddings.vector_models import VECTOR_EMBEDDERS def vector_embed_sentence(sent, tokenized=False, model="default"): embed_func = VECTOR_EMBEDDERS[model] return embed_func(sent, batch=False, tokenized=tokenized) def vector_embed_sentence_batch(sent, tokenized=False, model="...
nilq/baby-python
python
import torch.nn as nn import torch from .conv2d_repeat import Conv2dRepeat def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __ini...
nilq/baby-python
python
from flask import Blueprint socket_client = Blueprint('socket_client', __name__) from . import events
nilq/baby-python
python
from rest_framework import serializers from puzzle.models import Offer class OfferSerializer(serializers.ModelSerializer): author_name = serializers.CharField( source="author.user.username", read_only=True) class Meta: model = Offer fields = ["id", "author_name", "created", ...
nilq/baby-python
python
"""Collection of PBM-based click simulators.""" from typing import Optional from typing import Tuple import torch as _torch from pytorchltr.utils import mask_padded_values as _mask_padded_values _SIM_RETURN_TYPE = Tuple[_torch.LongTensor, _torch.FloatTensor] def simulate_pbm(rankings: _torch.LongTensor, ys: _torch...
nilq/baby-python
python
import ila import riscv_um def genVlg(): rm = riscv_um.riscvModel() rm.loadUnprivNxtFromDir('unpriv_asts') rm.model.generateVerilog('RISC-V-VLG.v') if __name__ == '__main__': genVlg()
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # 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 requi...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # In[ ]: #import libraries import string import ast from itertools import islice import csv from nltk.tokenize import RegexpTokenizer def createTsvFile_Search1(listUrl_Movies3): #create tsv file in 'tsv_correct' directory wehere we have preprocessed the tsv file (just creat...
nilq/baby-python
python
from django import template from classytags.core import Options from classytags.helpers import AsTag from classytags.arguments import Argument from ..models import CallToActionRepository class GetCallToAction(AsTag): name = 'get_call_to_action' options = Options( Argument('code', required=True), ...
nilq/baby-python
python
import json def get_list(): with open("config.json", "r") as f_obj: f_json = json.load(f_obj) return f_json def get_lang(item): return get_list()[item] def set_lang(item, lang): with open("list_lang.json", "r") as f_obj: list_lang = json.load(f_obj) if not (lang in list_lan...
nilq/baby-python
python
import os import os.path as osp import copy import yaml import numpy as np from ast import literal_eval from utils.collections import AttrDict __C = AttrDict() cfg = __C # ---------------------------------------------------------------------------- # # MISC options # -------------------------------------------------...
nilq/baby-python
python
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external") def rules_clojure_dependencies(): jvm_maven_import_external( name = "org_clojure", artifact = "org.clojure:clojure:1.10.1", artifact_sha256 = "d4f6f991fd9ed2a59e7ea4779010b3b069a2b905f3463136c42201106b4ad21a", ...
nilq/baby-python
python
from django.apps import AppConfig class ApacheKafkaConfig(AppConfig): name = 'apache_kafka'
nilq/baby-python
python
import click from neobox.cmd.list import list_ from neobox.cmd.clear_cache import clear_cache from neobox.cmd.login import login from neobox.cmd.logout import logout from neobox.cmd.search import search from neobox.cmd.play import play from neobox.cmd.pause import pause from neobox.cmd.stop import stop @click.group(...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author : yasin # @time : 18-12-28 下午9:28 # @File : config.py import logging.config logging.config.fileConfig("logger.conf") logger = logging.getLogger("novel-update-monitor-account") bindIp = '0.0.0.0' bindPort = 12126 token = 'VqmB965wOEBrPLNoMkHCfIOpxF0WWFM6' g...
nilq/baby-python
python
"""User profile model""" # Django from django.db import models # Utilities from mydea.utils.models import MyDeaModel class Profile(MyDeaModel): """Profile model. A profile holds a user's data""" # user user = models.OneToOneField('users.User', on_delete=models.CASCADE) def __str__(self): ...
nilq/baby-python
python
#---------------------------------------------------------------------- # Deep learning for classification for contrast CT; # Transfer learning using Google Inception V3; #------------------------------------------------------------------------------------------- import os import numpy as np import pandas as pd import...
nilq/baby-python
python
import os from time import time import krgram.tl.protocol import krgram.tl.protocol.auth from krgram.client.crypto import TLEncryptor from krgram.client.errors import SecurityError from krgram.mtproto.connection import MTProtoAbridgedConnection from krgram.mtproto.dcs import DataCenters from krgram.mtproto.errors impo...
nilq/baby-python
python
import sqlalchemy from pydantic import BaseModel from .model import Base class Category(BaseModel): """""" name: str color: str class CategoryTable(Base): __tablename__ = "category" name = sqlalchemy.Column(sqlalchemy.String, primary_key=True) color = sqlalchemy.Column(sqlalchemy.String) ...
nilq/baby-python
python
#!/usr/bin/env python3 import sys import gzip import ast import json class Dumper: def __init__(self, path): self.path = path self.open_file = {} def close_all(self): #close previous file(s) for name in self.open_file: self.open_file[name].close() self.open...
nilq/baby-python
python
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # 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 th...
nilq/baby-python
python
import os class Config: title = 'VocView' # URL root of this web application. This gets set in the before_first_request function. url_root = None # Subdirectory of base URL. Example, the '/corveg' part of 'vocabs.tern.org.au/corveg' SUB_URL = '' # Path of the application's directory. AP...
nilq/baby-python
python
list1=['car','ara','cabc'] c=0 for i in list1: a=list1 if( c=c+1 print(c)
nilq/baby-python
python
import pyeccodes.accessors as _ def load(h): h.add(_.Unsigned('n2', 2)) h.add(_.Unsigned('n3', 2)) h.add(_.Unsigned('nd', 3)) h.alias('numberOfDiamonds', 'nd') h.alias('Nj', 'nd') h.add(_.Unsigned('Ni', 3)) h.add(_.Codeflag('numberingOrderOfDiamonds', 1, "grib1/grid.192.78.3.9.table")) ...
nilq/baby-python
python
import struct from io import BytesIO p8 = lambda x:struct.pack("<B", x) u8 = lambda x:struct.unpack("<B", x)[0] p16 = lambda x:struct.pack("<H", x) u16 = lambda x:struct.unpack("<H", x)[0] p32 = lambda x:struct.pack("<I", x) u32 = lambda x:struct.unpack("<I", x)[0] p64 = lambda x:struct.pack("<Q", x) u64 = lambda x...
nilq/baby-python
python
from sacnn.core.we import get_word_to_vector word_to_vector, WORD_DIMENSION = get_word_to_vector()
nilq/baby-python
python
from __future__ import annotations import collections import copy import json import logging import operator import os from typing import Any, Dict, List, Optional, Tuple import joblib from poker_ai import utils from poker_ai.poker.card import Card from poker_ai.poker.engine import PokerEngine from poker_ai.games.sh...
nilq/baby-python
python
import json class SwearWords(object): def __init__(self): self.data = json.load(open('data.json')) def filter_words(self,text,symbol="*"): text = text.split() print(text) for i in range(len(text)): if text[i] in self.data['word']: text[i] = symbol * ...
nilq/baby-python
python
import RPi.GPIO as GPIO led_pin = 29 button_pin = 40 buzzer_pin = 31 GPIO.setmode(GPIO.BOARD) GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setup(led_pin, GPIO.OUT) GPIO.setup(buzzer_pin, GPIO.OUT) while True: if GPIO.input(button_pin) == GPIO.HIGH: GPIO.output(led_pin, True) GPIO.output(buz...
nilq/baby-python
python
""" MIT License Copyright (c) 2021 isaa-ctaylor 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, publish, ...
nilq/baby-python
python
""" The Importer feature sets up the ability to work with cuneiform text(s) one-on-one, whether it is the Code of Hammurabi, a collection of texts such as ARM01, or whatever your research desires. This cdli_corpus module is for working with text files having already been read by file_importer. The file_lines required ...
nilq/baby-python
python
# Copyright (c) 2016-2018, Neil Booth # # All rights reserved. # # See the file "LICENCE" for information about the copyright # and warranty status of this software. import asyncio import pylru from aiorpcx import run_in_thread from electrumx.lib.hash import hash_to_hex_str class ChainState(object): '''Used a...
nilq/baby-python
python
import sys from secret import FLAG, REGISTER, TAPS assert FLAG.startswith('flag') assert len(REGISTER) == 16 assert len(TAPS) == 5 class LFSR: def __init__(self, register, taps): self.register = register self.taps = taps def next(self): new = 0 ret = self.register[0] ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # External import import pytest from numpy import array, pi from os.path import join from multiprocessing import cpu_count # Pyleecan import from pyleecan.Classes.ImportGenVectLin import ImportGenVectLin from pyleecan.Classes.ImportMatrixVal import ImportMatrixVal from pyleecan.Classes.Simu1 i...
nilq/baby-python
python
#!/usr/bin/env python3 """SERVICE YET TO BE IMPLEMENTED. THIS FILE IS JUST A PLACEHOLDER.""" print("Sorry! This service has not yet been implemented\n(will you be the one to take care of it?\n --- RIGHT NOW THIS FILE IS JUST AN HANDY PLACEHOLDER ---")
nilq/baby-python
python
# Copyright 2020, The TensorFlow Federated 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 by applicable law o...
nilq/baby-python
python
# Generated by Django 2.1.3 on 2018-11-09 05:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('restapi', '0010_annotatedrecording_recitation_mode'), ] operations = [ migrations.CreateModel( name='TajweedInformation', ...
nilq/baby-python
python
# MIT License # # Copyright (c) 2021 TrigonDev # # 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, pu...
nilq/baby-python
python
import torch from numpy import histogram, random from scipy.stats import skewnorm from torch import Tensor, from_numpy from torch.nn.functional import softmax class WGAN: def __init__(self) -> None: super().__init__() def discriminator_loss(self, real_scores: Tensor, fake_scores: Tensor) -> Tensor: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-01 13:53 from __future__ import unicode_literals import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0003_auto_20170801_1819'), ] operations = [...
nilq/baby-python
python
import pytest from pathlib import Path from coolcmp.cmp.source_code import * from unit_tests.utils import run_test_codegen tests = [] with open('unit_tests/compiled_files.txt') as f: for line in f: tests.append(Path(line.rstrip()).resolve()) @pytest.mark.complete @pytest.mark.parametrize('file', tests, i...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' from common.log import logger from common.globalvar import db_related_to_project_dic from unittesttestcase import MyUnittestTestCase __all__ = ['DBUnittestTestCase'] class DBUnittestTestCase(MyUnittestTestCase): def test_select_one_record(self)...
nilq/baby-python
python
""" Simple HTTP Server with GET that waits for given seconds. """ from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import time ENCODING = 'utf-8' class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): """Simple multi-threaded HTTP Server.""" pass class MyR...
nilq/baby-python
python
from .regressor import CrossLgbRegression
nilq/baby-python
python
from django.urls import path, include from django.contrib import admin from django.contrib.auth import views as auth_views admin.autodiscover() import autobot.views # To add a new path, first import the app: # import blog # # Then add the new path: # path('blog/', blog.urls, name="blog") # # Learn more here: https:/...
nilq/baby-python
python
# This imports all that is listed in __init__.py of current directory: from __init__ import * #-------------------------------------------------------------------------------------- MAIN WINDOW CLASS ----------------------------------------------------------------------------------# class Window(QtGui.QMainWindow): ...
nilq/baby-python
python
import os # Database connection setup class Config(object): SERVER = '' DATABASE = '' DRIVER = '' USERNAME = '' PASSWORD = '' SQLALCHEMY_DATABASE_URI = f'mssql+pyodbc://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}' SQLALCHEMY_TRACK_MODIFICATIONS = False DEBUG = True S...
nilq/baby-python
python
import os import sys filename = __file__[:-5] + '-input' with open(filename) as f: lines = f.read().splitlines() lines = list(map(lambda s: s.split('-'), lines)) connections = {} for line in lines: if line[0] not in connections and line[1] != 'start' and line[0] != 'end': connections[line[0]] =...
nilq/baby-python
python
import numpy as np from . InverterException import InverterException from . InputData import InputData class Image(InputData): """ This class represents a camera image and can be used as input to the various inversion algorithms. Images can be created directly, or by importing and filtering a video. ...
nilq/baby-python
python
"""Support for Avanaza Stock sensor."""
nilq/baby-python
python
import os import re import codecs def isValidLine(line): if re.search('include \"', line) == None or line.find('.PSVita') != -1 or line.find('.PS4') != -1 or line.find('.Switch') != -1 or line.find('.XBoxOne') != -1: return True return False class CreateHeader: def __init__(self): self.lines = [] def addLine...
nilq/baby-python
python
from __future__ import annotations from typing import List, Tuple import ujson import os.path as path import stargazing.pomodoro.pomodoro_controller as pomo_pc CONFIG_FILE_PATH = f"{path.dirname(path.abspath(__file__))}/../config/settings.json" def get_saved_youtube_player_urls() -> List[str]: with open(CONFIG_...
nilq/baby-python
python
OUTPUT_ON = b'1' OUTPUT_OFF = b'0' OUTPUT_PULSE = b'P' OUTPUT_CURRENT = b'O' INPUT_DELTA = b'D' INPUT_CURRENT = b'C' TURNOUT_NORMAL = b'N' TURNOUT_REVERSE = b'R' IDENTIFY = b'Y' SERVO_ANGLE = b'A' SET_TURNOUT = b'T' GET_TURNOUT = b'G' CONFIG = b'F' ACKNOWLEDGE = b'!' STORE = b'W' ERRORRESPONSE = b'E' WARNINGRESPONSE = ...
nilq/baby-python
python
import tensorflow as tf # Stolen from magenta/models/shared/events_rnn_graph def make_rnn_cell(rnn_layer_sizes, dropout_keep_prob=1.0, attn_length=0, base_cell=tf.contrib.rnn.BasicLSTMCell, state_is_tuple=False): cells = [] for num_units in rnn_layer_sizes: cell = base_cell(num_units, stat...
nilq/baby-python
python
from block import Block from transaction import Transaction from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 import bitcoin class BlockChain: def __init__(self): self.chain = [] self.tx_pool = [] self.bits = 2 self.reward = 50 genesis_block = Block(None, sel...
nilq/baby-python
python
''' Nombre de archivo: +procesamientodatos.py Descripción: +Librería con funciones para el procesamiento de los datos Métodos: |--+cargar_datos |--+generar_tablas |--+almacenar_tablas ''' #librerías necesarias import sys, os, glob, datetime as dt from pyspark.sql import SparkSession, functions as F, window ...
nilq/baby-python
python
"""VIC Emergency Incidents feed entry.""" from typing import Optional, Tuple import logging import re from time import strptime import calendar from datetime import datetime import pytz from aio_geojson_client.feed_entry import FeedEntry from geojson import Feature from markdownify import markdownify from .consts impo...
nilq/baby-python
python
import networkx as nx from . import utils # ===== asexual lineage metrics ===== def get_asexual_lineage_length(lineage): """Get asexual lineage length. Will check that given lineage is an asexual lineage. Args: lineage (networkx.DiGraph): an asexual lineage Returns: length (int) of ...
nilq/baby-python
python
import tqdm from multiprocessing import Pool import logging from dsrt.config.defaults import DataConfig class Filter: def __init__(self, properties, parallel=True, config=DataConfig()): self.properties = properties self.config = config self.parallel = parallel self.init_logger() ...
nilq/baby-python
python
import os import numba import torch import torch.nn as nn from torch.optim.lr_scheduler import ReduceLROnPlateau from optimizer import * from trainer_callbacks import * from utils import * #%% #################################### Model Trainer Class #################################### class ModelTrainer(...
nilq/baby-python
python
from backend.stage import ready_stage from backend import message from backend import helpers class JobStage(ready_stage.ReadyStage): stage_type = 'Job' def __init__(self, game) -> None: super().__init__(game) self._job_selected = {} # facility selected indexed by player @classmethod ...
nilq/baby-python
python
""" Robot http server and interface handler Approach to operations: This http server module is conceptualized as a gateway between a robot, with private, internal operations, and the web. Incoming requests for actions to be executed by the robot and requests for information such as telemetry data arriv...
nilq/baby-python
python
""" How plugins work ---------------- From a user's perspective, plugins are enabled and disabled through the command line interface or through a UI. Users can also configure a plugin's behavior through the main Kolibri interface. .. note:: We have not yet written a configuration API, for now just make sure ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Base classes for Models. """ import typing as tp from uuid import UUID ModelType = tp.TypeVar("ModelType", bound='ModelBase') class Model(tp.Protocol): """ Interface for base model class. """ uid: tp.Optional[UUID] class ModelBase(object): """ Model storage ultim...
nilq/baby-python
python
# pylint doesn't know about pytest fixtures # pylint: disable=unused-argument import datetime import os import time import uuid import boto3 import pytest from dagster_k8s.test import wait_for_job_and_get_raw_logs from dagster_k8s_test_infra.integration_utils import ( can_terminate_run_over_graphql, image_pull...
nilq/baby-python
python
from __future__ import annotations import src.globe.hexasphere as hexasphere if __name__ == "__main__": hs = hexasphere.Hexsphere(50, 1, 0.8) print(hs)
nilq/baby-python
python
import itertools from matplotlib import cm import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from rllab.envs.base import Env from rllab.misc import logger from rllab.spaces import Box from rllab.spaces import Discrete from utils import flat_to_one_hot, np_seed class Discre...
nilq/baby-python
python
from distutils.core import setup import setuptools setup( name="turkishnlp", version="0.0.61", packages=['turkishnlp'], description="A python script that processes Turkish language", long_description=open('README.md', encoding="utf8").read(), long_description_content_type='text/markdown', u...
nilq/baby-python
python
"""Frontend for spectra group project""" __author__ = """Group01""" __version__ = '0.1.0'
nilq/baby-python
python