text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
# (c) 2008-2010, Marcin Kasperski
"""
Create and parse XMind maps.
"""
from lxml import etree
import zipfile
from .id_gen import IdGen, qualify_id, unique_id
from .xmlutil import XmlHelper, ns_name, \
CONTENT_NSMAP, STYLES_NSMAP, find_xpath
import logging
log = logging.getLogger(__name__)... | 25,115 | 7,348 |
import setuptools
setuptools.setup(
name="diplomova-praca-jankasvk",
version="0.0.1",
author="Jana Bátoryová",
author_email="janulik11@gmail.com",
description="Diplomova Praca lib",
long_description_content_type="text/markdown",
url="https://github.com/JankaSvK/thesis-grizzly",
... | 928 | 326 |
#
# @lc app=leetcode id=47 lang=python3
#
# [47] Permutations II
#
# @lc code=start
class Solution:
def generate(self, nums: list[int], pos: int) -> set[tuple[int]]:
if pos == len(nums):
return {tuple(nums)}
output = set()
for i in range(pos, len(nums)):
nums[pos], ... | 618 | 238 |
from haystack import indexes
from django.contrib.auth.models import User
from .models import Posts, Groups, HighSchools, University, Teams, Companies, Hobbies, PLanguages
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
post = indexes.EdgeNgra... | 3,746 | 1,096 |
from backend.routes import main
from social.apps.flask_app import routes
| 73 | 20 |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 15:59:32 2021
@author: vhamalai
"""
#!/usr/bin/python
# vim: set fileencoding=UTF-8 :
"""
load p3
Python 3 version of load.py
todo doc
"""
import sys,os,getopt
import requests
import json
import base64
from time import localtime, strftime
import dboperator
def maker... | 5,574 | 2,293 |
from datetime import date
from decimal import Decimal
import pytest
import netsgiro
def test_transmission_with_single_payment_request_transaction():
transmission = netsgiro.Transmission(
number='1703231',
data_transmitter='01234567',
data_recipient=netsgiro.NETS_ID,
)
assignment ... | 5,720 | 2,185 |
import datetime
from django import forms
from django.forms import ModelForm
from django.utils import timezone
from .models import Category, Transaction, Account
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = [
'name',
]
class TransactionForm(ModelForm)... | 778 | 209 |
# 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, software
# distributed under t... | 4,823 | 1,313 |
import re # Regular expressions
import string
import sys
from unidecode import unidecode
class Slugifier(object):
def __init__(self):
self.to_lower = True
self.safe_chars = string.ascii_letters + string.digits # "a...zA...Z0...9"
self.separator_char = '-'
def slugify(self, text):
... | 1,248 | 359 |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# 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 ... | 2,418 | 736 |
import serial
import time
import pandas as pd
from datetime import date,datetime
name=list()
roll=list()
time=list()
time_left=dict()
try:
ser=serial.Serial('COM3',9600)
except:
print("Processing")
column_names=['Name','Roll_No','Time','Time_left']
df=pd.DataFrame(columns=column_names)
i=0
while... | 2,127 | 799 |
from gaia_sdk.graphql.request.type.DeleteKnowledge import DeleteKnowledge
from gaia_sdk.graphql.request.type.UpdateKnowledge import UpdateKnowledge
from gaia_sdk.graphql.request.type.CreateKnowledge import CreateKnowledge
from gaia_sdk.graphql.request.type.ConnectKnowledge import ConnectKnowledge
from typing import C... | 2,070 | 575 |
from __future__ import print_function
import os
import sys
import getopt
##Count the number of minor variants in a target vcf reported as major variant in a reference vcf, adapted to lofreq vcf
#v0.0.1
def main(argv):
global ref
global var
global con
global oup
global oud
global ... | 7,634 | 2,979 |
import itertools
import os
import subprocess
import tempfile
from vulture_whitelist.utils import Creator, log
from lxml import etree
FEATURES = ['PyQt_Accessibility', 'PyQt_SessionManager', 'PyQt_SSL',
'PyQt_qreal_double', 'Py_v3', 'PyQt_PrintDialog', 'PyQt_Printer',
'PyQt_PrintPreviewWidget... | 3,372 | 1,284 |
#!/usr/bin/env python3
import os
import time
import h5py
import numpy as np
import pandas as pd
from pprint import pprint
import matplotlib.pyplot as plt
plt.style.use("../../pygama/clint.mpl")
from pygama import DataSet, read_lh5, get_lh5_header
import pygama.analysis.histograms as pgh
def main():
"""
this i... | 2,626 | 1,086 |
import json
from infrastructure import company_smtp
from infrastructure import companies
def save_company_smtp(data, id_company):
_host = data['host']
_user = data['user']
_password = data['password']
_port = data['port']
_encrypt_type = data['encrypt_type']
company_exist = companies.verify_c... | 1,748 | 538 |
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
class CloudFrontTLS12(BaseResourceValueCheck):
def __init__(self):
name = "Verify CloudFront Distribution Viewer Certificate is using TLS v1.2... | 1,711 | 518 |
import os
import logging
import numpy as np
import multiprocessing
from pathlib import Path
from tabulate import tabulate
import pandas as pd
from sklearn.model_selection import GroupShuffleSplit, train_test_split
from tqdm import tqdm_notebook as tqdm
import pickle
import torch
from torch.utils.data import Dataset, ... | 21,435 | 6,553 |
from abc import ABC, abstractmethod
from typing import Callable, Iterable, Iterator
from checklisting.task import Checklist
class BaseChecklistsProvider(ABC):
@abstractmethod
def get_all(self) -> Iterator[Checklist]:
pass
@abstractmethod
def get_filtered(self, predicate: Callable[[Checklist... | 763 | 220 |
class BaseFormat:
__byteorder = {
None: "=",
"little": "<",
"big": ">"
}
def __init__(self):
self.__byteorder = None
self._minPacketSize = None
@property
def byteorder(self):
return self.__byteorder
@byteorder.setter
def byteorder(self, byteorder):
... | 1,171 | 368 |
from django.db import models
class Question(models.Model):
question_text = models.CharField("Question", max_length=200)
pub_date = models.DateTimeField("date_published", auto_now=False, auto_now_add=False, null=True)
class Choice(models.Model):
question = models.ForeignKey("polls.Question", on_delete=mo... | 446 | 144 |
import numpy as np
import matplotlib.pyplot as plt
def plot_rf(rf, out_dim, M):
rf = rf.reshape(out_dim, -1)
# normalize
rf = rf.T / np.abs(rf).max(axis=1)
rf = rf.T
rf = rf.reshape(out_dim, M, M)
# plotting
n = int(np.ceil(np.sqrt(rf.shape[0])))
fig, axes = plt.subplots(nrows=n, ncols... | 879 | 389 |
'''
Name: color_segmentation.py
Version: 1.0
Summary: K-means color clustering based segmentation. This is achieved
by converting the source image to a desired color space and
running K-means clustering on only the desired channels,
with the pixels being grouped into a desired number
... | 19,883 | 6,915 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mediapipe/framework/testdata/zoo_mutator.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection a... | 5,819 | 2,218 |
"""
distribution.py
Author: Christopher Lee
Credit: https://developers.google.com/edu/python/sorting
Assignment:
Write and submit a Python program (distribution.py) that computes and displays
the distribution of characters in a given sample of text.
Output of your program should look like this:
Please enter a stri... | 1,524 | 437 |
from sys import stdin, setrecursionlimit
def euler_tour(n, i):
left[n] = i
i += 1
for c in children[n]:
i = euler_tour(c, i)
right[n] = i
return i
readline = stdin.readline
setrecursionlimit(10 ** 6)
N = int(readline())
root = -1
children = [[] for _ in range(N)]
for i in range(N):
... | 707 | 294 |
import datetime
import seaborn as sns
import numpy as np
import pandas as pd
# import MySQLdb as SQL
import pymysql.cursors
import matplotlib.pyplot as plt
from helper import linear_regression as lr
from helper import general as general
con = {"host": '60.205.94.60',
"port": 33009,
"user": 'bluestackscn'... | 9,713 | 3,736 |
#!/usr/bin/env python3
#
# Copyright 2020 NVIDIA 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 applic... | 2,855 | 852 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
def hidden_init(layer):
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class MADDPGModel(nn.Module):
def __init__(self, n_agents, state_dims, ... | 8,184 | 2,502 |
# Class that implements isotropic spherical DFs computed using the Eddington
# formula
import numpy
from scipy import interpolate, integrate
from ..util import conversion
from ..potential import evaluateR2derivs
from ..potential.Potential import _evaluatePotentials, _evaluateRforces
from .sphericaldf import isotropicsp... | 5,924 | 1,994 |
from cog.models import *
from django.forms import ModelForm, ModelMultipleChoiceField, NullBooleanSelect
from django.db import models
from django.contrib.admin.widgets import FilteredSelectMultiple
from django import forms
from django.forms import ModelForm, Textarea, TextInput, Select, SelectMultiple, FileInput, Check... | 9,756 | 2,586 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/3/17 11:52 上午
# @Author : xinming
# @File : 714_max_profit.py
from typing import List
class Solution2:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
buy = prices[0] + fee
profit = 0
for i i... | 1,121 | 515 |
import struct
import os
import sys
cmd = [
"Tx",
"TxSize",
"Alpha",
"End",
"Pos",
"ColorALL",
"Move",
"STAGE_BGM",
"SetFlat3D",
"ChangeFlat3D",
"SetCamDir",
"DisCamDir",
"Set3DObj",
"SetWAngleX",
"SetWAngleY",
"SetWAngleZ",
"SetLAngleX",
"SetLAngl... | 15,503 | 7,675 |
# yapf: disable
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['driver_station', 'driver_station.utils', 'driver_station.widgets'],
package_dir={'': 'src'}
)
s... | 330 | 119 |
from setuptools import setup
setup(
name='twitter-text-python',
version='1.0.1',
description='Twitter Tweet parser and formatter',
long_description="Extract @users, #hashtags and URLs (and unwind shortened links) from tweets including entity locations, also generate HTML for output. Visit https://githu... | 1,052 | 315 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,W0703,R0902,R1711,R0912,R0914,R0911
import os
import sys
import re
import argparse
import logging
import scandir
class FileScan:
def __init__(self, args=None):
pass
def scan(self, directory, all_files=None, file_types=None, all_fn... | 1,649 | 554 |
import asyncio
import unittest
from typing import Any, Coroutine
from pedantic.decorators.class_decorators import pedantic_class
from pedantic.exceptions import PedanticTypeCheckException
from pedantic.decorators.fn_deco_pedantic import pedantic
class TestPedanticAsyncio(unittest.IsolatedAsyncioTestCase):
async ... | 1,863 | 521 |
from ..factory import Type
class chatActionUploadingDocument(Type):
progress = None # type: "int32"
| 104 | 33 |
"""
sensitivity analysis naming
"""
def index_transition(n_dim, exclude=None):
"""
suppose orginal list is [0, 1, ..., n_dim - 1]
exclude = [0, 2]
return two dictionaries,
1), original to new dictionary
2), and new to original dictionary
"""
o_2_n = dict()
n_2_o = dic... | 554 | 207 |
#!/usr/bin/env python3
"""Boussinesq equations of state.
This module provides two functions for the equation of state (EOS) of seawater
suitable for Boussinesq ocean models. In both cases, the thermodynamic
variables are absolute salinity, conservative temperature, and depth. In
comparison, the standard formulation of... | 10,893 | 3,849 |
import sys
import secrets
sys.path.insert(0, "../argo")
from end_to_end import EndToEndJob, load_yaml, submit_jobs # noqa: E402
group = secrets.token_hex(3)
def _get_job(
config_name: str,
exp_tag: str,
limit_negative_qc: bool = False,
limit_negative_qv: bool = False,
):
config = load_yaml(f"... | 1,578 | 634 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
import traceback
import vymgmt
from vpn.models import Member
logger = logging.getLogger('vpn')
def disable_member(username):
"""
禁用租户
:return:
"""
try:
member = Member.objects.get(username... | 2,991 | 887 |
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar e vai retornar um dicionário com as seguntes informações: -Qauntidade de notas; -A maior nota; -A menor nota; -A média da turma; -A situção(opcional(padrão=False)). Adicione também as docstrings da função. Passar vár... | 1,363 | 522 |
import os
import sys
import random
import configparser
import pathlib
import platform
import json
import fHDHR.exceptions
from fHDHR import fHDHR_VERSION
from fHDHR.tools import isint, isfloat, is_arithmetic, is_docker
class Config():
def __init__(self, args, script_dir, fHDHR_web):
self.fHDHR_web = fHD... | 15,679 | 4,455 |
from typing import (
NewType,
TypeVar,
Union,
)
from eth_typing import Address
HexAddress = NewType('HexAddress', str) # for hex encoded addresses
ChecksumAddress = NewType('ChecksumAddress', HexAddress) # for hex addresses with checksums
AnyAddress = TypeVar('AnyAddress', Address, HexAddress, Checksum... | 415 | 133 |
from cachecat.session import Session
session = Session(1337)
for step, token in session:
try:
print("Step %i contains: %s” % (step, cache[token]))
except KeyError:
print("Missing step: %i" % (step))
break
| 249 | 89 |
"""
Descrição: Este programa calcula o reajuste correto de acordo com o salário do funcionário
Autor:Henrique Joner
Versão:0.0.1
Data:25/11/2018
"""
#Inicialização de variáveis
salario = 0
aumento = 0
novosalario = 0
#Entrada de dados
salario = float(input("Para que possamos verificar o seu reajuste, informe o se... | 641 | 280 |
"""What relationships (ownership, association...) do users have to things?"""
import logging
from model import DatastoreModel
def owns(user, id_or_entity):
"""Does this user own the object in question?"""
# Supers own everything.
if user.super_admin:
return True
if owns_program(user, id_or... | 2,332 | 725 |
from django.conf.urls import url
from django.contrib import admin as djadmin
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from .djangoadmin import UserAdminModel
from .views.admin.bans import BansList, DeleteBan, EditBan, NewBan
from .views.admin.ranks import (... | 4,005 | 1,321 |
from annoying.functions import get_object_or_None
from django.db import transaction
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views.generic import ListView, DetailView, UpdateView, DeleteView
from django.views.generic.edit import CreateView
from config import constants
... | 2,716 | 823 |
"""
Django Extensions abstract base model classes.
"""
from django.db import models
from django_extensions.db.fields import ModificationDateTimeField, CreationDateTimeField
class TimeStampedModel(models.Model):
""" TimeStampedModel
An abstract base class model that provides self-managed "created" and
"mod... | 469 | 121 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | 13,268 | 4,064 |
from Tkinter import *
import ttk
import random
import time
window = Tk()
canvas = Canvas(window, width=854, height=480, bg='white')
canvas.pack()
#Creates window and centers to any screen
window.geometry('{}x{}'. format(874, 670)) #Setting size of window
window.withdraw() #Hide window to stop showing in wrong positio... | 35,558 | 10,832 |
# ----- Info ------------------------------------------------------------------
__author__ = 'Michael Montero <mcmontero@gmail.com>'
# ----- Imports ---------------------------------------------------------------
from tinyAPI.base.services.cli import CLIOutputRenderer
import tinyAPI
import unittest
# ----- Tests -... | 940 | 192 |
from django.contrib.auth.backends import ModelBackend
from .models import User
class UserAuthenticationBackend(ModelBackend):
def authenticate(self, email, password, organization):
try:
user = User.objects.get(email__iexact=email,
organization=organization)... | 471 | 115 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-03-15 09:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('interface', '0005_dbquery_queries'),
]
operations = [
migrations.AlterField(
... | 796 | 246 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
pyspin
~~~~~~~
Little terminal spinner lib.
:copyright: (c) 2015 by lord63.
:license: MIT, see LICENSE for more details.
"""
__title__ = "pyspin"
__version__ = '1.1.1'
__author__ = "lord63"
__license__ = "MIT"
__copyright__ = "Copyright 2015 lord... | 324 | 147 |
from subscriber import podaac_data_subscriber as pds
import pytest
def test_temporal_range():
assert pds.get_temporal_range(None, '2021-01-01T00:00:00Z', "2021-08-20T13:30:38Z") == "1900-01-01T00:00:00Z,2021-01-01T00:00:00Z"
assert pds.get_temporal_range('2021-01-01T00:00:00Z', '2022-01-01T00:00:00Z', "2021-... | 3,892 | 1,931 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | 3,104 | 877 |
"""
Test stepping out from a function in a multi-threaded program.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ThreadStepOutTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
# Test occasionally times ou... | 6,251 | 1,861 |
import abc
import unittest
from yadi import decorators
from yadi import context_impl, types
class TestObjectInjection(unittest.TestCase):
def test_base_scopes_context_with_names(self):
sut = context_impl.BaseScopesContext()
class Component1I(metaclass=abc.ABCMeta):
pass
class... | 1,511 | 479 |
from __future__ import annotations
import os
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Tuple
from ParProcCo.scheduler_mode_interface import SchedulerModeInterface
from ParProcCo.utils import check_jobscript_is_readable, check_location, format_timestamp, get_absolute_pat... | 1,846 | 561 |
""" Helper methods for loading and parsing nuscenes2kitti data.
Authod: Siming Fan
Acknowledge: Charles R. Qi
Date: Jan 2020
"""
from __future__ import print_function
import os
import cv2
import numpy as np
import ipdb
import mayavi.mlab as mlab
class Object3d(object):
''' 3d object label '''
def __init__(se... | 23,767 | 9,677 |
# -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es archivo temporal
"""
import os
import glob
import errno
import argparse
from copy import deepcopy
from collections import Counter, OrderedDict
import numpy as np
import pandas as pd
from yaml import load, safe_dump
from win32com.client import Dispatch
try:
... | 16,681 | 4,600 |
import numpy as np
import pytest
from numpy.testing import assert_array_equal
import graphblas as gb
from graphblas import Matrix, Vector
@pytest.mark.parametrize("do_iso", [False, True])
def test_vector_head(do_iso):
v0 = Vector(int, 5)
if do_iso:
values1 = values2 = values3 = [1, 1, 1]
else:
... | 7,870 | 2,910 |
#!/usr/bin/env python3
###################################################################################################
#
# Project: Embedded Learning Library (ELL)
# File: train_classifier.py
# Authors: Chris Lovett
#
# Requires: Python 3.x
#
###############################################################... | 27,590 | 8,065 |
import paddle
import paddle.fluid as fluid
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
y_predict = fluid.layers.fc(input=x, size=1, act=None)
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(x=cost)... | 1,022 | 407 |
"""
Copyright 2021 Goldman Sachs.
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,
software di... | 5,308 | 1,845 |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
username = None
if request.session.get('username'):
username = request.session['username']
... | 716 | 197 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Set Methods
==============================================================================
"""
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
# Union
assert s1 | s2 == {1, 2, 3, 4, 5, 6}
assert set.union(s1, s2) == {1, 2, 3, 4, 5, 6}
assert s1.union(s2) == {1, 2, 3, 4, 5, 6}
as... | 801 | 411 |
#!/usr/bin/env python
"""
Script to find block names failed with block already in DBS error in cmsweb logs
To just find duplicated block names, one can use the following command in bash
grep -o -P \"(?<=Block name:\s)\S+$\" dbs-20130521.log | uniq -d
Not yet working since log files ar not consecutive at the moment
""... | 2,675 | 814 |
import numpy as np
import pandas as pd
import matplotlib.lines as mlines
import seaborn as sns
import hr_edl_data.experiment_parameters as xp
# Algorithm labels
_alg_label_map = {
'CFR': r'$\\\text{CF}$',
'A-EFR': r'$\\\text{ACT}$',
'CFR_IN': r'$\\\text{CF}_{\text{IN}}$',
'A-EFR_IN': r'$\\\text{ACT}_{\... | 11,644 | 4,821 |
import unittest
import click.testing
from multiply_ui.server.cli import mui_server
class CliTest(unittest.TestCase):
@classmethod
def invoke_cli(cls, *args):
runner = click.testing.CliRunner()
return runner.invoke(mui_server, args, catch_exceptions=False)
def test_help_option(self):
... | 938 | 281 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from commons.utils import Download
class SimpleLinearRegression:
def __init__(self, is_download: bool = False, filename: str = 'FuelConsumption.csv'):
... | 3,531 | 1,159 |
import unittest
import sys, os, shutil, tempfile
import tensorflow as tf
import numpy as np
import coremltools
from tensorflow.python.tools.freeze_graph import freeze_graph
from tensorflow.keras import backend as K
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Activat... | 5,242 | 1,640 |
from collections import OrderedDict
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from ipywidgets import Text, Image, Layout, GridBox
import plotly.graph_objs as go
import flask
import numpy as np
import pandas as pd
import pickle
i... | 9,343 | 3,098 |
import random
import numpy as np
class Sarsa:
def __init__(self, logic, epsilon, alpha, gamma, actions):
self.Q = {} # state-action dictionary
self.epsilon = epsilon # used for epsilon-greedy choice
self.alpha = alpha # used for diminished returns, "the sooner the better"
self.gamma = gamma # learning rate, i... | 1,760 | 566 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# 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
#
... | 50,735 | 18,125 |
# -*- coding: utf-8 -*-
"""Module for implementing demonstration procedure."""
from joint_pick_and_place import PickAndPlace
| 128 | 41 |
termo = int(input('Primeiro Termo: '))
razao = int(input('Razão: '))
decimo = 0
while decimo != 10:
print(termo, end=' ')
termo += razao
decimo += 1
| 161 | 72 |
"""unit tests for preprocess.py"""
import pytest
from src import preprocess
class TestPreprocessBulkText:
"""class holding test cases for preprocess_bulk_text function"""
# pylint: disable=no-self-use
@pytest.mark.parametrize('text, result', [
("""
Natural language processing (NLP) is the... | 3,867 | 1,048 |
import typing
from collections import Counter
from dataclasses import dataclass
from expyct.base import Equals, MapBefore, Satisfies, Optional, BaseMatcher
from expyct.base import Instance
@dataclass(repr=False, eq=False)
class AllOrAny(BaseMatcher):
"""Mixin for matching a collection object by checking that al... | 20,627 | 5,716 |
import numpy as np
import time
import multiprocessing
import ctypes
import warnings
#Suppress the divide by zero errors
warnings.filterwarnings('ignore', category=RuntimeWarning)
np.set_printoptions(linewidth = 200, suppress = True)
def fj_generate_sample(y, pct=0.10, random=True):
n = y.size
if random:
... | 6,914 | 2,351 |
"""
A simple model of the eletric transmission system of the Czech Republic.
"""
__version__ = "0.1.0"
| 104 | 35 |
import discord
from discord.ext import commands
from yonosumi_utils import my_channel
from typing import Union, Callable, List
from logging import Logger
import yonosumi_utils
class voice:
def is_active(self, channel: discord.VoiceChannel, count_bots=True) -> bool:
"""
通話に人がいるかどうかを確認します。
... | 4,550 | 1,718 |
import os
import sys
import bpy #pylint: disable=import-error
sys.path.append(os.path.join(os.path.dirname(__file__), '..', ))
import blender_script_common as common #pylint: disable=import-error,wrong-import-position
def export_egg(_, src, dst):
print('Converting .blend file ({}) to .egg ({})'.format(src, dst)... | 1,608 | 595 |
import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
from modules.mixers.flex_qmix import FlexQMixer, LinearFlexQMixer
import torch as th
from torch.optim import RMSprop
class QLearner:
def __init__(self, mac, scheme, logger,... | 10,993 | 3,645 |
"""`marketprice.messages.shark` namespace."""
| 46 | 15 |
import argparse
import os
import logging.config
import google.cloud.logging
from google.cloud.logging.handlers import CloudLoggingHandler
from .discord_bot_client import DiscordBotClient
from .dictionary_api import OwlBotDictionaryAPI, UnofficialGoogleAPI, MerriamWebsterCollegiateAPI, RapidWordsAPI, MerriamWebsterMedic... | 5,733 | 1,683 |
##
# Copyright (c) 2010-2017 Apple Inc. 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 applicable l... | 4,526 | 1,233 |
# -*- coding: utf-8 eval: (yapf-mode 1) -*-
#
# February 19 2015, Christian Hopps <chopps@gmail.com>
#
# Copyright (c) 2015, Deutsche Telekom AG
#
# 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 a... | 9,467 | 2,775 |
import numpy as np
from deep500.lv0.operators.operator_interface import CustomPythonOp
class ReluOp(CustomPythonOp):
def __init__(self, input_descriptors, output_descriptors):
super(ReluOp, self).__init__(input_descriptors, output_descriptors)
self._input_desc = input_descriptors
self._outp... | 659 | 235 |
# Generated by Django 2.1.2 on 2018-11-20 19:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('incidentes', '0002_auto_20181120_1612'),
]
operations = [
migrations.RemoveField(
model_name='t... | 971 | 325 |
# -*- coding: utf-8 -*-
class TestAw(object):
def __init__(self):
pass
def show(self):
print('show')
| 128 | 49 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
import os
from setuptools import setup, find_packages
version = os.environ['PACKAGE_VERSION']
requirements = ['pyspark',]
setup_requirements = ['pytest-runner', ]
test_requirements = ['pytest', ]
setup(
name='mysparkpackage',
author="L... | 871 | 281 |
import numpy as np
import torch
from .model.encoder import ResNetExtractor
MODEL_URL = "https://github.com/descriptinc/lyrebird-wav2clip/releases/download/v0.1.0-alpha/Wav2CLIP.pt"
def get_model(device="cpu", pretrained=True, frame_length=None, hop_length=None):
if pretrained:
checkpoint = torch.hub.lo... | 1,050 | 346 |
/usr/lib/python2.7/encodings/cp437.py | 37 | 21 |
import unittest
import ganesha
EXAMPLE_EXPORT = """## This export is managed by the CephNFS charm ##
EXPORT {
# Each EXPORT must have a unique Export_Id.
Export_Id = 1000;
# The directory in the exported file system this export
# is rooted on.
Path = '/volumes/_nogroup/test_ganesha_share/e12a49ef... | 2,466 | 1,015 |
from __future__ import absolute_import
import json
from sentry.api.event_search import get_filter
from sentry.models import Environment
from sentry.snuba.discover import resolve_discover_aliases
from sentry.snuba.models import (
QueryAggregations,
QueryDatasets,
QuerySubscription,
query_aggregation_to... | 5,751 | 1,663 |