content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# Authors: Jose C. Garcia Alanis <alanis.jcg@gmail.com> # # License: BSD-3-Clause # -- WIP -- { fig, ax = plt.subplots() im = ax.imshow(np.median(channel_corrs, axis=0), cmap="YlGn", ) # Create colorbar cbar = ax.figure.colorbar(im, ax=ax) cbar.ax.set_ylabel('Channels correlation', rotation=-90, va="bottom") # Show al...
nilq/baby-python
python
class Aws_Utils: @staticmethod def run_code_in_lambda(code): file_Path = 'temp_code/code.py' temp_Dir = 'temp_code' zip_file = 'temp_code.zip' def create_temp_files(): if not os.path.exists(temp_Dir): os.mkdir(temp_Dir) with open(file_P...
nilq/baby-python
python
# # resolution(KB, q): Given a propositional knowledge base and query, return # whether the query can be inferred from the knowledgebase using resolution. # The implementation is more efficient than pl_resolution in the AIMA code. # KnowledgeBasedAgent: An abstract class that makes decisions to navigate # through a w...
nilq/baby-python
python
from django.db import models from ...apps import UFDLCoreAppConfig class LicenceQuerySet(models.QuerySet): """ A query-set of data-set licences. """ pass class Licence(models.Model): """ The licence for a data-set. """ # The name for the licence name = models.CharField(max_lengt...
nilq/baby-python
python
""" This script contains all the functions related to the model """ import tensorflow as tf import numpy as np import random from math import ceil from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, LeakyReLU, Dropout from game import MOVES_POSSIBLE, ALL_BLOCK_PO...
nilq/baby-python
python
from Templates.make_excel import make2exel import Main.Tenderplan.participants2excel as p2ex import openpyxl excel_name = r'E:\Лиды_экспорт.xlsx' make2exel( ['Название компании', 'ИНН', 'Список выигранных тендеров', 'Список остальных тендеров c участием'], excel_name) wb = openpyxl.load_workbook(excel_name) she...
nilq/baby-python
python
#!/usr/bin/env python from HTMLParser import HTMLParser import re import os import sys import string class Html2MarkdownParser(HTMLParser): def __init__(self): self._markdown = '' self._tag_stack = [] self._tag_attr_data = {} self._handled_tag_body_data = '' self._converti...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function def pe5(n=20): """ What is the smallest number divisible by each of the numbers 1 to 20? >>> pe5() 232792560 """ if n < 2: return 1 p = 2 m = [2] for x in range(3, n + 1): ...
nilq/baby-python
python
import aiohttp import argparse import asyncio import ssl from urllib.parse import urlsplit from bs4 import BeautifulSoup from sitemap.utils import write_text_sitemap, clean_link # Have these at global scope so they remain shared. urls = [] results = [] def sitemap(url, verbose=False): """ Main mapping functio...
nilq/baby-python
python
import list_wifi_distances import requests def report(rogue_mac): pi_id = 8 distance = list_wifi_distances.get_network(rogue_mac.upper()) print(distance) requests.post("http://10.10.10.93:8000/report", data={'id':pi_id, 'dist': distance})
nilq/baby-python
python
import logging from cellfinder.figures import heatmap def run(args, atlas, downsampled_shape): logging.info("Generating heatmap") heatmap.run( args.paths.downsampled_points, atlas, downsampled_shape, args.brainreg_paths.registered_atlas, args.paths.heatmap, smo...
nilq/baby-python
python
# Generated by Django 3.1.2 on 2021-04-08 02:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bpmn', '0001_initial'), ] operations = [ migrations.CreateModel( name='Diagram', fi...
nilq/baby-python
python
"""Aramaic Bible Module tool""" from pathlib import Path import click from abm_tools.sedra.bible import parse_sedra3_bible_db_file from abm_tools.sedra.db import from_transliteration, parse_sedra3_words_db_file, sedra4_db_word_json @click.group() def tool(): """Tools for generating Aramaic bible software module...
nilq/baby-python
python
#!/usr/bin/env python >>> import snmp_helper c. Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and prints out both the MIB2 sysName and sysDescr.
nilq/baby-python
python
## ## ## import queue class BundGrammarQueue: def __init__(self): self.q = {} self.default_queue_name = "__root__" self.createLIFO("__root__") def queue(self, name, auto_create=True): if name not in self.q: if auto_create: self.default_queue_name = na...
nilq/baby-python
python
import vcr from umm.cli.client import umm_request from umm.server.utils import setup_folder @vcr.use_cassette() def test_umm_request(): setup_folder() resp = umm_request([]) assert resp == {"commands": []}
nilq/baby-python
python
""" Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ """Fabric commands for pack...
nilq/baby-python
python
def fun(x: int) -> str: return str(x) class SomeClass: def meth(self, x: int) -> str: return str(x)
nilq/baby-python
python
from typing import ( Any, Callable, Dict, Iterable, Iterator, NamedTuple, Optional, Set, ) from contextlib import contextmanager import pendulum import prefect from prefect.core import Edge, Flow, Task from prefect.engine.result import Result from prefect.engine.results import ConstantR...
nilq/baby-python
python
''' Menu Module Module to deal with menus and buttons. Used initially for start menu. Can be extended if required to create pause and other menues throughout the game. @author: Robert (unless stated otherwise) ''' import pygame from classes.text import Text from classes.sfxbox import SFXBox button_...
nilq/baby-python
python
from loguru import logger import cv2 import os import pickle import typing import numpy as np from sklearn.svm import LinearSVC from stagesepx.classifier.base import BaseModelClassifier from stagesepx import toolbox from stagesepx.video import VideoFrame from stagesepx import constants class SVMClassifier(BaseModelC...
nilq/baby-python
python
from fastapi import APIRouter from client.api.api_v1.endpoints import twitter, disk_space router = APIRouter() router.include_router(disk_space.router, prefix="/diskspace", tags=["diskspace"]) router.include_router(twitter.router, prefix="/twitter", tags=["twitter"])
nilq/baby-python
python
import socket import imagezmq import cv2 import time sender = imagezmq.ImageSender(connect_to='tcp://localhost:5555') sender_name = socket.gethostname() # send your hostname with each image # image = open("C:/Users/H S/PycharmProjects/Kivy/Untitled.png", 'rb') image = cv2.imread("C:/Users/H S/PycharmProjects/Kivy/Unt...
nilq/baby-python
python
import zerorpc client = zerorpc.Client() client.connect("tcp://127.0.0.1:4242") num = 7 result = client.double(num) print("Double", num, "is", result)
nilq/baby-python
python
from Components.Converter.Converter import Converter from Components.config import config from Components.Element import cached from Poll import Poll from enigma import eDVBVolumecontrol class ArcticVolume(Poll, Converter): def __init__(self, val): Converter.__init__(self, val) Poll.__...
nilq/baby-python
python
############################################################################### # WaterTAP Copyright (c) 2021, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National # Laboratory, National Renewable Energy Laboratory, and National Energy # Technology Laboratory ...
nilq/baby-python
python
import os import csv import timeit from datetime import datetime import numpy import logging import coloredlogs import numpy as np import argparse import copy import json import re import sys import onnxruntime from onnx import numpy_helper from perf_utils import * import pprint import time from float16 import * # impo...
nilq/baby-python
python
from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) image = models.ImageField(upload_to='person_images')
nilq/baby-python
python
import os import click from flask import current_app from sqlalchemy import text from app import db def register(app): @app.cli.group() def translate(): """Translation and localization commands.""" pass @translate.command() @click.argument('lang') def init(lang): """In...
nilq/baby-python
python
from __future__ import annotations import attr __all__ = ("AllowedMentions",) @attr.s(kw_only=True) class AllowedMentions: """Represents an allowed mentions object. This is used to determine the allowed mentions of any messages being sent from the client's user. Parameters ---------- everyone:...
nilq/baby-python
python
import csv class PlayerThumbnails: def getThumbnailsID(): ThumbnailsID = [] with open('Logic/Files/assets/csv_logic/player_thumbnails.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if lin...
nilq/baby-python
python
""" This file contains all the HTTP routes for basic pages (usually HTML) """ from flask import Blueprint, render_template, request import _config as config pages = Blueprint('controller', __name__) @pages.route('/') def index(): """ A basic landing page for this web service :return: HTTP Response (HTM...
nilq/baby-python
python
"""The Snooty documentation writer's tool.""" __version__ = "0.9.6.dev"
nilq/baby-python
python
#!/usr/bin/env python from subprocess import Popen from subprocess import PIPE class ChromeHtmlToPdf(): def __init__(self, url, output_path=None, verbose=False): ''' Initialize class with google chrome parameters Params: Return: ''' ...
nilq/baby-python
python
from streaming.app import app from streaming.config import config from streaming.phishtank.api import Reported # Topics reports_topic = app.topic('phishtank-reports') # Tables states_table = app.Table('phishtank-state', default=str) @app.agent(reports_topic) async def get_phishtank_reports(states): async for sta...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: UTF-8 -* from common.common_time import get_system_datetime from db.base import DbBase from db.connection_pool import MysqlConn import copy import datetime from utils.status_code import response_code from config import configuration import traceback import json import os from config impo...
nilq/baby-python
python
from .api import process_large_corpus, process_small_corpus, \ process_belscript, process_pybel_graph, process_json_file, \ process_pybel_neighborhood, process_cbn_jgif_file, \ process_bel_stmt
nilq/baby-python
python
from distutils.core import setup version = "1.2" setup( name='chainee', packages=['chainee'], version=version, license='MIT', description='Chain your predicates, easy way.', author='Yaroslav Pankovych', author_email='flower.moor@gmail.com', url='https://github.com/ypankovych/chainee', ...
nilq/baby-python
python
# The idea here is to store all the different things you need for Code in one module # Code can then import the module and call whatever functions are needed # R. Sheehan 27 - 10 - 2020 MOD_NAME_STR = "Measurement" # import the necessary modules import board import time import digitalio from analogio import AnalogOut...
nilq/baby-python
python
import pytest import main from time import time import hmac import hashlib from unittest.mock import Mock from unittest.mock import MagicMock def test_valid_signature(): timestamp = int(time()) slack_signing_secret = 'abcdefg' main.slack_signing_secret = slack_signing_secret req_body = 'abcdefgabcdefg...
nilq/baby-python
python
from matchbook.apiclient import APIClient from matchbook.exceptions import MBError __title__ = 'matchbook' __version__ = '0.0.9'
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Test Generic Map """ import os import pytest import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord import matplotlib.pyplot as plt import sunpy import sunpy.map import sunpy.coordinates import sunpy.data.test from sunpy.tests.helpers import figure_test tes...
nilq/baby-python
python
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # this should be fine, but failed with pychecker 0.8.18 on python 2.6 def func(): d = { 'a': 1, 'b': 2} print d.keys()
nilq/baby-python
python
import torch import torch.nn as nn import torch.nn.init as init import numpy as np import math import torchvision.utils as tvu from torch.autograd import Variable import matplotlib.pyplot as plt def generate_images(generator, centers, num_clusters, alpha, z_dim, device): idx_centers = torch.from_numpy(np.random.c...
nilq/baby-python
python
import os import numpy as np def _download_and_extract(url, path, filename): import shutil, zipfile import requests fn = os.path.join(path, filename) while True: try: with zipfile.ZipFile(fn) as zf: zf.extractall(path) print('Unzip finished.') ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = 'Chao Wu' r''' python C:\Users\cwu\Desktop\Software\Papers\pH_effect\plot_ph_effect_contour\plot_contour.py ''' import os import numpy as np import pandas as pd import matplotlib.pyplot as plt EPCS_FILE = 'path\to\epcs.xlsx' DGPS_FILE = 'path\to\dgps.xl...
nilq/baby-python
python
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib.patches import Polygon import numpy as np import stader d = stader.load_aircraft('b747_flight_condition2') ac = stader.Aircraft(d) msec = 15 dt = msec/1000 show_state = False if show_state: fig = plt.figure(figsize=(1...
nilq/baby-python
python
import os.path from lsst.meas.base import CircularApertureFluxAlgorithm config.measurement.load(os.path.join(os.path.dirname(__file__), "apertures.py")) config.measurement.load(os.path.join(os.path.dirname(__file__), "kron.py")) config.measurement.load(os.path.join(os.path.dirname(__file__), "convolvedFluxes.py")) co...
nilq/baby-python
python
import pyglet from pyglet.gl import * blueDot = pyglet.resource.image('blue-dot.png') redDot = pyglet.resource.image('red-dot.png') class Window(pyglet.window.Window): """docstring for Window""" def __init__(self): print("Init Window") super(Window, self).__init__(500, 400, vsync=False) ...
nilq/baby-python
python
# -*- coding:utf-8 -*- import logging from flask import request from flask_restx import Namespace from app.spider.csdn.csdn import CSDN from app.spider.toutiao.toutiao_hotnews import ToutiaoNews from app.api.util.base_resource import BaseResource from app.api.util.web_response import WebResponse from app.api.util.web...
nilq/baby-python
python
"""Singleton Class""" # standard library import threading class Singleton(type): """A singleton Metaclass""" _instances = {} _lock = threading.Lock() def __call__(cls, *args, **kwargs): """Evoke call method.""" with cls._lock: if cls not in cls._instances: ...
nilq/baby-python
python
def print_two(*args): # :TODO *args are for funcs and argv for inputs arg1, arg2 = args print('arg1: %r, arg2: %r' % (arg1, arg2)) def print_two_again(arg1, arg2): print('arg1: %r, arg2: %r' % (arg1, arg2)) print_two("zdr", "zdr") print_two_again("zdr", "zdr")
nilq/baby-python
python
import os import sys import time import requests from py2neo import Graph, Node, Relationship graph = Graph() graph.run("CREATE CONSTRAINT ON (u:User) ASSERT u.username IS UNIQUE") graph.run("CREATE CONSTRAINT ON (t:Tweet) ASSERT t.id IS UNIQUE") graph.run("CREATE CONSTRAINT ON (h:Hashtag) ASSERT h.name IS UNIQUE") ...
nilq/baby-python
python
import os import shutil def create_analysis_folder(folder_name): if not os.path.exists(folder_name): os.makedirs(folder_name) shutil.copy('ffield', folder_name) shutil.copy('parameters', folder_name)
nilq/baby-python
python
from collections import defaultdict import boto3 import click from halo import Halo from termcolor import colored, cprint from ..app import app from ..utils import formatted_time_ago def task_id(task_detail: dict) -> str: tags = {t["key"]: t["value"] for t in task_detail["tags"]} try: return tags["p...
nilq/baby-python
python
from setuptools import setup with open("README.md", "r", encoding="utf-8") as f: long_description = f.read() setup( name="sku", version="0.2", description="scikit-learn Utilities", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/myt...
nilq/baby-python
python
# sim_core/views.py ################# #### imports #### ################# from app import app from flask import render_template, Blueprint from logger import logger from flask import current_app ################ #### config #### ################ sim_core_blueprint = Blueprint('sim_core', __name__, static_folder=...
nilq/baby-python
python
from unittest import TestCase from demands.pagination import PaginatedResults, PaginationType class PaginationTestsMixin(object): args = (1, 2, 3) kwargs = {'one': 1, 'two': 2} def get(self, start, end, *args, **kwargs): self.assertEqual(args, self.args) self.assertEqual(kwargs, self.kwa...
nilq/baby-python
python
N, arr = int(input()), input().split() print(all([int(i) > 0 for i in arr]) and any([i == i[::-1] for i in arr]))
nilq/baby-python
python
import tkinter as tk import tkinter.filedialog as fd import src.helper.gui as hg from src.image.extractor import Extractor from src.helper.file import File class ImageExtractForm(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller ...
nilq/baby-python
python
import copy import operator from functools import cached_property, reduce from typing import Dict, List, Optional import torch import torch.nn as nn from torch import Tensor from torch.nn.functional import mse_loss from torch.optim import Adam from ai_traineree import DEVICE from ai_traineree.agents import AgentBase ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ flask_jsonschema ~~~~~~~~~~~~~~~~ flask_jsonschema """ import os from functools import wraps try: import simplejson as json except ImportError: import json from flask import current_app, request from jsonschema import ValidationError, validate class _JsonSchema(obj...
nilq/baby-python
python
from tortoise.contrib.pydantic import pydantic_model_creator from typing import Optional from pydantic import BaseModel from db.models import Meals MealsInSchema = pydantic_model_creator( Meals, name="MealIn", exclude_readonly=True ) MealsOutSchema = pydantic_model_creator( Meals, name="MealOut", exclude=["c...
nilq/baby-python
python
""" Host Guest Complex ================== """ from __future__ import annotations import typing from collections import abc from ...molecules import BuildingBlock from ...reactions import GenericReactionFactory from ..topology_graph import ( ConstructionState, NullOptimizer, Optimizer, TopologyGraph,...
nilq/baby-python
python
import bs4 import json import requests import time from utils import (get_content, get_soup, save_json, load_json) MANGA_SEARCH_URL = 'https://myanimelist.net/manga.php?type=1&q=' # load series information all_series = load_json("data.json") for series in all_series: # search on MyAnimeList query_soup = get...
nilq/baby-python
python
from random import randint from game_map.direction import Direction from game_map.rect import Rect class Room(Rect): """ A Room is just a Rect that can tell you where its walls are """ def __init__(self, x, y, width, height): super(Room, self).__init__(x, y, width, height) def get_wall(se...
nilq/baby-python
python
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here from collections import deque, defaultdict ...
nilq/baby-python
python
import unittest from mock import Mock from foundations_events.producers.jobs.run_job import RunJob class TestProducerRunJob(unittest.TestCase): def setUp(self): from foundations_internal.foundations_job import FoundationsJob self.route_name = None self.message = None self._fou...
nilq/baby-python
python
import os TEST_DIR = os.path.realpath(os.path.dirname(__file__))
nilq/baby-python
python
# Copyright (c) 2017-2019 Intel Corporation # # 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...
nilq/baby-python
python
import logging from logger_config import configure_logging logger_name = 'root_logger' configure_logging(logger_name, log_dir='logs') logger = logging.getLogger(logger_name) logger.warning('This is warning') logger.error('This is exception') logger.info('This is info message') logger.debug('This is debug message')
nilq/baby-python
python
# All edits to original document Copyright 2016 Vincent Berthiaume. # # Copyright 2015 The TensorFlow Authors. 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 # # ht...
nilq/baby-python
python
__version__ = '3.0.8' __buildinfo__ = {'branch': 'BRANCH_NOT_SET', 'last_commit': 'COMMIT_NOT_SET'}
nilq/baby-python
python
from dash import dcc import dash_bootstrap_components as dbc # pip install dash-bootstrap-components from dash import Input, Output, State, html from app import app # Lotties: Emil at https://github.com/thedirtyfew/dash-extensions url_sunlight = "https://assets8.lottiefiles.com/packages/lf20_bknKi1.json" url_earth = ...
nilq/baby-python
python
""" Tatoeba (https://tatoeba.org/) is a collection of sentences and translation, mainly aiming for language learning. It is available for more than 300 languages. This script downloads the Tatoeba corpus and extracts the sentences & translations in the languages you like """ import os import sentence_transformers impo...
nilq/baby-python
python
from django.test import TestCase from unittest2 import skipIf from django.db import connection import json import re from sqlshare_rest.util.db import get_backend from sqlshare_rest.test import missing_url from django.test.utils import override_settings from django.test.client import Client from django.core.urlresolver...
nilq/baby-python
python
from rest_framework import status from rest_framework.test import APITestCase from .. import models from .. import serializers class DocumentTopicTestCase(APITestCase): URL = '/v1/m2m/document/topic/' DOCUMENT_URL = '/v1/document/' def test_create_document_topic(self): topic_data = { ...
nilq/baby-python
python
#!/usr/bin/env python import sys import numpy from numpy import matrix class Policy(object): actions = None policy = None def __init__(self, num_states, num_actions, filename='policy/default.policy'): try: f = open(filename, 'r') except: print('\nError: unable to open file: ' + filename) ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Credits: Benjamin Dartigues, Emmanuel Bouilhol, Hayssam Soueidan, Macha Nikolski import pathlib from loguru import logger import constants import plot import numpy as np import helpers from image_set import ImageSet from helpers import open_repo from path import global_r...
nilq/baby-python
python
import matplotlib import matplotlib.colors as colors import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import networkx as nx import numpy as np import sklearn.metrics as metrics import torch import torch.nn as nn from torch.a...
nilq/baby-python
python
#!/usr/bin/env python3 import pandas as pd def cyclists(): df = pd.read_csv('src/Helsingin_pyorailijamaarat.csv', sep=';') # [Same as line below]: df = df[df.notna().any(axis=1)] df = df.dropna(how='all') df = df.dropna(how='all', axis=1) return df def main(): print(cyclists()) if __name...
nilq/baby-python
python
def calc_fitness(pop): from to_decimal import to_decimal from math import sin, sqrt for index, elem in enumerate(pop): # só atribui a fitness a cromossomos que ainda não possuem fitness # print(elem[0], elem[1]) x = to_decimal(elem[0]) y = to_decimal(elem[1]) # x = ...
nilq/baby-python
python
import os from typing import Tuple, List from tokenizers import BertWordPieceTokenizer, Tokenizer import sentencepiece as spm from enums.configuration import Configuration from services.arguments.pretrained_arguments_service import PretrainedArgumentsService from services.file_service import FileService class Bas...
nilq/baby-python
python
#!/usr/bin/env python3 import fileinput import hashlib salt = '' for line in fileinput.input(): salt = line.strip() def md5(i): return hashlib.md5((salt + str(i)).encode('utf-8')).hexdigest() def checkNple(s, n): i = 0 while i < len(s): char = s[i] consecutive = 0 while i < ...
nilq/baby-python
python
txt = ''.join(format(ord(x), 'b') for x in 'my foo is bar and baz') print txt from collections import Counter secs = { '60': '111100', '30': '11110', '20': '10100', '12': '1100', '10': '1010', '6': '110', '5': '101', '3': '11', '2': '10', '1': '1', '0': '0', ...
nilq/baby-python
python
############################################# # --- Day 8: I Heard You Like Registers --- # ############################################# import AOCUtils class Instruction: def __init__(self, inst): inst = inst.split() self.reg = inst[0] self.mul = {"inc": 1, "dec": -1}[inst[1]] s...
nilq/baby-python
python
import datetime import geospacelab.express.eiscat_dashboard as eiscat dt_fr = datetime.datetime.strptime('20201209' + '1800', '%Y%m%d%H%M') dt_to = datetime.datetime.strptime('20201210' + '0600', '%Y%m%d%H%M') # check the eiscat-hdf5 filename from the EISCAT schedule page, e.g., "EISCAT_2020-12-10_beata_60@uhfa.hdf5"...
nilq/baby-python
python
from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib.auth.models import User from django.conf import settings from postgresqleu.util.fields import LowercaseEmailField from postgresqleu.countries.models import Country from postgresqleu.invoices.models ...
nilq/baby-python
python
import numpy as np def readLine(line): return [ int(c) for c in line.split(' ') ] def schedule(activities): lastC = 0 lastJ = 0 sortedSchedule = '' sortedActivities = sorted(activities, key=lambda a: a[1]) for a in sortedActivities: if a[1] >= lastC: sortedSchedule += 'C'...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # slim主要是做代码瘦身-2016年开始 slim = tf.contrib.slim # 5 x Inception-Resnet-A def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Build the 35 x 35 resnet b...
nilq/baby-python
python
# ------------------------------------------------------------------------- # function: classes,type = dbscan(x, k, Eps) # ------------------------------------------------------------------------- # Objective: # Clustering the data with Density - Based Scan Algorithm with Noise (DBSCAN) # -------------------------...
nilq/baby-python
python
# form test
nilq/baby-python
python
# -*- coding: utf-8 -*- """ 测试方法: 1. 执行 s1, s2, s3 确保 document 被创建, 并且 value = 0 2. 打开两个 terminal 输入 python e3_concurrent_update.py 3. 快速在两个 terminal 按下 enter 运行. 效果是对 value 进行 1000 次 +1, 由于有两个 并发, 所以互相之间会争抢 4. 执行 s4, 查看 value 是否是 2000 ES 中处理并发的策略详解 https://www.elastic.co/guide/en/elasticsearch/reference/current...
nilq/baby-python
python
# -*- coding: utf-8 -*- import numpy as np from skued import azimuthal_average, powdersim from crystals import Crystal import unittest from skimage.filters import gaussian np.random.seed(23) def circle_image(shape, center, radii, intensities): """ Creates an image with circle or thickness 2 """ im = np.ze...
nilq/baby-python
python
# Copyright 2018 Luddite Labs Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
nilq/baby-python
python
import os import io import sys import time import string import random import pstats import unittest import cProfile import itertools import statistics from unittest.mock import patch, MagicMock import bucky3.statsd as statsd class RoughFloat(float): def __eq__(self, other): if not isinstance(other, flo...
nilq/baby-python
python
import os import cv2 import numpy as np import torch # from utils import cropping as fp from csl_common.utils import nn, cropping from csl_common import utils from landmarks import fabrec from torchvision import transforms as tf from landmarks import lmvis snapshot_dir = os.path.join('.') INPUT_SIZE = 256 transfo...
nilq/baby-python
python
from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin class NewFatpercentageView(LoginRequiredMixin, TemplateView): template_name = "new_fatpercentage.html" class FatpercentageView(LoginRequiredMixin, TemplateView): temp...
nilq/baby-python
python
import sys from io import StringIO def io_sys_stdin(): """标准输入流 Ctrl + D 结束输入 """ for line in sys.stdin: # 按行分割输入 s = line.split() # 该步返回一个 list,按空格分割元素 print(s) def io_input(): """使用 input() 读取输入,会将输入内容作为表达式 以换行符为结束标志 Python 3 没有 raw_input() 方法,以 input() 代替 """ ...
nilq/baby-python
python
# # Copyright 2014 Thomas Rabaix <thomas.rabaix@gmail.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/licenses/LICENSE-2.0 # # Unless required by applicable law...
nilq/baby-python
python