text
string
size
int64
token_count
int64
from pycodimd import CodiMD cmd = CodiMD('https://md.noemis.me') #cmd.login('user@example.com','CorrectHorseBatteryStaple') cmd.load_cookies() print(cmd.history()[-1]['text']) # Print Name of latest Note
206
80
import os print('echoenv...', end=' ') print('Hello,', os.environ['USER'])
75
26
""" Display command results. """ from __future__ import unicode_literals from contextlib import contextmanager from argparse import Namespace from io import BytesIO from colorama import AnsiToWin32 from chromalog.stream import stream_has_color_support from chromalog.colorizer import Colorizer from chromalog.mark.he...
4,137
1,096
### # Copyright (c) 2020-2021, The Limnoria Contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this l...
6,167
1,848
""" preprocess-twitter.py python preprocess-twitter.py "Some random text with #hashtags, @mentions and http://t.co/kdjfkdjf (links). :)" Script for preprocessing tweets by Romain Paulus with small modifications by Jeffrey Pennington with translation to Python by Motoki Wu Translation of Ruby script to create features f...
2,237
900
#! /usr/bin/env python # -*- coding:utf8 -*- # # pw_classes.py # # This file is part of pyplanes, a software distributed under the MIT license. # For any question, please contact one of the authors cited below. # # Copyright (c) 2020 # Olivier Dazel <olivier.dazel@univ-lemans.fr> # Mathieu Gaborit <gaborit@kth.se> # ...
37,124
18,560
from __future__ import absolute_import, division, print_function import sys import time from cctbx.array_family import flex from scitbx.math import superpose from mmtbx.conformation_dependent_library import mcl_sf4_coordination from six.moves import range from mmtbx.conformation_dependent_library import metal_coordina...
9,001
3,302
from contextlib import contextmanager import random import shutil import stat import tempfile import unittest from os.path import join from conda import install from conda.install import (PaddingError, binary_replace, update_prefix, warn_failed_remove, duplicates_to_remove) from .decorator...
15,778
5,227
"""A Queryset slicer for Django.""" def slice_queryset(queryset, chunk_size): """Slice a queryset into chunks.""" start_pk = 0 queryset = queryset.order_by('pk') while True: # No entry left if not queryset.filter(pk__gt=start_pk).exists(): break try: #...
728
233
from django.urls import path from . import views urlpatterns = [ path('', views.news_home, name='news_home'), path('create', views.create, name='create'), path('<int:pk>', views.NewsDetailView.as_view(), name='news-detail'), path('<int:pk>/update', views.NewsUpdateView.as_view(), name='news-update'), ...
402
133
import requests import lib.common MODULE_NAME = 'headers' def run(): r = requests.get(lib.common.SOURCE_URL) # X-Forwarded-By: if 'X-Powered-By' in r.headers: lib.common.RESULT_ONE_DICT['X-Powered-By'] = r.headers['X-Powered-By'] # Server: if 'Server' in r.headers: lib.common.R...
412
166
import os import requests from bs4 import BeautifulSoup from ekorpkit import eKonf from ekorpkit.io.download.web import web_download, web_download_unzip class EDGAR: def __init__(self, **args): self.args = eKonf.to_config(args) self.base_url = self.args.base_url self.url = self.args.url ...
1,234
398
from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType import numpy as np import unittest class testPerfForesightConsumerType(unittest.TestCase): def setUp(self): self.agent = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerType(cycles=0) PF_...
3,470
1,262
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server.models.component import Component from openapi_server import util from openapi_server.models.co...
3,893
1,225
import os from os import getcwd #---------------------------------------------# # 训练前一定要注意修改classes # 种类顺序需要和model_data下的txt一样 #---------------------------------------------# classes = ["cat", "dog"] sets = ["train", "test"] wd = getcwd() for se in sets: list_file = open('cls_' + se + '.txt', 'w')...
1,003
358
from protocolbuffers import SimObjectAttributes_pb2 as protocols from careers.career_unemployment import CareerUnemployment import services import sims4 logger = sims4.log.Logger('Relationship', default_owner='jjacobson') class SimKnowledge: __slots__ = ('_rel_data', '_known_traits', '_knows_career', '_known_stats...
5,272
1,625
# Given an integer n, count the total number of digit 1 appearing # in all non-negative integers less than or equal to n. # # For example: # Given n = 13, # Return 6, because digit 1 occurred in the following numbers: # 1, 10, 11, 12, 13. # class Solution: def countDigitOne(self, n): """ :type n: ...
1,001
328
from PIL import Image from math import sqrt import numpy as np import time import matplotlib.backends.backend_tkagg import matplotlib.pyplot as plt class Point: x: float y: float f: float h: float g: float def __init__(self, x, y, f): self.x = x self.y = y ...
13,954
5,201
#Author Shoaib Omar import time import rnnoise import numpy as np def time_rnnoise(rounds=1000): a = rnnoise.RNNoise() timer = 0.0 st = time.time() for i in range(rounds): inp = np.random.bytes(960) timer = (time.time() - st) print(timer) st = time.time() for i in range(rounds): inp = np.random.bytes(960) ...
624
286
""" shell sort tests module """ import unittest import random from sort import shell from tests import helper class ShellSortTests(unittest.TestCase): """ shell sort unit tests class """ max = 100 arr = [] def setUp(self): """ setting up for the test """ self.arr = random.sample(ran...
1,092
331
import h5pyd from datetime import datetime import tzlocal BUCKET="firefly-hsds" inventory_domain = "/FIREfly/inventory.h5" def formatTime(timestamp): local_timezone = tzlocal.get_localzone() # get pytz timezone local_time = datetime.fromtimestamp(timestamp, local_timezone) return local_time f = h5pyd.F...
666
242
#------------------------------------------------------------------------------ # Copyright (c) 2013-2017, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------...
2,640
652
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals from json import dumps import frappe import unittest from erpnext.erpnext_integrations.doctype.mpesa_settings.mpesa_settings import process_balance_info, verify_transact...
12,488
4,967
from __future__ import absolute_import import yaml with open("config.yml", "r") as f: config = yaml.load(f)
114
42
""" XVM (c) www.modxvm.com 2013-2017 """ # PUBLIC def getTiers(level, cls, key): return _getTiers(level, cls, key) # PRIVATE from logger import * from gui.shared.utils.requesters import REQ_CRITERIA from helpers import dependency from skeletons.gui.shared import IItemsCache _special = { # Data from http:/...
3,870
1,802
import math from pypy.module.cpyext import pystrtod from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w from rpython.rtyper.lltypesystem import rffi from rpython.rtyper.lltypesystem import lltype from pypy.module.cpyext.pystrtod import PyOS_string_to_double class TestPyOS_string_to_double(BaseApiTest)...
6,099
2,555
# -*- coding: utf-8 -*- from mathics.core.symbols import Symbol # Some other common Symbols. This list is sorted in alphabetic order. SymbolAssumptions = Symbol("$Assumptions") SymbolAborted = Symbol("$Aborted") SymbolAll = Symbol("All") SymbolAlternatives = Symbol("Alternatives") SymbolAnd = Symbol("And") SymbolAppe...
3,529
1,035
# from https://github.com/kvwoerden/mcts-cartpole # ---------------------------------------------------------------------------- # # Imports # # ---------------------------------------------------------------------------- # import os import time impor...
5,821
1,711
from django_cron import CronJobBase, Schedule class VerifyLicenceSpeciesJob(CronJobBase): """ Verifies LicenceSpecies against TSC server. """ RUN_AT_TIMES = ['00:00'] schedule = Schedule(run_at_times=RUN_AT_TIMES) code = 'applications.verify_licence_species' def do(self): pass
318
116
import ASV from simpletal import simpleTAL, simpleTALES try: import logging except: import InfoLogging as logging import codecs class ColumnSorter: def __init__ (self, columnList): self.columnList = columnList self.log = logging.getLogger ('ColumnSorter') def setup (self, fieldNames): mapList = [] fo...
2,999
1,189
from django.forms import BooleanField, ValidationError from django.utils.timezone import now from django.utils.translation import gettext as _ from .models import WagtailAdminModelForm class CommentReplyForm(WagtailAdminModelForm): class Meta: fields = ("text",) def clean(self): cleaned_data...
2,484
631
import os from sqlalchemy.orm import Session from db.database import SessionLocal class DbData: def __init__(self): self.root_directory: str = "db_merge_scripts" self.scripts = [ "loader.sql" ] def sync(self, db: Session): for script in self.scripts: ...
1,039
345
def compareMetaboliteDicts(d1, d2): sorted_d1_keys = sorted(d1.keys()) sorted_d2_keys = sorted(d2.keys()) for i in range(len(sorted_d1_keys)): if not compareMetabolites(sorted_d1_keys[i], sorted_d2_keys[i], naive=True): return False elif not d1[sorted_d1_keys[i]] == d2[sorted_...
6,274
1,932
#!/usr/bin/python # -*- coding:utf-8 -*- print("hello world") f = None try: f = open("./hello.txt","r",encoding="utf8") print(f.read(5),end='') print(f.read(5),end='') print(f.read(5)) except IOError as e: print(e) finally: if f: f.close() # with auto call the methods' close with open...
1,750
887
def prepare_sets(dataset, feature_columns, y_column): train_X, val_X, train_y, val_y = train_test_split(dataset[feature_columns], dataset[y_column], random_state=1) return train_X, val_X, train_y, val_y
210
76
# Copyright (c) 2009-2020, quasardb SAS. All rights reserved. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice,...
6,355
2,270
from nerwhal.backends.flashtext_backend import FlashtextBackend from nerwhal.recognizer_bases import FlashtextRecognizer def test_single_recognizer(embed): class TestRecognizer(FlashtextRecognizer): TAG = "XX" SCORE = 1.0 @property def keywords(self): return ["abc", "c...
2,128
704
import boto3 import sys import time import logging import getpass def new_rdsmysql(dbname, instanceID, storage, dbInstancetype, dbusername): masterPass = getpass.getpass('DBMasterPassword: ') if len(masterPass) < 10: logging.warning('Password is not at least 10 characters. Please try again') ...
1,444
419
import random import requests from api.block_api import BlockApi from exception.tzscan import TzScanException from log_config import main_logger logger = main_logger HEAD_API = {'MAINNET': {'HEAD_API_URL': 'https://api%MIRROR%.tzscan.io/v2/head'}, 'ALPHANET': {'HEAD_API_URL': 'http://api.alphanet.tzscan...
2,657
921
import pytest import cudf import mock from cuxfilter.charts.core.non_aggregate.core_non_aggregate import ( BaseNonAggregate, ) from cuxfilter.dashboard import DashBoard from cuxfilter import DataFrame from cuxfilter.layouts import chart_view class TestCoreNonAggregateChart: def test_variables(self): ...
10,086
3,621
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Tag' db.create_table(u'tagging_tag', ( (u'id'...
4,265
1,367
class Session(list): """Abstract Session class""" def to_strings(self, user_id, session_id): """represent session as list of strings (one per event)""" user_id, session_id = str(user_id), str(session_id) session_type = self.get_type() strings = [] for event, product in s...
1,004
294
def location(messaging_adaptor, user, channel, location): message = "Your location has been set to `{}`. You are ready to be matched for Lunch Tag :)".format(location) messaging_adaptor.send_message(channel, message)
219
65
#!/usr/bin/env python # Copyright (C) 2013-2016 by Yu-Jie Lin # # 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, mo...
6,462
2,177
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Outline explorer API. You need to declare a OutlineExplorerProxy, and a function for handle the edit_goto Signal. class OutlineExplorerProxyCustom(OutlineExplore...
8,729
2,592
import weakref class IpyString(str): def _repr_pretty_(self, p, cycle): return p.text(str(self)) class SeamlessBase: _destroyed = False _context = None _cached_path = None name = None def _get_macro(self): return self._context()._macro @property def path(self): ...
3,132
866
import os import re import sys from oguilem.configuration.fitness import OGUILEMFitnessFunctionConfiguration from oguilem.configuration.ga import OGUILEMGlobOptConfig from oguilem.configuration.geometry import OGUILEMGeometryConfig from oguilem.configuration.utils import ConnectedValue, ConfigFileManager from oguilem....
11,613
3,246
from __future__ import (division, print_function) import matplotlib.cm as cmx import matplotlib.colors as colors from matplotlib import gridspec from metadatastore.api import db_connect as mds_db_connect from filestore.api import db_connect as fs_db_connect fs_db_connect( **{'database': 'data-processing-dev', 'h...
8,705
3,440
from __future__ import unicode_literals import copy import json from six import string_types from . import default_operators from . import sql_prepare from . import values from .error import WinnowError from .templating import SqlFragment from .templating import WinnowSql class Winnow(object): """ Winnow is...
12,101
3,403
import regex as re import time import collections import datetime import six import pandas as pd import google.cloud.bigquery as bq from multipledispatch import Dispatcher import ibis import ibis.common as com import ibis.expr.operations as ops import ibis.expr.types as ir import ibis.expr.schema as sch import ibis...
12,525
4,100
from math import log, ceil def chart(person): res=helper(tuple(sorted(person.parents(), key=lambda x: x.sex, reverse=True)), 2, [], 16, 16) res.append((person.name, 16)) dict={j:i for i,j in res} dict2=helper2(16) chart=[] for i in range(1, 32): temp=((4-depth(i))*11-1)*" "+("|" if 4-de...
1,583
604
import numpy as np import ROOT from dummy_distributions import dummy_pt_eta counts, test_in1, test_in2 = dummy_pt_eta() f = ROOT.TFile.Open("samples/testSF2d.root") sf = f.Get("scalefactors_Tight_Electron") xmin, xmax = sf.GetXaxis().GetXmin(), sf.GetXaxis().GetXmax() ymin, ymax = sf.GetYaxis().GetXmin(), sf.GetYax...
690
299
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 14 17:42:27 2018 @author: zgeorg03 """ import re import json # Used for converting json to dictionary import datetime # Used for date conversions import matplotlib.pyplot as plt import numpy as np from sentiment import Sentiment import json cla...
5,755
2,015
"""Recursive implementations.""" def find_max(A): """invoke recursive function to find maximum value in A.""" def rmax(lo, hi): """Use recursion to find maximum value in A[lo:hi+1].""" if lo == hi: return A[lo] mid = (lo+hi) // 2 L = rmax(lo, mid) R = rmax(mid+1, hi) ...
1,214
428
#from distutils.core import setup from setuptools import setup, find_packages from distutils.extension import Extension import re import os import codecs here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open, See: # https://github.com/pyp...
3,084
1,054
import logging from flask import Flask from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy from flask_migrate import Migrate from flask_cors import CORS from flask_talisman import Talisman from flask_ipban import IpBan from config import Config, get_logger_handler # database class SQLAlchemy(_BaseSQLAlchemy):...
1,716
568
# -*- coding: utf-8 -*- import os import csv import pymongo from pymongo.errors import DuplicateKeyError from settings import MONGO_HOST, MONGO_PORT, SAVE_ROOT class MongoDBPipeline(object): def __init__(self): client = pymongo.MongoClient(MONGO_HOST, MONGO_PORT) db = client['weibo'] self....
4,937
1,551
from pathlib import Path from requests.auth import _basic_auth_str import pytest from bravado_core.formatter import SwaggerFormat, NO_OP from gc3_query.lib.gc3_config import GC3Config, IDMCredential TEST_BASE_DIR: Path = Path(__file__).parent.joinpath("GC3Config") config_dir = TEST_BASE_DIR.joinpath("config") def te...
6,020
2,218
import machine from machine import * import ssd1306 import time import socket import urequests as requests import json word = {'body':8} labels = ['c', 'o', 'l', 'u', 'm', 'b', 'i', 'a','null'] HOST = '18.218.158.249' PORT = 8080 flag = 0 stop = False data = {} xdata = [] ydata = [] n = 0 def dp(d): if (d > 128)...
2,871
1,188
from Geometry.VeryForwardGeometry.dd4hep.v5.geometryRPFromDD_2021_cfi import *
79
36
import argparse import matplotlib.pyplot as plt import torch from pytorch_warmup import * def get_rates(warmup_cls, beta2, max_step): rates = [] p = torch.nn.Parameter(torch.arange(10, dtype=torch.float32)) optimizer = torch.optim.Adam([{'params': p}], lr=1.0, betas=(0.9, beta2)) lr_scheduler = torch....
1,464
564
"""\ This plugin merely enables other plugins to accept data over HTTP. If a plugin defines a module level function named "httpev" it will be invoked for POST requests to the url http://$hostname/event/$pluginname. The function is invoked from the thread in the web.py request context and as such has access to the full ...
2,107
641
somaIdade = 0 maiorIdade = 0 nomeVelho = '' totmulher20 = 0 for p in range(1, 3): print('---- {}ª PESSOA ----'.format(p)) nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')) somaIdade += idade if p == 1 and sexo in 'Mm': maiorIdade = idade ...
773
313
"""\ PROMORT example. """ import argparse import random import sys import pyecvl.ecvl as ecvl import pyeddl.eddl as eddl from pyeddl.tensor import Tensor import models def VGG16(in_layer, num_classes): x = in_layer x = eddl.ReLu(eddl.Conv(x, 64, [3, 3])) x = eddl.MaxPool(eddl.ReLu(eddl.Conv(x, 64, [3, ...
6,583
2,592
from src.view.services_page import ServicesPage from src.view.services_add_page import ServicesAddPage class ServicesUpdatePage(ServicesAddPage): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.set_title("Update service") self.set_confirm_button_...
343
97
import os import gettext import bisect from locale import getdefaultlocale from collections.abc import MutableMapping from copy import copy, deepcopy import six class Trans: def __init__(self): self.registry = {} self.current = None self.set(getdefaultlocale()[0]) def __getitem__(se...
7,543
2,293
import socket s = socket.socket() s.bind(("localhost", 9999)) s.listen(1) sc, addr = s.accept() while True: recibido = sc.recv(1024) if recibido == "quit": break print "Recibido:", recibido sc.send(recibido) print "adios" sc.close() s.close()
272
118
import numpy import matplotlib.pyplot as plt import geojsoncontour # Create lat and lon vectors and grid data grid_size = 1.0 latrange = numpy.arange(-90.0, 90.0, grid_size) lonrange = numpy.arange(-180.0, 180.0, grid_size) X, Y = numpy.meshgrid(lonrange, latrange) Z = numpy.sqrt(X * X + Y * Y) n_contours = 10 levels...
743
303
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countGroups' function below. # # The function is expected to return an INTEGER. # The function accepts STRING_ARRAY related as parameter. # class Graph: def __init__(self, V): self.V = V self.adj = [[] for ...
1,861
579
import logging.config import util.logger_init import numpy as np import tensorflow as tf from sklearn.metrics import confusion_matrix from util.tensorboard_util import plot_confusion_matrix, plot_to_image from tensorflow.python.keras.callbacks_v1 import TensorBoard from keras import backend as K class MlModel: d...
1,597
506
from .BaseRequest import BaseRequest class UpdateSubscriptionRequest(BaseRequest): """ Update subscription request for generating API request URLs to Tableau Server. :param ts_connection: The Tableau Server connection object. :type ts_connection: class :param new_subs...
1,803
458
from __future__ import absolute_import from __future__ import division from __future__ import print_function import ray import click import inspect import numpy as np import cython_examples as cyth def run_func(func, *args, **kwargs): """Helper function for running examples""" ray.init() func = ray.rem...
2,293
870
from DataGenerator import * from Encoder import * import pandas as pd from keras.models import Model from keras.layers import Dense, Activation, Flatten, Input, Dropout, MaxPooling1D, Convolution1D from keras.layers import LSTM, Lambda, merge, Masking from keras.layers import Embedding, TimeDistributed from keras.layer...
17,314
5,876
"""This module implements methods for solving scalar valued functions. """ __all__ = ["DiscreteMinimizer", "ScalarMethod", "ScalarMinimizer", "ScalarSolverException"] from desdeo_tools.solver.ScalarSolver import DiscreteMinimizer, ScalarMethod, ScalarMinimizer, ScalarSolverException
287
90
from hawc_hal.maptree.map_tree import map_tree_factory from hawc_hal.response import hawc_response_factory import os from conftest import check_map_trees, check_responses def test_root_to_hdf_response(response): r = hawc_response_factory(response) test_filename = "response.hd5" # Make sure it doesn't e...
1,661
591
from __future__ import absolute_import from io import BytesIO import zstd from .base import BaseCompressor, BaseDecompressor from ..protocol import CompressionMethod, CompressionMethodByte from ..reader import read_binary_uint32 from ..writer import write_binary_uint32, write_binary_uint8 class Compressor(BaseCompr...
1,577
504
import requests import json import os API_TOKEN = os.environ.get("TMDB_API_TOKEN", "") def call_tmdb_api(_endpoint): endpoint = f"https://api.themoviedb.org/3/{_endpoint}" full_url = f'{endpoint}?api_key={API_TOKEN}' response = requests.get(full_url) response.raise_for_status() return response.js...
1,019
398
# -*- coding: utf-8 -*- from openerp.osv import fields, osv from openerp import models, fields, api, _ class Tipo_Colaborador(models.Model): _name = 'tipo.colaborador' _rec_name = 'name' name=fields.Char(string='Nombre') active=fields.Boolean(string='Activo',default=True)
300
112
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # """ Tests for environ.py """ # Standard library imports import os # Test library imports import pytest # Third party imports from qtpy.QtCore import QTimer # Local imports from spyder.utils.test impo...
967
305
import math def main(): print(""" \tComsole by MumuNiMochii version beta 1.6.23 \t\"Originally made with C\" \tMAIN MENU \tWhat do you want to execute and evaluate? \t1.) Add two addends \t2.) Subtract a minuend from its subtrahend \t3.) Multiply a multiplicand to its multiplier \t4.) Divide a dividend to its...
4,680
1,528
import unittest import json from server import server from models.abc import db from repositories import ChannelRepository, GitlabProvider from unittest.mock import MagicMock, Mock # from flask import make_response # from flask.json import jsonify from util import test_client class TestDiscussions(unittest.TestCase)...
3,485
1,043
""" This is an example cog that shows how you would make use of Lavalink.py. This example cog requires that you have python 3.6 or higher due to the f-strings. """ import math import re import discord import lavalink from discord.ext import commands from discord.ext import menus from .utils import checks ...
24,943
7,691
import numpy as np import sys import os sys.path.append('utils/') from config import * from utils import * sys.path.append(pycaffe_dir) import time import pdb import random import pickle as pkl import caffe from multiprocessing import Pool from threading import Thread import random import h5py import itertools import m...
17,005
6,028
import math import os from collections import Counter from fractions import Fraction import numpy as np from nltk import ngrams from nltk.translate.bleu_score import SmoothingFunction from .utils import get_ngrams, Threader def corpus_bleu(references, hypothesis, reference_max_counts...
17,856
5,767
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import re from setuptools import setup, find_packages # classifiers = """\ # Development Status :: 4 - Beta # Programming Language :: Python # Programming Language :: Python :: 3 # Programming Language :: Python :: 3.4 # Programming...
1,880
628
from .trainer.models import MultiTaskTagger from .trainer.utils import load_dictionaries,Config from .trainer.tasks.multitask_tagging import MultiTaskTaggingModule from fairseq.data.data_utils import collate_tokens from attacut import tokenize class HoogBERTaEncoder(object): def __init__(self,layer=12,cuda=False...
3,018
939
from . import usuario from . import equipo_cambio from . import equipo_computo from . import sucursales from . import depto from . import usuario
146
43
from pyglet.window import Window as PygletWindow from .controllers import ComponentContainerController from .models.container import ComponentContainerModel from .views import OrthoViewport class Window(PygletWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._m...
697
197
from pyconductor import load_test_values, calculate_conductance def conductance_calc(): preloaded_dict = load_test_values() while preloaded_dict: print( "[1] - Show currently available materials in Material Dictionary\n" "[2] - Add a material (will not be saved upon restart)\n"...
1,806
474
from .Fragment import Fragment from utils.flags import * from utils.CustomLogging import CustomLogging #from python_compiler.engines.utils.types import get_python_type_str, ANY DEFAULT_ASSIGN_OPERATOR = "=" ASSIGN_OPERATORS = { "=":"=", "+=":"+=", "-=":"-=", "*=":"*=", "/=":"/=", "//=":"//=", ...
2,073
686
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys if not os.path.exists(sys.argv[1]): raise Exception() open(sys.argv[2], 'w').close()
266
94
# -*- coding: utf-8 -*- # # Licensed under the terms of the Qwt License # Copyright (c) 2002 Uwe Rathmann, for the original C++ code # Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization # (see LICENSE file for more details) """ QwtAbstractScaleDraw -------------------- .. autoclass:: QwtAbstra...
37,440
10,726
from fuzzconfig import FuzzConfig import nonrouting import fuzzloops import re cfgs = [ FuzzConfig(job="SYSCONFIG40", device="LIFCL-40", sv="../shared/empty_40.v", tiles=["CIB_R0C75:EFB_0", "CIB_R0C72:BANKREF0", "CIB_R0C77:EFB_1_OSC", "CIB_R0C79:EFB_2", "CIB_R0C81:I2C_EFB_3", "CIB_R0C85:PMU", "CIB_...
3,524
1,218
import argparse import collections import os import random import json from copy import deepcopy import ConfigSpace import numpy as np # from tabular_benchmarks import FCNetProteinStructureBenchmark, FCNetSliceLocalizationBenchmark,\ # FCNetNavalPropulsionBenchmark, FCNetParkinsonsTelemonitoringBenchmark from ta...
368
112
from uuid import UUID import os import pytest from notifications_utils.base64_uuid import base64_to_uuid, uuid_to_base64, base64_to_bytes, bytes_to_base64 def test_bytes_to_base64_to_bytes(): b = os.urandom(32) b64 = bytes_to_base64(b) assert base64_to_bytes(b64) == b @pytest.mark.parametrize( "url...
1,254
538
"""The devolo_home_control integration.""" from __future__ import annotations import asyncio from functools import partial from types import MappingProxyType from typing import Any from devolo_home_control_api.exceptions.gateway import GatewayOfflineError from devolo_home_control_api.homecontrol import HomeControl fr...
3,571
1,170
## -------------------------------------------------------- ## # Trab 1 IA 2019-2 # # Rafael Belmock Pedruzzi # # hillClimbing.py: implements the hill climbing metaheuristic for the bag problem # # Python version: 3.7.4 ## -------------------------------------------------------- ## import bagProblem as bp from...
1,199
413
"""ssb-pseudonymization - Data pseudonymization functions used by SSB""" __version__ = '0.0.2' __author__ = 'Statistics Norway (ssb.no)' __all__ = []
151
56
""" Keepkey ******* """ from ..errors import ( DEVICE_NOT_INITIALIZED, DeviceNotReadyError, common_err_msgs, handle_errors, ) from .trezorlib import protobuf as p from .trezorlib.transport import ( hid, udp, webusb, ) from .trezor import TrezorClient, HID_IDS, WEBUSB_IDS from .trezorlib.mes...
7,657
2,527
# -*- coding: utf-8 -*- """K-medoids clustering""" # Authors: Timo Erkkilä <timo.erkkila@gmail.com> # Antti Lehmussola <antti.lehmussola@gmail.com> # Kornel Kiełczewski <kornel.mail@gmail.com> # Zane Dufour <zane.dufour@gmail.com> # License: BSD 3 clause import warnings import numpy as np ...
15,195
4,555