text string | size int64 | token_count int64 |
|---|---|---|
from rest_framework import mixins
from rest_framework_mongoengine import viewsets
from happ.serializers import FeedbackMessageSerializer
class FeedbackMessageViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
serializer_class = FeedbackMessageSerializer
def perform_create(self, serializer):
... | 362 | 101 |
import numpy as np
class Metrics:
def __init__(self):
super(Metrics, self).__init__()
def _levenshtein_distance(self, ref, hyp):
"""
:param ref: First sequence and or sentence (sequence of words)
:param hyp: Second sequence and or sentence (sequence of words)
... | 5,058 | 1,435 |
class Node():
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_balanced(self):
root = self
height_left = root.left.tree_height()
height_right = root.right.tree_height()
if abs(height_right - height_left > 1):
return False
ret... | 946 | 415 |
import numbers
from typing import Union, List
import numpy
import torch
EPSILON = torch.finfo(torch.float32).eps
__all__ = ["ComplexTensor"]
class ComplexTensor:
def __init__(
self, real: Union[torch.Tensor, numpy.ndarray], imag=None, device=None
):
if imag is None:
if isinstance... | 23,221 | 7,396 |
import trio
from trio_websocket import serve_websocket, ConnectionClosed
import sys
import names
class SetOfNames:
def __init__(self, server_name):
self.server_name = server_name
self.dict_of_names = {}
who_is_who = SetOfNames('Server Ben')
async def echo_server(request):
print("ECHO... | 1,724 | 557 |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
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 agre... | 8,638 | 2,496 |
from addaction import AddAction
from showaction import ShowAction
from getaction import GetAction
from listaction import ListAction
| 132 | 29 |
"""
This module allows to write a PDF object structure in a file stream. An object
structure consists of containers (dictionaries, lists, sets and tuples)
embedded in one another and other objects. This module also works on
structures that do not contain PDF objects.
"""
from PyPDF2.generic import BooleanObject, Dict... | 5,568 | 2,324 |
# -*- coding: utf-8 -*-
from django import forms
from django.test import TestCase
from ..models import CustomField, CustomFieldTypes
from .models import SomeModel
class CustomFieldModelsTestCase(TestCase):
def setUp(self):
self.sm1 = SomeModel.objects.create(name='abc')
self.sm2 = SomeModel.objec... | 1,459 | 439 |
# -*- coding: utf-8 -*-
"""hw1_310555029.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1JRZxfH5avZg0896ddvxZSfm2lUtMGKSu
#Linear Regression
##(0) Load the data -> Standardize data -> Split the dataset
"""
import numpy as np
import pandas as ... | 9,628 | 3,971 |
#### prime , even and odd number #####
# l=int(input("How many input do you need :"))
# x=[]
# y=[]
# z=[]
# b=[]
# for p in range (l):
# t=int(input("Enter the number :"))
# x.append(t)
# for i in x:
# if i > 1:
# for j in range(2,i):
# if i%j==0:
# break
# else... | 5,959 | 2,724 |
# Copyright 2016 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.
from analysis.analysis_testcase import AnalysisTestCase
from analysis.callstack_detectors import StartOfCallStack
from analysis.stacktrace import FunctionLin... | 16,380 | 5,549 |
# For building the Gaussioan Naive Bayes classifier, Iris dataset from Scikit Learn is being used.
from sklearn.datasets import load_iris
# Importing necessary scikit learn libraries
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy... | 327 | 92 |
# -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/5/12 13:16
# @author :Mo
# @function :chatbot based search, encode sentence_vec by bert
def chatbot_sentence_vec_by_bert_own():
"""bert encode is writted by my own"""
from FeatureProject.bert.extract_keras_bert_feature import KerasBertVecto... | 86,336 | 82,612 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import cntk as C
import numpy as np
import onnx
import os
model_file = 'model.onnx'
data_dir = 'test_data_set_0'
def SaveTensorProto(file_path, variable, data):
tp = onnx.TensorProto()
tp.name = variable.uid
for... | 2,663 | 1,021 |
import os
from setuptools import setup,find_packages
project_name = "SuperDiffer"
__version__ = "1.0.0"
__author__ = "Gabriel Oliveira"
__author_email__ = "gabriel.pa.oliveira@gmail.com"
__author_username__ = "gpaOliveira"
__description__ = "REST Service to calculate the difference between two input string... | 1,528 | 476 |
from django.conf.urls import url
from django.views.generic import RedirectView
from .views import (
NewCreditsView, ProcessingCreditsView,
ProcessedCreditsListView, ProcessedCreditsDetailView,
SearchView,
CashbookFAQView,
CashbookGetHelpView, CashbookGetHelpSuccessView,
)
urlpatterns = [
url(r... | 1,134 | 405 |
# coding: utf-8
# In[ ]:
from bs4 import BeautifulSoup
import csv
# In[ ]:
import requests
import pandas as pd
from time import sleep
# In[ ]:
brand = ' '
# header =['BRANDS', 'PRODUCT TITLE', 'PRODUCT GROUP', 'PRODUCT CODE',
# 'PRICE', 'PRODUCT IMAGE','PRODUCT', 'DESCRIPTION']
# with open('product... | 3,871 | 1,365 |
import re
w = 'AbcDefgHijkL'
ws= ' .nalf!!213knlsc'
wd =' ca++ and mbbs '
loc ='mumbai dombivli'
r = re.findall('([A-Z])', w)
print(r)
r = re.findall('([A-Z][a-z]+)', w)
print(r)
r = re.findall('([a-z,A-Z,+]+)',wd)
print(r)
print(' '.join(r))
loc.find('mumcai')
join_locations = {
'ncr': ['delhi', 'fari... | 661 | 303 |
"""
Finite-difference solver for wave equation:
u_yy = u_xx.
Initial and boundary conditions:
u(x, 0) = init(x), 0 <= x <= xf,
u_y(x, 0) = d_init(x), 0 <= x <= xf,
u(0, y) = bound_x0(y), 0 <= y <= yf,
u(xf, y) = bound_xf(y), 0 <= y <= yf.
"""
import numpy as np
from scipy import linalg
... | 2,724 | 1,264 |
"""
Cloud class for authentication and connexion setup.
It allow interactions with the irbt cloud api
"""
import json
from urllib.parse import urlparse
from aws_requests_auth.aws_auth import AWSRequestsAuth
import requests
from .logger import logging
logger = logging.getLogger(__name__)
class Cloud:
"""
... | 8,822 | 2,385 |
valcasa = float(input('Qual o valor da casa? R$'))
sal = float(input('Qual o valor do seu salário? R$ '))
anos = int(input('Em quantos anos você vai pagar?'))
meses = anos * 12
valprest = valcasa / meses
if valprest >= sal * 0.3:
print('Seu empréstimo foi aprovado e o valor da prestação é de R${:.2f}'.format(valpre... | 403 | 156 |
"""Unit tests for reviewboard.reviews.views.PreviewReviewRequestEmailView."""
from __future__ import unicode_literals
from django.contrib.auth.models import User
from reviewboard.site.urlresolvers import local_site_reverse
from reviewboard.testing import TestCase
class PreviewReviewRequestEmailViewTests(TestCase):... | 3,524 | 915 |
#!/usr/bin/env python3
import typing
import re
import os.path
import enum
import json
import urllib
import argparse
import asyncio
import lxml.html
import requests
import lxml.etree
import aiohttp.client
HOME = os.path.expanduser("~")
USERNAME = "adwin_" # type: str
CONTEST_DIR = os.path.join(HOME, "algo_competition... | 10,067 | 3,073 |
"""URL Configuration."""
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from django.views.decorators.csrf import csrf_exempt
import debug_toolbar
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
from rough_trade_calendar impo... | 930 | 278 |
#line to run:
#java -classpath D:\bin\jython-2.1\jython.jar;D:\bin\eclipse331_1\plugins\org.junit_3.8.2.v200706111738\junit.jar;D:\bin\eclipse331_1\plugins\org.apache.ant_1.7.0.v200706080842\lib\ant.jar org.python.util.jython w:\org.python.pydev\pysrc\tests\test_jysimpleTipper.py
import unittest
import os
import sys
#... | 10,010 | 3,454 |
from threading import Thread
from time import time
def factorize(number):
for i in range(1, number + 1):
if number % i == 0:
yield i
class FactorizeThread(Thread):
def __init__(self, number):
super().__init__()
self.number = number
def run(self):
self.factors... | 878 | 289 |
# -*- coding: utf-8
# Collection of functions to create data for testing
import numpy as np
from datetime import datetime
import itertools
from skimage.transform import rotate
import nibabel as nib
from spinalcordtoolbox.image import Image
from spinalcordtoolbox.resampling import resample_nib
DEBUG = False # Save ... | 8,774 | 3,125 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer\main.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainW... | 7,829 | 2,713 |
from django.apps import AppConfig
class CoreBackendConfig(AppConfig):
name = 'core_backend'
| 98 | 30 |
# Copyright 2009-2012 James P Goodwin ped tiny python editor
""" module that contains the symbolic names of the keys """
import curses
KEYTAB_NOKEY=chr(0)
KEYTAB_ALTA=chr(27)+'a'
KEYTAB_ALTB=chr(27)+'b'
KEYTAB_ALTC=chr(27)+'c'
KEYTAB_ALTD=chr(27)+'d'
KEYTAB_ALTE=chr(27)+'e'
KEYTAB_ALTF=chr(27)+'f'
KEYTAB_ALTG=chr(27)+... | 13,035 | 8,226 |
from copy import deepcopy
import torch
import torch.nn.functional as F
from mmgen.models.builder import MODELS, build_module
from mmgen.models.common import set_requires_grad
from mmgen.models.gans.static_unconditional_gan import StaticUnconditionalGAN
from torch.nn.parallel.distributed import _find_tensors
from .los... | 19,438 | 5,485 |
import xml.etree.ElementTree as ET
import pytest
from localstack.utils.aws.aws_responses import to_xml
result_raw = {
"DescribeChangeSetResult": {
# ...
"Changes": [
{
"ResourceChange": {
"Replacement": False,
"Scope": ["Tags"],
... | 1,766 | 588 |
import graphene
from graphene_django.types import DjangoObjectType
from graphql_jwt.decorators import login_required
from django.contrib.auth import get_user_model
class UserType(DjangoObjectType):
""" UserType object for GraphQL """
class Meta:
model = get_user_model()
has_unreaded_messages = g... | 991 | 296 |
#!/usr/bin/env python
import yaml
import argparse
import rospy
import rospkg
import math
from joy_handle import JoyHandle, ButtonState
from sensor_msgs.msg import Joy
from ual_core.srv import TakeOff, Land, SetVelocity
from ual_core.msg import State
from geometry_msgs.msg import TwistStamped
from geometry_msgs.msg impo... | 5,393 | 1,927 |
"""
Defines general coordinate system related functions including:
- xyz_to_rtz_array(xyz)
- xyz_to_rtp_array(xyz)
- rtz_to_xyz_array(xyz)
- rtp_to_xyz_array(xyz)
- rtz_to_rtp_array(xyz)
- rtp_to_rtz_array(xyz)
- coords = cylindrical_rotation_matrix(thetar, dtype='float64')
"""
# pylint: disable=C0103
from __... | 4,910 | 2,043 |
import locale
from iso639 import languages
from iso3166 import countries
DEFAULT_LANGUAGE_CODE = "en_US"
class Localization(object):
def __init__(self, language_code=None):
self._language_code = None
self.country = None
self.language = None
self.explicit = bool(language_code)
... | 2,414 | 639 |
import os
env = lambda var : os.environ[var]
try:
GREWW_PATH = env('GREWW_PATH')
GREWW_CACHE = env('GREWW_CACHE')
GREWW_CONFIG = env('GREWW_CONFIG')
except:
# no scop tests
def _dispatch_path(fdir):
fn, fd = '', ''
bo = False
for e in fdir[::-1]:
if bo:
... | 783 | 329 |
#!//anaconda/envs/py36/bin/python
#
# File name: mklatt.py
# Date: 2018/08/02 16:15
# Author: Lukas Vlcek
#
# Description:
#
import sys
import re
def make_sc(box):
print('sc', *box)
return
def make_bcc(box):
print('bcc', *box)
return
def make_fcc(box):
lx, ly, lz = box
latt ... | 1,464 | 607 |
# -*- coding: UTF-8 -*-
"""
Run experiments.
:author: Vincent Vercruyssen (2019)
:license: Apache License, Version 2.0, see LICENSE for details.
"""
import sys, os, time, argparse
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
# transfer models
from models.locit import apply_LocIT... | 10,083 | 3,885 |
import pytest
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption(
"--freeze_reqs",
action="store_true",
help="run check if requirements (req*.txt|pip) are frozen",
)
parser.addini(
"freeze-reqs-ignore-paths",
type="linelist",
... | 3,416 | 1,028 |
# -- coding:utf-8--
import json
import paramiko
import re
import os
from urllib import request
#---------------------------------------------------------------------------------------
def start_v2():
gzlj = os.getcwd()
key_json_lj = os.path.join(gzlj, "pythonz5", "sun36x64", "v2ray", "config.json")
request.urlret... | 17,760 | 8,839 |
pessoa_maior = 0
pessoa_menor = 0
for i in range(1, 8):
ano_pessoa = int(input(f'Em que ano a {i}ª pessoa nasceu? '))
if ano_pessoa <= 1900 or ano_pessoa >= 2021:
print('Your not alive bitch!')
break
elif ano_pessoa <= 2002:
pessoa_maior += 1
else:
pessoa_menor += 1
print... | 452 | 195 |
from __future__ import print_function, absolute_import
import os
import sys
import time
import datetime
import argparse
import os.path as osp
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torch.autograd import Variable
from torch... | 7,427 | 2,632 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
from torch.autograd import Function
def disparity_regression(x):
disp = torch.arange(0, x.size(1)).unsqueeze(0)
disp = disp.repeat(x.size(0), 1)
return torch.sum(x*disp, dim=1).uns... | 6,024 | 2,444 |
#to generate a random name
import tkinter as tk
import random
def namegen():
f=open("names.txt",'r')
r2=random.randrange(0,4945)
countline=0;name=''
for line in f:
if(countline==r2):
name=line
break
countline+=1
f.close()
message=tk.Message(r,text=name,bg=... | 542 | 201 |
# coding: utf-8
from transitions.extensions import GraphMachine
class Model(object):
pass
states = [
'Waiting inputs',
'Waiting inputs in <num>',
'Rejected',
'Rejected while matching with subset',
'Accepted',
'Accepted in <num>',
'Accepted in <any>'
]
transitions = [
# Waiting ... | 2,467 | 805 |
def wrapper(func):
def _inner(a):
results = []
results.append(func(a))
v = results[0].next()
idx = 0
while True:
if not isinstance(v, Result):
results.append(func(v))
idx = len(results) - 1
v = results[idx].next()
... | 1,163 | 399 |
"""App model factories.
"""
from factory import DjangoModelFactory, Faker, SubFactory
from ...azure_projects.models import Project
from ...azure_settings.tests.factories import SettingFactory
class ProjectFactory(DjangoModelFactory):
"""ProjectFactory."""
setting = SubFactory(SettingFactory)
name = Fa... | 666 | 188 |
#import time
from spark.ReqBase import ReqBase
class ReqModPython(ReqBase):
def __init__(self, req, reallympy=True):
self.reallympy = reallympy
self.mpyreq = req
self.mpyreq.add_common_vars()
self.mpyreq.content_type = "text/html"
self.mpyreq.status = 200
self._have_status = 0
ReqBase.__init__(self)
... | 2,190 | 952 |
import matplotlib.pyplot as plt
import numpy as np
def load_data(data_loc):
return np.genfromtxt(data_loc, delimiter=',')
def calc_average(files, range):
averages = []
for i in range:
to_average_rows = np.asarray(files)[:, i]
average = np.round(np.average(to_average_rows, axis=0))
... | 2,840 | 1,120 |
# Copyright cocotb contributors
# Licensed under the Revised BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-3-Clause
"""
Tests of cocotb.regression.TestFactory functionality
"""
import random
import string
from collections.abc import Coroutine
import cocotb
from cocotb.regression import TestFacto... | 2,171 | 823 |
#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p "python3.withPackages (ps: with ps; [ aiohttp astral async-timeout attrs certifi jinja2 pyjwt cryptography pip pytz pyyaml requests ruamel_yaml voluptuous python-slugify ])"
#
# This script downloads Home Assistant's source tarball.
# Inside the homeassistant/compone... | 5,617 | 1,695 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 9,778 | 2,852 |
# Copyright 2017 The Forseti Security 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 by ap... | 1,180 | 360 |
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
gc.collect()
gc.enable()
| 142 | 49 |
from flask import Flask, jsonify, redirect, request, url_for
from flask_cors import CORS
import config
import requests
import json
import os
import time
from textblob import TextBlob
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import praw
import geoc... | 25,336 | 8,268 |
from collections import Counter as Ct
from wordplay.criteria import Criteria
from wordplay.utils import ArgumentError, CriteriaError, Utils
def setup_function(function):
Utils.set_disallowed_chars(set())
def test_copy_constructor():
orig_words = Criteria()
orig_words.begins_with('d').ends_with('n').cont... | 4,484 | 1,624 |
import re
import sys
import copy
import operator
import numpy as np
import instructions
import trace
from scipy.optimize import nnls
from scipy.linalg import solve
from sets import Set
from scipy.io import savemat
import pdb
high_cost = ['ARRAYLEN_GC_OP',
'STRLEN_OP',
'STRGETITEM_OP',
'GETFIELD_GC_PURE_OP... | 8,313 | 2,841 |
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.misc import normc_initializer
from ray.rllib.models.lstm import add_time_dimension
from ray.rllib.models import ModelCatalog
import tensorflow as tf
tf.disable_v2_behavior()
import numpy as np
# TODO:
# ModelCatalog.register_custom_model("RNNmo... | 4,266 | 1,568 |
from IPython.core.display import HTML, display
def dict_to_html(dictionary):
html = '<ul>'
for key, value in dictionary.iteritems():
html += '<li><strong>{}</strong>: '.format(key)
if isinstance(value, list):
html += '<ul>'
for item in value:
html += '<li... | 736 | 211 |
PADDING = 23
NOTE_THICKNESS = 3
RAND_SIZE = 20
REF_BPM = 1000
SCALE = REF_BPM / 104.15
| 87 | 59 |
"""
=========================================================================
sim_util.py
=========================================================================
Utilty functions for running a testing simulation
Author : Xiaoyu Yan (xy97), Eric Tang (et396)
Date : 21 Decemeber 2019
"""
import struct
import random... | 13,000 | 4,449 |
import autograd.numpy as np
class WeightsParser(object):
"""A helper class to index into a parameter vector."""
def __init__(self):
self.idxs_and_shapes = {}
self.N = 0
def add_weights(self, name, shape):
start = self.N
self.N += np.prod(shape)
self.idxs_and_shape... | 997 | 378 |
import sys
from streamprocessor.client.base import Consumer, Producer
class StandardIOConsumer(Consumer):
def consume(self):
yield from sys.stdin
class StandardIOProducer(Producer):
def produce(self, message):
print(message)
| 253 | 72 |
#! /usr/bin/python
from winreg import QueryValueEx, OpenKey, CloseKey, HKEY_LOCAL_MACHINE
DEBUG = False
def decode_key_val(keyword_bytes):
keyword_list = keyword_bytes.split(b'\0')
DEBUG and print(keyword_list)
duplex_key = str( keyword_list[0], encoding='utf8' )
duplex_val = str( keyword_list[1], enco... | 996 | 396 |
import random
from airtable import Airtable
import config
class Word:
def __init__(self, user):
self.user_name = user
# Take scores
print('Collecting scores...')
self.scores_table = Airtable(config.base_key, 'scores', config.api_key)
scores = self.scores_tabl... | 4,685 | 1,431 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2018-11-28 14:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gcb_web_auth', '0005_auto_20181128_1453'),
]
operations = [
migrations.Alte... | 595 | 207 |
from django.shortcuts import render
from .serializers import RegisterSerializer, LoginSerializer, UserSerializer
from rest_framework.generics import GenericAPIView
from rest_framework import status, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from django.contrib.auth impor... | 1,763 | 504 |
import argparse
import binascii
from flask import Flask, request, render_template, jsonify
from werkzeug.exceptions import BadRequest
from config import SDMMAC_PARAM, ENC_FILE_DATA_PARAM, ENC_PICC_DATA_PARAM, SDM_FILE_READ_KEY, SDM_META_READ_KEY
from ntag424 import decrypt_sun_message, InvalidMessage
app = Flask(__n... | 2,805 | 937 |
# Generated by Django 2.0.8 on 2018-11-14 13:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('insights_integration', '0003_host_host_vars'),
]
operations = [
migrations.CreateModel(
name='P... | 726 | 225 |
class btbmtException(Exception):
def __init__(self, message=None):
self.message = message
def __str__(self):
if self.message is None:
return ""
else:
return self.message
class BTBConfigNotFound(btbmtException):
def __init__(self, path=None):
message... | 1,223 | 352 |
#-------------------------------------------------------------------------------
#
# Copyright (c) 2009, IMB, RWTH Aachen.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in simvisage/LICENSE.txt and may be redistributed only
# under the conditions des... | 6,025 | 1,695 |
#
# SPDX-License-Identifier: MIT
#
import os
from oeqa.selftest.case import OESelftestTestCase
import tempfile
import operator
from oeqa.utils.commands import get_bb_var
class TestBlobParsing(OESelftestTestCase):
def setUp(self):
import time
self.repo_path = tempfile.mkdtemp(prefix='selftest-buil... | 6,409 | 2,338 |
import copy
import logging
import os
import yaml
import avi.migrationtools.f5_converter.converter_constants as final
from avi.migrationtools.f5_converter.conversion_util import F5Util
from avi.migrationtools.avi_migration_utils import update_count
LOG = logging.getLogger(__name__)
ssl_count = {'count': 0}
# Creating f... | 86,974 | 23,781 |
#!/usr/local/bin env
import pprint as pprint
import statistics
import numpy as np
from datetime import datetime
from PIL.PngImagePlugin import PngImageFile, PngInfo
import random
import string
def running_mean(l, N):
"""From a list of values (N), calculate the running mean with a
window of (l) items. How larg... | 13,059 | 4,377 |
# Copyright (c) 2010-2011 Lazy 8 Studios, LLC.
# All rights reserved.
import re
from front import Constants, target_image_types, activity_alert_types
from front.lib import gametime, urls, db, utils
from front.models import species
from front.backend import notifications
from front.tests import base
from front.tests.b... | 25,692 | 7,419 |
# Copyright (c) 2020, 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 appli... | 1,777 | 524 |
import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from malib.utils.typing import Dict, Any, List, Union, DataTransferType
from malib.backend.datapool.offline_dataset_server import Episode
def soft_update(target, source, tau):
"""Perform DDPG soft update (move ta... | 8,954 | 2,980 |
import abc
import json
import six
try:
from urllib.parse import urlencode # py35
except ImportError:
from urllib import urlencode # py27
from tempest.lib.common import rest_client
from tempest.lib import exceptions as lib_exc
from nuage_tempest_plugin.lib.topology import Topology
CONF = Topology.get_conf()... | 7,746 | 2,334 |
import random
import re
import ircbot.plugin
class DefaultPlugin(ircbot.plugin.Plugin):
def __init__(self, bot, channel):
super().__init__(bot, channel)
self.insults = (
(re.compile(r'.*fuck(\s+you)\s*,?\s*'+self.bot.nick+'.*', re.IGNORECASE),
'fuck you too {nick}'),
(re.compile(r'.*'+self.bot.nick+'[... | 1,402 | 639 |
import pyodbc
import os
from multiprocessing import Process
def get_file_content(full_path):
"""Get file content function from read_sql_files_to_db.py"""
print(full_path)
bytes = min(32, os.path.getsize(full_path))
raw = open(full_path, 'rb').read(bytes)
if '\\xff\\xfe' in str(raw):
print("... | 1,598 | 537 |
"""
Fused Graphical Lasso experiment
=================================
We investigate the performance of Fused Graphical Lasso on powerlaw networks, compared to estimating the precision matrices independently with SGL.
In particular, we demonstrate that FGL - in contrast to SGL - is capable of estimating time-consiste... | 6,005 | 2,371 |
"""Put tests for the examples in this directory."""
| 52 | 13 |
from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
def send_invite(subject, from_email, to, **email_values):
html_content = render_to_string('invite.html', email_values)
text_con... | 546 | 185 |
"""
Package install information.
This build script provides information about
the `lib` package (e.g., the name and version,
what should be included the built package,
and etc.).
"""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="TVQ-Scripts",
... | 849 | 266 |
"""
Components Package of the General Simulator of Rankine Cycle
"""
__all__ = ["node","boiler", "condenser","condenser","openedheater","turbine"]
| 150 | 49 |
#
# * The source code in this file is based on the soure code of CuPy.
#
# # NLCPy License #
#
# Copyright (c) 2020-2021 NEC Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | 13,479 | 5,548 |
from setuptools import setup, find_packages
setup(name='CryptoPlus',
version='1.0',
description='PyCrypto Cipher extension',
author='Christophe Oosterlynck',
author_email='tiftof@gmail.com',
packages = find_packages('src'),
install_requires = ['pycrypto'],
package_dir={'': 'sr... | 325 | 102 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 29 23:04:12 2021
@author: tahashafique
"""
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
class chrome_driver:
def __init__(self, executable_path, max_window = True, window_size = None, ... | 1,200 | 396 |
from myhdl import *
from ConvInst import *
import random
def tbConvInst():
datain = Signal(modbv(0)[32:])
#din = Signal(modbv(0)[32:])
dataout = Signal(modbv(0)[32:])
#dout = Signal(modbv(0)[32:])
dut = ConvInst(datain,dataout)
interv = delay(7)
@always(interv)
def stim():
#hi = bin(random.randint(0,2*... | 992 | 487 |
print( input("ingrese su cadena" ).swapcase())
| 48 | 18 |
# 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果
from PIL import Image,ImageDraw,ImageFont
def add_num( imgPath, color = "#ff0000", msg = '4'):
try:
img = Image.open(imgPath, 'r')
draw = ImageDraw.Draw(img)
imagefont = ImageFont.truetype('C:/Windows/Fonts/Arial.ttf', 40)
... | 631 | 294 |
#!/usr/bin/env python3
import os
import unittest
from unittest import mock
from mathbind.compilers.gcc import GccCompiler
class TestGFortranCompiler(unittest.TestCase):
def setUp(self):
self.os_system_backup = os.system
def tearDown(self):
os.system = self.os_system_backup
def test1(se... | 894 | 328 |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: State
import flatbuffers
class FlatBufferObserver(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsFlatBufferObserver(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
... | 2,328 | 771 |
__author__ = 'Jan Bogaerts'
__copyright__ = "Copyright 2018, Elastetic"
__credits__ = []
__maintainer__ = "Jan Bogaerts"
__email__ = "jb@elastetic.com"
__status__ = "Development" # "Prototype", or "Production"
"""
a small tool to convert files from the sonar corpus into raw text data (as it only comes annotated).
son... | 4,126 | 1,233 |
"""Migration for Entries Table."""
from orator.migrations import Migration
class CreateEntriesTable(Migration):
"""Migration Class for Entries Table."""
def up(self):
"""Run the migrations."""
with self.schema.create("entries") as table:
table.increments("id")
table.st... | 655 | 184 |
import click
import scrapy
from scrapy.crawler import CrawlerProcess
from langdetect import detect
__author__ = 'Abdullah Alharbi'
def get_urls(keyword):
return [
'https://www.goodreads.com/quotes/tag/{}'.format(keyword),
]
class QuotesSpider(scrapy.Spider):
name = "quotes"
quotes = []
... | 2,613 | 803 |
#!/usr/bin/env python3
# request and response in this file refer to the HTTP specification, they are reversed for HTJP
import sys
import re
import base64
from urllib.parse import quote
import signal
def interrupted(signum, frame):
exit()
signal.signal(signal.SIGALRM, interrupted)
signal.alarm(5)
debug = False
... | 5,415 | 2,249 |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 14 15:57:46 2017
@author: tm3y13
"""
from random import shuffle
def random_tour(tour):
"""
Initial solution to tour is psuedo random
"""
rnd_tour = tour[1:len(tour)-1]
base_city = tour[0]
shuffle(rnd_tour)
rnd_tour.append(base... | 394 | 184 |