content
stringlengths
5
1.05M
# coding:utf-8 from __future__ import absolute_import, unicode_literals import click, json from jspider.cli.common import common_pass, common_options __author__ = "golden" __date__ = '2018/6/9' @click.group(name='list') def list_obj(): """show something""" pass @list_obj.command() @common_options @common_p...
import os import shutil import sqlite3 import argparse # http://stackoverflow.com/questions/12517451/python-automatically-creating-directories-with-file-output def copy_file_create_subdirs(src_file, dst_file): if not os.path.exists(os.path.dirname(dst_file)): try: os.makedirs(os.path.dirname(d...
import sys import click import random import webcolors from ete3 import Tree, TreeStyle, NodeStyle, TextFace from typing import List, Dict, AnyStr, Callable # ------------------------------------------------------------------------------- locationColours = {} teamColours = {} allColours = [*webcolors.CSS3_NAMES_TO_H...
from math import ceil from operator import attrgetter import time from flask import Flask, Response, abort, render_template, redirect, request, \ url_for from flask_bootstrap import Bootstrap from . import Mode, YIDashcam, YIDashcamException, \ YIDashcamConnectionException, YIDashcamFileException from .config...
from ..abstract_manifest import AbstractManifest from bitmovin.resources.enums.hls_version import HlsVersion class HlsManifest(AbstractManifest): def __init__(self, manifest_name, outputs, name=None, description=None, id_=None, custom_data=None, hls_media_playlist_version=None, hls_master_playli...
import asyncio import click from pyrobot.rgb_leds import RgbUnderlighting, HsvColor @click.group() @click.pass_context def cli(ctx): ctx.ensure_object(dict) @cli.command() @click.pass_context @click.option('-h', 'h', default=255, show_default=True) @click.option('-s', 's', default=255, show_default=True) @clic...
from abc import abstractmethod class Metric: def on_epoch_starts(self, *args, **kwargs): pass def on_epoch_ends(self, *args, **kwargs): pass def on_task_starts(self, *args, **kwargs): pass def on_task_ends(self, *args, **kwargs): pass def on_batch_starts(self, *...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 Abdelkrime Aries <kariminfo0@gmail.com> # # ---- AUTHORS ---- # 2018 Abdelkrime Aries <kariminfo0@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 ma...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import logging import traceback import tornado.ioloop from tornado import gen from tornado.httpclient import AsyncHTTPClient from data.models import LastDomain, Domain from data.session_mysql import SessionCM __author__ = 'f0x11' headers = { 'User-Agent...
# flake8: noqa from chat.server.core import Server, WebServer from chat.server.requests import Request, ServerRequest server: Server = WebServer() from . import routes
''' interface between networkx graphs and the world of chemistry via rdkit functionality: # gernerating networkx graphs: sdf_to_nx(file.sdf) smi_to_nx(file.smi) smiles_to_nx(smilesstringlist) # graph out: draw(nx) nx_to_smi(graphlist, path_to_file.smi) #bonus: garden style transformer. class MoleculeToGraph ''' fr...
""" LED_Analyze - gui_input_template Date: 15 June 2018 By: Ivan Pougatchev Version: 1.0 """ from tkinter import * from tkinter import messagebox from copy import deepcopy from gui_common import * from analysis_main import InputTemplate, ExtractVal, ExtractRange class TemplateScrFrame(SelectableScrFrame): """ ...
#!/usr/bin/env python """ This script retracts rows for specified pids from the site's submissions located in the archive The pids must be specified via a pid table containing a person_id and research_id The pid table must be located in the sandbox_dataset The schema for the pid table is located in retract_data_bq.py a...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-09-02 01:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recipes', '0005_auto_20170627_0052'), ] operations = [ migrations.AlterFiel...
from simpleaddress import simpleaddress # patch in a data specific value simpleaddress.replacemap["no."]="N" def parts(address): number, street=address.split(" ",1) unit="" for test in [" Suite "," Unit "]: if test in street: street,ste,uni=street.partition(test) unit=ste.l...
# Generated by Django 3.2.5 on 2021-08-05 02:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20210802_1421'), ] operations = [ migrations.CreateModel( name='AttendanceRec...
#!/usr/bin/python # -*- coding: utf-8 -*- """ post_process.py: This file is intended to perform some simple post-processing based on the data files generated by the CMA-ES. """ __author__ = 'Sander van Rijn' __email__ = 's.j.van.rijn@liacs.leidenuniv.nl' from config import experiment_repetitions, fi...
import pandas as pa import plotly import plotly.graph_objects as go path_random = r'C:\Users\AL\Desktop\test\test.csv' test_data_df = pa.read_csv(path_random) test_data_df.head() # trace0 = Scatter(x=[1,2,3,4], y=[1,2,3,4]) # trace1 = Scatter(x=[1,2,3,4], y=[5,6,7,8]) # data = [trace0, trace1] # plotly.offline.plot(d...
import tweepy import random import re while True: # ここに先程取得したAPIキーとトークンを入力 api_key = "" api_secret_key = "" access_token = "" access_token_secret = "" auth = tweepy.OAuthHandler(api_key, api_secret_key) auth.set_access_token(access_token, access_token_secret) api = tweep...
#!/usr/bin/env python3 from setuptools import setup # from distutils.core import setup with open('README.md') as f: long_description = f.read() setup( name = 'py-mgr', packages = ['py_mgr'], version = '0.0.9', description = 'administration of modules and plugin', long_description=long_description, long...
from setuptools import setup, find_packages setup( name='coinmarket-scraper', version='0.0.1', author='avery bostick', packages=['src','tests'], )
def find_min_max(nums): if nums[0]<nums[1]: min = nums[0] max = nums[1] else: min = nums[1] max = nums[0] for i in range(len(nums)-2): if nums[i+2] < min: min = nums[i+2] elif nums[i+2] > max: max = nums[i+2] return (min, max) de...
a = list(input()) cnt = 0 x = 0 for i in range(len(a)-1): if a[i] == a[i+1]: cnt += 1 if x <= cnt: x = cnt elif a[i] != a[i+1]: cnt = 0 print(x+1)
import json import sys from collections import OrderedDict, defaultdict from datetime import date from pathlib import Path from typing import Dict, List class DomainBlocklistConverter: INPUT_FILE = "pihole-google.txt" PIHOLE_FILE = "google-domains" UNBOUND_FILE = "pihole-google-unbound.conf" ADGUARD_...
import httplib import urllib import json def sql_injection(): username = "admin\" AND password LIKE \"" chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" password = "" while True: end = True for char in chars: try_password = password + char ...
from kv_db_interface import KeyValueDatabaseInterface import annoucement_pb2 as announcement_message def main(): kv_db = KeyValueDatabaseInterface(connection_string="sqlite:///proto_buf.db") message_to_serialize = announcement_message.Annoucement() message_to_serialize.sender = "Mikey" message...
#!/usr/bin/env python3 """ The initial use case for this script was needing a tool to append version numbers to all entries within the FASTA file. For example, if you start with a header lines like this: >transcript1_comp4_path3 >transcript1_comp4_path5 And you run this script like this: ./append_to_...
from netapp.netapp_object import NetAppObject class ProcessorComplexInfo(NetAppObject): """ Available information on the processor complex modules (PCMs) in the shelf. """ _is_pcm_element_not_installed = None @property def is_pcm_element_not_installed(self): """ Indicat...
#!/usr/bin/env python3 # Copyright (c) 2008-10 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the Li...
import sys import numpy as np import pandas as pd from google.cloud import bigquery import pandas_gbq as gbq def shRNAPreprocess(input_data, col_name): ''' Description:Preprocesses DEPMAP DEMETER2 data and converts into it long format Inputs: input_data: dataframe,either gene expression, cnv or gen...
from .dataset import * from .coco import * from .balloon import * from .fintabnet import *
# The MIT License (MIT) # # Copyright (c) 2018 stanwood GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, m...
import pickle as cPickle from parameters import CNN_Parameter, Or_Parameter import tensorflow as tf good_par = Or_Parameter(verbose=False) cnn_param = CNN_Parameter(verbose=False) class ConvNet(): def p(self, t): print(t.name, t.get_shape()) def ld_vgg_wts(self): with open(good_par.vgg_weig...
import numpy as np from visgrid.gridworld import skills class DistanceOracle: def __init__(self, env): self.env = env states = np.indices((env._rows, env._cols)).T.reshape(-1, 2) for s in states: for sp in states: # Pre-compute all pairwise distances ...
import os STUDENT_REPOSITORIES = [ "https://github.com/KurtDankovich/360-kurt-dankovich.git", "https://github.com/BryanGabe00/360-bryan-gabe", "https://github.com/RichGol/360-richard-goluszka", "https://github.com/mcclint50/360-colin-mcclintic.git", "https://github.com/JuanMoncada23/360-juan-moncada.git", "https...
""" quick sort algorithm adapted from Wikipedia page @author Axel Ancona Esselmann """ class QuickSort(): def sort(self, A): self._quicksort(A,0,len(A) - 1); def _quicksort(self, A, lo, hi): if lo < hi: p = self._partition(A, lo, hi); self._quicksort(A, lo, p - 1); self._...
from django.conf import settings from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from collections import namedtuple from markdown import markdown from chair_mail.utility import get_absolute_url, markdownify_link, \ markdownify_list from review.models import Review from sub...
from xml.etree import ElementTree from time import time from glob import glob #import multiprocessing import eventlet.green.subprocess as subprocess import socket import os.path import sys import os import simplejson as json import logging import clustohttp import eventlet import memcache import bottle import jinja2 ...
from os import getenv # TELEGRAM OWNER = int(getenv('OWNER')) if OWNER is None: raise Exception("Por favor configura tu Telegram User ID") API_ID = int(getenv('API_ID')) if API_ID is None: raise Exception("Por favor configura el API_ID del Bot") API_HASH = getenv('API_HASH') if API_HASH is None...
import cv2 import numpy as np from numpy import complex, array import colorsys ITERATIONS = 1000 SIZE = 700 # Image size # Convert from number of iterations to RGB def getColour(i): color = (0.4, 0.4, i*10/255.0) return color # function defining a mandelbrot def mandelbrot(x, y, iterations = ITERATIONS): ...
import shutil import pytest from mason.api.get import get from mason.api.apply import apply from mason.definitions import from_root from mason.test.support import testing_base as base from os import path, mkdir class TestGetConfiguration: def test_config_exists(self): env = base.get_env("/test/suppo...
from datetime import datetime from os import environ from json import loads from authlib.client import AssertionSession import gspread """ gspread: https://youtu.be/vISRn5qFrkM https://github.com/burnash/gspread https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption oauth issues: https://github.c...
import string from dataclasses import dataclass from multiprocessing import Queue from random import getrandbits, randrange @dataclass class RawMsg: msg_id: int destination: int msg: string class Supervisor: def __init__(self, msg_count, node_count): self.task_list = [] self.respons...
import math def shell(): print("This piece of software shows Pi to a user definded decimal. (max 15)") while True: print('>>> ', end='') entry = input() if entry == "quit" or entry == "q": break if not entry.isdigit(): print("Thats not a Number. Please ...
""" MIT License Copyright (c) 2020 GamingGeek Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
# -*- coding: utf-8 -*- """ Zentrales Skript für die Bewässerungssteuerung mit den Funktionen main() bewaesserungsablauf() shutdown() main() führt Initialisierungen durch und entscheidet ob der normale Bewässerungsablauf ausgeführt werden soll oder in den Wartungsmodus verzweigt wird Der bewaesserungsabla...
# -*- coding: utf-8 -*- """Runs graph validation tests in the specified folder.""" import logging from kombu import Connection, Exchange, Queue from kombu.mixins import ConsumerMixin from ..hydrators.ingest_hydrator import IngestHydrator from .test_action import TestAction from .common import load_test_queries fr...
from pydantic import BaseModel, validator from tracardi.domain.named_entity import NamedEntity class PushOverAuth(BaseModel): token: str user: str class PushOverConfiguration(BaseModel): source: NamedEntity message: str @validator("message") def name_not_empty(cls, value): if len(va...
import os import json import datasets """Summscreen dataset.""" _CITATION = """ @article{DBLP:journals/corr/abs-2104-07091, author = {Mingda Chen and Zewei Chu and Sam Wiseman and Kevin Gimpel}, title = {SummScreen: {A} Dataset for Abstractive Screenplay Summa...
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
import os import tempfile SLACKVIEWER_TEMP_PATH = os.path.join(tempfile.gettempdir(), "_slackviewer")
# 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...
#! /usr/bin/env python """ Wrap Savannah River test problem for PCGA """ import numpy as np import setup_savannah """ Set the input values for running the problem """ ##describe the geometry of the problem grid_gridgen= "./mesh_files/grid_savannah_river_nx501_ny41" #name of xy gridgen file rect_gridgen= "./mesh_file...
from project.animals.animal import Animal from abc import ABC, abstractmethod class Bird(Animal, ABC): @abstractmethod def __init__(self, name: str, weight: float, wing_size: float, food_eaten=0): super().__init__(name, weight, food_eaten) self.wing_size = wing_size def __repr__(self): ...
import os class TestCli(object): def run_cmd(self, cmd): result = os.popen(cmd) return result def equal(self, cmd, expect): run = self.run_cmd(cmd) result = run.read() # self.assertEqual(result, expect, "Unexpected Result") assert result.find(expect) >= 0
from src.models import Company, Portfolio class TestCompanyModel: """Test new company item.""" def test_create_company(self, company): """New company row is added to Company table.""" assert company.id > 0 def test_company_name(self, company): """New company name added successfull...
#!/usr/bin/python # -*- coding: utf-8 -*- # Code by imanSHA256 import nmap import requests as re from bs4 import BeautifulSoup import socket import bs4 import sys default = "\033[0m" white = '\033[97m' green = '\033[1;32m' red = '\033[1;31m' yellow = '\033[1;33m' magneta = "\033[35m...
from stone.ir import (ApiNamespace, ApiRoute) from stone.ir import ( Boolean, Float32, Float64, Int32, Int64, String, Timestamp, UInt32, UInt64, unwrap_nullable, is_composite_type, is_list_type, is_struct_type, Void, ) from stone.backends import helpers HEADER = ...
import collections from typing import Collection, Container import pandas as pd import os # CONSTANT FOR US REGION NORTH_EAST = ['CT', 'DE', 'MA', 'MD', 'ME', 'NH', 'NJ', 'NY', 'PA', 'RI', 'VT'] MID_WEST = ['IA', 'IL', 'IN', 'KS', 'MI', 'MN', 'MO', 'ND', 'NE', 'OH', 'SD', 'WI'] WEST = ['AK', 'AZ', 'CA', 'CO', 'HI',...
# Инициализируем переменную целочисленным значением var = 8 print(var) # Присваиваем переменной значение числа с плавающей точкой var = 3.142 print(var) # Присваиваем переменной строковое значение var = 'Python in easy steps' print(var) # Присваиваем переменной логическое значение var = True print(var)
# Alain Dechorgnat # 05/19/2014 from flask import Flask, request, Response import json import requests import re from array import * import sys sys.path.append("..") from sfcsmUtil.operate import Operate class Monitors: """docstring for Osds""" def __init__(self): pass class Monito...
from config import ElasticsearchConfig import opensearchpy import hashlib import json from storage import ElasticsearchStorage class TestElasticsearchStorage: def setup(self): config = ElasticsearchConfig.create_from_env() self._es_client = opensearchpy.OpenSearch(config.host) self._es_sto...
import re import scrapy import json from locations.items import GeojsonPointItem from locations.hours import OpeningHours DAY_MAPPING = { "monday": "Mo", "tuesday": "Tu", "wednesday": "We", "thursday": "Th", "friday": "Fr", "saturday": "Sa", "sunday": "Su", } class VitaliaSpider(scrapy....
"""Collection of common functions and other objects used throughout the program.""" import re from typing import Any, Iterable, Union def check_attributes(attrs_to_check: list = None, data: dict = None) -> Union[bool]: """Check to see if attributes specified in a list are contained within a dict. :param att...
#!/usr/bin/env python3 def __init__(hub): global HUB HUB = hub class InvalidStructureError(OSError): def __init__(self, msg): self.hub = HUB self.msg = msg class CorruptedMetarepoError(KeyError): def __init__(self, msg): self.hub = HUB self.msg = msg class Corrupt...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2021 The TARTRL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unle...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'StockPosition.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8...
from ipywidgets import DOMWidget from traitlets import Unicode, Int, Bool from ._version import EXTENSION_SPEC_VERSION module_name = "jupyter-plot-utils" class SimpleShape(DOMWidget): _model_name = Unicode('SimpleShapeModel').tag(sync=True) _model_module = Unicode(module_name).tag(sync=True) _model_modul...
""" Pruning module. Classes: - NoPruning - LazyCountPruning - BucketCountPruning - BatchCountPruning """ import math import logging logger = logging.getLogger(__name__) class NoPruning: """No Pruning class. Does not perform any pruning. """ @classmethod def filter(cls, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from scipy.spatial.transform import Rotation # Part of the code is referred from: https://gi...
from __future__ import annotations import game.entity from game.components.base_component import BaseComponent class Fighter(BaseComponent): def __init__(self, hp: int, base_defense: int, base_power: int): super().__init__() self.max_hp = hp self.hp = hp self.base_defense = base_d...
import unittest import tests.command_download class DownloadTophTest(unittest.TestCase): def snippet_call_download(self, *args, **kwargs): tests.command_download.snippet_call_download(self, *args, **kwargs) def test_call_download_toph_new_year_couple(self): self.snippet_call_download('https:...
from ..common.constants import MODEL_DEEPGO, MODEL_DEEPRED, MODEL_GOLABELER, MODEL_XBERT, MODEL_PROTBERT from .DeepGoPostProcess import DeepGoPostProcess from .PostProcess import PostProcess from pathlib import Path import pandas as pd import logging logger = logging.getLogger(__name__) def get_deepgo_postproces()...
# -*- coding: utf-8 -*- import logging import os import pickle from pathlib import Path from dotenv import find_dotenv, load_dotenv from src.models.train_model import ( train_k_and_radius, train_knn_grouping, train_and_save_catboost_ensemble, ) random_state = 123 def main(): """ Train best 3 models...
''' objects to hold experiments ''' import tkinter as tk import pandas as pd from tkinter import filedialog import time, datetime import os Tk = tk.Tk() Tk.withdraw() class experiment: def __init__(self, data: pd.DataFrame, params: pd.DataFrame, opt=None): ''' :param data: Dataframe holding main d...
#!python3.5 import sys from os import getenv, path from PyQt5 import QtWidgets, QtGui import webbrowser import urllib.parse as parseurl import six.moves # import httplib2 # import urllib3 import pyperclip import pickle #import oauth2 import tweepy #import twitter # Custom Packages import GlyphGrabber # UI Import from...
#!/usr/bin/python """ Author: Fabio Hellmann <info@fabio-hellmann.de> """ from attr import s, ib from attr.validators import instance_of from enum import Enum, unique from datetime import datetime @unique class StructPacking(Enum): PIN = '<I' BATTERY = '<B' DATETIME = '<BBBBB' STATUS = '<BBB' ...
''' Similar : https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ ''' class Day34(object): def min_insertions(self, string): """ :type s: str :rtype: int """ self.string = string s_len = len(string) dp = [[None for _ in range...
import math import warnings import tlz as toolz from fsspec.core import get_fs_token_paths from fsspec.implementations.local import LocalFileSystem from fsspec.utils import stringify_path from ....base import tokenize from ....delayed import Delayed from ....highlevelgraph import HighLevelGraph from ....layers import...
from unittest import TestCase from boto3_utils import ( dict_to_key_value, key_value_to_dict, snake_to_camel_case, make_tag_dict, ) class TestSnakeToCamelCase(TestCase): """Test Suite for snake_to_camel_case function.""" def setUp(self): self.answers = {'http_response':'HTTPResponse'} de...
import torch import torch.nn as nn import os from torch.autograd import Variable import argparse from model.resnet import resnet101 from dataset.My_Test import MyTest parser = argparse.ArgumentParser() parser.add_argument('--num_workers', type=int, default=2) parser.add_argument('--batchSize', type=int, de...
USER_NAME = '' USER_PWD = ''
from rest_framework import serializers from core.models import Category, Article, Comment from user.serializers import UserSerializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'title', 'slug') read_only_fields = ('id',) class Ab...
# -*- coding: utf-8 -*- __author__ = 'Meanwhile' import pymongo import Constants #create dabases use vk_parser #loc : [ <longitude> , <latitude> ] ''' СОздать индекс на дату ''' class ProvaderStorage: def __init__(self): self.client = pymongo.MongoClient(Constants.Constants.getMongoServer(), ...
import logging import pathlib from types import SimpleNamespace import click import parse import dtoolcore import skimage.measure import pandas as pd from dtoolbioimage import Image as dbiImage from fishtools.config import Config from fishtools.data import DataLoader, get_specs from fishtools.segment import segmenta...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-27 11:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('utils', '0008_auto_20160524_1436'), ] operations = [ migrations.AddField( ...
import ResModel import tensorflow as tf import numpy as np import re from yolo.net.net import Net class YoloTinyNet(Net): def __init__(self, common_params, net_params, test=False): """ common params: a params dict net_params : a params dict """ super(YoloTinyNet, self).__init__...
#!python3 import pandas as pd import numpy as np import os from Bio import AlignIO from Bio.Alphabet.IUPAC import IUPACUnambiguousDNA from Bio.Data.CodonTable import TranslationError from ete3 import Tree f = os.path.abspath('..') + "/DataEmpirical/Cetacea" phy = AlignIO.read("{0}/datadryad/DATASET_B.phylip".format(f...
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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...
import csv from os import getcwd import pandas as pd sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')] classes = ["go","stop","warning"] wd = getcwd() wd = '/home/coldrain/data/' sim = pd.read_csv(wd+'VOCdevkit/VOC2007/JPEGImages/annotation.csv') def convert_annotation(year, image_id, list_file): for ...
def histogram(s): d = dict() for c in s: d[c] = d.get(c, s.count(c)) return d h = histogram('brontosaurus') print(h)
from functools import wraps from statsmodels.tools.data import _is_using_pandas from statsmodels.tsa.base import datetools from statsmodels.tsa.tsatools import freq_to_period def _get_pandas_wrapper(X, trim_head=None, trim_tail=None, names=None): index = X.index #TODO: allow use index labels if trim_head...
class Solution: def XXX(self, str: str) -> int: s=0 d={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9} flag=True sign=1 for char in str: if char==' ' and flag: continue elif char=='-' and flag: sign=-1 ...
import sys import socket import threading opened_ports = [] socket_instance = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mutex = threading.Lock() def is_valid_ipv4_address(address): try: socket.inet_pton(socket.AF_INET, address) except AttributeError: try: socket.inet_aton(...
from commands.command import Command from fbchat import Message from fbchat import Mention class countdown(Command): def run(self): if 'countdown' not in self.database: self.database['countdown'] = "enabled" mentions = [Mention(self.author_id, length=len(self.author.first_name) + 1)] ...
import tensorflow as tf from absl.testing import parameterized from model.architectures.losses import Momentum_Neighbors_NT_X, Momentum_NT_X, get_neighbors_mask_temporal, \ get_neighbors_dt_label_multiclass class LossTest(parameterized.TestCase, tf.test.TestCase): @parameterized.named_parameters(("base",)) ...
## @package SimpleKL Provides some simple kinematic functions import numpy as np from Module import * ## Rotation matrix around x axis # @param row Row # @return Numpy matrix object of rotation matrix def rotx(row): return np.matrix([[1,0,0],[0,np.cos(row),-np.sin(row)],[0,np.sin(row),np.cos(row)]]) ## Rotation matri...
from pathlib import Path from re import compile import pytest from tests.unit.conftest import FIXTURE_PATH, does_not_raise, rule_path from whispers.plugins import Yml from whispers.rules import WhisperRules from whispers.utils import load_yaml_from_file @pytest.mark.parametrize( ("rulefile", "expectation"), ...
from set_additive import * from ff import * from set_additive import applicable as sa_applicable, first_goals as sa_first_goals, \ first_operators as sa_first_operators, first_combine as sa_first_combine from planner.main import default_plan, simple_debug from planner.progression import * def h_0(state, goal, operat...
from rest_framework import serializers from .models import Map class MapSerializer(serializers.ModelSerializer): class Meta: model = Map fields = ('id', 'name', 'size', 'category', 'broken', 'Tscore', 'valid', 'objects')