repo_name stringlengths 7 94 | repo_path stringlengths 4 237 | repo_head_hexsha stringlengths 40 40 | content stringlengths 10 680k | apis stringlengths 2 680k |
|---|---|---|---|---|
ruslan-ok/ruslan | v2_hier/site_stat.py | fc402e53d2683581e13f4d6c69a6f21e5c2ca1f8 | """Collecting statistics of site visits."""
import collections
from datetime import datetime
from functools import reduce
from django.utils.translation import gettext_lazy as _
from hier.models import IPInfo, AccessLog, SiteStat
from v2_hier.utils import APPS
def get_site_stat(user):
"""Processing a new portion of... | [((622, 643), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (641, 643), False, 'import collections\n'), ((668, 688), 'hier.models.IPInfo.objects.all', 'IPInfo.objects.all', ([], {}), '()\n', (686, 688), False, 'from hier.models import IPInfo, AccessLog, SiteStat\n'), ((715, 738), 'hier.models.AccessLo... |
mkosmo/cfncluster | cli/pcluster/utils.py | f1817cc187f2b92127d48f16debb4b7ea4f4a80f | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accom... | [((684, 718), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (716, 718), False, 'from future import standard_library\n'), ((939, 966), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (956, 966), False, 'import logging\n'), ((1256, 1292), 'o... |
ThinkmanWang/thinkutils_plus | thinkutils_plus/eventbus/sample/myeventbus.py | 65d56a1a0cfce22dff08a4f0baea6b4eb08a2e35 | __author__ = 'Xsank'
import time
from thinkutils_plus.eventbus.eventbus import EventBus
from myevent import GreetEvent
from myevent import ByeEvent
from mylistener import MyListener
if __name__=="__main__":
eventbus=EventBus()
eventbus.register(MyListener())
ge=GreetEvent('world')
be=ByeEvent('world'... | [((223, 233), 'thinkutils_plus.eventbus.eventbus.EventBus', 'EventBus', ([], {}), '()\n', (231, 233), False, 'from thinkutils_plus.eventbus.eventbus import EventBus\n'), ((277, 296), 'myevent.GreetEvent', 'GreetEvent', (['"""world"""'], {}), "('world')\n", (287, 296), False, 'from myevent import GreetEvent\n'), ((304, ... |
kjthegod/chromium | tools/telemetry/telemetry/core/platform/android_device_unittest.py | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | # Copyright 2014 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.
import unittest
from telemetry import benchmark
from telemetry.core import browser_options
from telemetry.core.platform import android_device
from telemetry... | [((512, 566), 'telemetry.unittest_util.system_stub.Override', 'system_stub.Override', (['android_device', "['adb_commands']"], {}), "(android_device, ['adb_commands'])\n", (532, 566), False, 'from telemetry.unittest_util import system_stub\n'), ((1033, 1122), 'telemetry.unittest_util.system_stub.Override', 'system_stub... |
bekaaa/xgboost_tuner | logger.py | 2d93f6cc751b3a8778420a88caf73fd1dc8ef2ce | #! /usr/bin/env python
import logging
#---------------------------------------
class logger :
'''
A ready to use logging class.
All you need to do is set an object with the parameters (log_filename, directory to save it)
then whenever you want to add text, type obj.add("some text").
The function obj.close() is no... | [((615, 634), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (632, 634), False, 'import logging\n'), ((728, 757), 'logging.FileHandler', 'logging.FileHandler', (['filename'], {}), '(filename)\n', (747, 757), False, 'import logging\n'), ((810, 883), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': '""... |
lessleslie/slm-code-generation | baselines/prep_baseline.py | 017ac0828faf3467e9f85883e27be09ec3898b14 | import json
import multiprocessing as mp
import re
from argparse import ArgumentParser
from enum import Enum, auto
import javalang
from functools import partial
PRED_TOKEN = 'PRED'
modifiers = ['public', 'private', 'protected', 'static']
class TargetType(Enum):
seq = auto()
tree = auto()
@staticmethod
... | [((487, 778), 're.compile', 're.compile', (['"""\n # Find words in a string. Order matters!\n [A-Z]+(?=[A-Z][a-z]) | # All upper case before a capitalized word\n [A-Z]?[a-z]+ | # Capitalized words / all lower case\n [A-Z]+ | # All upper case\n \\\\d+ | # Numbers\n _ |\n \\\\" |\n .+\n"""', 'r... |
varioustoxins/spack | var/spack/repos/builtin/packages/r-multicool/package.py | cab0e4cb240f34891a6d753f3393e512f9a99e9a | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RMulticool(RPackage):
"""Permutations of multisets in cool-lex order
A set of tools t... | [] |
erincerys/ergo | updatetranslations.py | 0aeedcdcccb5348d8eedb5faa6a0536d93ca3ae3 | #!/usr/bin/env python3
# updatetranslations.py
#
# tl;dr this script updates our translation file with the newest, coolest strings we've added!
# it manually searches the source code, extracts strings and then updates the language files.
# Written in 2018 by Daniel Oaks <daniel@danieloaks.net>
#
# To the extent possib... | [((1137, 1169), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""0.1.0"""'}), "(__doc__, version='0.1.0')\n", (1143, 1169), False, 'from docopt import docopt\n'), ((1287, 1318), 'os.walk', 'os.walk', (["arguments['<irc-dir>']"], {}), "(arguments['<irc-dir>'])\n", (1294, 1318), False, 'import os\n'), ((2697, 272... |
apanda/modeling | processing_tools/number_of_tenants.py | e032abd413bb3325ad6e5995abadeef74314f383 | import sys
from collections import defaultdict
def Process (fnames):
tenant_time = defaultdict(lambda: defaultdict(lambda: 0.0))
tenant_run = defaultdict(lambda: defaultdict(lambda:0))
for fname in fnames:
f = open(fname)
for l in f:
if l.startswith("tenant"):
co... | [] |
borisbolliet/pyfisher | pyfisher/mpi.py | 715e192baa4fadbff754416d2b001c3708c9276c | from __future__ import print_function
import numpy as np
import os,sys,time
"""
Copied from orphics.mpi
"""
try:
disable_mpi_env = os.environ['DISABLE_MPI']
disable_mpi = True if disable_mpi_env.lower().strip() == "true" else False
except:
disable_mpi = False
"""
Use the below cleanup stuff only for inte... | [((1658, 1692), 'numpy.array', 'np.array', (['([min_each] * avail_cores)'], {}), '([min_each] * avail_cores)\n', (1666, 1692), True, 'import numpy as np\n'), ((1917, 1936), 'numpy.cumsum', 'np.cumsum', (['num_each'], {}), '(num_each)\n', (1926, 1936), True, 'import numpy as np\n')] |
SpironoZeppeli/Magic-The-Scannening | ebay.py | 93c595a4c98fb725a79eeddfaba99cb0409d41fb | import requests
import urllib.request
import urllib.parse
import PIL
import re
import configparser
import json
from PIL import Image
from ebaysdk.trading import Connection as Trading
from ebaysdk.exception import ConnectionError
from yaml import load
from PyQt5.QtWidgets import QMessageBox
class EbaySeller:
def ... | [((355, 364), 'ebaysdk.trading.Connection', 'Trading', ([], {}), '()\n', (362, 364), True, 'from ebaysdk.trading import Connection as Trading\n'), ((382, 409), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (407, 409), False, 'import configparser\n'), ((1350, 1372), 'PIL.Image.open', 'Image... |
v1nam/gurkbot | bot/exts/github/github.py | a0f5e05a5f65e6169accc90271fca58f4df211fe | import typing
from bot.constants import BOT_REPO_URL
from discord import Embed
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from . import _issues, _profile, _source
class Github(commands.Cog):
"""
Github Category cog, which contains commands related to github.
... | [((633, 708), 'discord.ext.commands.group', 'commands.group', ([], {'name': '"""github"""', 'aliases': "('gh',)", 'invoke_without_command': '(True)'}), "(name='github', aliases=('gh',), invoke_without_command=True)\n", (647, 708), False, 'from discord.ext import commands\n'), ((898, 939), 'discord.ext.commands.cooldown... |
SmashKs/BarBarian | log/slack_sender.py | b308dcb9e24ec621abbbc121847923e14e5b6a4b | from slackclient import SlackClient
from external import SLACK_API_KEY
class SlackBot:
API_CHAT_MSG = 'chat.postMessage'
BOT_NAME = 'News Bot'
DEFAULT_CHANNEL = 'news_notification'
def __new__(cls, *p, **k):
if '_the_instance' not in cls.__dict__:
cls._the_instance = object.__new... | [((416, 442), 'slackclient.SlackClient', 'SlackClient', (['SLACK_API_KEY'], {}), '(SLACK_API_KEY)\n', (427, 442), False, 'from slackclient import SlackClient\n')] |
miracle2k/pytezos | src/pytezos/block/forge.py | e6b99f00f342d9a05b0c36a9883040961fd6d58e | from typing import Any, Dict, List, Tuple
from pytezos.michelson.forge import forge_array, forge_base58, optimize_timestamp
def bump_fitness(fitness: Tuple[str, str]) -> Tuple[str, str]:
if len(fitness) == 0:
major = 0
minor = 1
else:
major = int.from_bytes(bytes.fromhex(fitness[0]), ... | [((1052, 1081), 'pytezos.michelson.forge.forge_base58', 'forge_base58', (["content['hash']"], {}), "(content['hash'])\n", (1064, 1081), False, 'from pytezos.michelson.forge import forge_array, forge_base58, optimize_timestamp\n'), ((1970, 2011), 'pytezos.michelson.forge.forge_base58', 'forge_base58', (["shell_header['p... |
jichangjichang/Paddle | python/paddle/fluid/tests/unittests/test_roi_pool_op.py | 4fa3cee5499c6df0ad6043b0cfa220d09f2034e8 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | [((5305, 5320), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5318, 5320), False, 'import unittest\n'), ((1679, 1758), 'numpy.zeros', 'np.zeros', (['(self.rois_num, self.channels, self.pooled_height, self.pooled_width)'], {}), '((self.rois_num, self.channels, self.pooled_height, self.pooled_width))\n', (1687, 17... |
movermeyer/django-firestone | testproject/testapp/tests/__init__.py | e045089f6ff4a6686633f9c5909c314a010bd4a0 | from test_proxy import *
from test_serializers import *
from test_deserializers import *
from test_exceptions import *
from test_authentication import *
from test_whole_flow import *
from test_handlers_metaclass_magic import *
from test_handlers_serialize_to_python import *
from test_handlers_is_method_allowed im... | [] |
SheepiCagio/Advent-of-Code-2021 | Day20.py | 52f0035da2cb258810d8947cbf56b51b65a9fe8b | import numpy as np
raw = open("inputs/20.txt","r").readlines()
input_array= [(i.replace('\n', '').replace('.','0').replace('#', '1')) for i in raw]
test_raw = open("inputs/20_test.txt","r").readlines()
test_array= [(i.replace('\n', '').replace('.','0').replace('#', '1')) for i in test_raw]
def addLayerZero(grid):
#if... | [] |
sesu089/stackoverflow | questions/53349623/main.py | 6fae69be6fa74fba9d554e6b5f387e5d3c1aad73 | import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Demo(QtWidgets.QWidget):
def __init__(self):
super(Demo, self).__init__()
self.button = QtWidgets.QPushButton()
self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
self.combo = QtWidgets.QComboBox(self)
... | [((866, 886), 'PyQt5.QtCore.pyqtSlot', 'QtCore.pyqtSlot', (['int'], {}), '(int)\n', (881, 886), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((1582, 1614), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (1604, 1614), False, 'from PyQt5 import QtCore, QtGui, QtWi... |
iterait/apistrap | tests/test_error_descriptions_from_raises.py | e83460fa97f13a95a928971b0d2defe0ac611911 | import pytest
from apistrap.flask import FlaskApistrap
from apistrap.schemas import ErrorResponse
@pytest.fixture()
def app_with_raises(app):
oapi = FlaskApistrap()
@app.route("/", methods=["GET"])
def view():
"""
Something something.
:raises KeyError: KeyError description
... | [((102, 118), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (116, 118), False, 'import pytest\n'), ((354, 370), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (368, 370), False, 'import pytest\n'), ((156, 171), 'apistrap.flask.FlaskApistrap', 'FlaskApistrap', ([], {}), '()\n', (169, 171), False, 'from ap... |
chamathshashika/projects-python-wrappers | projects/api/UsersApi.py | 33e9f6bccba16a581b115c582033a93d43bb159c | #$Id$
from projects.util.ZohoHttpClient import ZohoHttpClient
from projects.api.Api import Api
from projects.parser.UsersParser import UsersParser
base_url = Api().base_url
zoho_http_client = ZohoHttpClient()
parser = UsersParser()
class UsersApi:
"""Users Api class is used to
1.Get all the users in th... | [((194, 210), 'projects.util.ZohoHttpClient.ZohoHttpClient', 'ZohoHttpClient', ([], {}), '()\n', (208, 210), False, 'from projects.util.ZohoHttpClient import ZohoHttpClient\n'), ((220, 233), 'projects.parser.UsersParser.UsersParser', 'UsersParser', ([], {}), '()\n', (231, 233), False, 'from projects.parser.UsersParser ... |
leader1313/Baxter_teleoperation_system | useless/tuck_arms.py | 856d999acd73e6c1dc15a342cb6c4fcd1a482863 | #!/usr/bin/env python
# Copyright (c) 2013-2015, Rethink Robotics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... | [((10616, 10641), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10639, 10641), False, 'import argparse\n'), ((11028, 11066), 'rospy.loginfo', 'rospy.loginfo', (['"""Initializing node... """'], {}), "('Initializing node... ')\n", (11041, 11066), False, 'import rospy\n'), ((11071, 11104), 'rosp... |
Deepak-Kharah/ioe-project | django-system/src/tsm_api/serializers.py | 6f83ddcfced25130e0f05c3380dde97429d1f224 | from rest_framework import serializers
from .models import Measurement
class MeasurementSerializer(serializers.ModelSerializer):
class Meta:
model = Measurement
fields = '__all__'
| [] |
pabferde/galaxy_dynamics_from_Vc | src/GalaxyDynamicsFromVc/units.py | 7232f7bfd6d2338bcec3bbf87478f7a482c749ef |
_Msun_kpc3_to_GeV_cm3_factor = 0.3/8.0e6
def Msun_kpc3_to_GeV_cm3(value):
return value*_Msun_kpc3_to_GeV_cm3_factor
| [] |
tedye/leetcode | Python/leetcode.031.next-permutation.py | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums: return
n = len(nums)-1
while n > 0 and nums[n-1] >= nums[n]:
n -= 1
t = n... | [] |
mirokrastev/poll-website | poll/models/telemetry_models.py | 4f26cce3f838ab05de91f0e1dba34d9bc59927b4 | from django.db import models
from django.contrib.auth import get_user_model
from poll.models.poll_models import Poll
class BasePollTelemetry(models.Model):
"""
This Base class gives a hint that in the future
more Telemetry classes could be implemented.
"""
poll = models.ForeignKey(db_index=True, ... | [((287, 354), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'db_index': '(True)', 'to': 'Poll', 'on_delete': 'models.CASCADE'}), '(db_index=True, to=Poll, on_delete=models.CASCADE)\n', (304, 354), False, 'from django.db import models\n'), ((692, 743), 'django.db.models.GenericIPAddressField', 'models.Generi... |
HenryLittle/OpenPCDet-HL | pcdet/models/backbones_2d/__init__.py | 7dba01750e10d170849314723ec0665782236a70 | from .base_bev_backbone import BaseBEVBackbone
from .decouple_bev_backbone import DecoupledBEVBackbone
__all__ = {
'BaseBEVBackbone': BaseBEVBackbone,
'DecoupledBEVBackbone': DecoupledBEVBackbone,
}
| [] |
beatrizserrano/galaxy | test/unit/app/tools/test_select_parameters.py | e149d9d32e1bca6c07c38b1a9cdabfee60323610 | from unittest.mock import Mock
import pytest
from galaxy import model
from galaxy.tools.parameters import basic
from .util import BaseParameterTestCase
class SelectToolParameterTestCase(BaseParameterTestCase):
def test_validated_values(self):
self.options_xml = """<options><filter type="data_meta" ref="... | [((3287, 3302), 'galaxy.model.History', 'model.History', ([], {}), '()\n', (3300, 3302), False, 'from galaxy import model\n'), ((371, 396), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (384, 396), False, 'import pytest\n'), ((799, 824), 'pytest.raises', 'pytest.raises', (['ValueError'], {})... |
Toasterstein/recumpiler | recumpiler/__init__.py | 390957cfaa8f60ffeb24adb43b91981dd445c6b9 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0)
| [] |
codenote/chromium-test | net/net.gyp | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | # Copyright 2013 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.
{
'variables': {
'chromium_code': 1,
'linux_link_kerberos%': 0,
'conditions': [
['chromeos==1 or OS=="android" or OS=="ios"', {
... | [] |
mdemoret-nv/clx | python/clx/analytics/detector.py | 3737706187d8f5720561e10b85cbd638c77b9267 | import logging
import torch
import torch.nn as nn
from abc import ABC, abstractmethod
log = logging.getLogger(__name__)
class Detector(ABC):
def __init__(self, lr=0.001):
self.lr = lr
self.__model = None
self.__optimizer = None
self.__criterion = nn.CrossEntropyLoss()
@proper... | [((93, 120), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (110, 120), False, 'import logging\n'), ((286, 307), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (305, 307), True, 'import torch.nn as nn\n'), ((1022, 1043), 'torch.load', 'torch.load', (['file_path'], {... |
openplans/streetscore | street_score/project/models.py | ea27f70399b070d3199f236d99575c5962943d67 | import math
import random
from django.db import models
class TimeStampedModel (models.Model):
"""
Base model class for when you want to keep track of created and updated
times for model instances.
"""
created_datetime = models.DateTimeField(auto_now_add=True)
updated_datetime = models.DateTim... | [((243, 282), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (263, 282), False, 'from django.db import models\n'), ((306, 341), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (326, 341), F... |
vitlabuda/selfdroid-web-app | src/selfdroid/appstorage/crud/AppAdder.py | 9eac9ee2c34038de13e179b6afb3d530a086e7b2 | # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2021 Vít Labuda. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice... | [((3860, 3884), 'selfdroid.db.session.add', 'db.session.add', (['db_model'], {}), '(db_model)\n', (3874, 3884), False, 'from selfdroid import db\n'), ((3893, 3912), 'selfdroid.db.session.commit', 'db.session.commit', ([], {}), '()\n', (3910, 3912), False, 'from selfdroid import db\n'), ((3982, 4017), 'selfdroid.appstor... |
bkmeneguello/ansible-role-libvirt | library/libvirt_filter.py | e7f82077b1fd4c2ec5afa463973ecde599209549 | # TODO: https://libvirt.org/formatnwfilter.html | [] |
Solunest/pyestafeta | estafeta/core/__init__.py | cd24cea4973f5184f4cc7e72a653de8b22e32f69 |
from estafeta.core.client import EstafetaClient
user = None
password = None
id = None
account_number = None
production = None
from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField
__url_label__ = [
'https://labelqa.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS?wsdl',
'https://label.e... | [] |
tb365/mcclient_python | yunionclient/api/flavors.py | 06647e7496b9e2c3aeb5ade1276c81871063159b | from yunionclient.common import base
class FlavorManager(base.StandaloneManager):
keyword = 'flavor'
keyword_plural = 'flavors'
_columns = ['ID', 'Name', 'VCPU_count', 'VMEM_size', 'Disk_size',
'Disk_backend', 'Ext_Bandwidth', 'Int_Bandwidth', 'is_public',
'Description', 'A... | [] |
rakib313/Bangla-End2End-Speech-Recognition | char_map.py | 67e776841bf2bb3f108e94d0567dc707497605ff | """
Defines two dictionaries for converting
between text and integer sequences.
"""
char_map_str = """
' 0
<SPACE> 1
ব 2
া 3
ং 4
ল 5
দ 6
ে 7
শ 8
য 9
় 10
ি 11
ত 12
্ 13
ন 14
এ 15
ধ 16
র 17
ণ 18
ক 19
ড 20
হ 21
উ 22
প 23
জ 24
অ 25
থ 26
স 27
ষ 28
ই 29
আ 30
ছ 31
গ 32
ু 33
ো 34
ও 35
ভ 36
ী 37
ট 38
ূ 39
ম 40
ৈ 41
ৃ 42
ঙ 4... | [] |
MaggieChege/New_App | app.py | 75a2be55d50cf21305036c875af2120607ac33c0 | from flask import Blueprint
from flask_restful import Api
# from restful import Api
from resources.Hello import CategoryResource
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
# Route
api.add_resource(CategoryResource, '/Hello') | [((140, 166), 'flask.Blueprint', 'Blueprint', (['"""api"""', '__name__'], {}), "('api', __name__)\n", (149, 166), False, 'from flask import Blueprint\n'), ((173, 184), 'flask_restful.Api', 'Api', (['api_bp'], {}), '(api_bp)\n', (176, 184), False, 'from flask_restful import Api\n')] |
ejojmjn/indiana-phone | websockets.py | 5d666ac651d3e02291806f24c265564002912e00 | #from gevent import monkey
#monkey.patch_all()
from flask import Flask, render_template, json
from flask_socketio import SocketIO, emit
from pydbus import SystemBus
from gi.repository import GLib
import threading
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_m... | [((235, 250), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (240, 250), False, 'from flask import Flask, render_template, json\n'), ((299, 336), 'flask_socketio.SocketIO', 'SocketIO', (['app'], {'async_mode': '"""threading"""'}), "(app, async_mode='threading')\n", (307, 336), False, 'from flask_socketio i... |
wayn111/RediSearch | tests/pytests/test_tags.py | 897b2de35988b84851dd8380c614a21ad8da7c0f | # -*- coding: utf-8 -*-
from includes import *
from common import *
def search(env, r, *args):
return r.execute_command('ft.search', *args)
def testTagIndex(env):
r = env
env.expect('ft.create', 'idx', 'ON', 'HASH','schema', 'title', 'text', 'tags', 'tag').ok()
N = 10
for n in range(N):
... | [] |
Lexa307/PhotonDefender | sc2/bot_ai.py | a08dc652e5c64e3ccb33b7cfa206846dca0575bd | import itertools
import logging
import math
import random
from collections import Counter
from typing import Any, Dict, List, Optional, Set, Tuple, Union # mypy type checking
from .cache import property_cache_forever, property_cache_once_per_frame
from .data import ActionResult, Alert, Race, Result, Target, race_gas,... | [((864, 891), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (881, 891), False, 'import logging\n'), ((25574, 25583), 'collections.Counter', 'Counter', ([], {}), '()\n', (25581, 25583), False, 'from collections import Counter\n'), ((26487, 26496), 'collections.Counter', 'Counter', ([], {}... |
xyzst/pants | src/python/pants/jvm/resolve/lockfile_metadata.py | d6a357fe67ee7e8e1aefeae625e107f5609f1717 | # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Any, Iterable, cast
from pants.core.util_rules.lockfile_metadata import (
... | [((580, 626), 'pants.core.util_rules.lockfile_metadata.lockfile_metadata_registrar', 'lockfile_metadata_registrar', (['LockfileScope.JVM'], {}), '(LockfileScope.JVM)\n', (607, 626), False, 'from pants.core.util_rules.lockfile_metadata import LockfileMetadata, LockfileMetadataValidation, LockfileScope, _get_metadata, lo... |
GregorKikelj/opendbc | generator/generator.py | a20ed24ea2593e5d019adf538dc0cecfc7ef8709 | #!/usr/bin/env python3
import os
import re
cur_path = os.path.dirname(os.path.realpath(__file__))
opendbc_root = os.path.join(cur_path, '../')
include_pattern = re.compile(r'CM_ "IMPORT (.*?)";')
def read_dbc(src_dir, filename):
with open(os.path.join(src_dir, filename)) as file_in:
return file_in.read()
def... | [((114, 143), 'os.path.join', 'os.path.join', (['cur_path', '"""../"""'], {}), "(cur_path, '../')\n", (126, 143), False, 'import os\n'), ((162, 195), 're.compile', 're.compile', (['"""CM_ "IMPORT (.*?)";"""'], {}), '(\'CM_ "IMPORT (.*?)";\')\n', (172, 195), False, 'import re\n'), ((71, 97), 'os.path.realpath', 'os.path... |
matheusdemicheli/dogtel | customer/admin.py | 4eed44c8214fe814c26a6df0125af9b065c81c1c | from django.contrib import admin
from django.utils.safestring import mark_safe
from customer.models import Owner, Dog, Breed, SubBreed
class OwnerAdmin(admin.ModelAdmin):
"""
Owner ModelAdmin.
"""
search_fields = ['name']
class BreedAdmin(admin.ModelAdmin):
"""
Breed ModelAdmin.
"""
s... | [((948, 982), 'django.contrib.admin.site.register', 'admin.site.register', (['Dog', 'DogAdmin'], {}), '(Dog, DogAdmin)\n', (967, 982), False, 'from django.contrib import admin\n'), ((983, 1021), 'django.contrib.admin.site.register', 'admin.site.register', (['Owner', 'OwnerAdmin'], {}), '(Owner, OwnerAdmin)\n', (1002, 1... |
APSL/kaneda | kaneda/tasks/rq.py | 739db48588d2237dd7710b16f23921d489182868 | from __future__ import absolute_import
from redis import Redis
from rq.decorators import job
from kaneda.utils import get_backend
backend = get_backend()
@job(queue='kaneda', connection=Redis())
def report(name, metric, value, tags, id_):
"""
RQ job to report metrics to the configured backend in kanedasett... | [((143, 156), 'kaneda.utils.get_backend', 'get_backend', ([], {}), '()\n', (154, 156), False, 'from kaneda.utils import get_backend\n'), ((191, 198), 'redis.Redis', 'Redis', ([], {}), '()\n', (196, 198), False, 'from redis import Redis\n')] |
jg-rivera/cert-ripper | src/ripper.py | 2bab5e02cd2da8e92a1c308640917b6f5ee729cb | from dotenv import load_dotenv
from PyPDF2 import PdfFileReader, PdfFileWriter
import os
import json
class CertRipper:
def __init__(
self,
start_page_index=0,
master_pdf_path=None,
json_points_path=None,
ripped_certs_path=None,
ripped_cert_file_name=None,
):
... | [((3709, 3722), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (3720, 3722), False, 'from dotenv import load_dotenv\n'), ((432, 462), 'PyPDF2.PdfFileReader', 'PdfFileReader', (['master_pdf_path'], {}), '(master_pdf_path)\n', (445, 462), False, 'from PyPDF2 import PdfFileReader, PdfFileWriter\n'), ((2328, 2348),... |
shehzadulislam/Assignment4 | venv/Lib/site-packages/tests/test_111_FieldNumAddCol.py | a9cced70be6ae5d2685027d68032d5849f638301 | #
# Licensed Materials - Property of IBM
#
# (c) Copyright IBM Corp. 2007-2008
#
import unittest, sys
import ibm_db
import config
from testfunctions import IbmDbTestFunctions
class IbmDbTestCase(unittest.TestCase):
def test_111_FieldNumAddCol(self):
obj = IbmDbTestFunctions()
obj.assert_expect(self.run_... | [((268, 288), 'testfunctions.IbmDbTestFunctions', 'IbmDbTestFunctions', ([], {}), '()\n', (286, 288), False, 'from testfunctions import IbmDbTestFunctions\n'), ((368, 429), 'ibm_db.connect', 'ibm_db.connect', (['config.database', 'config.user', 'config.password'], {}), '(config.database, config.user, config.password)\n... |
Mindelirium/foundation | foundation/djangocms_pagebanner/cms_toolbar.py | 2d07e430915d696ca7376afea633692119c4d30e | from cms.api import get_page_draft
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from cms.utils import get_cms_setting
from cms.utils.permissions import has_page_change_permission
from django.core.urlresolvers import reverse, NoReverseMatch
from django.utils.translation import ugette... | [((682, 723), 'cms.api.get_page_draft', 'get_page_draft', (['self.request.current_page'], {}), '(self.request.current_page)\n', (696, 723), False, 'from cms.api import get_page_draft\n'), ((874, 903), 'cms.utils.get_cms_setting', 'get_cms_setting', (['"""PERMISSION"""'], {}), "('PERMISSION')\n", (889, 903), False, 'fro... |
etri-edgeai/nn-comp-discblock | tasks/lm/models/lm.py | 6e00a019c223508797ca91a7d5ffec7917b12c6d | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, encoder=None, decoder=None):
su... | [((400, 419), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (410, 419), True, 'import torch.nn as nn\n'), ((4154, 4175), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (4164, 4175), True, 'import torch.nn as nn\n'), ((4190, 4219), 'torch.zeros', 'torch.zeros', (['max_le... |
Baibhabswain/pythonPrograms | fibo.py | 38380174f22e73b766b98754b00cd78a56b4bf59 | def main():
a=input("The enter the first number :")
b=input("The enter the second number :")
range=input("Please enter the range")
i=0;count=0;
print a
print b
while count!=range:
c=a+b
count +=1
print c
a=b
b=c
main() | [] |
gghf-service/gghf-api | scrapper/playstation/__init__.py | 9740700d1dd160e90fc949f9c3e652c3483a49aa | from scrapper.playstation.spider import main | [] |
motakine/ILAS_slackbot | plugins/number.py | ddfb34db1cddcb459fef34cfc04c498d6f85d135 | import slackbot.bot
import random
answer = random.randint(1, 50)
max = 50
def number(num):
'''number 判定
Args:
num (int): 判定する数字
Returns:
str: num が answer より大きい: 'Too large'
num が answer より小さい: 'Too small'
num が answer と一致: 'Correct!'、新しくゲームを始める
その他: 'C... | [] |
hatal175/pytype | pytype/analyze.py | 22150dd56c2a11f3d385a1cbb28eed985df31d72 | """Code for checking and inferring types."""
import collections
import logging
import re
import subprocess
from typing import Any, Dict, Union
from pytype import abstract
from pytype import abstract_utils
from pytype import convert_structural
from pytype import debug
from pytype import function
from pytype import met... | [((726, 753), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (743, 753), False, 'import logging\n'), ((976, 1005), 're.compile', 're.compile', (['"""<(?!lambda).+>$"""'], {}), "('<(?!lambda).+>$')\n", (986, 1005), False, 'import re\n'), ((1021, 1158), 'collections.namedtuple', 'collection... |
milescsmith/cDNA_Cupcake | src/cupcake/post_isoseq_cluster/demux_by_barcode_groups.py | 776d841c69fc6d8b3dce95bb9f076546bc0429c0 | #!/usr/bin/env python
__author__ = "etseng@pacb.com"
"""
Given a pooled input GFF + demux CSV file, write out per-{barcode group} GFFs
If input fasta/fastq is given, optionally also output per-{barcode group} FASTA/FASTQ
"""
import re
from collections import defaultdict
from csv import DictReader
from typing import Op... | [((493, 528), 're.compile', 're.compile', (['"""(PB.\\\\d+.\\\\d+)(|\\\\S+)"""'], {}), "('(PB.\\\\d+.\\\\d+)(|\\\\S+)')\n", (503, 528), False, 'import re\n'), ((535, 606), 'typer.Typer', 'typer.Typer', ([], {'name': '"""cupcake.post_isoseq_cluster.demux_by_barcode_groups"""'}), "(name='cupcake.post_isoseq_cluster.demux... |
paulhfu/3dcv-students | vll/data/circle_dataset.py | f8d42c985cf33903170733b0c8f6a2199099553c | import random
import numpy as np
import math
from skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa
from skimage.io import imsave
from skimage.util import random_noise
maxSlope = 10 # restrict the maximum slope of generated lines for stability
minLength = 20 # restrict the minimum length of li... | [((1439, 1469), 'skimage.draw.circle_perimeter_aa', 'circle_perimeter_aa', (['cY', 'cX', 'r'], {}), '(cY, cX, r)\n', (1458, 1469), False, 'from skimage.draw import line, line_aa, circle, set_color, circle_perimeter_aa\n'), ((1472, 1507), 'skimage.draw.set_color', 'set_color', (['data', '(rr, cc)', 'clr', 'val'], {}), '... |
youngmg1995/NES-Music-Maker | VAE/reduced_model/nesm_generator.py | aeda10a541cfd439cfa46c45e63411e0d98e41c1 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 17:14:19 2020
@author: Mitchell
nesm_generator.py
~~~~~~~~~~~~~~~~~
This file serves as a script for using our pre-trained VAE model to generate
brand new NES music soundtracks. NOTE - using the reduced model we only
generate the first melodic voice for each track rat... | [((1458, 1561), 'dataset_utils.load_training', 'load_training', (['training_foldername', 'train_save_filename'], {'measures': 'measures', 'measure_len': 'measure_len'}), '(training_foldername, train_save_filename, measures=measures,\n measure_len=measure_len)\n', (1471, 1561), False, 'from dataset_utils import load_... |
anttin/anlogger | anlogger/logger.py | dfa7be7ba2f4651507b188f986c10bab9bd7460e | import logging
import logging.handlers
import os
class Logger(object):
def __init__(self, name, default_loglevel='INFO', fmt=None, syslog=None):
self.name = name
self.syslog = syslog
self.fmt = fmt if fmt is not None else "%(asctime)-15s %(name)s %(levelname)s %(message)s"
if 'LOGLEVEL' in os.env... | [((435, 471), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'self.fmt'}), '(format=self.fmt)\n', (454, 471), False, 'import logging\n'), ((490, 518), 'logging.getLogger', 'logging.getLogger', (['self.name'], {}), '(self.name)\n', (507, 518), False, 'import logging\n'), ((902, 947), 'logging.handlers.Sys... |
saurabhcommand/Hello-world | Python/hello_world-theopaid.py | 647bad9da901a52d455f05ecc37c6823c22dc77e | #Author Theodosis Paidakis
print("Hello World")
hello_list = ["Hello World"]
print(hello_list[0])
for i in hello_list:
print(i) | [] |
uliang/NaturalLanguageQueryingSystem | question_answering/stubs.py | d18b4ae429362ba311d6f26debbcfe391b810458 | from collections import namedtuple
from unittest.mock import MagicMock
_fake_ext = namedtuple('_', ['qtype', 'kb_ident'])
class FakeDoc:
def __init__(self, text, qtype, kb_ident):
self._ = _fake_ext(qtype, kb_ident)
self.text = text
def __str__(self):
return f"<[MOCKED NLP]{sel... | [((86, 124), 'collections.namedtuple', 'namedtuple', (['"""_"""', "['qtype', 'kb_ident']"], {}), "('_', ['qtype', 'kb_ident'])\n", (96, 124), False, 'from collections import namedtuple\n')] |
devas123/Bitcoin-Trader-RL | lib/env/trade/BaseTradeStrategy.py | 097cb0ba7428b2c4f997bdb0425a6153c23f9c83 | from abc import ABCMeta, abstractmethod
from typing import Tuple, Callable
class BaseTradeStrategy(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self,
commissionPercent: float,
maxSlippagePercent: float,
base_precision: int,
asset_... | [] |
jsjang93/joony | 4day/Book04_1.py | 62f7a325094c887212b894932263bf84500e0f03 | # Book04_1.py
class Book:
category = '소설' # Class 멤버
b1 = Book(); print(b1.category)
b2 = b1; print(b2.category)
print(Book.category)
Book.category = '수필'
print(b2.category); print(b1.category) ; print(Book.category)
b2.category = 'IT'
print(b2.category); print(b1.category) ; print(Book.category) | [] |
odidev/virgil-crypto-c | wrappers/python/virgil_crypto_lib/foundation/kdf1.py | 3d5d5cb19fdcf81eab08cdc63647f040117ecbd8 | # Copyright (C) 2015-2021 Virgil Security, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of source code must retain the above copyright
# notice, this li... | [((3299, 3309), 'virgil_crypto_lib.common._c_bridge.Data', 'Data', (['data'], {}), '(data)\n', (3303, 3309), False, 'from virgil_crypto_lib.common._c_bridge import Data\n'), ((3324, 3339), 'virgil_crypto_lib.common._c_bridge.Buffer', 'Buffer', (['key_len'], {}), '(key_len)\n', (3330, 3339), False, 'from virgil_crypto_l... |
leixiayang/django-python | mysite/zoo/tests.py | 8faa84867af5645d3d3d8e67fe8020be4dc68551 | #!/usr/bin/env python
# encoding: utf-8
from django.test import TestCase
from zoo import models
class AnimalTestCase(TestCase):
"""Test animals' sound """
def test_dog_says(self):
"""test dog says woof or not
"""
dog = models.Dog(name='Snoopy')
self.assertEqual(dog.says()... | [((259, 284), 'zoo.models.Dog', 'models.Dog', ([], {'name': '"""Snoopy"""'}), "(name='Snoopy')\n", (269, 284), False, 'from zoo import models\n'), ((424, 451), 'zoo.models.Cat', 'models.Cat', ([], {'name': '"""Garfield"""'}), "(name='Garfield')\n", (434, 451), False, 'from zoo import models\n')] |
gjaosdij/PythonProject | EX025.py | ae27990efa93462b632f165d13c08c7fd93beb38 | print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome)
| [] |
linxi1158/iMIX | configs/_base_/datasets/stvqa_dataset.py | af87a17275f02c94932bb2e29f132a84db812002 | dataset_type = 'STVQADATASET'
data_root = '/home/datasets/mix_data/iMIX/'
feature_path = 'data/datasets/stvqa/defaults/features/'
ocr_feature_path = 'data/datasets/stvqa/defaults/ocr_features/'
annotation_path = 'data/datasets/stvqa/defaults/annotations/'
vocab_path = 'data/datasets/stvqa/defaults/extras/vocabs/'
trai... | [] |
2martens/rpo-website | src/rpocore/migrations/0007_auto_20160927_1517.py | 14990920722c537810aecd2b97f5af6bbdd1b5ec | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-27 13:17
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mezzanine.core.fields
class Migration(migrations.Migration):
dependencies = [
('rpocore', '0006_auto_20160921_19... | [((1261, 1411), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""carousel_items"""', 'to': '"""rpocore.HomepagePage"""', 'verbose_name': '"""Homepage"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='carousel_items', ... |
manno-xx/FutureLearnRobotBuggy | code/Line.py | d5f0172597ad88d6a8b883b0b16d425a76edfb0b | #LineSensor test
from gpiozero import LineSensor
from time import sleep
from signal import pause
def lineDetected():
print('line detected')
def noLineDetected():
print('no line detected')
sensor = LineSensor(14)
sensor.when_line = lineDetected
sensor.when_no_line = noLineDetected
pause()
sensor.close()
| [((210, 224), 'gpiozero.LineSensor', 'LineSensor', (['(14)'], {}), '(14)\n', (220, 224), False, 'from gpiozero import LineSensor\n'), ((296, 303), 'signal.pause', 'pause', ([], {}), '()\n', (301, 303), False, 'from signal import pause\n')] |
chmousset/litex-boards | litex_boards/platforms/myminieye_runber.py | c081177d77f37a4ea6cff150d42a69bd6f0abbc2 | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Gwenhael Goavec-Merou <gwenhael.goavec-merou@trabucayre.com>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from litex.build.generic_platform import *
from litex.build.gowin.platform import GowinPlatform
from litex.build.openfpgaloader import ... | [((3824, 3938), 'litex.build.gowin.platform.GowinPlatform.__init__', 'GowinPlatform.__init__', (['self', '"""GW1N-UV4LQ144C6/I5"""', '_io', '_connectors'], {'toolchain': 'toolchain', 'devicename': '"""GW1N-4"""'}), "(self, 'GW1N-UV4LQ144C6/I5', _io, _connectors,\n toolchain=toolchain, devicename='GW1N-4')\n", (3846,... |
zhangkunliang/BayesOptimization | combo/search/discrete/policy.py | 6d78c9e9f96239b0dbb85650a0d878e9410158ec | import numpy as np
import copy
import combo.misc
import cPickle as pickle
from results import history
from .. import utility
from ...variable import variable
from ..call_simulator import call_simulator
from ... import predictor
from ...gp import predictor as gp_predictor
from ...blm import predictor as blm_predictor
im... | [((559, 593), 'numpy.arange', 'np.arange', (['(0)', 'self.test.X.shape[0]'], {}), '(0, self.test.X.shape[0])\n', (568, 593), True, 'import numpy as np\n'), ((617, 626), 'results.history', 'history', ([], {}), '()\n', (624, 626), False, 'from results import history\n'), ((738, 763), 'numpy.random.seed', 'np.random.seed'... |
dequeb/asmbattle | venv/lib/python3.9/site-packages/py2app/bootstrap/disable_linecache.py | 27e8b209de5787836e288a2f2f9b7644ce07563e | def _disable_linecache():
import linecache
def fake_getline(*args, **kwargs):
return ""
linecache.orig_getline = linecache.getline
linecache.getline = fake_getline
_disable_linecache()
| [] |
s403o/tw_bot | source.py | fd26ebc86d4c7d1be1ae654f26f5ca74c2566a03 | import requests
from bs4 import BeautifulSoup as bs
import os
#source
url = '' # the source you want the bot take images from
#down page
page = requests.get(url)
html = bs(page.text, 'html.parser')
#locate
image_loc = html.findAll('img')
#create folder for located imgs
if not os.path.exists('imgs'):
os.makedirs(... | [((147, 164), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (159, 164), False, 'import requests\n'), ((172, 200), 'bs4.BeautifulSoup', 'bs', (['page.text', '"""html.parser"""'], {}), "(page.text, 'html.parser')\n", (174, 200), True, 'from bs4 import BeautifulSoup as bs\n'), ((350, 366), 'os.chdir', 'os.chdi... |
QIAOANGeo/BZB_ydzw | lib/appController.py | 8c11e9797cca31d1fab26be7eb0a71666cfac15f | '''
1、启动appium服务
subproccess
配置文件
1.1、校验服务是否启动
1.2、杀掉上一次的服务
2、启动driver
'''
from lib.tools import Tool
import subprocess
from lib.path import SYSTEMPATH, ERRORPATH
import time
from appium import webdriver
import queue
# 声明一个python队列
driver_queue = queue.Queue()
class Controller(object):
def __init__(se... | [((257, 270), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (268, 270), False, 'import queue\n'), ((917, 942), 'subprocess.getoutput', 'subprocess.getoutput', (['win'], {}), '(win)\n', (937, 942), False, 'import subprocess\n'), ((1608, 1621), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1618, 1621), False, 'i... |
passionzhan/LeetCode | pondSizes.py | c4d33b64b9da15ca7a9b0d41e645d86a697694fe | # -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : pondSizes.py
@Contact : 9824373@qq.com
@Desc :
你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
... | [((1662, 1669), 'collections.deque', 'deque', ([], {}), '()\n', (1667, 1669), False, 'from collections import deque\n')] |
kurtraschke/geolucidate | geolucidate/functions.py | 827195a90d972fa5efce5a03bdbe53d8395d94ba | # -*- coding: utf-8 -*-
from decimal import Decimal, setcontext, ExtendedContext
from geolucidate.links.google import google_maps_link
from geolucidate.links.tools import MapLink
from geolucidate.parser import parser_re
setcontext(ExtendedContext)
def _cleanup(parts):
"""
Normalize up the parts matched by :... | [((222, 249), 'decimal.setcontext', 'setcontext', (['ExtendedContext'], {}), '(ExtendedContext)\n', (232, 249), False, 'from decimal import Decimal, setcontext, ExtendedContext\n'), ((2246, 2261), 'decimal.Decimal', 'Decimal', (['latdeg'], {}), '(latdeg)\n', (2253, 2261), False, 'from decimal import Decimal, setcontext... |
rluzuriaga/pokedex | setup.py | e5c18c410994d5fb589bc3dceaba71f85268edfb | from setuptools import setup, find_packages
setup(
name='Pokedex',
version='0.1',
zip_safe=False,
packages=find_packages(),
package_data={
'pokedex': ['data/csv/*.csv']
},
install_requires=[
'SQLAlchemy>=1.0,<2.0',
'whoosh>=2.5,<2.7',
'markdown==2.4.1',
... | [((124, 139), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (137, 139), False, 'from setuptools import setup, find_packages\n')] |
j-luo93/lingvo | lingvo/tasks/asr/encoder.py | 7398974078391362f0c1b027164a8f33f88cf86b | # Copyright 2018 The TensorFlow 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 applica... | [((1225, 1280), 'collections.namedtuple', 'collections.namedtuple', (['"""ConvLSTMBlock"""', "('rnn', 'cnn')"], {}), "('ConvLSTMBlock', ('rnn', 'cnn'))\n", (1247, 1280), False, 'import collections\n'), ((4201, 4233), 'lingvo.core.py_utils.WeightInit.Uniform', 'py_utils.WeightInit.Uniform', (['(0.1)'], {}), '(0.1)\n', (... |
Yudabin/Review_Project | pos_neg_graph/graph_ratio.py | b924199d6845defeb4cd243a99426070c014d8d8 | import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
font_location = './wordcloud_file/malgun.ttf' # For Windows
font_name = fm.FontProperties(fname=font_location).get_name()
plt.rc('font', family=font_name)
def percent_graph2(movie_review) :
b = movie_review
labelss = sorte... | [((211, 243), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'family': 'font_name'}), "('font', family=font_name)\n", (217, 243), True, 'import matplotlib.pyplot as plt\n'), ((461, 487), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (471, 487), True, 'import matplotli... |
kbilak/City-portal | blog/views.py | f567764f3c4ae0287a178acf77f060dde0424f26 | from django.shortcuts import render
from django.views.generic import TemplateView
def index(request):
return render(request, 'index.html') | [((114, 143), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (120, 143), False, 'from django.shortcuts import render\n')] |
Vincent-Juma/area_master | my_area/views.py | 3ea1dd1039053fb4de6326deb967383d09d7145b | from django.shortcuts import render
from .forms import *
from django.shortcuts import redirect,get_object_or_404
from django.contrib.auth.decorators import login_required
from . models import *
from django.views import generic
@login_required(login_url='/accounts/login/')
def home(request):
mylocs = Myloc.objects.... | [((229, 273), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""/accounts/login/"""'}), "(login_url='/accounts/login/')\n", (243, 273), False, 'from django.contrib.auth.decorators import login_required\n'), ((387, 430), 'django.contrib.auth.decorators.login_required', 'login_requ... |
d02d33pak/Advent-Of-Code | 2020/day_01/__main__.py | 765b0302c256ad61864095a537a3f6379901b1c2 | """
Day 1 Main Module
"""
from day01 import parse_input, part1, part2
if __name__ == "__main__":
# trying out the new walrus[:=] oprtr in python
if (part := int(input("Enter Part: "))) == 1:
print(part1(parse_input("input.txt")))
elif part == 2:
print(part2(parse_input("input.txt")))
e... | [((221, 245), 'day01.parse_input', 'parse_input', (['"""input.txt"""'], {}), "('input.txt')\n", (232, 245), False, 'from day01 import parse_input, part1, part2\n'), ((288, 312), 'day01.parse_input', 'parse_input', (['"""input.txt"""'], {}), "('input.txt')\n", (299, 312), False, 'from day01 import parse_input, part1, pa... |
ignasgri/Django_Quiz | quiz_app/settings.py | c98969d4181350eaaf8883f3930d0e800c240a44 | """
Django settings for quiz_app project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
SITE_ID = 1
... | [((715, 743), 'os.environ.get', 'os.environ.get', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (729, 743), False, 'import os\n'), ((819, 849), 'os.environ.get', 'os.environ.get', (['"""DEBUG"""', '(False)'], {}), "('DEBUG', False)\n", (833, 849), False, 'import os\n'), ((3470, 3501), 'os.path.join', 'os.path.join', ... |
davrempe/predicting-physical-dynamics | scripts/data/topple_dataset.py | b0abb385a7ac491e25d1df0b9a9a943621fc2d37 | import numpy as np
import pickle
from os.path import exists, realpath
import sys
import math
from topple_data_loader import ToppleData, ToppleDataLoader
import transforms3d
class ToppleNormalizationInfo():
'''
Structure to hold all the normalization information for a dataset.
'''
def __init__(self... | [((3728, 3766), 'numpy.zeros', 'np.zeros', (['(self.size, self.num_pts, 3)'], {}), '((self.size, self.num_pts, 3))\n', (3736, 3766), True, 'import numpy as np\n'), ((3790, 3830), 'numpy.zeros', 'np.zeros', (['(self.size, self.num_steps, 3)'], {}), '((self.size, self.num_steps, 3))\n', (3798, 3830), True, 'import numpy ... |
efkandurakli/Graduation-Project1 | Part1/AverageAccuracy.py | fd2cba89929da2cef49ec67214b54c310b57ce01 | import numpy as np
from operator import truediv
def AA_andEachClassAccuracy(confusion_matrix):
counter = confusion_matrix.shape[0]
list_diag = np.diag(confusion_matrix)
list_raw_sum = np.sum(confusion_matrix, axis=1)
each_acc = np.nan_to_num(truediv(list_diag, list_raw_sum))
average_acc = n... | [((157, 182), 'numpy.diag', 'np.diag', (['confusion_matrix'], {}), '(confusion_matrix)\n', (164, 182), True, 'import numpy as np\n'), ((203, 235), 'numpy.sum', 'np.sum', (['confusion_matrix'], {'axis': '(1)'}), '(confusion_matrix, axis=1)\n', (209, 235), True, 'import numpy as np\n'), ((319, 336), 'numpy.mean', 'np.mea... |
YangHee-Min/spinalcordtoolbox | scripts/sct_apply_transfo.py | 38ca15aa99b03ca99b7885ddc98adf2755adc43d | #!/usr/bin/env python
#########################################################################################
#
# Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechn... | [((1160, 1176), 'msct_parser.Parser', 'Parser', (['__file__'], {}), '(__file__)\n', (1166, 1176), False, 'from msct_parser import Parser\n'), ((12852, 12906), 'sct_utils.init_sct', 'sct.init_sct', ([], {'log_level': 'transform.verbose', 'update': '(True)'}), '(log_level=transform.verbose, update=True)\n', (12864, 12906... |
vurankar/mongo-connector | tests/plugins/test_plugin_base.py | 202aa28743855643fddd77d3e66bf1a640df3ed6 | # Copyright 2013-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | [((3116, 3131), 'tests.unittest.main', 'unittest.main', ([], {}), '()\n', (3129, 3131), False, 'from tests import unittest\n'), ((996, 1016), 'tests.plugins.helpers.get_test_namespace', 'get_test_namespace', ([], {}), '()\n', (1014, 1016), False, 'from tests.plugins.helpers import BAD_PLUGIN_CONFIGS, get_test_namespace... |
PerchLive/django-address | address/models.py | edab73847ba95d4f7a71993bcd55ea6bf300693e | import logging
import sys
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields.related import ForeignObject
from django.utils.encoding import python_2_unicode_compatible
try:
from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor
... | [((465, 492), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (482, 492), False, 'import logging\n'), ((4865, 4906), 'django.core.exceptions.ValidationError', 'ValidationError', (['"""Invalid address value."""'], {}), "('Invalid address value.')\n", (4880, 4906), False, 'from django.core.e... |
eavatar/ava | src/eavatar.ava/pod/mods/tasks/__init__.py | 4f09c5417b7187dd919b7edabb8c516d8efc0696 | # -*- coding: utf-8 -*-
"""
Modules for exposing functions that can be run as tasks.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
| [] |
jjiege/odoo | addons/hr_payroll_account/models/hr_payroll_account.py | fd5b8ad387c1881f349d125cbd56433f4d49398f | #-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_is_zero
class HrPayslipLine(models.Model):
_inherit = 'hr.payslip.line'
def _get_partner_... | [((1104, 1266), 'odoo.fields.Date', 'fields.Date', (['"""Date Account"""'], {'states': "{'draft': [('readonly', False)]}", 'readonly': '(True)', 'help': '"""Keep empty to use the period of the validation(Payslip) date."""'}), "('Date Account', states={'draft': [('readonly', False)]},\n readonly=True, help=\n 'Kee... |
abkoesdw/ml-datasets | ml_datasets/utils.py | c8c7b85ba8ed9c0ea233b4092d499d5022952011 | import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import sys
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import BoundaryNorm
def plot_images(
num_sample_perclass=10, x=None, y=None, labels=None, title=None, cmap=None
):
grid_x = num_samp... | [((366, 402), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(grid_y, grid_x)'}), '(figsize=(grid_y, grid_x))\n', (376, 402), True, 'import matplotlib.pyplot as plt\n'), ((413, 446), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['grid_y', 'grid_x'], {}), '(grid_y, grid_x)\n', (430, 446), True, 'im... |
MasterRadule/DefenceFirst | Simulator/simulator.py | d3c3a652357ac433213c38fa6134780e286f6cf2 | import logging
import os
import random
from abc import ABC, abstractmethod
from random import randint
from time import sleep, strftime
HOSTNAME = ['defence-first.rs', 'defence-first.de', 'defence-first.ru']
HOSTIP = ['78.218.236.218', '87.236.11.212', '54.147.165.86']
SOURCEIP = ['163.189.141.53', '204.164.10.7', '213... | [((3803, 3811), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (3808, 3811), False, 'from time import sleep, strftime\n'), ((3947, 3993), 'logging.Formatter', 'logging.Formatter', (['FORMAT', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(FORMAT, '%Y-%m-%d %H:%M:%S')\n", (3964, 3993), False, 'import logging\n'), ((4012, 4042), 'lo... |
DaniMarts/bayesrace | bayes_race/pp/__init__.py | 3d0d2b26dac2e33ad7e38513304cfb259abe351c | from bayes_race.pp.pure_pursuit import purePursuit | [] |
utiasASRL/pysteam | pysteam/evaluator/vector_space_error_eval.py | c0c8809ee2a5e1dab5ce7f9e5ff9de91138ce68b | from typing import Optional
import numpy as np
from . import Evaluator
from ..state import VectorSpaceStateVar
class VectorSpaceErrorEval(Evaluator):
"""Error evaluator for a measured vector space state variable"""
def __init__(self, meas: np.ndarray, state_vec: VectorSpaceStateVar) -> None:
super().__init_... | [] |
mwussow/pytorch_geometric | torch_geometric/nn/unpool/__init__.py | 01c68f9b58c94d9efd1f6e39b9c85177aae521bb | from .knn_interpolate import knn_interpolate
__all__ = [
'knn_interpolate',
]
| [] |
namuyan/bc4py | bc4py/bip32/utils.py | 6484d356096261d0d57e9e1f5ffeae1f9a9865f3 | from bc4py_extension import PyAddress
import hashlib
def is_address(ck: PyAddress, hrp, ver):
"""check bech32 format and version"""
try:
if ck.hrp != hrp:
return False
if ck.version != ver:
return False
except ValueError:
return False
return True
def g... | [((488, 530), 'bc4py_extension.PyAddress.from_param', 'PyAddress.from_param', (['hrp', 'ver', 'identifier'], {}), '(hrp, ver, identifier)\n', (508, 530), False, 'from bc4py_extension import PyAddress\n'), ((789, 839), 'bc4py_extension.PyAddress.from_param', 'PyAddress.from_param', (['"""dummy"""', '(0)', 'dummy_identif... |
LaborBerlin/cubi-tk | cubi_tk/snappy/kickoff.py | 4aa5306c547c38eb41d5623ff6e4bace828f85b1 | """``cubi-tk snappy kickoff``: kickoff SNAPPY pipeline."""
import argparse
import os
import subprocess
import typing
from logzero import logger
from toposort import toposort
from . import common
from cubi_tk.exceptions import ParseOutputException
def run(
args, _parser: argparse.ArgumentParser, _subparser: ar... | [((373, 428), 'logzero.logger.info', 'logger.info', (['"""Try to find SNAPPY pipeline directory..."""'], {}), "('Try to find SNAPPY pipeline directory...')\n", (384, 428), False, 'from logzero import logger\n'), ((667, 744), 'logzero.logger.info', 'logger.info', (['"""Looking for pipeline directories (assuming standard... |
RajatRasal/devito | tests/test_autotuner.py | 162abb6b318e77eaa4e8f719047327c45782056f | from __future__ import absolute_import
from functools import reduce
from operator import mul
try:
from StringIO import StringIO
except ImportError:
# Python3 compatibility
from io import StringIO
import pytest
from conftest import skipif_yask
import numpy as np
from devito import Grid, Function, TimeFun... | [((410, 437), 'devito.silencio', 'silencio', ([], {'log_level': '"""DEBUG"""'}), "(log_level='DEBUG')\n", (418, 437), False, 'from devito import Grid, Function, TimeFunction, Eq, Operator, configuration, silencio\n'), ((452, 531), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape,expected"""', '[((30, 3... |
timctho/detectron2-chargrid | projects/CharGrid/data/bizcard2coco.py | 547479c88ad7d1de2348377706167a84d024a622 | from data.data_reader import BIZCARD_LABEL_MAP, BizcardDataParser
import argparse
from pathlib import Path
import os
import json
import cv2
import numpy as np
def convert_bizcard_to_coco_format(image_dir, json_dir, id_list, out_dir, out_name):
coco_json = {}
images = []
annotations = []
categories = [... | [((2152, 2177), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2175, 2177), False, 'import argparse\n'), ((351, 375), 'data.data_reader.BIZCARD_LABEL_MAP.keys', 'BIZCARD_LABEL_MAP.keys', ([], {}), '()\n', (373, 375), False, 'from data.data_reader import BIZCARD_LABEL_MAP, BizcardDataParser\n')... |
m09/deckz | deckz/cli/run.py | 0f97ef2a43c2c714ac18173a4fe3266cccba31e2 | from pathlib import Path
from typing import List, Optional
from typer import Argument
from deckz.cli import app
from deckz.paths import Paths
from deckz.running import run as running_run
@app.command()
def run(
targets: Optional[List[str]] = Argument(None),
handout: bool = True,
presentation: bool = Tru... | [((192, 205), 'deckz.cli.app.command', 'app.command', ([], {}), '()\n', (203, 205), False, 'from deckz.cli import app\n'), ((250, 264), 'typer.Argument', 'Argument', (['None'], {}), '(None)\n', (258, 264), False, 'from typer import Argument\n'), ((369, 378), 'pathlib.Path', 'Path', (['"""."""'], {}), "('.')\n", (373, 3... |
dlangille/pgeu-system | postgresqleu/confreg/templatetags/miscutil.py | 3f1910010063bab118e94a55ed757b23f1d36bf5 | from django import template
register = template.Library()
@register.filter(name='isboolean')
def isboolean(value):
return isinstance(value, bool)
@register.filter(name='vartypename')
def vartypename(value):
return type(value).__name__
| [((40, 58), 'django.template.Library', 'template.Library', ([], {}), '()\n', (56, 58), False, 'from django import template\n')] |
rchampa/chat-server | chat.py | 34b5897e90b580754ad95b36bf7f23ac9baf3175 | import asyncio
import contextvars
import aioredis
import uvloop
from aioredis import Redis
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.staticfiles import StaticFiles
from RLog import rprint
from routers import apirest, websockets
REDIS_HOST = 'redis'
REDIS_PORT =... | [((368, 413), 'contextvars.ContextVar', 'contextvars.ContextVar', (['"""redis"""'], {'default': 'None'}), "('redis', default=None)\n", (390, 413), False, 'import contextvars\n'), ((975, 984), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (982, 984), False, 'from fastapi import FastAPI\n'), ((943, 967), 'uvloop.EventL... |
abel-bernabeu/facecompressor | cli.py | 9322f4e3d3f2787dc9dec2fad6b3f1995d052077 | import argparse
import autoencoder
def addTrainablesArg(parser):
parser.add_argument('--model', dest='model', help='Trained model', default='model.pt')
def addExchangeArg(parser):
parser.add_argument('--exchange', dest='exchange', help='File with exchanged data', required=True)
parser = argparse.ArgumentPa... | [((301, 326), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (324, 326), False, 'import argparse\n'), ((858, 915), 'autoencoder.encode', 'autoencoder.encode', (['opts.model', 'opts.input', 'opts.exchange'], {}), '(opts.model, opts.input, opts.exchange)\n', (876, 915), False, 'import autoencoder... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.