text
string
size
int64
token_count
int64
import os, sys srcFolder = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'src') sys.path.append(srcFolder) from metrics import nss from metrics import auc from metrics import cc from utils import * import numpy as np import argparse parser = argparse.ArgumentParser(description='Evaluate predicted saliency...
2,507
965
from pandas import Series class Evaluator: series: Series def __init__(self, series: Series): self.series = series self.unique_series = [value for value in self.series.dropna().unique()] def series_match(self, pattern: str): return Series(self.unique_series).astype(str).str.match...
482
146
# -*- coding: utf-8 -*- # Importação da biblioteca import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 7, 1, 0] titulo = "Gráfico de barras" eixoX = "EixoX" eixoY = "EixoY" # Legendas plt.title(titulo) plt.xlabel(eixoX) plt.ylabel(eixoY) plt.bar(x, y) plt.show()
294
168
# Org_v01 by Orgdot (www.orgdot.com/aliasfonts). A tiny, # stylized font with all characters within a 6 pixel height. Org_01Bitmaps = [ 0xE8, 0xA0, 0x57, 0xD5, 0xF5, 0x00, 0xFD, 0x3E, 0x5F, 0x80, 0x88, 0x88, 0x88, 0x80, 0xF4, 0xBF, 0x2E, 0x80, 0x80, 0x6A, 0x40, 0x95, 0x80, 0xAA, 0x80, 0x5D, 0x00, 0xC0, 0x...
7,189
4,904
# Generated by Django 3.1.8 on 2021-05-26 11:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('manager', '0004_auto_20210519_1334'), ] operations = [ migrations.AddField( model_name='director', name='service_mes...
411
150
from django.db import models from resources_portal.models.material import Material from resources_portal.models.user import User class MaterialShareEvent(models.Model): class Meta: db_table = "material_share_events" get_latest_by = "created_at" objects = models.Manager() created_at = mo...
1,053
323
""" Archived flu data http://webarchive.nationalarchives.gov.uk/20130107105354/http://www.dh.gov.uk/en/Publicationsandstatistics/Statistics/Performancedataandstatistics/DailySituationReports/index.htm """ import collections import calendar import datetime import re import urllib from lxml.html import fromstring, tostr...
1,941
652
from rest_framework.serializers import ModelSerializer from .models import MonthlyBudget class MonthlyBudgetSerializer(ModelSerializer): class Meta: model = MonthlyBudget fields = '__all__'
213
60
from behave import * from google.cloud import datastore import os import uuid import pandas as pd @given('site "{site}" exists') def step_impl(context, site): print(f'STEP: Given provider {site} exists') context.domain = os.getenv('DOMAIN') # Instantiates a client datastore_client = datastore.Client()...
2,786
898
import os gpu_flag = False gpu_name = 'cpu' x_dim = 2048 num_class = 87 num_query = 5 batch_size = 84 eval_batch_size = 128 glove_dim = 200 pretrain_lr = 1e-4 num_epochs_pretrain = 20 eval_step_pre = 1 fusion_iter_len = 100000 # num_epochs_pretrain = 30 num_epochs_style = 30 num_epochs_fusion = 50 log_step_pre = ...
2,137
895
# -*- coding: utf-8 -*- from __future__ import print_function import caffe from caffe import params as P from google.protobuf import text_format #import inputParam import os import sys import math sys.path.append('../') from username import USERNAME sys.dont_write_bytecode = True # #####################################...
882
315
# -*- coding: utf-8 -*- from typing import Any from typing import Dict from typing import Optional from typing import Set from unittest import TestCase from flask import abort from app import create_app from app import db from app.configuration import TestConfiguration from app.userprofile import Permission from ap...
17,567
4,488
# Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk # # 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 l...
1,483
415
# Zipfile Module import zipfile # Open and List zip = zipfile.ZipFile('Archive.zip', 'r') print(zip.namelist()) # Lists everything within zip file # Metadata in the zip folder for meta in zip.infolist(): # List of the metadata within zip file print(meta) info = zip.getinfo("purchased.txt") # Access to files in ...
644
216
"""Recommendation Algorithm Base Class This module is a base class for algorithms using sparse matrices The required packages can be found in requirements.txt """ import pandas as pd import numpy as np from lenskit import batch, topn, util from lenskit import crossfold as xf from lenskit.algorithms import Recommende...
4,059
1,175
# -*- coding: utf-8 -*- """ This module implements the User functionality of TheTVDb API. Allows to retrieve, add and delete user favorites and ratings. See [Users API section](https://api.thetvdb.com/swagger#!/Users) """ from .base import TVDB class User(TVDB): """ User class to retrieve, add and delete us...
8,871
2,626
#!/usr/bin/env python import re from binaryninja.log import log_info from binaryninja.architecture import Architecture from binaryninja.function import RegisterInfo, InstructionInfo, InstructionTextToken from binaryninja.enums import InstructionTextTokenType, BranchType, FlagRole, LowLevelILFlagCondition from . impo...
14,178
4,188
import os import paramiko class SftpHandle(paramiko.SFTPHandle): def stat(self): try: return paramiko.SFTPAttributes.from_stat(os.fstat(self.readfile.fileno())) except OSError as e: return paramiko.SFTPServer.convert_errno(e.errno) def chattr(self, attr): pass
278
110
from brownie import ETH_ADDRESS, accounts def test_brownie(): """Test if the brownie module is working. """ acc = accounts[0] assert type(acc.address) == str
176
56
""" Copyright (c) 2022 Julien Posso """ import torch import optuna from config import Config from pose_net import POSENet from submission import SubmissionWriter from print_results import print_training_loss, print_training_score, print_beta_tuning, print_error_distance import os import numpy as np import random def...
5,023
1,598
from enum import IntEnum, unique """Stores the unique values for interpretting message signatures and command types. Extra key-value pairs have been added to simply to demonstrate how to modify this file. Not all key-value pairs have not implemented. """ @unique class MessageSource(IntEnum): UNKNOWN = 0 TEST...
526
156
"""fontTools.misc.fixedTools.py -- tools for working with fixed numbers. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * __all__ = [ "fixedToFloat", "floatToFixed", ] def fixedToFloat(value, precisionBits): """Converts a fixed-point number to a float, c...
1,482
627
from action_hero.utils import PipelineAction, DebugAction from action_hero.net import ( EmailIsValidAction, IPIsValidIPAddressAction, IPIsValidIPv4AddressAction, IPIsValidIPv6AddressAction, URLIsNotReachableAction, URLIsReachableAction, URLWithHTTPResponseStatusCodeAction, ) from action_hero...
3,548
1,114
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # import selenium exceptions module from selenium.common.exceptions import * browser = webdriver.Chrome() browser.get("ht...
725
203
"""Stacker custom lookup to get a Cognito User Pool App Client Secret.""" import logging from stacker.session_cache import get_session TYPE_NAME = 'CognitoUserPoolAppClientSecret' LOGGER = logging.getLogger(__name__) def handler(value, provider, **kwargs): # pylint: disable=W0613 """ Lookup a Cognito User Pool ...
1,670
488
# Generated by Django 3.0.7 on 2020-11-18 11:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0088_matierepremiere_is_huile_vegetale'), ] operations = [ migrations.AddField( model_name='depot', name='ad...
884
285
r"""2018 - Day 7 Part 1: The Sum of Its Parts. You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so y...
4,202
1,169
import pytest from riotwatcher import TftWatcher @pytest.mark.tft @pytest.mark.usefixtures("reset_globals") class TestTftWatcher: def test_require_api_key(self): with pytest.raises(ValueError): TftWatcher() def test_allows_positional_api_key(self): TftWatcher("RGAPI-this-is-a-fak...
419
164
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import scipy import copy def get_loss_from_z(model, z, t, reduction): if model.name_loss == 'multi-class classification': criterion = torch.nn.CrossEntropyLoss() loss = criterion(z, t.type(torch.LongTensor).to(z...
12,140
4,570
print("Hello") 1 / 0 print("world!")
38
18
from db_manager import db class MilkCollection(db.Model): id = db.Column(db.Integer, primary_key=True) shift = db.Column(db.String(80)) member_id = db.Column(db.Integer, db.ForeignKey('member.id')) member = db.relationship('Member', backref=db.backref('milk_collections', lazy='dynamic')) ...
924
337
''' - Leetcode problem: 352 - Difficulty: Hard - Brief problem description: Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals. For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will...
1,332
481
from mongo_test.utils.dal.identity_dal import * from mongo_test.utils.dal.object_dal import * from mongo_test.utils.dal.detection_dal import * from mongo_test.utils.dal.user_dal import * from mongo_test.utils.dal.process_dal import * from mongo_test.utils.dal.camera_dal import * from mongo_test.utils.dal.logger_dal imp...
476
154
# flake8: noqa from .stdout import StdOut
42
17
# vim:fileencoding=utf-8 import os import vim import socket import struct import contextlib fcitxsocketfile = vim.eval('s:fcitxsocketfile') class FcitxComm(object): STATUS = struct.pack('i', 0) ACTIVATE = struct.pack('i', 1 | (1 << 16)) DEACTIVATE = struct.pack('i', 1) INT_SIZE = struct.calcsize('i')...
2,032
761
# -*- coding: utf-8 -*- __author__ = "R. Bauer" __copyright__ = "MedPhyDO - Machbarkeitsstudien des Instituts für Medizinische Strahlenphysik und Strahlenschutz am Klinikum Dortmund im Rahmen von Bachelor und Masterarbeiten an der TU-Dortmund / FH-Dortmund" __credits__ = ["R.Bauer", "K.Loot"] __license__ = "MIT" __ver...
4,373
1,399
# Generated by Django 3.1.2 on 2020-10-28 05:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Contribution', fields=[ ('id', models.AutoF...
2,499
677
# -*- coding: utf-8 -*- import hashlib import base64 from Crypto.Cipher import AES import json from src.services.utils import Request class WXAPPError(Exception): def __init__(self, code, description): self.code = code self.description = description def __str__(self): return '%s: %s' ...
4,354
1,364
from tkinter import * from placeholder import EntPlaceHold from gradiente import GradientFrame from tkinter import ttk, messagebox from funcoes_sqlite import FuncsSqlite from funcoes_txt import ArquivosTexto import os class Front(FuncsSqlite, ArquivosTexto): def __init__(self): self.window = Tk() ...
15,265
5,209
""" Code for domain classes. """
33
12
import sys import os __all__ = [] __version__ = '0.0.1' sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.' + '/CryptoVinaigrette')))
164
73
import json import os.path import falcon from app.__root__ import __path__ class MockServerResource: def __init__(self): self.__root_path__ = __path__() async def on_get(self, req, resp, route: str): if not route.endswith(".json"): route += ".json" filepath = os.path.joi...
586
185
import asyncio import aiohttp async def duck_search(search_term): search_term = "+".join(search_term.split()) url = f"https://api.duckduckgo.com/?q={search_term}&format=json" async with aiohttp.ClientSession() as session: async with session.get(url) as r: if r.status == 200: ...
703
216
from __future__ import annotations from prettyqt import widgets from prettyqt.qt import QtWidgets QtWidgets.QStatusBar.__bases__ = (widgets.Widget,) class StatusBar(QtWidgets.QStatusBar): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.progress_bar = widgets....
1,709
544
# Function to clear data in instances folder before new run import os import shutil def clear_instances(directory): instances_folder = directory folders = os.listdir(instances_folder) for folder in folders: shutil.rmtree(instances_folder + folder) print('\nInstances folder cleared\n') def clear_all(): img_...
670
249
""" Activity commands """ from discord.ext import commands from bot.components.logging import log_all class Activities(commands.Cog): """ Activity Commands """ def __init__(self, api): self.api = api @commands.command() @log_all async def work(self, ctx): """ (NOT YET IMPLEMENTED) ...
1,338
412
"""Python functions to handle the ISO-14443-A protocol basics (parity and CRC)""" # Pynfc is a python wrapper for the libnfc library # Copyright (C) 2009 Mike Auty # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published...
1,535
570
import pytest import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from attrs_sqlalchemy import attrs_sqlalchemy class TestAttrsSqlalchemy: def test_deprecation(self): with pytest.warns(UserWarning, match='attrs_sqlalchemy is d...
4,294
1,331
""" Generate predictions for AIcrowd. Usage: python3 run.py The csv file produced will be "out/predictions.csv". """ # flake8: noqa: E402 import os import numpy as np # Import functions from scripts/ from csv_utils import create_csv_submission, load_csv_data from path import (add_src_to_path, load_json_parameters,...
3,331
1,272
DESC = f"""{__file__} - A code sample to help get you started with proceedurally generated terrain / chunkloading in Ursina. More complex terrain can be achieved by using a more complicated function in GameWithChunkloading.get_heightmap(). Supports both Perlin Noise and Open Simplex Noise. Written by Lyfe. """ TERRAIN...
8,958
3,414
"""CLI console script entry point.""" import clc def main(): clc.v1.Args() clc.v1.ExecCommand()
105
46
from namedivider import NameDivider from controller.model import DivisionRequest from controller import division_controller def test_division_controller(): divider = NameDivider() undivided_names = ["菅義偉"] division_request = DivisionRequest(names=undivided_names) res = division_controller.divide(divid...
688
236
from urllib.parse import urlparse from toolkit.lib.http_tools import request_page from bs4 import BeautifulSoup class AuditPage(): def __init__(self, url): parsed_url = urlparse(url) self.domain = parsed_url.netloc self.scheme = parsed_url.scheme self.path = parsed_url.path ...
1,001
324
import os import shutil import zipfile from http.server import HTTPServer, CGIHTTPRequestHandler import threading import subprocess import sys import traceback PORT = 3000 os.chdir('autoupdate') def create_folder_and_zip(): def zipdir(path, ziph): for root, dirs, files in os.walk(path): for f...
2,968
1,069
import RPi.GPIO as GPIO import time import os class Axis: """ Base Class for one of the XY gantry axes All move commands are written to be called in threads self.position and/or self.step position can safely be queried while the axis is moving. """ def __init__(self, name, pin_li...
8,202
2,778
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os import json from pymongo import MongoClient class LogImporter(object): def __init__(self, data, constring): self.data_dir = data self.db = MongoClient(constring).get_default_database() self.messages = self.db.messages ...
2,788
873
from moai.parameters.optimization.optimizers.swa import SWA as Outer import torch import omegaconf.omegaconf import hydra.utils as hyu import typing __all__ = ['SWA'] #NOTE: modified from https://github.com/alphadl/lookahead.pytorch class SWA(object): """Implements Stochastic Weight Averaging (SWA). - ...
973
335
#/usr/bin/env python ''' @2018-01 by lanhin Generate cluster json file. Usage: python2 clustergen.py The output file name is cluster.json ''' import getopt import sys import os def jsonout(fileout, devices, edges, nodelinks): with open(fileout, "wb") as result: outItem = "{\n \"devices\":\n [\n" ...
3,763
1,600
import unittest from xie.graphics.drawing import DrawingSystem from xie.graphics.canvas import EncodedTextCanvasController from xie.graphics.factory import StrokeSpec, StrokeFactory class DrawingSystemTestCase(unittest.TestCase): def setUp(self): self.controller = EncodedTextCanvasController() self.ds = DrawingS...
1,956
846
#!/usr/bin/env python # -*- coding: utf-8 -*- from PyQt5 import QtGui, QtWidgets, QtCore from sharedcomponets import GUIToolKit import logging from simpleFOCConnector import SimpleFOCDevice class DROGroupBox(QtWidgets.QGroupBox): def __init__(self, parent=None, simpleFocConn=None): """Constructor for Tool...
4,500
1,424
#!/usr/bin/env python # coding=utf-8 ''' ### 这个文件用来接管 控制 coredump 的存储 ### 需手动 echo "|/usr/bin/python /docker_host/1.py" > /proc/sys/kernel/core_pattern ### sys.stdin 如果没有数据 返回 '',不是 None ### 容器里对 core 对操作会持久化到 image 里 预期在 container 中对 /proc/sys/kernel/core_pattern 做的修改 如果不 commit , 下次从相同到 image 进入 containe...
7,157
2,603
plot = Plot() # Uneven error bars line = Line() line.xValues = range(6) line.yValues = [25, 21, 30, 23, 10, 30] line.yMins = [10, 18, 10, 10, 5, 20] line.yMaxes = [30, 50, 40, 30, 20, 45] line.label = "Asymmetric Errors" line.color = "red" line.xValues = range(len(line.yValues)) # Even error bars line2 = Line() line...
595
308
#!/usr/bin/env python from wurst import * from wurst.searching import * from wurst.transformations.activity import change_exchanges_by_constant_factor from wurst.transformations.uncertainty import rescale_exchange from wurst.IMAGE.io import * from wurst.IMAGE import * from wurst.ecoinvent.electricity_markets import ...
59,134
18,926
""" FJTYFilt_estimator.py Creates a vectorizer and estimated an SVM model from the files in FILE_NAMES; run a TRAIN_PROP train/test on these then saves these TO RUN PROGRAM: python3 SVM_filter_estimate.py PROGRAMMING NOTES: 1. There are no summary statistics across the experiments, as these are currently jus...
6,996
2,594
import sys print("Hello, "+sys.argv[1]+"!")
43
18
import cv2 import pickle import matplotlib.image as mpimg import matplotlib.pyplot as plt def load_cal_dist(): # load the pickle file file = open("wide_dist_pickle.p", "rb") dist_pickle = pickle.load(file) objpoints = dist_pickle["objpoints"] imgpoints = dist_pickle["imgpoints"] return objpoi...
694
252
# for loop numbers = [1, 2, 3, 4, 5] new_list = [] for n in numbers: add_1 = n + 1 new_list.append(add_1) print(new_list) # List Comprehension new_list_comprehension = [n + 1 for n in numbers] print(new_list_comprehension) # Rang List Comprehension range_list = [n * 2 for n in range(1, 5)] print(range_list) ...
658
274
from .iid_equal import distribute_batches_equally
50
17
from io import StringIO import os from pathlib import Path import pytest from herethere.everywhere import ConnectionConfig, runcode from herethere.everywhere import config code_with_definition = """ def foo(a, b): return a + b print(foo(1, 2)) """ @pytest.mark.parametrize( "code, expected", [ ...
2,673
877
import os import re import joblib import numpy as np import pandas as pd import traceback from .logger import create_logger from .ml_utils import fetch_ohlcv, normalize_position from .agent_api import submit_prediction agent_base_url = os.getenv('ALPHASEA_AGENT_BASE_URL') model_id = os.getenv('ALPHASEA_MODEL_ID') mode...
1,879
661
import cv2 import numpy as np img1 = cv2.imread('image.tif') img2 = cv2.imread('imglogo.png') rows, cols, channels = img2.shape roi = img1[0:rows, 0:cols] img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 230, 255, cv2.THRESH_BINARY_INV) mask_inv = cv2.bitwise_not(mask) img1_bg...
545
269
from django.contrib.auth.models import User from django import forms from constance import config #from constance.admin import ConstanceForm from django.conf import settings from .models import DeviceFamily, Firmware, Board ##############################################################################################...
2,378
646
{"Item1":[{"from":{"sourceType":"file","value":"~/obj/api/SortingVisualizer.yml"},"to":{"sourceType":"file","value":"~/obj/api/SortingVisualizer.FrmMain.yml"},"reportedBy":{"sourceType":"file","value":"~/obj/api/SortingVisualizer.yml"},"type":"children"},{"from":{"sourceType":"file","value":"~/obj/api/SortingVisualizer...
296,545
92,491
from . import auth from flask_login import login_user,login_required,logout_user from flask import render_template,url_for,flash,redirect,request from .forms import SignupForm,SigninForm from ..models import User from .. import db from ..email import mail_message @auth.route('/signup', methods = ["GET","POST"]) def si...
1,395
449
# # Copyright (c) 2019, NVIDIA CORPORATION. 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 applicab...
2,433
785
# _*_coding:utf-8_*_ # author:qq823947488 # date:2019/4/24 20:12 host='localhost' port=3306 user='root' passwd='123' db='flask_learn' charset='utf8'
150
88
""" These function implement functions or other functionalities provided by the linux userspace dynamic loader """
115
24
from wrappers import inner_f def compile_f(contents, attributes, doc, name): new_contents = [] for f in contents: sub_contents = getattr(f, "contents", None) if sub_contents: new_contents.extend(sub_contents) else: new_contents.append(f) new_func = inner_f(ne...
664
211
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Filip Stefanak <f.stefanak@rare-technologies.com> # Copyright (C) 2017 Rare Technologies # # This code is distributed under the terms and conditions # from the MIT License (MIT). import sys import unittest from bounter import HashTable long_long_max = 9223372...
7,732
2,646
import sys newick = '' with open(sys.argv[1]) as f: orig = f.read().rstrip() orig = orig.replace('(', '(\n').replace(',', '\n,\n').replace(')', ')\n') for line in orig.split('\n'): fields = line.rstrip().split(':') if len(fields) == 0: continue elif len(fields) == 1: newick += fields...
540
192
# -*- coding: utf-8 -*- # # Based on bitcraze example project: # https://github.com/bitcraze/crazyflie-lib-python/blob/master/examples/step-by-step/sbs_motion_commander.py import logging import sys import time from threading import Event import cflib.crtp from cflib.crazyflie import Crazyflie from cflib.crazyflie.log...
1,830
703
from datetime import datetime from discord.errors import NotFound from discord import Embed from discord_slash.utils.manage_commands import create_option, SlashCommandOptionType from data import get_invites_by_guild_and_code from .infrastructure import record_usage, CommandDefinition, registered_guild_and_admin_or_mo...
2,745
949
from .coco import COCO from .dac import DAC datasets = { "COCO": COCO, "DAC": DAC }
94
43
from typing import List class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: target = [] for n, i in zip(nums, index): target.insert(i, n) return target
235
72
class Tile: """ represents one space on the board responsible for storing and giving information about itself in a safe manner, usually generated by a board object Attributes: _x (integer): the x coordinate, should line up with our other methods _y (integer): the y coordinate e...
2,513
737
list = ['Tiago','Ivan','Henrique', 'Paulo'] nome = 'teste' nome = input('Digite um nome: ') # Python input prompt print(nome) for i in range(len(list)): if list[i] == nome: print(nome,'is number',i + 1,'on the list') break else: print(nome,'is not on the list')
285
101
import numpy as np import math import random class Ai(): def __init__(self, resolution, all_pos: list, all_ids, options: list): self.board_resolution = resolution self.all_pos = all_pos self.player_option, self.ai_option = options self.available_tiles = self.all_pos[:] self...
3,221
1,165
class CoreException(Exception): def __init__(self, message): self.message = message class ValidationError(CoreException): def __init__(self, message, errors=[]): super().__init__(message) self.errors = errors
244
68
""" test to generate noise but failed for 2d """ import math import random maxfreq = 1/500 myfrequencies = [random.random() * maxfreq * 2 * math.pi for _ in range(5)] myphases = [random.random() * math.pi for _ in range(5)] def myfunction(x, y): global myfrequencies global myphases start = 1 for f, ...
507
199
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import ( Event, EventDateAndTime, EventDescription, EventLocation) # Apply summernote to all TextField in model. class SomeModelAdmin(SummernoteModelAdmin): # instead of ModelAdmin summer_note_...
947
288
# Generated by Django 2.2.10 on 2020-02-13 05:16 from django.db import migrations, models import djangocms_bootstrap4.contrib.bootstrap4_link.validators class Migration(migrations.Migration): dependencies = [ ('bootstrap4_link', '0005_auto_20190709_1626'), ] operations = [ migrations.Ad...
930
300
"""Support files for podman API implementation.""" import datetime import re import threading __all__ = [ 'cached_property', 'datetime_parse', 'datetime_format', ] class cached_property(object): """cached_property() - computed once per instance, cached as attribute. Maybe this will make a future...
3,063
1,019
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: ResourceSecretService.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from...
46,271
16,899
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Girder plugin framework and tests adapted from Kitware Inc. source and # documentation by the Imaging and Visualization Group, Advanced Biomedical # Computational Science, Frederick Nation...
7,421
2,170
from keras.models import Sequential, load_model from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Activation, Flatten from keras.optimizers import Adam from keras.callbacks import TensorBoard import tensorflow as tf from tqdm import tqdm from collections import deque from gym.bug_env.environment import ...
5,325
1,789
# -*- coding: utf-8 -*- ''' Быстрая сортировка ''' from typing import MutableSequence, Callable def _qsort(data: MutableSequence, start: int, end: int, process_func: Callable[[MutableSequence, int, int], int]) -> None: if start < end: pivot_index = process_func(data, start...
1,701
601
from flask import Flask,render_template,request from flask_wtf.csrf import CSRFProtect from check_domain_result import compute from check_traceroute import get_traceroute_result from check_mtr import get_mtr_result from check_ping import get_ping_result from geo_latency_info import * import folium import os import logg...
3,834
1,267
import time import queue import threading import RPi.GPIO as GPIO _GPIO_PIN = 25 class Pixels: def __init__(self): self.is_light_on = 1 self.count_down = 0 self.light_on_count = 0 self.light_off_count = 0 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO...
2,111
716
## # 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 ...
40,231
13,006
from __future__ import division, print_function import time import os import configargparse import bz2 import csv import json import sys from datetime import datetime from os import listdir from os.path import isfile, join import multiprocessing as mp def process_file(records_reader, file): core_fields = {"file":...
6,154
1,857