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
ch10/data.py
kxen42/Learn-Python-Programming-Third-Edition
19
6627651
# data.py def get_clean_data(source): data = load_data(source) cleaned_data = clean_data(data) return cleaned_data
# data.py def get_clean_data(source): data = load_data(source) cleaned_data = clean_data(data) return cleaned_data
none
1
1.623202
2
baselines/jft/experiments/common_fewshot.py
dvdzhang/uncertainty-baselines
0
6627652
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # 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 ap...
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # 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 ap...
en
0.832105
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines Authors. # # 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 ap...
1.681057
2
autotest/osr/osr_proj4.py
nyalldawson/gdal
1
6627653
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test some PROJ.4 specific translation issues. # Author: <NAME> <<EMAIL>> # ################################################################...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test some PROJ.4 specific translation issues. # Author: <NAME> <<EMAIL>> # ################################################################...
en
0.289862
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test some PROJ.4 specific translation issues. # Author: <NAME> <<EMAIL>> # ################################################################...
1.558318
2
test/aqua/test_hhl.py
SooluThomas/qiskit-aqua
0
6627654
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
en
0.562061
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any ...
2.120059
2
examples/BigBoy/mediumboy_model.py
attraylor/poke-env
4
6627655
import gym import math import random import numpy as np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple from itertools import count from tqdm import trange from copy import deepcopy import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" # from PIL import Image import torch import torc...
import gym import math import random import numpy as np import matplotlib import matplotlib.pyplot as plt from collections import namedtuple from itertools import count from tqdm import trange from copy import deepcopy import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" # from PIL import Image import torch import torc...
en
0.586502
# from PIL import Image # import torchvision.transforms as T #Grab PCA functions #Batch size is 1: #Batch size is 1: #Embedding dimension sizes #self.layers.append(nn.Linear(self.input_dim,config.hidden_dim)) #for i in range(1, config.num_layers): # self.layers.append(nn.Linear(config.hidden_dim,config.hidden_dim)) #se...
1.848829
2
embedded/uvacbot/ui/button.py
dpm76/Microvacbot
1
6627656
<reponame>dpm76/Microvacbot<filename>embedded/uvacbot/ui/button.py<gh_stars>1-10 ''' Created on 1 may. 2020 @author: David ''' from micropython import schedule from pyb import Pin, Timer from utime import sleep_ms class Button(object): ''' This button can handle short and long press ''' ...
''' Created on 1 may. 2020 @author: David ''' from micropython import schedule from pyb import Pin, Timer from utime import sleep_ms class Button(object): ''' This button can handle short and long press ''' def __init__(self, pin, timerId = 6, thresholdTime = 1000, lowOnPress=False): ...
en
0.658647
Created on 1 may. 2020 @author: David This button can handle short and long press Constructor @param pin: Pin object where the button is @param timerId: (default=6) Timer to determine the long press @param thresholdTime: Waiting time to determine a long press as milliseconds ...
3.011693
3
homeassistant/components/device_tracker/device_trigger.py
SNoof85/core
2
6627657
"""Provides device automations for Device Tracker.""" from __future__ import annotations from typing import Any, Final import voluptuous as vol from homeassistant.components.automation import ( AutomationActionType, AutomationTriggerInfo, ) from homeassistant.components.device_automation import DEVICE_TRIGGE...
"""Provides device automations for Device Tracker.""" from __future__ import annotations from typing import Any, Final import voluptuous as vol from homeassistant.components.automation import ( AutomationActionType, AutomationTriggerInfo, ) from homeassistant.components.device_automation import DEVICE_TRIGGE...
en
0.791259
Provides device automations for Device Tracker. List device triggers for Device Tracker devices. # Get all the integrations entities for this device Attach a trigger. List trigger capabilities.
2.056854
2
wx_app.py
wolfg1969/my-wechat-app
1
6627658
<reponame>wolfg1969/my-wechat-app # coding=utf-8 from flask import Flask from flask.ext.redis import FlaskRedis from redis import StrictRedis from wechat_sdk import WechatConf app = Flask(__name__) app.config.from_envvar('MY_WECHAT_APP_SETTINGS') redis_store = FlaskRedis.from_custom_provider(StrictRedis, app) wechat_...
# coding=utf-8 from flask import Flask from flask.ext.redis import FlaskRedis from redis import StrictRedis from wechat_sdk import WechatConf app = Flask(__name__) app.config.from_envvar('MY_WECHAT_APP_SETTINGS') redis_store = FlaskRedis.from_custom_provider(StrictRedis, app) wechat_conf = WechatConf( token=app.c...
en
0.644078
# coding=utf-8
1.843225
2
pollbot/telegram/keyboard/date_picker.py
3wille/ultimate-poll-bot
0
6627659
<filename>pollbot/telegram/keyboard/date_picker.py """Reply keyboards.""" import calendar from datetime import date from telegram import ( InlineKeyboardButton, ) from pollbot.helper.enums import CallbackType def get_datepicker_buttons(poll): """Get the buttons for the datepicker.""" current_date = poll....
<filename>pollbot/telegram/keyboard/date_picker.py """Reply keyboards.""" import calendar from datetime import date from telegram import ( InlineKeyboardButton, ) from pollbot.helper.enums import CallbackType def get_datepicker_buttons(poll): """Get the buttons for the datepicker.""" current_date = poll....
en
0.75588
Reply keyboards. Get the buttons for the datepicker. # Add headline # Create the week-day column description # Iterate through all days and create respective buttons # Format the text. The currently chosen day should be surrounded by brackets e.g (26) # Only create real buttons for actual days of the month
3.373142
3
musicbatch/transcoder/app.py
sio/musicbatch
0
6627660
''' CLI application for transcoding music files ''' import os import json import platform import time import sys from argparse import ArgumentParser from contextlib import contextmanager from datetime import datetime from functools import partial from pkg_resources import resource_string from subprocess import Popen,...
''' CLI application for transcoding music files ''' import os import json import platform import time import sys from argparse import ArgumentParser from contextlib import contextmanager from datetime import datetime from functools import partial from pkg_resources import resource_string from subprocess import Popen,...
en
0.773996
CLI application for transcoding music files CLI entry point # 1. Load config from YAML # 2. Find relevant music files and add them to queue # 3. Concurrently process each file in the queue: # - Calculate target location # - Transcode # - Fill tags # - Copy lyrics # - Copy cover art # start progress repor...
2.466315
2
timer.py
niclaswue/retimer
0
6627661
#!/usr/local/bin/python3 import argparse import tempfile import subprocess parser = argparse.ArgumentParser(description="Set timer") parser.add_argument( "commands", metavar="N", type=str, nargs="+", help="end dates for timer or intervals", ) parser.add_argument("--name", type=str, help="event name...
#!/usr/local/bin/python3 import argparse import tempfile import subprocess parser = argparse.ArgumentParser(description="Set timer") parser.add_argument( "commands", metavar="N", type=str, nargs="+", help="end dates for timer or intervals", ) parser.add_argument("--name", type=str, help="event name...
en
0.732912
#!/usr/local/bin/python3 Return minutes from interval string Args: time_interval (str): time interval string Returns: int: minutes in interval # append stop char tell application "Reminders" # Calculate date time for midnight today set currentDay to (current date) - (time of (current ...
3.275675
3
serve.py
Hindol/python-gcm-server
1
6627662
__author__ = 'hadhya' from gcm import GcmClient from config import CONFIG from optparse import OptionParser import logging def start_xmpp_server(): client = GcmClient(CONFIG['GCM_API_KEY']) client.listen(CONFIG['GCM_SENDER_ID'], on_message) def on_message(message): print message if __name__ == '__main__...
__author__ = 'hadhya' from gcm import GcmClient from config import CONFIG from optparse import OptionParser import logging def start_xmpp_server(): client = GcmClient(CONFIG['GCM_API_KEY']) client.listen(CONFIG['GCM_SENDER_ID'], on_message) def on_message(message): print message if __name__ == '__main__...
en
0.664972
# Setup the command line arguments. # Output verbosity options. # Setup logging.
2.249662
2
scripts/2.1.split data into train and validation.py
nmningmei/BOLD5000_autoencoder
9
6627663
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 26 13:25:01 2019 @author: nmei """ import os import numpy as np from glob import glob from tqdm import tqdm from shutil import copyfile from sklearn.model_selection import train_test_split data_dir = '../../BOLD5000_data_store/data/volume_of_inter...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 26 13:25:01 2019 @author: nmei """ import os import numpy as np from glob import glob from tqdm import tqdm from shutil import copyfile from sklearn.model_selection import train_test_split data_dir = '../../BOLD5000_data_store/data/volume_of_inter...
en
0.434291
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Mon Aug 26 13:25:01 2019 @author: nmei
2.226265
2
src/train_interface.py
sunprinceS/MetaASR-CrossAccent
9
6627664
<reponame>sunprinceS/MetaASR-CrossAccent import pickle import time from shutil import rmtree from pathlib import Path from tqdm import tqdm from src.marcos import * from src.io.dataset import get_loader from src.monitor.metric import Metric import src.monitor.logger as logger from torchexp.stat import RunningAvgDict ...
import pickle import time from shutil import rmtree from pathlib import Path from tqdm import tqdm from src.marcos import * from src.io.dataset import get_loader from src.monitor.metric import Metric import src.monitor.logger as logger from torchexp.stat import RunningAvgDict class TrainInterface: def __init__...
de
0.529322
### config setting ####################################################################### ### Set path ######################################################################## ### Resume mechanism # time.sleep(10) #TODO: combine the following with Metric # bucket_reverse=True, # shuffle=False, #debug # transformer
1.9192
2
benchmarks/streamable.py
ftruzzi/chia-blockchain
1
6627665
<gh_stars>1-10 from dataclasses import dataclass from enum import Enum from statistics import stdev from time import process_time as clock from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import click from utils import EnumType, rand_bytes, rand_full_block, rand_hash from chia.types.blockcha...
from dataclasses import dataclass from enum import Enum from statistics import stdev from time import process_time as clock from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union import click from utils import EnumType, rand_bytes, rand_full_block, rand_hash from chia.types.blockchain_format.sized...
en
0.800402
# The strings in this Enum are by purpose. See benchmark.utils.EnumType. # The strings in this Enum are by purpose. See benchmark.utils.EnumType. # pylint: disable = no-value-for-parameter
2.272369
2
cs15211/DistinctSubsequencesII.py
JulyKikuAkita/PythonPrac
1
6627666
__source__ = 'https://leetcode.com/problems/distinct-subsequences-ii/' # Time: O() # Space: O() # # Description: Leetcode # 940. Distinct Subsequences II # # Given a string S, count the number of distinct, non-empty subsequences of S . # # Since the result may be large, return the answer modulo 10^9 + 7. # # Example 1...
__source__ = 'https://leetcode.com/problems/distinct-subsequences-ii/' # Time: O() # Space: O() # # Description: Leetcode # 940. Distinct Subsequences II # # Given a string S, count the number of distinct, non-empty subsequences of S . # # Since the result may be large, return the answer modulo 10^9 + 7. # # Example 1...
en
0.64429
# Time: O() # Space: O() # # Description: Leetcode # 940. Distinct Subsequences II # # Given a string S, count the number of distinct, non-empty subsequences of S . # # Since the result may be large, return the answer modulo 10^9 + 7. # # Example 1: # # Input: "abc" # Output: 7 # Explanation: The 7 distinct subsequenc...
3.573824
4
pytorch_optimizer/ralamb.py
gheyret/pytorch_optimizer
20
6627667
import math import torch from torch.optim import Optimizer from pytorch_optimizer.base_optimizer import BaseOptimizer from pytorch_optimizer.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS class RaLamb(Optimizer, BaseOptimizer): """ Reference : https://gist.github.com/redknightlois/c4023d393eb8f92bb...
import math import torch from torch.optim import Optimizer from pytorch_optimizer.base_optimizer import BaseOptimizer from pytorch_optimizer.types import BETAS, CLOSURE, DEFAULTS, LOSS, PARAMETERS class RaLamb(Optimizer, BaseOptimizer): """ Reference : https://gist.github.com/redknightlois/c4023d393eb8f92bb...
en
0.623785
Reference : https://gist.github.com/redknightlois/c4023d393eb8f92bb44b2ab582d7ec20 Example : from pytorch_optimizer import RaLamb ... model = YourModel() optimizer = RaLamb(model.parameters()) ... for input, output in data: optimizer.zero_grad() lo...
3.1071
3
klever/core/vtg/emg/generators/__init__.py
lutovna/klever
1
6627668
# # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 # # h...
# # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 # # h...
en
0.809391
# # Copyright (c) 2019 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 # # h...
2.017265
2
pkg/releasing/git.bzl
velentr/rules_pkg
0
6627669
# Copyright 2021 The Bazel 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 applicable la...
# Copyright 2021 The Bazel 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 applicable la...
en
0.840864
# Copyright 2021 The Bazel 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 applicable la...
1.820385
2
oi/algs/Graph/tree-gen.py
Riteme/test
3
6627670
<filename>oi/algs/Graph/tree-gen.py #!/usr/bin/env pypy import sys from random import * assert len(sys.argv) > 1 N = int(sys.argv[1]) S = [i for i in range(1, N + 1)] shuffle(S) print(N) for i in range(1, N): father = choice(S[:i]) print("{} {}".format(father, S[i]))
<filename>oi/algs/Graph/tree-gen.py #!/usr/bin/env pypy import sys from random import * assert len(sys.argv) > 1 N = int(sys.argv[1]) S = [i for i in range(1, N + 1)] shuffle(S) print(N) for i in range(1, N): father = choice(S[:i]) print("{} {}".format(father, S[i]))
ru
0.30987
#!/usr/bin/env pypy
2.941744
3
config.py
appKom/watchdog
0
6627671
<filename>config.py # Her er de forskjellige konfigureringsmulighetene som finnes i scriptet. # Endrer du disse her, så endres de alle steder. # ICS plassering icsLocation = 'https://calendar.google.com/calendar/ical/b72fgdhuv6g5mpoqa0bdvj095k%40group.calendar.google.com/public/basic.ics' # Mail variables frommail = ...
<filename>config.py # Her er de forskjellige konfigureringsmulighetene som finnes i scriptet. # Endrer du disse her, så endres de alle steder. # ICS plassering icsLocation = 'https://calendar.google.com/calendar/ical/b72fgdhuv6g5mpoqa0bdvj095k%40group.calendar.google.com/public/basic.ics' # Mail variables frommail = ...
no
0.544923
# Her er de forskjellige konfigureringsmulighetene som finnes i scriptet. # Endrer du disse her, så endres de alle steder. # ICS plassering # Mail variables # report mode. 'daily' for a daily report and 'weekly' for a weekly report
1.63076
2
python_packaging/src/test/conftest.py
jlmaccal/gromacs
3
6627672
# # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2019,2020,2021, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS is ...
# # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2019,2020,2021, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS is ...
en
0.816433
# # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2019,2020,2021, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS is ...
1.57343
2
src/ecco/lm.py
intellicommtech/ecco
0
6627673
from collections import defaultdict import inspect import json import os import random import torch import transformers from transformers import BatchEncoding import ecco import numpy as np from IPython import display as d from torch.nn import functional as F from ecco.attribution import compute_primary_attributions_s...
from collections import defaultdict import inspect import json import os import random import torch import transformers from transformers import BatchEncoding import ecco import numpy as np from IPython import display as d from torch.nn import functional as F from ecco.attribution import compute_primary_attributions_s...
en
0.737584
Ecco's central class. A wrapper around language models. We use it to run the language models and collect important data like input saliency and neuron activations. A LM object is typically not created directly by users, it is returned by `ecco.from_pretrained()`. Usage: ```python import ecco ...
2.451873
2
numpymate/packages/convert2/util.py
MacHu-GWU/numpymate-project
1
6627674
#!/usr/bin/env python # -*- coding: utf-8 -*- def extract_number_from_string(text): """Take number like string out of text. """ numberstr_list = list() chunks = list() for char in text: if char.isdigit() or char == ".": chunks.append(char) else: if len(c...
#!/usr/bin/env python # -*- coding: utf-8 -*- def extract_number_from_string(text): """Take number like string out of text. """ numberstr_list = list() chunks = list() for char in text: if char.isdigit() or char == ".": chunks.append(char) else: if len(c...
en
0.401762
#!/usr/bin/env python # -*- coding: utf-8 -*- Take number like string out of text.
4.128644
4
python/project/src/causal_system.py
DTUComputeCognitiveSystems/IntroductionToCausalInference
5
6627675
from ast import literal_eval import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt from networkx.drawing.nx_pydot import graphviz_layout class CausalSystem: _project_password = None def _sample(self, n_samples): raise NotImplementedError ##################...
from ast import literal_eval import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt from networkx.drawing.nx_pydot import graphviz_layout class CausalSystem: _project_password = None def _sample(self, n_samples): raise NotImplementedError ##################...
en
0.474828
########################################################################################## # Internal # noinspection PyTypeChecker # type: dict # type: dict # type: int # Ordering # type: list # For graph # Always ensure a single sample # Set # Compute # Set node-nr # Filter keys # Make table # Reset # Return # Remembe...
2.31946
2
mysite/album/views.py
rysnee/DoAn
0
6627676
from django.shortcuts import render, redirect from django.contrib import messages from .models import Photo, ResultPhoto from .forms import PhotoForm from .VLADlib.VLAD import * from .VLADlib.Descriptors import * import itertools import argparse import glob import cv2 def retrieval_k(img, k): descriptorName = "O...
from django.shortcuts import render, redirect from django.contrib import messages from .models import Photo, ResultPhoto from .forms import PhotoForm from .VLADlib.VLAD import * from .VLADlib.Descriptors import * import itertools import argparse import glob import cv2 def retrieval_k(img, k): descriptorName = "O...
en
0.358408
#load the index #load the visual dictionary # computing descriptors #ind = list(itertools.chain.from_iterable(ind)) # loop over the results # load the result image and display it #Query the image
2.24057
2
salt/modules/win_timezone.py
johnskopis/salt
5
6627677
<reponame>johnskopis/salt<gh_stars>1-10 # -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExec...
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try:...
en
0.530024
# -*- coding: utf-8 -*- Module for managing timezone on Windows systems. # Import Python libs # Import Salt libs # Import 3rd party libs # Define the module's virtual name Only load on windows Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecu...
2.571921
3
mmaction/core/evaluation/recall.py
why-know/YF-OpenLib-mmaction2
9
6627678
<reponame>why-know/YF-OpenLib-mmaction2 import numpy as np import torch from mmaction.utils import import_module_error_func try: from mmdet.core import bbox_overlaps except (ImportError, ModuleNotFoundError): @import_module_error_func('mmdet') def bbox_overlaps(*args, **kwargs): pass def _recal...
import numpy as np import torch from mmaction.utils import import_module_error_func try: from mmdet.core import bbox_overlaps except (ImportError, ModuleNotFoundError): @import_module_error_func('mmdet') def bbox_overlaps(*args, **kwargs): pass def _recalls(all_ious, proposal_nums, thrs): ...
en
0.587847
Check proposal_nums and iou_thrs and set correct format. Calculate recalls. Args: gts(list or ndarray): a list of arrays of shape (n, 4) proposals(list or ndarray): a list of arrays of shape (k, 4) or (k, 5) proposal_nums(int or list of int or ndarray): top N proposals thrs(float or...
1.833391
2
tests/gclient_test.py
newtalk/depot_tools
0
6627679
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for gclient.py. See gclient_smoketest.py for integration tests. """ import Queue import copy import logging import ...
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for gclient.py. See gclient_smoketest.py for integration tests. """ import Queue import copy import logging import ...
en
0.865705
#!/usr/bin/env python # Copyright (c) 2012 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. Unit tests for gclient.py. See gclient_smoketest.py for integration tests. Writes the content of a file and create the directories ...
2.242146
2
tests/test_bktree.py
agarwalutkarsh554/imagededup
4,100
6627680
<gh_stars>1000+ from collections import OrderedDict from imagededup.methods.hashing import Hashing from imagededup.handlers.search.bktree import BKTree, BkTreeNode # Test BkTreeNode def initialize_for_bktree(): hash_dict = OrderedDict( {'a': '9', 'b': 'D', 'c': 'A', 'd': 'F', 'e': '2', 'f': '6', 'g': '7...
from collections import OrderedDict from imagededup.methods.hashing import Hashing from imagededup.handlers.search.bktree import BKTree, BkTreeNode # Test BkTreeNode def initialize_for_bktree(): hash_dict = OrderedDict( {'a': '9', 'b': 'D', 'c': 'A', 'd': 'F', 'e': '2', 'f': '6', 'g': '7', 'h': 'E'} ...
en
0.932692
# Test BkTreeNode # test BKTree class # initialize root node and add 1 new node, check it goes as root's child and has it's parent as root # initialize root node, add 1 new node and enter another node with same distance from root, check it goes not as # root's child but the other node's child # to guarantee that 'a' is...
3.255184
3
src/bandersnatch_storage_plugins/filesystem.py
turinggirl/bandersnatch
0
6627681
<filename>src/bandersnatch_storage_plugins/filesystem.py import contextlib import filecmp import hashlib import logging import os import pathlib import shutil import tempfile from typing import IO, Any, Dict, Generator, List, Optional, Type, Union import filelock from bandersnatch.storage import PATH_TYPES, StoragePl...
<filename>src/bandersnatch_storage_plugins/filesystem.py import contextlib import filecmp import hashlib import logging import os import pathlib import shutil import tempfile from typing import IO, Any, Dict, Generator, List, Optional, Type, Union import filelock from bandersnatch.storage import PATH_TYPES, StoragePl...
en
0.857198
Retrieve the appropriate `FileLock` backend for this storage plugin :param str path: The path to use for locking :return: A `FileLock` backend for obtaining locks :rtype: SwiftFileLock A test helper simulating 'find'. Iterates over directories and filenames, given as relative paths to ...
2.392945
2
Problemset/qing-wa-tiao-tai-jie-wen-ti-lcof/qing-wa-tiao-tai-jie-wen-ti-lcof.py
worldwonderer/algorithm
1
6627682
# @Title: 青蛙跳台阶问题 (青蛙跳台阶问题 LCOF) # @Author: 18015528893 # @Date: 2020-09-28 21:53:14 # @Runtime: 36 ms # @Memory: 13.1 MB class Solution: def numWays(self, n: int) -> int: a, b = 1, 1 for _ in range(n): a, b = b, a+b return a % 1000000007
# @Title: 青蛙跳台阶问题 (青蛙跳台阶问题 LCOF) # @Author: 18015528893 # @Date: 2020-09-28 21:53:14 # @Runtime: 36 ms # @Memory: 13.1 MB class Solution: def numWays(self, n: int) -> int: a, b = 1, 1 for _ in range(n): a, b = b, a+b return a % 1000000007
en
0.19918
# @Title: 青蛙跳台阶问题 (青蛙跳台阶问题 LCOF) # @Author: 18015528893 # @Date: 2020-09-28 21:53:14 # @Runtime: 36 ms # @Memory: 13.1 MB
2.908117
3
tests/test_minifier.py
chinghwayu/mimesis
2,619
6627683
<filename>tests/test_minifier.py<gh_stars>1000+ import pytest from minifier import Minimizer, human_repr def test_human_repr(): assert human_repr(0) == "0.0B" assert human_repr(1) == "1.0B" assert human_repr(100.1) == "100.1B" assert human_repr(1024) == "1.0KB" assert human_repr(1024 * 100.1) == "...
<filename>tests/test_minifier.py<gh_stars>1000+ import pytest from minifier import Minimizer, human_repr def test_human_repr(): assert human_repr(0) == "0.0B" assert human_repr(1) == "1.0B" assert human_repr(100.1) == "100.1B" assert human_repr(1024) == "1.0KB" assert human_repr(1024 * 100.1) == "...
none
1
2.277275
2
ML/datasets/reviewsData/linecounter.py
JamesG3/Review-Based_Amazon_SearchEngine
0
6627684
<gh_stars>0 file = open("item_dedup.json",'r') counter = 0 for line in file: print line if counter == 100: break counter += 1 if counter%1000000 == 0: print counter/1000000 print counter file.close()
file = open("item_dedup.json",'r') counter = 0 for line in file: print line if counter == 100: break counter += 1 if counter%1000000 == 0: print counter/1000000 print counter file.close()
none
1
2.706863
3
main-node/model/model_abs.py
Valavanca/benchmark
0
6627685
from abc import ABC, abstractmethod class Model(ABC): @abstractmethod def build_model(self): pass @abstractmethod def validate_model(self): pass @abstractmethod def predict_solution(self): pass @abstractmethod def validate_solution(self): pass @abstractmethod def get_result(...
from abc import ABC, abstractmethod class Model(ABC): @abstractmethod def build_model(self): pass @abstractmethod def validate_model(self): pass @abstractmethod def predict_solution(self): pass @abstractmethod def validate_solution(self): pass @abstractmethod def get_result(...
none
1
2.998837
3
automateYT/__init__.py
umutambyi-gad/automateYT
2
6627686
""" automateYT is lightweight library for automating to download youtube videos, subtitles (if available) and playlist. """ __title__ = "automateYT" __author__ = "<NAME>" __copyright__ = "Copyright 2021 by <NAME>" __license__ = 'MIT' __version__ = '1.0.0' __all__ = ['Timing', 'Automate'] from automateYT.__main__ imp...
""" automateYT is lightweight library for automating to download youtube videos, subtitles (if available) and playlist. """ __title__ = "automateYT" __author__ = "<NAME>" __copyright__ = "Copyright 2021 by <NAME>" __license__ = 'MIT' __version__ = '1.0.0' __all__ = ['Timing', 'Automate'] from automateYT.__main__ imp...
en
0.725917
automateYT is lightweight library for automating to download youtube videos, subtitles (if available) and playlist.
1.200423
1
problem0176.py
kmarcini/Project-Euler-Python
0
6627687
<gh_stars>0 ########################### # # #176 Right-angled triangles that share a cathetus - Project Euler # https://projecteuler.net/problem=176 # # Code by <NAME> # ###########################
########################### # # #176 Right-angled triangles that share a cathetus - Project Euler # https://projecteuler.net/problem=176 # # Code by <NAME> # ###########################
de
0.287971
########################### # # #176 Right-angled triangles that share a cathetus - Project Euler # https://projecteuler.net/problem=176 # # Code by <NAME> # ###########################
1.591863
2
Assets/ScriptsExternos/flana_math.py
AlberLC/rocket-training
0
6627688
import math class Vector2: def __init__(self, x, y): self.x = x self.y = y def __mul__(self, other) -> (float, 'Vector2'): if other is None: other = Vector2(1, 0) if type(other) is Vector2: return self.x * other.x + self.y * other.y else: ...
import math class Vector2: def __init__(self, x, y): self.x = x self.y = y def __mul__(self, other) -> (float, 'Vector2'): if other is None: other = Vector2(1, 0) if type(other) is Vector2: return self.x * other.x + self.y * other.y else: ...
none
1
3.626343
4
core/libs/view_helpers/__init__.py
near-feign/pcapdb
244
6627689
def format_errors(errors): """Format serializer errors to conform to our messaging format. (ie, sending a list of messages or a single message under 'success', 'info', 'warning', or 'failure'). :param errors: An error dictionary as produced by rest_framework serializers. :returns: A list of messages."""...
def format_errors(errors): """Format serializer errors to conform to our messaging format. (ie, sending a list of messages or a single message under 'success', 'info', 'warning', or 'failure'). :param errors: An error dictionary as produced by rest_framework serializers. :returns: A list of messages."""...
en
0.55546
Format serializer errors to conform to our messaging format. (ie, sending a list of messages or a single message under 'success', 'info', 'warning', or 'failure'). :param errors: An error dictionary as produced by rest_framework serializers. :returns: A list of messages.
3.079606
3
python/GlobalMemoryInterface.py
KastnerRG/tinker
7
6627690
<filename>python/GlobalMemoryInterface.py # ---------------------------------------------------------------------- # Copyright (c) 2016, The Regents of the University of California All # rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that t...
<filename>python/GlobalMemoryInterface.py # ---------------------------------------------------------------------- # Copyright (c) 2016, The Regents of the University of California All # rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that t...
en
0.684863
# ---------------------------------------------------------------------- # Copyright (c) 2016, The Regents of the University of California 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.331892
1
cottonformation/res/elasticloadbalancing.py
MacHu-GWU/cottonformation-project
5
6627691
<filename>cottonformation/res/elasticloadbalancing.py # -*- coding: utf-8 -*- """ This module """ import attr import typing from ..core.model import ( Property, Resource, Tag, GetAtt, TypeHint, TypeCheck, ) from ..core.constant import AttrMeta #--- Property declaration --- @attr.s class PropLoadBalancerAccessL...
<filename>cottonformation/res/elasticloadbalancing.py # -*- coding: utf-8 -*- """ This module """ import attr import typing from ..core.model import ( Property, Resource, Tag, GetAtt, TypeHint, TypeCheck, ) from ..core.constant import AttrMeta #--- Property declaration --- @attr.s class PropLoadBalancerAccessL...
en
0.611198
# -*- coding: utf-8 -*- This module #--- Property declaration --- AWS Object Type = "AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy" Resource Document: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html Property Document: - ``rp_...
1.934069
2
agagd/agagd_core/models.py
leeschumacher/agagd
0
6627692
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to ...
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to ...
en
0.942578
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to ...
2.279807
2
knack/output.py
srinivas32/knack
0
6627693
<gh_stars>0 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
en
0.675009
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1.986711
2
setup.py
jeffreylovitz/RLTest
0
6627694
<filename>setup.py from setuptools import setup, find_packages setup( name='RLTest', version='0.2.1', description="Redis Labs Test Framework, allow to run tests on redis and modules on a variety of environments.", packages=find_packages(), install_requires=[ 'redis>=3.0.0', 'redis-p...
<filename>setup.py from setuptools import setup, find_packages setup( name='RLTest', version='0.2.1', description="Redis Labs Test Framework, allow to run tests on redis and modules on a variety of environments.", packages=find_packages(), install_requires=[ 'redis>=3.0.0', 'redis-p...
en
0.238164
[console_scripts] RLTest=RLTest.__main__:main
1.320928
1
old_ARS_2018/tests/odometry_test.py
Brechard/Robot-Simulator
0
6627695
import unittest import math from bot import odometry as od __author__ = '<NAME>' class TestOdometry(unittest.TestCase): def test_normal_dist(self): tmp = od.prob_normal_dist(0, 1) self.assertEqual(round(tmp, 10), 0.3989422804) tmp = od.prob_normal_dist(1, 1) self.assertEqual(roun...
import unittest import math from bot import odometry as od __author__ = '<NAME>' class TestOdometry(unittest.TestCase): def test_normal_dist(self): tmp = od.prob_normal_dist(0, 1) self.assertEqual(round(tmp, 10), 0.3989422804) tmp = od.prob_normal_dist(1, 1) self.assertEqual(roun...
en
0.778583
# set noise parameters # current position # position after move # measured positions before and after move (from encoder data) # get probability # set another prob func # get probability # set noise parameters # current position # measured positions before and after move (from encoder data) # get position # set another...
2.87761
3
test/functional/tachacoin_pos.py
tachacoin/tachacoin
0
6627696
<filename>test/functional/tachacoin_pos.py #!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework...
<filename>test/functional/tachacoin_pos.py #!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework...
en
0.907918
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. Add a P2P connection to the node. Helper to connect and wait for version handshake. # We need to ...
2.068384
2
stayclean-2019-august/display.py
foobarbazblarg/stayclean
1
6627697
<reponame>foobarbazblarg/stayclean #!/usr/bin/python # TODO: issues with new oauth2 stuff. Keep using older version of Python for now. # #!/usr/bin/env python from participantCollection import ParticipantCollection import re import datetime import pyperclip # Edit Me! currentMonthTotalDays = 31 currentMonthIndex = d...
#!/usr/bin/python # TODO: issues with new oauth2 stuff. Keep using older version of Python for now. # #!/usr/bin/env python from participantCollection import ParticipantCollection import re import datetime import pyperclip # Edit Me! currentMonthTotalDays = 31 currentMonthIndex = datetime.date.today().month currentM...
en
0.698422
#!/usr/bin/python # TODO: issues with new oauth2 stuff. Keep using older version of Python for now. # #!/usr/bin/env python # Edit Me! # TODO: testing... # currentDayOfMonthIndex = 31 # print "There are currently **" + str(numberStillIn) + " out of " + str(initialNumber) +"** original participants. That's **" + str(i...
2.486807
2
apps/classifier_grid/canvas.py
neuralbotnetworks/ncappzoo
968
6627698
<gh_stars>100-1000 import numpy as numpy import cv2 class Canvas: #IMAGES_ACROSS = 32 #IMAGES_DOWN = 12 BOTTOM_INFO_BAR_HEIGHT_MIN = 20 TOP_INFO_BAR_HEIGHT_MIN = 150 FPS_TEXT_ROW = 2 TIMER_TEXT_ROW = 1 INFERENCE_LABEL_TEXT_ROW = 1 PAUSE_TEXT_ROW = 1 LOADING_TEXT_ROW = 1 DONE_C...
import numpy as numpy import cv2 class Canvas: #IMAGES_ACROSS = 32 #IMAGES_DOWN = 12 BOTTOM_INFO_BAR_HEIGHT_MIN = 20 TOP_INFO_BAR_HEIGHT_MIN = 150 FPS_TEXT_ROW = 2 TIMER_TEXT_ROW = 1 INFERENCE_LABEL_TEXT_ROW = 1 PAUSE_TEXT_ROW = 1 LOADING_TEXT_ROW = 1 DONE_COUNT_TEXT_ROW = 2 ...
en
0.707245
#IMAGES_ACROSS = 32 #IMAGES_DOWN = 12 # white text #total canvas dimensions # for now no use for bottom bar # top info bar # bottom info bar #grid dimensions #clear whole canvas to start # add some padding for the text that goes on top bar so not right against the edge of window #clear whole canvas to start #image_left...
2.948647
3
tests/models/test_simple.py
project-lolquiz/the-backend
0
6627699
<reponame>project-lolquiz/the-backend<filename>tests/models/test_simple.py from unittest import mock from models.simple import Simple @mock.patch('models.simple.db.session') @mock.patch('models.simple.Simple') def test_add_new(mock_db, mock_connection): new_simple = Simple('a simple object') from_db = new_s...
from unittest import mock from models.simple import Simple @mock.patch('models.simple.db.session') @mock.patch('models.simple.Simple') def test_add_new(mock_db, mock_connection): new_simple = Simple('a simple object') from_db = new_simple from_db.id = 1 mock_db.add_new.return_value = from_db mo...
none
1
2.908357
3
EMDetector/test/data.py
jabae/detectEM
1
6627700
from __future__ import print_function import imp import numpy as np import math import torch import torch.utils.data from torch.utils.data import DataLoader import torch.nn.functional as F import torch.nn as nn from time import time downsample = nn.AvgPool2d(kernel_size=(2,2), stride=(2,2), padding=0)...
from __future__ import print_function import imp import numpy as np import math import torch import torch.utils.data from torch.utils.data import DataLoader import torch.nn.functional as F import torch.nn as nn from time import time downsample = nn.AvgPool2d(kernel_size=(2,2), stride=(2,2), padding=0)...
en
0.928176
# Each worker already has its own random state (Torch). # print("worker ID = {}, seed = {}".format(worker_id, seed)) # Attributes
2.588078
3
appdaemon/plugins/mqtt/mqttplugin.py
Rootie/appdaemon
443
6627701
<filename>appdaemon/plugins/mqtt/mqttplugin.py<gh_stars>100-1000 import copy import paho.mqtt.client as mqtt import asyncio import traceback import ssl import appdaemon.utils as utils from appdaemon.appdaemon import AppDaemon from appdaemon.plugin_management import PluginBase class MqttPlugin(PluginBase): def __...
<filename>appdaemon/plugins/mqtt/mqttplugin.py<gh_stars>100-1000 import copy import paho.mqtt.client as mqtt import asyncio import traceback import ssl import appdaemon.utils as utils from appdaemon.appdaemon import AppDaemon from appdaemon.plugin_management import PluginBase class MqttPlugin(PluginBase): def __...
en
0.921219
Initialize MQTT Plugin. # get AD loop # disconnect cleanly # # Placeholder for constraints # # means connection was successful # # Register MQTT Services # # means there was an error # continue processing # unexpected disconnection # now check if the topic belongs to any of the wildcards # the binary data is not requir...
2.067963
2
rest-server.py
betacode-projects/my-escpos-webapi
1
6627702
import sys, os import traceback import datetime import base64 import io from PIL import Image from flask import Flask, make_response, request from flask_cors import CORS, cross_origin import json import escpos_ex api = Flask(__name__) CORS(api) cmd_list = ['print'] res_json = { 'status' : 'success', 'msg-...
import sys, os import traceback import datetime import base64 import io from PIL import Image from flask import Flask, make_response, request from flask_cors import CORS, cross_origin import json import escpos_ex api = Flask(__name__) CORS(api) cmd_list = ['print'] res_json = { 'status' : 'success', 'msg-...
ja
0.99617
#print(req_json) # 必須情報確認 # ヘッダ生成 # 画像ある場合
2.300101
2
server.py
z-------------/newsstand
1
6627703
<gh_stars>1-10 import sys from http.server import CGIHTTPRequestHandler, HTTPServer port = 8000 if len(sys.argv) > 1: port = int(sys.argv[1]) handler = CGIHTTPRequestHandler handler.cgi_directories = ["/py"] server = HTTPServer(("", port), handler) print("Server running on port " + str(port)) server.serve_fore...
import sys from http.server import CGIHTTPRequestHandler, HTTPServer port = 8000 if len(sys.argv) > 1: port = int(sys.argv[1]) handler = CGIHTTPRequestHandler handler.cgi_directories = ["/py"] server = HTTPServer(("", port), handler) print("Server running on port " + str(port)) server.serve_forever()
none
1
2.985031
3
datasets_tools/trans_mapillary_vistas_to_cityscapes.py
vghost2008/wml
6
6627704
import sys from iotoolkit.mapillary_vistas_toolkit import * from multiprocess import Pool import img_utils as wmli import object_detection_tools.visualization as odv import matplotlib.pyplot as plt import numpy as np import object_detection2.mask as odm import wml_utils as wmlu import copy import json import cv2 lid ...
import sys from iotoolkit.mapillary_vistas_toolkit import * from multiprocess import Pool import img_utils as wmli import object_detection_tools.visualization as odv import matplotlib.pyplot as plt import numpy as np import object_detection2.mask as odm import wml_utils as wmlu import copy import json import cv2 lid ...
en
0.121462
#sub_dir_name="training", #list(map(fun,r_idxs))
1.848155
2
merendeira/supplies/admin.py
diogobaeder/merendeira
0
6627705
from django.contrib import admin from merendeira.supplies.models import Category, Product admin.site.register(Category) admin.site.register(Product)
from django.contrib import admin from merendeira.supplies.models import Category, Product admin.site.register(Category) admin.site.register(Product)
none
1
1.271919
1
linkedlist/Reference_code/q12.py
pengfei-chen/algorithm_qa
79
6627706
<gh_stars>10-100 """ 问题描述:给定一个单链表的头结点head,实现一个调整单链表的函数,使得每K个节点之间逆序, 如果最后不够k个节点一组,则不调整最后几个节点。 例如:k = 3时 链表:1->2->3->4->5->6->7->8->None 调整后:3->2->1->6->5->4->7->8->None,7、8不调整,因为不够一组 思路: 1)使用辅助栈或者队列来做n*k个节点的倒置 2)直接使用有限(四个)变量来解决该问题,left表示每k个节点的前一个,start表示每k个节点 的第一个,end表示每k个节点的最后一个,right表示每k个节点的最后一个的下一个。在翻转之前, 有关系:left.n...
""" 问题描述:给定一个单链表的头结点head,实现一个调整单链表的函数,使得每K个节点之间逆序, 如果最后不够k个节点一组,则不调整最后几个节点。 例如:k = 3时 链表:1->2->3->4->5->6->7->8->None 调整后:3->2->1->6->5->4->7->8->None,7、8不调整,因为不够一组 思路: 1)使用辅助栈或者队列来做n*k个节点的倒置 2)直接使用有限(四个)变量来解决该问题,left表示每k个节点的前一个,start表示每k个节点 的第一个,end表示每k个节点的最后一个,right表示每k个节点的最后一个的下一个。在翻转之前, 有关系:left.next = start end....
zh
0.971854
问题描述:给定一个单链表的头结点head,实现一个调整单链表的函数,使得每K个节点之间逆序, 如果最后不够k个节点一组,则不调整最后几个节点。 例如:k = 3时 链表:1->2->3->4->5->6->7->8->None 调整后:3->2->1->6->5->4->7->8->None,7、8不调整,因为不够一组 思路: 1)使用辅助栈或者队列来做n*k个节点的倒置 2)直接使用有限(四个)变量来解决该问题,left表示每k个节点的前一个,start表示每k个节点 的第一个,end表示每k个节点的最后一个,right表示每k个节点的最后一个的下一个。在翻转之前, 有关系:left.next = start end.next...
3.945144
4
main.py
zetof/boing
0
6627707
from interface.lpd8 import LPD8 from interface.theater import Theater from interface.stage import Stage from helpers.instrument import Instrument from helpers.scale import Scale THEATER_WIDTH = 400 # Width of main window in pixels THEATER_HEIGHT = 400 # Height of main window in pixels STAGE_SIZE = 8 # ...
from interface.lpd8 import LPD8 from interface.theater import Theater from interface.stage import Stage from helpers.instrument import Instrument from helpers.scale import Scale THEATER_WIDTH = 400 # Width of main window in pixels THEATER_HEIGHT = 400 # Height of main window in pixels STAGE_SIZE = 8 # ...
en
0.887202
# Width of main window in pixels # Height of main window in pixels # Number of cells in a border of a square stage # Tempo in BPM # IP address where to send OSC messages # Port where to send OSC messages # Starts a LPD8 as MIDI device # Prepare the main window, also called the theater # Prepare the stage # Build two in...
2.685276
3
model/attention.py
thepowerfuldeez/VAENAR-TTS
0
6627708
import torch import torch.nn as nn from torch.nn import functional as F import math from .utils import LinearNorm, FFN from utils.tools import get_mask_from_lengths # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class BaseAttention(nn.Module): def __init__(self, attention_dim): ...
import torch import torch.nn as nn from torch.nn import functional as F import math from .utils import LinearNorm, FFN from utils.tools import get_mask_from_lengths # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class BaseAttention(nn.Module): def __init__(self, attention_dim): ...
en
0.525237
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu") :param inputs: query, [batch, q_time, q_dim] :param memory: [batch, m_time, m_dim] :param memory_lengths: [batch,] :param query_lengths: [batch,] :return: (tensor1, tensor2) tensor1: contexts, [batch, q_t...
2.097205
2
isofit/geometry.py
cfranken/isofit
0
6627709
#! /usr/bin/env python3 # # Copyright 2018 California Institute of Technology # # 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 # # Unle...
#! /usr/bin/env python3 # # Copyright 2018 California Institute of Technology # # 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 # # Unle...
en
0.808797
#! /usr/bin/env python3 # # Copyright 2018 California Institute of Technology # # 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 # # Unle...
2.274918
2
python/wheedle/errors.py
kpvdr/actions-artifact-poller
1
6627710
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
en
0.823258
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
1.845249
2
aiida_abacus/data/__init__.py
materials-science/aiida-abacus
4
6627711
# -*- coding: utf-8 -*- """ Data types provided by plugin Register data types via the "aiida.data" entry point in setup.json. """ # You can directly use or subclass aiida.orm.data.Data # or any other data type listed under 'verdi data' from voluptuous import Schema, Optional from aiida.orm import Dict # A subset of ...
# -*- coding: utf-8 -*- """ Data types provided by plugin Register data types via the "aiida.data" entry point in setup.json. """ # You can directly use or subclass aiida.orm.data.Data # or any other data type listed under 'verdi data' from voluptuous import Schema, Optional from aiida.orm import Dict # A subset of ...
en
0.504847
# -*- coding: utf-8 -*- Data types provided by plugin Register data types via the "aiida.data" entry point in setup.json. # You can directly use or subclass aiida.orm.data.Data # or any other data type listed under 'verdi data' # A subset of diff's command line options # pylint: disable=too-many-ancestors Command line...
2.235081
2
src/look-around/eval.py
srama2512/visual-exploration
12
6627712
""" Script to evaluate look-around policies """ import os import sys import pdb import json import torch import random import argparse import torchvision import tensorboardX import torch.optim as optim import torchvision.utils as vutils from envs import * from utils import * from agent import * from base.common impor...
""" Script to evaluate look-around policies """ import os import sys import pdb import json import torch import random import argparse import torchvision import tensorboardX import torch.optim as optim import torchvision.utils as vutils from envs import * from utils import * from agent import * from base.common impor...
en
0.362077
Script to evaluate look-around policies # Optimization options # Agent options # Environment options #%d, image #%d'%(choice, pano_count), x, 0) #%d, image #%d'%(choice, pano_count), x, 0)
2.029099
2
scripts/training/reflection/training/dataset_processing/multi_objective/multi_split.py
DanJSG/reflectiment
0
6627713
<filename>scripts/training/reflection/training/dataset_processing/multi_objective/multi_split.py from math import floor from random import shuffle from nltk import word_tokenize import string bawe_sentences = open("./dataset_processing/bawe/sentences.txt", "r").readlines() bawe_scores = open("./dataset_processing/bawe...
<filename>scripts/training/reflection/training/dataset_processing/multi_objective/multi_split.py from math import floor from random import shuffle from nltk import word_tokenize import string bawe_sentences = open("./dataset_processing/bawe/sentences.txt", "r").readlines() bawe_scores = open("./dataset_processing/bawe...
none
1
2.864765
3
A2C/simplePG.py
CommanderCero/RL_Algorithms
1
6627714
import numpy as np import torch import torch.nn as nn import gym import models import utils def train(policy: models.Policy, env, train_steps = 1000, reward_decay=0.99, learning_rate=0.001): action_cache = [] state_cache = [] reward_cache = [] optimizer = torch.optim.Adam(policy.parameters(),...
import numpy as np import torch import torch.nn as nn import gym import models import utils def train(policy: models.Policy, env, train_steps = 1000, reward_decay=0.99, learning_rate=0.001): action_cache = [] state_cache = [] reward_cache = [] optimizer = torch.optim.Adam(policy.parameters(),...
en
0.843759
# Clear cache # Collect data from one trajectory # Collect data # Compute "Loss"-function for computing the policy gradient # Gradient descent (Technically ascend since we took the negative of the policy gradient)
2.989241
3
chiebukuro2.py
l-plantarum/chiebukuro
0
6627715
<filename>chiebukuro2.py #!/usr/bin/python3 # coding=utf-8 import time import urllib.request from bs4 import BeautifulSoup import sys from pymongo import MongoClient import re import datetime import json import syslog # 指定した記事を開き,取り消し済みならNoneを返す def urlopen(url): try: resp = urllib.request.urlopen(url) except ur...
<filename>chiebukuro2.py #!/usr/bin/python3 # coding=utf-8 import time import urllib.request from bs4 import BeautifulSoup import sys from pymongo import MongoClient import re import datetime import json import syslog # 指定した記事を開き,取り消し済みならNoneを返す def urlopen(url): try: resp = urllib.request.urlopen(url) except ur...
ja
0.977081
#!/usr/bin/python3 # coding=utf-8 # 指定した記事を開き,取り消し済みならNoneを返す # これは取り消し済 # どの道中身は返せない # 指定したURLのページを情報を取得しMongoDBに追加する # True: DBの内容を変更した # False: DBの内容はそのまま # 登録済URLなら以下の処理は実施しない # 取り消し済みなら何もしない # 検索クエリを発行 # 最初から取り消ししてあれば何もしない # 質問 # 質問者情報 # usrInfo = usrQ.find("div", class_="usrInfo") # author = usrInfo.find("p", cla...
2.706044
3
python/blocked_sampling/dataset/helper_compute_area/SRLutils.py
goldleaf3i/generativeCMLgraphs
0
6627716
<reponame>goldleaf3i/generativeCMLgraphs import xml.etree.ElementTree as ET import matplotlib.pyplot as plt import matplotlib.colors as pltcol import matplotlib.cbook as cbook import numpy as np import math import cmath import glob from myDictionaries import * from xml.dom.minidom import parse import numpy.random as rn...
import xml.etree.ElementTree as ET import matplotlib.pyplot as plt import matplotlib.colors as pltcol import matplotlib.cbook as cbook import numpy as np import math import cmath import glob from myDictionaries import * from xml.dom.minidom import parse import numpy.random as rnd from matplotlib.patches import Ellipse ...
it
0.295103
# STUPIDO SCIKIT #line+= str("{0:2f}".format(M[i,j]))+' ,' #'RC' : labels_RC_java2012[letter], #'ellipse' : Ellipse(xy=[0.7,counter*0.7], width=0.6, height=0.6,angle=0), #break # assumendo che la root sia sempre <building> # buildings_dict[floor_id] = [] # buildings_dict['floor_id'].append(space.get('id')) # space_dict...
2.861623
3
groups/arm/ggd/arm.py
awslabs/aws-greengrass-mini-fulfillment
25
6627717
#!/usr/bin/env python # Copyright 2017 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 t...
#!/usr/bin/env python # Copyright 2017 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 t...
en
0.863877
#!/usr/bin/env python # Copyright 2017 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 th...
2.163499
2
grr/server/grr_response_server/aff4_objects/stats_store.py
billstackpole/grr
1
6627718
#!/usr/bin/env python """Storage implementation for gathered statistics. Statistics collected by StatsCollector (see lib/stats.py) is stored in AFF4 space. Statistics data for different parts of the system is separated by process ids. For example, for the frontend, process id may be "frontend", for worker - "worker", ...
#!/usr/bin/env python """Storage implementation for gathered statistics. Statistics collected by StatsCollector (see lib/stats.py) is stored in AFF4 space. Statistics data for different parts of the system is separated by process ids. For example, for the frontend, process id may be "frontend", for worker - "worker", ...
en
0.812512
#!/usr/bin/env python Storage implementation for gathered statistics. Statistics collected by StatsCollector (see lib/stats.py) is stored in AFF4 space. Statistics data for different parts of the system is separated by process ids. For example, for the frontend, process id may be "frontend", for worker - "worker", etc...
2.172297
2
niapy/algorithms/other/hc.py
altaregos/NiaPy
202
6627719
<reponame>altaregos/NiaPy<gh_stars>100-1000 # encoding=utf8 import logging from niapy.algorithms.algorithm import Algorithm logging.basicConfig() logger = logging.getLogger('niapy.algorithms.other') logger.setLevel('INFO') __all__ = ['HillClimbAlgorithm'] def neighborhood(x, delta, task, rng): r"""Get neighbou...
# encoding=utf8 import logging from niapy.algorithms.algorithm import Algorithm logging.basicConfig() logger = logging.getLogger('niapy.algorithms.other') logger.setLevel('INFO') __all__ = ['HillClimbAlgorithm'] def neighborhood(x, delta, task, rng): r"""Get neighbours of point. Args: x (numpy.nda...
en
0.566326
# encoding=utf8 Get neighbours of point. Args: x (numpy.ndarray): Point. delta (float): Standard deviation. task (Task): Optimization task. rng (numpy.random.Generator): Random generator. Returns: Tuple[numpy.ndarray, float]: 1. New solution. 2. ...
2.750111
3
tests/test_ecwid_endpoint_customers.py
DanPalmz/pyecwid
3
6627720
import json import os #from pprint import pprint from pyecwid import Ecwid, EcwidMock import pytest import pytest_dependency import pytest_dotenv import time API_TOKEN = os.getenv("API_TOKEN") API_STORE = os.getenv("API_STORE") SLEEP_TIME = 5 @pytest.fixture def dummy_customer(): with open('./tests/samplejson/cu...
import json import os #from pprint import pprint from pyecwid import Ecwid, EcwidMock import pytest import pytest_dependency import pytest_dotenv import time API_TOKEN = os.getenv("API_TOKEN") API_STORE = os.getenv("API_STORE") SLEEP_TIME = 5 @pytest.fixture def dummy_customer(): with open('./tests/samplejson/cu...
en
0.858009
#from pprint import pprint # Sleep: Server wasn't updating quick enough for tests following this one..
2.055967
2
src/zope/i18n/gettextmessagecatalog.py
Shoobx/zope.i18n
0
6627721
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
en
0.422573
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
2.187099
2
snafu/benchmarks/systemd_analyze/systemd_analyze.py
dagrayvid/benchmark-wrapper
14
6627722
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """sample_benchmark hosts and export results.""" import datetime import json import logging import os import re import subprocess from typing import List import distro from snafu.benchmarks import Benchmark, BenchmarkResult logger = logging.getLogger("snafu") class sy...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """sample_benchmark hosts and export results.""" import datetime import json import logging import os import re import subprocess from typing import List import distro from snafu.benchmarks import Benchmark, BenchmarkResult logger = logging.getLogger("snafu") class sy...
en
0.472204
#!/usr/bin/env python3 # -*- coding: utf-8 -*- sample_benchmark hosts and export results. # pylint: disable=invalid-name Wrapper for the systemd-analyze Test benchmark. cd /<working dir>/snafu ./run_snafu.py --tool systemd_analyze --create-archive # Test configuration lists # pylint: disable=attribute-defined-o...
2.11775
2
src/python_quickstart_client.py
BlackCowThrower/batch-python-quickstart
0
6627723
from __future__ import print_function import datetime import io import os import sys import time import config try: input = raw_input except NameError: pass import azure.batch.batch_auth as batch_auth import azure.batch.batch_service_client as batch import azure.batch.models as batchmodels import azure.stor...
from __future__ import print_function import datetime import io import os import sys import time import config try: input = raw_input except NameError: pass import azure.batch.batch_auth as batch_auth import azure.batch.batch_service_client as batch import azure.batch.models as batchmodels import azure.stor...
en
0.691681
# Update the Batch and Storage account credential strings in config.py with values # unique to your accounts. These are used when constructing connection strings # for the Batch and Storage client objects. Prompts the user for yes/no input, displaying the specified question text. :param str question: The text of t...
2.661802
3
poppy/manager/default/ssl_certificate.py
LukeRepko/poppy
3
6627724
# Copyright (c) 2014 Rackspace, 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 wr...
# Copyright (c) 2014 Rackspace, 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 wr...
en
0.752716
# Copyright (c) 2014 Rackspace, 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 wr...
1.653247
2
src/cfnlint/rules/resources/UniqueNames.py
Adam-sHub/cfn-lint
1,134
6627725
<reponame>Adam-sHub/cfn-lint """ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ from cfnlint.rules import CloudFormationLintRule, RuleMatch class UniqueNames(CloudFormationLintRule): id = 'E3007' shortdesc = 'Unique resource and parameter names' descr...
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ from cfnlint.rules import CloudFormationLintRule, RuleMatch class UniqueNames(CloudFormationLintRule): id = 'E3007' shortdesc = 'Unique resource and parameter names' description = 'All resources and p...
en
0.650999
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0
2.220334
2
iter/multi_process.py
kissf-lu/python_test
3
6627726
from simpy import Environment, Resource def print_stats(res): print('%d of %d slots are allocated.' % (res.count, res.capacity)) print(' Users:', res.users) print(' Queued events:', res.queue) def user(env, res, name): """ """ with res.request() as req: # 每个req的yield迭代两个list:...
from simpy import Environment, Resource def print_stats(res): print('%d of %d slots are allocated.' % (res.count, res.capacity)) print(' Users:', res.users) print(' Queued events:', res.queue) def user(env, res, name): """ """ with res.request() as req: # 每个req的yield迭代两个list:...
zh
0.448901
# 每个req的yield迭代两个list: server queue, waiting queue, # 每次服务队列迭代server queue 获取在一次 # capacity个request都延迟1秒才能释放资源, # with内的yield timeout 用于阻塞正在服务的request一段时间才释放, # 释放后被阻塞的waiting request 立即获得服务资源 # with外的yield timeout不会阻塞waiting request获得服务资源, # # yield env.timeout(1) # env.process(multi_process(env, res))
2.78621
3
trinity/components/builtin/peer_discovery/component.py
teotoplak/trinity
0
6627727
from argparse import ( ArgumentParser, _SubParsersAction, ) import asyncio from typing import ( Type, ) from lahja import EndpointAPI from p2p.abc import ProtocolAPI from p2p.constants import ( DISCOVERY_EVENTBUS_ENDPOINT, ) from p2p.discovery import ( DiscoveryService, PreferredNodeDiscoveryP...
from argparse import ( ArgumentParser, _SubParsersAction, ) import asyncio from typing import ( Type, ) from lahja import EndpointAPI from p2p.abc import ProtocolAPI from p2p.constants import ( DISCOVERY_EVENTBUS_ENDPOINT, ) from p2p.discovery import ( DiscoveryService, PreferredNodeDiscoveryP...
en
0.837319
# For now DiscoveryByTopicProtocol supports a single topic, so we use the latest # version of our supported protocols. Maybe this could be more generic? # TODO: This needs to support the beacon protocol when we have a way to # check the config, if trinity is being run as a beacon node. Bootstrap discovery to provide a ...
2.030526
2
geneparse/index/impute2.py
legaultmarc/geneparse
4
6627728
<reponame>legaultmarc/geneparse """IMPUTE2 index.""" # This file is part of geneparse. # # The MIT License (MIT) # # Copyright (c) 2017 Pharmacogenomics Centre # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to dea...
"""IMPUTE2 index.""" # This file is part of geneparse. # # The MIT License (MIT) # # Copyright (c) 2017 Pharmacogenomics Centre # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without rest...
en
0.786885
IMPUTE2 index. # This file is part of geneparse. # # The MIT License (MIT) # # Copyright (c) 2017 Pharmacogenomics Centre # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction...
2.617793
3
scrapers/cdms.py
nseifert/splatalogue
0
6627729
import urllib2 from bs4 import BeautifulSoup import time import numpy as np import pandas as pd from itertools import izip_longest from collections import OrderedDict import re import MySQLdb as sqldb import easygui as eg from QNFormat import * import sys import os class CDMSMolecule: def parse_cat(self, cat_url=...
import urllib2 from bs4 import BeautifulSoup import time import numpy as np import pandas as pd from itertools import izip_longest from collections import OrderedDict import re import MySQLdb as sqldb import easygui as eg from QNFormat import * import sys import os class CDMSMolecule: def parse_cat(self, cat_url=...
en
0.747823
This function takes a Pickett prediction file (a so-called "CAT" file) and converts it into a Pandas DataFrame. This code should work for any well-formed CAT file, and works for all CDMS and JPL entries, as well as custom, user-generated CAT files. It is unclear if there are any edge cases this misses ...
2.550103
3
fab_support/__init__.py
drummonds/fab_support
3
6627730
<filename>fab_support/__init__.py # -*- coding: utf-8 -*- """Top-level package for fab_support.""" from ._version import * from .utils import * # Import first as also imported by platform_support from .env_support import * from .platform_support import fab_support_function from .stages_support import list_stages
<filename>fab_support/__init__.py # -*- coding: utf-8 -*- """Top-level package for fab_support.""" from ._version import * from .utils import * # Import first as also imported by platform_support from .env_support import * from .platform_support import fab_support_function from .stages_support import list_stages
en
0.922239
# -*- coding: utf-8 -*- Top-level package for fab_support. # Import first as also imported by platform_support
1.224474
1
paramtools/tests/test_parameters.py
PSLmodels/ParamTools
18
6627731
import copy import os import json import datetime from collections import OrderedDict from random import shuffle import pytest import numpy as np import marshmallow as ma from paramtools import ( ParamToolsError, ValidationError, SparseValueObjectsException, InconsistentLabelsException, collision_...
import copy import os import json import datetime from collections import OrderedDict from random import shuffle import pytest import numpy as np import marshmallow as ma from paramtools import ( ParamToolsError, ValidationError, SparseValueObjectsException, InconsistentLabelsException, collision_...
en
0.828933
# Tests data is serialized. # check that specification method got only the value item with label0="one" # check that get method got only value item with label0="one" # check that specification method gets other data, not containing a label0 # label. # Make sure "value" is removed when meta_data is False Ensure sort run...
2.06913
2
mistralclient/api/v2/executions.py
mail2nsrajesh/python-mistralclient
0
6627732
<gh_stars>0 # Copyright 2014 - Mirantis, Inc. # Copyright 2015 - StackStorm, 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....
# Copyright 2014 - Mirantis, Inc. # Copyright 2015 - StackStorm, 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 # # Unl...
en
0.836925
# Copyright 2014 - Mirantis, Inc. # Copyright 2015 - StackStorm, 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 # # Unl...
1.858267
2
mixin.py
yupeng0921/pymixin
6
6627733
<reponame>yupeng0921/pymixin #!/usr/bin/env python import sys import types __all__ = ['mixin', 'Mixin', 'InstantiationMixinError', 'InvalidMixinError', 'InheritMixinError'] # class_types and add_metaclass were copied from six PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: class_types = t...
#!/usr/bin/env python import sys import types __all__ = ['mixin', 'Mixin', 'InstantiationMixinError', 'InvalidMixinError', 'InheritMixinError'] # class_types and add_metaclass were copied from six PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY3: class_types = type, else: class_types = ...
en
0.885408
#!/usr/bin/env python # class_types and add_metaclass were copied from six Class decorator for creating a class with a metaclass.
2.397293
2
Exercices/chapter_03/stack.py
joelwembo/expert-python-dts-algorithms
0
6627734
class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if self.items: return self.items[-1] r...
class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): if self.items: return self.items[-1] r...
en
0.853619
# in python the `len` function is preferred to `size` methods # lets us use the stack as a conditional
3.920035
4
src/utils/beam_search.py
r39ashmi/LastMileRoutingResearchChallenge
0
6627735
<reponame>r39ashmi/LastMileRoutingResearchChallenge import torch class CachedLookup(object): def __init__(self, data): self.orig = data self.key = None self.current = None def __getitem__(self, key): assert not isinstance(key, slice), "CachedLookup does not support slicing, " ...
import torch class CachedLookup(object): def __init__(self, data): self.orig = data self.key = None self.current = None def __getitem__(self, key): assert not isinstance(key, slice), "CachedLookup does not support slicing, " \ "you ca...
en
0.774541
# If tensor, idx all tensors by this tensor:
2.673756
3
vi/search.py
uri/Vintageous
0
6627736
import sublime def find_in_range(view, term, start, end, flags=0): found = view.find(term, start, flags) if found and found.b <= end: return found def find_wrapping(view, term, start, end, flags=0, times=1): current_sel = view.sel()[0] # Search wrapping around the end of the buffe...
import sublime def find_in_range(view, term, start, end, flags=0): found = view.find(term, start, flags) if found and found.b <= end: return found def find_wrapping(view, term, start, end, flags=0, times=1): current_sel = view.sel()[0] # Search wrapping around the end of the buffe...
en
0.937762
# Search wrapping around the end of the buffer. # Start searching in the upper half of the buffer if we aren't doing it yet. # No luck in the whole buffer. # Search wrapping around the end of the buffer. # Start searching in the lower half of the buffer if we aren't doing it yet. # No luck in the whole buffer. # revers...
3.135974
3
rx/core/operators/groupbyuntil.py
daliclass/RxPY
0
6627737
from typing import Callable, Optional from collections import OrderedDict from rx import operators as ops from rx.core import Observable, GroupedObservable from rx.core.typing import Mapper from rx.subjects import Subject from rx.disposable import CompositeDisposable, RefCountDisposable, SingleAssignmentDisposable fro...
from typing import Callable, Optional from collections import OrderedDict from rx import operators as ops from rx.core import Observable, GroupedObservable from rx.core.typing import Mapper from rx.subjects import Subject from rx.disposable import CompositeDisposable, RefCountDisposable, SingleAssignmentDisposable fro...
en
0.721188
Groups the elements of an observable sequence according to a specified key mapper function. A duration mapper function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same key value as a reclaimed group occurs, the gro...
2.612405
3
herbie/models/hrrr.py
WToma/Herbie
0
6627738
## Added by <NAME> ## July 26, 2021 """ A Herbie template for the HRRR model. Because the file path to GRIB2 model data is predictable, we can template the download URL for model output. Follow this template for writing your own template file for any model with GRIB2 files available via https. Requirements ---------...
## Added by <NAME> ## July 26, 2021 """ A Herbie template for the HRRR model. Because the file path to GRIB2 model data is predictable, we can template the download URL for model output. Follow this template for writing your own template file for any model with GRIB2 files available via https. Requirements ---------...
en
0.735256
## Added by <NAME> ## July 26, 2021 A Herbie template for the HRRR model. Because the file path to GRIB2 model data is predictable, we can template the download URL for model output. Follow this template for writing your own template file for any model with GRIB2 files available via https. Requirements ------------ 1...
2.699209
3
hypha/apply/activity/migrations/0032_migrate_submission_to_generic_event.py
maxpearl/hypha
20
6627739
<filename>hypha/apply/activity/migrations/0032_migrate_submission_to_generic_event.py # Generated by Django 2.0.13 on 2019-07-10 22:36 from django.db import migrations from django.db.models import F def submission_to_source(apps, schema_editor): Event = apps.get_model('activity', 'Event') if Event.objects.ex...
<filename>hypha/apply/activity/migrations/0032_migrate_submission_to_generic_event.py # Generated by Django 2.0.13 on 2019-07-10 22:36 from django.db import migrations from django.db.models import F def submission_to_source(apps, schema_editor): Event = apps.get_model('activity', 'Event') if Event.objects.ex...
en
0.78738
# Generated by Django 2.0.13 on 2019-07-10 22:36
1.540578
2
app/core/middleware.py
elifesciences/digests
0
6627740
from logging import getLogger from typing import Callable from django.conf import settings from django.http.request import HttpRequest as Request from django.http.response import HttpResponse as Response from django.views.decorators.cache import patch_cache_control LOGGER = getLogger(__name__) def _set_can_modify(r...
from logging import getLogger from typing import Callable from django.conf import settings from django.http.request import HttpRequest as Request from django.http.response import HttpResponse as Response from django.views.decorators.cache import patch_cache_control LOGGER = getLogger(__name__) def _set_can_modify(r...
none
1
2.019236
2
EvalBox/Attack/AdvAttack/rfgsm.py
Yzx835/AISafety
32
6627741
#!/usr/bin/env python # coding=UTF-8 """ @Author: <NAME> @LastEditors: <NAME> @Description: @Date: 2019-03-27 09:40:58 @LastEditTime: 2019-04-15 09:23:19 """ import numpy as np import torch from torch.autograd import Variable from EvalBox.Attack.AdvAttack.attack import Attack class RFGSM(Attack): def __init__(...
#!/usr/bin/env python # coding=UTF-8 """ @Author: <NAME> @LastEditors: <NAME> @Description: @Date: 2019-03-27 09:40:58 @LastEditTime: 2019-04-15 09:23:19 """ import numpy as np import torch from torch.autograd import Variable from EvalBox.Attack.AdvAttack.attack import Attack class RFGSM(Attack): def __init__(...
en
0.359954
#!/usr/bin/env python # coding=UTF-8 @Author: <NAME> @LastEditors: <NAME> @Description: @Date: 2019-03-27 09:40:58 @LastEditTime: 2019-04-15 09:23:19 @description: Random FGSM @param { model: device: kwargs: } @return: None @description: @param { ...
2.286981
2
src/services/Schedule/test.py
IAPark/PITherm
0
6627742
<reponame>IAPark/PITherm import subprocess import unittest from datetime import datetime import requests import time from pymongo import MongoClient class TestSchedule(unittest.TestCase): url = "http://localhost:5003" schedule = subprocess.Popen(["python", ["Schedule.py"]]) def test_add_to_schedule(self...
import subprocess import unittest from datetime import datetime import requests import time from pymongo import MongoClient class TestSchedule(unittest.TestCase): url = "http://localhost:5003" schedule = subprocess.Popen(["python", ["Schedule.py"]]) def test_add_to_schedule(self): requests.post(...
none
1
2.580853
3
test/test_customer_api.py
MPW1412/kimai-python
6
6627743
# coding: utf-8 """ Kimai 2 - API Docs JSON API for the Kimai 2 time-tracking software. Read more about its usage in the [API documentation](https://www.kimai.org/documentation/rest-api.html) and then download a [Swagger file](doc.json) for import e.g. in Postman. Be aware: it is not yet considered stable and...
# coding: utf-8 """ Kimai 2 - API Docs JSON API for the Kimai 2 time-tracking software. Read more about its usage in the [API documentation](https://www.kimai.org/documentation/rest-api.html) and then download a [Swagger file](doc.json) for import e.g. in Postman. Be aware: it is not yet considered stable and...
en
0.694738
# coding: utf-8 Kimai 2 - API Docs JSON API for the Kimai 2 time-tracking software. Read more about its usage in the [API documentation](https://www.kimai.org/documentation/rest-api.html) and then download a [Swagger file](doc.json) for import e.g. in Postman. Be aware: it is not yet considered stable and BC break...
2.032381
2
tests/test_validators.py
papaemmelab/toil_example
0
6627744
<gh_stars>0 """toil_example validators tests.""" from os.path import join import pytest from toil_example import exceptions from toil_example import validators def test_validate_patterns_are_files(tmpdir): """Create multiple files and test test_validate_patterns_are_files.""" tmpdir_path = str(tmpdir) ...
"""toil_example validators tests.""" from os.path import join import pytest from toil_example import exceptions from toil_example import validators def test_validate_patterns_are_files(tmpdir): """Create multiple files and test test_validate_patterns_are_files.""" tmpdir_path = str(tmpdir) for i in ran...
en
0.526105
toil_example validators tests. Create multiple files and test test_validate_patterns_are_files. # check empty files exist # check files exist amd are not empty # check that empty files raise error with default setting # check that empty files raise error with flag # check that pattern is not file # check that empty fil...
2.72209
3
tests/test_brew_list.py
locriandev/art-bot
4
6627745
<reponame>locriandev/art-bot import flexmock import pytest from unittest.mock import patch, MagicMock from artbotlib import brew_list @pytest.mark.parametrize("params, expected", [ [("4.5",), f"{brew_list.RHCOS_BASE_URL}/rhcos-4.5"], [("4.5", "s390x"), f"{brew_list.RHCOS_BASE_URL}/rhcos-4.5-s390x...
import flexmock import pytest from unittest.mock import patch, MagicMock from artbotlib import brew_list @pytest.mark.parametrize("params, expected", [ [("4.5",), f"{brew_list.RHCOS_BASE_URL}/rhcos-4.5"], [("4.5", "s390x"), f"{brew_list.RHCOS_BASE_URL}/rhcos-4.5-s390x"], ] ) def test_rhcos_re...
en
0.929812
{ "rpmostree.rpmdb.pkglist" : [ [ "NetworkManager", "1", "1.20.0", "5.el8_1", "x86_64" ], [ "NetworkManager-l...
2.14808
2
pymatgen/analysis/elasticity/tensors.py
mailhexu/pymatgen
0
6627746
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import from scipy.linalg import polar import numpy as np import itertools import warnings import collections from pymatgen.symm...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, print_function, unicode_literals, \ absolute_import from scipy.linalg import polar import numpy as np import itertools import warnings import collections from pymatgen.symm...
en
0.79582
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. This module provides a base class for tensor-like objects and methods for basic tensor manipulation. It also provides a class, SquareTensor, that provides basic methods for creating and manipulating rank 2 tens...
2.315659
2
identity/views.py
Natan7/vault
1
6627747
# -*- coding: utf-8 -*- import logging from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.core.urlresolvers import reverse_lazy from django.utils.decorators imp...
# -*- coding: utf-8 -*- import logging from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.core.urlresolvers import reverse_lazy from django.utils.decorators imp...
en
0.447556
# -*- coding: utf-8 -*- # can't modify primary project # Mostra a gerencia de roles qd for superuser acessando admin # Houve falha no cadastro # Falhou ao auntenticar com as credenciais enviadas pelo usuario # TODO: in v3 client users won't list roles (verify role_assignments)
1.777113
2
accounts/views.py
drkEvo/DjangoBankSystem
0
6627748
from django.contrib import messages from django.contrib.auth import get_user_model, login, logout from django.contrib.auth.views import LoginView from django.shortcuts import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import TemplateView, RedirectView from .forms import UserReg...
from django.contrib import messages from django.contrib.auth import get_user_model, login, logout from django.contrib.auth.views import LoginView from django.shortcuts import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import TemplateView, RedirectView from .forms import UserReg...
en
0.173424
# import pdb # pdb.set_trace() # form = TransactionDateRangeForm(request.GET or None) # if form.is_valid(): # self.form_data = form.cleaned_data # def get_queryset(self): # queryset = super().get_queryset().filter( # account=self.request.user.account # ) # daterange = self.form_data.get("dateran...
2.260025
2
batch_generator.py
danathughes/DeepEmbeddedClustering
22
6627749
## batch_generator.py ## ## ## ## History: ## 1.0 29-Jun-2016 Initial version ## 1.1 12-Aug-2016 Changed input / output to key / value pairs ## Changed class from Dataset to Batch ## 1.2 30-Sep-2016 Changed class from Batch to BatchGenerator ## ...
## batch_generator.py ## ## ## ## History: ## 1.0 29-Jun-2016 Initial version ## 1.1 12-Aug-2016 Changed input / output to key / value pairs ## Changed class from Dataset to Batch ## 1.2 30-Sep-2016 Changed class from Batch to BatchGenerator ## ...
en
0.732123
## batch_generator.py ## ## ## ## History: ## 1.0 29-Jun-2016 Initial version ## 1.1 12-Aug-2016 Changed input / output to key / value pairs ## Changed class from Dataset to Batch ## 1.2 30-Sep-2016 Changed class from Batch to BatchGenerator ## ...
3.068677
3
tests/generator/common/shell.py
multiplemonomials/MIRP
24
6627750
<filename>tests/generator/common/shell.py #!/usr/bin/env python3 def ncart(am): return ((am+1)*(am+2))//2 def iterate_gaussian(lmn): am = lmn[0] + lmn[1] + lmn[2] if lmn[2] >= am: return None if lmn[2] < (am - lmn[0]): return (lmn[0], lmn[1]-1, lmn[2]+1) else: return (lmn...
<filename>tests/generator/common/shell.py #!/usr/bin/env python3 def ncart(am): return ((am+1)*(am+2))//2 def iterate_gaussian(lmn): am = lmn[0] + lmn[1] + lmn[2] if lmn[2] >= am: return None if lmn[2] < (am - lmn[0]): return (lmn[0], lmn[1]-1, lmn[2]+1) else: return (lmn...
fr
0.221828
#!/usr/bin/env python3
2.84609
3