max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
poll/models/telemetry_models.py | mirokrastev/poll-website | 3 | 2900 | <filename>poll/models/telemetry_models.py
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.
"""
... | <filename>poll/models/telemetry_models.py
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.
"""
... | en | 0.904979 | This Base class gives a hint that in the future more Telemetry classes could be implemented. To "store" the anonymous users that have viewed the Poll, I need to store their IP Addresses. It will NEVER be displayed outside the admin panel. | 2.465099 | 2 |
pcdet/models/backbones_2d/__init__.py | HenryLittle/OpenPCDet-HL | 0 | 2901 | from .base_bev_backbone import BaseBEVBackbone
from .decouple_bev_backbone import DecoupledBEVBackbone
__all__ = {
'BaseBEVBackbone': BaseBEVBackbone,
'DecoupledBEVBackbone': DecoupledBEVBackbone,
}
| from .base_bev_backbone import BaseBEVBackbone
from .decouple_bev_backbone import DecoupledBEVBackbone
__all__ = {
'BaseBEVBackbone': BaseBEVBackbone,
'DecoupledBEVBackbone': DecoupledBEVBackbone,
}
| none | 1 | 1.117819 | 1 | |
test/unit/app/tools/test_select_parameters.py | beatrizserrano/galaxy | 0 | 2902 | 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="... | 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="... | en | 0.239618 | <options><filter type="data_meta" ref="input_bam" key="dbkey"/></options> <options><filter type="data_meta" ref="input_bam" key="dbkey"/></options> <options><filter type="data_meta" ref="input_bam" key="dbkey"/></options> <options><filter type="data_meta" ref="input_bam" key="dbkey"/></options> <options><filter type="d... | 2.414381 | 2 |
recumpiler/__init__.py | Toasterstein/recumpiler | 0 | 2903 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""recumpiler
Recompile text to be semi-readable memey garbage.
"""
__version__ = (0, 0, 0) | en | 0.305295 | #!/usr/bin/env python # -*- coding: utf-8 -*- recumpiler Recompile text to be semi-readable memey garbage. | 1.351241 | 1 |
net/net.gyp | codenote/chromium-test | 0 | 2904 | <reponame>codenote/chromium-test<gh_stars>0
# 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==... | # 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"', {
... | en | 0.757648 | # 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. # Disable Kerberos on ChromeOS, Android and iOS, at least for now. # It needs configuration (krb5.conf and so on). # chromeos == 0 # The way the cache uses mm... | 1.3783 | 1 |
python/clx/analytics/detector.py | mdemoret-nv/clx | 0 | 2905 | 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... | 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... | en | 0.708502 | This function load already saved model and sets cuda parameters. :param file_path: File path of a model to loaded. :type file_path: string This function saves model to given location. :param file_path: File path to save model. :type file_path: string This function leverages model by se... | 2.767625 | 3 |
street_score/project/models.py | openplans/streetscore | 4 | 2906 | <reponame>openplans/streetscore<filename>street_score/project/models.py
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 = model... | 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... | en | 0.924849 | Base model class for when you want to keep track of created and updated times for model instances. The criterion that this rating is for. The first place that this rating compares The second place that this rating compares The rating score. 1 means that place1 "wins" over place2 for the given criterion. -... | 2.976023 | 3 |
src/selfdroid/appstorage/crud/AppAdder.py | vitlabuda/selfdroid-web-app | 1 | 2907 | # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2021 <NAME>. 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, th... | # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2021 <NAME>. 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, th... | en | 0.751006 | # SPDX-License-Identifier: BSD-3-Clause # # Copyright (c) 2021 <NAME>. 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, th... | 1.163816 | 1 |
library/libvirt_filter.py | bkmeneguello/ansible-role-libvirt | 1 | 2908 | # TODO: https://libvirt.org/formatnwfilter.html | # TODO: https://libvirt.org/formatnwfilter.html | en | 0.255672 | # TODO: https://libvirt.org/formatnwfilter.html | 0.961307 | 1 |
estafeta/core/__init__.py | Solunest/pyestafeta | 0 | 2909 | <reponame>Solunest/pyestafeta<filename>estafeta/core/__init__.py
from estafeta.core.client import EstafetaClient
user = None
password = <PASSWORD>
id = None
account_number = None
production = None
from estafeta.core.error import EstafetaWrongData, EstafetaEmptyField
__url_label__ = [
'https://labelqa.estafeta.c... | from estafeta.core.client import EstafetaClient
user = None
password = <PASSWORD>
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://la... | none | 1 | 1.716041 | 2 | |
yunionclient/api/flavors.py | tb365/mcclient_python | 3 | 2910 | <gh_stars>1-10
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',
'D... | 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... | none | 1 | 1.234979 | 1 | |
char_map.py | rakib313/Bangla-End2End-Speech-Recognition | 0 | 2911 | <reponame>rakib313/Bangla-End2End-Speech-Recognition
"""
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
... | """
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... | bn | 0.37907 | Defines two dictionaries for converting between text and integer sequences. ' 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 ঙ 43 খ 44 ঃ 45 ১ 46 ৯ 47 ৬ 48 ০ ... | 3.583975 | 4 |
app.py | MaggieChege/New_App | 0 | 2912 | 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') | 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') | en | 0.819367 | # from restful import Api # Route | 2.295279 | 2 |
websockets.py | ejojmjn/indiana-phone | 0 | 2913 | #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... | #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... | en | 0.198083 | #from gevent import monkey #monkey.patch_all() #socketio = SocketIO(app) #Message: (':1.654', '/hfp/org/bluez/hci0/dev_94_65_2D_84_61_99', 'org.ofono.Modem', 'PropertyChanged', ('Powered', False)) #Data: Powered <html> <head> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.... | 2.138059 | 2 |
tests/pytests/test_tags.py | wayn111/RediSearch | 0 | 2914 | <filename>tests/pytests/test_tags.py
# -*- 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 ... | <filename>tests/pytests/test_tags.py
# -*- 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 ... | en | 0.93102 | # -*- coding: utf-8 -*- # inorder should not affect tags # invalid syntax # this test basically make sure we are not leaking # not casesensitive # casesensitive # not casesensitive # casesensitive # delete two tags # delete last tag # check term can be used after being empty # delete both documents and run the GC to cl... | 2.12961 | 2 |
sc2/bot_ai.py | Lexa307/PhotonDefender | 2 | 2915 | <filename>sc2/bot_ai.py
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, R... | <filename>sc2/bot_ai.py
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, R... | en | 0.87953 | # mypy type checking # imports for mypy and pycharm autocomplete Base class for bots. # Specific opponent bot ID used in sc2ai ladder games http://sc2ai.net/ # The bot ID will stay the same each game so your bot can "adapt" to the opponent # Doesn't include workers in production Returns time in seconds, assumes the gam... | 2.350947 | 2 |
src/python/pants/jvm/resolve/lockfile_metadata.py | xyzst/pants | 0 | 2916 | # 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 (
... | # 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 (
... | en | 0.812327 | # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). Call the most recent version of the `LockfileMetadata` class to construct a concrete instance. This static method should be used in place of the `LockfileMetadata` construc... | 2.185852 | 2 |
generator/generator.py | GregorKikelj/opendbc | 1,059 | 2917 | #!/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... | #!/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... | ru | 0.371772 | #!/usr/bin/env python3 #print(src_dir) #print(filename) | 2.705533 | 3 |
customer/admin.py | matheusdemicheli/dogtel | 0 | 2918 | 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... | 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... | en | 0.261311 | Owner ModelAdmin. Breed ModelAdmin. SubBreed ModelAdmin. Dog ModelAdmin. Render the dog's photo. | 2.071632 | 2 |
kaneda/tasks/rq.py | APSL/kaneda | 59 | 2919 | 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... | 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... | en | 0.852547 | RQ job to report metrics to the configured backend in kanedasettings.py To run the worker execute this command: rqworker [queue] | 2.406714 | 2 |
src/ripper.py | jg-rivera/cert-ripper | 0 | 2920 | 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,
):
... | 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,
):
... | none | 1 | 2.806926 | 3 | |
venv/Lib/site-packages/tests/test_111_FieldNumAddCol.py | shehzadulislam/Assignment4 | 0 | 2921 | #
# 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_... | #
# 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_... | it | 0.187313 | # # Licensed Materials - Property of IBM # # (c) Copyright IBM Corp. 2007-2008 # #__END__ #__LUW_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False #__ZOS_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) #False #__SYSTEMI_EXPECTED__ #False #int(0) #int(1) #False #False #False #int(1) ... | 2.480292 | 2 |
foundation/djangocms_pagebanner/cms_toolbar.py | Mindelirium/foundation | 0 | 2922 | <reponame>Mindelirium/foundation<gh_stars>0
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 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... | en | 0.779208 | # always use draft if we have a page # Nothing to do # check global permissions if CMS_PERMISSIONS is active # check if user has page edit permission # not in urls | 2.039752 | 2 |
tasks/lm/models/lm.py | etri-edgeai/nn-comp-discblock | 10 | 2923 | <gh_stars>1-10
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=No... | 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... | en | 0.68362 | Container module with an encoder, a recurrent module, and a decoder. An invalid option for `--model` was supplied, options are ['LSTM', 'GRU', 'RNN_TANH' or 'RNN_RELU'] # Optionally tie weights as in: # "Using the Output Embedding to Improve Language Models" (Press & Wolf 2016) # https:... | 2.907164 | 3 |
fibo.py | Baibhabswain/pythonPrograms | 1 | 2924 | <reponame>Baibhabswain/pythonPrograms
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() | 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() | none | 1 | 3.792834 | 4 | |
scrapper/playstation/__init__.py | gghf-service/gghf-api | 1 | 2925 | from scrapper.playstation.spider import main | from scrapper.playstation.spider import main | none | 1 | 1.083322 | 1 | |
plugins/number.py | motakine/ILAS_slackbot | 0 | 2926 | 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... | 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... | ja | 0.987657 | number 判定 Args: num (int): 判定する数字 Returns: str: num が answer より大きい: 'Too large' num が answer より小さい: 'Too small' num が answer と一致: 'Correct!'、新しくゲームを始める その他: 'Can I kick you?.' 0は不可思議な数である maxが1の時に2以上を答えると1だけだと言われる # 入力された値に応じて返答を構成、正解なら... | 3.899585 | 4 |
pytype/analyze.py | hatal175/pytype | 0 | 2927 | """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... | """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... | en | 0.839274 | Code for checking and inferring types. # Most interpreter functions (including lambdas) need to be analyzed as # stand-alone functions. The exceptions are comprehensions and generators, which # have names like "<listcomp>" and "<genexpr>". # How deep to follow call chains: # during module loading # during non-quick ana... | 2.24404 | 2 |
src/cupcake/post_isoseq_cluster/demux_by_barcode_groups.py | milescsmith/cDNA_Cupcake | 0 | 2928 | #!/usr/bin/env python
__author__ = "<EMAIL>"
"""
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 Optional
... | #!/usr/bin/env python
__author__ = "<EMAIL>"
"""
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 Optional
... | en | 0.60991 | #!/usr/bin/env python 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 :param pooled_sam: SAM file :param demux_count_file: comma-delimited per-barcode count file :param output_prefix: output prefi... | 2.820858 | 3 |
vll/data/circle_dataset.py | paulhfu/3dcv-students | 4 | 2929 | 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... | 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... | en | 0.72569 | # restrict the maximum slope of generated lines for stability # restrict the minimum length of line segments Generator of circle segment images. Images will have 1 random circle each, filled with noise and distractor lines. Class also offers functionality for drawing line parameters, hypotheses and point predictions... | 2.909042 | 3 |
VAE/reduced_model/nesm_generator.py | youngmg1995/NES-Music-Maker | 3 | 2930 | <reponame>youngmg1995/NES-Music-Maker
# -*- 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 ... | # -*- 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... | en | 0.430567 | # -*- 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 rather ... | 2.393292 | 2 |
anlogger/logger.py | anttin/anlogger | 0 | 2931 | 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... | 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... | none | 1 | 2.75154 | 3 | |
Python/hello_world-theopaid.py | saurabhcommand/Hello-world | 1,428 | 2932 | #Author <NAME>
print("Hello World")
hello_list = ["Hello World"]
print(hello_list[0])
for i in hello_list:
print(i) | #Author <NAME>
print("Hello World")
hello_list = ["Hello World"]
print(hello_list[0])
for i in hello_list:
print(i) | en | 0.748841 | #Author <NAME> | 3.316132 | 3 |
question_answering/stubs.py | uliang/NaturalLanguageQueryingSystem | 0 | 2933 | <filename>question_answering/stubs.py
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... | <filename>question_answering/stubs.py
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... | none | 1 | 2.707191 | 3 | |
lib/env/trade/BaseTradeStrategy.py | devas123/Bitcoin-Trader-RL | 0 | 2934 | 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_... | 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_... | none | 1 | 3.249586 | 3 | |
4day/Book04_1.py | jsjang93/joony | 0 | 2935 | <reponame>jsjang93/joony<gh_stars>0
# 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) ; ... | # 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) | en | 0.88756 | # Book04_1.py # Class 멤버 | 3.084826 | 3 |
wrappers/python/virgil_crypto_lib/foundation/kdf1.py | odidev/virgil-crypto-c | 26 | 2936 | <filename>wrappers/python/virgil_crypto_lib/foundation/kdf1.py
# 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 so... | <filename>wrappers/python/virgil_crypto_lib/foundation/kdf1.py
# 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 so... | en | 0.717412 | # 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... | 1.12728 | 1 |
mysite/zoo/tests.py | leixiayang/django-python | 54 | 2937 | #!/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()... | #!/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()... | en | 0.732171 | #!/usr/bin/env python # encoding: utf-8 Test animals' sound test dog says woof or not test cat says meow of not | 2.706917 | 3 |
EX025.py | gjaosdij/PythonProject | 0 | 2938 | print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome)
| print('Digite seu nome completo: ')
nome = input().strip().upper()
print('Seu nome tem "Silva"?')
print('SILVA' in nome)
| none | 1 | 3.731581 | 4 | |
configs/_base_/datasets/stvqa_dataset.py | linxi1158/iMIX | 23 | 2939 | 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... | 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... | none | 1 | 1.735125 | 2 | |
src/rpocore/migrations/0007_auto_20160927_1517.py | 2martens/rpo-website | 0 | 2940 | # -*- 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... | # -*- 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... | en | 0.802593 | # -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-09-27 13:17 | 1.576893 | 2 |
code/Line.py | manno-xx/FutureLearnRobotBuggy | 0 | 2941 | #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()
| #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()
| en | 0.313693 | #LineSensor test | 2.84623 | 3 |
litex_boards/platforms/myminieye_runber.py | chmousset/litex-boards | 0 | 2942 | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
# 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 OpenFPGALoader
# IOs ----------------------... | #
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 <NAME> <<EMAIL>>
# 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 OpenFPGALoader
# IOs ----------------------... | en | 0.444849 | # # This file is part of LiteX-Boards. # # Copyright (c) 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause # IOs ---------------------------------------------------------------------------------------------- # Clk / Rst # Leds # RGB led, active-low # Switches # Buttons. # Serial. # FT232H has only one inter... | 1.196671 | 1 |
combo/search/discrete/policy.py | zhangkunliang/BayesOptimization | 139 | 2943 | 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... | 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... | none | 1 | 2.216055 | 2 | |
venv/lib/python3.9/site-packages/py2app/bootstrap/disable_linecache.py | dequeb/asmbattle | 193 | 2944 | <filename>venv/lib/python3.9/site-packages/py2app/bootstrap/disable_linecache.py
def _disable_linecache():
import linecache
def fake_getline(*args, **kwargs):
return ""
linecache.orig_getline = linecache.getline
linecache.getline = fake_getline
_disable_linecache()
| <filename>venv/lib/python3.9/site-packages/py2app/bootstrap/disable_linecache.py
def _disable_linecache():
import linecache
def fake_getline(*args, **kwargs):
return ""
linecache.orig_getline = linecache.getline
linecache.getline = fake_getline
_disable_linecache()
| none | 1 | 2.252489 | 2 | |
source.py | s403o/tw_bot | 0 | 2945 | <reponame>s403o/tw_bot
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(... | 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(... | en | 0.782772 | #source # the source you want the bot take images from #down page #locate #create folder for located imgs #open the new folder #img name #get images | 3.039021 | 3 |
lib/appController.py | QIAOANGeo/BZB_ydzw | 2 | 2946 | <filename>lib/appController.py
'''
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 Controll... | <filename>lib/appController.py
'''
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 Controll... | zh | 0.778936 | 1、启动appium服务 subproccess 配置文件 1.1、校验服务是否启动 1.2、杀掉上一次的服务 2、启动driver # 声明一个python队列 # 获取配置信息 # 获取到所有的手机信息 # port 用于校验服务是否启动 ps -ef|grep appium|grep -v grep|grep %s|awk '{print "kill -9 " $2}'|sh # mac = 'ps -ef|grep appium|grep -v grep|grep %s' % self.port # 合并手机信息和包名入口 | 2.813702 | 3 |
pondSizes.py | passionzhan/LeetCode | 1 | 2947 | # -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : pondSizes.py
@Contact : <EMAIL>
@Desc :
你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1... | # -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : pondSizes.py
@Contact : <EMAIL>
@Desc :
你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1... | zh | 0.73021 | # -*- encoding: utf-8 -*- @project : LeetCode @File : pondSizes.py @Contact : <EMAIL> @Desc : 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。 示例: 输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1... | 3.366242 | 3 |
geolucidate/functions.py | kurtraschke/geolucidate | 3 | 2948 | <filename>geolucidate/functions.py
# -*- 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):
"""
... | <filename>geolucidate/functions.py
# -*- 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):
"""
... | en | 0.419895 | # -*- coding: utf-8 -*- Normalize up the parts matched by :obj:`parser.parser_re` to degrees, minutes, and seconds. >>> _cleanup({'latdir': 'south', 'longdir': 'west', ... 'latdeg':'60','latmin':'30', ... 'longdeg':'50','longmin':'40'}) ['S', '60', '30', '00', 'W', '50', '40', '00... | 2.703604 | 3 |
setup.py | rluzuriaga/pokedex | 30 | 2949 | 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',
... | 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',
... | none | 1 | 1.294568 | 1 | |
lingvo/tasks/asr/encoder.py | j-luo93/lingvo | 4 | 2950 | # 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... | # 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... | en | 0.846237 | # 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... | 1.930048 | 2 |
pos_neg_graph/graph_ratio.py | Yudabin/Review_Project | 0 | 2951 | 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... | 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... | ko | 0.99666 | # For Windows ## 라벨설정함. 한글이 적용이 안됨!!! ## 빈도 ## 캔버스 생성 ## 캔버스 배경색을 하얀색으로 설정 ## 프레임 생성 ## 파이차트 출력 ## 시작점을 90도(degree)로 지정 ## 시계 방향으로 그린다. # autopct=lambda p : '{:.2f}%'.format(p), ## 퍼센티지 출력 ## 빈도수 총합 ## 백분율 초기값 ## 각1, 각2 ## 원의 반지름 ## 정중앙 x좌표 ## 정중앙 y좌표 ## 백분율을 누적한다. ## 백분율 텍스트 표시 ## 총합을 100으로 맞추기위해 마지막 백분율은 100에서 백분율 누적... | 2.71006 | 3 |
blog/views.py | kbilak/City-portal | 0 | 2952 | <reponame>kbilak/City-portal
from django.shortcuts import render
from django.views.generic import TemplateView
def index(request):
return render(request, 'index.html') | from django.shortcuts import render
from django.views.generic import TemplateView
def index(request):
return render(request, 'index.html') | none | 1 | 1.490293 | 1 | |
my_area/views.py | Vincent-Juma/area_master | 1 | 2953 | 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.... | 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.... | none | 1 | 2.16992 | 2 | |
2020/day_01/__main__.py | d02d33pak/Advent-Of-Code | 0 | 2954 | """
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... | """
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... | en | 0.603826 | Day 1 Main Module # trying out the new walrus[:=] oprtr in python | 3.272148 | 3 |
quiz_app/settings.py | ignasgri/Django_Quiz | 0 | 2955 | """
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
... | """
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
... | en | 0.575374 | 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/ # Build paths inside... | 2.078209 | 2 |
scripts/data/topple_dataset.py | davrempe/predicting-physical-dynamics | 16 | 2956 | 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... | 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... | en | 0.770618 | Structure to hold all the normalization information for a dataset. # max element of any linear vel vector # max element of any angular vel vector # max distance between positions in two contiguous timesteps # max change in rotation around any axis between two contiguous timesteps (for euler rot) # max angle of rotation... | 2.421776 | 2 |
Part1/AverageAccuracy.py | efkandurakli/Graduation-Project1 | 1 | 2957 | 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... | 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... | none | 1 | 2.49912 | 2 | |
scripts/sct_apply_transfo.py | YangHee-Min/spinalcordtoolbox | 0 | 2958 | #!/usr/bin/env python
#########################################################################################
#
# Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechn... | #!/usr/bin/env python
#########################################################################################
#
# Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2014 Polytechn... | en | 0.492788 | #!/usr/bin/env python ######################################################################################### # # Apply transformations. This function is a wrapper for sct_WarpImageMultiTransform # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechn... | 1.907159 | 2 |
tests/plugins/test_plugin_base.py | vurankar/mongo-connector | 1 | 2959 | # 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... | # 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... | en | 0.807702 | # 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... | 2.119973 | 2 |
address/models.py | PerchLive/django-address | 0 | 2960 | 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
... | 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
... | en | 0.786983 | # If there is no value (empty raw) then return None. # Fix issue with NYC boroughs (https://code.google.com/p/gmaps-api-issues/issues/detail?id=635) # If we have an inconsistent set of value bail out now. # Handle the country. # Handle the state. # Handle the locality. # Handle the address. # If "formatted" is empty tr... | 2.174865 | 2 |
src/eavatar.ava/pod/mods/tasks/__init__.py | eavatar/ava | 0 | 2961 | <reponame>eavatar/ava
# -*- coding: utf-8 -*-
"""
Modules for exposing functions that can be run as tasks.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
| # -*- coding: utf-8 -*-
"""
Modules for exposing functions that can be run as tasks.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals) | en | 0.888814 | # -*- coding: utf-8 -*- Modules for exposing functions that can be run as tasks. | 1.1293 | 1 |
addons/hr_payroll_account/models/hr_payroll_account.py | jjiege/odoo | 0 | 2962 | <reponame>jjiege/odoo<filename>addons/hr_payroll_account/models/hr_payroll_account.py
#-*- 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
clas... | #-*- 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_... | en | 0.848809 | #-*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. Get partner_id of slip line to use in account_move_line # use partner of salary rule or fallback on employee's address | 1.937144 | 2 |
ml_datasets/utils.py | abkoesdw/ml-datasets | 1 | 2963 | 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... | 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... | en | 0.149059 | # np.arange(mat_min + 6, mat_max - 6, 0.1) # fig.set_size_inches((6, 12), forward=False) # fig.savefig("img/dna.png", dpi=200) | 2.559823 | 3 |
Simulator/simulator.py | MasterRadule/DefenceFirst | 0 | 2964 | 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 = ['172.16.17.32', '192.168.127.12', '172.16.58.3']
SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16... | 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 = ['172.16.17.32', '192.168.127.12', '172.16.58.3']
SOURCEIP = ['192.168.3.11', '192.168.127.12', '172.16... | none | 1 | 2.304161 | 2 | |
bayes_race/pp/__init__.py | DaniMarts/bayesrace | 23 | 2965 | <gh_stars>10-100
from bayes_race.pp.pure_pursuit import purePursuit | from bayes_race.pp.pure_pursuit import purePursuit | none | 1 | 0.98612 | 1 | |
pysteam/evaluator/vector_space_error_eval.py | utiasASRL/pysteam | 5 | 2966 | <reponame>utiasASRL/pysteam
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) ... | 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_... | en | 0.792931 | Error evaluator for a measured vector space state variable | 2.72916 | 3 |
torch_geometric/nn/unpool/__init__.py | mwussow/pytorch_geometric | 13 | 2967 | <reponame>mwussow/pytorch_geometric
from .knn_interpolate import knn_interpolate
__all__ = [
'knn_interpolate',
]
| from .knn_interpolate import knn_interpolate
__all__ = [
'knn_interpolate',
] | none | 1 | 1.139508 | 1 | |
bc4py/bip32/utils.py | namuyan/bc4py | 12 | 2968 | 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... | 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... | en | 0.847582 | check bech32 format and version get address from public key convert address's version | 2.612922 | 3 |
cubi_tk/snappy/kickoff.py | LaborBerlin/cubi-tk | 0 | 2969 | <reponame>LaborBerlin/cubi-tk<filename>cubi_tk/snappy/kickoff.py
"""``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
de... | """``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... | en | 0.644145 | ``cubi-tk snappy kickoff``: kickoff SNAPPY pipeline. # TODO: this assumes standard naming which is a limitation... Setup argument parser for ``cubi-tk snappy pull-sheet``. | 2.367818 | 2 |
tests/test_autotuner.py | RajatRasal/devito | 0 | 2970 | <filename>tests/test_autotuner.py
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 dev... | <filename>tests/test_autotuner.py
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 dev... | en | 0.857754 | # Python3 compatibility Check that autotuning is actually running when switched on, in both 2D and 3D operators. # Expected 3 AT attempts for the given shape # Now try the same with aggressive autotuning, which tries 9 more cases Check that each autotuning run (ie with a given block shape) takes ``autotuning.co... | 2.125404 | 2 |
projects/CharGrid/data/bizcard2coco.py | timctho/detectron2-chargrid | 3 | 2971 | 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 = [... | 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 = [... | none | 1 | 2.578377 | 3 | |
deckz/cli/run.py | m09/deckz | 0 | 2972 | <reponame>m09/deckz
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,
pres... | 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... | en | 0.756617 | Compile main targets. | 2.352774 | 2 |
postgresqleu/confreg/templatetags/miscutil.py | dlangille/pgeu-system | 0 | 2973 | <gh_stars>0
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__
| 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__ | none | 1 | 2.12139 | 2 | |
chat.py | rchampa/chat-server | 0 | 2974 | 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 =... | 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 =... | en | 0.766459 | # uvloop is written in Cython and is built on top of libuv http://magic.io/blog/uvloop-blazing-fast-python-networking/ #, uds='uvicorn.sock') | 2.205076 | 2 |
cli.py | abel-bernabeu/facecompressor | 2 | 2975 | <reponame>abel-bernabeu/facecompressor<gh_stars>1-10
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... | 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... | none | 1 | 2.62005 | 3 | |
lib/bridgedb/email/request.py | liudonghua123/bridgedb | 0 | 2976 | <filename>lib/bridgedb/email/request.py
# -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*-
#_____________________________________________________________________________
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL... | <filename>lib/bridgedb/email/request.py
# -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*-
#_____________________________________________________________________________
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL... | en | 0.802637 | # -*- coding: utf-8; test-case-name: bridgedb.test.test_email_request; -*- #_____________________________________________________________________________ # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> 0xA3ADB67A2CDB8B35 # <NAME>... | 1.932987 | 2 |
test/com/facebook/buck/skylark/parser/testdata/rule_with_wrong_types/attr_value_type/subdir/foo.bzl | Unknoob/buck | 8,027 | 2977 | <gh_stars>1000+
""" Module docstring """
def _impl(_ctx):
""" Function docstring """
pass
some_rule = rule(
attrs = {
"attr1": attr.int(
default = 2,
mandatory = False,
),
"attr2": 5,
},
implementation = _impl,
)
| """ Module docstring """
def _impl(_ctx):
""" Function docstring """
pass
some_rule = rule(
attrs = {
"attr1": attr.int(
default = 2,
mandatory = False,
),
"attr2": 5,
},
implementation = _impl,
) | en | 0.309581 | Module docstring Function docstring | 2.236444 | 2 |
src/printReport.py | griimx/Summer-2016 | 0 | 2978 | <filename>src/printReport.py
from __future__ import print_function
from connection import *
from jinja2 import Environment, FileSystemLoader
import webbrowser
def print_report(id):
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("src/template.html")
cursor = db.cursor(MySQLdb.cursors.D... | <filename>src/printReport.py
from __future__ import print_function
from connection import *
from jinja2 import Environment, FileSystemLoader
import webbrowser
def print_report(id):
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("src/template.html")
cursor = db.cursor(MySQLdb.cursors.D... | en | 0.161341 | # print(sql) # print(result[0]) # self.entry_text(self.entry_name, result['firstName']+" "+result['lastName'] ) # self.entry_text(self.entry_EmpID, result['empID']) # self.entry_text(self.entry_EmpName, result['firstName']+" "+result['lastName']) # self.entry_text(self.entry_personalno, result['empI... | 2.702939 | 3 |
packages/pyre/schemata/Container.py | avalentino/pyre | 25 | 2979 | # -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2021 all rights reserved
#
# superclass
from .Schema import Schema
# declaration
class Container(Schema):
"""
The base class for type declarators that are sequences of other types
"""
# constants
typename = 'container' # the name of my... | # -*- coding: utf-8 -*-
#
# <NAME>
# orthologue
# (c) 1998-2021 all rights reserved
#
# superclass
from .Schema import Schema
# declaration
class Container(Schema):
"""
The base class for type declarators that are sequences of other types
"""
# constants
typename = 'container' # the name of my... | en | 0.85073 | # -*- coding: utf-8 -*- # # <NAME> # orthologue # (c) 1998-2021 all rights reserved # # superclass # declaration The base class for type declarators that are sequences of other types # constants # the name of my type The default container represented by this schema # complain that the subclass is not constructed proper... | 2.631309 | 3 |
electronicparsers/exciting/parser.py | nomad-coe/electronic-parsers | 0 | 2980 | #
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD.
# See https://nomad-lab.eu for further info.
#
# 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/lic... | #
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD.
# See https://nomad-lab.eu for further info.
#
# 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/lic... | en | 0.86191 | # # Copyright The NOMAD Authors. # # This file is part of NOMAD. # See https://nomad-lab.eu for further info. # # 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/lic... | 1.796064 | 2 |
services/storage/client-sdk/python/simcore_service_storage_sdk/api/users_api.py | KZzizzle/osparc-simcore | 0 | 2981 | # coding: utf-8
"""
simcore-service-storage API
API definition for simcore-service-storage service # noqa: E501
OpenAPI spec version: 0.1.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3... | # coding: utf-8
"""
simcore-service-storage API
API definition for simcore-service-storage service # noqa: E501
OpenAPI spec version: 0.1.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3... | en | 0.604009 | # coding: utf-8 simcore-service-storage API API definition for simcore-service-storage service # noqa: E501 OpenAPI spec version: 0.1.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech # noqa: F401 # python 2 and python 3 compatibility library NOTE: This class is auto generated by OpenAP... | 2.011367 | 2 |
reservation_management/migrations/0021_delete_greenpass.py | mattiolato98/reservation-ninja | 1 | 2982 | <filename>reservation_management/migrations/0021_delete_greenpass.py
# Generated by Django 3.2.7 on 2021-10-22 14:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reservation_management', '0020_greenpass'),
]
operations = [
migrations.DeleteM... | <filename>reservation_management/migrations/0021_delete_greenpass.py
# Generated by Django 3.2.7 on 2021-10-22 14:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reservation_management', '0020_greenpass'),
]
operations = [
migrations.DeleteM... | en | 0.879248 | # Generated by Django 3.2.7 on 2021-10-22 14:23 | 1.421052 | 1 |
demos/iaf_pop_demo.py | bionet/ted.python | 4 | 2983 | <reponame>bionet/ted.python
#!/usr/bin/env python
"""
Demos of encoding and decoding algorithms using populations of
IAF neurons.
"""
# Copyright (c) 2009-2015, <NAME>
# All rights reserved.
# Distributed under the terms of the BSD license:
# http://www.opensource.org/licenses/bsd-license
import sys
import numpy as ... | #!/usr/bin/env python
"""
Demos of encoding and decoding algorithms using populations of
IAF neurons.
"""
# Copyright (c) 2009-2015, <NAME>
# All rights reserved.
# Distributed under the terms of the BSD license:
# http://www.opensource.org/licenses/bsd-license
import sys
import numpy as np
# Set matplotlib backend... | en | 0.602145 | #!/usr/bin/env python Demos of encoding and decoding algorithms using populations of IAF neurons. # Copyright (c) 2009-2015, <NAME> # All rights reserved. # Distributed under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license # Set matplotlib backend so that plots can be generated without a ... | 2.487306 | 2 |
regtests/calling/function_expression.py | bpmbank/PythonJS | 319 | 2984 | """func expr"""
F = function( x,y ):
return x+y
def main():
TestError( F(1,2) == 3 )
| """func expr"""
F = function( x,y ):
return x+y
def main():
TestError( F(1,2) == 3 )
| none | 1 | 3.08048 | 3 | |
nadmin/plugins/sortable.py | A425/django-xadmin-1.8 | 1 | 2985 | #coding:utf-8
from nadmin.sites import site
from nadmin.views import BaseAdminPlugin, ListAdminView
SORTBY_VAR = '_sort_by'
class SortablePlugin(BaseAdminPlugin):
sortable_fields = ['sort']
# Media
def get_media(self, media):
if self.sortable_fields and self.request.GET.get(SORTBY_VAR):
... | #coding:utf-8
from nadmin.sites import site
from nadmin.views import BaseAdminPlugin, ListAdminView
SORTBY_VAR = '_sort_by'
class SortablePlugin(BaseAdminPlugin):
sortable_fields = ['sort']
# Media
def get_media(self, media):
if self.sortable_fields and self.request.GET.get(SORTBY_VAR):
... | en | 0.273252 | #coding:utf-8 # Media # Block Views # current_refresh = self.request.GET.get(REFRESH_VAR) # context.update({ # 'has_refresh': bool(current_refresh), # 'clean_refresh_url': self.admin_view.get_query_string(remove=(REFRESH_VAR,)), # 'current_refresh': current_refresh, # 'refresh_times': [{ # 'time... | 1.822569 | 2 |
batch-tmp.py | texastribune/donations | 6 | 2986 | <filename>batch-tmp.py
import logging
from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE
from datetime import datetime, timedelta
from pytz import timezone
import celery
import redis
from charges import amount_to_charge, charge, ChargeException
from npsp import Opportunity
from util import s... | <filename>batch-tmp.py
import logging
from config import ACCOUNTING_MAIL_RECIPIENT, LOG_LEVEL, REDIS_URL, TIMEZONE
from datetime import datetime, timedelta
from pytz import timezone
import celery
import redis
from charges import amount_to_charge, charge, ChargeException
from npsp import Opportunity
from util import s... | en | 0.902113 | This encapulates sending to the console/stdout and email all in one. Add something to the log. Send the assembled log out as an email. Here to show when more than one job of the same type is running. Claim an exclusive lock. Using Redis. # TODO stop sending this email and just rely on Sentry and logs? | 2.320445 | 2 |
rotkehlchen/tests/integration/test_blockchain.py | coblee/rotki | 0 | 2987 | import operator
import os
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.chain.ethereum.manager import NodeName
from rotkehlchen.constants.assets import A_BTC
from rotkehlchen.tests.utils.blockchain import mock_etherscan_query
from rotkehlchen.typing import SupportedBlockchain
@pytes... | import operator
import os
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.chain.ethereum.manager import NodeName
from rotkehlchen.constants.assets import A_BTC
from rotkehlchen.tests.utils.blockchain import mock_etherscan_query
from rotkehlchen.typing import SupportedBlockchain
@pytes... | en | 0.885523 | # pylint: disable=unused-argument TODO for this test. Either: 1. Not use own chain but use a normal open node for this test. 2. If we use own chain, deploy the eth-scan contract there. But probably (1) makes more sense Due to a programming mistake at addition and removal of blockchain accounts after th... | 2.149489 | 2 |
__init__.py | LaptopBiologist/ReferenceAnalyzer | 0 | 2988 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: I am
#
# Created: 02/11/2017
# Copyright: (c) I am 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: I am
#
# Created: 02/11/2017
# Copyright: (c) I am 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... | en | 0.267107 | #------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: I am # # Created: 02/11/2017 # Copyright: (c) I am 2017 # Licence: <your licence> #------------------------------------------------------------------------------- | 1.824697 | 2 |
app/__init__.py | jimmybutton/moviedb | 0 | 2989 | from flask import Flask
from config import Config
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_moment import Moment
from flask_misaka import Misaka
from flask_bootstrap import Bootstrap
import os
import logging
... | from flask import Flask
from config import Config
from sqlalchemy import MetaData
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_moment import Moment
from flask_misaka import Misaka
from flask_bootstrap import Bootstrap
import os
import logging
... | en | 0.575794 | # migrate.init_app(app, db) | 2.284606 | 2 |
optimize.py | AranKomat/Sequential-Alpha-Zero | 7 | 2990 | <gh_stars>1-10
import numpy as np
import random
from time import time, sleep
import h5py
import torch
import torch.nn as nn
import torch.optim as optimizer
import glob
import os
#from scipy.stats import rankdata
from lstm import Model, initialize
from Optim import ScheduledOptim
# import _pickle as cPickle
# np.set... | import numpy as np
import random
from time import time, sleep
import h5py
import torch
import torch.nn as nn
import torch.optim as optimizer
import glob
import os
#from scipy.stats import rankdata
from lstm import Model, initialize
from Optim import ScheduledOptim
# import _pickle as cPickle
# np.set_printoptions(t... | en | 0.569112 | #from scipy.stats import rankdata # import _pickle as cPickle # np.set_printoptions(threshold=np.nan) #optim = optimizer.SGD(model.parameters(), lr=2e-4, momentum=0.9, weight_decay=config.c) #lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, step_size=200, gamma=0.1) # 20M iters # model_ckpt = config.model_path + ... | 1.858287 | 2 |
src/bin_expr.py | Command-Master/MCCC | 6 | 2991 | from c_int import Int
from casting import cast
from globals_consts import NAMESPACE
from temps import used_temps, get_temp, get_temp_func
def binary_expression(copy_strings, expression, target, variables_name, vtypes):
from expression import generate_expression
c1, t1, tt1 = generate_expression(None, expressi... | from c_int import Int
from casting import cast
from globals_consts import NAMESPACE
from temps import used_temps, get_temp, get_temp_func
def binary_expression(copy_strings, expression, target, variables_name, vtypes):
from expression import generate_expression
c1, t1, tt1 = generate_expression(None, expressi... | none | 1 | 2.497706 | 2 | |
tools/mkcodelet.py | bobmittmann/yard-ice | 2 | 2992 | <gh_stars>1-10
#!/usr/bin/python
from struct import *
from getopt import *
import sys
import os
import re
def usage():
global progname
print >> sys.stderr, ""
print >> sys.stderr, " Usage:", progname, "[options] fname"
print >> sys.stderr, ""
print >> sys.stderr, "Options"
print >> sys.stderr, " -h... | #!/usr/bin/python
from struct import *
from getopt import *
import sys
import os
import re
def usage():
global progname
print >> sys.stderr, ""
print >> sys.stderr, " Usage:", progname, "[options] fname"
print >> sys.stderr, ""
print >> sys.stderr, "Options"
print >> sys.stderr, " -h, --help show... | ru | 0.258958 | #!/usr/bin/python | 2.741236 | 3 |
utest/x3270/test_screenshot.py | MichaelSeeburger/Robot-Framework-Mainframe-3270-Library | 3 | 2993 | <reponame>MichaelSeeburger/Robot-Framework-Mainframe-3270-Library<gh_stars>1-10
import os
from pytest_mock import MockerFixture
from robot.api import logger
from Mainframe3270.x3270 import x3270
def test_set_screenshot_folder(under_test: x3270):
path = os.getcwd()
under_test.set_screenshot_folder(path)
... | import os
from pytest_mock import MockerFixture
from robot.api import logger
from Mainframe3270.x3270 import x3270
def test_set_screenshot_folder(under_test: x3270):
path = os.getcwd()
under_test.set_screenshot_folder(path)
assert under_test.imgfolder == os.getcwd()
def test_set_screenshot_folder_no... | none | 1 | 2.335552 | 2 | |
splat/photometry.py | brackham/splat | 0 | 2994 | <filename>splat/photometry.py
# -*- coding: utf-8 -*-
from __future__ import print_function, division
"""
.. note::
These are the spectrophotometry functions for SPLAT
"""
# imports - internal
import copy
import os
# imports - external
import numpy
from astropy import units as u # standard units... | <filename>splat/photometry.py
# -*- coding: utf-8 -*-
from __future__ import print_function, division
"""
.. note::
These are the spectrophotometry functions for SPLAT
"""
# imports - internal
import copy
import os
# imports - external
import numpy
from astropy import units as u # standard units... | en | 0.669233 | # -*- coding: utf-8 -*- .. note:: These are the spectrophotometry functions for SPLAT # imports - internal # imports - external # standard units # physical constants in SI units # for numerical integration # splat functions and constants ##################################################### ############### S... | 2.648684 | 3 |
helpers/time_utils.py | mandalorian-101/badger-system | 0 | 2995 | <reponame>mandalorian-101/badger-system
import datetime
ONE_MINUTE = 60
ONE_HOUR = 3600
ONE_DAY = 24 * ONE_HOUR
ONE_YEAR = 1 * 365 * ONE_DAY
def days(days):
return int(days * 86400.0)
def hours(hours):
return int(hours * 3600.0)
def minutes(minutes):
return int(minutes * 60.0)
def to_utc_date(timesta... | import datetime
ONE_MINUTE = 60
ONE_HOUR = 3600
ONE_DAY = 24 * ONE_HOUR
ONE_YEAR = 1 * 365 * ONE_DAY
def days(days):
return int(days * 86400.0)
def hours(hours):
return int(hours * 3600.0)
def minutes(minutes):
return int(minutes * 60.0)
def to_utc_date(timestamp):
return datetime.datetime.utcfro... | none | 1 | 3.598528 | 4 | |
example_scripts/profile_validation/plot_validation_gridded_data.py | British-Oceanographic-Data-Centre/NEMO-ENTRUST | 0 | 2996 | """
Plot up surface or bottom (or any fixed level) errors from a profile object
with no z_dim (vertical dimension). Provide an array of netcdf files and
mess with the options to get a figure you like.
You can define how many rows and columns the plot will have. This script will
plot the provided list of netcdf datase... | """
Plot up surface or bottom (or any fixed level) errors from a profile object
with no z_dim (vertical dimension). Provide an array of netcdf files and
mess with the options to get a figure you like.
You can define how many rows and columns the plot will have. This script will
plot the provided list of netcdf datase... | en | 0.744127 | Plot up surface or bottom (or any fixed level) errors from a profile object with no z_dim (vertical dimension). Provide an array of netcdf files and mess with the options to get a figure you like. You can define how many rows and columns the plot will have. This script will plot the provided list of netcdf datasets f... | 2.90455 | 3 |
feature-engineering/samples/statistical_features.py | jeury301/text-classifier | 0 | 2997 | from sklearn.feature_extraction.text import TfidfVectorizer
def compute_tf_idf(corpus):
"""Computing term frequency (tf) - inverse document frequency (idf).
:param corpus: List of documents.
:returns: tf-idf of corpus.
"""
return TfidfVectorizer().fit_transform(corpus)
if __name__ == '__main__':
... | from sklearn.feature_extraction.text import TfidfVectorizer
def compute_tf_idf(corpus):
"""Computing term frequency (tf) - inverse document frequency (idf).
:param corpus: List of documents.
:returns: tf-idf of corpus.
"""
return TfidfVectorizer().fit_transform(corpus)
if __name__ == '__main__':
... | en | 0.775258 | Computing term frequency (tf) - inverse document frequency (idf). :param corpus: List of documents. :returns: tf-idf of corpus. | 3.479082 | 3 |
Gds/src/fprime_gds/executables/tcpserver.py | hunterpaulson/fprime | 0 | 2998 | <gh_stars>0
#!/usr/bin/env python3
from __future__ import print_function
import socket
import threading
try:
import socketserver
except ImportError:
import SocketServer as socketserver
import time
import os
import signal
import sys
import struct
import errno
from fprime.constants import DATA_ENCODING
from opt... | #!/usr/bin/env python3
from __future__ import print_function
import socket
import threading
try:
import socketserver
except ImportError:
import SocketServer as socketserver
import time
import os
import signal
import sys
import struct
import errno
from fprime.constants import DATA_ENCODING
from optparse import... | en | 0.819589 | #!/usr/bin/env python3 # Universal server id global Derived from original Stable demo during R&TD and adapted for use in new FSW gse.py applicaiton. TCP socket server for commands, log events, and telemetry data. Later this will handle other things such as sequence files and parameters. Handle is inst... | 2.574358 | 3 |
btb_manager_telegram/__init__.py | haivle/BTB-manager-telegram | 3 | 2999 | import logging
import sched
import time
(
MENU,
EDIT_COIN_LIST,
EDIT_USER_CONFIG,
DELETE_DB,
UPDATE_TG,
UPDATE_BTB,
PANIC_BUTTON,
CUSTOM_SCRIPT,
) = range(8)
BOUGHT, BUYING, SOLD, SELLING = range(4)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"... | import logging
import sched
import time
(
MENU,
EDIT_COIN_LIST,
EDIT_USER_CONFIG,
DELETE_DB,
UPDATE_TG,
UPDATE_BTB,
PANIC_BUTTON,
CUSTOM_SCRIPT,
) = range(8)
BOUGHT, BUYING, SOLD, SELLING = range(4)
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"... | none | 1 | 2.367182 | 2 |