text string | size int64 | token_count int64 |
|---|---|---|
p = 'p'
q = 'q'
r = 'r'
| 27 | 22 |
import pyodbc
def create_table(table_name, cursor):
"""Create a table and drop it if it exists.
Args:
table_name (str): Table name.
cursor (object): pyobdc cursor.
**Examples**
.. code-block:: python
conn = pyodbc.connect(connection_string)
cur = conn.curso... | 666 | 223 |
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
from Instrucciones.TablaSimbolos.Tipo import Tipo_Dato
from Instrucciones.Excepcion import Excepcion
from Instrucciones.Expresiones import Relacional
class Case(Instruccion):
'''
La clase Case, recibe una lista de condiciones y cada una de ellas t... | 9,050 | 2,879 |
# -*- coding: utf-8 -*-
# $Id: useraccount.py 69111 2017-10-17 14:26:02Z vboxsync $
"""
Test Manager - User DB records management.
"""
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is ... | 10,896 | 3,181 |
#!/usr/bin/env python
# entropy generating geigercounter
# Modified from https://apollo.open-resource.org/mission:log:2014:06:13:generating-entropy-from-radioactive-decay-with-pigi
import geiger
import time
import datetime
import textwrap
import binascii # for conversion between Hexa and bytes
import qrcode
import i... | 11,129 | 3,780 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
import sklearn
from sklearn import metrics
from sklearn.metrics import (
auc,
average_precision_score,
classification_report,
confusion_matrix,
precision_recall_curve,
roc_auc_score,
roc_curve,
)
f... | 3,908 | 1,494 |
"""Test gmag and themis load functions."""
import os
import unittest
from pyspedas.utilities.data_exists import data_exists
import pyspedas
class GmagTestCases(unittest.TestCase):
"""Test GMAG functions."""
def test_get_group(self):
"""Get gmag stations of a group."""
from pyspedas.themis.gr... | 4,308 | 1,660 |
__author__ = 'yalnazov'
try:
import unittest2 as unittest
except ImportError:
import unittest
from paymill.paymill_context import PaymillContext
from paymill.models.subscription import Subscription
import test_config
class TestSubscriptionService(unittest.TestCase):
currency = 'EUR'
interval = '2 DA... | 6,673 | 1,884 |
num = float(input())
while num < 1 or num > 100:
num = float(input())
print(f'The number {num} is between 1 and 100') | 123 | 51 |
'''module for textfiles connectors'''
__import__('pkg_resources').declare_namespace(__name__)
| 94 | 27 |
from examples.example_imports import *
VIOLET = "#EE82EE"
INDIGO = "#4B0082"
VIBGYOR = [VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED]
class RecamanSequence(EagerModeScene):
CONFIG = {
"n": 100, # number of iterations
}
def clip1(self):
self.count = 0
visited = [0] + [None] *... | 1,824 | 602 |
def check_gribfile(f):
'''
check if file is a grib file and readeable
'''
pass
| 95 | 34 |
# Copyright 2016 Intel 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 agreed to in wri... | 5,182 | 1,318 |
# https://stackoverflow.com/questions/34518656/how-to-interpret-loss-and-accuracy-for-a-machine-learning-model
from additional_models.data2 import read_csv_data, get_samples
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten, Lambda
from keras.layers.convolutional import Conv2D
f... | 2,052 | 765 |
"""
MIT License
Copyright (c) 2019 Kuan-Yu Huang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish,... | 4,254 | 1,450 |
# Copyright 2015 NEC Foundation
# 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... | 6,693 | 2,542 |
# Copyright 2018 Vincent Deuschle. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanyin... | 2,769 | 970 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
def get_std_icon(name):
if not name.startswith('SP_'):
name = 'SP_' + name
standardIconName = getattr(QtGui.QStyle, name, None)
if standardIconName is not None:
return QtGui.QWidget().style().standardIcon( standa... | 1,670 | 528 |
'''
Run the graph embedding methods on Karate graph and evaluate them on
graph reconstruction and visualization. Please copy the
gem/data/karate.edgelist to the working directory
'''
import matplotlib.pyplot as plt
from time import time
from gem.utils import graph_util, plot_util
from gem.evaluation import visualize... | 3,616 | 1,166 |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mu = 0
sigma = 2
def f(x):
return 1/ ( np.sqrt( 2*np.pi ) * sigma ) * np.exp( -.5 * ( ( x - mu ) / sigma ) **2 )
x = np.arange( -4.0, 4.0, 0.1 )
plt.plot( x, f(x) )
plt.show() | 256 | 125 |
DEFAULT_MAX_LENGTH = 512
DEFAULT_EASY_TRANSFORMERS_CACHE_SIZE = 1
DEFAULT_EASY_TRANSFORMERS_TEXT_EMB_CACHE_SIZE = 10000
| 120 | 61 |
from pynextion.color import (
NamedColor,
Color
)
def test_named_color():
assert NamedColor.BLACK.value == 0
assert NamedColor.WHITE.value == 65535
assert NamedColor.RED.value == 63488
assert NamedColor.GREEN.value == 2016
assert NamedColor.BLUE.value == 31
assert NamedColor.GRAY.value... | 1,981 | 967 |
# A company is developing a new additive for gasoline.
# The additive is a mixture of three liquid ingredients, I, II, and III.
# For proper performance, the total amount of additive must be at least 7 oz per gal of gasoline.
# However, for safety reasons, the amount of additive should not exceed 19 oz per gal ... | 1,149 | 474 |
import drawSvg as draw
import pandas as pd
from PIL import Image
df = pd.DataFrame([[15.7, 11.9, 3.8]], index=[1], columns=['Comp', 'Traffic', 'Ticket'])
# df = pd.DataFrame([[9.0, -2.0, 11.1]], index=[1], columns=['Comp', 'Traffic', 'Ticket'])
comp_val = df.at[1, 'Comp']
traffic_val = df.at[1, 'Traffic']
ticket_val... | 3,994 | 1,893 |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 13:07:06 2020
@author: Adolfo Correa
Professor: Dr. Iuri Segtovich
"""
import numpy as np
print('\nExercise 1\n')
# Exercise 1
# =============================================
x = [1, 346432, 68, 1223, 5, 47, 678]
max_val = x[0]
for elem in x:
if e... | 3,135 | 1,515 |
from time import sleep
import pyrebase
import RPi.GPIO as GPIO
url = 'https://dw-1d-kivy.firebaseio.com' # URL to Firebase database
apikey = '"AIzaSyADs22Rdhef_5w28Y4oOvx0Aat1NiKCl5U"' # unique token used for authentication
config = {"apiKey": apikey, "databaseURL": url, }
# Create a firebase object by specifying ... | 4,495 | 1,825 |
from fastapi import APIRouter, HTTPException
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import os
router = APIRouter()
DATA_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "..","data", "rental_all.csv")
@router.get('/predict_rental/{city_id}')
async ... | 6,526 | 2,720 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 version.
#
# This program is distrib... | 2,185 | 650 |
'''
Main code for finding the nearest target spots and
export an webpage
'''
import os
import webbrowser
import pandas as pd
import util
import gmplot
COLOR_MAP = {'family support (children services)': '#FFFACD',
'family support (senior services)':'#FFFACD',
'family support (domestic violenc... | 6,605 | 2,009 |
import inspect
import os
import sys
import unittest
__author__ = "David Juboor"
__version__ = "1.0"
# Can't use __file__ because when running with coverage via command line, ___file__ is not the full path
my_location = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
def test_runner_suite():
tests_source... | 765 | 253 |
# encoding: utf-8
"""
File: core_service
Author: twotrees.us@gmail.com
Date: 2020年7月30日 31周星期四 10:55
Desc:
"""
import psutil
import os
import os.path
from .package import jsonpickle
from typing import List
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.bas... | 8,500 | 2,701 |
import abc
from typing import *
from dropSQL.engine.row_set import *
from dropSQL.engine.types import *
from dropSQL.generic import *
from dropSQL.parser.streams import *
from dropSQL.parser.tokens import *
from .alias import AliasedTable
from .ast import *
from .expression import Expression
if TYPE_CHECKING:
fro... | 4,282 | 1,411 |
import paho.mqtt.client as PahoMQTT
import json
class MyMQTT:
def __init__(self, clientID, broker, port, notifier=None):
self.broker = broker
self.port = port
self.notifier = notifier
self.clientID = clientID
self._topic = ""
self._isSubscriber = False
# creat... | 2,007 | 635 |
from django.urls import path
from .views import *
urlpatterns = [
path('users', UserView.as_view(), name='user_list'),
]
| 128 | 45 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Olivier Noguès
# All colors are coming from the template
# https://credit-agricole.ua/pdf/Credit_Agricole_AR_2016_ENG_full_17072017_.pdf
import CssBase
charts = ['#71bf44', '#1d99d6', '#6bcff6', '#bed630', '#00805f', '#00a96c', '#66bbaa', '#bbeeee', ... | 895 | 474 |
from dask.distributed import WorkerPlugin
from numcodecs import PackBits
from numcodecs.compat import ensure_ndarray, ndarray_copy
import numpy as np
# See: https://github.com/zarr-developers/numcodecs/blob/master/numcodecs/packbits.py
class PackGeneticBits(PackBits):
"""Custom Zarr plugin for encoding allele co... | 1,960 | 606 |
import collections
import copy
from typing import Any, Dict, List, Optional, Tuple, Union
from astromodels.utils.logging import setup_logger
from .tree import Node
log = setup_logger(__name__)
# Exception for when a parameter is out of its bounds
class SettingUnknownValue(RuntimeError):
pass
class PropertyBas... | 6,363 | 1,636 |
#!/usr/bin/python3
import json
import logging
import logging.handlers
import os
import pickle
import requests
import sqlite3
import shutil
from contextlib import closing
_handler = logging.handlers.WatchedFileHandler("/var/log/menagerie.log")
logging.basicConfig(handlers=[_handler], level=logging.INFO)
API_TARGET_U... | 4,354 | 1,117 |
import os
import mysql.connector as mysql
sql_host = os.environ["SQL_HOST"]
query_on = os.environ["QUERY_ON"]
metrics_mysql_password = os.environ["METRICS_MYSQL_PWD"]
def make_lookup_dict():
cpu_file = open("custom_scripts/app_reserved_cpu_lookup_file.txt", "r")
lines = cpu_file.readlines()
count = 0
... | 2,296 | 764 |
from __future__ import division, unicode_literals
import argparse
import time
import math
import random
import torch.nn as nn, torch
import torch.nn.init as init
import torch.optim as optim
import os
import numpy as np
import pickle
from torch.autograd import Variable
from torch.utils.data import DataLoader
from scip... | 7,157 | 2,491 |
# > \brief \b ICAMAX
#
# =========== DOCUMENTATION ===========
#
# Online html documentation available at
# http://www.netlib.org/lapack/explore-html/
#
# Definition:
# ===========
#
# INTEGER FUNCTION ICAmax(N,CX,INCX)
#
# .. Scalar Arguments ..
# INTEGER INCX,N
# ..
# .. Ar... | 2,605 | 979 |
from .oeo import Oeo
from .element import Element
from .stats import Stats
from .move import Move, MoveCategory
from .item import Item
| 135 | 38 |
import logging
import random
import sys
import numpy
from sklearn.cross_validation import StratifiedKFold
from sklearn.metrics import precision_recall_curve
from iepy import defaults
from iepy.extraction.relation_extraction_classifier import RelationExtractionClassifier
logger = logging.getLogger(__name__)
HIPREC... | 8,708 | 2,470 |
""" Methods helpful for multi-objective HPO.
"""
import numpy as np
def retrieve_pareto_front(training_history, objectives):
"""Retrieves the pareto efficient points discovered during a
scheduler's search process.
Parameters
----------
training_history:
A training history dictionary gen... | 3,211 | 967 |
#!/usr/bin/env python
"""
Interfaces for Phonopy.
"""
from phonopy.structure.atoms import PhonopyAtoms
def get_phonopy_structure(cell:tuple) -> PhonopyAtoms:
"""
Return phonopy structure.
Args:
cell: (lattice, scaled_positions, symbols).
Returns:
PhonopyAtoms: Phonopy structure.
... | 1,191 | 371 |
from django.contrib import admin
from unecorn.models import *
admin.site.register(Discount)
admin.site.register(Category)
admin.site.register(Company) | 151 | 45 |
import os
import pyotp
def totp(secret):
totp = pyotp.TOTP(secret)
return totp.now()
| 101 | 44 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | 1,929 | 589 |
__version__ = "0.0.1"
# NOTE: I am moving the forcats module from siuba to here
# https://github.com/machow/siuba/blob/master/siuba/dply/forcats.py
| 149 | 62 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-24 21:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('boards', '0006_board_hourly_rates'),
]
operations = [
migrations.AddField(
... | 958 | 292 |
# Copyright (c) 2013, Lewin Villar and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
def execute(filters=None):
fields = ["paciente","ars_nombre","diferencia","reclamado","autorizado","medico"]
filters = {"name":"CLS-0000001795"}
result = frap... | 547 | 189 |
from features import addFeature
from lib import implants
from lib import globals
import tableprint
import timeago
import sys
import time
global lastImplantCount
lastImplantCount = 0
def delLast(num):
return
num += 4
ERASE_LINE = '\x1b[2K'
CURSOR_UP_ONE = '\x1b[1A'
CURSOR_DOWN_ONE = '\x1b[1B'
print((CURS... | 2,014 | 704 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import secrets
from pathlib import Path
class text_color:
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
... | 2,883 | 1,026 |
#!/usr/bin/env python
#coding:utf-8
import sys
if sys.getdefaultencoding()=='ascii':
reload(sys)
sys.setdefaultencoding('utf-8')
from django.apps import AppConfig
class ViewBaseApp(AppConfig):
name = "view_base"
| 226 | 79 |
"""Command-line usage of the package"""
from argparse import ArgumentParser
from . import EquidistantPoints
def parse_args():
"""Command-line arguments parsing"""
parser = ArgumentParser()
parser.add_argument(
'n_points',
help='Number of points to be generated',
metavar='N',
... | 2,569 | 804 |
from conda_verify.conda_package_check import CondaPackageCheck
def verify(path_to_package=None, verbose=True, **kwargs):
package_check = CondaPackageCheck(path_to_package, verbose)
package_check.no_setuptools()
pedantic = kwargs.get("pedantic") if "pedantic" in kwargs.keys() else True
package_check.no... | 406 | 135 |
# write new version of csv with numbered (not named) fields
import os
import sys
args = sys.argv
lines = open(args[1]).readlines()
lines = [line.strip() for line in lines]
hdr = lines[0].split(',')
hdr = ','.join([str(i) for i in range(len(hdr))])
lines[0] = hdr
open(args[1] + "_numbered_fields.csv", "wb").write(('\... | 346 | 129 |
from bike.globals import *
import os
from bike.parsing.fastparser import fastparser
class Cache:
def __init__(self):
self.reset()
def reset(self):
self.srcnodecache = {}
self.typecache = {}
self.maskedlinescache = {}
instance = None
Cache.instance = Cache()
class CantLoca... | 2,532 | 742 |
# Tai Sakuma <tai.sakuma@gmail.com>
import pytest
try:
import unittest.mock as mock
except ImportError:
import mock
from qtwirl._parser.expander import _expand_config
##__________________________________________________________________||
@pytest.fixture()
def mock_expand_one_dict(monkeypatch):
def ret(cf... | 736 | 222 |
"""
Functions for visualization of molecules
"""
import numpy as np
import matplotlib.pyplot as plt
from .atom_data import atom_colors
def draw_molecule(coordinates, symbols, draw_bonds=None, save_location=None, dpi=300):
"""Draw a picture of a molecule.
Parameters
----------
coordinates : np.ndarray... | 2,815 | 888 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2017 FIWARE Foundation, e.V.
# 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.apach... | 2,185 | 746 |
from test_base import TestBase
class TestParityAccounts(TestBase):
def test_parity_all_accounts_info(self):
cb = lambda: self.client.parity_all_accounts_info()
self.mock(cb, True)
def test_parity_change_password(self):
address = '0xdae1bfb92c7c0fd23396619ee1a0d643bf609c2e'
ol... | 5,365 | 2,191 |
import os
from datetime import datetime
from django.core.management.base import BaseCommand
from . import find_date_range_of_ligo_file
class Command(BaseCommand):
help = 'Import historical daily compute stats for LIGO from bz2 files.'
def add_arguments(self, parser):
parser.add_argument... | 1,955 | 575 |
# coding: utf-8
"""
Xero Payroll UK
This is the Xero Payroll API for orgs in the UK region. # noqa: E501
OpenAPI spec version: 2.4.0
Contact: api@xero.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class Benefits(BaseMod... | 2,949 | 925 |
from supplychainpy.reporting.blueprints.contact.views import about
| 67 | 19 |
# Generated by Django 2.2.6 on 2019-12-30 18:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('harmony_checker', '0017_auto_20191230_1246'),
]
operations = [
migrations.AlterField(
model_name='test',
name='func'... | 390 | 145 |
import json
try:
from .Helpers.create_logger import create_logger
except ImportError:
from Helpers.create_logger import create_logger
try:
from .emhmeter import *
except ModuleNotFoundError:
from emhmeter import *
from time import sleep
import datetime
class CRMtoRedis:
url = "http://10.11.30.97:... | 11,486 | 3,534 |
from ..widget import Widget
from .bitcoin import bitcoin
from .clock import clock, calendar
from .music import music
from .volume import volume
from .memory import memory
| 172 | 44 |
"""Support for Vivint door locks."""
from homeassistant.components.lock import LockEntity
from vivintpy.devices.door_lock import DoorLock
from .const import DOMAIN
from .hub import VivintEntity
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Vivint door locks using config entry."""... | 1,280 | 395 |
import json
from typing import List, Union
from app.domain.adapter import (
Adapter,
CreateVolvoCaretrackAdapter,
CreateWackerNeusonKramerAdapter,
)
from app.repository.database.adapters import PolymorphicAdaptersBase, adapters_repo
from kafka import KafkaProducer
from sqlalchemy.orm import Session
class... | 1,482 | 461 |
import cv2
import sys
# do instal modul opencv-python
image = cv2.imread("gambar.jpg")
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
grayImageInv = 255 - grayImage
grayImageInv = cv2.GaussianBlur(grayImageInv, (21, 21), 0)
output = cv2.divide(grayImage, 255-grayImageInv, scale = 256.0)
resizeImg = cv2.resize(ou... | 592 | 258 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Dirk Chang and contributors
# For license information, please see license.txt
#
# Api for user.token
#
from __future__ import unicode_literals
import frappe
import uuid
from ioe_api.helper import throw
@frappe.whitelist(allow_guest=True)
def test():
frappe.response.upda... | 2,111 | 881 |
import cv2 as cv
import numpy as np
from random import randrange
def noise(img):
s = salt(img)
p = pepper(img)
noise = cv.addWeighted(s, 0.5, p, 0.5, 0)
output = cv.addWeighted(img, 0.5, noise, 0.5, 0)
return output
def salt(img):
rows, cols = img.shape[:2]
dens = (rows*cols*0.5)//2
... | 1,608 | 623 |
"""Core functions to integrate the gui and the backup."""
import logging
from .gui import App, tk
from .backup import collect_emails, ImapRuntimeError
logging.basicConfig(
level=logging.INFO,
)
def _do_backup():
app.disable_submit(True)
dialog_values = app.as_dict()
server_login = dict(
... | 726 | 231 |
from .basic import BasicRedirectMiddlewareTests
from .django_cms import RedirectMiddlewareTestsWithDjangoCMS
from .wagtail_cms import RedirectMiddlewareTestsWithWagtailCMS
| 172 | 50 |
from rest_framework import serializers
from .models import CustomUser
class UserSerializer(serializers.ModelSerializer):
"""
Serilizer for user
"""
class Meta:
model = CustomUser
# fields = '__all__'
fields = ['id','email'] | 265 | 71 |
import math
import operator
import random
# Seed used to control the tests
random.seed()
# A set of nodes composes a binary tree
class Node(object):
def __init__(self, item, right=None, left=None, level=1):
self.right = right # Right child
self.left = left # Left child
self.item = item
self.level = level # T... | 2,302 | 723 |
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.36
工具: python == 3.7.3
"""
"""
思路:
以每个元素为中心,分别向外扩散寻找奇数回文子串和偶数回文子串
结果:
执行用时 : 868 ms, 在所有 Python3 提交中击败了82.03%的用户
内存消耗 : 13.7 MB, 在所有 Python3 提交中击败了19.28%的用户
"""
class Solution:
def longestPalindrome(self, s):
... | 1,290 | 661 |
x = (1,2,3,4)
y = (1,2,'abc',[1,2,3]) // Only can change data with a list, other cannot be change
y[3][1] = 22
print(y)
x = 1,2,3,4,5
tuple(x) // You can create a tuple this way
| 210 | 93 |
# -*- coding: utf-8 -*-
# This work is part of the Core Imaging Library (CIL) developed by CCPi
# (Collaborative Computational Project in Tomographic Imaging), with
# substantial contributions by UKRI-STFC and University of Manchester.
# Licensed under the Apache License, Version 2.0 (the "License");
# you... | 2,359 | 657 |
from leapp.models import Model, fields
from leapp.topics import SystemInfoTopic
class VsftpdConfig(Model):
"""
Model representing some aspects of a vsftpd configuration file.
The attributes representing the state of configuration options are nullable, so that
they can represent the real state of the ... | 1,284 | 364 |
"""
Given an array of integers, we need to fill in the "holes" such that it contains all the integers from some range.
Example
For sequence = [6, 2, 3, 8], the output should be
makeArrayConsecutive(sequence) = [4, 5, 7].
"""
def makeArrayConsecutive(sequence):
s = sorted(sequence)
x = range(min(s), max(s) +... | 426 | 148 |
# -*- coding: utf-8 -*-
import logging
from http import client
from retrying import retry
import requests
from aiohttp import ClientSession, ClientTimeout, TCPConnector
# from aiohttp_client_cache import CachedSession, SQLiteBackend
# from findy.interface import RunMode
# from findy.utils.cache import hashable_lru
l... | 6,141 | 1,865 |
import argparse
import sys
import os
import torch
import struct
from pathlib import Path
sys.path.append('../')
from classification.tools import load_model
def export_weights(model, wts_file):
# Export model to TensorRT compatible format
with open(wts_file, 'w') as fd:
fd.write('{}\n'.format(len(mode... | 1,290 | 409 |
import binascii
from base64 import b64decode
from aiohttp import ClientResponseError, ClientSession
from requests import get
def decode_dict(d):
"""
Recursivly decode all strings in a dict
:param d: the input dict
:return: a dict with all its vals decoded
"""
if isinstance(d, int):
re... | 1,153 | 369 |
from Layer import *
class Network(BasicLayer):
def __init__(self,para={}):
self.model = []
#para={
# "Conv_layer":{XX..}
# }
for key in para.keys():
if "Conv" in key:
self.model.append(Conv_layer(para[key]))
elif "Fully" in key:
... | 1,213 | 386 |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Status bar container.
"""
# Third-party imports
from qtpy.QtCore import Signal
# Local imports
from spyder.api.widgets import PluginMainContainer
... | 1,882 | 598 |
from typing import Iterable, Sequence, Tuple, TypeVar, Generic
from yaga_ga.evolutionary_algorithm.details import Comparable
from yaga_ga.evolutionary_algorithm.individuals import IndividualType
ScoreType = TypeVar("ScoreType", bound=Comparable)
class Ranking(Generic[IndividualType, ScoreType]):
def __init__(se... | 589 | 175 |
LOG = {
}
| 10 | 7 |
def show_permutations_anti_lexicographic_fast(sequence=None, length=None):
if sequence is None:
if length is None:
length = 3
sequence = [i + 1 for i in range(length)]
if length is None:
length = len(sequence)
if length == 0:
print(sequence)
return
e... | 957 | 296 |
# Generated by Django 2.2.1 on 2019-05-25 19:40
import autoslug.fields
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
replaces = [('blog', '0001_initial'), ('blog', '0002_auto_20150802_0017'), ('blog', '0003_auto_2... | 2,774 | 897 |
if __name__ == "__main__" and __package__ is None:
#use the local version of schema
import sys, os
if os.getcwd().endswith('serene_schema'):
sys.path.insert(0, os.getcwd())
elif os.getcwd().endswith('helpers'):
sys.path.insert(0, os.path.join(os.getcwd(), '..', '..'))
from serene_schem... | 5,548 | 1,738 |
# TODO: implement tracing helpers here
traces = {}
def add(at,cmd):
try:
#at = "0x%x"%int(at, 16)
print("ADD",at)
print(traces[at])
if traces[at]:
return False
except:
pass
traces[at] = cmd
return True
def get(at):
try:
try:
at = "0x%x"%int(at, 16)
except:
pass
print("GET",at)
return ... | 640 | 332 |
"""Test the driver model."""
import json
from zwave_js_server.event import Event
from zwave_js_server.model import driver as driver_pkg
from .. import load_fixture
def test_from_state():
"""Test from_state method."""
ws_msgs = load_fixture("basic_dump.txt").strip().split("\n")
driver = driver_pkg.Drive... | 609 | 203 |
import numpy as np
import math as ma
import os
from pywt import wavedec
from pyeeg import hfd, pfd
from scipy.io import wavfile as wav
from python_speech_features.sigproc import framesig
from python_speech_features import mfcc, fbank, logfbank
from python_speech_features.base import delta
from pandas import DataFrame
f... | 9,342 | 3,238 |
txt = 'but soft what light in yonder window breaks'
words = txt.split ()
t = list ()
for word in words:
t.append ((len (word), word))
print(t)
t.sort (reverse = True)
print(t)
res = list ()
for length, word in t:
res.append (word)
print (res) | 252 | 91 |
'''
Created on Oct 18, 2011
@author: IslamM
'''
from logging import getLogger
log = getLogger(__name__)
from util import catalog
from util.config import config
from portlets.collector import Collector, remove_collector
from core.uim import UIManager
from urlparse import urlparse
from threading import Thr... | 3,923 | 1,343 |
#-*- encoding: utf-8-*-
"""
file: __init__.py
author: Yoann Dupont
MIT License
Copyright (c) 2018 Yoann Dupont
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including wi... | 13,798 | 4,272 |
myset ={"C","C++","Python","Shap","Ruby","Java"}
print("Set Content:",myset) | 77 | 31 |
import re
from d_parser.d_spider_common import DSpiderCommon
from d_parser.helpers.re_set import Ree
from helpers.url_generator import UrlGenerator
from d_parser.helpers.stat_counter import StatCounter as SC
VERSION = 29
# Warn: Don't remove task argument even if not use it (it's break grab and spider crashed)
# W... | 6,539 | 1,896 |