text
string
size
int64
token_count
int64
# -*- coding: utf-8 -*- """ A Probabiltics Context Free Grammer (PCFG) Parser using Python. This code implemented a weighted graph search @author: Zhang Long """ import codecs from collections import defaultdict import math f_grammer=".\\test\\08-grammar.txt" nonterm=[] preterm=defaultdict(list) gramm...
2,781
1,057
# spark-submit generator.py out 9 3 2 10 # imports import sys import random import numpy from pyspark import SparkContext from pyspark.mllib.random import RandomRDDs # constants MIN_MEAN_VALUE = 0 MAX_MEAN_VALUE = 100 STEPS = 0.1 # methods def point_values(means_value, normal_value, std, cluster, dimension): val...
2,876
939
#!/usr/bin/env python # # test tool for PostgreSQL Commitfest website # # written by: Andreas Scherbaum <ads@pgug.de> # import re import os import sys import logging import tempfile import atexit import shutil import time import subprocess from subprocess import Popen import socket import sqlite3 import datetime from ...
1,263
381
import random from fake_useragent import UserAgent agent_list = '''Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50 Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50 Mozilla/5.0 (com...
856
365
import numpy as np from collections import deque QLEN = 8 class Line(object): """ from #2.Tips and Tricks for the Project """ def __init__(self, yp=None, xp=None): self.ym_per_pix = yp self.xm_per_pix = xp # self.frame_shape = fs # was the line detected in the last iteration...
5,078
1,741
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import seaborn as sns import numpy as np import tensorflow as tf tf.enable_eager_execution() import tensorflow_probability as tfp from tensorflow_proba...
2,730
1,004
import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.transforms import LaplacianLambdaMax from torch_geometric.data import Data from .chebconvatt import ChebConvAtt class Spatial_Attention_layer(nn.Module): ''' compute spatial attention scores ''' def __init__(self, i...
10,625
3,840
""" File defining the classes Normalize and Standardize used respectively to normalize and standardize the data set. """ class Normalize(object): """ Data pre-processing class to normalize data so the values are in the range [new_min, new_max]. """ def __init__(self, min_, max_, new_min=0, new_max=1)...
1,596
467
from abc import ABC, abstractmethod, abstractproperty class AbstractPlugin(ABC): """Abstract interface for all persistence layer plugins. Expects the following to be defined by the subclass: - :attr:`type` (as a read-only property) - :func:`generate_user` - :func:`get_status` ...
5,522
1,360
# -*- coding: utf-8 -*- """ Autor: André Pacheco Email: pacheco.comp@gmail.com """ import sys sys.path.insert(0,'../../') # including the path to deep-tasks folder sys.path.insert(0,'../../my_models') # including the path to my_models folder from constants import RAUG_PATH sys.path.insert(0,RAUG_PATH) from raug.loade...
6,016
1,899
import random import string from itertools import repeat import time RANDOM_1KB = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(1000)) RANDOM_100MB = bytearray(''.join(list(repeat(RANDOM_1KB, 100 * 1024))), 'utf-8') NEWLINE = bytes("\n", 'UT...
1,673
592
import json from collections import namedtuple import aiohttp METHOD_GET = aiohttp.hdrs.METH_GET METHOD_DELETE = aiohttp.hdrs.METH_DELETE METHOD_POST = aiohttp.hdrs.METH_POST METHOD_PUT = aiohttp.hdrs.METH_PUT METHOD_PATCH = aiohttp.hdrs.METH_PATCH CONTENT_TYPE = aiohttp.hdrs.CONTENT_TYPE JSON_TYPE = 'application/jso...
5,338
1,557
def f(): return True and not False<caret>
45
15
# -*- coding: utf-8 -*- """ Created on Sun Dec 9 23:12:30 2018 @author: Andrej Leban """ import itertools as it import functools as ft import collections as coll import sortedcontainers as sc from blist import blist import re import numpy as np import scipy.signal import scipy.sparse import mat...
7,071
2,887
# distutils: language = c++ # cython: language_level=3 # ---------- # RadarSimPy - A Radar Simulator Built with Python # Copyright (C) 2018 - PRESENT Zhengyu Peng # E-mail: zpeng.me@gmail.com # Website: https://zpeng.me # ` ` # -:. -#: # -//:. -###: # -////:. ...
808
341
from setuptools import setup # Used in pypi.org as the README description of your package with open("README.md", 'r') as f: long_description = f.read() # Remove this whole block from here... setup( name='python-sample-app', version='1.0', description='python-sample-app is a starter templat...
1,542
443
import sys import re import spotipy import spotipy.util as util ''' shows the albums and tracks for a given artist. ''' def get_artist_urn(name): results = sp.search(q='artist:' + name, type='artist') items = results['artists']['items'] if len(items) > 0: return items[0]['uri'] else: r...
2,519
729
# Print some simple information using the WScript.Network object. import sys from win32com.client.gencache import EnsureDispatch ob = EnsureDispatch('WScript.Network') # For the sake of ensuring the correct module is used... mod = sys.modules[ob.__module__] print "The module hosting the object is", mod # Now use the...
466
134
import BOMFinder.UI.UI as UI def to_prompt_sequence(part): prompt_sequence = [] for key, value in part.properties.items(): if isinstance(key, str): if isinstance(value, str): prompt_sequence.append(UI.ValuePrompt(key)) elif isinstance(value, list): ...
974
279
import dash_bootstrap_components as dbc from dash import dcc import plotly.graph_objects as go import iris query = ("""SELECT location, CAST(total_cases AS int) as total_cases, CAST(total_deaths as int) as total_deaths, CAST(total_vaccinations AS int) as total_vaccinations FROM Data.Covid19 WHERE ...
934
316
# # This source file is part of the EdgeDB open source project. # # Copyright 2016-present MagicStack Inc. and the EdgeDB authors. # # 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...
13,573
3,951
# -*- coding: utf-8 -*- from TopCmds import * import quality_check import data_management as dat Qualitytest = quality_check.Qualitytest left_boundary=float(dat.get_globalParameter("left_boundary")) right_boundary=float(dat.get_globalParameter("right_boundary")) def Check_180turn(leftboundary,rightboundary):...
2,295
804
# Generated by Django 3.2.4 on 2021-11-02 08:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_rename_on_authtoggle_protected'), ] operations = [ migrations.RenameField( model_name='authtoggle', old_nam...
389
134
import os import pickle import requests from bs4 import BeautifulSoup import re import prettytable as pt from selenium import webdriver from selenium.webdriver.chrome.options import Options import warnings from colorama import init, Fore, Back, Style warnings.filterwarnings("ignore") import time chrome_options=Options(...
6,509
2,825
import time from queue import Queue, Full, Empty from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor from concurrent.futures.process import _get_chunks, _process_chunk from functools import partial import sys import contextlib import threading import itertools class StreamExecutor(Executo...
6,161
1,409
#Copyright (C) 2021 Fanwei Kong, Shawn C. Shadden, University of California, Berkeley #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 req...
29,581
9,895
from .defines import MsgLv, UnknownFieldValue, ValidateResult, get_msg_level from .validators import SpecValidator def _wrap_error_with_field_info(failure): if get_msg_level() == MsgLv.VAGUE: return RuntimeError(f'field: {failure.field} not well-formatted') if isinstance(failure.value, UnknownFieldVal...
2,455
759
import sys __all__ = ['IntegerTypes', 'StringTypes'] if sys.version_info < (3,): IntegerTypes = (int, long) StringTypes = (str, unicode) long = long import __builtin__ as builtins else: IntegerTypes = (int,) StringTypes = (str,) long = int import builtins
290
97
from ..factory import Type class secretChat(Type): id = None # type: "int32" user_id = None # type: "int32" state = None # type: "SecretChatState" is_outbound = None # type: "Bool" ttl = None # type: "int32" key_hash = None # type: "bytes" layer = None # type: "int32"
285
120
import PegandoVariavel as v print(v.get_Pessoas()) print() for d in v.get_Pessoas(): print(d)
100
44
import click from Crypto.Cipher import AES import base64 from hashlib import md5 import warnings import requests_cache import requests import logging import subprocess import tempfile from anime_downloader.sites import get_anime_class import util @click.command() @click.argument('name') @click.option('-e', '--ep', d...
2,689
970
from __future__ import unicode_literals from django.db import models class Document(models.Model): file_name = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self...
333
103
import abc from collections import OrderedDict from .constants import RESULT_KEY_MAP class ResultMessageBase(abc.ABC): """ Result message base class. """ @abc.abstractmethod def get_content(self, custom_data=None): """ Get message content. Args: custom_data ...
3,106
871
# coding: utf-8 from nltk.corpus import wordnet as wn all_synsets = set() for word in wn.words(): for synset in wn.synsets(word): all_synsets.add(synset) with open("wordnet_synset_definition.txt", "wb+") as fp: for synset in all_synsets: print >> fp, "%s\t%s" % ( synset.name()...
377
136
n=1 def f(x): print(n) f(0)
32
22
"""Main module.""" from sqlalchemy import create_engine import pandas as pd import collections import logging import re from pprint import pprint from typing import Sequence from opentelemetry.metrics import Counter, Metric from opentelemetry.sdk.metrics.export import ( MetricRecord, MetricsExporter, Metr...
2,047
553
# Copyright (c) 2017 UFCG-LSD. # # 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,...
4,410
1,252
# creates a list and prints it days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] # traversing without an index for day in days: print(day) # traversing with an index for i in range(len(days)): print(f"Day {i} is {days[i]}") days[1] = "Lunes" print("Day[1] is now ...
362
142
try: import tensorflow except ModuleNotFoundError: pkg_name = 'tensorflow' import os import sys import subprocess from cellacdc import myutils cancel = myutils.install_package_msg(pkg_name) if cancel: raise ModuleNotFoundError( f'User aborted {pkg_name} installation' ...
826
262
import aioredis import trafaret as t import yaml from aiohttp import web CONFIG_TRAFARET = t.Dict( { t.Key('redis'): t.Dict( { 'port': t.Int(), 'host': t.String(), 'db': t.Int(), 'minsize': t.Int(), 'maxsize': t.In...
1,290
470
from anonymizers.base_anonymizer import Anonymizer class LocationAnonymizer(Anonymizer): anonymization_type = "location" location_prepositions = ["in", "at"] def __init__(self): self.initialize_spacy_model() def is_location(self, index: int) -> bool: if self.parsed_user_input[index ...
1,667
507
from pymongo import MongoClient import json class InitData: def __init__(self): self.client = MongoClient('localhost', 27017, w='majority') self.db = self.client.mongo_bank self.accounts = self.db.accounts # drop data from accounts collection every time to start from a clean slate ...
5,838
1,779
### tensorflow==2.3.1 import tensorflow as tf # Float16 Quantization - Input/Output=float32 height = 384 width = 384 converter = tf.lite.TFLiteConverter.from_saved_model('saved_model') converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.float16] tflite_model = converter.c...
532
200
import os from experiments.file_naming.single_target_classifier_indicator import SingleTargetClassifierIndicator from project_info import project_dir def get_single_target_tree_rule_dir() -> str: mcars_dir: str = os.path.join(project_dir, 'models', ...
2,598
864
import ast.value import ast.qualifier import ast.mixins.node import ast.mixins.typed import ast.mixins.qualified class LValueExpression(ast.mixins.node.Node, ast.mixins.typed.Typed, ast.mixins.qualified.Qualified): def __init__(self): super().__init__() self.__value: ast.value.Value or None = No...
1,291
392
import importlib def _declare_backend(backend_path): backend_path = backend_path.split('.') backend_module_name = '.'.join(backend_path[:-1]) class_name = backend_path[-1] def backend(*args, headers={}, from_address=None, **kwargs): def _backend(): backend_module = importlib.import...
911
267
from database import Base from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime, Float from sqlalchemy.types import DateTime from flask import Flask, request, jsonify, make_response from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = ...
795
285
##################################### ##### Class to Query Census API ##### ##################################### import requests import json import pandas as pd import datascience as ds from .utils import * class CensusQuery: """Object to query US Census API""" _url_endings = { "acs5": "acs/acs5", "acs1": "ac...
4,131
1,478
import json from pathlib import Path def load_json(path: Path): data = None with open(path.absolute(), encoding='utf-8') as f: data = json.load(f) return data def format_mock_url(url: str, mock_value: str): return f'{url}/{mock_value}'
264
92
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="pyaww", version="0.0.3", author="ammarsys", author_email="amarftw1@gmail.com", description="A simple API wrapper around the pythonanywhere's API.", long_description=l...
999
336
import os, sys, re, json, random, importlib import numpy as np import pandas as pd from collections import OrderedDict from tqdm import tqdm import matplotlib import matplotlib.pyplot as plt import seaborn as sns import logomaker as lm from venn import venn from venn import generate_petal_labels, draw_venn from scipy.s...
24,831
8,424
#!usr/bin/python # -*- coding: utf-8 -*- ' an im_send project ' # __author__ 'ZHU JIAMIN' import sys import mysql.connector #python3不支持 import requests import json from os import path, access, R_OK # W_OK for write permission. #python2默认编码ascii 使用此方法改为utf8 reload(sys) sys.setdefaultencoding('utf8') # 流程 # 1....
4,478
2,330
from flask_script import Manager, Server from flask_migrate import Migrate, MigrateCommand from app import create_app, db from app.models import User, Article, Category, Comment, Quote app = create_app('development') manager = Manager(app) migrate= Migrate(app, db) manager.add_command('db', MigrateCommand) manager...
556
174
from distutils.core import setup import setuptools setup( name = 'mindset', packages = ['mindset'], version = '0.0.1', description = 'Mindset', author = '', url = 'https://github.com/alvations/mindset', keywords = [], classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approv...
389
131
#!/usr/bin/env python import rospy from std_msgs.msg import String from peyetribe import EyeTribe import time from cir_user.srv import UserAction, UserActionResponse TH1 = 1280*(1.0/3) TH2 = 1280*(2.0/3) IP = "192.168.101.72" class CameraUserServer: def __init__(self): rospy.init_node("talker") ...
2,082
697
import requests cookie = {'_ga':'GA1.2.1373385590.1498799275','_gid':'GA1.2.867459789.1498799275','_gat':'1','PHPSESSID':'1kr76vh1164sbgeflnngimi321'} url = 'http://captcha.ringzer0team.com:7421' headers = {'Authorization':'Basic Y2FwdGNoYTpRSmM5VTZ3eEQ0U0ZUMHU='} for i in range(1000): # get captacha r = requests.g...
833
386
import sys from antlr4 import * from ChatParser import ChatParser from ChatListener import ChatListener from antlr4.error.ErrorListener import * import io class ChatErrorListener(ErrorListener): def __init__(self, output): self.output = output self._symbol = '' def syntaxError(sel...
685
180
from django.urls import path from . import views urlpatterns = [ path("", views.home, name="home"), path("faq/", views.faq, name="faq"), path("plagiarism_policy/", views.plagiarism_policy, name="plagiarism_policy"), path("privacy_policy/", views.privacy_policy, name="privacy_policy"), path...
568
204
import wx from ogreyPopupMenu import * from ogreyOgreManagers import * from ogreyTool import * class Singleton(type): def __init__(self, *args): type.__init__(self, *args) self._instances = {} def __call__(self, *args): if not args in self._instances: self._instan...
13,750
4,408
import nltk nltk.download('stopwords') from nltk.corpus import stopwords stopwords=stopwords.words('german') nltk.download('punkt') from nltk.stem.snowball import SnowballStemmer import spacy from spacy_iwnlp import spaCyIWNLP nlp=spacy.load('de') #You need to download the 'de'-module in advance. This will be done auto...
2,366
794
# # 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 # ...
2,960
829
import os from datetime import datetime directory = "../runs" current = os.path.join(directory, ".current") class Run: def __init__(self, runName): run = os.path.join(directory, runName) self.model = os.path.join(run, "model.h5") self.log = os.path.join(run, "log.csv") self.accurac...
858
306
# coding:utf-8 from flask import Flask, render_template, request # 创建flask应用 app = Flask(__name__) # 视图函数 @app.route('/xss', methods=['POST', 'GET']) def xss(): text = "" if request.method == 'POST': text = request.form.get('text') return render_template('xss.html', text=text) # 启动flas应用 if ...
415
174
# -*- coding: utf-8 -*- # Memory addresses ADDRESS_R15 = 0x400f ADDRESS_ADC_POWER = 0x4062 ADDRESS_ADC_BATTERY = 0x4063 ADDRESS_LEVELA = 0x4064 ADDRESS_LEVELB = 0x4065 ADDRESS_PUSH_BUTTON = 0x4068 ADDRESS_COMMAND_1 = 0x4070 ADDRESS_COMMAND_2 = 0x4071 ADDRESS_MA_MIN_VALUE = 0x4086 ADDRESS_MA_MAX_VALUE = 0x4087 ADDRESS_...
1,543
947
import os import csv from pyparsing import Word, alphas, Combine, nums, Regex, ParseException from collections import OrderedDict class BlueGeneLog(object): def __init__(self, dataset): self.dataset = dataset self.bluegenelog_grammar = self.__get_bluegenelog_grammar() @staticmethod def __...
3,359
1,098
from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.http import Http404, HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from wagtailcomments import registry from wagtailcomments.models impo...
2,106
571
from typing import List, Optional from open_mafia_engine.core.all import ( Ability, Action, Actor, ATBase, CancelAction, EPreAction, Game, GameObject, handler, ) from .auxiliary import TempPhaseAux class RoleBlockerAux(TempPhaseAux): """Aux object that blocks actions made by ...
2,468
722
import os import io import math import requests from datetime import datetime, date, timedelta import pandas as pd from covid_data.models import State, County, Outbreak, OutbreakCumulative from covid_data.utilities import get_datetime_from_str, api_request_from_str # Some functions only work for specific region types ...
6,836
1,982
import bs4 with open("example.html") as f: # 텍스트 파일로 부터 BeautifulSoup 객체 생성 soup = bs4.BeautifulSoup(f.read(), "lxml") print(type(soup)) # <class 'bs4.BeautifulSoup'> # id가 author인 태그 리스트 조회 elems = soup.select("#author") print(type(elems)) # <class 'list'> print(type(elems[0])) # <class 'bs4.element.Tag'...
483
303
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 13 11:34:33 2019 @author: manninan """
109
60
r""" .. include::../README.md :start-line: 1 """
55
28
from utils import * import torch import sys import numpy as np import time import torchvision from torch.autograd import Variable import torchvision.transforms as transforms import torchvision.datasets as datasets def validate_pgd(val_loader, model, criterion, K, step, configs, logger, save_image=False, HE=False): ...
8,548
2,949
#!/usr/bin/env python3 """This is a script for making graphs of constant rank instances with varying rank Usage: <script> <src_dir> <dest_dir> Where <src_dir> is a directory with subfolders ``` constant02 constant04 ... ``` And each subfolder has a file `data.csv` with the CXY run in it. This combines the graphs o...
2,493
912
# coding: utf-8 from PIL import Image, ImageFont from handright import Template, handwrite text = """ 这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。 这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是...
1,829
1,624
from django.conf import settings from hawkrest import HawkAuthentication from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .constants import ( BARRIER_PENDING, BARRIER_SOURCE, BarrierStatus, BARRIER_CHA...
4,627
1,584
import numpy as np from numexpr_kernel import numexpr_kernel from numba_kernel import numba_kernel N = 10000 x = np.random.rand(N) y = np.random.rand(N) z = np.random.rand(N) tau = np.random.rand(N) r1 = numexpr_kernel(x, y, z, tau) r1 = numexpr_kernel(x, y, z, tau) r2 = np.zeros(N, dtype=float) numba_kernel(x, y, z,...
367
174
# http://www.codewars.com/kata/55f73f66d160f1f1db000059/ def combine_names(first_name, last_name): return "{0} {1}".format(first_name, last_name)
151
75
"""project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based...
1,125
355
""" This module give the classification results for test data using SVM with RBF kernel. Email: harikrishnannb07@gmail.com Dtd: 2 - August - 2020 Parameters ---------- classification_type : string DESCRIPTION - classification_type == "binary_class" loads binary classification artificial data. class...
3,425
1,218
class DefaultPreferences(type): """The type for Default Preferences that cannot be modified""" def __setattr__(cls, key, value): if key == "defaults": raise AttributeError("Cannot override defaults") else: return type.__setattr__(cls, key, value) def __delattr__(c...
2,115
579
# User welcome extension coded by github u/tandemdude # https://github.com/tandemdude import discord import json from discord.ext import commands class Welcome(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_member_join(self, member): with open('config.json') as ...
1,224
483
# ------------------------------------------ # # Program created by Maksim Kumundzhiev # # # email: kumundzhievmaxim@gmail.com # github: https://github.com/KumundzhievMaxim # ------------------------------------------- BATCH_SIZE = 10 IMG_SIZE = (160, 160) MODEL_PATH = 'checkpoints/model'
293
103
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from conditional import db from conditional.models import models, old_models as zoo import flask_migrate # pylint: skip-file old_engine = None zoo_session = None # Takes in param of SqlAlchemy Database Connection String def...
10,247
3,258
import numpy as np def cross_entropy_error(y, t): delta = 1e-7 # to avoid log(0) return - np.sum(t * np.log(y + delta)) if __name__ == '__main__': t = np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]) y1 = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]) y2 = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) y3 = n...
789
405
from tool.runners.python import SubmissionPy class DavidSubmission(SubmissionPy): def bucket_key(self, w, i): return w[:i] + w[i+1:] def run(self, s): words = s.split("\n") n = len(words[0]) buckets = [set() for i in range(n)] for w in words: for i in range(...
466
153
# Pro-Football-Reference.com # TEAMS import re, os import uuid import json from datetime import datetime, date, time from bs4 import BeautifulSoup import bs4 from Constants import * from PathUtils import * from PluginSupport import * from Serialization import * from StringUtils import * import ProFoo...
3,653
1,544
import torch import numpy as np import time import datetime import random from Kfold import KFold from split_data import DataManager from transformers import BertTokenizer from transformers import BertTokenizer from torch.utils.data import TensorDataset, random_split from torch.utils.data import DataLoader, RandomSamp...
9,565
2,673
#!/usr/bin/env python # pylint: disable=invalid-name """ Web-based proxy to a Kerberos KDC for Webathena. """ import base64 import json import os import select import socket import dns.resolver from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1.error im...
7,957
2,477
# -*- coding: utf8 -*- # # DB migration 001 by 2017-11-03 # # New statistics for subvolume - root diff in blocks / bytes # __author__ = 'sergey' __NUMBER__ = 20171103001 def run(manager): """ :param manager: Database manager :type manager: dedupsqlfs.db.sqlite.manager.DbManager|dedupsqlfs.db.mysql.manage...
1,980
649
import pytest @pytest.mark.parametrize("cli_options", [ ('-k', 'notestdeselect',), ]) def test_autoexecute_yml_keywords_skipped(testdir, cli_options): yml_file = testdir.makefile(".yml", """ --- markers: - marker1 - marker2 --- - provider: python type: assert expression: "1" """) assert yml_fi...
582
222
#1 num = int(input("Enter a number : ")) largest_divisor = 0 #2 for i in range(2, num): #3 if num % i == 0: #4 largest_divisor = i #5 print("Largest divisor of {} is {}".format(num,largest_divisor))
224
95
# Description # 中文 # English # Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right) # offset >= 0 # the length of str >= 0 # Have you met this question in a real interview? # Example # Example 1: # Input: str="abcdefg", offset = 3 # Output:...
1,532
528
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import ipdb import time # Clustering penalties class ClusterLoss(torch.nn.Module): """ Cluster loss comes from the SuBiC paper and consists of two losses. First is the Mean Entropy Loss which makes the output to be clos...
5,854
1,861
import solana_rpc as rpc def get_apr_from_rewards(rewards_data): result = [] if rewards_data is not None: if 'epochRewards' in rewards_data: epoch_rewards = rewards_data['epochRewards'] for reward in epoch_rewards: result.append({ 'percent_c...
1,134
401
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.core.urlresolvers import reverse from rest_framework import serializers from ralph_assets.models_dc_assets import ( DataCenter, ...
5,545
1,604
# -*- coding: utf-8 -*- import numpy as np import time from endochrone import Base from endochrone.classification import BinaryDecisionTree __author__ = "nickwood" __copyright__ = "nickwood" __license__ = "mit" class RandomForest(Base): def __init__(self, n_trees, sample_size=None, feat_per_tree=None, ...
2,163
722
BUCKET = "vcm-ml-experiments" PROJECT = "microphysics-emulation"
65
29
class ObjectProperties: def __init__(self, object_id, extra_data=None, ticket_type=None, quantity=None): if extra_data: self.extraData = extra_data self.objectId = object_id if ticket_type: self.ticketType = ticket_type if quantity: self.quantity =...
330
91
import re class Solution: def helper(self, expression: str) -> List[str]: s = re.search("\{([^}{]+)\}", expression) if not s: return {expression} g = s.group(1) result = set() for c in g.split(','): result |= self.helper(expression.replace('{' + g + '}', c, ...
463
148
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) == 0: return 0 m = 1 for _ in range(len(s)): i = 0 S = set() for x in range(_, len(s)): if s[x] not in S: S.add(s...
455
137