content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# Copyright (c) 2014, Oracle and/or its affiliates. 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 # # ...
nilq/baby-python
python
"""This module provides a mock callable class.""" from __future__ import annotations import queue import unittest.mock from typing import Any, Dict, NamedTuple, Optional, Tuple from .consumer import ConsumerAsserter, MockConsumerGroup class MockCallableGroup: """This class implements a group of callables.""" ...
nilq/baby-python
python
# Is Prime # determine whether the number is prime or not class isPrime: def isPrime(self, n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True ip = isPrime() print(ip.isPrime(5))
nilq/baby-python
python
#!/bin/env python import platform, socket, random, time _appname_="slowloris" _version_="0.1" _description_="fastly take down the web" _author_="blackc8" ncol ="\033[0m" bold ="\033[1m" dim ="\033[2m" uline ="\033[4m" reverse="\033[7m" red ="\033[31m" green ="\033[32m" yellow ="\033[33m" blue ="\033[34m"...
nilq/baby-python
python
import sys, os import allel import random import numpy as np from diploshic.msTools import * from diploshic.fvTools import * import time ( trainingDataFileName, totalPhysLen, numSubWins, maskFileName, vcfForMaskFileName, popForMask, sampleToPopFileName, unmaskedGenoFracCutoff, chrAr...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: second/protos/train.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google....
nilq/baby-python
python
''' Created on Nov 9, 2011 @author: ppa ''' from analyzer.lib.errors import Errors, UfException class DAMFactory(object): ''' DAM factory ''' @staticmethod def createDAM(dam_name, config): ''' create DAM ''' if 'yahoo' == dam_name: from analyzerdam.yahooDAM imp...
nilq/baby-python
python
from pydantic import BaseModel class ProfileStats(BaseModel): visits: int = 0 views: int = 0 counters: dict = {}
nilq/baby-python
python
import pyautogui import time import cv2 import numpy as np import imutils def ImageDetection(temp_img,threshold,img_type): image = pyautogui.screenshot() img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # 0 is for grayscale template = cv2.imread(tem...
nilq/baby-python
python
""" Finds the dictionary for the measurement specification based on the name of the measurement. """ def find_measurement_spec(monitoring_system_specs, measurement_type): """ Scans the list of specs and returns dictionary of specifications for the named measurement type Parameters ---------- ...
nilq/baby-python
python
# HeadPhoneJacks Cause Vaccines # Softdev2 pd8 # K#06: Yummy Mango Py #2019-02-28 import pymongo SERVER_ADDR="" connection =pymongo.MongoClient(SERVER_ADDR) db = connection.test collection = db.restaurants def boro_find(borough): ''' finds restaurants by borough and returns them in a list. ''' restua...
nilq/baby-python
python
''' Function: AI玩俄罗斯方块 Author: Charles 公众号: Charles的皮卡丘 ''' import copy import math from modules.utils import * '''AI玩俄罗斯方块''' class TetrisAI(): def __init__(self, inner_board): self.inner_board = inner_board '''获得下一步的行动''' def getNextAction(self): if self.inner_board.current_tetris == tetrisShape().shape_e...
nilq/baby-python
python
import requests import urllib.request import time from bs4 import BeautifulSoup import json import csv filecsv = open('SouqDataapple.csv', 'w',encoding='utf8') # Set the URL you want to webscrape from url = 'https://saudi.souq.com/sa-ar/apple/new/a-c/s/?section=2&page=' file = open('SouqDataapple.json','w',encoding='ut...
nilq/baby-python
python
#!/usr/bin/python # # Scraper for libraries hosted at jcenter and custom maven repos # Retrieves jar|aar files along with some meta data # @author erik derr [derr@cs.uni-saarland.de] # import sys import json import urllib2 import datetime import os import errno import zipfile import traceback import xml.etree.ElementT...
nilq/baby-python
python
#!/usr/bin/env python # # Copyright (c) 2018 Intel Labs. # # authors: Bernd Gassmann (bernd.gassmann@intel.com) # """ Actor registry class for carla-id mapping """ class ActorIdRegistry(object): """ Registry class to map carla-ids (potentially 64 bit) to increasing numbers (usually not exceeding 32 bit)...
nilq/baby-python
python
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
nilq/baby-python
python
from typing import Optional, Union from torch_sparse import SparseTensor from torch_geometric.data import Data, HeteroData from torch_geometric.transforms import BaseTransform from torch_geometric.utils import sort_edge_index class ToSparseTensor(BaseTransform): r"""Converts the :obj:`edge_index` attributes of ...
nilq/baby-python
python
from __future__ import print_function import re import time from ...version import __version__ HEADER_FMT = '''\ /** * The MIT License (MIT) * * Copyright (c) 2018 Erik Moqvist * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * fi...
nilq/baby-python
python
from traffic.imports.builtins import SequenceType, sub def concat(strings: SequenceType[str], separator: str) -> str: return "".join(s if i == 0 else separator + s for i, s in enumerate(strings)) def to_func_name(name: str): return sub(r"\W", "_", name).lower()
nilq/baby-python
python
try: import urllib.parse as urlparse except ImportError: import urlparse from aws_xray_sdk.core.models import http from aws_xray_sdk.ext.flask.middleware import XRayMiddleware as OrigMiddleware from flask import request __all__ = 'XRayMiddleware', class XRayMiddleware(OrigMiddleware): def _before_reques...
nilq/baby-python
python
# Exercício Python 069: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, # o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: # A) quantas pessoas tem mais de 18 anos. # B) quantos homens foram cadastrados. # C) quantas mulheres tem menos de 20 anos....
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import typing # noqa F401 import torch from torch import Tensor def _flip_sub_u...
nilq/baby-python
python
from numpy import * class Nematic: def __init__(self, xx=0, xy=0): self.xx=xx self.xy=xy def angle(self): return 0.5*arctan2(self.xy, self.xx) def norm(self): return sqrt(self.xx**2 + self.xy**2) def __str__(self): return "Nematic(%g, %g)"%(self.xx, self.xy)
nilq/baby-python
python
# this file serves as both a test suite and an illustration of how tracing # responds to various AST node types import re from tracelib import macros, kite_trace, get_all_traced_ast_reprs with kite_trace: for i in range(5): print i print len([1, 2, 3, 1 + 1]) x = {1: 2} # AugAssign a = 0...
nilq/baby-python
python
import numpy as np import mmap import os import glob import re class Uio: """A simple uio class""" @staticmethod def find_device_file(device_name): device_file = None r = re.compile("/sys/class/uio/(.*)/name") for uio_device_name_file in glob.glob("/sys/class/uio/uio*/name"): ...
nilq/baby-python
python
# Wanderlust Wine - UK # Tutorial from John Watson Rooney YouTube channel import requests from bs4 import BeautifulSoup from requests.api import head import pandas as pd import re wine_list = [] # Step 1 - Request def request(x): url = f'http://www.wanderlustwine.co.uk/buy-wine-online/page/{x}/' headers = {'...
nilq/baby-python
python
import os.path import tempfile import maptools import maptools.external import pytest @pytest.mark.skipif(not maptools.external.is_ccp4_available(), reason="requires CCP4") def test_fit(ideal_map_filename, pdb_filename): _, output_pdb_filename = tempfile.mkstemp() _, log_filename = tempfile.mkstemp() ma...
nilq/baby-python
python
#!/usr/bin/env python3 from otl866 import at89, util import unittest import os class TestCase(unittest.TestCase): def setUp(self): """Call before every test case.""" print("") port = util.default_port() self.verbose = os.getenv("VERBOSE", "N") == "Y" self.tl = at89.AT89(po...
nilq/baby-python
python
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
nilq/baby-python
python
# batch running of experiments import os import getpass import argparse from utils import * from runmm2 import Simulation def CleanState (): os.system('sudo killall python2 receiver sender mm-link mm-delay >/dev/null 2>&1 ') # os.system('sudo ../ccp-kernel/ccp_kernel_unload') # os.system('sudo ../ccp-kernel/cc...
nilq/baby-python
python
from file_utilities import readCSVFile from PlotterLine import PlotterLine solution = readCSVFile("output.csv") a_liq_plotter = PlotterLine("Position", "Volume Fraction") a_liq_plotter.addSet(solution["x"], solution["a_liq"], "$\\alpha_\ell$", color=4, linetype=2) a_liq_plotter.save("volume_fraction.png") r_liq_plot...
nilq/baby-python
python
""" Benchmarks for array expressions. """ import numpy as np # @jit(nopython=True) def sum(a, b): return a + b # @jit(nopython=True) def sq_diff(a, b): return (a - b) * (a + b) # @jit(nopython=True) def rel_diff(a, b): return (a - b) / (a + b) # @jit(nopython=True) def square(a, b): # Note this is...
nilq/baby-python
python
""" Example usages: python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4 -o . python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4-9 -o tmp python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 1,2,4-9 -o tmp Pages can ...
nilq/baby-python
python
import util import os def run(): util.process_usgs_source( base_path=os.path.realpath(__file__), url="http://pubs.usgs.gov/of/1998/of98-354/sfs_data.tar.gz", uncompress_e00=True, e00_path="sfs-geol.e00", srs="+proj=lcc +lat_1=37.066667 +lat_2=38.433333 +lat_0=36.5 " ...
nilq/baby-python
python
class SleepSort(object): """ Sorting list of positive numbers using multi-threading wherein thread will sleep for integer value and add integer in result collection. These multi-threads will add integers of input list in such way that, result contains collection of sorted integers. eg: [3, 1...
nilq/baby-python
python
""" A precondition for the algorithm working is that the library 'requests' must be installed on the device prior to using the program """ import requests def auto_reconnect(): """ Auto reconnect to password module The ClientURL (cURL) command converted over to python for compatibility ...
nilq/baby-python
python
class DependencyPropertyDescriptor(PropertyDescriptor): """ Provides an extension of System.ComponentModel.PropertyDescriptor that accounts for the additional property characteristics of a dependency property. """ def AddValueChanged(self,component,handler): """ AddValueChanged(self: DependencyPropertyDescrip...
nilq/baby-python
python
from pathlib import Path import pytest import caption_contest_data as ccd filenames = list(ccd._api._get_response_fnames().keys()) DUELING_XFAIL = """These contests are dueling bandits, not cardinal bandits (which have pairwise comparisons, not single caption ratings). These aren't officially supported. """ def _...
nilq/baby-python
python
from pdip.cqrs.decorators import requestclass from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionDatabaseRequest import \ CreateDataIntegrationConnectionDatabaseRequest from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionFileRequest import \ CreateDa...
nilq/baby-python
python
"""Astronomical coordinate functions.""" import re,pdb import numpy as np from numpy import arccos,sin,cos from math import pi # constants DEG_PER_HR = 360. / 24. # degrees per hour DEG_PER_MIN = DEG_PER_HR / 60. # degrees per min DEG_PER_S = DEG_PER_MIN / 60. # degrees per sec DEG_PER_AMIN = 1./...
nilq/baby-python
python
import os from functools import reduce def xor(a,b): c=bytearray() for i,j in zip(a,b): c.append(i^j) return c msg1="did you expect another rsa? sorry" msg2=" to disappoint you. What you see is a bad use " msg3="of the otp in encryption. It literally says one" msg4=" and not multi time. masrt{think_out_of_the_b...
nilq/baby-python
python
import torch from common.utils.clip_pad import * import numpy as np class BatchCollator(object): def __init__(self, dataset, append_ind=False): self.dataset = dataset self.test_mode = self.dataset.test_mode self.data_names = self.dataset.data_names self.append_ind = append_ind ...
nilq/baby-python
python
from .leaderboards import * #from .nominationAssessmentTeam import * from .players import * #from .publicRanking import * #from .qualityAssuranceTeam import * #from .rankingTeam import * #from .websiteUser import *
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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nilq/baby-python
python
# celcius to fahrenheit import tkinter class FahrenheiterGUI(): # :D def __init__(self): # create the main window self.main_window = tkinter.Tk() # set the title self.main_window.title("Celcius to Fahrenheit") # create three frames for this GUI self.top_frame = tk...
nilq/baby-python
python
#!/usr/local/bin/python # Physics Equation Graph # Ben Payne <ben.is.located@gmail.com> import sys import os lib_path = os.path.abspath('lib') sys.path.append(lib_path) # this has to proceed use of physgraph db_path = os.path.abspath('databases') sys.path.append(lib_path) # this has to proceed use of physgraph import ...
nilq/baby-python
python
import numpy as np import torch from colorsys import hsv_to_rgb def get_camera_rays(c_pos, width=320, height=240, focal_length=0.035, sensor_width=0.032, noisy=False, vertical=None, c_track_point=None): #c_pos = np.array((0., 0., 0.)) # The camera is pointed at the origin if c_track_p...
nilq/baby-python
python
from __future__ import with_statement import re import pytest from flask import Flask from blessed_extensions import csrf_token from pg_discuss._compat import to_unicode csrf_token_input = re.compile( r'([0-9a-z#A-Z-\.]*)' ) def get_csrf_token(data): match = csrf_token_input.search(to_unicode(data)) ass...
nilq/baby-python
python
############################################################################## # For copyright and license notices, see __manifest__.py file in root directory ############################################################################## from odoo import api, fields, models, _ from odoo.exceptions import ValidationErro...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: helloworld.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.prot...
nilq/baby-python
python
# extract text from a img and its coordinates using the pytesseract module import cv2 import pytesseract # You need to add tesseract binary dependency to system variable for this to work img =cv2.imread('img.png') #We need to convert the img into RGB format img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) hI,wI,k=img.shape pr...
nilq/baby-python
python
from cwr_admin.resources.cwr import CWRFilesResource, CWRProcessorResource, \ CWRMatchResultResource, CWRFilesRemoveResource, CWRMatchBeginResource, \ CWRMatchRejectResource, CWRMatchAcceptResource, CWRMatchFeedbackResource
nilq/baby-python
python
# This code is based on https://github.com/Ryo-Ito/spatial_transformer_network import tensorflow as tf def mgrid(*args, **kwargs): low = kwargs.pop("low", -1) high = kwargs.pop("high", 1) low = tf.to_float(low) high = tf.to_float(high) coords = (tf.linspace(low, high, arg) for arg in args) gr...
nilq/baby-python
python
#!/usr/bin/env python # # Copyright (c) 2016 Nutanix Inc. All rights reserved. # # # Unit tests for test reports. import inspect import os import unittest from curie.node_failure_test.node_failure_test import NodeFailureTest from curie.node_failure_data_loss_test.node_failure_data_loss_test \ import NodeFailureDataL...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2021-07-24 11:30:23 # @Author : Chenghao Mou (mouchenghao@gmail.com) from typing import List from datasketch import MinHash, MinHashLSH from nltk.util import ngrams from text_dedup.utils.group import get_group_indices import multiprocessing as mp import time ...
nilq/baby-python
python
from .binary_tree import *
nilq/baby-python
python
# -*- coding: utf-8 -*- # KNN.py import numpy as np import matplotlib.pyplot as plt import cv2 if __name__ == '__main__': # 记住numpy的array有下面这种神器的用法 test = np.array([1,-2,3,-4,5]) res = test[test > 0] # res = [1,3,5] a = np.random.randint(0,101,(50,2),dtype=np.int64).astype(np.float32) fl...
nilq/baby-python
python
""" This is comment section """ def display_hello_world(): """ This is a function to display "Hello World!" :return: void """ print("Hello World!") display_hello_world() # Set text texts = ["Hello", "World", "!"] for text in texts: print(text) numberString = "917254" for char in numberStri...
nilq/baby-python
python
import xmltodict import defusedxml.ElementTree as ET class Locations: """Provides lookup of raw location data based on UKPRN and LOCID""" def __init__(self, root): """Build the locations lookup table Locations are unique on UKPRN and LOCID """ self.lookup_dict = {} f...
nilq/baby-python
python
from django.urls import path from apps.contents.views import IndexView urlpatterns = [ path('index/', IndexView.as_view()), ]
nilq/baby-python
python
import numpy as np from data.external_data.maturities import convert_maturity from data.external_data.yahoo import Yahoo from data.local_data.parameters_generator import ParametersGenerator from stochastic_process.markov_chain import MarkovChain, Sigma from stochastic_process.risky_asset import RiskyAsset class Data...
nilq/baby-python
python
# -*- coding: utf-8 -*- import cv2 import numpy as np from scipy.sparse.linalg import spsolve def fix_source(source, mask, shape, offset): mydict = {} counter = 0 for i in range(mask.shape[0]): for j in range(mask.shape[1]): if mask[i][j]>127: mydict[(i+offset[0], j+off...
nilq/baby-python
python
from typing import List, Optional, Tuple, Dict, Callable import torch from torch import Tensor from tha2.poser.poser import PoseParameterGroup, Poser from tha2.nn.batch_module.batch_input_module import BatchInputModule from tha2.compute.cached_computation_func import TensorListCachedComputationFunc class ...
nilq/baby-python
python
# test_ble_commands.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). # This copyright was auto-generated on Tue May 18 22:08:51 UTC 2021 import pytest from construct import Int32ub from open_gopro.ble_commands import BLECommunicator, BleCommands, BleSettings, BleStatuses from op...
nilq/baby-python
python
from django.conf import settings # - {% if cookiecutter.django_media_engine == S3 %} from storages.backends.s3boto3 import S3Boto3Storage class PrivateMediaStorage(S3Boto3Storage): """Media storage which disables public access by default When you use this as the default storage it makes sense to turn of...
nilq/baby-python
python
""" Implementation of POSFrequencyPipeline for score ten only. """ import json import re from constants import ASSETS_PATH from core_utils.article import ArtifactType from core_utils.visualizer import visualize from pipeline import CorpusManager, validate_dataset class EmptyFileError(Exception): """ Custom e...
nilq/baby-python
python
#!/usr/bin/env python """Helper functions to store and get the selected backend""" from collections import namedtuple import logging from dosna.util import named_module log = logging.getLogger(__name__) _current = None AVAILABLE = ['ram', 'hdf5', 'ceph', 'sage', 's3'] # Currently there is no need for more fancy at...
nilq/baby-python
python
from helpers.runner import run_main from helpers.cli import cmdout def test_no_cmd(cmdout): try: run_main([]) except SystemExit: pass cmdout.assert_substrs_in_line(0, ["usage:"], on_stderr=True)
nilq/baby-python
python
from ZstudentDAO import studentDAO # We put in the data we get passed up from the json #create latestid = studentDAO.create(('Eilish', 22)) #find by id result = studentDAO.findByID(latestid); # needs to be made into json object print (result) #update studentDAO.update(('Liam',23,latestid)) result = studentDAO.findB...
nilq/baby-python
python
""" Script to solve z-factor and gas density at the same time Using Dranchuk and Aboukassem (1975) """ def dranchuk(T_pr, P_pr): # T_pr : calculated pseudoreduced temperature # P_pr : calculated pseudoreduced pressure from scipy.optimize import fsolve # non-linear solver import numpy as np a1 ...
nilq/baby-python
python
# Generated by Django 3.0.2 on 2020-03-06 22:30 from django.db import migrations import streamfield.fields class Migration(migrations.Migration): dependencies = [ ('pagine', '0014_event_carousel'), ] operations = [ migrations.AddField( model_name='blog', name='ca...
nilq/baby-python
python
from typing import Any, Optional from rx.disposable import Disposable from rx.core import typing from .subject import Subject from .innersubscription import InnerSubscription class AsyncSubject(Subject): """Represents the result of an asynchronous operation. The last value before the close notification, or ...
nilq/baby-python
python
from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now class BaseModel(models.Model): created = models.DateTimeField(auto_now_add=True, verbose_name=_("Created, UTC")) updated = models.DateTimeField(auto_now=True, verbose_name=_("Updated, UTC...
nilq/baby-python
python
# Testing various potentials. from asap3 import * from asap3.md.verlet import VelocityVerlet from asap3.EMT2013Parameters import PtY_parameters from ase.lattice.cubic import * from ase.lattice.compounds import * from numpy import * from asap3.testtools import ReportTest try: import potResults except ImportError: ...
nilq/baby-python
python
import numpy as np import sys from PyQt5 import QtCore, QtGui, QtWidgets import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button #, RadioButtons import scipy.signal as ss from binary_file_options import Ui_MainWindow def get_raw_data_from_binary_file(fname,offset_samples,duration_samples,bit_de...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ve...
nilq/baby-python
python
from goolabs import GoolabsAPI import time def name_check(api_id, text_list): """固有表現抽出器で名前と判断された語のリストを取得 Parameters ---------- api_id : str text_list : list[str] ツイッターの文章のリスト Returns ------- name_list : list[str] 名前と判断された語(重複あり) """ n_list = ["鬼太郎", "ぬらりひょん",...
nilq/baby-python
python
from django.contrib import admin from .models import HeaderCTA, BlogEmbeddedCTA # Register your models here. admin.site.register(HeaderCTA) admin.site.register(BlogEmbeddedCTA)
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Sep 24 21:08:15 2019 @author: Olivier """ #####prévoir le résultat avant d'exécuter le code####### a=3 def test0(): """None->None affiche a, variable non déclarée dans la fonction""" print("valeur de a dans test0",a) test0() #attention, si a n...
nilq/baby-python
python
import socket from unittest import TestCase from tempfile import NamedTemporaryFile from mock import patch, Mock from oasislmf.utils.conf import load_ini_file, replace_in_file from oasislmf.utils.exceptions import OasisException class LoadInIFile(TestCase): def test_values_are_bool___values_are_correctly_conve...
nilq/baby-python
python
n = int(input()) ratings = [int(input()) for _ in range(n)] candies = [1] * n for i in range(1, n): if ratings[i] > ratings[i-1]: candies[i] = candies[i-1] + 1 #print (candies) for i in reversed(range(1, n)): if ratings[i] < ratings[i-1]: candies[i-1] = max(candies[i-1], candies[i]+1)...
nilq/baby-python
python
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup VERSION = '2.0.1' setup( name='usabilla-api', version=VERSION, description="Python client for Usabilla API", license='MIT', install_requires=['urllib3', 'requests'], packages=find_pack...
nilq/baby-python
python
import os from shutil import copyfile import lxml.etree as etree os.chdir("../") operating_system = 'Linux' target_level_path = '../level_variations/generated_levels/fourth generation' origin_level_path = '../buildgame/{}/9001_Data/StreamingAssets/Levels/novelty_level_1/type1/Levels/'.format(operating_system) game_lev...
nilq/baby-python
python
from random import randint number = randint(1, 100) print("Guess a number between 1 and 100") #print(number) while True: guess = int(input("Enter guess:")) if guess < number: print("Too low") elif guess > number: print("Too high") else: break print("Correct!")
nilq/baby-python
python
# DESCRIPTION # You are a product manager and currently leading a team to develop a new product. # Unfortunately, the latest version of your product fails the quality check. # Since each version is developed based on the previous version, all the versions after a bad version are also bad. # Suppose you have n versions ...
nilq/baby-python
python
""" Description: This script calibrate result from LP solution. Probablistically select ASYMPs. Then, compute metric features from those. """ from utils.networkx_operations import * from utils.pandas_operations import * from utils.time_operations import * from tqdm import tqdm import pandas as pd import numpy as np im...
nilq/baby-python
python
import rubrik_cdm rubrik = rubrik_cdm.Connect() username = "python-sdk-read-only" read_only_permission = rubrik.read_only_authorization(username)
nilq/baby-python
python
import torch import torch.nn as nn import numpy as np class AttentionGate(nn.Module): def __init__(self, x_ch, g_ch, mid_ch, scale): super(AttentionGate, self).__init__() self.scale = scale self.conv_g = nn.Conv2d(in_channels=g_ch, out_channels=mid_ch, kernel_size=1, bias=True) sel...
nilq/baby-python
python
""" Loader and Parser for the txt format. Version: 0.01-beta """ from konbata.Data.Data import DataNode, DataTree from konbata.Formats.Format import Format def txt_toTree(file, delimiter=None, options=None): """ Function transforms a txt file into a DataTree. Parameters ---------- file...
nilq/baby-python
python
from __future__ import print_function from recon.core.module import BaseModule import os import subprocess from libs.pentestlymodule import PentestlyModule from libs.misc import parse_mimikatz, Colors class Module(PentestlyModule): meta = { 'name': 'Execute Mimikatz', 'author': 'Cory Duplantis (...
nilq/baby-python
python
if __name__ == "__main__": if __package__ is None: # add parent dir to allow relative import from pathlib import Path import sys top = Path(__file__).resolve().parents[1] sys.path.append(str(top)) # PEP 0366 __package__ = "lvscharts" __import__(__pa...
nilq/baby-python
python
from .toolbar_controller import ToolbarController
nilq/baby-python
python
from unittest import TestCase import unittest from rengine.config import TIME_BASED_CONDITIONS, ExerciseType, MuscleGroup from rengine.exercises import pick_random_exercise import dataframe_image as dfi from rengine.workouts import AutoGeneratedWorkout, BaseWorkout, LowerBodyWorkout, UpperBodyWorkout, dictionary_additi...
nilq/baby-python
python
from sklearn.linear_model import RidgeClassifierCV, RidgeClassifier from eye_detector.train.models.find import find_params from eye_detector.train.models.decorator import ModelDecorator def ridge(x, y, shape): grid = RidgeClassifierCV(alphas=[1e-3, 1e-2, 1e-1, 1]) alpha = find_params(grid, x, y, attr="alpha_"...
nilq/baby-python
python
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate import pandas as pd import plotly.graph_objects as go import numpy as np external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"...
nilq/baby-python
python
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RStatnetCommon(RPackage): """Non-statistical utilities used by the software developed by t...
nilq/baby-python
python
# Grupo: Gabriel Macaúbas Melo, Louise Fernandes Caetano, Maria Eduarda de Almeida Vitorino e Fernando Luiz Castro Seixas # Importando Funções from functions import * # Programa Principal num = iniciar() cartelas = criar_cartela(num) sorteio(cartelas)
nilq/baby-python
python
import os from sklearn import datasets import xgboost as xgb from xgboost_ray import RayDMatrix, predict import numpy as np def main(): if not os.path.exists("simple.xgb"): raise ValueError(f"Model file not found: `simple.xgb`" f"\nFIX THIS by running `python `simple.py` first ...
nilq/baby-python
python
# FP involving global variables modified in a different scope i = 0 def update_i(): global i i = i + 1 update_i() if i > 0: print("i is greater than 0") # FP: This is reachable
nilq/baby-python
python
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from functools import wraps from common import Logging from common.Logging import get_generic_logger from common.YamlConfig import AppConfig from lib.bottle import Bottle, request, response from ..AppRunner import AppRunner from ..RemoteServerApi import get_server_config, ge...
nilq/baby-python
python