content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python3 """ Simulate 3D aggregate mixing Generate simulated aggregates that can be analyzed by `analyze_3d_aggregate_mixing.py` .. code-block:: bash $ ./simulate_3d_aggregate_mixing.py \\ --num-red 400 \\ --num-green 127 \\ --aggregate-radius 75.3 \\ --neighbor-rad...
nilq/baby-python
python
from statuscheck.services.bases._statuspageio import BaseStatusPageAPI class ServiceAPI(BaseStatusPageAPI): name = "Epic Games" domain_id = "ft308v428dv3" status_url = "https://status.epicgames.com/" service_url = "http://epicgames.com/"
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import unittest from tr55.water_quality import get_volume_of_runoff, get_pollutant_load from tr55.tables import POLLUTION_LOADS class TestWaterQuality(unittest.TestCase): def tes...
nilq/baby-python
python
import pytorch_lightning as pl class TeacherForcingAnnealCallback(pl.Callback): def __init__(self, start, end, epochs): assert start >= end self.start = start self.end = end self.epochs = epochs self.slope = float((start - end)) / epochs def on_validation_ep...
nilq/baby-python
python
import datetime import pandas as pd import io import os import boto3 from io import BytesIO from io import StringIO from airflow import DAG from airflow.providers.amazon.aws.operators.redshift_sql import RedshiftSQLOperator from airflow.operators.dummy import DummyOperator from airflow.operators.redshift_to_s3_operat...
nilq/baby-python
python
import databases import sqlalchemy import logging import os import json from fastapi import FastAPI from sqlalchemy import text logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) db_string = "postgresql://{0}:{1}@{2}/{3}".format(os.getenv("POSTGRES_USER"), ...
nilq/baby-python
python
#!/usr/bin/env python import socket import warnings import pytest from flask import _request_ctx_stack from ._internal import _determine_scope from ._internal import _make_accept_header from ._internal import _rewrite_server_name from .live_server import LiveServer @pytest.fixture def client(app): """A Flask te...
nilq/baby-python
python
from Jumpscale import j def main(self): """ to run: kosmos 'j.clients.zdb._tests_run(name="admin")' """ c = j.servers.zdb.test_instance.client_admin_get() c.reset() c.namespaces_list() assert c.namespaces_list() == ["default"] c.namespace_new("test_namespace") assert c.nam...
nilq/baby-python
python
class IdentityHashingService: def hash(self, value): return value
nilq/baby-python
python
class Solution: """ @param s: a string @param words: a list of words @return: all starting indices of substring(s) """ def findSubstring(self, s, words): # write your code here m = len(s) target = len(words) result = [] if m == 0 or target == 0: ...
nilq/baby-python
python
import requests import json import logging logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True auth_server = 'https://api.amazon.com/auth/register' alexa_user_name = 'username...
nilq/baby-python
python
#!/usr/bin/env python a = [66.25, 333, 333, 1, 1234.5] print("\na=", a) print("\na.count(333) = %d, a.count(66.25) = %d, a.count('x') = %d" % (a.count(333), a.count(66.25), a.count('x')) ) print("\na.insert(2, -1) = ", a.insert(2, -1)) print("a = ", a) print("\na.append(333) = ", a.append(333)) print("a = ", a) pr...
nilq/baby-python
python
'''The doc module provides decorator functions that will modify a functions __apidoc__ object. For example, when using `method('GET')` it will set the value of the functions method as 'get' on its __apidoc__''' from http import HTTPStatus from oapispec.core.utils import merge, not_none def doc(**kwargs): '''A d...
nilq/baby-python
python
import itertools import json from collections import defaultdict from django.core.serializers.json import DjangoJSONEncoder from .orm_lookups import get_django_filter from .query import BoundQuery from .types import ASC, DSC def _filter(qs, path_str, filter_): negation = False lookup = filter_.lookup i...
nilq/baby-python
python
""" Unit tests for \ landlab.components.vegetation_dynamics.vegetation_dynamics """ from nose.tools import assert_equal, assert_true, assert_raises, with_setup from numpy.testing import assert_array_almost_equal try: from nose.tools import assert_is_instance except ImportError: from landlab.testing.tools im...
nilq/baby-python
python
import os #We don't want to show the pygmy version and welcome message. Snif os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" from random import uniform,randint import tqdm """ We import pygame in order to create a patch for the long calculations If the QLearning calculation time or the creation of the path is t...
nilq/baby-python
python
# -*- coding: utf-8 -*- import time # from datetime import datetime, timedelta from flask import Blueprint, request, Response, abort from sqlalchemy import func, and_, or_ import os import math import ujson import logging from datetime import datetime from models import FDMEvent, FDMEventType, FDMEventGroup, DataQarSe...
nilq/baby-python
python
from typing import Tuple import requests from bs4 import BeautifulSoup from hospital_types import ( ScrapedData, AppointmentAvailability, HospitalAvailabilitySchema, ) import aiohttp, asyncio URL: str = "http://netreg.afph.tsgh.ndmctsgh.edu.tw/webreg/calendar_type/5xn1z9fPG5H4JDJEV98dHQ%3D%3D" async def...
nilq/baby-python
python
from django.contrib.auth import get_user_model from django.test import TestCase UserModel = get_user_model() class UserModelTest(TestCase): def setUp(self) -> None: self.user = UserModel.objects.create_user( email='test@abv.bg', ) self.user.set_password = '1234567890Mazen' ...
nilq/baby-python
python
#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: FCCH Bursts Detector # Author: Piotr Krysik # # Description: Detects positions of FCCH bursts. At the end of each # detected FCCH burst adds to the stream a tag with key "fcch" and value # which is a frequen...
nilq/baby-python
python
import logging def get_logger(LEVEL='info', log_file = None,name=None): head = '[%(asctime)-15s] [%(levelname)s] %(message)s' if LEVEL == 'info': logging.basicConfig(level=logging.INFO, format=head) elif LEVEL == 'debug': logging.basicConfig(level=logging.DEBUG, format=head) logger = lo...
nilq/baby-python
python
from sklearn.neighbors import KNeighborsClassifier from sklearn import datasets from sklearn.metrics import accuracy_score iris = datasets.load_iris() X, y = iris.data, iris.target knn = KNeighborsClassifier() knn.fit(X, y) accuracy_score(y, knn.predict(X))
nilq/baby-python
python
import random import discord from discord.ext import commands from .inputs import cl, cf, chill, cfe, ur from .utils import COLOR class Coffee(commands.Cog): def __init__(self, client): self.client = client @commands.command(aliases=['ask_out']) async def wannagrabacoffee(self, ctx, *, member: d...
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. import unittest import torch from mmf.common.sample import Sample from mmf.models.transformers.heads.itm import ITM from mmf.models.transformers.heads.mlm import MLM from mmf.models.transformers.heads.mlp import MLP from omegaconf import OmegaConf from tests.test_uti...
nilq/baby-python
python
import pandas as pd from sklearn.model_selection import train_test_split class DataLoader: def __init__(self): self.dataset = None self.sensor = None self.target = None def load(self,file,isTest=False): if not isTest: print("loading") self.dataset = pd.r...
nilq/baby-python
python
#!/usr/bin/env python3 import sys def isBalanced(expression): if len(expression) & 1: return False parentheses = [] for c in expression: if c == '(' or c == '{' or c == '[': parentheses.append(c) elif c == ')' or c == '}' or c == ']': offset = 1 if c == ')' else 2 if len(parent...
nilq/baby-python
python
from collections import defaultdict from dataclasses import dataclass, field from typing import Any, DefaultDict, Optional, Type, TypeVar from discord import Guild from commanderbot.lib import FromDataMixin, GuildID, JsonSerializable, LogOptions from commanderbot.lib.utils import dict_without_ellipsis, dict_without_f...
nilq/baby-python
python
from flask_restful import Resource, current_app from backend.services.campaign_service import CampaignService from backend.services.organisation_service import OrganisationService from backend.models.postgis.utils import NotFound from backend.services.users.authentication_service import token_auth class Organisation...
nilq/baby-python
python
#!/usr/bin/env python #coding: utf-8 __author__ = 'Toshihiro Kamiya <kamiya@mbj.nifty.com>' __status__ = 'experimental' import os.path import re import sys import subprocess UNIZP_COMMAND = "/usr/bin/unzip" def get_class_names_from_jar(jar_file): class_names = [] pat = re.compile(r"^\s*testing:\s*(.+)[.]cla...
nilq/baby-python
python
# Copyright 2020 Katteli Inc. # TestFlows.com Open-Source Software Testing Framework (http://testflows.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/lice...
nilq/baby-python
python
from pathlib import Path import importlib import tensorflow as tf from annoy import AnnoyIndex DEFAULT_CONFIG = { "dataset": "Dataset", "model": "RetreivalModel", "network": "retrieval_basic_factorization", "network_args": { "embedding_dimension": 32, } } class Ret...
nilq/baby-python
python
# Generated by Django 2.1.3 on 2018-12-08 07:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('staf', '0010_process_slug'), ('multiplicity', '0023_referencespacetype_process'), ] operations = [ ...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function try: from threading import local except ImportError: from django.utils._threading_local import local _thread_locals = local() def get_current_request(): """ returns the request object for this thread """ return getattr(_thr...
nilq/baby-python
python
# Copyright 2020 Google LLC # # 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, ...
nilq/baby-python
python
from rest_framework import serializers from .models import ListModel from utils import datasolve class BinsizeGetSerializer(serializers.ModelSerializer): bin_size = serializers.CharField(read_only=True, required=False) bin_size_w = serializers.FloatField(read_only=True, required=False) bin_size_d = seriali...
nilq/baby-python
python
""" https://leetcode.com/problems/logger-rate-limiter/ Tags: Google; Medium; Stack """ from typing import List from operator import add, sub, mul, floordiv def div(op1: int, op2: int) -> int: neg = (op1 < 0 < op2) or (op2 < 0 < op1) ans = floordiv(abs(op1), abs(op2)) return ans * (-1 if neg el...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .aapt import Aapt from .minicap import Minicap from .rotation import Rotation from .performance.fps import Fps from .performance.cpu import Cpu from .performance.meminfo import Meminfo from .performance import DeviceWatcher __all__ = ['Aapt', 'Minicap', 'Rotation', 'Fps', 'Cpu', 'Meminfo'...
nilq/baby-python
python
import numpy, re def encode_onehot(index, size): onehot = numpy.zeros(size, dtype=numpy.int8) onehot[index] = 1 return onehot def prettify_string(string, replace_newline_with_space=True): pretty_string = str(string).strip() if replace_newline_with_space: pretty_string = pre...
nilq/baby-python
python
from unittest import TestCase from ddsc.core.consistency import UploadDetails, ProjectChecker, DSResourceNotConsistentError from mock import Mock, patch, call class TestUploadDetails(TestCase): def test_inconsistent_status(self): mock_dds_file = Mock() mock_dds_file.name = 'file1.dat' mock...
nilq/baby-python
python
# Global Benchmark Database (GBD) # Copyright (C) 2020 Markus Iser, Karlsruhe Institute of Technology (KIT) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or...
nilq/baby-python
python
import pianohat import time from pygame import mixer my_sound_files = [ "/home/pi/Downloads/despacito.wav", "/home/pi/Downloads/Metal.wav", "/home/pi/Downloads/Metal.wav", "/home/pi/Downloads/Metal.wav", "/home/pi/Downloads/Metal.wav", "/home/pi/Downloads/despacito.wav", "/home/pi/Downloads/...
nilq/baby-python
python
from django.db import models # Create your models here. class Employee(models.Model): Name = models.CharField(max_length=64) Email = models.CharField(max_length=64) Password = models.CharField(max_length=64) Position = models.CharField(max_length=64) Salary = models.IntegerField() def __str__...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup # Use 2to3 build conversion if required try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: # 2.x from distutils.command.build_py import build_py setup( name="snpy", description="A...
nilq/baby-python
python
# Copyright (C) 2021 ServiceNow, Inc. import pytest from nrcan_p2.data_processing.preprocessing_str import ( add_newline, sentence_tokenize_spacy_sm, sentence_tokenize_spacy_lg, tokenize_spacy_sm, tokenize_spacy_lg, rm_stopwords_spacy, rm_punct, rm_newline ) @pytest.mark.parametrize("i...
nilq/baby-python
python
""" Helper functions and classes around GeoIP lookups, based on Maxmind's `maxminddb <https://pypi.python.org/pypi/maxminddb>`_ and `geoip2 <https://pypi.python.org/pypi/geoip2>`_ Python packages. """ import logging import time import genc from geoip2.database import Reader from geoip2.errors import AddressNotFoundEr...
nilq/baby-python
python
#define the main() function def main(): i = 0 x = 119.0 for i in range(120): if((i%2)==0): x += 3. else: x -= 5. s = "%3.2e" % x print(s) if __name__ == "__main__": main()
nilq/baby-python
python
import asyncio from userbot import CMD_HELP, StartTime, bot from userbot.utils import bash, edit_or_reply, zelda_cmd @zelda_cmd(pattern="sxs (.*)") async def amireallysxs(sxs): user = await bot.get_me() capt = str(sxs.pattern_match.group(1).split(" ", 2)[0]) link = str(sxs.pattern_match.group(1).split(" "...
nilq/baby-python
python
#!/usr/bin/env python from flexbe_core import EventState, Logger import actionlib import rospy from jacobian_control.msg import DoAdaptionAction, DoAdaptionGoal, DoAdaptionResult, DoAdaptionFeedback class HandoverAdaptionExec(EventState): ''' Calls jacobian-control node for adaption. ''' def __init__(self...
nilq/baby-python
python
from .receipt_parser import parse_receipt # noqa
nilq/baby-python
python
import animal class Bear(animal.Animal): pass
nilq/baby-python
python
from dataclasses import dataclass from minsk.analysis.binding.expression import BoundExpression from minsk.analysis.binding.kind import BoundNodeKind from minsk.analysis.binding.operators.unary import BoundUnaryOperator from minsk.analysis.type import MinskType @dataclass(frozen=True) class BoundUnaryExpression(Boun...
nilq/baby-python
python
from zeit.cms.i18n import MessageFactory as _ import fb import gocept.form.grouped import requests import urllib import urlparse import zeit.cms.browser.menu import zope.app.appsetup.product import zope.formlib.form import zope.session.interfaces class IFacebookApp(zope.interface.Interface): app_id = zope.schema...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms from DQMOffline.Trigger.razorHemispheres_cff import * from DQMOffline.Trigger.RazorMonitor_cfi import hltRazorMonitoring # HLT_Rsq0p35_v* Rsq0p35_RazorMonitoring = hltRazorMonitoring.clone() Rsq0p35_RazorMonitoring.FolderName = cms.string('HLT/SUSY/Rsq0p35/') Rsq0p35_RazorMon...
nilq/baby-python
python
project = 'matador-test' environments = { 'test': {'dbms': 'oracle', 'connection': 'user@instance'} } credentials = { 'test': {'user': 'test_user', 'password': 'test_password'} }
nilq/baby-python
python
events = ["evt1", "evt2", "evt3"] def my_pop(): if events: evt = events.pop(0) print(evt) print(events) my_pop() my_pop() my_pop() my_pop()
nilq/baby-python
python
"Models for managing site sections and ad placements." from __future__ import unicode_literals from django.conf import settings from django.core.cache import cache from django.db import models from django.utils.encoding import python_2_unicode_compatible from .conf import SECTION_CACHE_KEY, PLACEMENTS_KEY_FORMAT from...
nilq/baby-python
python
from .base_regularizer import BaseRegularizer from .center_invariant_regularizer import CenterInvariantRegularizer from .regular_face_regularizer import RegularFaceRegularizer from .lp_regularizer import LpRegularizer from .zero_mean_regularizer import ZeroMeanRegularizer from .sparse_centers_regularizer import Sp...
nilq/baby-python
python
#!/usr/bin/env python """circuits Hello World""" from circuits import Component, Event class hello(Event): """hello Event""" class App(Component): def hello(self): """Hello Event Handler""" print("Hello World!") def started(self, component): """Started Event Handler ...
nilq/baby-python
python
#!/usr/bin/env python # Very useful script because I know the DMC steps start from s005 import re import sys import argparse #import numpy as np import autorunner @autorunner.dmc_dat() def common(x): return x # this style is not optimal but fine for now regardless @autorunner.qmcpack_output() def output_capturer(...
nilq/baby-python
python
# Generated by Django 4.0.4 on 2022-04-21 02:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cheese', fields=[ ('slug', models.SlugField...
nilq/baby-python
python
import os from PIL import Image wnid = 'n03082979' image_dir = './downloaded_images/{}/{}_urlimages'.format(wnid, wnid) for filename in os.listdir(image_dir): # if filename.endswith('.png'): try: filepath = os.path.join(image_dir, filename) img = Image.open(filepath) # open the image file img.verify() # ...
nilq/baby-python
python
# INTERSECTION OF TWO ARRAYS LEETCODE SOLUTION: # creating a class. class Solution(object): # creating a function to solve the problem. def intersection(self, nums1, nums2): # returning the intersection between the two arrays. return list(set(nums1).intersection(set(nums2)))
nilq/baby-python
python
import enum import math import time import warnings from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast import torch import torch.nn as nn import torch.nn.functional as F import torch.optim from torch import Tensor from . import functional as rtdlF ModuleType = Union[str, Callable[..., n...
nilq/baby-python
python
#coding: utf8 from rust.core import db as models class Permission(models.Model): """ 资源权限 """ resource = models.CharField(default='', max_length=128) # 资源名 method = models.CharField(default='GET', max_length=32) # 方法名 created_at = models.DateTimeField(auto_now_add=True) # 更新时间 class Meta(obj...
nilq/baby-python
python
from phoopy.kernel import Bundle from os import path class AppBundle(Bundle): def service_path(self): return path.join(self.get_bundle_dir(), 'config', 'services.yml') # pragma: no cover
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Collection of tests for :mod:`orion.core.utils.working_dir`.""" import os import shutil from pathlib import Path import pytest from orion.core.utils.working_dir import SetupWorkingDir class ExperimentStub: def __init__(self, working_dir=None): self.name =...
nilq/baby-python
python
#!/usr/bin/python import matplotlib.pyplot as plt from matplotlib import * import sys, getopt import copy import time import datetime import random import sys import os import re def get_data(file_list, type, start, finish, nice): mapped_reqs, running_reqs, refused_reqs = [], [], [] mapped_requests_dict = di...
nilq/baby-python
python
from pyexcel.renderer import Renderer from pyexcel_echarts.options import MANAGER DEFAULT_TITLE = 'pyexcel via pyechars' class Chart(Renderer): def render_sheet(self, sheet, chart_type='bar', mode='embed', title=DEFAULT_TITLE, subtitle="", width=800...
nilq/baby-python
python
class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: S = {-1: set()} for x in sorted(nums): S[x] = max((S[d] for d in S if x % d == 0), key=len) | {x} return list(max(S.values(), key=len))
nilq/baby-python
python
# coding=utf-8 """execution.py - This module provides classes that execute commands. """ import os import sys import signal import subprocess from .config import Config from .base import PluginManager from .log import LogManager class ExecutionManager(PluginManager): """This class is used to execute commands for ...
nilq/baby-python
python
# -*- encoding: utf-8 -*- import numpy as np def get_seq_graph(edge): dy, dx = np.array([-1,0,1,1,1,0,-1,-1]), np.array([-1,-1,-1,0,1,1,1,0]) def get_neighbors(node): Y, X = node[0]+dy, node[1]+dx neighbors = edge[Y, X] Y, X = Y[neighbors], X[neighbors] return zip(Y,X) grap...
nilq/baby-python
python
from __future__ import print_function import argparse import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data import torchvision.transforms as transforms import torchvision.utils as vutils from torch.aut...
nilq/baby-python
python
import numpy as np # 对一维数组的切片 origin = np.arange(1,100) print(origin) print(origin[0:2]) print(origin[:12:4]) print(origin[:12:]) print(origin[5:]) print(origin[::-1]) #倒序 # 二维数组切片 origin = np.random.random((3,4)) print(origin) print(origin[-2:,:2]) print(origin[::-2,::-1])
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 distri...
nilq/baby-python
python
#!/usr/bin/python import aud, sys, time, multiprocessing device = aud.Device() hrtf = aud.HRTF().loadLeftHrtfSet(".wav", sys.argv[2]) threadPool = aud.ThreadPool(multiprocessing.cpu_count()) source = aud.Source(0, 0, 0) sound = aud.Sound.file(sys.argv[1]).rechannel(1).binaural(hrtf, source, threadPool) handle = device....
nilq/baby-python
python
# coding: utf-8 # flake8: noqa """ Velo Payments APIs ## Terms and Definitions Throughout this document and the Velo platform the following terms are used: * **Payor.** An entity (typically a corporation) which wishes to pay funds to one or more payees via a payout. * **Payee.** The recipient of funds paid ...
nilq/baby-python
python
from data.mag.build_docs_from_sqlite import generate_papers, UPDATE_GENERATORS, strip_and_dump_from_gen from solr.instances import get_session from data import upload_batches_unparsed from solr.session import SolrSession from solr.configsets import get_config from multiprocessing import Pool, cpu_count import itertools...
nilq/baby-python
python
""" Module to log on screen ==================================== """ # ============================================================================ # STANDARD IMPORTS # ============================================================================ import click from functools import partial from click.termui import s...
nilq/baby-python
python
# # ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property # # 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
#!/usr/bin/env python3 import subprocess import os import glob import sys import time import argparse def merge(infile, outfile, id_name_map): merge_dict = {} with open(infile, 'r') as f: content = "" name = "" for line in f: if line[0] == ">": name = line[1:].strip() if name n...
nilq/baby-python
python
#--------------------------------------- # Import Libraries #--------------------------------------- import sys import json import codecs import os #--------------------------------------- # [Required] Script Information #--------------------------------------- ScriptName = "Queue Display" Website = "twitch.tv/enc...
nilq/baby-python
python
"""Implementation of the StarBound block file v2/3 storage""" import logging import struct from starfuse.fs.mapped_file import MappedFile log = logging.getLogger(__name__) class InvalidMagic(Exception): """A block file has an invalid magic string""" def __init__(self, path): super(InvalidMagic, sel...
nilq/baby-python
python
import pandas as pd import numpy as np def load_file(filename: str): """Load the .xls file and return as a dataframe object.""" df = pd.read_csv(filename, delimiter='\t') return df data = load_file('outputs.xls') print(data.info())
nilq/baby-python
python
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import csv import sys import json import pickle import logging from copy import deepcopy from collections import Counter from itertools import groupby, chain from indra.statements import Agent from indra.da...
nilq/baby-python
python
__author__ = 'marcusmorgenstern' __mail__ = '' import copy import os import unittest from os.path import join import numpy as np from pyfluka.base import InvalidInputError from pyfluka.reader.UsrbinReader import UsrbinReader as UR from pyfluka.utils import PhysicsQuantities as PQ _basedir = os.path.dirname(__file__) ...
nilq/baby-python
python
# @lc app=leetcode id=211 lang=python3 # # [211] Design Add and Search Words Data Structure # # https://leetcode.com/problems/design-add-and-search-words-data-structure/description/ # # algorithms # Medium (41.04%) # Likes: 3106 # Dislikes: 130 # Total Accepted: 293.8K # Total Submissions: 712.7K # Testcase Examp...
nilq/baby-python
python
from django.shortcuts import render from django.views.generic import TemplateView from booking.models import Booking from userprofile.models import userProfile class IndexPageView(TemplateView): template_name = 'main/index.html' class ChangeLanguageView(TemplateView): template_name = 'main/change_language....
nilq/baby-python
python
from sqlalchemy import ( create_engine, Column, MetaData, Integer, String, Numeric, DateTime) from sqlalchemy.orm import class_mapper from .common import ( generate_sqla_connection_uri, _insert_entries_from_log_file, _import_logs_from_folder) from sqlalchemy.orm import scoped_session, sessionmaker f...
nilq/baby-python
python
from __future__ import print_function, division, absolute_import import numpy as np import networkx as nx from visvis import ssdf from stentseg.utils.new_pointset import PointSet from stentseg.stentdirect.stentgraph import (StentGraph, check_path_integrity, _get_pairs_of_neighbours, add_nodes_at_crossings, ...
nilq/baby-python
python
from pyspark import SparkContext from pyspark.sql.functions import count, lit, col, udf, collect_list, explode, sqrt, mean from pyspark.sql.types import IntegerType, StringType, MapType, ArrayType, BooleanType, FloatType from pyspark.sql import SQLContext, HiveContext import sys def filter_slot_id(df, slot_ids=[]): ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2015 www.suishouguan.com # # Licensed under the Private License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://github.com/samuelbaizg/ssguan/blob/master/LICENSE # # Unless ...
nilq/baby-python
python
""" These are utilities for the `/bin` scripts, not for the `cibuildwheel` program. """ from io import StringIO from typing import Dict, List from .typing import Protocol __all__ = ("Printable", "dump_python_configurations") class Printable(Protocol): def __str__(self) -> str: ... def dump_python_con...
nilq/baby-python
python
# -*- coding: utf-8 -*- # global import io import sys import json import logging import pandas as pd # core import core import core.utils import core.indexer from core.DocVocabulary import DocVocabulary from core.TermVocabulary import TermVocabulary from core.features import Features from core.msg import TwitterMessa...
nilq/baby-python
python
class Dinosaur: def __init__(self, name, attack_power): self.name = name self.attack_power = int(attack_power) self.health = 50 self.energy = 100 self.att_list = ["Tail Whip", "Body Slam", "Stomp", "Hyper Beam"] self.att = "error" def attack(self, robot): ...
nilq/baby-python
python
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.data import kb from lib.request.connect import Connect as Request def getPageTemplate(payload, place): retVal = (kb.originalPage, kb.errorIsNone) if pa...
nilq/baby-python
python
# def encode_as_bytes(input_file_path: str, output_gif_path: str): # """ # The practical encoder with optimized GIF assembler and multiprocessing acceleration. # # :param input_file_path: input file path # :param output_gif_path: output gif file path # :param chunk_string_length: the length of base6...
nilq/baby-python
python
# Version: 2020.02.21 # # MIT License # # Copyright (c) 2018 Jiankang Deng and Jia Guo # # 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 limitatio...
nilq/baby-python
python
n= str(input("digite um valor ")).upper().strip() d=n.split() j= ''.join(d) inver= '' for i in range(len(j)-1,-1,-1): inver+=j[i] if n==inver: print("o valor é um palindromo") else: print("o valor não é um palindromo")
nilq/baby-python
python
import itertools import random S = " " def main(): # init gophers_count = 100 windmills_count = 18 factors = [17, 13, 11, 7, 5, 3, 2] seed = 1951 a, b, c = [], [], [] random.seed(seed) # generate input data for each night for f in factors: windmills = [f] * windmills_cou...
nilq/baby-python
python
from tensorflow.keras.layers import LSTM, Dense, TimeDistributed, Masking, BatchNormalization, Dropout, Input, \ Bidirectional, ConvLSTM2D, Attention from tensorflow.keras.models import Model from lsct.models.cnn_1d import CNN1D from cnn_lstm.attention_with_context import Attention def create_cnn_lstm_model(clip...
nilq/baby-python
python