text
string
size
int64
token_count
int64
from pyrogram import Client as bot, filters, emoji MENTION = "[{}](tg://user?id={})" text1="hi{} {} welcome to Group Chat" group ="jangobotz" @bot.on_message(filters.chat(group) &filters.new_chat_members) async def welcome(bot, message): new_members = [u.mention for u in message.new_chat_members] TEXT2= te...
666
316
import locale from xml.sax import saxutils defaultEncoding = locale.getdefaultlocale()[-1] class Generator(saxutils.XMLGenerator): """Friendly generator for XML code""" def __init__(self, out=None, encoding="utf-8"): """Initialise the generator Just overrides the default encoding of the bas...
2,079
559
# -*- coding: utf-8 -*- import json import codecs import traceback import sys import requests import requests_cache import feedparser import collections from bs4 import BeautifulSoup from urlparse import urlparse, urljoin one_day = 60 * 60 * 24 requests_cache.install_cache( 'rss_cache', backend='sqlite', expire_...
4,877
1,469
from src.main.common.model import endpoint class TableEndpoint(endpoint.Endpoint): @classmethod def do_get(cls, *args, **kwargs): from src.main.admin_api.utils.descriptor_utils import DescriptorUtils db_system_name = kwargs.get("db_system_name") tb_system_name = kwargs.get(...
3,102
916
#!/usr/bin/python import yaml import json import sys import re import argparse from distutils.version import LooseVersion from collections import defaultdict discovery_port = '5998' config_api_port = '8082' analytics_api_port = '8081' control_port = '8083' dns_port = '8092' agent_port = '8085' def get_neutron_userna...
10,326
3,485
def rec_sum(n): if(n<=1): return n else: return(n+rec_sum(n-1))
88
39
import tensorflow as tf from data.BaseReader import BaseReader import numpy as np class Base2DReader(BaseReader): # inherit from BaseReader, implement different 2D cropping (cropping from 2D) def __init__(self, objtype=0, shuffle=True, batch_size=1, crop_noise=False): super(Base2DReader, self).__init...
9,292
3,189
from tortoise import Model, fields class TZProfile(Model): account = fields.CharField(36, pk=True) contract = fields.CharField(36) valid_claims = fields.JSONField() invalid_claims = fields.JSONField() errored = fields.BooleanField() class Meta: table = "tzprofiles"
301
98
#api for extracting the results from wikidata #https://www.wikidata.org/w/api.php?search=las&language=en&uselang=en&format=jsonfm&limit=25&action=wbsearchentities # importing modules import requests from lxml import etree import wikipedia import sys import re import pickle import numpy as np import os import sys i...
6,006
2,158
from Crypto.Util.number import getRandomRange from sympy.ntheory.residue_ntheory import jacobi_symbol N = int(input("N ? ")) x = getRandomRange(2, N) x2 = (x*x) % N J = jacobi_symbol(x, N) print(f"x2 = {x2}") guess = int(input("j_guess ? ")) print(f"x = {x}") print("Outcome = Heads" if guess == J else "Outcome = T...
327
144
from django.core.management.base import BaseCommand, CommandError from scoreboard.ranking import calculate_statistics class Command(BaseCommand): help = 'Run Statistics' def handle(self, *args, **options): calculate_statistics()
248
66
class Solution(object): def twoSum(self, nums, target): seen = {} output = [] for i in range(len(nums)): k = target - nums[i] if k in seen: output.append(seen[k]) output.append(i) del seen[k] else: ...
796
253
""" Copyright (c) 2018, Joseph Sullivan All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the follo...
9,028
2,747
import numpy as np import time from inaccel.keras.applications.resnet50 import decode_predictions, ResNet50 from inaccel.keras.preprocessing.image import ImageDataGenerator, load_img model = ResNet50(weights='imagenet') data = ImageDataGenerator(dtype='int8') images = data.flow_from_directory('imagenet/', target_siz...
901
352
from rest_framework.permissions import BasePermission, SAFE_METHODS from .models import User class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): return bool( request.method in SAFE_METHODS or request.user and request.user.is_authenticated and ...
1,084
315
# -*- coding: utf-8 -*- from morphological_classifier.perceptron import AveragedPerceptron from morphological_classifier.performance_metrics import PerformanceMetrics from morphological_classifier.stats_plot import StatsPlotter from morphological_classifier import constants, utils import numpy as np from collecti...
8,090
2,592
"""evaluation function for chromosome """ import subprocess from subprocess import PIPE, STDOUT from autoprover.evaluation.coqstate import CoqState def preprocess(theorem, chromosome): """ convert chromosome to complete Coq script Args: theorem (list): a list of string contains theorem or some pr...
4,263
1,321
import os import numpy from numpy import * import math from scipy import integrate, linalg from matplotlib import pyplot from pylab import * from .integral import * def get_velocity_field(panels, freestream, X, Y): """ Computes the velocity field on a given 2D mesh. Parameters --------- panel...
1,323
442
import abc from .exceptions import HamsException import logging # Constants HAMS_INTERNAL_QUERY_PORT = 1337 HAMS_INTERNAL_MANAGEMENT_PORT = 1338 HAMS_INTERNAL_RPC_PORT = 7000 HAMS_INTERNAL_METRIC_PORT = 1390 HAMS_INTERNAL_REDIS_PORT = 6379 HAMS_DOCKER_LABEL = "ai.hams.container.label" HAMS_NAME_LABEL = "ai.hams.name"...
4,125
1,420
# -*- encoding: utf-8 -*- """ endpoint_user_tokens.py """ from solidata_api.api import * # from log_config import log, pformat log.debug(">>> api_auth ... creating api endpoints for USER_TOKENS") ### create namespace ns = Namespace('tokens', description='User : tokens freshening related endpoints') ### import mo...
11,044
3,847
"""Main module.""" import copy import io import logging import re from typing import Dict, List import yaml log = logging.getLogger(__name__) TEKTON_TYPE = ("pipeline", "pipelinerun", "task", "taskrun", "condition") class TektonBundleError(Exception): pass def tpl_apply(yaml_obj, parameters): def _apply...
4,750
1,404
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ import os from sims4.commands import Command, CommandType, ...
2,385
719
# Generated by Django 3.1.4 on 2021-01-22 22:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blackbook', '0021_update_account_categories'), ] operations = [ migrations.RemoveField( model_name='budgetperiod', name='bud...
1,884
487
from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model class EmailPhoneBackend(BaseBackend): """ docstring """ def authenticate(self,request, email=None,phone=None, password=None): # Check the username/password and return a user. my_...
1,431
411
import requests from django.core.management.base import BaseCommand, CommandError from apps.core.models import EmailDomain DATA_URL = ( 'https://raw.githubusercontent.com/martenson/disposable-email-domains' '/master/disposable_email_blacklist.conf' ) class Command(BaseCommand): help = 'Update list of b...
1,655
463
# Given a positive integer num consisting only of digits 6 and 9. # Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). # Example 1: # Input: num = 9669 # Output: 9969 # Explanation: # Changing the first digit results in 6669. # Changing the second digit results in 9969...
1,659
600
import base64 import rsa from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from ticketing.models import BalanceTicket, RideTicket class VerifyFailedError(Exception): pass class QRCode: """ QRCode creator is used to create a user ticket/balance ID, which is then...
3,245
990
import datetime from webService import WebService import Utilidades as ut import sys if __name__ == "__main__": param = ut.mainMoodle(sys.argv[1:]) #param = 'moodle_plugin_sessions.txt', '', '2020-08-01 00:00:00,2020-12-31 00:00:00' webService = WebService() report = [] ret = 0 dates = param[2]...
3,015
758
from rest_framework.views import APIView from rest_framework import status from eva.serializers import WorkSerializer, PageSerializer, WordSerializer, RadicalSerializer from eva.models import Work, Page, Word, Radical from rest_framework.response import Response from django.http import Http404 class WorkView(APIView)...
5,549
1,583
from flask import Flask, request, render_template import pickle app = Flask(__name__)#khoi tao flask model = pickle.load(open('modelID3.pkl', 'rb'))#unpicke model @app.route('/',methods =["GET", "POST"]) def home(): if request.method == "POST": #lay gia tri tu form one= request.form.get("a0") ...
1,447
494
#!/usr/bin/python import os import sys import argparse #Auto-import parent module sys.path.insert(1, os.path.join(sys.path[0], '..')) import voc #from pydmv import voc parser = argparse.ArgumentParser(description="Print VOC index file without duplicates") parser.add_argument("file", help="Input index file") args = p...
474
160
from django.shortcuts import render from django.http import HttpResponse from App.models import * # Create your views here. def search(seq): myclass=Myclass.objects.all() return render(seq,'test.html',context={'myclass':myclass}) def students(req): students_id=req.GET.get('classid') studentt=Student.ob...
448
141
import os import cv2 import time path = "C:/Users/lenovo/Documents/Sites/github/hotpoor_autoclick_xhs/Xiaomi_8/day_start/hotpoor_autoclick_cache" cache = "hotpoor_autoclick_cache/screen.png" def get_image(): os.system(f"adb shell screencap -p /sdcard/%s"%cache) os.system(r"adb pull /sdcard/%s %s"%(cache,path))...
962
428
from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.shortcuts import get_object_or_404 from django.core.paginator import Paginator from hknweb.utils import markdownify from hknweb.utils import allow_public_access from hknweb.events.constants import ( ACCESSLEVEL_...
3,359
1,134
# # PySNMP MIB module HPN-ICF-VOICE-IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-VOICE-IF-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:41:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
9,756
3,948
from abc import ABC, abstractmethod from entities.customers import Customer from typing import List class CustomerDao(ABC): @abstractmethod def create_customer_entry(self, customer: Customer) -> Customer: pass @abstractmethod def get_customer_by_id(self, customer_id: str) -> Customer: ...
1,230
371
import sys import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # NOQA import seaborn # NOQA from spherecluster import sample_vMF plt.ion() n_clusters = 3 mus = np.random.randn(3, n_clusters) mus, r = np.linalg.qr(mus, mode='reduced') kappas = [15, 15, 15] num_points_per...
975
458
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Furthest point sampling Original author: Haoqiang Fan Modified by Charles R. Qi All Rights Reserved. 2017. Modified by Larissa Triess (2020) """ import os import sys import tensorflow as tf from tensorflow.python.framework import ops BASE_DIR = os.path.dirname(os.p...
1,043
362
from ariadne import MutationType from datetime import datetime as dt from models.scope import Scope from schemas.helpers.normalize import change_keys from schemas.scope import ScopeCreate mutations_resolvers = MutationType() @mutations_resolvers.field("scopeCreate") async def resolve_scope_create(_, info, scope) ->...
561
174
from typing import Optional import napari import napari.layers import numpy as np from napari.utils.geometry import project_point_onto_plane def point_in_bounding_box(point: np.ndarray, bounding_box: np.ndarray) -> bool: """Determine whether an nD point is inside an nD bounding box. Parameters ---------...
5,188
1,820
import numpy as np class AttributeGenerator: def __init__(self, RTs, Ks, Ps): self._RTs = RTs self._Ks = Ks self._Ps = Ps def generate(self): self._update_intrinsics() self._update_translation_and_rotation() self._updateProjection() def use_default_translation_and_rotation(self): self.rotation_tra...
1,245
568
# 分析黑魔法防御课界面 import cv2 import sys sys.path.append(r"C:\\Users\\SAT") # 添加自定义包的路径 from UniversalAutomaticAnswer.conf.confImp import get_yaml_file from UniversalAutomaticAnswer.screen.screenImp import ScreenImp # 加入自定义包 from UniversalAutomaticAnswer.ocr.ocrImp import OCRImp from UniversalAutomaticAnswer.util.filter imp...
6,265
3,071
# standard traversal problem class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ # leaf condition if root == None: return 0 # skeleton, since function has return, need to assign variables for followin...
521
140
import pygame.mixer from vec2d import Vec2d from saveable import Saveable class Anim(Saveable): __slots__ = ( 'func', 'time', 'pos', 'sound', 'positional_sound', ) def __init__(self, func: str, time: int, x_or_pair, y=None, sound: pygame.mixer.Sou...
826
259
import os from pathlib import Path import json from contracts_lib_py.utils import get_account from common_utils_py.ddo.ddo import DDO from nevermined_sdk_py import Nevermined, Config import yaml from configparser import ConfigParser config_parser = ConfigParser() configuration = config_parser.read('config.ini') GROUP...
5,926
1,759
""" Module to interact with scoop. """ from subprocess import Popen, PIPE # nosec import os class ScoopMockProvider: """ Module to interact with scoop. """ def __init__(self): self.version = 'unknown' def get_version(self): pass def __run_scoop(self, args, universal_newlines=False): ...
1,206
394
import datetime import uuid from typing import Optional from models.base import CustomBaseModel class ConvertVideoIn(CustomBaseModel): source_path: str destination_path: str resolution: str codec_name: Optional[str] = None display_aspect_ratio: Optional[str] = None fps: Optional[int] = None ...
515
155
# Copyright 2021 NREL # 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, software # distri...
3,965
1,415
import logging import uuid from typing import Iterable import numpy as np import pyaudio from cltl.backend.api.util import raw_frames_to_np from cltl.backend.spi.audio import AudioSource logger = logging.getLogger(__name__) class PyAudioSource(AudioSource): BUFFER = 8 def __init__(self, rate, channels, fr...
2,797
852
# -*- coding: utf-8 -*- # @Date : 2020/7/6 # @Author : mingming.xu # @Email : xv44586@gmail.com # @File : optimizers.py import re import numpy as np import tensorflow as tf from keras.optimizers import * from toolkit4nlp.backend import keras, K, is_tf_keras, piecewise_linear from toolkit4nlp.utils import * ...
21,097
7,637
from sympy import Rational as frac from ..helpers import article from ._helpers import TriangleScheme, concat, s1, s2, s3 citation = article( authors=["M.E. Laursen", "M. Gellert"], title="Some criteria for numerically integrated matrices and quadrature formulas for triangles", journal="International Jour...
5,832
3,372
# ThreadedNotifier example from tutorial # # See: http://github.com/seb-m/pyinotify/wiki/Tutorial # import pyinotify wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # watched events class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): ...
624
230
#coding=utf-8 '''/* * Copyright 2015 lixiaobo * * VersionUpgrade project licenses this file to you 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 ...
885
294
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # Copyright 2017 ROBOTIS CO., LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
9,158
3,140
# -*- coding: utf-8 -*- # file: lcf_bert.py # author: yangheng <yangheng@m.scnu.edu.cn> # Copyright (C) 2019. All Rights Reserved. # The code is based on repository: https://github.com/yangheng95/LCF-ABSA import torch import torch.nn as nn from models.lcf import LCF_BERT class Global_LCF(nn.Module): def __in...
2,063
715
def integrate_surface_flux(flux_map, r): ''' Integrates a healpix surface flux to compute the total net flux out of the sphere. r is the radius of the sphere in meters ''' import numpy as np import healpy as hp from scipy.integrate import trapz from seren3.array import SimArray ...
10,351
4,157
import numpy as np from composes.matrix.sparse_matrix import SparseMatrix from composes.matrix.dense_matrix import DenseMatrix from composes.matrix.matrix import Matrix from scipy.sparse import issparse from composes.utils.py_matrix_utils import is_array from warnings import warn def to_matrix(matrix_): """ C...
2,859
930
from .component import Component from cpu.Memory import SCOREBOARD from isa.Instructions import ALUInstruction as alu class writeback_unit(Component): def add_result(self, result): result.finished = True self.pipeline_register = self.pipeline_register + [result] self.clean() def clean(s...
1,646
434
frase = str(input('Digite uma frase: ').strip().upper()) print('A letra a aparece {} vezes'.format(frase.count('A'))) print('Sua primeira aparição é na posição {}'.format(frase.find('A') + 1)) print('Ela aparece pela última vez na posição {}'.format(frase.rfind('A') + 1))
273
100
import glob import io import numpy as np import re import os from io import BytesIO import random from uuid import uuid4 import torch from PIL import Image from torch.utils.data import Dataset from torchvision.transforms import RandomCrop from torchvision.transforms.functional import to_tensor class ListDatasetLite(D...
3,269
1,131
f = open("OI_school.csv") op = open("mdt.txt","w") for i in f.readlines(): c = i.split('","') op.write(c[-3]+','+c[-2]+','+"".join([i+',' for i in eval(c[1])])[:-1]+'\n')
179
85
class GlobalOptions: """ Class to evaluate global options for example: project path""" @staticmethod def evaluate_project_path(path): """ Method to parse the project path provided by the user""" first_dir_from_end = None if path[-1] != "/": path = path + "/" new_p...
523
142
#!/users/aneben/python/bin/python import sys import commands import numpy as np import string np.set_printoptions(precision=3,linewidth=200) months={'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sept':'09','Oct':'10','Nov':'11','Dec':'12'} def make_datetime_numeric(dt): d...
2,068
899
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File : prepare.py # Author : Chi Han, Jiayuan Mao # Email : haanchi@gmail.com, maojiayuan@gmail.com # Date : 17.07.2019 # Last Modified Date: 03.12.2019 # Last Modified By : Chi Han # # This file is part of the VCML codeb...
6,060
1,983
''' plot_allband_ds.py - Load P,L,S band dynamic spectrum for a given epoch, bin to specified resolution, and plot to file ''' import dynspec.plot reload(dynspec.plot) from dynspec import load_dict from dynspec.plot import * from pylab import * import os, subprocess import matplotlib.gridspec as gridspec ''' def get...
14,280
5,757
import os import argparse import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm def plot_1d(X_train, Y_train, X_test, Y_test, mean=None, std=None, str_figure=None, show_fig=True): plt.rc('text', usetex=True) fig = plt.figure(figsize=(8, 6)) ax = fig.gca() ax.plot(X_test, Y_...
2,518
1,042
import random import cocos from cocos.tiles import TileSet, RectCell, RectMapLayer from cocos.director import director from cocos.layer.scrolling import ScrollingManager import pyglet from game import Game from views import WorldMap, CharacterView2 class MainLayer(cocos.layer.Layer): is_event_handler = True ...
1,191
384
from itertools import takewhile from eunjeon import Mecab import queue from jamo import h2j, j2hcj import numpy as np import re import json import sys from pkg_resources import VersionConflict global script_table global voice_table global s_idx global v_idx script_table = [] voice_table = [] def main(ans,speak): ...
3,532
1,547
from flask import Blueprint blueprint = Blueprint('board', __name__) from rboard.board import routes
103
30
import logging import asyncio import sys from kademlia.network import Server handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) log = logging.getLogger('kademlia') log.addHandler(handler) log.setLevel(logging.DEBUG) ...
615
222
from src.commons.big_query.copy_job_async.result_check.result_check_request import \ ResultCheckRequest from src.commons.big_query.copy_job_async.task_creator import TaskCreator class BigQueryJobReference(object): def __init__(self, project_id, job_id, location): self.project_id = project_id s...
1,771
522
#!/usr/bin/env python3 # --- Copyright Disclaimer --- # # In order to support PyInstaller with numpy<1.20.0 this file will be duplicated for a short period inside # PyInstaller's repository [1]. However this file is the intellectual property of the NumPy team and is # under the terms and conditions outlined their repo...
2,068
617
from django.contrib import admin, messages from django.shortcuts import render from django.utils.translation import gettext_lazy as _ from inline_actions.actions import DefaultActionsMixin, ViewAction from inline_actions.admin import InlineActionsMixin, InlineActionsModelAdminMixin from . import forms from .models im...
4,480
1,328
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class MacInMACv42(Base): __slots__ = () _SDM_NAME = 'macInMACv42' _SDM_ATT_MAP = { 'HeaderBDstAddress': 'macInMACv42.header.bDstAddress-1', 'HeaderBSrcAddress': 'macInMACv42.header.bSrcAddress-2', 'BTAG...
12,731
4,441
"""Commands module common setup.""" from importlib import import_module from typing import Sequence def available_commands(): """Index available commands.""" return [ {"name": "help", "summary": "Print available commands"}, {"name": "provision", "summary": "Provision an agent"}, {"nam...
1,037
284
gScore = 0 #use this to index g(n) fScore = 1 #use this to index f(n) previous = 2 #use this to index previous node inf = 10000 #use this for value of infinity #we represent the graph usind adjacent list #as dictionary of dictionaries G = { 'biratnagar' : {'itahari' : 22, 'biratchowk' : 30, 'rangeli': 2...
3,646
1,268
from enum import IntEnum from time import gmtime, strftime import warnings import pandas as pd import numpy as np import pvl import struct from plio.io import ControlNetFileV0002_pb2 as cnf from plio.io import ControlNetFileHeaderV0005_pb2 as cnh5 from plio.io import ControlPointFileEntryV0005_pb2 as cnp5 from plio.u...
19,918
5,479
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x02\x05\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ ...
4,028
3,398
#!/usr/bin/env python """ Given one or more DCC experiment IDs, looks at all read2s that were submitted and updates each r2 file object such that it's paired_with property points to the correct r1. This works by looking at the aliases in the r2 file object to see if there is one with _R2_001 in it. If so, it sets pair...
2,130
597
"""Update node API method.""" from ibsng.handler.handler import Handler class updateNode(Handler): """Update node class.""" def control(self): """Validate inputs after setup method. :return: None :rtype: None """ self.is_valid(self.node_id, int) self.is_valid_...
1,022
331
from django.utils import unittest from nose.tools import eq_, ok_ from make_mozilla.events.paginators import results_page sample_results = [1,2,3,4,5,6,7,8,9,0] class TestResultsPage(unittest.TestCase): def test_returns_page_1_if_page_unspecified(self): page = results_page(sample_results, 4) ...
935
350
import copy import pytest from river import utils from river import ensemble estimator = ensemble.SRPClassifier( n_models=3, # Smaller ensemble than the default to avoid bottlenecks seed=42) @pytest.mark.parametrize('estimator, check', [ pytest.param( estimator, check, id=f'{...
644
217
#!/usr/bin/env python3 # 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. "The core logic of how plugins integrate with `popen_nspawn`" import functools import subprocess from contextlib impor...
2,071
712
# -*- coding: utf-8 -*- import time import pandas as pd # self-made import manage_mysql def horseDB(table,search): con = manage_mysql.connect() c = con.cursor() column=[] value=[] for i in range(len(search)): if i%2 == 0: column.append(search[i]) else: va...
4,577
1,464
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from .coco import COCODataset from .voc import PascalVOCDataset from .concat_dataset import ConcatDataset __all__ = ["COCODataset", "ConcatDataset", "PascalVOCDataset"] # if isinstance(dataset, datasets.MyDataset): # return coco_evaluation(**...
325
108
from social_core.actions import do_auth, do_complete, do_disconnect
68
21
""" Code for working with data. In-memory format (as a list): - board: Tensor (8, 8, 2) [bool; one-hot] - move: Tensor (64,) [bool; one-hot] - value: Tensor () [float32] On-disk format (to save space and quicken loading): - board: int64 - move: int64 - value: float32 """ from typing import Dict, Tuple import ...
3,097
1,081
t=int(input("")) while (t>0): n=int(input("")) f=1 for i in range(1,n+1): f=f*i print(f) t=t-1
140
64
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False for x in [2,3,5]: while(num % x ==0): num /= x return num==1
269
83
# Copyright: 2005 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD # "More than one statement on a single line" # pylint: disable-msg=C0321 """ atom exceptions """ __all__ = ("MalformedAtom", "InvalidVersion", "InvalidCPV", "ParseError") from pkgcore.package import errors class MalformedAtom(errors.InvalidD...
1,569
498
#! /usr/bin/env python import datetime import os import time import tensorflow as tf from datahelpers import data_helper_ml_mulmol6_OnTheFly as dh from evaluators import eval_pan_archy as evaler from networks.cnn_ml_archy import TextCNN def init_data(embed_dimension, do_dev_split=False): dater = dh.DataHelperM...
10,578
3,548
__version_info__ = (1, 6, 1) __version__ = '.'.join(map(str, __version_info__))
80
36
#Area of a rectangle = width x length #Perimeter of a rectangle = 2 x [length + width# width_input = float (input("\nPlease enter width: ")) length_input = float (input("Please enter length: ")) areaofRectangle = width_input * length_input perimeterofRectangle = 2 * (width_input * length_input) print ("\n...
442
151
# # Copyright (c) 2013-2020 Contributors to the Eclipse Foundation # # See the NOTICE file distributed with this work for additional information regarding copyright # ownership. All rights reserved. This program and the accompanying materials are made available # under the terms of the Apache License, Version 2.0 whic...
2,324
621
import requests from libcellml import * import lxml.etree as ET # pre-generated model recipe in JSON format model_recipe = [ { "med_fma": "http://purl.obolibrary.org/obo/FMA_84666", "med_pr": "http://purl.obolibrary.org/obo/PR_P26433", "med_pr_text": "sodium/hydrogen exchanger 3 (rat)", ...
33,084
12,397
from typing import List import requests from pathlib import Path from datetime import date, datetime from bs4 import BeautifulSoup from helper.classes import Channel, Program from helper.utils import get_channel_by_name, get_epg_datetime TIMEZONE_OFFSET = "+0800" PROGRAM_URL = "https://epg.beinsports.com/utctime_id.ph...
2,383
767
from django.shortcuts import render from .models import BlogPost from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .forms import BlogForm from django.contrib.auth.decorators import login_required from .auth import check_blog_author def index(request): blogs = BlogPost.obje...
1,608
492
import sys import site import os
34
11
class DNASuitEdge: COMPONENT_CODE = 22 def __init__(self, startPoint, endPoint, zoneId): self.startPoint = startPoint self.endPoint = endPoint self.zoneId = zoneId def setStartPoint(self, startPoint): self.startPoint = startPoint def setEndPoint(self, endPoint): ...
410
132
#! /usr/bin/env python3 """Converts cpplint output to JUnit XML format.""" import argparse import collections import os import re import sys from typing import Dict, List from xml.etree import ElementTree from exitstatus import ExitStatus class CpplintError(object): def __init__(self, file: str, line: int, mes...
3,455
1,015