text string | size int64 | token_count int64 |
|---|---|---|
"""solved, easy"""
class Solution:
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
unique = set()
for email in emails:
index = email.find("@")
unique.add(
email[:index].split("+")[0].replace(".",... | 592 | 195 |
from _version import __version__
###############################################
# Constants | Logo and help messages
###############################################
VERSION = f'v{__version__}'
USAGE = 'Usage: %prog [options] arg'
EPILOG = 'Example: dripper -t 100 -m tcp-flood -s tcp://192.168.0.1:80'
GITHUB_OWNER = '... | 4,401 | 2,083 |
from abc import ABC, abstractmethod
class AbstractModel(ABC):
def __init__(self):
pass
@abstractmethod
def fit(self, X, y, *args, **kwargs):
raise NotImplementedError
@abstractmethod
def transform(self, X):
raise NotImplementedError
def fit_trasform(self, X, y):
... | 415 | 133 |
# Copyright (c) 2021, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | 3,481 | 1,057 |
import itertools
import json
import re
from functools import partial
from itertools import chain
from typing import Tuple, List
import requests
from etl.common.utils import join_url_path, remove_falsey, replace_template, remove_none, is_collection
from pyhashxx import hashxx
class BreedingAPIIterator:
"""
It... | 5,798 | 1,714 |
"""Provides read-only interfaces to configuration backends."""
| 64 | 17 |
# coding: utf-8
import sys
import warnings
sys.path.insert(0, '.')
sys.path.insert(0, '..')
import os
import pandas as pd
import czsc
from czsc.analyze import KlineAnalyze, find_zs
from czsc.signals_v1 import KlineSignals
warnings.warn("czsc version is {}".format(czsc.__version__))
cur_path = os.path.split(os.path.... | 752 | 319 |
"""Module for counterbalancing and shuffling trial types, conditions,
experimental blocks, etc.
""" | 99 | 26 |
"""This module is responsible for a visual representation of the model data"""
from calendar import Calendar
from rich.console import Console
from rich.style import Style
from rich.table import Table
from clocker import converter
from clocker.model import AbsenceType, WorkDay
from clocker.statistics import... | 4,215 | 1,341 |
# coding: utf-8
import os
import re
from clocwalk.libs.core.common import recursive_search_files
from clocwalk.libs.core.data import logger
__product__ = 'Java'
__version__ = '0.1'
"""
https://docs.gradle.org/current/dsl/org.gradle.api.Project.html#N14F2A
https://docs.gradle.org/current/javadoc/org/gradle/api/Proje... | 6,669 | 1,976 |
## Functions for to train action optimization model ##
import os
import json
from datetime import datetime
import numpy as np
import tensorflow.keras.backend as K
from tensorflow import keras
from jsmp.query_pq import query_train_pq, query_preds_pq
from jsmp.eval_tools import compute_utility
def __profit_maximizer__... | 6,325 | 2,046 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: schema.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf... | 31,821 | 12,124 |
import os
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException
IG_EMAIL = os.environ.get("IG_EMAIL")
IG_PWD = os.environ.get("IG_PWD")
SIMILAR_ACCOUNT ... | 2,850 | 854 |
import traceback
import urllib2
import urlparse
class ConnectivityManager(object):
cache = {}
# def __init__(self):
# super(ConnectivityManager, self).__init__()
# self.cache = {}
def is_connectable(self, url):
# server_url = self.get_server(url)
server_url = url
... | 855 | 247 |
def test_dynamic_item_dataset():
from speechbrain.dataio.dataset import DynamicItemDataset
import operator
data = {
"utt1": {"foo": -1, "bar": 0, "text": "hello world"},
"utt2": {"foo": 1, "bar": 2, "text": "how are you world"},
"utt3": {"foo": 3, "bar": 4, "text": "where are you wo... | 3,451 | 1,241 |
# -*- coding: utf-8 -*-
import yt.mods as yt
import numpy as np
mu0 = 1.25663706e-6
gamma = 1.6666
@yt.derived_field(take_log=False, units=r'kg m^{-3}')
def density(field, data):
return data['density_pert'] + data['density_bg']
@yt.derived_field(take_log=False, units=r'T')
def mag_field_x(field, data):
retur... | 5,015 | 2,222 |
# encoding=utf-8
import time, os, sys
import json
import mmcv
from collections import defaultdict
from mmdet.apis import init_detector, inference_detector
import numpy as np
# from tqdm import tqdm
import cv2
import datetime, time
from collections import defaultdict
def get_jpg(path, list1):
for root, filedir, fi... | 11,536 | 4,104 |
### This code is for comparing the performance of L2, L1 regularized
### RFSVM and KSVM.
import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import tr... | 3,351 | 1,394 |
from django import forms
from django.forms import ModelForm
from .models import Todo, STATUS, PRIORITY
class CreateTodo(ModelForm):
priority = forms.ChoiceField(choices=PRIORITY, widget=forms.RadioSelect())
task = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control'}))
descriptio... | 507 | 153 |
n = int(input())
odd_set = set()
even_set = set()
for i in range(1, n + 1):
name = input()
summed = sum([ord(x) for x in name]) // i
if summed % 2 == 0:
even_set.add(summed)
else:
odd_set.add(summed)
odd_sum = sum(odd_set)
even_sum = sum(even_set)
if odd_sum == even_sum:
union_va... | 663 | 253 |
# ===============================================================================
# Copyright 2014 Jake Ross
#
# 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... | 2,126 | 568 |
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.constant([[1, 2, 3],
[3, 2, 1],
[-1,-2,-3]])
boolean_tensor = tf.constant([[True, False, True],
[False, False, True],
[True, False, False]])
tf.redu... | 692 | 228 |
from django.db import models
# TODO Create any models needed for the blog application.
| 89 | 22 |
# Copyright (c) 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
import pytest
... | 4,693 | 1,607 |
chars = "☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■? "
cols = 8
rows = 256//cols
table = list("" for n... | 609 | 453 |
import deoplete.util as util
def test_pos():
assert util.bytepos2charpos('utf-8', 'foo bar', 3) == 3
assert util.bytepos2charpos('utf-8', 'あああ', 3) == 1
assert util.charpos2bytepos('utf-8', 'foo bar', 3) == 3
assert util.charpos2bytepos('utf-8', 'あああ', 3) == 9
def test_custom():
custom = {'sourc... | 2,044 | 757 |
from ..dojo_test_case import DojoTestCase
from dojo.models import Test
from dojo.tools.meterian.parser import MeterianParser
class TestMeterianParser(DojoTestCase):
def test_meterianParser_invalid_security_report_raise_ValueError_exception(self):
with self.assertRaises(ValueError):
testfile =... | 4,536 | 1,495 |
import tensorflow as tf
class rFFTPooling2D(tf.keras.layers.Layer):
'''
Pooling in frequency domain by truncating higher frequencies. Layer input is asumed to be in spatial domain.
args:
- isChannelFirst: True or False. If True, input shape is assumed to be [batch,channel,height,width]. If False, input sha... | 3,781 | 1,200 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for gluon.sql
"""
import sys
import os
if os.path.isdir('gluon'):
sys.path.append(os.path.realpath('gluon'))
else:
sys.path.append(os.path.realpath('../'))
import unittest
import datetime
from dal import DAL, Field, Table, SQLALL
ALLOWED_DATATY... | 18,258 | 6,695 |
from collections import defaultdict
import csv
import json
import math
import os
import argparse
def list_files(names):
for i, name in enumerate(names):
print(i, name)
def main(names):
rels = defaultdict(defaultdict)
general = dict()
for name in names:
try:
with open(logs... | 3,110 | 1,100 |
"""
Use this script to run scenarios for TOU optimization
involving merit order plants for summer and winter months.
Generates input data necessary for optimization in each scenario
and runs optimization.
"""
import os
from tou_merit_order_optimization import RunModel
from pemv1 import GeneratePEM
import pandas as ... | 4,197 | 1,438 |
numeros = list()
n = 0
while n != -1:
n = int(input('Digite um número [para sair digite -1]: '))
if n in numeros:
print('O número já existe na lista!')
elif n != -1:
numeros.append(n)
print(sorted(numeros)) | 242 | 95 |
import logging
import numpy as np
import megengine.module as M
import megengine.functional as F
import megengine as mge
def pad_list(xs, pad_value):
"""Perform padding for the list of tensors."""
n_batch = len(xs)
max_len = max(x.size(0) for x in xs)
pad = xs[0].new(n_batch, max_len, *xs[0].size()[1:]... | 1,268 | 482 |
import os
import datetime
from jira import JIRA
import logging
from alerta.exceptions import ApiError
try:
from alerta.plugins import app # alerta >= 5.0
except ImportError:
from alerta.app import app # alerta < 5.0
from alerta.plugins import PluginBase
LOG = logging.getLogger('alerta.plugins.jira')
JIRA_AP... | 3,513 | 1,162 |
"""
This is is a part of the DeepLearning.AI TensorFlow Developer Professional Certificate offered on Coursera.
All copyrights belong to them. I am sharing this work here to showcase the projects I have worked on
Course: Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning
... | 3,324 | 1,222 |
import numpy as np
from matplotlib import pyplot as plt
from sklearn.manifold import TSNE
import torch
def clean_plot():
ax = plt.subplot(111)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
... | 7,169 | 2,909 |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import math
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
match_mask_color = 255
cv2.fillPoly(mask, vertices, match_mask_color)
masked_image = cv2.bitwise_and(img, mask)
return masked_i... | 2,765 | 1,111 |
# Copyright © VASP Software GmbH,
# Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
def add(doc_string):
def add_documentation_to_function(func):
func.__doc__ = doc_string
return func
return add_documentation_to_function
| 283 | 93 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author : Heethesh Vhavle
Email : heethesh@cmu.edu
Version : 1.0.0
Date : Apr 13, 2019
'''
# Python 2/3 compatibility
from __future__ import print_function, absolute_import, division
# ROS modules
import rospy
# ROS messages
from geometry_msgs.msg import Point
... | 6,007 | 2,088 |
from policy.policy import Policy
import os
import numpy as np
import pcp_utils
from pcp_utils.utils import Config
from pcp_utils.load_ddpg import load_policy
class PenincupController(Policy):
class Config(Config):
policy_name = "pen_in_cup_controller"
policy_model_path = ""
model_name = No... | 6,491 | 2,111 |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.12.0
# kernelspec:
# display_name: 'Python 3.7.7 64-bit (''.venv'': poetry)'
# name: python3
# ---
# %% [markdown]
# # Slope distributions
#
... | 5,813 | 2,549 |
"""
***************************************************************************************
© 2019 Arizona Board of Regents on behalf of the University of Arizona with rights
granted for USDOT OSADP distribution with the Apache 2.0 open source license.
*********************************************************... | 2,792 | 1,335 |
from _hashlib import new
import pickle
import random
from scipy.special import expit
import matplotlib.pyplot as plt
import numpy as np
from tentacle.board import Board
from tentacle.dfs import Searcher
from tentacle.dnn3 import DCNN3
from tentacle.game import Game
from tentacle.mcts import MonteCarlo
from tentacle.m... | 15,939 | 5,215 |
import argparse
import logging
import os
import subprocess
from io import StringIO
import pandas as pd
import configs
import utils
from datahandler import DataHandler
from dgc import DGC
def main(tag, seed, dataset):
opts = getattr(configs, 'config_%s' % dataset)
opts['work_dir'] = './results/%s/' % tag
... | 2,296 | 832 |
from django.core.management.base import BaseCommand, CommandError
from webui.models import BuildConfiguration
class Command(BaseCommand):
help = 'Get debian package version by build_conf id'
def handle(self, *args, **options):
self.stdout.write("{0}\n".format(BuildConfiguration.objects.get(pk=args[0]... | 331 | 93 |
import torch
import torchvision
from torch import nn
from torch.nn import Conv2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
dataset = torchvision.datasets.CIFAR10("./data", train=False, transfo... | 1,164 | 441 |
from pathlib import Path
from shutil import rmtree
from typing import List, Union
def clean_dir(path_to_clean: Union[str, Path], exception: List[str]) -> None:
"""
Removes all files and directories in the given path if they don't match the exception list.
Parameters
----------
path_to_clean : Uni... | 873 | 260 |
from .arena import *
from .channel import *
from twitchbot.api.chatters import *
from .colors import *
from .command import *
from .config import *
from .enums import *
from .irc import *
from .message import *
from .permission import *
from .ratelimit import *
from .regex import *
from .util import *
from .database im... | 1,295 | 420 |
# Copyright (c) 2021 PaddlePaddle Authors. 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 ... | 5,114 | 1,708 |
class _Node:
""" Class for the Node instances"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class LinkedList:
""" Class for the LinkedLists instances"""
def __init__(self):
"""Method to iniate a LinkedList"""
self.head =... | 2,759 | 767 |
from os import path
from utils import call_file_op
from pyinfra import host, local, state
from pyinfra.api import deploy
from pyinfra.operations import files, server
@deploy('My nested deploy')
def my_nested_deploy(state, host):
server.shell(
name='First nested deploy operation',
commands='echo ... | 1,993 | 609 |
from fabric.api import *
@task
def release():
local('python setup.py sdist upload')
local('python setup.py sdist upload -r lime')
local('python setup.py bdist_wheel upload')
local('python setup.py bdist_wheel upload -r lime')
| 244 | 79 |
#!python
# for GHEdit comment
import sys, getopt, os
from pydispatch import dispatcher
import gluserver
import glugit
def usage():
print 'Usage : glu [<options>]... [<query>] [<repository>]'
print '\t-h, --help\t\tPrint this message.'
print '\t-s, --server\t\tExcute with server-mode.'
print '\t-q\t\t\tQuery strin... | 1,632 | 683 |
"""
***************************************
MCSH - A Minecraft Server Helper.
Coded by AllenDa 2020.
Licensed under MIT.
***************************************
Module name: MCSH.first_time_setup
Module Revision: 0.0.1-18
Module Description:
Guides the user through first-time setup routines.
"""
from MCSH.c... | 2,083 | 644 |
import random
import time
from hashlib import sha1
random.seed()
WORDLIST = {
'adjective': [
'angenehm', 'attraktiv', 'aufmerksam', 'bunt', 'blau', 'charmant',
'dankbar', 'edel', 'frei', 'gelb', 'glatt', 'hell', 'ideal', 'jung',
'leicht', 'lieb', 'luftig', 'mutig', 'nah', 'neu', 'offen', '... | 1,640 | 633 |
import datetime
import pytz
utc = pytz.UTC
class PhotosGroupedByDate:
def __init__(self, location, date, photos):
self.photos = photos
self.date = date
self.location = location
def get_photos_ordered_by_date(photos):
from collections import defaultdict
groups = defaultdict(lis... | 1,091 | 325 |
#!/usr/bin/env python
from ethereum.tools import tester
from ethereum.tools.tester import TransactionFailed
from pytest import fixture, raises
from utils import stringToBytes, EtherDelta, TokenDelta
def test_mailbox_eth_happy_path(localFixture, mailbox):
# We can send some ETH to the mailbox
with EtherDelta(1... | 3,976 | 1,318 |
OP_FALSE = 0
OP_0 = 0
OP_PUSHDATA1 = 0x4c
OP_PUSHDATA2 = 0x4d
OP_PUSHDATA4 = 0x4e
OP_1 = 0x51
OP_2 = 0x52
OP_3 = 0x53
OP_RETURN = 0x6a
OP_DUP = 0x76
OP_EQUAL = 0x87
OP_EQUALVERIFY = 0x88
OP_HASH160 = 0xa9
OP_CHECKMULTISIG = 0xae
... | 1,817 | 761 |
# Copyright 2018 Google 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 to in writing, ... | 1,565 | 473 |
__author__ = 'seb'
| 20 | 11 |
import numpy as np
from random import shuffle
anno_file_path = 'anno/celeba_id_landmark_anno.txt'
train1_anno_file_path = 'anno/celeba_train1_anno.txt'
train2_anno_file_path = 'anno/celeba_train2_anno.txt'
test1_anno_file_path = 'anno/celeba_test1_anno.txt'
test2_anno_file_path = 'anno/celeba_test2_anno.txt'
total_id... | 4,222 | 2,041 |
from flask import Flask, jsonify, render_template
import pypyodbc
import os
import numpy as np
import io
import base64
from pandas import datetime
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.cross_validation import train_test_split
from skle... | 2,766 | 1,001 |
from __future__ import absolute_import, unicode_literals
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from mayan.apps.acls.models import AccessControlList
from mayan.apps.django_gpg.models import Key
from mayan.ap... | 6,852 | 1,911 |
"""Simple run script using SORunner."""
import torch.optim as optim
import deepobs.pytorch as pyt
from sorunner import SORunner
from probprec import Preconditioner
import numpy
import math
class PreconditionedSGD(Preconditioner):
"""docstring for PreconditionedSGD"""
def __init__(self, *args, **kwargs):
... | 2,353 | 822 |
"""Recursive function to generate fibonacci series"""
def recursive_fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return(recursive_fib(n-1) + recursive_fib(n-2))
print("Enter the number of terms : ")
n=int(input())
print("Fibonacci series is given by: ")
"""Recurs... | 586 | 243 |
from GenericRequest import GenericRequest
from kol.manager import PatternManager
STARTSWITH = 1
CONTAINS = 2
ENDSWITH = 3
class SearchPlayerRequest(GenericRequest):
def __init__(self, session, queryString, queryType=STARTSWITH, pvpOnly=False, hardcoreOnly=None, searchLevel=None, searchRanking=None):
super... | 1,469 | 416 |
import pandas as pd
import argparse
from pathlib import Path
import hail as hl
import utils
'''Runs fisher's test on variants found in protein domain (includes MPC>=2 and AF_NFE=0).'''
def calculate_fishers(case_carrier, control_carrier, case_noncarrier, control_noncarrier):
'''Runs fisher's test one one gene an... | 3,830 | 1,388 |
from hetbuilder.algorithm import CoincidenceAlgorithm
from hetbuilder.plotting import InteractivePlot
# we read in the structure files via the ASE
import ase.io
bottom = ase.io.read("graphene.xyz")
top = ase.io.read("MoS2_2H_1l.xyz")
# we set up the algorithm class
alg = CoincidenceAlgorithm(bottom, top)
# we run the... | 560 | 208 |
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.detail import DetailView
from django.views.generic import ListView, View
import logging
import j... | 3,114 | 883 |
import warnings
from netcdf_scm.errors import raise_no_iris_warning
def test_raise_no_iris_warning():
expected_warn = (
"A compatible version of Iris is not installed, not all functionality will "
"work. We recommend installing the lastest version of Iris using conda to "
"address this."
... | 523 | 163 |
import json
import falcon
class Resource:
def on_get(self, req, resp):
users = {
'users': [
{
'name': 'Admin',
'email': 'admin@example.com'
}
]
}
resp.body = json.dumps(users, ensure_ascii=Fal... | 363 | 109 |
import argparse
import glob
import math
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numba import jit, prange
from sklearn import metrics
from utils import *
@jit(nopython=True, nogil=True, cache=True, parallel=True, fastmath=True)
def compute_tp_tn_fp_fn(y_true,... | 13,852 | 4,827 |
def explode(bomb_r, bomb_c, size, m):
bomb = m[bomb_r][bomb_c]
for row in range(bomb_r - 1, bomb_r + 2):
for col in range(bomb_c - 1, bomb_c + 2):
current_pos = [row, col]
if is_valid(current_pos, size) and matrix[current_pos[0]][current_pos[1]] > 0:
m[current_pos... | 1,167 | 473 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from common.layer_test_class import check_ir_version
from common.onnx_layer_test_class import Caffe2OnnxLayerTest
from unit_tests.utils.graph import build_graph
class TestReshape(Caffe2OnnxLayerTest):
def create_resh... | 11,784 | 3,881 |
# BSD 3-Clause License
#
# Copyright (c) 2018 Rigetti & Co, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
... | 4,893 | 1,919 |
# proxy module
from __future__ import absolute_import
from codetools.contexts.adapter.unit_converter_functions import *
| 120 | 34 |
from yaml import safe_load as load
import requests
print('Fetching the SHA for live BinderHub and repo2docker...')
# Load master requirements
url_requirements = "https://raw.githubusercontent.com/jupyterhub/mybinder.org-deploy/master/mybinder/requirements.yaml"
requirements = load(requests.get(url_requirements).text)... | 2,356 | 880 |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import seq_merge
expected_verilog = """
module test;
reg CLK;
reg RST;
blinkled
uut
(
.CLK(CLK),
.RST(RST)
);
reg reset_done;
initial begin
CLK = 0;
forever begin
#5 CLK = !CLK;
... | 1,828 | 835 |
'''Train model'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import memn2n.model
import memn2n.util
FLAGS = tf.app.flags.FLAG... | 6,293 | 2,116 |
from setuptools import setup, find_packages
with open('README.md') as f:
long_description = ''.join(f.readlines())
setup(
name='ghia_volekada',
version='0.6',
description='GitHub issues assignment tool',
long_description=long_description,
author='Adam Volek',
author_email='volekada@fit.c... | 1,085 | 345 |
import numpy as np
import glob,sys,os
import matplotlib.pyplot as plt
from itertools import product
from quspin.basis import spin_basis_general,tensor_basis
from quspin.operators import hamiltonian
from quspin.tools.evolution import evolve
from quspin.basis.transformations import square_lattice_trans
from tilted_squar... | 4,019 | 1,824 |
from django.db import models
# Here we implement a custom profiled user, this user extends the
# django's AbstractUser, the parent class handles all the authentification
# process whereas this class adds some fields.
| 219 | 52 |
class Person:
id = int()
name = str()
lastname = str()
photo = str()
bdate = str()
def __init__(self, id, name, lastname, photo, bdate):
self.id = id
self.name = name
self.lastname = lastname
self.photo = photo
self.bdate = bdate
def gets(self):
... | 1,121 | 371 |
#
# Copyright (c) 2022 TUM Department of Electrical and Computer Engineering.
#
# This file is part of MLonMCU.
# See https://github.com/tum-ei-eda/mlonmcu.git for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... | 5,317 | 1,523 |
import sqlite3
import logging
from brunodb.sqlite_utils import get_db
from brunodb.database_generic import DBaseGeneric
from brunodb.format_query import format_sql_in_context
logger = logging.getLogger(__file__)
def db_is_open(db):
try:
db.execute('SELECT 1')
except sqlite3.ProgrammingError:
... | 1,157 | 367 |
def reformat(value):
chars = {"Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ä": "ae", "ö": "oe", "ü": "ue", "\\": "/"}
for char in chars:
value = value.replace(char, chars[char])
return value
| 200 | 81 |
import mock
import pytest
from werkzeug.datastructures import MultiDict
from app.main.helpers import search_helpers, framework_helpers
from ...helpers import BaseApplicationTest
def test_should_hide_both_next_and_prev_if_no_services():
assert not search_helpers.pagination(0, 100)["show_prev"]
assert not sear... | 10,202 | 3,321 |
from promval.extractor import AggregationGroupExtractor
def test_aggregation_group_extractor():
expr = """
avg by (first, second)(metric{label='thing'})
"""
extractor = AggregationGroupExtractor()
items = extractor.extract(expr)
assert items == [["first", "second"]]
def test_aggregation_... | 846 | 260 |
class Node(object):
"""Generic tree node."""
def __init__(self, name):
self.name = name
self.parent = None
self.children = []
def __repr__(self):
return "Node(" + self.name + ")"
def add_parent(self, node):
assert isinstance(node, Node)
self.parent = nod... | 1,840 | 574 |
#
# Enthought product code
#
# (C) Copyright 2013-2016 Enthought, Inc., Austin, TX
# All right reserved.
#
from textwrap import dedent
# Local imports
from .template import Template
class VueTemplate(Template):
"""A template for vue.js templates. Note that this assumes that the
ViewModel is attached to the... | 1,375 | 376 |
# -*- coding: utf-8 -*-
from django.core.mail import EmailMultiAlternatives
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import render_to_string
from nopassword.backends.base import NoPasswordBackend
class EmailBackend(NoPasswordBackend):
template_name = 'registration/l... | 1,137 | 332 |
import argparse
import socket
from time import time
from proto.announcement_pb2 import Announcement
RECEIVE_TIMEOUT_SECONDS = 0.2
def receive_announcements(port: int, duration: int) -> [Announcement]:
"""
Returns a list of Announcements, without duplicates received within a time window of 4s on a specified ... | 1,939 | 591 |
SAMPLE_ALLOWED_SCHEMAS = ['sample/sample-v1.0.0.json']
SAMPLE_PREFERRED_SCHEMA = 'sample/sample-v1.0.0.json'
| 109 | 57 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Model tests."""
from __future__ import absolute_import, print_function
import p... | 14,794 | 4,666 |
import cloudscraper
from bs4 import BeautifulSoup
from urllib.parse import unquote, quote
import requests, json, re
def parseTable(table):
columns = list([x.string for x in table.thead.tr.find_all('th')])
rows = []
for row in table.tbody.find_all('tr'):
values = row.find_all('td')
if ... | 8,576 | 2,649 |
# -*- coding: utf-8 -*-
"""
Linked Books
Parser that extracts annotations (i.e. files with annotations) and export a series of pickle objects to be used by patter matching facilities
Exports:
1- lines with citations and without citations for Sup and Unsup extraction of lines with citations
2- annotations and list of ... | 15,048 | 4,503 |
from datasets.dataset import ConcatDataset, MultiDataset, unique_header
from builders.dataloader_builder import build_collate_fn, ERROR_STRING
from torch.utils.data import DataLoader
from datasets.utils import make_dataset_default, cv2_loader
from samplers.sequential_sampler import SequentialSampler
from samplers.batch... | 9,424 | 3,322 |
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7116
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print '... | 495 | 220 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 17:10:26 2020
@author: Ethan
Markers:
bmi_start
prepare
nothing, imagine, or move
relax
bmi_end
"""
def bmi_main():
import numpy as np
import matplotlib.pyplot as plt
import time, reiz, liesl
from reiz.visua... | 4,073 | 1,677 |
import base64
from io import BytesIO
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import floris.tools as wfct
import matplotlib.pyplot as plt
import reusable_components as rc # see reusable_components.py
# ############ Create ... | 5,273 | 2,015 |