text string | size int64 | token_count int64 |
|---|---|---|
import atexit
import os
import re
import shutil
from enum import Enum
from typing import List, Optional
import collections
from gitflow import cli, const, repotools, _, utils
from gitflow.common import Result
from gitflow.const import VersioningScheme
from gitflow.properties import PropertyIO
from gitflow.repotools i... | 18,861 | 5,032 |
class Solution:
def __init__(self):
self.m = 0
self.n = 0
def dfs(self, y, x, grid) -> int:
if y < 0 or y >= self.m or x < 0 or x >= self.n or grid[y][x] == 0:
return 0
res = 0
tmpGrid = grid[y][x]
grid[y][x] = 0
for y_, x_ in ((y, x - 1),... | 705 | 281 |
from model.contact import Contact
from random import randrange
def test_modify_contact_name(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.contact.create(Contact(firstname="test"))
old_contacts = db.get_contact_list()
index = randrange(len(old_contacts))
contact = Contact(first_name... | 2,307 | 802 |
import webapp2
from webapp2_extras import sessions
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.r... | 734 | 217 |
import unittest
try:
from unittest.mock import Mock, call
except ImportError:
from mock import Mock, call
from dbhelpers import cm_cursor, fetchiter, fetchone_nt, fetchmany_nt, fetchall_nt, fetchiter_nt
class HelpersTestCase(unittest.TestCase):
def test_cm_cursor(self):
"""
Creates a cont... | 6,999 | 2,284 |
#!/usr/bin/env python
# THIS SHEBANG IS REALLY REALLY IMPORTANT
import rospy
import roscpp
import numpy as np
from sensor_msgs.msg import Joy
from std_msgs.msg import Int16MultiArray
class JoystickNode(object):
def __init__(self):
# put away our toys cleanly
rospy.on_shutdown(self.shutdown)
... | 2,641 | 931 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Soldeva, SRL and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class ConfiguracionISR(Document):
pass
@frappe.whitelist()
def getRangosISR():
return frappe... | 650 | 242 |
import logging
import typing
from electrumsv_sdk.utils import get_directory_name
COMPONENT_NAME = get_directory_name(__file__)
logger = logging.getLogger(COMPONENT_NAME)
if typing.TYPE_CHECKING:
from .electrumsv_server import Plugin
class LocalTools:
"""helper for operating on plugin-specific state (like... | 1,367 | 416 |
# -*- coding: utf-8 -*-
# pylint: disable=all
import base64
import binascii
import contextlib
import math
import os
import textwrap
import time
import urllib.parse
from const import LOGS_PATH
from logparser import parse
from utils import is_nan, print_file
# from utils import IPAddressJSONEncoder, is_nan, print_file
... | 4,955 | 1,819 |
import numpy as np
from src.compute_corr_coef import compute_corr_coef
from utils.plotting import plot_similarities
def compute_trust_values(dsk, do_plot=False):
"""
Compute trust values following formula 6
k:= number of blendshapes
n:= num_features (num_markers*3)
:param dsk: delta_sk vector (k... | 1,647 | 613 |
import unittest
from jaqalpaq.core.parameter import ParamType
from jaqalpaq.core.constant import Constant
from . import randomize
from . import common
class ConstantTester(unittest.TestCase):
def test_valid_types(self):
"""Test that a Constant can only be created from valid types."""
valid_values... | 2,042 | 555 |
# -*- coding: utf-8 -*-
# richard -- video index system
# Copyright (C) 2012, 2013, 2014, 2015 richard contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | 8,035 | 2,206 |
"""
copy-paste from my (beckermr) personal code here
https://github.com/beckermr/metadetect-coadding-sims
"""
import numpy as np
import galsim
from descwl_shear_sims.masking import get_bmask_and_set_image
from descwl_shear_sims.artifacts import (
generate_bad_columns,
generate_cosmic_rays,
)
def test_basic_m... | 1,399 | 597 |
from getpass import getpass
import os
from .utils import Command
from .db import DB
class Init(Command):
name = 'init'
description = "Initializes a new Stylobate project, forking the original"
def add_args(self, parser):
parser.add_argument(
'name',
type=str,
... | 2,270 | 670 |
#!/usr/bin/env python
# Reverse Integer https://oj.leetcode.com/problems/reverse-integer/
# Reverse digits of an integer.
# Example1: x = 123, return 321
# Example2: x = -123, return -321
#Math
# Xilin SUN
# Dec 7 2014
class Solution:
# @return an integer
def reverse(self, x):
if x > 2147483646:
... | 628 | 345 |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | 1,400 | 465 |
from skin_reaper import SkinReaper
if __name__ == "__main__":
r = SkinReaper()
data = r.harvestLinks(5)
r.setSkinPreview()
r.collectRandom(data)
r.kill() | 174 | 70 |
# Credits go to <http://codereview.stackexchange.com/q/37522>
import random
import time
def current_time():
'''Returns a tuple containing (hour, minute) for current local time.'''
local_time = time.localtime(time.time())
return (local_time.tm_hour, local_time.tm_min)
(hour, minute) = current_time()
de... | 528 | 190 |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='solar-viabili... | 575 | 199 |
# -*- coding: utf-8 -*-
# @Time : 2021/5/4 下午3:05
# @Author : godwaitup
# @FileName: framework.py
# original framework for joint extraction.
import torch.optim as optim
from torch import nn
import os
import data_loader
import torch.nn.functional as F
import numpy as np
import json
from functools import partial
fro... | 31,028 | 10,330 |
"""
Settings for application when being run in the test suite.
"""
import os
import sys
# Add the directory containing this file to the search path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import function to generate a self-signed cert dynamically
from x509cert import gen_self_signed_cert
DEBUG... | 799 | 291 |
ips = [
'10.0.0.5',
'10.5.3.1',
'192.168.11.10',
'2.2.2.2',
'100.0.0.1',
'20.3.2.4'
]
def getKey(item):
return tuple(int(part) for part in item.split('.'))
def sort_ips(iplist):
return sorted(ips, key=getKey)
print(sort_ips(ips))
| 254 | 150 |
#!/usr/bin/python
import os
import sys
import glob
import argparse
import tempfile
import numpy as np
from scipy.io import *
from scipy import stats
from subprocess import Popen, PIPE
from scai_utils import *
from get_qdec_info import get_qdec_info
from read_xml_labels import read_xml_labels
atlas_label_fn = \
"... | 5,330 | 2,031 |
# Module to scrap all auction listings on the auction prices page
from selenium import webdriver
from bs4 import BeautifulSoup
import csv
import os
# Utility to write as .csv file format
def save_to_csv(data, SAVE_PATH, MODE):
if not os.path.exists(SAVE_PATH.split('/')[0]):
os.makedirs(SAVE_PATH.s... | 1,995 | 752 |
/home/runner/.cache/pip/pool/7d/da/46/b543433b18dcfd975ecc18a25baa2105812baf0edc0bdbfae3890e1df2 | 96 | 69 |
"""Location cards."""
import logging
from onirim.card._base import ColorCard
from onirim import exception
from onirim import util
LOGGER = logging.getLogger(__name__)
class LocationKind(util.AutoNumberEnum):
"""
Enumerated kinds of locations.
Attributes:
sun
moon
key
"""
... | 3,343 | 1,005 |
import pytest
from gitlabform.gitlabform import GitLabForm
from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, create_readme_in_project, \
GROUP_NAME
PROJECT_NAME = 'branches_project'
GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME
@pytest.fixture(scope="module")
d... | 4,247 | 1,343 |
from bespin.errors import StackDepCycle
class Layers(object):
"""
Used to order the creation of many stacks.
Usage::
layers = Layers({"stack1": stack1, "stack2": "stack2, "stack3": stack3, "stack4": stack4})
layers.add_to_layers("stack3")
for layer in layers.layered:
#... | 2,543 | 732 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""events.py
Pulse sequence events for the Arduino Due pulsebox.
Radim Hošák <hosak(at)optics.upol.cz>
2021 Quantum Optics Lab Olomouc
"""
from functools import reduce
from pulsebox.codeblocks import state_change, loop, channel_states_to_odsr
from pulsebox.config impor... | 6,851 | 1,965 |
def words_to_sentence(words: list) -> str:
""" This function create a string from a list of strings, separated by space. """
return ' '.join(words)
| 160 | 46 |
# Copyright 2020 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... | 1,839 | 568 |
import pytest
import os
from tests import test_analyzer
from spectra_analyzer import analyzer
def file_ref(name):
"""Helper function for getting paths to testing spectra."""
file = os.path.join(os.path.dirname(test_analyzer.__file__),
"test_analyzer", name)
return file
def normal... | 3,291 | 1,076 |
from django.shortcuts import render
from .models import User
from . import forms
# Create your views here.
def index(request):
context = {
'django':'The Web Framework for Developers with a deadline'
}
return render(request,'index.html', context=context)
def signup(request):
sign_up = forms.User... | 774 | 234 |
import unittest
from submitty_utils import string_utils
class TestUser(unittest.TestCase):
def testNegativeLength(self):
self.assertEqual(string_utils.generate_random_string(-1), '')
def testZeroLength(self):
self.assertEqual(string_utils.generate_random_string(0), '')
def testPositiveL... | 920 | 285 |
import os
class FileHandler:
def __init__(self):
self.directory = os.path.expanduser('~') + '/.simple_backup'
if not os.path.exists(self.directory):
os.mkdir(self.directory)
def save (self, filename, data):
f = open(self.directory + '/' + filename, 'w')
f.write(da... | 486 | 155 |
import os
import argparse
import logging
import numpy as np
import SimpleITK as sitk
logging.basicConfig(level=logging.INFO)
from tqdm import tqdm
import cv2
import sys
from PIL import Image
from sklearn import metrics
def Accuracy(y_true, y_pred):
TP = np.sum(np.logical_and(y_pred == 255, y_true == 255))
TN =... | 3,449 | 1,429 |
from app.models.enums.station import Station
class Parser:
def __init__(self, data):
self.data = data
def getDataByStation(self, station):
airDataForStation = {"timeSet": [], "level": [], "airType": [], "invalid": []}
for d in self.data:
if int(d.station) == station:
... | 2,757 | 768 |
import os
import sys
import copy
import asyncio
import logging
import argparse
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.lib.cli as s_cli
import synapse.lib.cmd as s_cmd
import synapse.lib.node as s_node
import synapse.lib.time as s_time
import ... | 11,747 | 3,853 |
from sklearn.feature_selection import VarianceThreshold
# Create feature matrix with:
# Feature 0: 80% class 0
# Feature 1: 80% class 1
# Feature 2: 60% class 0, 40% class 1
X = [[0, 1, 0],
[0, 1, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0]]
# Run threshold by variance
thresholder = VarianceThreshold(thre... | 374 | 170 |
#!/usr/bin/python3
import sys
sys.path.insert(0, '../..') # make '..' first in the lib search path
import gzip
import numpy
from lemminflect.kmodels.ModelLemma import ModelLemma
from lemminflect.kmodels.ModelLemmaInData import ModelLemmaInData
from lemminflect.kmodels.ModelLemmaClasses import ModelLemm... | 1,677 | 584 |
# coding=utf-8
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
from _ctypes import byref, pointer
from builtins import range, str
from ctypes import c_char_p, string_at
from snips_nlu_parsers.utils import (CStringArray, check_ffi_error, lib,
... | 9,006 | 2,870 |
import os;os.environ['TMPDIR'] = os.path.join(os.environ['HOME'], 'tmp')
import pwn
remote_binary = "/problems/got_5_c5119617c90aa544a639812dbc41e24e/vuln"
def segfault():
try:
pr = pwn.process(remote_binary)
elf = pwn.ELF(remote_binary, False)
print(elf.got)
pr.sendlineafter("Inpu... | 521 | 212 |
#!/usr/bin/env python
# coding: utf-8
# *Author: Dezso Ribli*
"""
Util functions for training CNN on weak lesnsing maps.
Mostly data loaders and data generators with some
additional functionality.
"""
import numpy as np
# https://github.com/IntelPython/mkl_fft/issues/11
#np.fft.restore_all()
import cv2
import math... | 9,518 | 3,577 |
import hashlib
import io
import json
import os
import re
import struct
def decode_bin(s, encoding=None):
if encoding is None:
encoding = "utf-8"
if encoding in ("bin", "binary", "bytes", "raw"):
return s
return s.decode(encoding)
class open_output(object):
def __init__(self, filename,... | 4,683 | 1,540 |
class Element:
def __init__(self, name : str, symbol : str, Z : int):
self.name = name
self.symbol = symbol
self.Z = Z
def __repr__(self):
return "Element(\"{0}\", Z={1})".format(self.name, self.Z)
def __str__(self):
return self.symbol
... | 2,080 | 631 |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
import logging
import unittest
from unittest import mock
from vdk.plugin.control_api_auth.authentication import Authentication
from vdk_provider.hooks.vdk import VDKHook
log = logging.getLogger(__name__)
# Monkey-patch the authentication logic to a... | 2,924 | 1,020 |
"""Funcs for logging"""
import logging
_CRITICAL = logging.CRITICAL
_ERROR = logging.ERROR
_WARNING = logging.WARNING
_INFO = logging.INFO
_DEBUG = logging.DEBUG
_NOTSET = logging.NOTSET
def build_logger(log_level, logger_name, capture_warning=True):
logger = logging.Logger(logger_name)
# All warnings are ... | 720 | 236 |
#!/usr/bin/env python3
# https://leetcode.com/problems/contains-duplicate/
import unittest
from typing import List
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)... | 575 | 200 |
from __future__ import division
import numpy as np
np.seterr(divide='ignore') # these warnings are usually harmless for this code
from matplotlib import pyplot as plt
import copy, os
import pyhsmm
from pyhsmm.util.text import progprint_xrange
###################
# generate data #
###################
T = 1000
obs_d... | 1,818 | 692 |
from django.db import transaction
from rest_framework.exceptions import ValidationError
from .base_nested_mixin import BaseNestedMixin
class UpdateNestedMixin(BaseNestedMixin):
@transaction.atomic
def update(self, instance, validated_data):
"""
:param instance:
:param validated_data:
... | 2,644 | 674 |
__version__ = "2021.10.07"
| 27 | 18 |
"""Make datasets available."""
from forayer.datasets.oaei_kg import OAEIKGDataset
from forayer.datasets.open_ea import OpenEADataset
__all__ = ["OpenEADataset", "OAEIKGDataset"]
| 179 | 66 |
from django.contrib import admin
from challenge.models import Goal, GoalInstance, SignificantOther
# Register your models here.
admin.site.register(Goal)
admin.site.register(GoalInstance)
admin.site.register(SignificantOther)
| 227 | 66 |
import library
import random
import re
def allocate(studPrefs,unassignedStudents,lecturerprefs,projLects,lectProjs,lecturercaps,projCaps,randomise,updates,iterationLimit):
# Create projected preference list - first pass; add students not on lecturer's list
for k, v in studPrefs.items():
for project in v:
... | 14,142 | 5,806 |
import pytest
# External imports
import numpy as np
from gpmap import GenotypePhenotypeMap
# Module to test
import epistasis
from epistasis.models.classifiers import *
THRESHOLD = 0.2
@pytest.fixture
def gpm(test_data):
"""
Create a genotype-phenotype map
"""
d = test_data[0]
return GenotypePh... | 3,271 | 1,104 |
from django.contrib import admin
from .models import Notification
class NotificationAdmin(admin.ModelAdmin):
ordering = ('published',)
search_fields = ('get_author',)
list_display = ('id', 'get_author', 'published', 'summary')
def get_author(self, obj: Notification):
return obj.author.displa... | 381 | 106 |
import bz2
import time
import urllib.request
import io
from typing import List, Tuple
from credo_cf import load_json_from_stream, progress_and_process_image, group_by_device_id, group_by_resolution, too_often, near_hot_pixel2, \
too_bright
from credo_cf import xor_preprocess
from credo_cf.commons.utils import get_... | 3,655 | 1,293 |
from apptweak.plateform import *
class Ios(Plateform):
plateform_name = 'ios'
def __init__(self):
super().__init__(self.plateform_name)
@classmethod
def ratings(self, application_id, params = {}):
return self.applications(application_id, API_END_PATH['ratings'], params)
@classmet... | 427 | 128 |
print('---------- Opening Files for Reading ----------')
f = open('./files/reading_file_example.txt')
print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='cp936'>
print('\t---------- read() ----------')
# read(): read the whole text as string. If we want to limit the number of char... | 3,944 | 1,343 |
#!/usr/bin/env python
import os
from glob import glob
import json
import pandas
import datetime
import sys
here = os.path.dirname(os.path.abspath(__file__))
folder = os.path.basename(here)
latest = '%s/latest' % here
year = datetime.datetime.today().year
output_data = os.path.join(here, 'data-latest.tsv')
output_year... | 2,491 | 768 |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 10 07:20:39 2022
@author: maout
"""
import numpy as np
from scipy.spatial.distance import cdist
import torch
#from score_function_estimators import my_cdist
from typing import Union
from torch.autograd import grad
#%% select available device
def set_device():
device... | 10,476 | 3,542 |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import tflearn
from tflearn import variables as vs
from tflearn import activations
from tflearn import initializations
from tflearn import losses
from tflearn import utils
def condition(cond, t, f):
i... | 11,075 | 3,215 |
from ..testcases import DustyTestCase
from dusty.warnings import Warnings
class TestWarnings(DustyTestCase):
def setUp(self):
super(TestWarnings, self).setUp()
self.warnings = Warnings()
def test_warn(self):
message_1 = 'Something is wrong, yo'
message_2 = 'Yo this thing is al... | 1,984 | 629 |
from random import randint
import re
# Supported formats:
# [A]dX[(L|H|K)n][.Y1[.Y2[...]]]
# A - number of dice
# X - number of sides of dice
# . - operation: allowed are + - * x /
# Ln/Hn/Kn - discard the Lowest n dice or Keep the Highest n dice. - will only apply the first of these, in order LHK
# Y1,Y2,...... | 4,655 | 1,486 |
import os
from sentiment_discovery.reparameterization import remove_weight_norm
from sentiment_discovery.model import make_model
class ModuleConfig(object):
def __init__(self, parser):
super(ModuleConfig, self).__init__()
self.parser = parser
def apply(self, cfg, opt):
"""make model and format model... | 2,471 | 931 |
"""Tests for the ConsoleEnvironment and Console helper."""
from j5.backends.console import Console
def test_console_instantiation() -> None:
"""Test that we can create a console."""
console = Console("MockConsole")
assert type(console) is Console
assert console._descriptor == "MockConsole"
def tes... | 4,309 | 1,247 |
from os import listdir, remove, makedirs
from os.path import isfile, join, exists
import shutil
import joblib
from termcolor import cprint
import json
from pathlib import Path
_cache_path = None
_log_actions = True
def init(cache_path, log_actions=True):
"""
Initializes the cache.
Keyword Arguments:
... | 6,351 | 1,908 |
import torch
import os
import numpy as np
import random
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from data.tileimages import *
from data.multitask import *
import fastai
from fastai.vision import *
class FoldSampler:
def __init__(self, TRAIN, LABELS,
mean, std, N,
... | 8,123 | 2,427 |
def main():
# input
A, B = map(int, input().split())
# compute
# output
if A+B>=15 and B >= 8:
print(1)
elif A+B>=10 and B>=3:
print(2)
elif A+B >= 3:
print(3)
else:
print(4)
if __name__ == '__main__':
main()
| 281 | 117 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from ase.build import molecule
from ase.lattice.cubic import SimpleCubic
from graphdot.graph import Graph
from graphdot.graph.adjacency import AtomicAdjacency
adjacencies = [
AtomicAdjacency(shape='tent1', length_scale=1.0, zoom=1),
AtomicAdjacency(s... | 2,578 | 1,155 |
import string
import scipy
import PslgIo, ElementAwarePslg
def loadEle(filename):
pslg = ElementAwarePslg.ElementAwarePslg()
file = open(filename, "r")
try:
PslgIo.readFromFile(file, pslg, filename)
finally:
file.close()
return pslg
def saveFem(filename, femResults):
#Open the ... | 2,735 | 852 |
"""
DIANNA: Deep Insight And Neural Network Analysis.
Modern scientific challenges are often tackled with (Deep) Neural Networks (DNN).
Despite their high predictive accuracy, DNNs lack inherent explainability. Many DNN
users, especially scientists, do not harvest DNNs power because of lack of trust and
understanding ... | 3,466 | 992 |
try:
import RPi.GPIO as GPIO
except RuntimeError:
print("Error importing RPi.GPIO! This is probably because you need "
"superuser privileges. You can achieve this by using 'sudo' to run "
"your script")
gpios = [7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29,
31, 32... | 2,925 | 970 |
#!/usr/bin/env python
import rospy # For all things ros with python
# JointState is defined in sensor_msgs.msg
# If you know a message but not where it is
# call rosmsg info MSGNAME from the terminal
from sensor_msgs.msg import JointState
# This tutorial takes heavily from
# http://wiki.ros.org/ROS/Tutorials/WritingP... | 1,395 | 403 |
#!/usr/bin/env python
# Aran Sena 2018
#
# Code example only, provided without guarantees
#
# Example for how to get both cameras streaming together
#
####
import rospy
from intera_core_msgs.srv._IOComponentCommandSrv import IOComponentCommandSrv
from intera_core_msgs.msg._IOComponentCommand import IOCompon... | 1,291 | 437 |
# -*- coding: utf-8 -*-
"""
Created on Sun May 2 2021
@name: CityData CensusTract Download Application
@author: Jack Kirby Cook
"""
import sys
import os.path
import warnings
import logging
import regex as re
MAIN_DIR = os.path.dirname(os.path.realpath(__file__))
MODULE_DIR = os.path.abspath(os.path.join(MAIN_DIR, ... | 12,279 | 4,160 |
import math
def estimate_lowest_divisor(method, divisor, populations, seats):
"""
Calculates the estimated lowest possible divisor.
:param method: The method used.
:type method: str
:param divisor: A working divisor in calculating fair shares.
:type divisor: float
:param populations: Th... | 3,644 | 1,092 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
# import pylatex
from pylatex import Document, Section, Tabular, Math, Axis, Subsection
import pandas as pd
import sys
import os
def main():
pm = u"\u00B1"
filename = sys.argv[1]
results = pd.read_csv(filename+'.csv')
cols = results.col... | 4,084 | 1,369 |
import os.path as osp
import yaml
import torch.nn as nn
from torch import hub
__all__ = ['get_vggish', 'vggish_category_metadata']
model_urls = {
'vggish': "https://github.com/w-hc/vggish/releases/download/v0.1/vggish_orig.pth",
'vggish_with_classifier': "https://github.com/w-hc/vggish/releases/download/v0.1... | 2,803 | 1,071 |
import os
import warnings
import pandas
import sqlite3
import logging
from typing import List
from dask import delayed, dataframe
from contextlib import closing
from cuchemcommon.utils.singleton import Singleton
from cuchemcommon.context import Context
warnings.filterwarnings("ignore", message=r"deprecated", categor... | 12,584 | 3,722 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='CustomUser',
fields=[
('id', models.AutoField(s... | 769 | 211 |
from PyObjCTools.TestSupport import *
import objc
import Foundation
if hasattr(Foundation, 'NSMachPort'):
class TestNSMachPort(TestCase):
def testAlloc(self):
obj = Foundation.NSMachPort.alloc()
self.assertIsNot(obj, None)
obj = obj.init()
self.assertIsNot(o... | 370 | 117 |
#!/usr/bin/env python2
"""Command line utility for querying the Logitech Harmony."""
import argparse
import logging
import json
import sys
import auth
import client as harmony_client
LOGGER = logging.getLogger(__name__)
def login_to_logitech(args):
"""Logs in to the Logitech service.
Args:
args: ar... | 7,125 | 2,178 |
#
# MIT No Attribution
#
# 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, distribute, subli... | 14,567 | 4,575 |
alpha = "abcdefghijklmnopqrstuvwxyz"
n = int(raw_input())
for i in xrange(n):
word = raw_input()
aux_word = ""
first_part = ""
second_part = ""
for j in xrange(len(word)-1, -1, -1):
if(word[j].lower() in alpha):
aux_word += chr(ord(word[j]) + 3)
else:
aux_word += word[j]
middle = (len(word)/2)
firs... | 483 | 220 |
import numpy as np
# For file manipulation and locating
import os
# For the progress bar
from tqdm import tqdm
# To create a deep copy of the data
import copy
# To load the pre-processed and split data
from pre_process import load_data as ld
# For normalization of the samples
from sklearn.preprocessing import normalize... | 6,095 | 1,920 |
import pandas as pd
import time
from image_matcher import read_image, bjorn_score
def main(data_location='../data/', data_file='input.csv'):
df = pd.read_csv(data_location + data_file)
score_list, runtime_list = [], []
for idx, row in df.iterrows():
image1_file, image2_file = data_location + \
... | 776 | 266 |
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
class Encryptor:
def __init__(self):
#Todo: read key from file
... | 2,006 | 618 |
# Question 7
# Find out the number of CPUs using
import os
print("Number of CPUs using:", os.cpu_count())
# Alternative,
""" import multiprocessing
print("Number of CPUs using:", multiprocessing.cpu_count()) """
| 218 | 74 |
import re
import datetime
import lxml.html
import requests
from billy.utils.fulltext import text_after_line_numbers
from .bills import IABillScraper
from .legislators import IALegislatorScraper
from .events import IAEventScraper
from .votes import IAVoteScraper
# Silencing unverified HTTPS request warnings.
requests.p... | 3,081 | 1,104 |
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.writer.excel import save_virtual_workbook
class ExcelFile:
def __init__(self, file_name):
self.file_name = file_name
self.workbook = Workbook()
self.active_worksheet = self.workbook.active
sel... | 2,965 | 878 |
import vipy
from vipy.flow import Flow
import numpy as np
def test_flow():
imfrom = vipy.image.RandomScene(num_objects=1)
imto = imfrom.clone().zeropad(5, 10).cornercrop(imfrom.height(), imfrom.width())
imf = Flow().imageflow(imfrom, imto)
assert np.abs(np.median(imf.dx()) - 5) < 1 and np.abs(np.median... | 435 | 184 |
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED=21
BUZZER=23
GPIO.setup(LED,GPIO.OUT)
def panikMode():
print("Entering PanikMode")
GPIO.output(LED,GPIO.HIGH)
GPIO.output(BUZZER,GPIO.HIGH)
... | 660 | 292 |
# -*- coding: utf-8 -*-
"""bootstrap_py.tests.test_package."""
import unittest
import os
import shutil
import tempfile
from glob import glob
from datetime import datetime
from mock import patch
from bootstrap_py import package
from bootstrap_py.tests.stub import stub_request_metadata
# pylint: disable=too-few-public-... | 8,656 | 2,801 |
# Generated by Django 3.2.6 on 2021-08-30 13:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20210830_0359'),
]
operations = [
migrations.AlterField(
model_name='article',
name='urlToImage',
... | 383 | 141 |
from pathlib import Path
import numpy as np
import tables
# Use snapshot from aug08 before the last update that broke things.
with tables.open_file('cmds_aug08.h5') as h5:
cmds = h5.root.data[:]
print(cmds.dtype)
# [('idx', '<u2'), ('date', 'S21'), ('type', 'S12'), ('tlmsid', 'S10'),
# ('scs', 'u1'), ('step', '<... | 1,175 | 498 |
"""
18. Faça um programa que peça o tamanho de um arquivo para download (em MB) e
a velocidade de um link de Internet (em Mbps), calcule e informe o tempo
aproximado de download do arquivo usando este link (em minutos).
"""
mb_arquivo = float(input('Informe o tamanho de um arquivo para download (em MB): '))
mbps_lin... | 579 | 204 |
import argparse
import pickle
import os
import json
from sklearn.metrics import confusion_matrix
from utils.data_reader import embed_data_sets_with_glove, embed_data_set_given_vocab, prediction_2_label
from utils.text_processing import vocab_map
from common.util.log_helper import LogHelper
from deep_models.MatchPyramid... | 4,802 | 1,505 |
import shutil, os, random
from pydub import AudioSegment
try:
os.mkdir('noise')
except:
shutil.rmtree('noise')
os.mkdir('noise')
def extract_noise(filename, length):
song = AudioSegment.from_mp3(filename)
first = song[100:100+length]
first.export(filename[0:-4]+'_noise.mp3')
shutil.move(os.getcwd()+'/'+filename[... | 854 | 380 |
from django.conf.urls import url
from Apps.Apiv2.views import GetARResourcesView, GetARExperienceDetailView
from Apps.Apiv2.views import GetTagListView,GetARExperienceRecommendList,GetARExperiencePublicListView,GetARExperiencesView
from Apps.Apiv2.views import GetARexperienceByTagsListView
app_name = 'Apps.Users'
urlp... | 1,030 | 363 |