text
string
size
int64
token_count
int64
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(26, GPIO.OUT) GPIO.output(26, GPIO.HIGH)
102
65
import os import sys import DIRECT import json import numpy as np from hpolib.benchmarks.ml.surrogate_svm import SurrogateSVM from hpolib.benchmarks.ml.surrogate_cnn import SurrogateCNN from hpolib.benchmarks.ml.surrogate_fcnet import SurrogateFCNet run_id = int(sys.argv[1]) benchmark = sys.argv[2] n_iters = 50 n_i...
2,456
944
# *** Delete Call Feedback Summary *** # Code based on https://www.twilio.com/docs/voice/api/call-quality-feedback # Download Python 3 from https://www.python.org/downloads/ # Download the Twilio helper library from https://www.twilio.com/docs/python/install import os from twilio.rest import Client # from datetime impo...
1,197
386
# coding:utf-8 import _env from os.path import join, dirname, abspath, exists, splitext from os import walk, mkdir, remove, makedirs from collections import defaultdict from hashlib import md5 from glob import glob from base64 import urlsafe_b64encode import envoy import os from tempfile import mktemp from json import...
8,523
2,891
from flask import Blueprint, Flask, render_template, request, redirect from models.transaction import Transaction import repositories.transaction_repository as transaction_repo import repositories.merchant_repository as merchant_repo import repositories.tag_repository as tag_repo transactions_blueprint = Blueprint("t...
5,693
1,552
import asyncio import copy import csv import io import math from math import inf import os import sys import time import traceback import logging from importlib import reload from datetime import datetime import logging import aiohttp import discord import requests import json import ujson from discord.ext import comm...
86,261
24,601
import pytest from evalml.data_checks import DataCheckActionCode from evalml.data_checks.utils import handle_data_check_action_code from evalml.problem_types import ProblemTypes def test_handle_action_code_errors(): with pytest.raises(KeyError, match="Action code 'dropping cols' does not"): handle_data_c...
1,225
392
from astropy.io import fits import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('ticks') sns.set_context('paper', font_scale=1.7) from plot_fits import get_wavelength, dopplerShift from scipy.interpolate import interp1d plt.rcParams['xtick.direction'] = 'in' """ Compare the spectrum ...
3,480
1,575
from statistical_hypothesis_testing.plots import plots_z_test from statistical_hypothesis_testing.tails import Tail #plots_z_test.create_critical_region_plot(alphas=[0.1, 0.05, 0.01], tails=Tail.RIGHT_TAILED) plots_z_test.create_p_value_plot(0.5109,alpha=0.05,lang='cs', tails=Tail.RIGHT_TAILED)
298
132
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-07-21 04:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.db.models.manager class Migration(migrations.Migration): initial = True dependencies = [ ] operatio...
3,471
955
# -*- coding: utf-8 -*- """ @author: satohara """ import sys sys.path.append('../') import codecs import numpy as np import pandas as pd from EnumerateLinearModel import EnumLasso # data - x fn = './data/call_method_32.b' df = pd.read_csv(fn, sep=',', header=None) data_id_x = np.array([int(v) for v in df.ix[1, 2:]])...
1,818
855
# coding: utf-8 """ Couchbase Backup Service API This is REST API allows users to remotely schedule and run backups, restores and merges as well as to explore various archives for all there Couchbase Clusters. # noqa: E501 OpenAPI spec version: 0.1.0 Generated by: https://github.com/swagger-api...
8,309
2,650
from flask import Flask, jsonify, request from db import db_session, init_db from model import Funcion app = Flask(__name__) app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False init_db() @app.route("/funciones", methods=["POST"]) def create_funcion(): data = request.json if data["nombreFuncion"] is None: ...
1,618
572
import onnx # Load the ONNX model model = onnx.load("./mobilenetv2_new.onnx") # model = onnx.load("../FaceAnti-Spoofing.onnx") # Check that the IR is well formed onnx.checker.check_model(model) # Print a human readable representation of the graph onnx.helper.printable_graph(model.graph) print(model.graph)
309
112
import re wires = {} for i in open('day7.txt'): set = re.match(r'([a-z0-9]+) -> ([a-z]+)',i) if set: wires[set.group(2)] = set.group(1) op1 = re.match(r'(NOT) ([a-z0-9]+) -> ([a-z]+)',i) if op1: wires[op1.group(3)] = [op1.group(1), op1.group(2)] op2 = re.match(r'([a-z0-9]+) (AND|OR|LSHIFT|RSHIFT) ([a-z0-9]+) ...
1,071
508
import matplotlib.patches as mpatches import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd from math import cos, radians def shift_position(pos, x_shift, y_shift) -> dict: """ Moves nodes' position by (x_shift, y_shift) """ return {n: (x + x_shift, y + y_shift)...
7,167
2,391
"""my_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
1,254
422
#!/bin/env python3 from osgeo import ogr import os import csv import settings class PlacesIntersector: def run(self): print("PlacesIntersector") self.reproject(settings.INPUT_ZONESFILE, settings.REPROJECTED_ZONESFILE, settings.CTAZONES_SHAPEFILE_IDFIELD, settings.CTAZONES_SHAPEFILE_NAMEFIELD) ...
3,870
1,157
# scrapes both regular and shopping ads (top, right blocks) from serpapi import GoogleSearch import json, os params = { "api_key": os.getenv("API_KEY"), "engine": "google", "q": "buy coffee", "gl": "us", "hl": "en" } search = GoogleSearch(params) results = search.get_dict() if results.get("ads",...
580
209
import click from tomomibot.cli import pass_context from tomomibot.runtime import Runtime from tomomibot.utils import check_valid_voice, check_valid_model from tomomibot.const import (INTERVAL_SEC, INPUT_DEVICE, OUTPUT_CHANNEL, INPUT_CHANNEL, OUTPUT_DEVICE, SAMPLE_RATE, ...
3,316
941
""" MIT License Copyrights © 2020, Philippe-Henri Gosselin. 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, m...
3,451
955
import fbchat import random as rd from .logger import logger from ..bot_actions import BotActions from ..sql import handling_group_sql BOT_WELCOME_MESSAGE = """👋 Witajcie, jestem botem 🤖 ❓ Jeśli chcesz zobaczyć moje komendy napisz !help""" def check_admin_permission(function): async def wrapper(self, event, ...
5,516
1,806
import os import xml.etree.ElementTree as ET def parse_xml(file_path) -> dict: tree = ET.parse(file_path) root = tree.getroot() groups_colours = {i.attrib['Name']: i.attrib['Color'] for i in root.iter('Group')} groups = ['hotspot', 'lymphocytes', 'tumorbuds', 'lymphocytesR', 'tumorbudsR'] annotat...
1,100
355
import os import time import shutil import pickle import torch import torch.nn.functional as F from tqdm import tqdm from torch.optim.lr_scheduler import ReduceLROnPlateau from tensorboard_logger import configure, log_value import pandas as pd from model import RecurrentAttention from stop_model import StopRecurren...
51,802
16,497
from rest_framework import serializers from .models import ShopItem class ShopItemSerializer(serializers.ModelSerializer): buy_method = serializers.SerializerMethodField() class Meta: model = ShopItem fields = ("id", "name", "cost", "source", "buy_method") def get_buy_method(self, obj):...
392
118
from flask import Flask, request import telegram from moneyGooseBot.master_mind import mainCommandHandler from moneyGooseBot.credentials import URL, reset_key, bot_token, bot_user_name from web_server import create_app # https://api.telegram.org/bot1359229669:AAEm8MG26qbA9XjJyojVKvPI7jAdMVqAkc8/getMe bot = telegram...
2,205
705
import yaml from collections import OrderedDict def construct_odict(load, node): """This is the same as SafeConstructor.construct_yaml_omap(), except the data type is changed to OrderedDict() and setitem is used instead of append in the loop. >>> yaml.load(''' ... !!omap ... - foo: bar ......
3,061
987
#!/usr/bin/env python import json from mimetypes import guess_type import urllib import envoy from flask import Flask, Markup, abort, render_template, redirect, Response import app_config from models import Joke, Episode, EpisodeJoke, JokeConnection from render_utils import flatten_app_config, make_context app = Fl...
10,609
3,630
# MIT License # # Copyright (c) 2020 Oleksii Petrenko # # 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...
12,129
3,467
import traffic_tests from vn_test import * from vm_test import * from floating_ip import * from policy_test import * from compute_node_test import ComputeNodeFixture from user_test import UserFixture from multiple_vn_vm_test import * from tcutils.wrappers import preposttest_wrapper sys.path.append(os.path.realpath('tcu...
43,958
13,984
# -*- coding: utf-8 -*- import json import base64 import decimal from unittest import TestCase import requests import responses from odata.tests import Service, Product, DemoUnboundAction class TestContext(TestCase): def test_context_query_without_auth(self): def request_callback(request): ...
2,466
675
import torch def readout_function(x, readout, batch=None, device=None): if len(x.size()) == 3: if readout == 'max': return torch.max(x, dim=1)[0].squeeze() # max readout elif readout == 'avg': return torch.mean(x, dim=1).squeeze() # avg readout elif readout == 'sum': return torch.sum(x,...
1,432
530
from ef.external_field import ExternalField class ExternalFieldUniform(ExternalField): def __init__(self, name, electric_or_magnetic, uniform_field_vector): super().__init__(name, electric_or_magnetic) self.uniform_field_vector = uniform_field_vector def get_at_points(self, positions, time):...
362
107
import logging import re import json import jsonlines from urllib import parse logger = logging.getLogger(__name__) # EFO # The current implementation is based on the conversion from owl format to json lines format using Apache RIOT # The structure disease_obsolete stores the obsolete terms and it is used to retriev...
11,493
3,526
import numpy as np from interaction3 import abstract from interaction3.arrays import matrix from interaction3.mfield.solvers.transmit_receive_beamplot_2 import TransmitReceiveBeamplot2 array = matrix.create(nelem=[2, 2]) simulation = abstract.MfieldSimulation(sampling_frequency=100e6, ...
948
270
#!/usr/bin/env python2 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __fu...
16,172
5,879
# -*- coding: utf-8 -*- ''' * finance4py * Based on Python Data Analysis Library. * 2016/03/22 by Sheg-Huai Wang <m10215059@csie.ntust.edu.tw> * Copyright (c) 2016, finance4py team * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted ...
2,782
1,335
# coding: utf-8 # flake8: noqa """ ASR documentation No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 1.0.dev Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import ab...
1,778
529
# -*- coding: utf-8 -*- # Copyright (c) T. H. import urllib.request import re import urllib.parse import codecs import filecmp import os.path import os from bs4 import BeautifulSoup from slacker import Slacker from datetime import datetime class Slack(object): __slacker = None def __init__(self, token): ...
2,818
1,200
import numpy as _np from minitf.kernel.core import notrace_primitive from minitf.kernel.core import primitive # ----- Differentiable functions ----- add = primitive(_np.add) subtract = primitive(_np.subtract) multiply = primitive(_np.multiply) divide = primitive(_np.divide) dot = primitive(_np.dot) square = primitive...
582
187
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2017-01-10 20:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migration...
5,802
1,739
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\gsi_handlers\object_lost_and_found_service_handlers.py # Compiled at: 2018-10-26 00:20:22 # Size of ...
4,561
1,553
#Importing OpenAI gym package and MuJoCo engine import gym import numpy as np import mujoco_py import matplotlib.pyplot as plt import env #Setting MountainCar-v0 as the environment env = gym.make('InvertedPendulum-down') #Sets an initial state env.reset() print (env.action_space) # Rendering our instance 300 times i =...
685
229
import matplotlib.pyplot as plt import numpy as np from scipy.special import logit import pandas as pd from matplotlib.axes import Axes, Subplot from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm SMALL = 14 SIZE = 16 plt.rc('font', size=SIZE) # controls defaul...
5,317
2,079
#!/usr/bin/env python3 import numpy as np import math import random import time import scipy.misc import scipy.signal import multiprocessing import json import itertools import os import pprint from collections import namedtuple from fractions import gcd from optimized import get_distance OBSTACLE = -1 MAX = 21474836...
15,773
5,215
from __future__ import annotations from typing import Union from luxor.core.events import Event from luxor.controllers.expressions import Var class Int(Var): def __init__(self, value: Number = 0, **kwargs) -> None: super(Int, self).__init__(**kwargs) self.event_prefix = self.name + '.int.' ...
2,438
721
5 5 integer 5.0 5.0 float 5 % 2 1 int 5 > 1 True boolean '5' '5' String 5 * 2 10 int '5' * 2 '55' String '5' + '2' '52' String 5 / 2 2.5 float 5 // 2 ...
412
143
import argparse import arrow import json import config from . import EdgecastReportReader from media_type import PLATFORM def main(): parser = argparse.ArgumentParser( description='EdgeCast Usage Report Reader' ) parser.add_argument('-g', '--granularity', dest='granularity', action='store', type=str, ...
1,270
430
#!/usr/bin/python """ ZetCode wxPython tutorial This program creates a browser UI. author: Jan Bodnar website: zetcode.com last edited: May 2018 """ import wx from wx.lib.buttons import GenBitmapTextButton class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, *...
3,483
1,285
import torch import torch.nn as nn class TDSBlock(nn.Module): def __init__(self, channels, kernel_size, width, dropout, right_padding): super().__init__() self.channels = channels self.width = width assert(right_padding >= 0) self.conv_block = nn.Sequential( ...
1,673
646
from ._base import Endpoint from ..util._six import Path import bottle from ..util import gitHttpBackend class GitHTTPBackend: """ WSGI git-http-backend interface to actual endpoints. """ def __init__(self, route, repo_root): self.route = route self.repo_root = Path(repo_root) def get(self, path): return sel...
1,968
669
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, check out LICENSE.md import torch import torch.nn as nn from imaginaire.layers import Conv2dBlock from imaginaire.layers.misc import ApplyNoise...
2,999
1,132
import sqlite3 class Database: def __init__(self): self.database = "chat.db" def perform_insert(self, sql, params): conn = sqlite3.connect(self.database) cursor = conn.cursor() cursor.execute(sql, params) conn.commit() conn.close() def perform_select(self,...
2,959
879
# -*- coding: utf-8 -*- """Non user friendly script. """ from mss.core.class_filesystem import Filesystem def update_by_condition(root_path: str, theme: str): """Change records by condition.""" fs = Filesystem() path = fs.join(root_path, theme, 'metainfo') for folder, filename, name, ext in fs.iter_...
938
303
from environment import * import random class ValueIterationGraphicDisplay(GraphicDisplay): def __init__(self, agent, title): self.btn_1_text = "Calculate" self.btn_2_text = "Print Policy" self.btn_1_func = self.calculate_value self.btn_2_func = self.print_optimal_policy sel...
2,555
870
from enum import Enum from math import * from scipy import integrate import matplotlib.pyplot as plt from libcellml import * import lxml.etree as ET __version__ = "0.1.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 29 class VariableType(Enum): CONSTANT = 1 COMPUTED_CONSTANT = 2 ALGEBRAI...
8,289
3,392
# AUTOGENERATED! DO NOT EDIT! File to edit: image.ipynb (unless otherwise specified). __all__ = ['Img', 'FileImg', 'File16bitImg', 'ArrayImg'] # Cell import warnings import numpy as np import torch from PIL import Image from .utils import * # Cell class Img: def exists(self): raise NotImplemented...
2,342
736
# coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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 applic...
2,144
702
import socket from IPy import IP print(""" You are using the DOOM Port scanner. This tool is for educational purpose ONLY!!!! 1. You can change the range of the ports you want to scan. 2. You can change the speedof the scan 3. you can scan a list of targets by using ', ' after each target 4. You can sc...
1,800
631
from __future__ import print_function import logging import numpy as np from optparse import OptionParser import sys from time import time import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.feature_extraction.text import HashingVectorizer from skl...
9,380
3,302
# Copyright 2018 Red Hat, 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 agre...
5,953
1,731
from pdfminer.pdfinterp import PDFResourceManager, process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from cStringIO import StringIO def convert_pdf(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = T...
709
251
from ..utility import * def handle(data, theme): if isStatusVisible(data['repository']['url'], data['status_message'].lower()): theme.travis( branch = data['branch'], repo = data['repository']['name'], status = data['status_message'], commitId = data['commit'...
480
121
""" Unit Tests for Py-ART's io/mdv_radar.py module. """ import numpy as np from numpy.testing import assert_almost_equal from numpy.ma.core import MaskedArray import pyart ############################################ # read_mdv tests (verify radar attributes) # ############################################ # read in...
10,417
3,789
import uuid, json, os, pymongo from models import User def addUser(user): res = {} res['result'] = 1 res['message'] = '' if User.insert_one(user).inserted_id != '': res['message'] = 'success' else: res['result'] = 0 res['message'] = 'Fail to add user in database!' ret...
2,430
770
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'DiskType', ] class DiskType(str, Enum): """ Required. The type of the disk to create. """ TYP...
969
326
#!/usr/bin/env python3 """Importing""" # Importing Common Files from botModule.importCommon import * """Start Handler""" @Client.on_message(filters.private & filters.command("start")) async def start_handler(bot:Update, msg:Message): if await search_user_in_community(bot, msg): await msg.reply_text(BotM...
634
209
#! /usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint filter_blueprint = Blueprint('filters', __name__) # Register all the filter. from . import time_process, text_process, user_manage
206
68
import numpy as np import scipy as sp import pandas as pd import ast import itertools from itertools import product from collections import Counter import networkx as nx import network_utils as nu import hicode as hc import matplotlib.pyplot as plt import matplotlib.cm as cm plt.style.use('classic') # ------------...
3,596
1,207
from ..bs_node.iterable import BSNodeIterable from ..bs_reference.iter import BSReferenceIter class SharedRules(BSNodeIterable): _tag_name = 'sharedRules' _iter_child_class = BSReferenceIter('Rule')
209
70
''' pca_utils.py Module containing functions to run PCAs, and generate diagnostic plots ''' from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np def run_PCA(parameters, observables, n_components): ''' Runs a principal component analysis to reduce dimensionality of o...
5,487
1,524
# Copyright 2022 Google. # # 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, soft...
17,452
5,658
from django_rq.decorators import job from src.core.core import runtime_calculate from src.jobs.models import JobStatuses from src.jobs.ws_publisher import publish from src.logs.models import Log from src.utils.file_service import get_log @job("default", timeout='1h') def runtime_task(job, model): print("Start ru...
952
302
default_app_config = 'django_models_from_csv.apps.DjangoDynamicModelsConfig' __version__ = "1.1.0"
99
37
from .legacy import uTensorLegacyCodeGenerator from .rearch import uTensorRearchCodeGenerator
93
26
from collections import UserString from typing import List class Token(UserString): """A string that has additional information about the source code for the string.""" def __init__(self, s: str, line_number:int, character_number: int, filename: str = None): super().__init__(s) self.line_numbe...
417
106
import os import time import math import logging.config from datetime import datetime from subprocess import run from urllib.request import urlopen, urlretrieve from urllib.parse import urlparse, urljoin import smtplib, ssl from os.path import basename from email.mime.application import MIMEApplication from email.mime...
2,655
894
# -*- coding: utf-8 -*- ############################################################################### # Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. # # All rights reserved. # # This file is part of the AiiDA-FLEUR package. ...
1,987
540
from .utils import ShellParser class Parser(ShellParser): """Extract text from doc files using antiword. """ def extract(self, filename, **kwargs): stdout, stderr = self.run(['antiword', filename]) return stdout
243
68
#!/usr/bin/env python from __future__ import absolute_import from create_multi_langs.creater.go import CreaterGo from create_multi_langs.creater.python import CreaterPython from create_multi_langs.creater.python_typing import CreaterPythonTyping from create_multi_langs.creater.typescript_backend import CreaterTypeScrip...
4,674
1,484
__author__ = 'Justus Adam' __version__ = '0.1' def main(): import unittest import sys import os m = os.path.dirname(__file__) sys.path = [m, os.path.split(m)[0]] + sys.path import test unittest.main(test) if __name__ == '__main__': main() else: del main
297
116
import re def parse_to_latex(): configs = ['nolm', 'lm', 'maskedlm', 'lm+bp', 'lm+pos', 'lm+rnn', 'lm+bpe+rnn', 'lm+bpe+crf'] datasets = ['kp20k', 'inspec', 'krapivin', 'nus', 'semeval', 'kptimes', 'jptimes', 'duc'] config_dict = {} with open('class_results-FINAL.txt', 'r', encoding='utf8') as file: ...
15,798
8,471
import matplotlib matplotlib.use('Agg') # coding: utf-8 # # Ice drift retrieval algorithm based on [1] from a pair of SAR images # [1] J. P. Lewis, "Fast Normalized Cross-Correlation", Industrial Light and Magic. # ################################################## # Last modification: 22 July, 2019 # TODO: # 1) Pyrami...
55,975
21,326
from betterproto import __version__ from pathlib import Path import tomlkit PROJECT_TOML = Path(__file__).joinpath("..", "..", "pyproject.toml").resolve() def test_version(): with PROJECT_TOML.open() as toml_file: project_config = tomlkit.loads(toml_file.read()) assert ( __version__ == projec...
426
131
'''Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se encontram no intervalo de 1 até 500. ''' cont = 0 total = 0 for soma in range(1, 501, 2): if soma % 3 == 0: cont += 1 total += soma print(f'Foram encontrados {cont} valores coma as característic...
383
143
"""classes and methods for different model architectures """ #python packages import numpy as np # Machine Learning from Scratch packages from Layers import FullyConnected from utils.optimizers import * class NeuralNet(): """ Linear stack of layers. """ def __init__(self, layers=None): # Add ...
9,722
2,612
input = """ a(S,T,Z) :- #count{X: r(T,X)} = Z, #count{W: q(W,S)} = T, #count{K: p(K,Y)} = S. q(1,1). q(2,2). r(1,1). r(1,2). r(1,3). r(2,2). r(3,3). p(1,1). p(2,2). %out{ a(2,1,3) } %repository error """ output = """ a(S,T,Z) :- #count{X: r(T,X)} = Z, #count{W: q(W,S)} = T, #count{K: p(K,Y)} = S. q(1,1). q(2,2)...
421
291
import argparse import logging import os import requests import urllib3 from dotenv import load_dotenv logger = logging.getLogger("__name__") logging.basicConfig( format="%(asctime)s [%(levelname)8s] [%(name)s:%(lineno)s:%(funcName)20s()] --- %(message)s", level=logging.INFO, ) logging.getLogger("...
1,724
611
"""Stuff to do with processing images and loading icons""" import importlib.resources as res import cv2 import PySimpleGUI as sg def get_application_icon(): """Get the PyHSI icon for this OS (.ico for Windows, .png otherwise)""" return res.read_binary("pyhsi.gui.icons", "pyhsi.png") def get_icon(icon_name...
1,572
584
lr = 0.001 model_path = 'model/IC_models/densenet169_lr_0.001/' crop_size = 32 log_step = 10 save_step = 500 num_epochs = 400 batch_size = 256 num_workers = 8 loading = False # lr # Model parameters model = dict( net='densenet169', embed_size=256, hidden_size=512, num_layers=1, resnet=101 )
315
161
''' Implements the computation of the time derivatives and associated Jacobian corresponding to the approximated equations in a metapopulation. Added kwargs in every function so that we may reuse the parameter dictionary used in the models, even if some of the parameters it contains are not used in these functions. '''...
3,750
1,774
import pygame from settings import Settings from vector import Vector import utils class AbstractTile: pass class AbstractStaticTile(AbstractTile): IMAGE_FOLDER = 'static_tiles' def __init__(self, code, filename, with_sparkle=False): self.code = code self.filename = filename se...
2,759
921
import torch import numpy as np filename = '2020.01.12-044406' model = torch.load('logs/'+filename+'/checkpoint.pth.tar') k1 = model['state_dict']['module.conv1.weight'].data.cpu().numpy() k2 = model['state_dict']['module.conv2.weight'].data.cpu().numpy() k3 = model['state_dict']['module.fc1.weight'].data.cpu().numpy(...
657
290
from sqlalchemy.exc import IntegrityError import pytest from app.dao.marketings_dao import ( dao_update_marketing, dao_get_marketing_by_id, dao_get_marketings ) from app.models import Marketing from tests.db import create_marketing class WhenUsingMarketingsDAO(object): def it_creates_an_marketing(self, db_...
2,174
672
# Copyright 2019 Robert Bosch GmbH # Copyright 2020-2021 Christophe Bedard # # 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 requir...
14,898
4,277
# coding=utf-8 import os from distutils.spawn import find_executable from setuptools import setup, find_packages import sys sys.path.append('./test') from esfabric import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() if os.path.exists(os.path.join...
1,543
495
# Generated by Django 2.2 on 2019-08-09 18:22 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('catalogue', '0007_auto_20190809_1735'), ] operations = [ migrations.AlterField( model_name='artwo...
673
226
#utils.py import torch from tqdm import tqdm from torch.autograd import Variable from fmtl import FMTL def tuple2var(tensors,data): def copy2tensor(t,data): t.resize_(data.size()).copy_(data,async=True) return Variable(t) return tuple(map(copy2tensor,tensors,data)) def new_tensors(n,cuda,type...
3,455
1,210
# from ..Models import Base, dbConfig # from sqlalchemy import ( # Column, # DateTime, # ForeignKey, # Integer, # Numeric, # String, # Unicode, # text, # Sequence, # orm, # func, # select, # bindparam, # UniqueConstraint, # event) # from sqlalchemy.orm import ...
2,867
948
#!/usr/bin/env python3 import logging import os import os.path import tornado.web import tornado.options from appleseed import AlpineIndexFile, DebianIndexFile from cdtz import set_time_zone from motor import MotorClient from shirow.ioloop import IOLoop from shirow.server import RPCServer, TOKEN_PATTERN, remote from t...
11,704
3,456