text
string
size
int64
token_count
int64
from board import Game from agent import Agent from humanAgent import HumanAgent from randomAgent import RandomAgent from MCTS import * from NeuralNetwork import Connect4Zero import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #AI VS RANDOM ''' def main(): builder = Connect4Ze...
3,757
1,185
# coding: utf-8 # # Project: X-ray image reader # https://github.com/silx-kit/fabio # # # Copyright (C) European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu) # # Permission is hereby granted, free of charge, to any person obtai...
4,390
1,425
# -*- coding: utf-8 -*- # # Copyright (C) tkornuta, IBM Corporation 2019 # # 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 require...
8,699
2,737
from Domain.student import Student from Repository.assignment_repository import AssignmentRepository from Repository.grade_repository import GradeRepository from Repository.student_repository import StudentRepository from Repository_Binary_File.assignment_repository_binary_file import AssignmentRepositoryBinaryFile fro...
2,613
629
# # entry for gunicorn # from nntpchan.app import app from nntpchan import viewsp
83
32
""" @brief test log(time=3s) """ import unittest import inspect import logging from time import sleep, perf_counter from pyquickhelper.pycode import ExtTestCase from cpyquickhelper.profiling import ( EventProfiler, WithEventProfiler) from cpyquickhelper.profiling.event_profiler import EventProfilerDebug clas...
6,997
2,344
# coding: utf-8 """ CLOUD API IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and ...
4,572
1,348
import os import re import subprocess from setuptools import setup, find_packages, Command from setuptools.command.test import test as TestCommand __author__ = 'Eric Hulser' __email__ = 'eric.hulser@gmail.com' __license__ = 'MIT' INSTALL_REQUIRES = [] DEPENDENCY_LINKS = [] TESTS_REQUIRE = [] LONG_DESCRIPTION = '' ...
5,503
1,758
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired, FileAllowed class CSVUploadForm(FlaskForm): csvfile = FileField( "CSV Mark Sheet", validators=[FileRequired(), FileAllowed(["csv"], "CSV Files only!")], )
265
84
import pandas as pd from tensorflow import keras, reduce_sum, ragged, function, math, nn, reduce_mean from os import environ class MaskedEmbeddingsAggregatorLayer(keras.layers.Layer): def __init__(self, agg_mode='sum', **kwargs): super(MaskedEmbeddingsAggregatorLayer, self).__init__(**kwargs) if ...
6,298
2,248
import django_tables2 as tables from nautobot.utilities.tables import ( BaseTable, ButtonsColumn, ToggleColumn, ) from example_plugin.models import AnotherExampleModel, ExampleModel class ExampleModelTable(BaseTable): """Table for list view of `ExampleModel` objects.""" pk = ToggleColumn() ...
818
235
import json from typing import Optional, Union, Dict def replace_from_keyword_in_json( data, # type: Optional[Dict] ): # type: (...) -> Dict """ Rename the 'from' field coming from the Graph API. As 'from' is a Python keyword, we cannot use this as an attribute with 'attrs' package. So renamin...
555
178
from unittest import TestCase from datetime import datetime from ctparse.ctparse import ctparse, _match_rule from ctparse.types import Time class TestCTParse(TestCase): def test_ctparse(self): txt = '12.12.2020' res = ctparse(txt) self.assertEqual(res.resolution, Time(year=2020, month=12,...
1,224
444
import argparse import os import subprocess import time import sys import ipdb import pickle from utils.meter import * def main(args): # Parameters from the args dir, h, w, fps, common_suffix = args.dir, args.height, args.width, args.fps, args.common_suffix # avi dir dir_split = dir.split('/') av...
5,841
1,917
#!/usr/bin/env python import math import random import matplotlib.pyplot as plt # sample from linear distribution and plot it bins = [0.1 * i for i in range(12)] plt.hist([(1.0 - math.sqrt(random.random())) for k in range(10000)], bins) plt.show()
251
94
from __future__ import absolute_import from __future__ import print_function import veriloggen import thread_mutex_try_lock expected_verilog = """ module test; reg CLK; reg RST; blinkled uut ( .CLK(CLK), .RST(RST) ); initial begin $dumpfile("uut.vcd"); $dumpvars(0, uut); end ini...
43,183
19,334
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Idea(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delet...
926
303
# Write a Python program to compute the greatest common divisor (GCD) of two positive integers. n1 = int(input("Enter the first number: ")) n2 = int(input("Enter the second number: ")) a1 = [] a2 = [] a3 = [] for i in range(1, n1 + 1): if n1 % i == 0: a1.append(i) for i in range(1, n2 + 1): if n2 % ...
416
174
import time start_time = time.process_time() import sys sys.path.append("../") from Biological_Questions.Cell_Cycle_Duration.Shortlist_Outliers import ShortlistOutliers from Movie_Analysis_Pipeline.Merging_Movie_Datasets.Find_Family_Class import FindFamily from Cell_IDs_Analysis.Plotter_Lineage_Trees import PlotLinea...
2,110
733
""" Reduce neural net structure (Conv + BN -> Conv) Also works: DepthwiseConv2D + BN -> DepthwiseConv2D SeparableConv2D + BN -> SeparableConv2D This code takes on input trained Keras model and optimize layer structure and weights in such a way that model became much faster (~30%), but works identically to initi...
13,283
4,347
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class TopicItemVo(object): def __init__(self): self._desc = None self._id = None self._status = None self._title = None @property def desc(self): return...
2,031
639
from rest_framework import status from rest_framework.viewsets import ViewSet from rest_framework.decorators import action from rest_framework.permissions import AllowAny, IsAuthenticated from api.lib.response import Response from payment.get_bank_list import BankList class BankListViewSet(ViewSet): @action(metho...
541
153
#!/usr/bin/env python from os import system log = f'r0_arrp.log' C = ' -c ../../1_Prem_Matrices_to_df/Data/UNSDMethodology.csv' E = ' -e ../../3_Prem_Matrices_to_PF_Eigenvalue/Output/pf_eigenvalue.csv' S = ' -s ../../2_ARRP/Output/slope.csv' system( f'r0_arrp.py {C} {E} {S} > {log}' )
290
145
# -*- coding: utf-8 -*- # Copyright 2015 Objectif Libre # # 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 ...
2,816
876
import time from ina219 import INA219 SHUNT_OHMS = 0.1 MAX_EXPECTED_AMPS = 0.2 def read(): ina1 = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, address=0x40) ina1.configure(ina1.RANGE_16V, ina1.GAIN_AUTO) # print("ici") # print("INA1 ==============") # print("Bus Voltage : %.3f V" % ina1.voltage()) ...
3,739
1,514
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provide the Little Dog robotic platform. """ import os import numpy as np from pyrobolearn.robots.legged_robot import QuadrupedRobot __author__ = "Brian Delhaisse" __copyright__ = "Copyright 2018, PyRoboLearn" __license__ = "GNU GPLv3" __version__ = "1.0.0" __maintain...
3,646
1,293
# 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\business\advertising_manager.py # Compiled at: 2017-04-27 01:01:18 # Size of source mod 2**32: 6129 ...
3,818
1,249
import os import datetime import csv import json i = 0 def initial_menu(): user_action = input("1. Log In \n" + "2. Create new user \n" + "3. Create with CSV \n" + "4. Update with CSV \n") if user_action == "1": user_name = inp...
8,603
2,523
import numpy as np from mpi4py import MPI from tacs import TACS, elements, constitutive, functions from static_analysis_base_test import StaticTestCase ''' Create a two separate cantilevered plates connected by an RBE3 element. Apply a load at the RBE2 center node and test KSFailure, StructuralMass, and Compliance fu...
8,598
2,801
# Copyright 2021 Southwest Research Institute # Licensed under the Apache License, Version 2.0 #UR IP Address is now 175.31.1.137 #Computer has to be 175.31.1.150 # Imports for ros # from _typeshed import StrPath from builtins import staticmethod from operator import truediv from pickle import STRING, TRUE import st...
31,649
9,546
''' Simple socket server using threads ''' import socket import sys from thread import * def clientthread(conn): conn.send('Nice job! The flag is hackgt{here_kitty_kitty}\n') conn.close() HOST = '' # Symbolic name, meaning all available interfaces PORT = 9000 # Arbitrary non-privileged port...
989
323
# Only used for PyTorch open source BUCK build IGNORED_ATTRIBUTE_PREFIX = [ "apple", "fbobjc", "windows", "fbandroid", "macosx", ] IGNORED_ATTRIBUTES = [ "feature", "platforms", ] def filter_attributes(kwgs): keys = list(kwgs.keys()) # drop unncessary attributes for key in ke...
563
206
import datetime import pandas as pd # Retrieve the test cases from the csv into a dictionary dataFile = open('testcases.csv', 'r') dataFrame = pd.read_csv('testcases.csv', index_col=0) dataDictionary = dataFrame.transpose().to_dict() # Create a new dictionary to save the results result = {} # Data optimization -> get ...
1,901
548
import os from datetime import timedelta from allennlp.data.iterators import BucketIterator from allennlp.data.token_indexers import ELMoTokenCharactersIndexer from allennlp_rumor_classifier import load_classifier_from_archive, RumorTweetsDataReader from allennlp_rumor_classifier import timestamped_print if __name__...
9,403
3,301
import math class Solution: def restoreString(self, s, indices): str_list, mov_index = list(s), 0 traverse = len(indices) for x in range(0, traverse): mov_index = indices[x] if mov_index == x: continue str_list[mov_index] = s[x] ...
511
193
# -*- coding: UTF-8 -*- # # Copyright 2008-2011, Lukas Lueg, lukas.lueg@gmail.com # # This file is part of Pyrit. # # Pyrit 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 3 of th...
2,218
702
def spiral_matrix(size): pass
34
13
''' @author: Sougata Saha Institute: University at Buffalo ''' from tqdm import tqdm from preprocessor import Preprocessor from indexer import Indexer from collections import OrderedDict from linkedlist import LinkedList import inspect as inspector import sys import argparse import json import time import random impor...
12,982
3,921
# coding:utf8 # 调用蓝图 from . import home from flask import render_template, redirect, url_for, flash, session, request,current_app from app.home.forms import RegistForm, LoginForm, UserdetailForm, PwdForm, CommentForm, PostForm from app.models import User, UserLoginLog, Comment, Post,Col from werkzeug.security import ge...
16,234
6,207
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the CGS units. They are also available in the top-level `astropy.units` namespace. """ from __future__ import absolute_import, division, print_function, unicode_literals from ..utils.compat.fractions impo...
3,797
1,213
# # Copyright (c) 2019 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import pecan from pecan import rest from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from sysinv.api.controllers.v1 import base from sysinv.api.controllers.v1 import collection from sysinv.common import except...
5,164
1,495
import sys import pylab as plb import numpy as np import mountaincar class DummyAgent(): """A not so good agent for the mountain-car task. """ def __init__(self, mountain_car = None, parameter1 = 3.0): if mountain_car is None: self.mountain_car = mountaincar.MountainCar() ...
1,699
528
import numpy as np from pyquil import Program from pyquil.api import QuantumComputer, get_qc from grove.alpha.jordan_gradient.gradient_utils import (binary_float_to_decimal_float, measurements_to_bf) from grove.alpha.phaseestimation.phase_estimation import phase_...
2,260
721
from torch import randn from torch.nn import Conv2d from backpack import extend def data_conv2d(device="cpu"): N, Cin, Hin, Win = 100, 10, 32, 32 Cout, KernelH, KernelW = 25, 5, 5 X = randn(N, Cin, Hin, Win, requires_grad=True, device=device) module = extend(Conv2d(Cin, Cout, (KernelH, KernelW))).to...
732
318
# -*- coding: utf-8 -*- """ Spyder Editor Code written by Samuel Drapeau with modifications by Johannes Wiesel and Jan Obloj This file produces plots comparing our first order sensitivity with BS vega. """ # %% # To run the stuff, you need the package plotly in your anaconda "conda install plotly" import plotly.g...
5,229
2,125
import sys import docplex.mp import cplex # Teams in 1st division team_div1 = ["Baltimore Ravens","Cincinnati Bengals", "Cleveland Browns","Pittsburgh Steelers","Houston Texans", "Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans","Buffalo Bills","Miami Dolphins", "New Englan...
4,360
1,559
# Copyright (c) 2021, 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 applic...
1,995
615
# -*- coding: utf-8 -*- import re import sys import xml.etree.ElementTree as ET from argparse import ArgumentParser from pathlib import Path from lark.exceptions import UnexpectedCharacters, UnexpectedToken from .parser import validate, SFZ, SFZValidatorConfig from . import spec, settings formats = { 'default': ...
3,596
1,152
import numpy as np # Copyright 2020 Joshua Laniado and Todd O. Yeates. __author__ = "Joshua Laniado and Todd O. Yeates" __copyright__ = "Copyright 2020, Nanohedra" __version__ = "1.0" def euclidean_squared_3d(coordinates_1, coordinates_2): if len(coordinates_1) != 3 or len(coordinates_2) != 3: raise Val...
2,809
946
from flask import Flask, render_template, request, make_response, g import os import socket import random import json import collections hostname = socket.gethostname() votes = collections.defaultdict(int) app = Flask(__name__) def getOptions(): option_a = 'Cats' option_b = 'Dogs' return option_a, option...
1,187
405
"""Hebrew Letter-Based Numering Identifiers and Quantifiers""" def remove_chucks(hebrew_word) -> str: """ Hebrew numbering systems use 'chuck-chucks' (aka quotation marks that aren't being used to signify a quotation) in between letters that are meant as numerics rather than words. To mak...
4,959
1,540
import pytest import pglet from pglet import Textbox, Stack @pytest.fixture def page(): return pglet.page('test_add', no_window=True) def test_add_single_control(page): result = page.add(Textbox(id="txt1", label="First name:")) assert result.id == "txt1", "Test failed" def test_add_controls_argv(page): ...
1,024
370
#!/usr/bin/env python """ Created by howie.hu at 2021/04/29. Description: 采集器相关通用工具函数 Changelog: all notable changes to this file will be documented """ import os import html2text import requests from gne import GeneralNewsExtractor from readability import Document from textrank4zh import TextRank4Keywor...
2,197
841
from mysql_comm.mysql_comm import * from redis_comm.redis_comm import * def insert_datas(datas): with UsingMysql(log_time=True) as um: pass def insert_data(database, data): with UsingMysql(log_time=True) as um: sql = "insert into " + database + "(fp_id, fp_title, fp_res_org, fp_report_tim...
1,886
717
#!/usr/bin/env python # -*- coding: utf-8 -*- import gc import sys import random import unittest from cllist import sllist from cllist import sllistnode from cllist import dllist from cllist import dllistnode gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_STATS) if sys.hexversion >= 0x03000000: # python 3 compat...
61,881
23,403
import trio from trio._highlevel_open_tcp_stream import close_on_error from trio.socket import socket, SOCK_STREAM try: from trio.socket import AF_UNIX has_unix = True except ImportError: has_unix = False __all__ = ["open_unix_socket"] async def open_unix_socket(filename,): """Opens a connection to ...
1,240
369
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # Встроенные модули import time, sys, subprocess from threading import Thread # Внешние модули try: import psycopg2 except ModuleNotFoundError as err: print(err) sys.exit(1) # Внутренние модули try: from mod_common import * except ModuleNotFoundError as err: ...
6,854
2,183
from django import forms from . models import Holdings class HoldingsForm(forms.ModelForm): class Meta: model = Holdings fields = ['title', 'holding', 'authors', 'category'] widgets={ 'title': forms.TextInput(attrs={'class': 'form-control'}), 'holding': forms.FileInp...
731
216
import pytest from aircraft.deploys.ubuntu.models.v1beta3 import StorageConfigData @pytest.fixture def input_config(request): marker = request.node.get_closest_marker('data_kwargs') config = dict( disks=[ { 'path': '/dev/sda', 'partitions': [ ...
2,805
832
from simbatch.core import core from simbatch.core.definitions import SingleAction import pytest # TODO check dir on prepare tests TESTING_AREA_DIR = "S:\\simbatch\\data\\" @pytest.fixture(scope="module") def simbatch(): # TODO pytest-datadir pytest-datafiles vs ( path.dirname( path.realpath(sys.a...
1,009
354
from creational.singleton.logic import God def main(): god = God() another_god = God() if god != another_god: raise Exception("God should be equal to God") for _ in range(0, 7): god.do_something() another_god.do_something() if __name__ == "__main__": main()
304
103
#!/usr/bin/env python # aws s3
31
14
# Really hackey stubs, not suitable for typeshed. from typing import Any class Integer(): def __init__(self, value: Any = None) -> None: ... class Sequence(): def __init__(self) -> None: ... def setComponentByPosition(self, idx: int, value: Any) -> None: ...
277
85
import pytest from day25_1 import map_step, map_step_n from day25_1 import main as main1 @pytest.fixture def test_input(): with open('../../data/test25.txt') as f: return [line.strip() for line in f.readlines()] example_1_0 = [ list('...>...'), list('.......'), list('......>'), list('v....
4,730
2,440
import cv2, os import numpy as np import sys from utils import movingAverage, plot, computeAverage import queue from sklearn import linear_model class Solver(): def __init__(self, config): self.vid = cv2.VideoCapture(config.vidpath) self.txtfile = config.txtfile self.vis = config.vis self.len_gt = config.len_...
7,504
3,415
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests import os import sys from app import app from shapely.geometry import LineString from status.profile_plots import iter_deployments, is_recent_data, is_recent_update def get_trajectory(erddap_url): ''' Reads the trajectory information fr...
4,035
1,214
from abc import ABC, abstractmethod class Pad(ABC): def __init__(self, view, x0: int, y0: int, x1: int, y1: int): """ Creates pad with corners in specified coordinates :param view: base view instance :param x0: x-coordinate of top left corner (included) :param y0: y-coordin...
663
202
from django.conf.urls import url from .views import pdk_codebook_page, pdk_codebook_sitemap urlpatterns = [ url(r'^(?P<generator>.+)/$', pdk_codebook_page, name='pdk_codebook_page'), url(r'^sitemap.json$', pdk_codebook_sitemap, name='pdk_codebook_sitemap') ]
269
112
# -*- coding: utf-8 -*- """ Created on Sat May 8 09:54:36 2021 @author: Administrator """ import torch from torch.utils.tensorboard import SummaryWriter from sklearn.metrics import roc_auc_score import numpy as np # %% data = torch.load('dataset/dic_3_1_7878.pt') print(len(data)) print(data[0][2].shape...
934
430
# coding=utf8 # Copyright 2018 JDCLOUD.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 or agreed ...
2,087
699
from django.contrib import admin from .models import Car # Register your models here. @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ("name", "price", "buyer", "code")
198
61
from typing import Iterable, Optional from django import VERSION from django.db.models.base import Model from django.db.models.fields.related import ManyToManyField from django.db.models.fields.reverse_related import ManyToOneRel from django.db.models.manager import Manager from django.db.models.query import QuerySet ...
5,683
1,873
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import os import psycopg2 import numpy as np import pandas as pd import patsy import statsmodels.api as sm import pickle import random from math import floor, exp from datetime import * import pytz from dateutil.relativedelta import * import calendar fro...
16,914
5,727
#! python3 import pandas as pd import numpy as np import re, json from ta import * import sys, os, logging, logging.config, traceback, concurrent_log_handler, getopt import multiprocessing as mp import contextlib import heapq import talib from datetime import datetime, timedelta #import numba as nb #fro...
67,494
20,158
import cv2 class VideoReader(object): ''' Class docstring for VideoReader(): Provides a generator for video frames. Returns a numpy array in BGR format. ''' def __init__(self, file_name): self.file_name = file_name try: # OpenCV parses an integer to read a webcam. Supplying '0' wi...
1,075
356
import os import json from contextlib import suppress from OrderBook import * from Signal import Signal class OrderBookContainer: def __init__(self, path_to_file): self.order_books = [] self.trades = [] self.cur_directory = os.path.dirname(path_to_file) self.f_name = ...
4,041
1,301
# -*- coding: utf-8 -*- class Solution: def crackSafe(self, n, k): if k == 1: return '0' * n s = self.deBrujin(n, k) return s + s[:n - 1] def deBrujin(self, n, k): """See: https://en.wikipedia.org/wiki/De_Bruijn_sequence#Algorithm""" def _deBrujin(t, p): ...
979
388
from django.apps import AppConfig class EstimatorConfig(AppConfig): name = 'estimators'
94
30
#!/usr/bin/env python3 # # MIT License # # Copyright (c) 2020-2022 EntySec # # 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...
4,507
1,288
'''Functions and classes to wrap existing classes. Provides a wrapper metaclass and also a function that returns a wrapped class. The function is more flexible as a metaclass has multiple inheritence limitations. A wrapper metaclass for building wrapper objects. It is instantiated by specifying a class to be to be wra...
7,146
1,972
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time import os import json import sys from lib import setupDriver, setupMode, access, stopUntilLoading, stopUntilSpinnerLoading from loginModule import loginSection from notification import notifySystem, notifySlackF...
1,558
455
import traceback class A: def __init__(self): pass def tb(self): es = traceback.extract_stack() print(es) fs = es[-2] print(fs.name) print(fs.locals) def another_function(): lumberstack(A()) lumberstack(A()) def lumberstack(a): a.tb() another_fu...
862
305
import os from biicode.common.model.brl.block_cell_name import BlockCellName from biicode.common.model.bii_type import BiiType def _binary_name(name): return os.path.splitext(name.replace("/", "_"))[0] class CPPTarget(object): def __init__(self): self.files = set() # The source files in this targe...
4,577
1,437
from tf_keras_1.finetune.imports import * from system.imports import * from tf_keras_1.finetune.level_10_schedulers_main import prototype_schedulers class prototype_optimizers(prototype_schedulers): ''' Main class for all optimizers in expert mode Args: verbose (int): Set verbosity levels ...
20,554
5,809
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
1,078
303
''' This program implements a Fast Neural Style Transfer model. References: https://www.tensorflow.org/tutorials/generative/style_transfer ''' from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import tensorflow_hub as hub import os, sys import time import...
1,488
456
# -*- coding: utf-8 -*- # @Author: Anderson # @Date: 2019-04-25 00:30:09 # @Last Modified by: ander # @Last Modified time: 2019-12-07 01:14:16 from django.urls import path from . import views urlpatterns = [ path("", views.editor, name="editor"), path("upload_code", views.upload_code, name="upload_code") ...
322
139
s = "Rats live on no evil star" print(s[::-1])
47
22
import numpy as np import torchvision.datasets as datasets from pathlib import Path import libs.dirs as dirs import libs.utils as utils import libs.dataset_utils as dutils import models.utils as mutils import libs.commons as commons from libs.vis_fun...
4,168
1,300
import cv2 as cv import sys import numpy as np import tifffile as ti import argparse import itertools max_lowThreshold = 100 window_name = 'Edge Map' title_trackbar = 'Min Threshold:' ratio = 3 kernel_size = 3 def CannyThreshold(val): low_threshold = val #img_blur = cv.blur(src_gray, (3,3)) ...
6,851
2,763
# -*- encoding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re from addonpayments.utils import GenerationUtils class TestGenerationUtils: def test_generate_hash(self): """ Test Hash generation success case. """ test_string = '20120926112654.thestore...
1,179
386
import tensorflow as tf from typing import Union, Tuple class LayerConv(tf.keras.layers.Layer): """ A layer class that implements sequence convolution. Instances of this class can be used as layers in the context of tensorflow Models. This layer implements convolution and pooling. Uses the following sequ...
5,276
1,461
from flask import Flask, render_template, request app = Flask(__name__) bd={"usuario":"alexandre.c.andreani@gmail.com","senha":"12345"} def usuario_existe(usuario): return usuario == bd["usuario"] def verifica_senha(usuario,senha): return usuario == bd["usuario"] and senha==bd["senha"] @app.rout...
1,207
501
import picamera from time import sleep from time import time import os import numpy as np import cv2 import imutils import argparse import face_recognition from camera.check_rectangle_overlap import check_rectangle_overlap # https://picamera.readthedocs.io/en/release-1.0/api.html def get_number_faces(): time_now...
2,883
943
from Cuadrado import Cuadrado from Rectangulo import Rectangulo print("Creacion objeto Cuadrado".center(50, "-")) cuadrado1 = Cuadrado(lado=10, color='azul') print(cuadrado1) print(cuadrado1.color) print(cuadrado1.ancho) print(cuadrado1.alto) print(cuadrado1.area()) # trabajando con el metodo MRO - Method Resolution...
609
244
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import sys import traceback from PySide2.QtCore import (QObject, QRunnable, Signal, Slot) class WorkerSignals...
1,399
420
# Copyright 2018-current ICON Foundation # # 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 ...
1,252
362
def media_suicida (mediaProvas, mediaTrabalhos): if mediaProvas >= 5 and mediaTrabalhos >= 5: return mediaProvas * 0.6 + mediaTrabalhos * 0.4 return min(mediaProvas, mediaTrabalhos) notasProva = [] notasTrabalho = [] quantidadeProva = int(input("Quantidade de provas: ")) for item in range(quantidade...
788
297
"""Encoder module""" from __future__ import division import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_packed_sequence as unpack class LSTMEncoder(nn.Module): """LSTM encoder""" def __init__( self, hidden_size, ...
1,832
593
import pandas as pd def summarize(vars, df): ''' this function prints out descriptive statistics in the similar way that Stata function sum does. Args: pandas column of a df Output: None (print out) ''' num = max([len(i) for i in vars]) if num < 13: num = 13 print("{} |...
4,239
1,364