content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.http import JsonResponse, HttpResponse
from .models import User, Photo, Followers
from .forms import *
from django.contrib.auth import authenticate, login, logout as dlogout
import json
def ajaxsignup(request)... | nilq/baby-python | python |
import numpy
from scipy.spatial import distance
import matplotlib.pyplot as plt
# wspolczynnik uczenia
eta = 0.1
# momentum
alfa = 0
class NeuralNetwork:
def __repr__(self):
return "Instance of NeuralNetwork"
def __str__(self):
# todo: zaktualizuj to_string()
if self.is_bias:
... | nilq/baby-python | python |
import torch
import matplotlib.pyplot as plt
from torchsummary import summary
import yaml
from pprint import pprint
import random
import numpy as np
import torch.nn as nn
from torchvision import datasets, transforms
from itertools import product
def imshow(img):
# functions to show an image
fi... | nilq/baby-python | python |
from models.mlm_wrapper import MLMWrapper
from transformers import BertForMaskedLM, BertTokenizer
class BertWrapper(MLMWrapper):
def __init__(self, tokenizer: BertTokenizer, model: BertForMaskedLM, device: int = None):
super().__init__(tokenizer, model, device=device)
| nilq/baby-python | python |
import csv
import clueUtils
import guess
suspects = clueUtils.suspects
weapons = clueUtils.weapons
rooms = clueUtils.rooms
allCards = clueUtils.allCards
playerNames = clueUtils.playerNames
numPlayers = clueUtils.numPlayers
numSuspects = clueUtils.numSuspects
numWeapons = clueUtils.numWeapons
numRooms = clueUtils.nu... | nilq/baby-python | python |
# This file is part of the scanning-squid package.
#
# Copyright (c) 2018 Logan Bishop-Van Horn
#
# 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 limita... | nilq/baby-python | python |
"""
Feb 23
Like net_feb23_1 but with faster affine transform and more filters and DNN (~15s faster)
363 | 0.678831 | 0.869813 | 0.780434 | 74.74% | 69.6s
Early stopping.
Best valid loss was 0.846821 at epoch 262.
Finished training. Took 25459 seconds
Accuracy test score is 0.7608
Multicla... | nilq/baby-python | python |
# cat train.info | grep "Test net output #0: accuracy =" | awk '{print $11}'
import re
import os
import matplotlib.pyplot as plt
import numpy as np
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--traininfo', type=str, required=True)
args = parser.parse_... | nilq/baby-python | python |
'''
Perform Object Classification (SGCLS only)
Input is the pointcloud of the BOX, its location and heading is known
Output the predicted class of the BOX
'''
import torch
from torch import nn
from torch.nn import functional as F
from model.modeling.detector.pointnet2.pointnet2_modules import PointnetSAModuleVotes, P... | nilq/baby-python | python |
# Copyright 2016 Intel
#
# 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, softwar... | nilq/baby-python | python |
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p "python3.withPackages(ps: [ps.numpy ps.psycopg2 ps.requests ps.websockets])"
import sys
import threading
from tenmoTypes import *
from tenmoGraph import universe_print_dot
import select
import time
import datetime
import pprint
import traceback
import io
import jso... | nilq/baby-python | python |
from django.urls import path
from django.contrib.auth import views as auth_views
from account import views as account_views
urlpatterns = [
path('login',
auth_views.LoginView.as_view(
template_name='account/login.html',
extra_context={
'title': 'Account login'})... | nilq/baby-python | python |
'''
This is based on cnn35_64. This is after the first pilot.
Changes:
-don't filter out # in the tokenizer, tokenize both together. or save tokenizer https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring
-use 'number' w2v as representation for any digit
-shu... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sqlite3
import cherrypy
from collections import namedtuple
import tweepy
import random
import twitterkeys
# setup twitter authentication and api
twitter_auth = tweepy.OAuthHandler(twitterkeys.consumer_key, twitterkeys.consumer_secret)
twitter_auth.set_access_token(twitterkeys.ac... | nilq/baby-python | python |
#!/usr/bin/env python3
import xml.etree.ElementTree as ET
CSPROJ_FILE = 'Uri/Uri.csproj'
ENV_VARIABLE_FILE = '.env'
ENV_VARIABLE_NAME = 'URI_VERSION'
csproj_tree = ET.parse(CSPROJ_FILE)
version_tag = csproj_tree.getroot().find('PropertyGroup').find('Version')
version_parts = version_tag.text.split('.', 2)
version_p... | nilq/baby-python | python |
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
dic = {}
stack = []
for num in nums2:
stack.append(num)
while len(stack) >= 2:
if stack[-1] > stack[-2]:
dic[stack[-2]] = stack[-1]
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from torch.nn import BatchNorm1d
from ncc.models import register_model
from ncc.models.ncc_model import (
NccEncoder,
NccEncoderModel,
)
from ncc.modules.base.layers import (
Embedding,
Linear,
)
class DeepTuneEncoder(NccEncoder):
def __... | nilq/baby-python | python |
# MAP WARMPUP
# Given the two lists of numbers below, produce a new iterable of their element-wise sums
# In this example, that'd be (21, 33, 3, 60...)
# Hint: look for a `from operator import ...`
one = [1, 2, 3, 40, 5, 66]
two = [20, 31, 0, 20, 55, 10]
# FILTER WARMPUP
# Take the following iterable, and filter o... | nilq/baby-python | python |
"""
This is templates for common data structures and algorithms.
Frequently used in my leetcode practices.
"""
"""
Binary search
"""
nums, target
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
# might need modification to fit the problem.
if nums[mid] < target:
... | nilq/baby-python | python |
from __future__ import (absolute_import, division,print_function, unicode_literals)
from builtins import *
import numpy as np
import cv2
import SimpleITK as sitk
from builtins import *
from scipy.spatial import distance
from scipy import stats
import sys
import time
############### FUNCTIONS ##############... | nilq/baby-python | python |
import tempfile
import pickle
import os
import sys
import time
import zipfile
import inspect
import binaryninja as binja
from binaryninja.binaryview import BinaryViewType, BinaryView
from binaryninja.filemetadata import FileMetadata, SaveSettings
from binaryninja.datarender import DataRenderer
from binaryninja.function... | nilq/baby-python | python |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
d=[0]*(n+1)
max_val=0
for query in queries:
d[query[0]-1]+=query[2]
d[query[1]]+=query[2]*(-1)
max_dif=0
for i in d:
... | nilq/baby-python | python |
from model.model.space.space import Space
from model.model.space.space import Space
from watchmen.auth.storage.user_group import get_user_group_list_by_ids, update_user_group_storage, USER_GROUPS
from watchmen.auth.user_group import UserGroup
from watchmen_boot.guid.snowflake import get_surrogate_key
from watchmen.co... | nilq/baby-python | python |
from scipy.spatial.distance import pdist, squareform
from causality.greedyBuilder.scores import mutual_info_pairwise
import networkx as nx
class TreeBuilder:
def __init__(self, score=None):
if score is None:
self.score = mutual_info_pairwise
else:
self.score = score
d... | nilq/baby-python | python |
"""Interval set abstract type"""
import datetime
import collections
__version__ = "0.1.5"
_InternalInterval = collections.namedtuple("Interval", ["begin", "end"])
class Interval(_InternalInterval):
"""Represent an immutable interval, with beginning and ending value.
To create a new interval:
... | nilq/baby-python | python |
#!/usr/bin/env python3
from ctypes import cdll, c_char_p, c_int, create_string_buffer, c_long
SO_PATH="/home/***************/libAdAuth/libAdAuth.so"
username = create_string_buffer(b"********")
password = create_string_buffer(b"********")
host = create_string_buffer(b"*********.uk")
domain = create_string_buffer(b"**... | nilq/baby-python | python |
# rearrange name of data in anat directories,
# delete repeated task-name pattern, add missing pattern
import os
# change to main directory
main_directory = '/mindhive/saxelab3/anzellotti/forrest/forrest_bids/'
#main_directory = '/Users/chloe/Documents/test10/'
os.chdir(main_directory)
# get all subject folders in main... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.ohio import ohio
def test_ohio():
"""Test module ohio.py by downloading
ohio.csv and testing shape of
extracted data has 2148 rows and 4 c... | nilq/baby-python | python |
class User:
"""
This class will contain all the details of the user
"""
def __init__(self,login,password):
"""
This will create the information of (Levert) the user
"""
self.login = login
self.password = password
# Levert
def user_exists(self,password):
"""Levert Co
... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nilq/baby-python | python |
import pytest
import numpy as np
class DataGenerator:
def __init__(self, fs=100e3, n_iter=10, sample_duration=1):
self.fs = fs
self.n_iter = n_iter
self.sample_duration = sample_duration
self.n_samples = int(round(sample_duration * fs))
def _iter(self):
self.generate... | nilq/baby-python | python |
#
# Copyright (c) Sinergise, 2019 -- 2021.
#
# This file belongs to subproject "field-delineation" of project NIVA (www.niva4cap.eu).
# All rights reserved.
#
# This source code is licensed under the MIT license found in the LICENSE
# file in the root directory of this source tree.
#
import os
import re
from setuptool... | nilq/baby-python | python |
import time
import base64
def normalize_scope(scope):
return ' '.join(sorted(scope.split()))
def is_token_expired(token, offset=60):
return token['expires_at'] - int(time.time()) < offset
def get_authorization_headers(client_id, client_secret):
auth_header = base64.b64encode(f'{client_id}... | nilq/baby-python | python |
"""
# 100daysCodingChallenge
Level: Medium
Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, S
.
Both players have to make substrings using the letters of the string S
.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vow... | nilq/baby-python | python |
'''
Date: 2021-08-02 22:38:28
LastEditors: xgy
LastEditTime: 2021-08-15 16:12:14
FilePath: \code\ctpn\src\CTPN\BoundingBoxDecode.py
'''
import mindspore.nn as nn
from mindspore.ops import operations as P
class BoundingBoxDecode(nn.Cell):
"""
BoundintBox Decoder.
Returns:
pred_box(Tensor): decoder ... | nilq/baby-python | python |
'''In this exercise, the task is to write a function that picks a random word from a list of words from the
SOWPODS dictionary. Download this file and save it in the same directory as your Python code.
This file is Peter Norvig’s compilation of the dictionary of words used in professional Scrabble tournaments.
Each lin... | nilq/baby-python | python |
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField('Titulo', max_length=150)
description = models.TextField('Description')
# author = models.ForeignKey(User, verbose_name = 'Autor')
is_published = models.BooleanField('Publicado?', default = False... | nilq/baby-python | python |
# from os.path import dirname
import os,sys,pytest
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from Page.login_page import Login_Page
from Base.init_driver import get_driver
from Base.read_data import Op_Data
from time import sleep
from loguru import logger
# sys.path.append(os.getcwd())
def get_data... | nilq/baby-python | python |
from unittest import TestCase
import pytest
import pandas as pd
import numpy as np
from pipelines.wine_quality_preparers import WinesPreparerETL, WhiteWinesPreparer
inputs = [7.0, 0.27, 0.36, 20.7, 0.045, 45.0, 170.0, 1.0010, 3.00, 0.45, 8.8, 6]
np_inputs = np.array(inputs)
class TestWinesPreparerETL(TestCase):... | nilq/baby-python | python |
from openfermion_dirac import MolecularData_Dirac, run_dirac
from openfermion.transforms import jordan_wigner
from openfermion.utils import eigenspectrum
import os
# Set molecule parameters.
basis = 'STO-3G'
bond_length = 0.5
charge = 1
data_directory=os.getcwd()
delete_input = True
delete_xyz = True
delete_output = ... | nilq/baby-python | python |
# Copyright (c) 2021-present, Ethan Henderson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# :Project: pglast -- DO NOT EDIT: automatically extracted from struct_defs.json @ 13-2.1.0-0-gd1d0186
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2021 Lele Gaifax
#
from collections import namedtuple
from decima... | nilq/baby-python | python |
"""
mqtt_base_client.py
====================================
Base MQTT Client
"""
import paho.mqtt.client as mqtt
from helper import run_async
import _thread
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def on_subscribe_callback(client, userdata, mid, granted_qos):
""... | nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, DateField,IntegerField, FloatField, SelectField, SelectMultipleField, RadioField, TextAreaField, Form, FieldList, FormField
from wtforms.fields.html5 import DateField
from wtforms.widgets import ListWidget, CheckboxInput
from wtforms.validato... | nilq/baby-python | python |
"""Thread function's arguments
When target function you want to call to run in a thread
has arguments.
"""
import threading, time
def pause(seconds):
i = 0
while i < seconds:
print('Run thread: ' + threading.currentThread().name)
i = i + 1
time.sleep(1)
print('Start main')
threading.T... | nilq/baby-python | python |
import logging
import os
import sys
from constants.dbpedia import LINKS_FILE
from extras.dbpedia.loader import start_crawling
log = logging.getLogger( __name__ )
if __name__ == '__main__':
if not os.path.isfile( LINKS_FILE ):
log.error( 'File with links to DBpedia-related files not found. nothing to do'... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
site.py
~~~~~~~
Flask main app
:copyright: (c) 2015 by Vivek R.
:license: BSD, see LICENSE for more details.
"""
import os
import datetime
from urlparse import urljoin
from collections import Counter, OrderedDict
from flask import Flask
from flask_frozen import Freezer
from werkzeug... | nilq/baby-python | python |
from allennlp.predictors.predictor import Predictor
from typing import List
from allennlp.common.util import JsonDict, sanitize
from allennlp.data import Instance
@Predictor.register("rationale_predictor")
class RationalePredictor(Predictor) :
def _json_to_instance(self, json_dict):
raise NotImplementedEr... | nilq/baby-python | python |
from setuptools import setup, find_packages
with open("README.md", "r") as f:
long_description = f.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='alfrodull',
version='0.1.0',
author='Philip Laine',
author_email='philip.laine@gmail.com',
descri... | nilq/baby-python | python |
annoy_index_db_path = 'cache/index.db'
already_img_response = 'there are not math image'
success_response = 'success'
dim_800x800 = (800,800) | nilq/baby-python | python |
#!/usr/bin/env python3
# (C) Copyright 2022 European Centre for Medium-Range Weather Forecasts.
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunit... | nilq/baby-python | python |
from typing import Any, Dict
import pytest
from nuplan.common.utils.testing.nuplan_test import NUPLAN_TEST_PLUGIN, nuplan_test
from nuplan.planning.metrics.evaluation_metrics.common.ego_yaw_acceleration import EgoYawAccelerationStatistics
from nuplan.planning.metrics.utils.testing_utils import metric_statistic_test
... | nilq/baby-python | python |
import pandas as pd
import numpy as np
from src.configs import *
from src.features.transform import categorical_to_ordinal
import collections
class HousePriceData:
'''
Load House Price data for Kaggle competition
'''
def __init__(self, train_path, test_path):
self.trainset = pd.read_csv(train_... | nilq/baby-python | python |
#!/usr/bin/env python
# coding=utf-8
import os
import shutil
from src.core.setcore import *
# Py2/3 compatibility
# Python3 renamed raw_input to input
try: input = raw_input
except NameError: pass
dest = ("src/html/")
url = ("")
debug_msg(mod_name(), "entering src.html.templates.template'", 1)
#
# used for pre-def... | nilq/baby-python | python |
from typing import Any, Optional
from fastapi import HTTPException
class NotFoundHTTPException(HTTPException):
"""Http 404 Not Found exception"""
def __init__(self, headers: Optional[dict[str, Any]] = None) -> None:
super().__init__(404, detail="Not Found", headers=headers)
class BadRequestHTTPExce... | nilq/baby-python | python |
from setuptools import setup
setup(name="spikerlib",
version="0.8",
description="Collection of tools for analysing spike trains",
author="Achilleas Koutsou",
author_email="achilleas.k@gmail.com",
#package_dir={'': 'spikerlib'},
packages=["spikerlib", "spikerlib.metrics"]
)
| nilq/baby-python | python |
"""Parse CaffeModel.
Helped by caffe2theano, MarcBS's Caffe2Keras module.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
from __future__ import print_function
from collections import OrderedDict
import numpy as np
from scipy.io import loadmat
from transcaffe import caffe_pb2, utils
from google.protobuf.text_fo... | nilq/baby-python | python |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | nilq/baby-python | python |
import json
from dejavu import Dejavu
from dejavu.logic.recognizer.file_recognizer import FileRecognizer
from dejavu.logic.recognizer.microphone_recognizer import MicrophoneRecognizer
# load config from a JSON file (or anything outputting a python dictionary)
config = {
"database": {
"host": "db",
... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# # Exercises 9: Functions
#
# There are some tricky questions in here - don't be afraid to ask for help. You might find it useful to work out a rough structure or process on paper before going to code.
#
# ## Task 1: Regular functions
#
# 1. Write a function to find the maximu... | nilq/baby-python | python |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
import pytorch_lightning as pl
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from deperceiver.models.debug_model import DebugModel
if __name__ == '__main__':
model = DebugModel()
wandb_logger = WandbLogger(
name='debug_cifar',
project='DePerceiver',
... | nilq/baby-python | python |
def img_to_encoding(image_path, model):
# loading the image with resizing the image
img = load_img(image_path, target_size=(160, 160))
print('\nImage data :',img)
print("\nImage Data :",img.shape)
# converting the img data in the form of pixcel values
img = np.around(np.array(img) / 255.0, dec... | nilq/baby-python | python |
from styx_msgs.msg import TrafficLight
from keras.models import load_model
import cv2
import numpy as np
import tensorflow as tf
import os
import rospy
from PIL import Image
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
class TLSimClassifier(object):
def __init__(self):
#TODO load classifier
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import galaxy.main.fields
import galaxy.main.mixins
class Migration(migrations.Migration):
dependencies = [('main', '0049_auto_20161013_1744')]
operations = [
migrations.CreateModel(
... | nilq/baby-python | python |
from __future__ import annotations
import numpy as np
from bqskitrs import Circuit as Circ
from bqskit.ir.circuit import Circuit
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
def check_gradient(circ: Circuit, num_params: int) -> None:
totaldiff = [0] * num_params
eps = 1e-5
repeats = 100
... | nilq/baby-python | python |
"""WMEL diagrams."""
# --- import --------------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
# --- define --------------------------------------------------------------------------------------
# --- subplot --------------------------... | nilq/baby-python | python |
import torch.utils.data as data
import cv2
import numpy as np
import math
from lib.utils import data_utils
from pycocotools.coco import COCO
import os
from lib.utils.tless import tless_utils, visualize_utils, tless_config
from PIL import Image
import glob
class Dataset(data.Dataset):
def __init__(self, ann_file, ... | nilq/baby-python | python |
"""
Proxy discovery operations
"""
import os
import socket
import logging
import functools
from contextlib import closing
from dataclasses import dataclass
from typing import Mapping, Tuple, List
from urllib.parse import urlparse
from nspawn import CONFIG
logger = logging.getLogger(__name__)
@dataclass
class ProxyC... | nilq/baby-python | python |
"""
Partition the numbers using a very simple round-robin algorithm.
Programmer: Erel Segal-Halevi
Since: 2022-02
"""
from typing import Callable, List, Any
from prtpy import outputtypes as out, objectives as obj, Bins
def roundrobin(
bins: Bins,
items: List[any],
valueof: Callable[[Any], float] = lambd... | nilq/baby-python | python |
import cv2
import dlib
import threading
import numpy as np
from keras.models import load_model
from scipy.spatial import distance as dist
from imutils import face_utils
import sys
from tensorflow import Graph, Session
import utils.logging_data as LOG
'''
Blink frequence, This file predicts blinking
Make sure models a... | nilq/baby-python | python |
import sys
import argparse
import os
import re
import yaml
from . import workflow
class Runner(object):
tasks = [
]
out_and_cache_subfolder_with_sumatra_label = True
def run(self):
parser = argparse.ArgumentParser(description='Run workflow')
parser.add_argument('config_path', type... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2018 Nortxort
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,... | nilq/baby-python | python |
import json
from dotenv import load_dotenv
from os import getenv
from plex_trakt_sync.path import config_file, env_file, default_config_file
from os.path import exists
class Config(dict):
env_keys = [
"PLEX_BASEURL",
"PLEX_FALLBACKURL",
"PLEX_TOKEN",
"PLEX_USERNAME",
"TRAKT... | nilq/baby-python | python |
import datetime
from random import randint
from telegram.chat import Chat
from telegram.message import Message
from telegram.user import User
class MockBot:
last_message = {}
def send_message(self, chat_id, text, **kwargs):
self.last_message[chat_id] = text
def sendMessage(self, *args, **kwargs... | nilq/baby-python | python |
def pairs(k, arr):
result = 0
arr = sorted(arr)
j = 1
for i in range(len(arr)-1):
while j<len(arr):
if arr[j] - arr[i] == k:
result += 1
j += 1
elif arr[j] - arr[i] > k:
break
elif arr[j] - arr[i] < k:... | nilq/baby-python | python |
# MINLP written by GAMS Convert at 04/21/18 13:54:23
#
# Equation counts
# Total E G L N X C B
# 19 18 1 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | nilq/baby-python | python |
from org.mowl.Parsers import TaxonomyWithRelsParser as Parser
from org.semanticweb.owlapi.model import OWLOntology
from mowl.graph.edge import Edge
import sys
from mowl.graph.graph import GraphGenModel
class TaxonomyWithRelsParser(GraphGenModel):
r'''
This class will project the ontology considering the fo... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from de_expl import de_expl
from es_expl import es_expl
from gwo_expl import gwo_expl
from hho_expl import hho_expl
from mfo_expl import mfo_expl
from pso_expl import pso_expl
from p5_base import plot_progress, plot_objs
fevals = 10000
#de_x, de_y, de_hist, de_res,... | nilq/baby-python | python |
# Create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
}
# Careate a basic set of states and some cities in them
cities = {
'CA': 'San Farncisco',
'MI': 'Detroit',
'FL': 'JAcksonsville',
}
# Add so... | nilq/baby-python | python |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from modules.execution.models import *
class Project(models.Model):
PROJECT_TYPES = (
("internal", "internal"),
("public", "public")
)
name = models.CharField(max_length=100, unique=... | nilq/baby-python | python |
from datasets.parties.all import df_regions_votes_and_parties
from datasets.regions.province import df_community_and_provice | nilq/baby-python | python |
# Link - https://www.hackerrank.com/challenges/designer-door-mat/problem
inp = input().split()
N = int(inp[0])
M = int(inp[1])
for i in range(1, N, 2):
print((i * ".|.").center(M, "-"))
print("WELCOME".center(M,"-"))
for i in range(N-2, -1, -2):
print((i * ".|.").center(M, "-"))
| nilq/baby-python | python |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | nilq/baby-python | python |
import time
import uuid
import six
from mazepa.queue import Queue
from mazepa.job import Job, AllJobsIndicator
class Scheduler:
def __init__(self, queue_name=None, completion_queue_name=None,
queue_region=None, threads=1):
self.queue = Queue(queue_name=queue_name,
completion_qu... | nilq/baby-python | python |
"""Main module which implements the components of graph-based autoconstraint model.
"""
import torch
from sketchgraphs.pipeline.graph_model import target, scopes_from_offsets
from sketchgraphs_models.graph.model import EdgePartnerNetwork, numerical_features, message_passing
from sketchgraphs_models import nn as sg_n... | nilq/baby-python | python |
# Ensures the validity of blocks inside a blockchain
# Copyright (c) 2022 gparap
from Blockchain import Blockchain
class Validator:
def __init__(self, blockchain: Blockchain):
self.blockchain = blockchain
# the previous hash of the current block must match the hash of the previous block
def valid... | nilq/baby-python | python |
from pdb import set_trace as T
import numpy as np
from itertools import chain
from neural_mmo.forge.blade import core
from neural_mmo.forge.blade.lib import material
from random import randint
import os
numsent = 0
class Map:
'''Map object representing a list of tiles
Also tracks a sparse list of tile up... | nilq/baby-python | python |
# encoding: cinje
: from .template import page
: from .letterscountsbar import letterscountsbar
: from .namelist import namelist
: def browsetemplate title, ctx, letterscountslist, names=None
: using page title, ctx, lang="en"
<div class="row">
: if letterscountslist is not None
: use ... | nilq/baby-python | python |
# [그리디] 거스름돈
#========== input ===========
# n : 거스름돈 금액
#========== output ==========
# result : 금액에 해당되는 최소의 동전 개수
# 풀이 : 가장 큰 동전부터, 거스를 수 있을 만큼 거슬러 주기
n = int(input())
result = 0
coin_list = [500, 100, 50, 10]
for coin in coin_list:
result += n//coin
n %= coin
print(result)
| nilq/baby-python | python |
from collections import namedtuple
from copy import copy
from datetime import *
from geojson import Feature, Point, FeatureCollection, LineString
from geojson.mapping import to_mapping
from typing import List, Dict
import functools
import os
import struct
import pyall
from hyo2.mate.lib.scan import Scan, A_NONE, A_PAR... | nilq/baby-python | python |
import argparse
import sys
class ContactsCLI():
"""Parse command line arguments for contacts program"""
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument(
'-f',
'--filter',
default=None,
type=str,
h... | nilq/baby-python | python |
from client import Client
import pprint
"""
MAIN INSTANCE (petition)
"""
tenant_id = ""
client_id = ""
client_secret = ""
dynamics_resource = ""
CRM_resource = ""
refresh_token = ""
token = ""
petition = Client(client_id=client_id, client_secret=client_secret, token=token)
"""
API ENDPOINTS EXAMPLES
"contacts", "acco... | nilq/baby-python | python |
# */
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements. See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership. The ASF licenses this file
# * to you under the Apache License, Version 2.0 (the
# * "License... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import combinations, permutations
import logging
import networkx as nx
import numpy as np
import pandas as pd
# +
# generate a random adjacency matrix
# traces: Number or Domino Traces
# If traces>1 the output will be a data frame of list
# nodes: Number ... | nilq/baby-python | python |
# AUTOGENERATED FILE - DO NOT MODIFY!
# This file generated by Djinni from foo_client_interface.djinni
from djinni.support import MultiSet # default imported in all files
from djinni.exception import CPyException # default imported in all files
from djinni.pycffi_marshal import CPyPrimitive, CPyRecord
from PyCFFIlib_c... | nilq/baby-python | python |
import numpy as np
a = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
print(np.cumsum(a)) # 1 次元 array に変換してから累積和を計算
'''
[ 0 1 3 6 10 15 21 28 36 45 55 66]
'''
print(np.cumsum(a, axis=0)) # 縦方向に累積和を計算
'''
[[ 0 1 2 3]
[ 4 6 8 10]
[12 15 18 21]]
'''
print(np.cumsum(a, axi... | nilq/baby-python | python |
import pytest
try:
import simplejson as json
except ImportError:
import json
from click.testing import CliRunner
from diderypy.cli import main
from diderypy.lib import generating as gen
def parsOutput(data):
return list(filter(None, data.split('\n')))
def testValidConfigFile():
runner = CliRunner()... | nilq/baby-python | python |
import time
import heapq
def curr_time():
return round(time.time() * 1000)
class GameEventPQueue:
''' singleton event queue for the game, event listeners handle different game event types
game events are scheduled in a pqueue for certain events can be handled before others
uses minpqueue since... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This contains a 128x128 px thumbnail in PNG format
# Taken from http://www.zwahlendesign.ch/en/node/20
# openoffice_icons/openoffice_icons_linux/openoffice11.png
# License: Freeware
import base64
iconstr = """\
iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAAG0OVFdAAAABGdBTUEAANbY1E9Y... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.