text
string
size
int64
token_count
int64
from abc import ABC class Refferal_API(ABC): def __init__(self): # TODO pass def NewVacancy(): # TODO pass def NewApplication(): # TODO pass def NotifyReferrer(): # TODO pass def NotifyApplicant(): # TODO pass ...
324
98
# Generated by Django 3.2.8 on 2021-11-10 05:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms_voting', '0011_auto_20211110_0502'), ] operations = [ migrations.RemoveField( model_name='bulletin', name='resul...
502
172
import os from config import config def getpath(path): base_path = os.path.join(config.upload_path, 'app', 'static', 'upload') UPLOAD_LICENCE_FOLDER = os.path.join(base_path, 'licence') UPLOAD_COVER_FOLDER = os.path.join(base_path, 'cover') UPLOAD_PIECE_FOLDER = os.path.jo...
670
244
from click.exceptions import FileError from scipy.optimize import curve_fit import matplotlib.pyplot as plt from . import util import numpy as np import click import sys import csv import os def pt1(t, K, T): """ time-domain solution/formula for a first-order/pt1 system Args: t (float): time K (float): ...
5,551
2,195
'''What is premium?''' from discord.ext import commands from packages.utils import Embed, ImproperType class Command(commands.Cog): def __init__(self, client): self.client= client @commands.command() async def premium(self, ctx): #return await ctx.send('This command is currently under...
2,632
921
from cmd import Cmd import sys from select import poll, POLLIN import string from subprocess import call from wireless_emulator import * from wireless_emulator.clean import cleanup class CLI(Cmd): prompt = 'WirelessTransportEmulator>' identchars = string.ascii_letters + string.digits + '_' + '-' def __in...
4,435
1,195
from django.db import models # Create your models here. class HelthDepartment(models.Model): name = models.CharField(max_length=100) availability = models.DateTimeField() def __str__(self): return self.name #helth_department = ((0,"daily task"),(1,"work jobs"),(2,"house needs")) class Patient(mo...
1,036
337
# Generated by Django 3.0.3 on 2021-12-22 00:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vid', '0002_allnty'), ] operations = [ migrations.CreateModel( name='CountyMetrics', fields=[ ('id',...
1,647
470
import math s = 0.0 k = 1 n = int(input()) for i in range(n+1): k*=max(1,i) s += 1/k print(s)
101
56
from unittest import TestCase from ..Model import Model from ..Simulation import Simulation from os.path import dirname, join import numpy as np import math class TestToy3(TestCase): def test_toy3(self): model = Model(join(dirname(__file__), "../../notebooks/model_files/toy3.bnet")) ...
745
261
class KeyBinderDummy(object): """Class used to allow keybindings to be caught and to be actioned.""" def __init__(self): self.bindings = [] self.saved_obj = None def bind(self, action, dispatcher, dispatcher_params): """ Bind a key press """ self.bindings.append({ ...
755
226
""" 题目:礼物的最大价值 在一个mxn的期盼的每一格都放有一个礼物 每个礼物有一定的价值(价值大于0) 你可以从棋盘的左上角开始拿格子里的礼物 并每次向右或者向下移动一格 直到达到棋盘的右下角 给定一个棋盘及其上面的礼物 请计算你最多能拿到多少价值的礼物 思路:动态规划 动态规划方程 dp[i][j]=max(dp[i-1][j],dp[i][j-1])+arr[i][j] """ class Solution: def GetGiftMaxValue(self, arr): if arr is None or len(arr) == 0: return ...
1,179
581
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : doubanRequest.py # @Author: G # @Date : 2018/8/5 import requests url = 'https://movie.douban.com' doubanText = requests.get(url).text print(doubanText)
218
100
import json import unittest from flask_caching import Cache from app import app, db from apps.shop.models import ( ShopItems, ShopCategories, ShopItemsCategoriesMapping, ShopItemLogos, ShopItemsURLMapping ) from apps.users.models import Users, UsersAccessTokens, UsersAccessLevels, Use...
31,876
9,353
# The MIT License (MIT) # Copyright (c) 2017 Massachusetts Institute of Technology # # Author: Cody Rude # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this sof...
3,728
1,153
import json from urllib.parse import urlencode from flask import Response from werkzeug.http import HTTP_STATUS_CODES class ApiResponse(Response): default_status = 200 default_mimetype = 'application/json' def __init__(self, data=None, status=None, **kwargs): if data is None: if kwa...
1,964
588
import argparse import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from dgl.nn.pytorch import GraphConv import dgl.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel import os import sys import samgraph.torch as sam impo...
16,675
5,644
import serial # Using SERIAL module to connect to comm ports via ARDUINO Arduino_Serial = serial.Serial('/dev/ttyACM0',9600) # Connecting via ttyACM0 port (LINUX) print (Arduino_Serial.readline()) # Status print ("Please enter --------> 1 <------- to TURN...
1,445
416
import os import pathlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd from collections import OrderedDict class Logger: def __init__(self, save_dir, prefix=''): #names = ['epoch', # 'loss', 'loss...
3,453
1,217
# AFM font ZapfDingbats (path: /usr/share/fonts/afms/adobe/pzdr.afm). # Derived from Ghostscript distribution. # Go to www.cs.wisc.edu/~ghost to get the Ghostcript source code. import dir dir.afm["ZapfDingbats"] = (500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, ...
1,493
1,363
import bs import random import math class RunaroundGame(bs.CoopGameActivity): tips = [ 'Jump just as you\'re throwing to get bombs up to the highest levels.', 'No, you can\'t get up on the ledge. You have to throw bombs.', 'Whip back and forth to get more distance on your throws..'] ...
43,185
13,216
#!/usr/bin/python3 from plano import * ENV["BACKEND_SERVICE_HOST"] = "localhost" ENV["BACKEND_SERVICE_PORT"] = backend_port = str(get_random_port()) ENV["FRONTEND_SERVICE_PORT"] = frontend_port = str(get_random_port()) backend_url = f"http://localhost:{backend_port}/api/hello" frontend_url = f"http://localhost:{fron...
710
250
"""Python C API alternative to `fractions` module.""" __version__ = '1.4.0' try: from _cfractions import Fraction except ImportError: import numbers as _numbers from fractions import Fraction as _Fraction from typing import (Any as _Any, Dict as _Dict, O...
14,492
3,565
import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import LabelBinarizer from sklearn.linear_model.logistic import LogisticRegression from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import classificat...
1,401
494
import numpy as np from lane_pixel_finder import find_lane_pixels ''' Calculates the curvature of polynomial functions in meters. ''' # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension def measure_cur...
1,289
504
#----------------------------------------------------------------------------- # Name: Catching Exceptions (try-except.py) # Purpose: To provide example of a simple input loop using try-catch # # Author: Mr. Brooks # Created: 01-Oct-2020 # Updated: 01-March-2021 #--------------------------------...
816
219
# coding: utf-8 r"""Tabby rear suspension assembly""" from car_assemblies import make_rear_suspension_assembly from osvcad.view import view_assembly, view_assembly_graph assembly = make_rear_suspension_assembly() if __name__ == "__main__": view_assembly(assembly) view_assembly_graph(assembly)
306
104
############################ # This example shows how to run pygosolnp with Truncated Normal distribution using Numpy and Scipy ############################ from typing import List, Optional # Numpy random has the PCG64 generator which according to some research is better than Mersenne Twister from numpy.random impor...
2,791
886
from .utils import GenomeFile, split_locus_tag class CustomAnnotationFile(GenomeFile): def __init__(self, file: str, original_path: str = None, custom_annotation_type: str = None): if custom_annotation_type: self.custom_annotation_type = custom_annotation_type else: self.cu...
3,197
1,052
import argparse, joblib, csv, sys, os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import pandas as pd from mpl_toolkits.mplot3d import Axes3D from yellowbrick.text import TSNEVisualizer from sklearn.cluster import KMeans from sklearn.svm import SVC, LinearSVC from sklearn...
11,757
4,051
from yaml.composer import Composer as YamlComposer, ComposerError class Composer(YamlComposer): def compose_document(self): # Drop the DOCUMENT-START event. self.get_event() # UNITY: used to store data after the anchor self.extra_anchor_data = {} # Compose the root node....
951
278
import platform from setuptools import Extension import numpy from Cython.Build import cythonize compile_args = [] link_args = [] pf = platform.system() if pf == "Windows": # for MSVC compile_args = ["/std:c++14", "/DNOMINMAX", "/O2", "/openmp"] elif pf == "Darwin": # for clang compile_args = ["-std=...
1,164
432
import logging from django.views import View from .models import Users, Tokens from libs.response_extra import response_failure, response_success, user_does_not_exists, view_exception from libs.tool_decorator import cvb_params from .decorator import cvb_token_check log = logging.getLogger(__name__) class LoginView...
3,802
1,233
from compas_plotters.artists import Artist from matplotlib.patches import Circle as CirclePatch # from matplotlib.transforms import ScaledTranslation __all__ = ['CircleArtist'] class CircleArtist(Artist): """""" zorder = 1000 def __init__(self, circle, linewidth=1.0, linestyle='solid', facecolor=(1.0, ...
1,871
596
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 21:06:14 2018 Taken from Data Structures and Algorithms using Python """ class SortedPriorityQueue(PriorityQueueBase): def __init__(self): self._data = PositionalList() def __len__(self): return len(self._data) def add(self,ke...
1,044
329
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
14,576
4,555
#!/usr/env python import pprocess # parallel computing module import os # os utilitites import time # keep track of time import astropy.io.fits as fits # FITS manipulating library import matplotlib.pyplot as plt import numpy as np # numeric python for array manipulation import myscitools # my personal tools ...
2,284
833
import requests import urllib3 from urllib3 import HTTPConnectionPool class HttpsClient: def __init__(self): pass @staticmethod def get(_url, _query_string={}, _header=None): urllib3.disable_warnings() _resp = requests.get(_url, _query_string, headers=_header, verify=False) ...
625
212
import os import sys from dataclasses import field from typing import List, Optional, Set, cast from unittest import skipUnless from aio_rom import Model from aio_rom.attributes import RedisModelSet if sys.version_info >= (3, 8): from unittest.async_case import IsolatedAsyncioTestCase as TestCase ASYNCTEST =...
6,217
2,077
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( str ) : n = len ( str ) C = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] P = [ [ False for i in ...
1,514
611
from .utils import return_response, api_get_request class StaffMixin(): TIMETAP_API_STAFF = '/staff' api_get_request = api_get_request @return_response def get_staff(self): return self.api_get_request(f'{self.TIMETAP_API_STAFF}') @return_response def get_staff_by_professionalId(self...
787
260
from django.apps import AppConfig class TreatmentConfig(AppConfig): name = 'goutdotcom.treatment'
104
35
# Space: O(1) # Time: O(logn) class Solution: def search(self, nums, target): length = len(nums) if length == 0: return -1 if length == 1: return 0 if nums[0] == target else -1 # First, find out the actual end point of sorted array left, right = 0, length - 1 whil...
1,201
363
import time import numpy as np from typing import Dict, List, Tuple from nxs_libs.interface.workload_manager import ( NxsBaseWorkloadManagerPolicy, ) from nxs_types.frontend import FrontendModelPipelineWorkloadReport from nxs_types.message import ( NxsMsgPinWorkload, NxsMsgType, NxsMsgReportInputWorkloa...
7,807
2,453
# -*- coding: utf-8 -*- import os import uuid import platform import warnings from pathlib import Path from collections import defaultdict from dataclasses import replace import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from convergence import Convergence from snl_d3d_cec_veri...
23,258
7,306
import numpy as np import matplotlib.pyplot as plt import torch import scipy from GLM.GLM_Model import GLM_Model, PyTorchObj from scipy.optimize import minimize, Bounds from tqdm import tqdm class GLM_Model_GP(GLM_Model.GLM_Model): def __init__(self, params): super().__init__(params) self.kernel...
15,236
5,008
from k5test import * # Test that the kdcpreauth client_keyblock() callback matches the key # indicated by the etype info, and returns NULL if no key was selected. testpreauth = os.path.join(buildtop, 'plugins', 'preauth', 'test', 'test.so') conf = {'plugins': {'kdcpreauth': {'module': 'test:' + testpreauth}, ...
13,127
4,318
#!/usr/bin/env python3 # ## Licensed to the .NET Foundation under one or more agreements. ## The .NET Foundation licenses this file to you under the MIT license. # ## # Title: antigen_unique_issues.py # # Notes: # # Script to identify unique issues from all partitions and print them on console. # ######################...
4,303
1,129
""" .. module:: CMetricTestError :synopsis: Performance Metric: Test Error .. moduleauthor:: Marco Melis <marco.melis@unica.it> """ import sklearn.metrics as skm from secml.array import CArray from secml.ml.peval.metrics import CMetric class CMetricTestError(CMetric): """Performance evaluation metric: Test ...
1,448
465
from __future__ import division, print_function import argparse import sys, os, time, gzip, glob from collections import defaultdict from base.config import combine_configs from base.io_util import make_dir, remove_dir, tree_to_json, write_json, myopen from base.sequences_process import sequence_set from base.utils imp...
35,592
10,422
# -*- coding: utf-8 -*- # Copyright (c) 2015, nodux and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe import throw, _ class NoduxItemPrice(Document): def validate(self): self.validate_ite...
1,777
666
from flask import render_template from flask_mail import Message from main import mail, app def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg) def send_password_reset...
799
224
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union from cdm.persistence.cdmfolder.types.projections.operation_base import OperationBase from cdm.persistence.cdmfolder.types.type_attribute im...
779
196
""" Query functions to run against ElasticSearch """ # pylint: disable=invalid-name from ebr_connector.schema.build_results import BuildResults detailed_build_info = { "includes": [ "br_build_date_time", "br_job_name", "br_job_url_key", "br_source", "br_build_id_key", ...
1,900
582
#!/usr/bin/env python3 import socket import sys import time import argparse # action can be reflect or drop action = "drop" test = 0 def test_data (data, n_rcvd): n_read = len (data); for i in range(n_read): expected = (n_rcvd + i) & 0xff byte_got = ord (data[i]) if (byte_got != expe...
4,714
1,658
import torch from torch.utils import data import numpy as np import os import cv2 import torchvision.transforms as transforms from PIL import Image import random from PIL import ImageFile def get_transform(opt): transform_list = [] if opt.resize_or_crop == 'resize_and_crop': osize = [opt.loadSize_1, op...
2,806
974
################################################################################################################################################################ # @project Open Space Toolkit ▸ Physics # @file bindings/python/test/time/test_time.py # @author Lucas Brémond <lucas@loftorbital.com...
6,290
1,260
from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from datetime import datetime, timedelta from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.header import Header import psycopg2.extension...
61,602
23,378
from datetime import datetime, timedelta from flask import current_app import jwt from api import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(128), unique=True, nullable=False) email = db.Col...
2,022
595
import ccs team = ccs.team(raw_input("Team Number: ")) summary = team.summary print "Team {} ({} {}) - {} images ({} points) - {}/{} {}".format( summary.number, summary.division, summary.location, summary.images, summary.score, summary.playtime, summary.scoretime, summary.warn) for image in team.ima...
522
169
# Copyright 2015, 2017 IBM Corp. # # 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 require...
10,795
3,116
import random import networkx as nx from ..node import Node def generate(input_data): graph = nx.Graph() groups_size = [random.choice(range(input_data['min_group_nodes'], input_data['max_group_nodes']+1)) for i in range(input_data['num_groups'])] num_attacker = int(sum(groups_size) * ...
5,752
1,769
#!/usr/bin/env python3 sx, sy, tx, ty = map(int, input().split()) x, y = tx - sx, ty - sy print("R"*x + "U"*-~y + "L"*-~x + "D"*-~y + "R" + "U"*y + "R"*-~x + "D"*-~y + "L"*-~x + "U")
182
109
a = list(map(int, input().split())) [i[0] for i in sorted(enumerate(a), key=lambda x:x[1])]
92
39
"""This module provides the RP To-Do CLI.""" from typing import Optional import typer from rptodo import __app_name__, __version__ app = typer.Typer() def _version_callback(value: bool) -> None: if value: typer.echo(f"{__app_name__} v{__version__}") raise typer.Exit() @app.callback() def mai...
560
186
import asyncio import logging import pigpio class Relay: """Simple to use relay class implemented with pigpio :param pin: GPIO pin number :type pin: int :param on_level_low: Determines the logic level of the on-state. If set to True, the relay is on when the GPIO pin state is LOW. De...
4,629
1,443
""" MIT License Copyright (c) 2020 ValkyriaKing711 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...
8,322
2,611
class Solution: def getHint(self, secret: str, guess: str) -> str: bull = 0 cow = 0 values = dict() for i in range(len(secret)): if secret[i] == guess[i]: bull += 1 elif secret[i] in values: values[secret[i]] += 1 el...
689
202
from django.conf.urls import url from . import classviews urlpatterns = [ url(r'^event/$', classviews.HookEvent.as_view()), ]
131
46
"""Stream class for tap-parquet.""" import requests from copy import deepcopy from pathlib import Path from typing import Any, Dict, Optional, Union, List, Iterable from singer_sdk.streams import Stream from singer_sdk.typing import ( ArrayType, BooleanType, DateTimeType, IntegerType, NumberType,...
2,392
697
import sys import random from design import * from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5 import QtGui ppt = ['Rock', 'Paper', 'Scissors'] game = [] def aChoice(): esc = random.choice(ppt) game.append(esc) class App(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): ...
3,851
1,411
import unittest from geopy.point import Point from geopy.format import format_degrees class TestFormat(unittest.TestCase): @unittest.skip("") def test_format(self): """ format_degrees """ self.assertEqual( format_degrees(Point.parse_degrees('-13', '19', 0)), ...
354
124
# -*- coding: utf-8 -*- """ Created on Sun Oct 20 20:52:56 2019 @author: 陈彪,版权所有 这个是一个排序算法的总结,将所有的排序算法都重新写一遍,然后我们首先会分析算法的时间 复杂度,然后简单介绍一下这些算法的原理,最后使用python实现,然后我们会使用测试案例 来进行测试。 """ import random '''首先映入眼帘的就是冒泡排序,这是一个让人理解起来最简单的排序算法,这个算法的时间复 杂度是O(N^2),从下面的程序中也能看出来这个算法的时间复杂度确实是O(N^2). ''' def bubble(a): for i in...
653
430
# # Usage: # # % brownie console # >>> from scripts import token # >>> green = token.main() # >>> token.issue(green) # >>> token.transfer(green, accounts[1], accounts[2], 1) # from brownie import Token, accounts admin = accounts[0] issuer = accounts[1] holders = accounts[2:9] max_supply...
722
260
import string WIKI_BESTAND = '/Users/tom/Downloads/\ nlwiktionary-20191020-pages-articles-multistream-index.txt' WOORD_BESTAND = 'woord-frequenties.txt' SLECHT_BESTAND = 'slechte-woorden.txt' BLACKLIST = {i.strip() for i in open(SLECHT_BESTAND)} AANTAL = 1000000000000000 MIN = 4 MIN_ACHTERVOEGSEL = 4 VOORVOEGSELS = ...
2,711
1,026
import os import random import numpy as np import pandas as pd def set_random_seed(seed=42): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) def set_display_options(): pd.set_option("max_colwidth", 1000) pd.set_option("max_rows", 50) pd.set_option("max_column...
384
152
offset = -8 while offset != 0 : print('Benar') if offset > 0 : offset = offset -3 else: offset = offset +2 print(offset)
158
54
from tortoise.contrib.fastapi import register_tortoise as config_tortoise from config.settings import settings DB_URL = f'postgres://{settings.DB_USERNAME}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_DATABASE}' TORTOISE_MODULES = ['app.example.model'] TORTOISE_ORM_MODULES = TORTOISE_MOD...
832
301
from django.shortcuts import redirect def login_redirect(request): return redirect('/account/login')
105
27
# Copyright (c) 2020 Aiven, Helsinki, Finland. https://aiven.io/ from setuptools import setup import version version = version.get_project_version("rpm_s3_mirror/version.py") setup( name="rpm_s3_mirror", packages=["rpm_s3_mirror"], version=version, description="Tool for syncing RPM repositories with ...
982
332
import time from pytest_bdd import scenarios, when, then, given, parsers from pages.search import SearchTests from pages.register_page import RegisterPage # Scenarios scenarios('../features/test_register_search_scenario.feature') @given('open the page') def open_page(browser): negative = SearchTests(browser) ...
2,074
675
import codecs from logging import getLogger import os from pendium import app from pendium.plugins import IRenderPlugin from pendium.plugins import ISearchPlugin from yapsy.PluginManager import PluginManager log = getLogger(__name__) # Populate plugins lib_path = os.path.abspath(os.path.dirname(__file__)) manager =...
8,668
2,601
import random import numpy as np import pandas as pd import math from sklearn import preprocessing import scipy.stats as stats def edge_in_cliq(edge, nodes_in_cliq): if edge[0] in nodes_in_cliq: return True else: return False def edges_to_remove_neighbourhood(all_edges, neighbourhood_density...
3,957
1,164
import tempfile import speech.models import speech.loader import shared def test_save(): freq_dim = 120 model = speech.models.Model(freq_dim, shared.model_config) batch_size = 2 data_json = "test.json" preproc = speech.loader.Preprocessor(data_json) save_dir = tempfile....
767
280
import matplotlib.pyplot as plt # TODO: port away from matplotlib to a seaborn # Probability Distribution Function (PDF). # Cumulative Distribution Function (CDF) # TODO: put all of these functions within a custom function image = plt.imread('900px-Astronaut-EVA.jpg') plt.subplot(2, 1, 1) plt.imshow(image, cmap='gra...
928
356
from .model_zoo import load_weights
35
12
from logging_logger import loggerClass import logging loggerClass.WritetoScreen(loggerClass,logging.INFO,"testing...", '%(levelname)s:%(message)s') loggerClass.Writetofile(loggerClass,'sample.log',logging.WARNING,"testing...", '%(levelname)s:%(message)s')
282
86
formatter = "{} {} {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("a", "b", "c", "d", "r"))
111
52
""" The HR solver and algorithm. """ from matching import Game, Matching from matching import Player as Resident from matching.players import Hospital from .util import delete_pair, match_pair class HospitalResident(Game): """ A class for solving instances of the hospital-resident assignment problem (HR). ...
14,115
3,798
#!/usr/bin/env python # coding: utf-8 # based on public kernel https://www.kaggle.com/corochann/ashrae-feather-format-for-fast-loading import os import random import gc import tqdm import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def prepare(root, output): train_df ...
2,931
1,063
import copy import functools import os import numpy as np from scipy import sparse from spinsys import constructors, half, dmrg, exceptions from cffi import FFI class SiteVector(constructors.PeriodicBCSiteVector): def __init__(self, ordered_pair, Nx, Ny): super().__init__(ordered_pair, Nx, Ny) def a...
23,531
7,816
import pandas as pd import copy from pathlib import Path import pandas as pd import numpy as np import math from datetime import datetime,timedelta import matplotlib.pyplot as plt from predictor.utility import msg2log def Forcast_imbalance_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_240920...
16,528
6,994
# -*- coding: utf-8 -*- import requests, json from bs4 import BeautifulSoup from mspider.spider import MSpider class Get_indic_idSpider(MSpider): def __init__(self): self.name = "get_count_id" self.indics = ['GDP', 'GDP-based-on-PPP', 'Real-GDP-growth', 'GDP-per-capita', 'GDP-per-capita-based-on-P...
5,450
2,097
from random import choice from copy import deepcopy def minCut(G): # the function which randomly chooses the edges and fuses the nodes which are linked with that edge # input: the graph G, represented by a dictionary # output: the min cut # while the graph has more than two nodes, randomly...
2,556
794
import tvm from tvm.tensor_graph.core2.graph.concrete import Compute, Tensor from .padding import zero_pad2d ###################################################################### # for functional, all states are inputs, data from inside functionals # can only be constants ##########################################...
5,223
1,745
import numpy as np from functools import lru_cache, wraps #from fastcache import clru_cache def np_lru_cache(*args, **kwargs): """ LRU cache implementation for functions whose FIRST parameter is a numpy array forked from: https://gist.github.com/Susensio/61f4fee01150caaac1e10fc5f005eb75 """ ...
1,352
501
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
4,951
1,562
# Generated by Django 4.0.1 on 2022-01-28 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project_organizer', '0008_rename_tg_id_student_tg_user_project_manager_tg_user_and_more'), ] operations = [ migrations.AddField( ...
706
225
from bintray.bintray import Bintray def test_get_user(): bintray = Bintray() response = bintray.get_user("uilianries") assert response.get("name") == "uilianries" assert response.get("error") == False assert response.get("statusCode") == 200 def test_get_organization(): bintray = Bintray() ...
842
291
#! /usr/bin/env python import sys import os version_file = os.path.join( os.path.abspath(os.path.dirname(__file__)), "problog/version.py" ) version = {} with open(version_file) as fp: exec(fp.read(), version) version = version["version"] if __name__ == "__main__" and len(sys.argv) == 1: from problog im...
3,424
1,140