text
string
size
int64
token_count
int64
# (C) Copyright 2017- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernme...
18,148
5,529
#!/usr/bin/env python3 # coding: UTF-8 '''! module description @author <A href="email:fulkgl@gmail.com">George L Fulk</A> ''' __version__ = 0.01 def main(): '''! main description ''' print("Hello world") return 0 if __name__ == "__main__": # command line entry point main() # END #
316
119
from .write_grok import *
25
9
from hashlib import sha256 from django.http import HttpResponse from django.shortcuts import redirect, render from .models import Usuarios def login(request): if request.session.get('usuario'): return redirect('/livro/home/') status = request.GET.get('status') return render(request, 'login....
1,883
624
import torch from transformers import BertTokenizer from .base_tester import Tester from textclf.utils.raw_data import create_tokenizer from textclf.utils.create import create_instance from textclf.config import DLTesterConfig from textclf.data.dictionary import Dictionary class DLTester(Tester): """负责Deep Learn...
2,737
854
import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt import numpy as np import os from nanopores.tools import fields from scipy.interpolate import interp1d HOME = os.path.expanduser("~") DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields") fields.set_dir(DATADIR) data = fields.get_fi...
3,303
1,760
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : unseen_pairs_prepare.py # Author : Honghua Dong # Email : dhh19951@gmail.com # Date : 02/04/2019 # # Distributed under terms of the MIT license. ''' To split dataset into {train/val/test}_split_{rel}_{attr}_{args}.pkl It will produce a set of indexes stored...
7,885
2,672
from datetime import datetime from sqlalchemy import UniqueConstraint from apis.initialization import db class Movie(db.Model): """ Movie Model for storing movie details""" id = db.Column(db.Integer, primary_key=True, autoincrement=True) ninety_nine_popularity = db.Column(db.Float, index=True, nullable...
1,533
519
# from distutils.core import setup from setuptools import setup, find_packages setup( name='py-toolkit', version='0.0.3', packages=find_packages(exclude=("tests",)), url='https://github.com/DewMaple/toolkit', description='python toolkit for common usage', author='DewMaple', author_email='de...
719
239
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'hnc.ui' # # Created by: PyQt5 UI code generator 5.15.6 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, Q...
3,934
1,266
""" data preprocessing and get batch """ import os import re import logging import itertools from collections import Counter import numpy as np import pandas as pd class DataLoad(object): logging.getLogger().setLevel(logging.INFO) def __init__(self, data_path, batch_size, num_epochs, dev_sample_rate, forced_...
6,373
2,155
# -*- coding: utf-8 -*- # Copyright (c) 2013, Sergio Callegari # All rights reserved. # This file is part of PyDSM. # PyDSM 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 3 of the License, o...
11,629
4,431
import os import nibabel import numpy as np import random from scipy import ndimage import SimpleITK as sitk def load_nifty_volume_as_array(filename, with_header = False): """ load nifty image into numpy array, and transpose it based on the [z,y,x] axis order The output array shape is like [Depth, Height,...
1,258
388
# project/server/user/views.py ################# #### imports #### ################# from flask import render_template, Blueprint, url_for, \ redirect, flash, request, session from flask_login import login_user, logout_user, login_required from project.server import bcrypt, db from project.server.models import ...
8,802
2,641
import torch import numpy as np from torch import nn def get_avg_discounted_value(next_dones, next_mask, next_rewards, next_value_preds, gamma): minibatch_size, td_lambda = next_dones.shape lambda_gamma = torch.cumprod(torch.ones(td_lambda)*gamma,dim=0) * (1/gamma) # all dones also must be masks, by def...
5,477
1,814
# https://www.facebook.com/hackercup/problem/169401886867367/ __author__ = "Moonis Javed" __email__ = "monis.javed@gmail.com" def numberOfDays(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: ...
660
356
class Robot: def __init__(self, left="MOTOR4", right="MOTOR2", config=1): print("init") def forward(self): print("forward") def backward(self): print("backward") def left(self): print("left") def right(self): print("right") def stop(self): pri...
331
110
from .messaging_service import MessagingService
47
11
from random import randint s = t = ma = 0 m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): m[l][c] = randint(0, 100) print('-='*15) for l in range(0, 3): t += m[l][2] for c in range(0, 3): print(f'[{m[l][c]:^5}]', end='') if m[l][c] % 2 == 0: ...
556
268
from .utils_tests import * from .views_tests import *
54
17
#!/usr/bin/env python import rospy as rp import numpy as np import math as math from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint from scipy.spatial import KDTree from std_msgs.msg import Int32 ''' This node will publish waypoints from the car's current position to some...
7,851
2,491
"""Exceptions.""" class OandaError(Exception): """ Generic error class, catches oanda response errors """ def __init__(self, error_response): self.error_response = error_response msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) " super...
595
167
# 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...
4,444
1,455
from ._base import * DEBUG = False WEBSITE_URL = "https://example.com" # without trailing slash MEDIA_URL = f"{WEBSITE_URL}/media/"
135
51
from tkinter import * from tkinter import filedialog from pyascii import main class App: def __init__(self, master): #initalize myFile instance variable self.myFile = None self.saveFile = None #set window height master.minsize(height = 440, width = 680) #create frame frame = Frame(master) f...
1,657
648
import unittest import os import numpy as np from constants import ( del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR, ) from perform.constants import REAL_TYPE from perform.system_solver import SystemSolver from perform.input...
13,093
4,668
#!/path/to/interpreter """ Flask App REST API testing: POST """ # Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ import allure import requests from tests.system.base_test import BaseTestCase from api.cars_app import USER_LIST @allure.epic('Simpl...
4,139
1,113
#!/usr/bin/env python '''Assert HDF5 input is non-zero. Print to stderr if not. For example, find . -iname '*.hdf5' -exec h5zero.py {} + ''' from __future__ import print_function import argparse import sys import h5py from dautil.IO.h5 import h5assert_nonzero __version__ = '0.1' def main(args): for filenam...
1,165
381
from django.core.exceptions import ValidationError def validate_first_of_month(value): if value.day != 1: raise ValidationError("%s should only be first day of the month." % value)
195
57
__version__ = "1.0.0" __author__ = "sunhailin-Leo"
51
27
#User function Template for python3 class Solution: def calculateSpan(self,a,n): Span = [0 for i in range(n)] stack = [0] #span value of first day is always 1. Span[0] = 1 for i in range(1, n): #we pop elements from the stack till price at top of stack is less th...
1,525
473
#!python # -*- coding: utf-8 -*- """Unit testing for scriptorium""" import os import tempfile import shutil import textwrap import unittest import scriptorium class TestScriptorium(unittest.TestCase): @classmethod def setUpClass(cls): """Set up unit tests for scriptorium""" TestScriptorium.templa...
2,768
893
"""Test the module SMOTE ENN.""" # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # Christos Aridas # License: MIT import pytest import numpy as np from sklearn.utils.testing import assert_allclose, assert_array_equal from imblearn.combine import SMOTEENN from imblearn.under_sampling import EditedNear...
4,794
2,694
# Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
46,925
14,231
""" Entradas monto de dinero presupuestal-->float-->a Salidas dinero correspondiente para ginecologia-->float-->b dinero correspondiente para traumatologia-->float-->c dinero correspondiente para pediatria-->float-->d """ a=float(input("Presupuesto anual al Hospital rural ")) b=a*0.40 c=a*0.30 d=a*0.30 print("El presup...
519
176
import os import subprocess PAGES_DIR = "../../pages" keyword_note = { 'tutorials': '', 'demos': '', 'quizzes': '', 'mathematics': '', 'algorithms': '', 'programming': 'By the way, if you prefer books to blogs, <a href="https://wordsandbuttons.online/SYTYKC.pdf">there is a free book</a> that was originally made from ...
5,926
2,431
# Generated by Django 3.0.7 on 2020-09-22 05:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('listings', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='post', name='author', ), ]
316
110
from django.forms import RadioSelect class RadioSelectButtonGroup(RadioSelect): """ This widget renders a Bootstrap 4 set of buttons horizontally instead of typical radio buttons. Much more mobile friendly. """ template_name = "bootstrap4/widgets/radio_select_button_group.html"
303
81
import logging import os import traceback from typing import List from workflower.adapters.sqlalchemy.setup import Session from workflower.adapters.sqlalchemy.unit_of_work import SqlAlchemyUnitOfWork from workflower.application.event.commands import CreateEventCommand from workflower.application.workflow.commands impo...
2,990
804
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import absolute_import, unicode_literals import io import os import re from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) PROJECT_MODULE = 'dragonite' PROJECT = 'dragonite' AUTHOR = 'Bryce Eggleton' EMAIL = '...
2,492
926
import random import database from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware import uvicorn # Instantiate FastAPI app = FastAPI() # Whitelist origins app.add_middleware( CORSMiddleware, allow_origins = ["*"], allow_credentials = True, allow_methods = ["*"], ...
3,427
1,180
# django imports from django import forms from django.conf import settings from django.core.cache import cache from django.template.loader import render_to_string # portlets imports from portlets.models import Portlet # lfs imports from lfs.page.models import Page class PagesPortlet(Portlet): """Portlet to disp...
1,211
363
from django.conf import settings from django.db import models from django.utils import timezone from users.models import Profile class Post(models.Model): description = models.CharField(max_length=255) picture = models.ImageField(upload_to='posts', blank=True) date_posted = models.DateTimeField(auto_now_a...
829
260
from django.contrib import admin from django.db import models from django.utils.translation import gettext as _ from .models import (MilitaryRank, Platoon, ServiseID, Unit, OfficialPosition, Company, Education, Creed, Nationality, Command) from osoba.widgets import CustomDatePickerInput class Ser...
2,168
699
# coding=utf-8 from typing import List class Solution: """ 旋转数组 """ def reverse(self, nums: List[int], i: int, j: int) -> None: """ :param nums: :param i: :param j: :return: """ while i < j: nums[i], nums[j] = nums[j], nums[i] ...
725
278
import sys, os, glob from skimage import io from skimage import viewer import registration as reg from skimage import data def display(): pass if __name__ == "__main__": # ------------------Create input ndarray------------------------ inputDir = '../data/test/' imageFiles = glob.glob(os.path.join(inp...
931
294
import numpy as np import torch import torch.utils.data as data from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import os, random, glob, cv2 class LFW2G(data.Dataset): def __init__(self, data_dir='data', transform=None): super(LFW2G, self).__init__() self.indexlist = glob.gl...
1,605
560
"""Set of questions for the IP Law quiz questions.py Lasya Sreepada Yale College '19 May 6, 2017 """ from random import shuffle import time def quiz(): questions = [ ("Copyright protects both expression of an idea and the idea itself. \nTrue or False?", "f", "cp"), ("Clothing, such as Katy Perr...
4,536
1,267
''' Created on 1.12.2016 @author: Darren '''''' Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path...
529
228
from unittest import TestCase from regulations.generator.layers.toc_applier import * class TableOfContentsLayerTest(TestCase): def test_section(self): toc = TableOfContentsLayer(None) el = {} toc.section(el, {'index': ['1']}) self.assertEqual({}, el) toc.section(el, {'in...
8,286
2,914
""" Numpy's `split` can split a multidimensional array into non-overlapping sub-arrays. However, this is not a memory-efficient way of dealing with non-overlapping partitions of an array because it effectively doubles memory usage. This module provides an iterable generator that produces tuples of slices, each of whic...
1,929
596
import json from textwrap import dedent import pytest @pytest.mark.usefixtures("add_host_with_interface") class TestAddHostBonded: def test_no_hosts(self, host): result = host.run('stack add host bonded') assert result.rc == 255 assert result.stderr == dedent('''\ error - "host" argument is required {ho...
7,197
3,070
#Задача 8. Вариант 11. #1-50. Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4) так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на подсказку в том случае, если у него нет никаких предположений. Разработайте систему начисления очков, по которой бы игроки, отгадавшие ...
1,669
673
# ColorPaint.py import pygame # setup import random pygame.init() screen = pygame.display.set_mode([800, 600]) pygame.display.set_caption('Click and drag to draw, using up to 3 mouse buttons') keepGoing = True ORANGE = (255,255,0) # RGB color triplets for 3 mousebutton colors GREEN = (0,25...
1,254
384
import datetime import unittest from accounts.models import AccountDetails from categories.models import Category from django.contrib.auth.models import User from django.test import Client from django.test import TestCase from django.urls import reverse from events.models import Comment from events.models import E...
14,508
4,310
from django.views.generic import TemplateView from .. import mixins class ProfileView(mixins.BillingMixin, TemplateView): template_name = "profile.html"
159
47
# -*- coding: utf-8 -*- """ @inproceedings{DBLP:conf/cvpr/SunLCS19, author = {Qianru Sun and Yaoyao Liu and Tat{-}Seng Chua and Bernt Schiele}, title = {Meta-Transfer Learning for Few-Shot Learning}, booktitle = {{IEEE} Conference on Computer Vision and Pattern ...
4,225
1,488
from capture_words import capture_words_from_file import random def find_letter_indexes(letter, word): indexes = [] for index, l in enumerate(word): if l == letter: indexes.append(index) return indexes def convert_word_to_asterisks(word): final_word = '*' * len(word) return...
1,023
333
# coding=utf-8 from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut from OTLMOW.OTLModel.Classes.DwarseMarkeringToegang import DwarseMarkeringToegang from OTLMOW.OTLModel.Datatypes.KlDwarseMarkeringVerschuindCode import KlDwarseMarkeringVerschuindCode from OTLMOW.OTLModel.Datatypes.KlDwarseMarkeringVerschu...
4,895
1,523
from django import forms from .models import Review class ReviewsForm(forms.ModelForm): """Форма добавления отзыва""" class Meta: model = Review fields = ["name", "text", "social_link", "git_link"] labels = { "name": (""), "text": (""), # "social_li...
549
169
#!/usr/bin/env python3 """ Copyright 2018 Couchbase, Inc 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 ...
6,875
2,011
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0003_auto_20150123_1148'), ] operations = [ migrations.AlterField( model_name='project', ...
542
183
# -*- coding: utf-8 -*- import logging # import pyodbc from odoo import models, fields, api, _ from odoo.exceptions import UserError, AccessError, MissingError _logger = logging.getLogger(__name__) class SQLConfig(models.Model): _name = 'sql.config' _description='sql_config' _sql_constraints = [('check_...
2,506
846
from blog.models import Category from django.template import Library from core.models import * register = Library() @register.filter def main_catagory(self): if self.category == None: return self.category
223
63
#Represents an object class Object: def __init__(self,ID,name): self.name = name self.ID = ID self.importance = 1 #keep track of the events in which this file was the object self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def getName(self)...
4,476
1,255
""" nginterface.py: NovaGenesis Interface """ __author__ = "Daniel Mazzer" __copyright__ = "Copyright 2016, CogRIoT Project" __credits__ = "Antonio Marcos Alberti" __license__ = "MIT" __maintainer__ = "Daniel Mazzer" __email__ = "dmazzer@gmail.com" import sys import zmq import threading from bzrlib.plugins.launchpad...
4,336
1,228
# # 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...
2,625
829
#!/usr/bin/env python3 """pdoc's CLI interface and helper functions.""" import argparse import ast import importlib import inspect import os import os.path as path import json import re import sys import warnings from contextlib import contextmanager from functools import lru_cache from http.server import BaseHTTPRequ...
19,947
6,083
import cx_Oracle import psycopg2 import pymysql import pyodbc from application.common.constants import APIMessages, SupportedDBType, \ GenericStrings def connection_check(db_type_id, db_hostname, db_username, db_password, db_name): """ Helper method to check the database connectivity...
4,981
1,470
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///db.sqlite3') Session = sessionmaker(engine) import sys sys.path.append("D:\\Users\\furea2\\NodejsProjects\\login_sample\\src\\db\\alembic\\app\\models") from problem import Problem userList=[ Problem(ti...
701
234
def uint(x): # casts x to unsigned int (1 byte) return x & 0xff def chunkify(string, size): # breaks up string into chunks of size chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): # generates and returns round constants # the round cons...
2,871
1,273
from .zip_dict import ZipDict
30
11
def modulus_three(n): r = n % 3 if r == 0: print("Multiple of 3") elif r == 1: print("Remainder 1") else: assert r == 2, "Remainder is not 2" print("Remainder 2") def modulus_four(n): r = n % 4 if r == 0: print("Multiple of 4") elif r == 1: p...
546
214
# =========================================================================== # # DATA EXPLORER # # =========================================================================== # # =========================================================================== # ...
17,038
4,582
from pyrogram import Client ,filters import os from py_youtube import Data, Search from pyrogram.types import * TOKEN = os.environ.get("TOKEN", "") APP_ID = int(os.environ.get("APP_ID", "")) API_HASH = os.environ.get("API_HASH", "") app = Client( "yt-search", bot_token = TOKEN, api_id =API_ID , api_hash =...
1,080
392
import numpy as np import keras import spacy from sklearn.feature_extraction.text import CountVectorizer from sklearn.exceptions import NotFittedError from keras.models import Sequential from keras.layers import BatchNormalization, Conv1D, Dense, Embedding from keras.layers.pooling import GlobalMaxPooling1D from keras....
7,582
2,174
from paste.deploy import loadapp app = loadapp("config:/home/webenmr/WebENMR/development.ini")
96
33
""" Contains classes to handle batch data components """ class ComponentDescriptor: """ Class for handling one component item """ def __init__(self, component, default=None): self._component = component self._default = default def __get__(self, instance, cls): try: if ...
2,548
683
#-*- coding:utf-8 -*- from .apps import db class User(db.Model): __tablename__ = 'user' user_id = db.Column(db.Integer, primary_key=True) user_count = db.Column(db.String(100), unique=True) user_name = db.Column(db.String(100), unique=True) user_sex = db.Column(db.String(100)) user_pwd = db.C...
708
279
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 7 03:26:16 2019 @author: sodatab MITx: 6.00.1x """ """ 03.6-Finger How Many --------------------- Consider the following sequence of expressions: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals...
834
288
BASE_FILES = "C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\" BASE_FILES_GENERAL = BASE_FILES + "general\\" G1 = BASE_FILES + "t_graph_1.ttl" G1_NT = BASE_FILES + "t_graph_1.nt" G1_TSVO_SPO = BASE_FILES + "t_graph_1.tsv" G1_JSON_LD = BASE_FILES + "t_graph_1.json" G1_XML = BASE_FILES + "t_graph_1.xml" G1_N3 = B...
1,569
711
# Copyright Amazon.com, Inc. or its affiliates. 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 # http://www.apache.org/licenses/LICENSE-2.0 # Unle...
23,265
6,272
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # from setuptools import setup, find_packages setup( name='alarm_process_connectivity', version='0.1dev', packages=find_packages(), entry_points = { 'contrail.analytics.alarms': [ 'ObjectCollectorInfo = alarm_proces...
793
224
import asyncio import os from localization import LocalizationManager from services.dialog.queue_picture import queue_graph from services.lib.config import Config from services.lib.db import DB from services.lib.depcont import DepContainer async def q_points(d: DepContainer): image = await queue_graph(d, d.loc_m...
813
285
""" Base class for fenpei job; this should be considered abstract. Your custom job(s) should inherit from this job and extend the relevant methods, such as:: * is_prepared * is_complete * prepare * start * result * summary """ from re import match from sys import stdout from bardeen.system import mkdirp from time i...
8,482
3,242
val = int(input("Valor:")) soma = val maior = val menor = val for i in range(0,9): val = int(input("Valor:")) if val>maior: maior = val if val<menor: menor=val soma+=val print("O maior valor é:",maior) print("O menor valor é:",menor) print("A média é:",(soma/10))
303
125
from http import HTTPStatus from waterbutler.core.exceptions import ProviderError class GitHubUnsupportedRepoError(ProviderError): def __init__(self, dummy): """``dummy`` argument is because children of ``WaterButlerError`` must be instantiable with a single integer argument. See :class:`waterbu...
746
182
"""updates the encyclopedia section in the mkdocs.yml should be run whenever a file is removed or added into the directory""" import os import yaml ABSFILEPATH = os.path.dirname(os.path.realpath(__file__)) FILEARRAY = os.listdir(ABSFILEPATH + '/docs/Encyclopedia/pages') FILEARRAY = sorted(FILEARRAY, key=str.lower) ...
899
326
""" This file is part of nucypher. nucypher 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 3 of the License, or (at your option) any later version. nucypher is distributed in the hope that it wil...
3,056
942
#!/usr/bin/env python import sys import os import re import json import traceback import anchore.anchore_utils # main routine try: config = anchore.anchore_utils.init_query_cmdline(sys.argv, "params: all\nhelp: shows dockerfile lines.") except Exception as err: print str(err) sys.exit(1) if not config:...
1,550
514
import uuid from spikeforest import mdaio import io import base64 import vdomr as vd import os import numpy as np import mtlogging import time import traceback source_path = os.path.dirname(os.path.realpath(__file__)) def _mda32_to_base64(X): f = io.BytesIO() mdaio.writemda32(X, f) return base64.b64encod...
2,258
800
import torch from torch import nn from torch.autograd import grad from torch.autograd.functional import jacobian from scipy.optimize import root from ceem.dynamics import * from ceem.nn import LNMLP from ceem.utils import temp_require_grad from tqdm import tqdm from delsmm.lagsys import AbstractLagrangianSystem import ...
5,968
2,099
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence import pdb import math torch.manual_seed(1) class GRUAudio(nn.Module): def __init__(self, num_features, hidden_dim, num_layers, dropout_rate, num_labels, batch_size, bidirectional=False): ...
16,642
5,799
print(("F"*6+"DCBAA")[int(input())//10])
40
22
# Copyright 2021 TileDB Inc. # Licensed under the MIT License. import numpy as np import pytest from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype netCDF4 = pytest.importorskip("netCDF4") @pytest.mark.parametrize( "input_dtype,scale_factor,add_offset,output_dtype", ( ...
2,596
911
#!/usr/bin/env python import os import numpy as np import html from bs4 import BeautifulSoup import bibtexparser from bibtexparser.bparser import BibTexParser from bibtexparser.customization import convert_to_unicode import eyed3 from tokenizer import MyTokenizer # acronyms to spell out acronyms = [ 'LES', ...
9,091
2,644
import os import re import subprocess tag = os.getenv('GITHUB_REF_NAME') if tag is None: raise Exception("GITHUB_REF_NAME is not defined") with open("tag_body.txt", "w") as file: output = subprocess.check_output(["git", "tag", "-l", "--format='%(contents)'", tag], stdin=None, stderr=None, shell=False) m...
529
189
"""This module contains the views exposed to the user.""" from django.http import HttpResponse from rest_framework.decorators import api_view from rest_framework.request import Request from api.view_handlers import ( handle_get_trained_city_model, handle_persist_sight_image, handle_add_new_city, handle_...
3,456
990
import requests, json, argparse, os from termcolor import colored parser = argparse.ArgumentParser(description="Verify the recipes by running them through CyberSaucier") parser.add_argument('--rulefolder', help='Folder containing the json recipes') parser.add_argument("--url", help="URL to CyberSaucier", default="http...
1,154
335
import os import pytest from dsplot.errors import InputException from dsplot.tree import BinaryTree def test_binary_tree(): tree = BinaryTree(nodes=[5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]) assert tree.root.val == 5 assert tree.root.right.left.val == 13 assert tree.root.right.right.left.v...
761
335