text
string
size
int64
token_count
int64
# Copyright 2019 Ali (@bincyber) # # 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, ...
5,343
1,810
import matplotlib.pyplot as plt plt.plot([1,23,2,4]) plt.ylabel('some numbers') plt.show()
93
42
# # PySNMP MIB module HP-ICF-IP-ROUTING (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-IP-ROUTING # Produced by pysmi-0.3.4 at Mon Apr 29 19:21:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
62,779
30,979
# ------------------------------------------------------------------------------ # CodeHawk Binary Analyzer # Author: Henny Sipma # ------------------------------------------------------------------------------ # The MIT License (MIT) # # Copyright (c) 2021-2022 Aarno Labs LLC # # Permission is hereby granted, free of ...
13,261
4,373
import unittest from selenium import webdriver #submodulo para usar el dropdown from selenium.webdriver.support.ui import Select class LanguageOptions(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path = r'./chromedriver') driver = self.driver driver.implicitly_wait(30) driv...
1,810
615
# -*- coding: utf-8 -*- from unittest.mock import patch import opentracing from chaoslib.types import Configuration from chaostracing.control import cleanup_control, configure_control def test_create_noop_tracer(configuration: Configuration): assert opentracing.is_global_tracer_registered() is False tracer ...
819
260
import tensorflow as tf import flags logging = tf.logging BASIC = "basic" CUDNN = "cudnn" BLOCK = "block" def get_config(): """Get model config.""" config = None if flags.FLAGS.model == "small": config = SmallConfig() elif flags.FLAGS.model == "medium": config = MediumConfig() elif flags.FLAGS.mode...
1,870
845
import logging import time import requests import influxdb from nrf24 import NRF24 log = logging.getLogger("ledmatrix") class RF24_Sensor(object): def __init__(self, dbclient): # Set up the RF24 pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]] ...
1,752
735
from bs4 import BeautifulSoup, SoupStrainer import tldextract import json import re from urlparse import urlparse, urlunparse import requests ARCHIVE_WEB_URL = 'http://web.archive.org/web' ARCHIVE_CDX_URL = 'http://web.archive.org/cdx/search/cdx' MAX_EXTRACTION_LEVEL = 5 class Spider: def __init__(self, extrac...
4,465
1,275
def test_sm_b2b_center_include_eic_yestoday(app): app.testhelpersm.refresh_page() app.session.open_SM_page(app.smPurchases) app.session.ensure_login_sm(app.username, app.password) app.session.ensure_login_sm(app.username, app.password) app.session.open_SM_page(app.smPurchases) app.testHelperS...
9,145
3,630
from . import submodule # noqa: F401
38
16
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17/2/17 下午2:39 # @Author : Jason # @File : exceptions.py class InvalidGoodUrlException(Exception): pass class InvalidCategoryUrlException(Exception): pass class DocumentNotFoundException(Exception): pass class InvalidParamException(E...
340
117
# # Copyright (c) 2019 Jonathan McGee <broken.source@etherealwake.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS I...
9,985
3,365
#!/usr/bin/env python # # self-test: socat -x pty,link=/tmp/com1,raw,echo=0 pty,link=/tmp/com2,raw,echo=0 from math import ceil from m3_common import printing_sleep as sleep import socket import sys import os import mimetypes import queue import logging logging.basicConfig(level=logging.INFO, format="%(message)s") log...
7,094
2,680
"""Functions related to certificates""" import json import logging import uuid from datetime import datetime, timedelta from enum import Enum from pathlib import Path import attr from cryptography import x509 from cryptography.hazmat.backends import default_backend logger = logging.getLogger(__name__) class CertErr...
7,889
2,371
########################################################################## # Copyright (c) 2018-2019 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 #...
4,456
1,274
# coding: utf-8 """ Blog Post endpoints \"Use these endpoints for interacting with Blog Posts, Blog Authors, and Blog Tags\" # noqa: E501 The version of the OpenAPI document: v3 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from hubspot.cms.blo...
85,636
27,742
import pandas as pd import os import torch import numpy as np import pickle import dill from settings import settings from model import BatchProgramCC from torch.autograd import Variable from gensim.models.word2vec import Word2Vec from sklearn.metrics import precision_recall_fscore_support categories = 5 HIDDEN_DIM =...
4,743
1,664
def поздороваться(): print("Привет, программист!") поздороваться() поздороваться() поздороваться() поздороваться() поздороваться() def поздравить_с(как, чем): print(как + " поздравляю с " + чем + "!") поздравить_с("непременно", "новым годом") поздороваться() поздравить_с("вяло", "днём тунеядца и разгильдяя"...
653
309
import matplotlib.pyplot as plt import pickle import numpy as np import argparse from whatthefood.data.xml_to_obj import parse_file from whatthefood.data.obj_to_nparray import get_objects_from_output, load_input_image from whatthefood.data.preprocessing import ScalePreprocessor from whatthefood.classification.utils im...
3,336
1,116
from random import randint d3 = 0 d4 = 0 d5 = 0 d6 = 0 d7 = 0 d8 = 0 d9p = 0 nm = 100000 def roll(): return randint(1,10); def count(): num = 0 n2 = 0; while(num<3): n2+=1 r = roll() if r == 10: pass else: num+=1 return n2 def avg_win_day(): return (d3*3+d4*4+d5*5+d6*6+d7*7+d8*8+d9p*9)/nm te...
855
532
import argparse # Essentials import os, sys, glob import pandas as pd import numpy as np import copy import json # Stats import scipy as sp from scipy import stats # Sklearn from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.model_selection import KFold, GridSearchCV,...
12,320
4,402
from threading import Thread class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): """ Performs the creation of an object of type ThreadWithReturnValue :param group: group of thread :param target: ta...
941
248
import speech_recognition as sr from gtts import gTTS import os import threading import time heard = False control = False r = sr.Recognizer() audio = "" def secondary_detect(): global heard, control, audio, r while True: s = "" if control==True: try: s = r.recognize_google(audio).lower() except sr.U...
1,783
681
from __future__ import division from model2 import RBM2 import numpy as np n = 15 samples = 400 X = np.zeros((samples, n, 2), dtype=np.int32) for i in xrange(samples): m = np.random.randint(1, n//2) j1 = np.random.choice(n, size=(m), replace=False) j2 = np.random.choice(n, size=(m), replace=False) X...
838
441
# Runs on all swiss roll datasets, quickly. Experiment(description='Swiss roll normalized slow', data_dir='../data/swiss-roll2/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=3, sd=4, ...
629
196
# encoding=utf-8 import jieba.posseg as psg # string="来到北京清华大学" string ="""  4月12日0—24时,31个省(自治区、直辖市)和新疆生产建设兵团报告新增确诊病例108例,其中98例为境外输入病例,10例为本土病例(黑龙江7例,广东3例);新增死亡病例2例(湖北2例);新增疑似病例6例,均为境外输入病例(黑龙江4例,上海2例)。   当日新增治愈出院病例88例,解除医学观察的密切接触者1092人,重症病例减少18例。   境外输入现有确诊病例867例(含重症病例38例),现有疑似病例72例。累计确诊病例1378例,累计治愈出院病例511例,无死亡病例。 ...
2,633
3,134
from __future__ import unicode_literals import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import AzureProvider LOGIN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0' GRAPH_URL = 'https://graph.micr...
2,120
739
# -*- coding: ISO-8859-1 -*- import wx from meerk40t.core.units import Length from meerk40t.gui.icons import icons8_administrative_tools_50 from meerk40t.gui.mwindow import MWindow from meerk40t.kernel import signal_listener _ = wx.GetTranslation FIX_SPEEDS_RATIO = 0.9195 class ConfigurationUsb(wx.Panel): def...
44,887
16,063
import tools from multiprocessing import SimpleQueue, Process import numpy as np __all__ = ['fast_multiply'] def get_b(i, level_to_nodes, max_level, b): indices = level_to_nodes[max_level][i].Indices start, end = indices[0], indices[-1] res = b[start:end + 1] return res def get_G(k, i, level_to_no...
2,686
1,095
import tornado.web import settings import views storage_router = tornado.web.Application([ (settings.ENDPOINTS["storage"], views.StorageHandler) ], debug=settings.DEBUG)
187
52
import torch import torch.utils.data as data import os import pickle import numpy as np import nltk from PIL import Image import os.path import random def load_dataset(N=30000, NP=1800): obstacles = np.zeros((N, 2800), dtype=np.float32) for i in range(0, N): temp = np.fromfile('../dataset2/obs_cloud/o...
449
175
import pymongo import json import urllib.request connection_string = 'mongodb://<USERNAME>:<PASSWORD>@cluster0-shard-00-00-pjgev.mongodb.net:27017,cluster0-shard-00-01-pjgev.mongodb.net:27017,cluster0-shard-00-02-pjgev.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true' clien...
2,885
1,048
"""The different phases of the data generation pipeline.""" from .phase1 import ( # noqa: F401 phase1, ) from .phase2 import ( # noqa: F401 phase2, ) from .phase3 import ( # noqa: F401 phase3, ) from .phase4 import ( # noqa: F401 phase4, ) from .phase5 import ( # noqa: F401 phase5, ) from .pha...
411
175
#!/usr/bin/env python #-*- encoding: UTF-8 -*- ############################################### # Todos los derechos reservados a: # # CreceLibre Consultores en Tecnologías Ltda. # # # # ©Milton Inostroza Aguilera # # minostro@minostro.com ...
4,458
1,534
from PyQt5 import QtCore, QtGui, QtWidgets, uic import qdarkgraystyle class Ui_AboutBoxForm(QtWidgets.QDialog): def __init__(self): super(Ui_AboutBoxForm, self).__init__() uic.loadUi('airodb_analyzer/designer/aboutBoxForm.ui', self) self.setStyleSheet(qdarkgraystyle.load_stylesheet()) ...
453
149
# -*- coding: utf-8 -*- import csv import json import datetime import urllib from collections import Counter import requests from bs4 import BeautifulSoup from .post import Post class TrashException(Exception): pass class AuthException(Exception): pass class LoginException(Exception): pass class ...
4,263
1,348
import numpy as np import pandas as pd def print_statistics(correct, confusion_m, total, confusion_m_flag): if confusion_m_flag == 0: accuracy = 100 * np.array(correct) / np.array(total) index = ['normal', 'untvbl obs', 'tvbl obs', 'crash'] columns = ['accuracy'] print('Accuracy of...
1,152
402
import asyncio from chaperone.cproc.subproc import SubProcess from chaperone.cutil.errors import ChProcessError class OneshotProcess(SubProcess): process_timeout = 60.0 # default for a oneshot is 90 seconds @asyncio.coroutine def process_started_co(self): result = yield from self.timed_wait...
1,185
341
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.security import check_password_hash, generate_password_hash from helpers import apology, login_required, lookup, usd # Configure appl...
7,994
2,319
# # PySNMP MIB module BLADETYPE6-NETWORK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLADETYPE6-NETWORK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:22:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
673,905
338,715
""" fnExchange is a scalable, open source API layer (also called an API "router") that provides a consistent proxy web interface for invoking various web APIs without the caller having to write separate, special-purpose code for each of them. fnExchange is packaged as a command line interface executable ``fnexchange``...
1,918
578
################################################################################ # Time SPK: Traction retard VSS1 VSS2 VSS1 ms 1 VSS2 ms 1 TC slip * time # the info for traction control says "slip% X 0.01s" # Retard 0.0 3.3 6.7 10.0 # slip x time 0.0 6.7 13.3 20.0 # settings were above 50.1 mph and 10% slip...
3,026
1,265
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class KeyValue(models.Model): key = models.CharField(max_length=128) value = models.TextField() ttl = models.DecimalField(max_digits=10, decimal_places=6) created_by = models.ForeignKey(User, related_...
869
292
import codecs import eyed3 import http.client import http.server import json import re from sys import exit import taglib import time import urllib.error import urllib.parse import urllib.request import webbrowser from util import log class Spotify: # Requires an OAuth token. def __init__(self, auth): ...
6,455
1,893
import math import unittest def calculate_sd(d): m = calculate_mean(d) v = sum([((i - m) ** 2) for i in d]) / len(d) return v ** 0.5 def calculate_mean(n): return sum(n)/len(n) def calculate_median(d): d.sort() n = len(d) if n % 2 == 0: m1 = d[n//2] m...
5,003
2,626
# Copyright (c) 2021 Food-X Technologies # # This file is part of foodx_devops_tools. # # You should have received a copy of the MIT License along with # foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>. """Configuration file path management.""" import logging import pathlib import typing fr...
6,173
1,792
from .base import load_excavators __all__ = ["load_excavators"]
65
26
from typing import List class Solution: def repeatedNTimes(self, nums: List[int]) -> int: for k in range(1, 4): for i in range(len(nums) - k): if nums[i] == nums[i + k]: return nums[i] return -1 s = Solution() print(s.repeatedNTimes([1, 2, 3, 3])) ...
414
179
import json from web3 import Web3, HTTPProvider, IPCProvider from web3.middleware import geth_poa_middleware import os from os.path import join, dirname from dotenv import load_dotenv load_dotenv(join(dirname(__file__), '.env')) if(os.environ.get("WEB3_USE_IPC") == False): web3 = Web3(HTTPProvider(os.environ.get(...
948
366
import fileinput import string import sys import os c_compiler = 'icc' c_link_flags = '-g -O1 -xT -march=core2 -mtune=core2 -align'# -strict-ansi' c_opt_flags = '-g -O3 -xT -march=core2 -mtune=core2 -funroll-loops -align'# -strict-ansi' fortran_compiler = 'ifort' fortran_link_flags = '-g -O1 -xT -march=core2 -mtune=co...
5,088
2,219
#! /usr/bin/env python3 import os,string,sys,types instructions={} inst_id=1 OpcodeWidth=25 Dnops={} DmanualIfields={} DmanualOpcodes={} DnfSpecials = {} Chip = 'chip' def get_inst_id(): global inst_id x = inst_id inst_id=inst_id+1 return x class Instruction: def __init__(self,Name): self...
42,079
15,653
from LSP.plugin.core.types import diff from LSP.plugin.core.types import DocumentSelector from LSP.plugin.core.typing import List from unittest.mock import MagicMock import sublime import unittest class TestDiff(unittest.TestCase): def test_add(self) -> None: added, removed = diff(("a", "b", "c"), ("a", ...
7,598
2,438
import subB.importA import importB my_local = 'ggg' print(subB.importA.foo) print(importB.flab)
97
42
import numpy as np import cv2 im = cv2.imread('py/shap.png') cv2.imshow('original image',im) cv2.waitKey() imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) cv2.imshow('gray image',imgray) cv2.waitKey() ret,thresh = cv2.threshold(imgray,80,255,1) cv2.imshow('thresh image',thresh) cv2.waitKey() image, contours, hierarchy...
1,242
545
from os import system , name def Run(Input): if name == "nt": # Windows Machine system('dir') else: # Linux/Unix Machine system('ls')
182
59
# Copyright 2019 The DMLab2D 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
5,840
1,809
# -*- coding: utf-8 -*- """ @author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/ """ #pandas_datareader is deprecated, use YahooGrabber #This is part of a k-th fold optimization tool #Import modules #import numpy as np #from pandas_datareader import data import pandas as pd import time as t ...
7,336
3,106
from __future__ import print_function import logging import sys import pip import os def install(package): try: pip.main(["install", package]) except Exception as ex: raise "Unable to install " + package + ex try: install("colorlog") import colorlog except Exception as ex: raise...
2,292
694
import copy import numpy as np import torch import torch.nn.functional as F from utils import ReplayPool from networks import Policy, StochasticPolicy, DoubleQFunc device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class OffPolicyAgent: def __init__(self, seed, state_dim, action_dim, ...
18,438
6,002
# Copyright (c) 2019 Agenium Scale # # 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, publish, distr...
33,002
11,329
from typing import Type from blessed import Terminal from pydantic import BaseModel from app import constants as const class HitBox(BaseModel): """A hitbox is any entity that provides some sort of interaction""" pos_x: int pos_y: int content: str time: int parent: Type def __lt__(self,...
1,160
383
from __future__ import print_function import sys import time import os.path as osp from PIL import Image import cv2 import numpy as np import random from collections import defaultdict from .Dataset import Dataset from ..utils.utils import measure_time from ..utils.re_ranking import re_ranking from ..utils.metric imp...
21,907
7,292
from aiautomation.log.abstract_log import AbstractLog from aiautomation.utils.log import get_logger ''' 写入控制台和文件的日志 ''' class SimpleLog(AbstractLog): def step_log_before(self, oper_type, oper_name, oper_id, parent_oper_id=None, *key, **kwargs): if oper_type == AbstractLog.STEP_TYPE_COMPONENT: ...
1,793
783
PATH = '../input/google-quest-challenge/' #BERT_PRETRAINED_MODEL = 'bert-base-cased' BERT_PRETRAINED_MODEL = 'bert-base-uncased' BERT_TOKENIZER_PATH = '../input/transformers/' + BERT_PRETRAINED_MODEL + '/tokenizer/' BERT_PRETRAINED_MODEL_PATH = '../input/transformers/' + BERT_PRETRAINED_MODEL + '/pretrained_mod...
326
145
from girder.models.assetstore import Assetstore from girder.models.file import File from girder.models.folder import Folder from girder.models.item import Item from girder.models.upload import Upload from girder.models.user import User from dive_server.utils import get_annotation_csv_generator from dive_utils.constant...
1,875
532
# Easy # https://leetcode.com/problems/reverse-vowels-of-a-string/ # Time Complexity: O(N) # Space Complexity: O(N) class Solution: def reverseVowels(self, s: str) -> str: stack = [] for letter in s: if letter in "aeiouAEIOU": stack.append(letter) word = "" ...
504
153
def Awesome_face(thoughts, eyes, eye, tongue): return f""" {thoughts} {thoughts} \#[/[#:xxxxxx:#[/[\\x [/\\ &3N W3& \\/[x [[x\@W W\@x[[\\ /#&N N_# /#\@ \@#/x ...
1,360
607
# -*- coding: utf-8 -*- try: from pygarlic_validator.validator import validators, checkers, errors from pygarlic_validator.__version__ import __version__ except ImportError: from .validator import validators, checkers, errors from .__version__ import __version__
280
84
import functools import copy from dataclasses import dataclass from marshmallow import Schema from typing import ( Optional, MutableMapping, Any, Union, Callable, Tuple, Dict, AsyncGenerator, Generator, Sequence, ) from spantools import MimeType, convert_params_headers, MimeType...
13,460
3,816
import test_classification import numpy as np from SimpleGP import SparseGPPG, SparseArray from SimpleGP.gppg import PGCl import os cl = test_classification.cl X = test_classification.X def test_gppg(): x = map(lambda x: SparseArray.fromlist(X[x]), range(X.shape[0])) fname = 'gppg.npy.gz' gp = SparseGPPG...
3,240
1,269
from shift_detector.precalculations.text_embedding_precalculation import TextEmbeddingPrecalculation from shift_detector.precalculations.store import Store from shift_detector.precalculations.precalculation import Precalculation from datawig.utils import random_split import numpy as np from numpy.linalg import norm c...
1,911
618
""" """ import archon.facade as facade import archon.broker as broker import archon.exchange.exchanges as exc import archon.model.models as models from archon.util import * from pymongo import MongoClient import time import datetime import math afacade = facade.Facade() broker.setClientsFromFile(afacade) a = brok...
694
276
# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/topics/items.html from scrapy.item import Item, Field class PnasItem(Item): # define the fields for your item here like: category = Field() category_minor = Field() authors = Field() title = Field() ...
505
156
import subprocess from argparse import ArgumentParser def run(src_dir, fast=False): print(f'Formatting all files under {src_dir} using black.') cmd = ['black'] if fast: cmd.append('--fast') cmd.append(src_dir) subprocess.run(cmd) if __name__ == '__main__': parser = ArgumentParser(des...
792
232
import socket import datetime import os import better_exceptions from from_parlai.eval_model import eval_model from from_parlai.eval_model import setup_args as eval_setupargs better_exceptions.hook() __PATH__ = os.path.abspath(os.path.dirname(__file__)) def setup_args(current_time): parser = eval_setupargs() ...
873
289
from ares.phenom.Tanh21cm import Tanh21cm from ares.phenom.OpticalDepth import Madau1995 from ares.phenom.Gaussian21cm import Gaussian21cm from ares.phenom.DustCorrection import DustCorrection from ares.phenom.Parametric21cm import Parametric21cm from ares.phenom.ParameterizedQuantity import ParameterizedQuantity
315
114
import itertools import contextlib import time import numbers import numpy as np @contextlib.contextmanager def timeit(fmt=None): if fmt is None: fmt = "{0:.2g} sec" t0 = time.time() yield t1 = time.time() print(fmt.format(t1 - t0)) def create_rng(seed): """Turn seed into a np.random...
5,408
1,765
import FWCore.ParameterSet.Config as cms from RecoEgamma.EgammaElectronProducers.gsfElectrons_cfi import * lowPtGsfElectrons = ecalDrivenGsfElectrons.clone( gsfElectronCoresTag = "lowPtGsfElectronCores", gedElectronMode = True, ) from Configuration.Eras.Modifier_fastSim_cff import fastSim fastSim.toModify(lo...
622
275
def hand_total(hand): total = 0 # Count number of aces and deal with how to apply them at the end aces = 0 for card in hand: if card in ['J', 'Q', 'K']: total += 10 elif card == 'A': aces += 1 else: # Convert the number on card to int's ...
1,767
603
# -*- python -*- # -*- coding: utf-8 -*- # # michael a.g. aïvázis <michael.aivazis@para-sim.com> # # (c) 2013-2021 parasim inc # (c) 2010-2021 california institute of technology # all rights reserved # # externals import math # the package import altar # declaration class Gaussian(altar.models.bayesian, family="alt...
6,281
1,908
# -*- coding: utf-8 -*- #naverFuncs.py import requests import urllib.request from bs4 import BeautifulSoup import re import json if __name__ != '__main__': from . import config #-------------------------------------------------------------------------- # 실시간 인기 검색어 cnt개 반환 #--------------------------------------...
2,486
846
#!/usr/bin/python import argparse import multiprocessing from distutils.util import strtobool def configure_argparse(): ap = argparse.ArgumentParser() ap.add_argument("-p", "--password", required=True, type=str, help="database password") ap.add_argument("-u", "--user", required=True, t...
2,922
868
from sgmllib import SGMLParser import htmlentitydefs class BaseHTMLProcessor(SGMLParser): def reset(self): # extend (called by SGMLParser.__init__) self.pieces = [] self.buffer = "" self.parents = [] SGMLParser.reset(self) def unknown_starttag(self, tag, attrs): strattrs = "".join([' %s="%s"' % (key,...
1,893
841
if TYPE_CHECKING: pass class UIntBase(serializable.SerializableMixin): _data = bytearray() _hash: int = 0 def __init__(self, num_bytes: int, data: Union[bytes, bytearray] = None) -> None: super(UIntBase, self).__init__() if data is None: self._data = bytearray(num_bytes) else: if isinstance(data, bytes)...
2,708
1,058
from pathlib import Path PROJECT_DIR = Path(__file__).resolve().parent.parent DATA_DIR = PROJECT_DIR.joinpath("data") DATA_ORIGIN_DIR = DATA_DIR.joinpath("_origin") DATA_AFTER_PREPARATION_DIR = DATA_DIR.joinpath("prepared") DATA_TRIPS_AS_HEXES_DIR = DATA_DIR.joinpath("trips_as_hexes") DATA_ORIGIN_AMIENS_DIR = DATA_O...
1,171
481
# Python libraries # Ex1a import pysnmp import paramiko # Ex1b dir(pysnmp) ver = pysnmp.__version__ print "pysnmp version is: %s " % ver dir(paramiko) ver = paramiko.__version__ print "paramiko version is: %s " % ver # Ex1c
231
97
import os import sys import numpy as np import torch import torch.autograd as autograd import torch.nn as nn import torch.optim as optim from scipy.stats import norm from scipy.stats.mstats import gmean from pyhrt.utils import batches, create_folds, logsumexp ###########################################################...
18,971
6,826
from src.FeatureExtractor import Extractor from src.DataLoader import Dataset from src.Trainer import TrainClf from src.Inference import PredictClf from src.Models import MLModel
178
48
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Rastislav Szabo <raszabo@cisco.com>, Lukas Macko <lmacko@cisco.com>" __copyright__ = "Copyright 2016, Cisco Systems, Inc." __license__ = "Apache 2.0" # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compl...
3,637
1,155
import numpy as np from typing import List from wrench.basemodel import BaseClassModel from wrench.dataset import BaseDataset from sklearn.metrics import f1_score from snorkel.utils import probs_to_preds def calc_prior(labels: List, n_class: int): return [labels.count(i) for i in range(n_class)] def create_unb...
1,144
444
from .models import get_latest_serialized from django.core import serializers from django.http import HttpResponse from django.views.generic import View from django.conf import settings import json class GetJson(View): def get(self, _): # pylint:disable=no-self-use return HttpResponse(json.dumps(get_late...
663
202
""" RMSD Results ============= #. :class:`.RmsdResults` Results class for extracting RMSD of two molecules. """ from .results import Results class RmsdResults(Results): """ Results class containing RMSD measures. """ def __init__(self, generator): self._value = next(generator) def ...
363
119
from flask import Blueprint store_blueprint = Blueprint('stores', __name__) @store_blueprint.route('/') def index(): return "This is the stores index" @store_blueprint.route('store/<string:name>') def store_page(name): pass
235
78
# Copyright 2017 Rice University # # 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 writin...
5,462
1,821
from supervised.base.baseRegression import BaseRegression from processing.regularization import L2Regularization class RidgeRegression(BaseRegression): def __init__(self, iterations=5000, learning_rate=.01, alpha=1): super(RidgeRegression, self).__init__(iterations=iterations, learning_rate=learning_rate)...
375
109
from .merpy import ( get_entities, get_similarities, generate_lexicon, process_lexicon, show_lexicons, get_lexicons, download_lexicon, create_lexicon, create_mappings, download_mer, download_lexicons, mer_path, get_entities_mp, create_lexicon_from_file, delete...
941
346
import logging import numpy as np import pandas as pd import pymc3 as pm import theano as tt from abc import ABC, abstractmethod from contextlib import contextmanager from sklearn.base import BaseEstimator from typing import List, Optional, Tuple, Union logger = logging.getLogger(__name__) class BasePyMC3Model(ABC,...
3,231
1,005
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: website_domain.py # author: Harold Bradley III # email: harold@bradleystudio.net # created on: 11/03/2015 # # TODO: add DNS API capabilities """ ww.website_domain ~~~~~~~~~~~~~~~~~ A class to describe and ...
2,678
693
#!/usr/bin/env python3 # Floats (float) is numeric values like 1.0, 100,5 0,478, -1.36 print("1.0 + 0.2 =", 1.0 + 0.2) print("2.4 - 100.7 =", 2.4 - 100.7) print("2.7 * 1.5 =", 2.7 * 1.5) # You can do expressions and mixing integers and floats. print("1 + 2.5 =", 1 + 2.5)
275
152