text
string
size
int64
token_count
int64
""" Press run above to start """ from exercises.question_runner import run from question_directory import ( boolean_operators, boolean_review, changing_lists, dictionaries, equality_and_booleans, for_loops, functions, functions_quick_review, greater_than_less_than_and_booleans, ...
1,666
638
import os class Config(object): DEBUG = False STORAGE = os.environ['STORAGE'] SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] # these are on heroku only so get safely BASIC_AUTH_USERNAME = os.environ.get('BASIC_AUTH_USERNAME') BASIC_AUTH_PASSWORD = os.environ.get('BASIC_AUTH_PASSWORD') c...
462
165
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1,124
315
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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.or...
7,407
2,316
# Copyright (C) 2014 Alex Wilson # Copyright (C) 2012-14 Abram Hindle # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later v...
8,518
2,777
from flask_mail import Message from mailer import mailer from middleware.error_handling import write_log class MailService: @staticmethod def send_welcome_email(email: str, full_name: str) -> None: try: email = Message( subject="Welcome to DNSTool!", recipie...
1,003
274
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
2,390
685
INPUT_FILE_NAME = 'input.txt' puzzle_input = None with open(INPUT_FILE_NAME) as input_file: puzzle_input = list(map(lambda val: int(val), input_file.readline().rstrip('\n').split(','))) def run_instruction(opcode, param_1, param_2, param_3, memory): if opcode == 1: memory[param_3] = memory[param_1] +...
1,469
537
from pymongo import MongoClient import pymongo import datetime import sqlite3 as sql import os import signal from signal import SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM, SIGHUP import traceback from anonymizer.utils import logger_manager import sys ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) ATEXIT_SINGLET...
6,299
1,834
from django.db import models from django.contrib.auth.models import User from django.conf import settings class Calculation(models.Model): '''Just an example model: a log of all calculations made''' log_date = models.DateTimeField(auto_now_add=True) num1 = models.FloatField(blank=True, null=True) num2 = model...
826
269
import cyanodbc import dbapi20 from distro import linux_distribution import pytest class CyanodbcDBApiTest(dbapi20.DatabaseAPI20Test): driver = cyanodbc connect_args = ("Driver={SQLite3 ODBC Driver};Database=" "example.db;Timeout=1000;", ) "" def test_setoutputsize(self): pass def test...
552
184
from problem import Problem from utils.primes import sieve_of_eratosthenes, simple_is_prime class ConsecutivePrimeSum(Problem, name="Consecutive prime sum", expected=997651): @Problem.solution() def brute_force(self): upper_bound = 1_000_000 primes = list(sieve_of_eratosthenes(4000)) m...
802
248
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..types import UNSET, Unset T = TypeVar("T", bound="IndyPresAttrSpec") @attr.s(auto_attribs=True) class IndyPresAttrSpec: """ """ name: str cred_def_id: Union[Unset, str] = UNSET mime_type: Union[Unset, str] = UNSET refe...
2,312
775
from helpers import cd_to_datetime, datetime_to_str class CloseApproach: """A close approach to Earth by an NEO. A `CloseApproach` encapsulates information about the NEO's close approach to Earth, such as the date and time (in UTC) of closest approach, the nominal approach distance in astronomical un...
4,929
1,248
#!/usr/bin/env python # -*- coding: utf-8 -*- import asyncio import logging import json import ssl import uuid from terncy.version import __version__ import terncy.event as event import ipaddress from datetime import datetime from enum import Enum from zeroconf import ServiceBrowser, Zeroconf import aiohttp import webs...
11,023
3,234
if sm.getSlotsLeftToAddByInvType(2) < 8: sm.dispose() sm.addInventorySlotsByInvType(8, 2) sm.consumeItem()
110
51
import vispy vispy.use(app='egl') from moviepy.editor import VideoClip import numpy as np from vispy import scene, io, visuals from vispy.color import * import cv2 # Check the application correctly picked up egl assert vispy.app.use_app().backend_name == 'egl', 'Not using EGL' class AlphaAwareCM(BaseColormap): d...
5,310
1,983
bl_info = { 'name': 'BlendNet - distributed cloud render', 'author': 'www.state-of-the-art.io', 'version': (0, 4, 0), 'warning': 'development version', 'blender': (2, 80, 0), 'location': 'Properties --> Render --> BlendNet Render', 'description': 'Allows to easy allocate resources in cloud a...
69,906
20,548
"""Main module.""" from collections import defaultdict from functools import cache from itertools import product from operator import itemgetter from typing import List import numpy as np from Bio.Data.CodonTable import unambiguous_dna_by_id class CodonDegeneracy: def __init__(self, table_id: int = 1): ...
3,601
1,229
# -*- coding: utf-8 -*- """ Created on Sun Dec 15 01:37:59 2019 @author: kfmah """ stuff = list() stuff.append('python') stuff.append('chuck') stuff.sort() print (stuff[0]) print (stuff.__getitem__(0)) print (list.__getitem__(stuff,0))
243
118
import tarfile with tarfile.open('archive.zip') as tar: #BAD : This could write any file on the filesystem. for entry in tar: tar.extract(entry, "/tmp/unpack/")
179
59
# Author: Richard Correro from sklearn.base import ClusterMixin from .transformer_socket import TransformerSocket class ClustererSocket(TransformerSocket, ClusterMixin): '''Class which allows for treating clusterers as model parameters. Parameters ---------- estimator : Sci-kit learn estimator o...
2,206
593
# coding: utf-8 """ Telstra Messaging API # Introduction <table><tbody><tr><td class = 'into_api' style='border:none;padding:0 0 0 0'><p>Send and receive SMS and MMS messages globally using Telstra's enterprise grade Messaging API. It also allows your application to track the delivery status of both sent an...
17,639
5,106
from gym_minigrid.minigrid import * from gym_minigrid.register import register class MyEnv(MyMiniGridEnv): def __init__(self, size=9, max_steps=100, start_pos=(1, 1), good_goal_pos=None, bad_goal_pos=None, reward='sparse', good_goal_reward=10, bad_goal_reward=-10): self.start_pos = start_pos self....
1,598
577
#頂点数 n=7 #隣接リスト表現 G=[[] for _ in range(n)] G[0]=[1,2] G[1]=[0,3] G[2]=[0,4,5] #etc.
86
72
#!/usr/bin/env python # coding=utf-8 # @Time : 2019-06-04 # @Author : hongshu import sys import asyncio from tawsocks import common class TcpRelayHandler(object): def __init__(self, is_client, config, loop): self.is_client = is_client self.config = config self.loop = loop asyn...
5,854
1,838
# -*- coding: utf-8 -*- import requests import json import logging class HttpUtil: """ http util """ def get(self, url, params=None): ''' get request :param str url: url :param set params: parameters :return: json object or json array ''' resp =...
1,033
304
""" Vertical: Adds movement functions along the vertical (Y) axis to a game object """ class Vertical: def __init__(self, speed): self.speed = speed self.current_speed = self.speed.y def _change_speed(self, value): self.current_speed = value def up(self): self._change_sp...
452
147
# -*- coding: utf-8 -*- import datetime from typing import Optional, List, Any from pip_services3_commons.config import ConfigParams from pip_services3_commons.convert import StringConverter from pip_services3_commons.errors import ConfigException from pip_services3_commons.refer import IReferences from pip_services3_...
3,828
1,050
import logging import os from functools import partial from PIL.Image import Image from PyQt5.QtCore import QObject, pyqtSignal, QThread from PyQt5.QtWidgets import QProgressDialog from .threading import QThreadedWorkerDebug as QThreadedWorker from analyze.composition import Composition, Spectrogram from analyze.medi...
2,802
821
""" Node module =========== The ``node`` module contains the ``MetalNode`` class, which is the foundation for MetalPipe. """ import time import datetime import uuid import importlib import logging import os import threading import pprint import sys import copy import random import functools import csv import MySQLdb ...
61,891
17,009
import random numeroPc = random.randint(1, 5) numeroUsuario = int(input('Digite um número: ')) print('Parabéns vc acertou!' if numeroPc == numeroUsuario else 'O Computador venceu')
184
72
import pyipmi import pyipmi.interfaces import os import re import datetime import os.path import time import math import numpy import mmap import array import getopt import sys #Inmport path sys.path.append('../src') from aardvark_initial import * #Inmport path sys.path.append('../') from os_parameters_define import...
5,739
2,110
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from collections import Counter n, *a = map(int, read().split()) counter = Counter(a).values() ans = len(counter) if (sum(counter) - ans) % 2 == 1: ans -= 1 print(ans)...
321
123
import json from plato import db from plato.model.user import User from plato.test.base import BaseTestCase from plato.test.utils import add_user, add_domain class TestDomainService(BaseTestCase): def test_add_domain(self): '''Ensure a new domain can be added to database''' add_user('test', 'test...
9,730
2,694
import sqlite3 import datetime conn = sqlite3.connect('database.db') print("Opened database successfully") # NOTE: ID is DEPRECATED conn.execute('CREATE TABLE simulated (id TEXT, lat NUMERIC, lon NUMERIC, alt NUMERIC, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)') conn.execute('CREATE TABLE locations (id TEXT, lat NUMER...
442
140
# A bit of duplication of the component system tests to ensure # typescript components are transpiled properly to Python. # Types are tested in test_mypy. import json import re import pytest from . import ts_components as tsc @pytest.mark.parametrize( 'component', [tsc.TypedComponent, tsc.TypedClassComponen...
3,091
1,020
# -*- coding: utf-8 -*- import random import numpy as np import colorama from colorama import Fore, Back import copy colorama.init() LEFT = 'lft' RIGHT = 'rgt' UP = 'up' DOWN = 'dwn' HORIZONTAL = 'horizontal' VERTICAL = 'vertical' class Room: def __init__(self, x=0, y=0, h=0, w=0): self.x = x s...
9,371
3,015
#!/usr/bin/env python3 import wx import vmwizard as vmw if __name__ == '__main__': app = wx.App(False) frame = wx.Frame(None, wx.ID_ANY, "Variant Matrix") wiz = vmw.Wizard(frame) frame.Show(True) frame.Centre() app.MainLoop()
255
104
import os import string import textwrap import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # DMRIInstall # class DMRIInstall(ScriptedLoadableModule): """ """ helpText = textwrap.dedent( """ Please use the Extension Manager to install the "SlicerDMRI" ex...
2,308
764
import requests import json from typing import Tuple from datetime import timedelta, datetime from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.utils.html import...
24,698
7,213
import sacred from sacred import Experiment import os.path as osp import pandas as pd import scipy.io as sio import numpy as np from sacred import SETTINGS SETTINGS.CONFIG.READ_ONLY_CONFIG=False def pair_nuclei_and_generate_output(out_files_dir, datasetName, detector = "tracktor_prepr_det"): startFrame = 159 ...
5,603
2,011
import numpy as np arrs = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arrs[[0,2]])
90
53
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from .......
1,087
303
# one identifier for one types of dict # for instance, DK_SOME_KEY means this is a key for a data_dict DK_BATCH_SIZE = "batch_size" DK_PAD = "pad" # DK: general purpose data_dict DK_SRC_WID = "src_wid" # src = msg + ctx DK_SRC_WID_MASK = "src_wid_mask" DK_SRC_SEQ_MASK = "src_seq_mask" DK_MSG_WID = "msg_wid" # msg is us...
2,682
1,384
# -*- coding: utf-8 -*- """ .. module:: register.views.list :synopsis: View to list all registered users .. moduleauthor:: Chris Bartlett """ from django.urls import reverse from django.views.generic import TemplateView from register.api.utils.make_request import make_request class UserListView(TemplateView): ...
794
235
import unittest from prymate import evaluator, objects from prymate.lexer import Lexer from prymate.parser import Parser class TestEvaluator(unittest.TestCase): def test_eval_numeric_exp(self): tests = [ ["5", 5], ["10", 10], ["-5", -5], ["-10", -10], ...
12,308
4,137
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # A simple native client in python. # All this client does is echo the text it receives back at the extension. import sys import s...
1,074
349
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. from django.dispatch import receiver class AppUser(AbstractUser): email = models.EmailField(unique=True) is_author =...
1,140
342
# -*- coding: utf-8 -*- # Copyright 2017 Edoardo Pasca # # 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 ap...
1,748
581
""" Defines the dataclass for holding training related arguments. """ import json import math import sys from dataclasses import asdict, dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Union from das.models.model_args import ModelArguments from das.utils.basic_utils import create_...
4,658
1,460
""" Perform sanitization check prior of releasing the app as ready. """ def main(): "Perform sanitization checks" pass
128
41
import asyncio import traceback from asyncio import StreamWriter, StreamReader, Task from .BaseClientHandler import BaseClientHandler from data import Message class ClientHandler(BaseClientHandler): _inputTask: Task _errorCheckTask: Task reader: StreamReader writer: StreamWriter # noinspection PyUnresolvedRef...
1,982
724
# chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import RoomControl from channels.db import database_sync_to_async class ChatConsumer(AsyncWebsocketConsumer): # when a user connect async def connect(self): self.user = self.scope['user'] ...
8,658
2,166
import numpy as np from cnnclustering._primitive_types import P_AINDEX, P_AVALUE from cnnclustering import _types, _fit COMPONENT_ALT_KW_MAP = { "input": "input_data", "data": "input_data", "n": "neighbours", "na": "neighbours", "nb": "neighbour_neighbours", "getter": "neighbours_getter", ...
7,342
2,404
#!/usr/bin/env python from __future__ import print_function from ipywidgets import * from IPython.display import display from getpass import getpass import glob import os import stat import paramiko from string import Template from os.path import expanduser from pkg_resources import resource_string from IPython.core.ma...
15,620
4,947
import subprocess import os import shutil import time import yaml import sys import logging logger = logging.getLogger(__name__) class compile(): def __init__(self): args = sys.argv args.pop(0) if len(args) >= 1: self.release_type = args.pop(0) else: self.release_type = None self.build_folder = None ...
5,419
2,427
# Generated by Django 2.1.11 on 2019-08-14 03:10 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sfm', '0001_squashed_0003_auto_20180319_0924'), ('ibms', '0010_auto_20190808_1104'), ] operations = [ migrations.AlterUniqueTogether( ...
990
345
class Config(object): poetry_file = 'poetry4min.txt' weight_file = 'poetry_model_4_1.h5' # 根据前六个字预测第七个字 max_len = 4 batch_size = 128 learning_rate = 0.0005
180
89
"""A CSV annotation writer that reads the bbox in x, y, w, h format.""" from discolight.annotations import BoundingBox from .types import CSVRow, CSVAnnotationLoader class WidthHeightCSV(CSVAnnotationLoader): """Loads annotations from a CSV file in the following format. image_name, x_min, y_min, width, heig...
840
267
from days import day09 from ddt import ddt, data, unpack import unittest import util @ddt class MyTestCase(unittest.TestCase): @data( [['{}'], '1'], [['{{{}}}'], '6'], [['{{},{}}'], '5'], [['{{{},{},{{}}}}'], '16'], [['{<a>,<a>,<a>,<a>}'], '1'], [['{{<...
1,286
541
"""A utility module which has FD-related functions. This module mostly exists for L{clean_fds}, so it can be imported without accidentally getting a reactor or something else that might create a critical file descriptor. """ import os import resource def clean_fds(): """Close all non-stdio file descriptors. ...
751
215
""" This script creates users in a JAMF Pro Server instance from an LDAP query. """ # Copyright 2020 Dalton Durst # # 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, inclu...
6,760
2,222
# coding:utf-8 ''' from http://www.pythonchallenge.com/pc/def/integrity.html ''' un = 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084' pw = 'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08' def bz2_un(): return un.d...
442
288
from flask import Flask, jsonify, request from flask_cors import CORS from twilio.twiml.messaging_response import MessagingResponse, Message from twilio.rest import Client import sqlconnector as sql from datetime import datetime import os # configuration DEBUG = True twilio_sid = os.environ.get('TWILIO_SID') twilio_se...
1,387
455
#!/usr/bin/env python from scapy.all import * import dpkt import argparse import sys def printTS(pcapFile, lib): if lib == 'scapy': packets = rdpcap(pcapFile) counter = 0 for packet in packets: # print packet.time print str.format('{0:.9f}', packet.time) ...
1,174
369
#!/usr/bin/env python3 # coding=utf-8 from __future__ import print_function from jsonrpcclient.http_client import HTTPClient from url_util import endpoint import argparse import simplejson def get_topics(): with open("../output/transaction/topics", 'r') as topicfile: topics = simplejson.load(topicfile) ...
1,101
343
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class TeamModel(db.Model): rowId = db.Column(db.Integer, primary_key=True) teamName = db.Column(db.String) teamRole = db.Column(db.String) def __repr__(self) -> str: return "{}:{}:{}".format(self.rowId, self.teamName, self.teamRole)
319
118
__version__ = "0.0.1" from .revx_output_siip import SIIPTimeSeriesMetadata, concat, max_fiber_size, match_points
114
45
# -*- coding: utf-8 -*- """ Created on Sun Jan 07 07:52:52 2018 @author: MVGrigoriev @task: kNN method """ import pandas import numpy as np from sklearn.neighbors import KNeighborsClassifier # Import class from scikit-learn from sklearn.model_selection import KFold # Import KFold function from sklearn.model_se...
2,095
752
# ipython utils import os import sys import time import yaml import datetime from pathlib import Path from IPython import get_ipython from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic) import warnings; warnings.simplefilter('ignore') s...
1,946
722
#!/usr/bin/python3 # Run the camera with a 180 degree rotation. from qt_gl_preview import * from picamera2 import * import time picam2 = Picamera2() preview = QtGlPreview(picam2) preview_config = picam2.preview_configuration() preview_config["transform"] = libcamera.Transform(hflip=1, vflip=1) picam2.configure(prev...
362
135
#!/usr/bin/env python from __future__ import unicode_literals from prompt_toolkit import prompt if __name__ == '__main__': print('If you press meta-! or esc-! at the following prompt, you can enter system commands.') answer = prompt('Give me some input: ', enable_system_bindings=True) print('You said: %s'...
331
102
import unittest import searcheval.metrics as sm class MetricsTests(unittest.TestCase): def test_mean(self): vector = [2, 3, 7] mean = sm.mean(vector) self.assertEqual(mean, 4) def test_precision(self): relevance_vector = [1, 0, 0, 1, 0] precision = sm.precision(relev...
3,294
1,360
# # 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 # distributed under ...
1,054
331
from collections import OrderedDict from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Optional, Set import discord import functools from .gameflags import GameFlagsManager from .playerdict import PlayerDict from .repoman import GameRepoManager from constants impor...
16,732
4,989
# -*- coding: utf-8 -*- from ..stanzas import Stanza from ..errors import makeStanzaError from ..protocols.stream_mgmt import NS_URI async def handle(stream, feature_elem, sm_opts, timeout=None): assert(feature_elem is not None) nsmap = {"sm": NS_URI} enable_elem = Stanza("enable", nsmap={None: NS_URI}) ...
897
309
from dataclasses import dataclass @dataclass class Channel: index: int name: str = None @property def display_name(self): if self.name is None or self.name.strip().isspace(): return f"Channel {self.index}" return f"Ch{self.index}. {self.name}"
293
91
from unittest import TestCase import pandas as pd from feature_extraction.pattern.pattern import Pattern from preprocessing.corpus import build_corpus class Test_Pattern(TestCase): raw_data = { "class": [0, 0, 1, 0], "content": [ "John hates bitches", "John hates hookers",...
705
228
from starlette.responses import Response from passlib.hash import pbkdf2_sha256 from starlette.websockets import WebSocketDisconnect from blockchain import Blockchain # from wallet import Wallet from fastapi import FastAPI, WebSocket import uvicorn import socket import requests as r from pydantic import BaseModel from ...
11,525
3,430
import json from bunch import Bunch import os def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(namespace) or config(dictionary) """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_fi...
4,650
1,317
import json from django.views import View from django.shortcuts import redirect, render from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.http.response import HttpResponseRedirect from rest_framework.renderers import TemplateHTMLRenderer from rest_framework import st...
7,096
1,905
from apps.vadmin.system.models.celery_log import CeleryLog from apps.vadmin.system.models.config_settings import ConfigSettings from apps.vadmin.system.models.dict_data import DictData from apps.vadmin.system.models.dict_details import DictDetails from apps.vadmin.system.models.logininfor import LoginInfor from apps.va...
560
160
from django.conf.urls import url from .views import profile, hunterList, changePass urlpatterns = [ url(r'^$', profile, name='hunter_profile'), url(r'^password', changePass, name='hunter_password'), url(r'^list', hunterList, name='hunter_list') ]
260
89
from scipy.sparse import dok_matrix import pandas as pd from cytoolz import itemmap def long_dataframe_to_sparse_matrix( df, index, vars, values, id_to_row=None, var_to_column=None ): if id_to_row is None: unique_index_values = df[index].unique() id_to_row = dict(zip(unique_index_values, range...
1,822
662
from django.db import migrations from backent.api import enums def populate_tags(apps, schema_editor): EventTag = apps.get_model('backent_api', 'EventTag') EventTag.objects.get_or_create(name=enums.EVENT_TAG_BEGINNER_FRIENDLY) EventTag.objects.get_or_create(name=enums.EVENT_TAG_INTERNATIONAL) EventTa...
1,059
397
from .test_uk_base import TestUkBase class TestUkPipes(TestUkBase): ################ # Tests def test_pipe_seq_start(self): self.equkz("|c","c") self.equkz("c|","c<¬") self.equkz("[ce|]","[ce]<¬") def test_pipe_seq_end(self): self.equkz("[c||d]e","c(de)") self.equkz("[c*2_3||d]e","c*2_3(...
938
437
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019-2020 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl """ Harvest functions & annotate their ...
25,329
7,531
import pandas as pd import os import torch import numpy as np import argparse from trojai_utils import * def batch_embeddings(reviews, N, batch_size, tokenizer, embedding, cls_first, embedding_dim=768): embeddings = torch.zeros((N, 1, embedding_dim)) for i in range(N // batch_size): review_batch = revi...
2,637
909
""" test pretrained models """ from __future__ import print_function import mxnet as mx from common import find_mxnet, modelzoo from common.util import download_file, get_gpus from score import score def download_data(): download_file('http://data.mxnet.io/data/val-5k-256.rec', 'data/val-5k-256.rec') def test_ima...
1,584
658
""" Provides Siren rendering support. """ from __future__ import unicode_literals from rest_framework.renderers import JSONRenderer class SirenRenderer(JSONRenderer): """ Renderer which serializes to YAML. """ media_type = 'application/vnd.siren+json' format = 'siren'
293
94
import numpy as np __all__ = ( "standard_bipolar_sine", "double_bipolar_sine", "standard_bipolar", "double_bipolar", "semicircle", "double_semicircle", "gaussian", "double_gaussian", ) def semicircle(a, T): """Return semicircle bipolar wave with amplitude a (units of V) and period...
4,050
1,616
from keras import layers import tensorflow as tf from Resnet import ResNet50 import keras from keras.models import Input,Model def inference(image_pre,image_now,location_tensor,shape): #extra high leavl feature input = Input(shape=shape) vision_model = keras.applications.MobileNet(include_top=False, ...
1,686
572
"""Visualizations for NLP analysis""" import pandas as pd import numpy as np from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import seaborn as sns def _plot_classification_report(val_y,predictions): report = classification_report(val_y...
1,807
670
from sqlpuzzle._common import Object from sqlpuzzle._queries.options import Options __all__ = () class SelectOptions(Options): _definition_of_options = { 'sql_cache': { 'off': '', 'cache': 'SQL_CACHE', 'no_cache': 'SQL_NO_CACHE' }, 'duplicated': { ...
2,844
919
from Code.utility_functions import get_excel_row_index class RowVariable: def __init__(self) -> None: self.value = None def evaluate(self, bindings: dict) -> str: """ This function checks if the row variable exists in the bindings dictionary If yes, then returns the value from...
1,199
303
import logging from datetime import datetime from datetime import timedelta from cvprac.cvp_client_errors import CvpApiError class CvpChangeControl(object): """Change-control class to provide generic method for CVP CC mechanism. Change Control structure is based on: - A name to identify change ...
9,189
2,378
from flask import current_app, request from http import HTTPStatus from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm import Session from app.models.stores.store_model import StoreModel from app.decorators import verify_payload, validator @validator(zip_code="zip_code") @verify_payload( fields_and...
1,289
375
#!/usr/bin/env python import argparse import boto from boto.s3 import connection as s3_connection from cinderclient.v1 import client as cinder_v1 import code from novaclient.v1_1 import client as nova_v1 from novaclient.shell import OpenStackComputeShell as open_shell from glanceclient import Client as glance_client fr...
4,197
1,232
import inspect from .descriptors import Descriptor from .arguments import ArgsDescriptor def node(fget, *args, **kwargs): signature = inspect.signature(fget) base = ArgsDescriptor if len(signature.parameters) > 1 else Descriptor cls = type(fget.__code__.co_name, (base, ), {}) return cls(fget, *args,...
330
107