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
PytorchRouting/Examples/run_experiments.py
oleksost/RoutingNetworks
63
8700
<filename>PytorchRouting/Examples/run_experiments.py """ This file defines some simple experiments to illustrate how Pytorch-Routing functions. """ import numpy as np import tqdm import torch from PytorchRouting.DecisionLayers import REINFORCE, QLearning, SARSA, ActorCritic, GumbelSoftmax, PerTaskAssignment, \ WPL,...
<filename>PytorchRouting/Examples/run_experiments.py """ This file defines some simple experiments to illustrate how Pytorch-Routing functions. """ import numpy as np import tqdm import torch from PytorchRouting.DecisionLayers import REINFORCE, QLearning, SARSA, ActorCritic, GumbelSoftmax, PerTaskAssignment, \ WPL,...
en
0.528215
This file defines some simple experiments to illustrate how Pytorch-Routing functions. # while True: # MNIST # dataset = MNIST_MTL(64, data_files=['./Datasets/mnist.pkl.gz']) # model = PerTask_all_fc(1, 288, 2, dataset.num_tasks, dataset.num_tasks) # model = WPL_routed_all_fc(1, 288, 2, dataset.num_tasks, dataset.num_t...
3.020533
3
output/models/ms_data/regex/re_g22_xsd/__init__.py
tefra/xsdata-w3c-tests
1
8701
from output.models.ms_data.regex.re_g22_xsd.re_g22 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
from output.models.ms_data.regex.re_g22_xsd.re_g22 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
none
1
1.167351
1
code/image-manipulation.py
rgeirhos/object-recognition
33
8702
#!/usr/bin/env python from skimage.color import rgb2gray from skimage.io import imread, imsave from scipy.misc import toimage import numpy as np import wrapper as wr ########################################################### # IMAGE IO ########################################################### def imload_rgb(pa...
#!/usr/bin/env python from skimage.color import rgb2gray from skimage.io import imread, imsave from scipy.misc import toimage import numpy as np import wrapper as wr ########################################################### # IMAGE IO ########################################################### def imload_rgb(pa...
en
0.358418
#!/usr/bin/env python ########################################################### # IMAGE IO ########################################################### Load and return an RGB image in the range [0, 1]. Save image as either .jpeg or .png ########################################################### # IMAGE MANIPULATI...
2.657595
3
students/K33402/Akhmetzhanov Alisher/lr2/main/forms.py
AlishKZ/ITMO_ICT_WebDevelopment_2020-2021
0
8703
from django.db.models import fields from main.models import RoomReservation, UserRoom from django import forms from django.core.exceptions import ValidationError from django.contrib.auth import authenticate, login from django.contrib.auth import get_user_model class ReservateRoomForm(forms.Form): begin_date = for...
from django.db.models import fields from main.models import RoomReservation, UserRoom from django import forms from django.core.exceptions import ValidationError from django.contrib.auth import authenticate, login from django.contrib.auth import get_user_model class ReservateRoomForm(forms.Form): begin_date = for...
none
1
2.055691
2
emmet-core/emmet/core/vasp/calc_types.py
espottesmith/emmet
0
8704
<filename>emmet-core/emmet/core/vasp/calc_types.py<gh_stars>0 """ Module to define various calculation types as Enums for VASP """ import datetime from itertools import groupby, product from pathlib import Path from typing import Dict, Iterator, List import bson import numpy as np from monty.json import MSONable from ...
<filename>emmet-core/emmet/core/vasp/calc_types.py<gh_stars>0 """ Module to define various calculation types as Enums for VASP """ import datetime from itertools import groupby, product from pathlib import Path from typing import Dict, Iterator, List import bson import numpy as np from monty.json import MSONable from ...
en
0.646212
Module to define various calculation types as Enums for VASP # type: ignore # type: ignore # type: ignore Determines the run_type from the VASP parameters dict This is adapted from pymatgen to be far less unstable Args: parameters: Dictionary of VASP parameters from Vasprun.xml helper function to deal ...
2.044944
2
sensors/__init__.py
dawnos/robotcar-to-rosbag
0
8705
from mono_left import MonoLeft from mono_right import MonoRight from mono_rear import MonoRear from stereo_left import StereoLeft from stereo_right import StereoRight from stereo_centre import StereoCentre
from mono_left import MonoLeft from mono_right import MonoRight from mono_rear import MonoRear from stereo_left import StereoLeft from stereo_right import StereoRight from stereo_centre import StereoCentre
none
1
1.139627
1
models/train_classifier.py
YiWang-Evonne/disaster_response
0
8706
<filename>models/train_classifier.py import sys import pandas as pd from sqlalchemy import create_engine import nltk nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger']) import re from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import classification_repo...
<filename>models/train_classifier.py import sys import pandas as pd from sqlalchemy import create_engine import nltk nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger']) import re from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import classification_repo...
en
0.493456
load data from sql db :param database_filepath: sql db path :return: pandas dataframe processing the text input :param text: text inputs :return: build model pipeline :return: model pipeline evaluate model performances :param model: model obj :param X_test: test x :param Y_test: test ...
2.671436
3
terra/terra/emails.py
dymaxionlabs/platform
0
8707
<reponame>dymaxionlabs/platform import os from datetime import date from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext as _ from mailchimp3 import MailChimp clas...
import os from datetime import date from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext as _ from mailchimp3 import MailChimp class Email: from_email = settin...
en
0.588827
Replaces MailChimp variables for Django template variables, and do some post-processing. # Unused variables (for now):
2.300007
2
experimental/attentive_uncertainty/toy_regression/datasets.py
miksu/edward2
0
8708
# coding=utf-8 # Copyright 2019 The Edward2 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 applicable law o...
# coding=utf-8 # Copyright 2019 The Edward2 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 applicable law o...
en
0.777681
# coding=utf-8 # Copyright 2019 The Edward2 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 applicable law o...
2.537671
3
critiquebrainz/frontend/views/index.py
shagun6/critiquebrainz
0
8709
<filename>critiquebrainz/frontend/views/index.py from flask import Blueprint, render_template from flask_babel import format_number import critiquebrainz.db.users as db_users import critiquebrainz.db.review as db_review from bs4 import BeautifulSoup from markdown import markdown DEFAULT_CACHE_EXPIRATION = 10 * 60 # s...
<filename>critiquebrainz/frontend/views/index.py from flask import Blueprint, render_template from flask_babel import format_number import critiquebrainz.db.users as db_users import critiquebrainz.db.review as db_review from bs4 import BeautifulSoup from markdown import markdown DEFAULT_CACHE_EXPIRATION = 10 * 60 # s...
en
0.69376
# seconds # Popular reviews # Preparing text for preview # Recent reviews # Statistics
2.165501
2
Enigma/Enigma-master/GBS/gbsHelper.py
Q-Alpha/Hackathon2020
12
8710
import strawberryfields as sf from strawberryfields import ops from strawberryfields.utils import random_interferometer from strawberryfields.apps import data, sample, subgraph, plot import plotly import networkx as nx import numpy as np class GBS: def __init__(self, samples =[], min_pho = 16, max_pho = 30, subgra...
import strawberryfields as sf from strawberryfields import ops from strawberryfields.utils import random_interferometer from strawberryfields.apps import data, sample, subgraph, plot import plotly import networkx as nx import numpy as np class GBS: def __init__(self, samples =[], min_pho = 16, max_pho = 30, subgra...
en
0.697348
# Initial squeezed states # Allowed values are r=1.0 or r=0.0 # Interferometer on the signal modes (0-3) # *Same* interferometer on the idler modes (4-7) # state = results.state # measurements = results.samples
2.302253
2
happy/HappyNodeJoin.py
jenniexie/happy
0
8711
<reponame>jenniexie/happy #!/usr/bin/env python # # Copyright (c) 2015-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # h...
#!/usr/bin/env python # # Copyright (c) 2015-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licen...
en
0.760091
#!/usr/bin/env python # # Copyright (c) 2015-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licens...
2.234889
2
__init__.py
SDRAST/Data_Reduction
0
8712
# -*- coding: utf-8 -*- """ Modules to support data reduction in Python. The main purpose of the base module ``Data_Reduction`` is to provide a suplerclass with a good set of attributes and methods to cover all common needs. The base module is also able to read data from a text file as a ``numpy`` structured array. ...
# -*- coding: utf-8 -*- """ Modules to support data reduction in Python. The main purpose of the base module ``Data_Reduction`` is to provide a suplerclass with a good set of attributes and methods to cover all common needs. The base module is also able to read data from a text file as a ``numpy`` structured array. ...
en
0.713471
# -*- coding: utf-8 -*- Modules to support data reduction in Python. The main purpose of the base module ``Data_Reduction`` is to provide a suplerclass with a good set of attributes and methods to cover all common needs. The base module is also able to read data from a text file as a ``numpy`` structured array. This...
3.493397
3
PyGRB/__init__.py
HughPaynter/PyGRB
0
8713
""" PyGRB. A GRB light-curve analysis package. """ __version__ = "0.0.5" __author__ = '<NAME>' from . import backend from . import fetch from . import main from . import postprocess from . import preprocess
""" PyGRB. A GRB light-curve analysis package. """ __version__ = "0.0.5" __author__ = '<NAME>' from . import backend from . import fetch from . import main from . import postprocess from . import preprocess
en
0.767558
PyGRB. A GRB light-curve analysis package.
0.715536
1
src/config.py
john9384/PyblogRestAPI
0
8714
import os from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get('EMAIL_USERNAME') MAIL_P...
import os from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get('EMAIL_USERNAME') MAIL_P...
none
1
1.83995
2
Context_Guided_RelRep/train.py
Huda-Hakami/Context-Guided-Relation-Embeddings
1
8715
import numpy as np from wordreps import WordReps from algebra import cosine, normalize import tensorflow as tf import random from dataset import DataSet import CGRE_Model from Eval import eval_SemEval import sklearn.preprocessing # ============ End Imports ============ class Training(): def __init__(self): # Compo...
import numpy as np from wordreps import WordReps from algebra import cosine, normalize import tensorflow as tf import random from dataset import DataSet import CGRE_Model from Eval import eval_SemEval import sklearn.preprocessing # ============ End Imports ============ class Training(): def __init__(self): # Compo...
en
0.62083
# ============ End Imports ============ # Compositional relation embeddings (G1) Hyperparameters #boolean variable T/F for batch normalization on G1 MLP # L2 regularization coefficient # 1.0 means no Dropout applied during training on G1 # LSTM pattern encoding (G2) Hyperparameters # 1.0 means no Dropout applied during...
2.436919
2
synch_integrate.py
HerculesJack/grtrans
25
8716
<filename>synch_integrate.py from radtrans_integrate import radtrans_integrate from polsynchemis import polsynchemis import numpy as np import scipy.integrate # calculate synchrotron emissivity for given coefficients def synch_jarho(nu,n,B,T,theta): if ((np.isscalar(nu)==False) & (np.isscalar(n)==True)): n...
<filename>synch_integrate.py from radtrans_integrate import radtrans_integrate from polsynchemis import polsynchemis import numpy as np import scipy.integrate # calculate synchrotron emissivity for given coefficients def synch_jarho(nu,n,B,T,theta): if ((np.isscalar(nu)==False) & (np.isscalar(n)==True)): n...
en
0.650102
# calculate synchrotron emissivity for given coefficients
2.194252
2
actions/lib/Template_Parser.py
pjimmybrcd/campus_ztp_nps
0
8717
<gh_stars>0 """ Copyright 2016 Brocade Communications Systems, 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...
""" Copyright 2016 Brocade Communications Systems, 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 i...
en
0.836286
Copyright 2016 Brocade Communications Systems, 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...
2.116847
2
lca_writer/data/loader.py
line-mind/lca_writer
1
8718
<reponame>line-mind/lca_writer import os __all__ = ['DATA_FOLDER', 'load_data'] DATA_FOLDER = os.path.dirname(os.path.abspath(__file__)) def load_data(name): """ Loads an Excel form from the data folder with the specified name. Parameters ---------- name : str The name of the form with...
import os __all__ = ['DATA_FOLDER', 'load_data'] DATA_FOLDER = os.path.dirname(os.path.abspath(__file__)) def load_data(name): """ Loads an Excel form from the data folder with the specified name. Parameters ---------- name : str The name of the form without file extension. """ ...
en
0.622142
Loads an Excel form from the data folder with the specified name. Parameters ---------- name : str The name of the form without file extension. # to prevent recursive import
2.94347
3
main.py
Dephilia/pipenv-docker-development
0
8719
var = "Docker" print(f"Hello {var} world!")
var = "Docker" print(f"Hello {var} world!")
none
1
1.312097
1
app/v1/utils/mixins.py
pndemo/yummy-recipes-api
0
8720
<gh_stars>0 """ Model mixin classes for auth, category and recipe modules """ from app import db # pylint: disable=C0103 # pylint: disable=E1101 class BaseMixin(object): """ Define the 'BaseModel' mapped to all database tables. """ id = db.Column(db.Integer, primary_key=True, autoincrement=True) def sa...
""" Model mixin classes for auth, category and recipe modules """ from app import db # pylint: disable=C0103 # pylint: disable=E1101 class BaseMixin(object): """ Define the 'BaseModel' mapped to all database tables. """ id = db.Column(db.Integer, primary_key=True, autoincrement=True) def save(self): ...
en
0.629719
Model mixin classes for auth, category and recipe modules # pylint: disable=C0103 # pylint: disable=E1101 Define the 'BaseModel' mapped to all database tables. Save to database table Delete from database table Database logging of data manipulation timestamps.
2.540699
3
apps/dash-port-analytics/app/ui/tab_map_controls.py
JeroenvdSande/dash-sample-apps
2,332
8721
<reponame>JeroenvdSande/dash-sample-apps import dash_core_components as dcc import dash_html_components as html from config import strings def make_tab_port_map_controls( port_arr: list, port_val: str, vessel_types_arr: list, vessel_type_val: str, year_arr: list, year_val: int, month_arr: ...
import dash_core_components as dcc import dash_html_components as html from config import strings def make_tab_port_map_controls( port_arr: list, port_val: str, vessel_types_arr: list, vessel_type_val: str, year_arr: list, year_val: int, month_arr: list, month_val: int, ) -> html.Div: ...
en
0.404029
Returns a HTML div of user controls found on top of the map tab. :param port_arr: list, all possible ports :param port_val: str, current port value :param vessel_types_arr: list, all possible vessel types :param vessel_type_val: str, current vessel type value :param year_arr: list, all possible yea...
2.771475
3
subs2srs/gui/state.py
TFarla/subs2srs-cross-platform
3
8722
<filename>subs2srs/gui/state.py from typing import List from subs2srs.core.preview_item import PreviewItem class StatePreview: items: List[PreviewItem] = [] inactive_items = set() def __init__(self): super().__init__() self.items = [] self.inactive_items = set() self.audio...
<filename>subs2srs/gui/state.py from typing import List from subs2srs.core.preview_item import PreviewItem class StatePreview: items: List[PreviewItem] = [] inactive_items = set() def __init__(self): super().__init__() self.items = [] self.inactive_items = set() self.audio...
none
1
2.324013
2
sync_ends/main.py
nirav1997/sync_ends
0
8723
<reponame>nirav1997/sync_ends import sys sys.path.append("..") from src.sync_ends_service import SyncEnd from src.parser import Parser def main(): # get the arguments from commadn line parser = Parser() collection_name, api_key, trigger_interval, slack_channel, slack_token = parser.get_argumenets() ...
import sys sys.path.append("..") from src.sync_ends_service import SyncEnd from src.parser import Parser def main(): # get the arguments from commadn line parser = Parser() collection_name, api_key, trigger_interval, slack_channel, slack_token = parser.get_argumenets() sync_end = SyncEnd(api_key, co...
en
0.637058
# get the arguments from commadn line
2.144802
2
graphql_compiler/compiler/workarounds/orientdb_query_execution.py
0xflotus/graphql-compiler
0
8724
# Copyright 2018-present Kensho Technologies, LLC. """Workarounds for OrientDB scheduler issue that causes poor query planning for certain queries. For purposes of query planning, the OrientDB query planner ignores "where:" clauses that hit indexes but do not use the "=" operator. For example, "CONTAINS" can be used t...
# Copyright 2018-present Kensho Technologies, LLC. """Workarounds for OrientDB scheduler issue that causes poor query planning for certain queries. For purposes of query planning, the OrientDB query planner ignores "where:" clauses that hit indexes but do not use the "=" operator. For example, "CONTAINS" can be used t...
en
0.914852
# Copyright 2018-present Kensho Technologies, LLC. Workarounds for OrientDB scheduler issue that causes poor query planning for certain queries. For purposes of query planning, the OrientDB query planner ignores "where:" clauses that hit indexes but do not use the "=" operator. For example, "CONTAINS" can be used to c...
2.010179
2
traffic_light/core.py
ofalk/cleware-traffic-light
0
8725
from enum import IntEnum import functools import usb.core import usb.util from traffic_light.error import TrafficLightError, MultipleTrafficLightsError BM_REQUEST_TYPE = 0x21 B_REQUEST = 0x09 W_VALUE = 0x200 W_INDEX = 0x00 ID_VENDOR = 0x0d50 ID_PRODUCT = 0x0008 INTERFACE = 0 class Color(IntEnum): RED = 0x10 ...
from enum import IntEnum import functools import usb.core import usb.util from traffic_light.error import TrafficLightError, MultipleTrafficLightsError BM_REQUEST_TYPE = 0x21 B_REQUEST = 0x09 W_VALUE = 0x200 W_INDEX = 0x00 ID_VENDOR = 0x0d50 ID_PRODUCT = 0x0008 INTERFACE = 0 class Color(IntEnum): RED = 0x10 ...
en
0.79782
Attaches the device back to the kernel Detaches the device from to kernel so it can be used Returns the raw iterator of all found traffic lights Prints a list of all connected traffic lights Returns a list of ClewareTrafficLight instances Sets the given state and color of the attached traffic light Attribute: ...
2.919528
3
sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_analyze_orchestration_app_luis_response_async.py
dubiety/azure-sdk-for-python
1
8726
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ """ FILE: sample_analyze_orchestration_app_luis_response_async.py DESCRIPTION: This sample demonstrates how to analyze user query using an orchestra...
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ """ FILE: sample_analyze_orchestration_app_luis_response_async.py DESCRIPTION: This sample demonstrates how to analyze user query using an orchestra...
en
0.659231
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ FILE: sample_analyze_orchestration_app_luis_response_async.py DESCRIPTION: This sample demonstrates how to analyze user query using an orchestration ...
1.953416
2
src/sunstruck/schemas/__init__.py
la-mar/sunstruck-api
3
8727
# flake8: noqa from schemas.client_credentials import * from schemas.message import * from schemas.token import * from schemas.user import *
# flake8: noqa from schemas.client_credentials import * from schemas.message import * from schemas.token import * from schemas.user import *
it
0.238973
# flake8: noqa
1.094032
1
intro/deploy.py
terziev-viktor/SolidityCourse
0
8728
<gh_stars>0 import json from web3 import Web3 from solcx import compile_standard, install_solc with open("./SimpleStorage.sol", "r") as file: simple_storage_src = file.read() # install solcx install_solc("0.8.0") # compile the source compiled_sol = compile_standard( { "language": "Solidity", ...
import json from web3 import Web3 from solcx import compile_standard, install_solc with open("./SimpleStorage.sol", "r") as file: simple_storage_src = file.read() # install solcx install_solc("0.8.0") # compile the source compiled_sol = compile_standard( { "language": "Solidity", "sources": ...
en
0.791989
# install solcx # compile the source # getting the bytecode # getting the abi # connecting to ganache # Create the contract in python # Get the latest test transaction # 1. Build a transaction # 2. Sing the transaction # 3. Send the transaction # confirm transaction is received # working on-chain
2.215618
2
noise/extras/meta/protocol/protocol.py
mgp25/noise
6
8729
<reponame>mgp25/noise from noise.dh.dh import DH from noise.cipher.cipher import Cipher from noise.hash.hash import Hash from noise.processing.handshakepatterns.handshakepattern import HandshakePattern from noise.processing.impl.handshakestate import HandshakeState from noise.processing.impl.symmetricstate import Symm...
from noise.dh.dh import DH from noise.cipher.cipher import Cipher from noise.hash.hash import Hash from noise.processing.handshakepatterns.handshakepattern import HandshakePattern from noise.processing.impl.handshakestate import HandshakeState from noise.processing.impl.symmetricstate import SymmetricState from noise....
en
0.576752
:param pattern: :type pattern: :param dh: :type dh: :param cipher: :type cipher: :param hash: :type hash: # type: HandshakePattern # type: DH # type: Cipher # type: Hash # type: bool :param cipher: :type cipher: Cipher :return: :rtype: Ciph...
2.33459
2
info_popup.py
cartazio/SublimeHaskell
2
8730
import urllib.parse import webbrowser import json from xml.etree import ElementTree import sublime import SublimeHaskell.sublime_haskell_common as Common import SublimeHaskell.internals.utils as Utils import SublimeHaskell.internals.unicode_opers as UnicodeOpers import SublimeHaskell.symbols as symbols import Sublim...
import urllib.parse import webbrowser import json from xml.etree import ElementTree import sublime import SublimeHaskell.sublime_haskell_common as Common import SublimeHaskell.internals.utils as Utils import SublimeHaskell.internals.unicode_opers as UnicodeOpers import SublimeHaskell.symbols as symbols import Sublim...
en
0.54856
# Unused module variable: # style_header = "<style>" \ # "a { text-decoration: underline; }" \ # ".type { color: red; }" \ # ".tyvar { color: blue; }" \ # ".operator { color: green; }" \ # ".comment { color: gray; font-style: italic; }" \ # ".docs { color: gray; }" \ # "</style>" Loads and h...
2.177699
2
modules/google_home_lights.py
artizanatweb/ghome-assistant
0
8731
<reponame>artizanatweb/ghome-assistant #!/usr/bin/env python # Copyright (C) 2017 Seeed Technology Limited # # 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/licen...
#!/usr/bin/env python # Copyright (C) 2017 Seeed Technology Limited # # 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 ...
en
0.832492
#!/usr/bin/env python # Copyright (C) 2017 Seeed Technology Limited # # 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 a...
2.753712
3
python/modules_packages_libraries/models/animal_kigdom/animals.py
aloa04/practice
0
8732
class Animal(): edad:int patas:int ruido:str nombre: str kgComida: float = 0 def __init__(self, edad, patas, ruido, nombre): self.edad =edad self.patas = patas self.ruido = ruido self.nombre = nombre def comer(self, alimento): self.kgComida += alimento...
class Animal(): edad:int patas:int ruido:str nombre: str kgComida: float = 0 def __init__(self, edad, patas, ruido, nombre): self.edad =edad self.patas = patas self.ruido = ruido self.nombre = nombre def comer(self, alimento): self.kgComida += alimento...
none
1
3.424185
3
tensortools/optimize/mncp_hals.py
klmcguir/tensortools
0
8733
""" Nonnegative CP decomposition by Hierarchical alternating least squares (HALS). With support for missing data. """ import numpy as np import scipy as sci from scipy import linalg from tensortools.operations import unfold, khatri_rao from tensortools.tensors import KTensor from tensortools.optimize import FitResult...
""" Nonnegative CP decomposition by Hierarchical alternating least squares (HALS). With support for missing data. """ import numpy as np import scipy as sci from scipy import linalg from tensortools.operations import unfold, khatri_rao from tensortools.tensors import KTensor from tensortools.optimize import FitResult...
en
0.530111
Nonnegative CP decomposition by Hierarchical alternating least squares (HALS). With support for missing data. Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least Squares (HALS) Method. Supports missing data. Parameters ---------- X : (I_1, ..., I_N) array_like A real array w...
2.508288
3
raredecay/tools/data_tools.py
jonas-eschle/raredecay
7
8734
""" @author: <NAME> "Mayou36" DEPRECEATED! USE OTHER MODULES LIKE rd.data, rd.ml, rd.reweight, rd.score and rd.stat DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED! Contains several tools to convert, load, save and plot data """ import warnings import os import copy import pandas as pd import numpy...
""" @author: <NAME> "Mayou36" DEPRECEATED! USE OTHER MODULES LIKE rd.data, rd.ml, rd.reweight, rd.score and rd.stat DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED! Contains several tools to convert, load, save and plot data """ import warnings import os import copy import pandas as pd import numpy...
en
0.643366
@author: <NAME> "Mayou36" DEPRECEATED! USE OTHER MODULES LIKE rd.data, rd.ml, rd.reweight, rd.score and rd.stat DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED!DEPRECEATED! Contains several tools to convert, load, save and plot data # both produce error (27.07.2016) when importing them if run from main.py. # No pr...
1.916833
2
toontown/coghq/boardbothq/BoardOfficeManagerAI.py
LittleNed/toontown-stride
1
8735
<reponame>LittleNed/toontown-stride<filename>toontown/coghq/boardbothq/BoardOfficeManagerAI.py from direct.directnotify import DirectNotifyGlobal import DistributedBoardOfficeAI from toontown.toonbase import ToontownGlobals from toontown.coghq.boardbothq import BoardOfficeLayout from direct.showbase import DirectObject...
from direct.directnotify import DirectNotifyGlobal import DistributedBoardOfficeAI from toontown.toonbase import ToontownGlobals from toontown.coghq.boardbothq import BoardOfficeLayout from direct.showbase import DirectObject import random class BoardOfficeManagerAI(DirectObject.DirectObject): notify = DirectNotif...
none
1
2.272752
2
ansiblemetrics/utils.py
radon-h2020/AnsibleMetrics
1
8736
<reponame>radon-h2020/AnsibleMetrics from typing import Union def key_value_list(d: Union[dict, list], key=None) -> list: """ This function iterates over all the key-value pairs of a dictionary and returns a list of tuple (key, value) where the key contain only primitive value (i.e., no list or dict), e.g., s...
from typing import Union def key_value_list(d: Union[dict, list], key=None) -> list: """ This function iterates over all the key-value pairs of a dictionary and returns a list of tuple (key, value) where the key contain only primitive value (i.e., no list or dict), e.g., string, number etc. d -- a diction...
en
0.635071
This function iterates over all the key-value pairs of a dictionary and returns a list of tuple (key, value) where the key contain only primitive value (i.e., no list or dict), e.g., string, number etc. d -- a dictionary to iterate through Returns a list of all the keys of a dictionary (duplicates included) d -...
4.115702
4
yampy/apis/groups.py
Kunal-Shah-Bose/yam-python
0
8737
<reponame>Kunal-Shah-Bose/yam-python from yampy.apis.utils import ArgumentConverter, none_filter, stringify_booleans from yampy.models import extract_id class GroupsAPI(object): """ Provides an interface for accessing the groups related endpoints of the Yammer API. You should not instantiate this class d...
from yampy.apis.utils import ArgumentConverter, none_filter, stringify_booleans from yampy.models import extract_id class GroupsAPI(object): """ Provides an interface for accessing the groups related endpoints of the Yammer API. You should not instantiate this class directly; use the :meth:`yampy.Yam...
en
0.728803
Provides an interface for accessing the groups related endpoints of the Yammer API. You should not instantiate this class directly; use the :meth:`yampy.Yammer.groups` method instead. Initializes a new GroupsAPI that will use the given client object to make HTTP requests. Returns all the groups in the c...
2.824139
3
phy/gui/actions.py
ycanerol/phy
118
8738
<filename>phy/gui/actions.py # -*- coding: utf-8 -*- """Actions and snippets.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import inspect from functools import partial, wraps import loggin...
<filename>phy/gui/actions.py # -*- coding: utf-8 -*- """Actions and snippets.""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import inspect from functools import partial, wraps import loggin...
en
0.681662
# -*- coding: utf-8 -*- Actions and snippets. # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Snippet parsing utilit...
2.36637
2
PP4E-Examples-1.4/Examples/PP4E/Tools/cleanpyc.py
AngelLiang/PP4E
0
8739
""" delete all .pyc bytecode files in a directory tree: use the command line arg as root if given, else current working dir """ import os, sys findonly = False rootdir = os.getcwd() if len(sys.argv) == 1 else sys.argv[1] found = removed = 0 for (thisDirLevel, subsHere, filesHere) in os.walk(rootdir): for filename...
""" delete all .pyc bytecode files in a directory tree: use the command line arg as root if given, else current working dir """ import os, sys findonly = False rootdir = os.getcwd() if len(sys.argv) == 1 else sys.argv[1] found = removed = 0 for (thisDirLevel, subsHere, filesHere) in os.walk(rootdir): for filename...
en
0.866688
delete all .pyc bytecode files in a directory tree: use the command line arg as root if given, else current working dir
2.971683
3
apps.py
louxfaure/sudoc_recouv
1
8740
<reponame>louxfaure/sudoc_recouv from django.apps import AppConfig class SudocRecouvConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'sudoc_recouv' verbose_name = 'Analyses de recouvrement SUDOC'
from django.apps import AppConfig class SudocRecouvConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'sudoc_recouv' verbose_name = 'Analyses de recouvrement SUDOC'
none
1
1.236604
1
src/states.py
amancevice/terraform-aws-slack-interactive-components
24
8741
import boto3 from logger import logger class States: def __init__(self, boto3_session=None): self.boto3_session = boto3_session or boto3.Session() self.client = self.boto3_session.client('stepfunctions') def fail(self, task_token, error, cause): params = dict(taskToken=task_token, er...
import boto3 from logger import logger class States: def __init__(self, boto3_session=None): self.boto3_session = boto3_session or boto3.Session() self.client = self.boto3_session.client('stepfunctions') def fail(self, task_token, error, cause): params = dict(taskToken=task_token, er...
none
1
2.467343
2
apps/controllerx/cx_core/type/light_controller.py
clach04/controllerx
0
8742
from typing import Any, Dict, Optional, Type, Union from cx_const import Light, PredefinedActionsMapping from cx_core.color_helper import get_color_wheel from cx_core.controller import action from cx_core.feature_support.light import LightSupport from cx_core.integration import EventData from cx_core.integration.decon...
from typing import Any, Dict, Optional, Type, Union from cx_const import Light, PredefinedActionsMapping from cx_core.color_helper import get_color_wheel from cx_core.controller import action from cx_core.feature_support.light import LightSupport from cx_core.integration import EventData from cx_core.integration.decon...
en
0.846925
# Once the minimum supported version of Python is 3.8, # we can declare the ColorMode as a Literal # ColorMode = Literal["auto", "xy_color", "color_temp"] This is the main class that controls the lights for different devices. Type of actions: - On/Off/Toggle - Brightness click and hold - Col...
2.642417
3
kts/core/types.py
konodyuk/kts
18
8743
from typing import Union import pandas as pd from kts.core.frame import KTSFrame AnyFrame = Union[pd.DataFrame, KTSFrame]
from typing import Union import pandas as pd from kts.core.frame import KTSFrame AnyFrame = Union[pd.DataFrame, KTSFrame]
none
1
1.69837
2
krispy/mod_user/models.py
jlaura/krispy
2
8744
<filename>krispy/mod_user/models.py from app import db from flask.ext.login import UserMixin class User(UserMixin, db.Model): __tablename__ = 'oauth2users' id = db.Column(db.Integer, primary_key=True) social_id = db.Column(db.String(64), nullable=False, unique=True) nickname = db.Column(db.String(64), ...
<filename>krispy/mod_user/models.py from app import db from flask.ext.login import UserMixin class User(UserMixin, db.Model): __tablename__ = 'oauth2users' id = db.Column(db.Integer, primary_key=True) social_id = db.Column(db.String(64), nullable=False, unique=True) nickname = db.Column(db.String(64), ...
none
1
2.216953
2
blog_app/blog/views.py
flxj/Django_blog
1
8745
<gh_stars>1-10 import markdown from comments.forms import CommentForm,BookCommentForm,MovieCommentForm from django.shortcuts import render, get_object_or_404 from.models import Post,Category,Tag, Book,Movie #from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.utils.tex...
import markdown from comments.forms import CommentForm,BookCommentForm,MovieCommentForm from django.shortcuts import render, get_object_or_404 from.models import Post,Category,Tag, Book,Movie #from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.utils.text import slugif...
zh
0.896648
#from django.http import HttpResponse def index(request): #post_list = Post.objects.all().order_by('-created_time') post_list = Post.objects.all() return render(request, 'blog/index.html', context={'post_list': post_list}) 在视图函数中将模板变量传递给模板是通过给 render 函数的 context 参数传递一个字典实现的, 例如 render(request, 'blog...
2.407009
2
src/command_modules/azure-cli-security/azure/cli/command_modules/security/_params.py
jfcoz/azure-cli
1
8746
# -------------------------------------------------------------------------------------------- # 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.466718
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1.776854
2
utils/path_utils.py
kuyu12/pygame_fight_game
1
8747
import sys IMAGES_PATH = sys.path[1] + "/Images" BACKGROUND_IMAGES_PATH = IMAGES_PATH + '/background' USER_INFO_BACKGROUND_PATH = BACKGROUND_IMAGES_PATH+"/blue_background.jpg" SPRINT_IMAGE_PATH = IMAGES_PATH + '/sprite' PROFILE_IMAGES_PATH = IMAGES_PATH + '/profile' CONFIGURATION_FILES_PATH = sys.path[1] + "/configur...
import sys IMAGES_PATH = sys.path[1] + "/Images" BACKGROUND_IMAGES_PATH = IMAGES_PATH + '/background' USER_INFO_BACKGROUND_PATH = BACKGROUND_IMAGES_PATH+"/blue_background.jpg" SPRINT_IMAGE_PATH = IMAGES_PATH + '/sprite' PROFILE_IMAGES_PATH = IMAGES_PATH + '/profile' CONFIGURATION_FILES_PATH = sys.path[1] + "/configur...
none
1
1.717004
2
tests/models/test_transformers.py
Alicegaz/torchok
8
8748
import unittest import torch from parameterized import parameterized from src.constructor import create_backbone from src.models.backbones.utils import list_models from .test_segmentation import example_backbones def inp(bsize, in_ch, w, h): return torch.ones(bsize, in_ch, w, h) class TestBackboneCorrectness(...
import unittest import torch from parameterized import parameterized from src.constructor import create_backbone from src.models.backbones.utils import list_models from .test_segmentation import example_backbones def inp(bsize, in_ch, w, h): return torch.ones(bsize, in_ch, w, h) class TestBackboneCorrectness(...
none
1
2.355238
2
aiogram/types/inline_query.py
SvineruS/aiogram
1
8749
import typing from . import base from . import fields from .inline_query_result import InlineQueryResult from .location import Location from .user import User class InlineQuery(base.TelegramObject): """ This object represents an incoming inline query. When the user sends an empty query, your bot could r...
import typing from . import base from . import fields from .inline_query_result import InlineQueryResult from .location import Location from .user import User class InlineQuery(base.TelegramObject): """ This object represents an incoming inline query. When the user sends an empty query, your bot could r...
en
0.674216
This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. https://core.telegram.org/bots/api#inlinequery Use this method to send answers to an inline query. No more than 50 results per query are allowed. Source...
2.707727
3
app/app.py
shaswat01/Disaster_Response_ETL
0
8750
import nltk import json import plotly import pandas as pd import plotly.graph_objects as go from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize nltk.download(['punkt','wordnet']) from flask import Flask from flask import render_template, request, jsonify from plotly.graph_objs import Bar, H...
import nltk import json import plotly import pandas as pd import plotly.graph_objects as go from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize nltk.download(['punkt','wordnet']) from flask import Flask from flask import render_template, request, jsonify from plotly.graph_objs import Bar, H...
en
0.690963
# load data # load model # index webpage displays cool visuals and receives user input text for model # extract data needed for visuals # Viz 1 # Viz 2 # Viz 3 # create visuals # encode plotly graphs in JSON # render web page with plotly graphs # web page that handles user query and displays model results # save user i...
2.800805
3
tools/mo/openvino/tools/mo/front/mxnet/mx_reshape_reverse.py
pazamelin/openvino
1
8751
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.mxnet.mx_reshape_to_reshape import MXReshapeToReshape from openvino.tools.mo.ops.Reverse import Reverse from openvino.tools.mo.ops.mxreshape import MXReshape from openvino.tools.mo.front.c...
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.mxnet.mx_reshape_to_reshape import MXReshapeToReshape from openvino.tools.mo.ops.Reverse import Reverse from openvino.tools.mo.ops.mxreshape import MXReshape from openvino.tools.mo.front.c...
en
0.607493
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 If reshape layer with reverse True, special values will inferred from right to left. The Replacer simulate the behavior. The replaced subgraph reverse input data and special dims, and after reshape reverse output result to backwar...
2.262639
2
Python/Simulation/Numerical_Methods/test_cubic_spline_solve.py
MattMarti/Lambda-Trajectory-Sim
0
8752
<reponame>MattMarti/Lambda-Trajectory-Sim import unittest; import numpy as np; import scipy as sp; from cubic_spline_solve import cubic_spline_solve; from cubic_spline_fun import cubic_spline_fun; class Test_cubic_spline_solve(unittest.TestCase): ''' Test_cubicsplineSolve Test case for the cubic splin...
import unittest; import numpy as np; import scipy as sp; from cubic_spline_solve import cubic_spline_solve; from cubic_spline_fun import cubic_spline_fun; class Test_cubic_spline_solve(unittest.TestCase): ''' Test_cubicsplineSolve Test case for the cubic spline solver function. This function just solv...
en
0.698745
Test_cubicsplineSolve Test case for the cubic spline solver function. This function just solves for the spline data, so that the spline can be precomputed before code is run. This improves code performance by removing the need to invert a matrix every time the spline function is called. @a...
3.036769
3
PassWord.py
IQUBE-X/passGenerator
1
8753
# PassWord - The Safe Password Generator App! # importing the tkinter module for GUI from tkinter import * # importing the message box widget from tkinter from tkinter import messagebox # importing sqlite3 for database import sqlite3 # importing random for password generation import random # creatin...
# PassWord - The Safe Password Generator App! # importing the tkinter module for GUI from tkinter import * # importing the message box widget from tkinter from tkinter import messagebox # importing sqlite3 for database import sqlite3 # importing random for password generation import random # creatin...
en
0.789507
# PassWord - The Safe Password Generator App! # importing the tkinter module for GUI # importing the message box widget from tkinter # importing sqlite3 for database # importing random for password generation # creating fonts # creating a database and establishing a connection # creating a cursor to navigate through d...
4.522357
5
1805_number_of_different_integers_in_a_string.py
hotternative/leetcode
0
8754
<filename>1805_number_of_different_integers_in_a_string.py from string import ascii_lowercase ts = 'a123bc34d8ef34' cur = [] res = set() for c in ts: if c in ascii_lowercase: if cur: s = ''.join(cur) res.add(int(s)) cur = [] else: cur.append(c) else: if...
<filename>1805_number_of_different_integers_in_a_string.py from string import ascii_lowercase ts = 'a123bc34d8ef34' cur = [] res = set() for c in ts: if c in ascii_lowercase: if cur: s = ''.join(cur) res.add(int(s)) cur = [] else: cur.append(c) else: if...
none
1
3.476522
3
app.py
ahmedriaz9908/memeapiiz
0
8755
from flask import Flask, render_template, jsonify from reddit_handler import * app = Flask(__name__) meme_subreddits = ['izlam'] @app.route('/') def index(): return render_template('index.html') @app.route('/meme') def one_post(): sub = random.choice(meme_subreddits) re = get_posts(sub...
from flask import Flask, render_template, jsonify from reddit_handler import * app = Flask(__name__) meme_subreddits = ['izlam'] @app.route('/') def index(): return render_template('index.html') @app.route('/meme') def one_post(): sub = random.choice(meme_subreddits) re = get_posts(sub...
none
1
2.698476
3
10_compare_between_main_product_pages.py
e-davydenkova/SeleniumWebDriver_Training
0
8756
import pytest from selenium import webdriver import re @pytest.fixture def driver(request): wd = webdriver.Chrome() wd.get("http://localhost/litecart/en/") request.addfinalizer(wd.quit) return wd # check that product names are identical on the main page and on product page def test_product_names(driv...
import pytest from selenium import webdriver import re @pytest.fixture def driver(request): wd = webdriver.Chrome() wd.get("http://localhost/litecart/en/") request.addfinalizer(wd.quit) return wd # check that product names are identical on the main page and on product page def test_product_names(driv...
en
0.914373
# check that product names are identical on the main page and on product page # get a product name on the main page # get a product name on a product page # check that prices (regular and campaign) are identical on the main page and on product page # get a regular price on the main page # get a campaign price on the ma...
2.665517
3
pyrite/llvm.py
iahuang/pyrite
0
8757
import shutil from pyrite import fs from pyrite.command_line import run_command from pyrite.errors import UserError from pyrite.globals import Globals from os.path import join class LLVMInterface: _clang_path: str def __init__(self): self._clang_path = self._get_clang_path() def _get_clang_path(s...
import shutil from pyrite import fs from pyrite.command_line import run_command from pyrite.errors import UserError from pyrite.globals import Globals from os.path import join class LLVMInterface: _clang_path: str def __init__(self): self._clang_path = self._get_clang_path() def _get_clang_path(s...
en
0.736421
Compile the contents of [source] as LLVM IR code, outputting a binary specified by [output_path]. If any errors arise in compilation, raise an error. Pyrite uses a temporary working "build" directory to store files needed for LLVM/Clang
2.373717
2
bag_recursive.py
eduardogerentklein/Algoritmos-Geneticos
0
8758
maxWeight = 30 value = [15, 7, 10, 5, 8, 17] weight = [15, 3, 2, 5, 9, 20] def bag(pos, selected): # calcula o total totalValue = 0 pesoTotal = 0 for i in selected: totalValue += value[i] pesoTotal += weight[i] if pesoTotal > maxWeight: return (0,0) if pos >= len(weight): return (totalValue, pesoT...
maxWeight = 30 value = [15, 7, 10, 5, 8, 17] weight = [15, 3, 2, 5, 9, 20] def bag(pos, selected): # calcula o total totalValue = 0 pesoTotal = 0 for i in selected: totalValue += value[i] pesoTotal += weight[i] if pesoTotal > maxWeight: return (0,0) if pos >= len(weight): return (totalValue, pesoT...
en
0.364433
# calcula o total
3.583946
4
train.py
MEfeTiryaki/trpo
2
8759
<reponame>MEfeTiryaki/trpo import argparse from itertools import count import signal import sys import os import time import numpy as np import gym import torch import torch.autograd as autograd from torch.autograd import Variable import scipy.optimize import matplotlib.pyplot as plt from value import Value from p...
import argparse from itertools import count import signal import sys import os import time import numpy as np import gym import torch import torch.autograd as autograd from torch.autograd import Variable import scipy.optimize import matplotlib.pyplot as plt from value import Value from policy import Policy from ut...
en
0.57737
# Algorithm Parameters # Value Function Learning Parameters # TODO: implement # Policy Optimization parameters # Environment parameters # Training length # Rendering # Logging # Load Signal Handler to save the networks when shutting down via ctrl+C Parameters: Returns: Get the batch data and calculate value,ret...
2.054693
2
task3/task3_xgb_cv.py
meck93/intro_ml
0
8760
from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import f_classif, SelectKBest import numpy as np import pandas as pd import os mingw_path = 'C:\\Program Files\\mingw-w64\\x86_64-7.2.0-posix...
from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import f_classif, SelectKBest import numpy as np import pandas as pd import os mingw_path = 'C:\\Program Files\\mingw-w64\\x86_64-7.2.0-posix...
en
0.557208
# Constants # read training file # test_data = pd.read_hdf(FILE_PATH_TRAIN, "test") # training data # extracting the x-values # extracting the y-values # training the scaler # scaling the training and test data # feature selection # splitting the training set into a training & validation set # training, evaluation and ...
2.840855
3
discovery-provider/src/queries/get_plays_metrics.py
atticwip/audius-protocol
429
8761
<gh_stars>100-1000 import logging import time from sqlalchemy import func, desc from src.models import Play from src.utils import db_session logger = logging.getLogger(__name__) def get_plays_metrics(args): """ Returns metrics for play counts Args: args: dict The parsed args from the request ...
import logging import time from sqlalchemy import func, desc from src.models import Play from src.utils import db_session logger = logging.getLogger(__name__) def get_plays_metrics(args): """ Returns metrics for play counts Args: args: dict The parsed args from the request args.start_tim...
en
0.740954
Returns metrics for play counts Args: args: dict The parsed args from the request args.start_time: date The start of the query args.limit: number The max number of responses to return args.bucket_size: string A date_trunc operation to aggregate timestamps by Returns: Ar...
2.540101
3
CAutomation/settings.py
Rich9rd/CAutomation
0
8762
""" Django settings for CAutomation project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pat...
""" Django settings for CAutomation project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pat...
en
0.610859
Django settings for CAutomation project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ # Build paths ins...
1.843328
2
calculators/credit_card_calculator.py
wanderindev/financial-calculator-backend
2
8763
from .calculator import Calculator # noinspection PyTypeChecker class CreditCardCalculator(Calculator): def __init__(self, **kwargs): super(CreditCardCalculator, self).__init__(**kwargs) self.cc_debt = self.get_float(kwargs.get("cc_debt", 0)) self.add_c = self.get_float(kwargs.ge...
from .calculator import Calculator # noinspection PyTypeChecker class CreditCardCalculator(Calculator): def __init__(self, **kwargs): super(CreditCardCalculator, self).__init__(**kwargs) self.cc_debt = self.get_float(kwargs.get("cc_debt", 0)) self.add_c = self.get_float(kwargs.ge...
en
0.214864
# noinspection PyTypeChecker
3.12905
3
setup.py
phaustin/MyST-Parser
0
8764
"""myst-parser package setup.""" from importlib import import_module from setuptools import find_packages, setup setup( name="myst-parser", version=import_module("myst_parser").__version__, description=( "An extended commonmark compliant parser, " "with bridges to docutils & sphinx." ), lo...
"""myst-parser package setup.""" from importlib import import_module from setuptools import find_packages, setup setup( name="myst-parser", version=import_module("myst_parser").__version__, description=( "An extended commonmark compliant parser, " "with bridges to docutils & sphinx." ), lo...
en
0.387349
myst-parser package setup.
1.600544
2
python/tests/extractor/refmt.py
kho/cdec
114
8765
#!/usr/bin/env python import collections, sys lines = [] f = collections.defaultdict(int) fe = collections.defaultdict(lambda: collections.defaultdict(int)) for line in sys.stdin: tok = [x.strip() for x in line.split('|||')] count = int(tok[4]) f[tok[1]] += count fe[tok[1]][tok[2]] += count lines...
#!/usr/bin/env python import collections, sys lines = [] f = collections.defaultdict(int) fe = collections.defaultdict(lambda: collections.defaultdict(int)) for line in sys.stdin: tok = [x.strip() for x in line.split('|||')] count = int(tok[4]) f[tok[1]] += count fe[tok[1]][tok[2]] += count lines...
ru
0.26433
#!/usr/bin/env python
2.6582
3
blog/models.py
tomitokko/django-blog-with-astradb
3
8766
from django.db import models import uuid from datetime import datetime from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel # Create your models here. class PostModel(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4) title = column...
from django.db import models import uuid from datetime import datetime from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel # Create your models here. class PostModel(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4) title = column...
en
0.963489
# Create your models here.
2.496449
2
fedex/services/availability_commitment_service.py
miczone/python-fedex
0
8767
<filename>fedex/services/availability_commitment_service.py<gh_stars>0 """ Service Availability and Commitment Module This package contains the shipping methods defined by Fedex's ValidationAvailabilityAndCommitmentService WSDL file. Each is encapsulated in a class for easy access. For more details on each, refer to ...
<filename>fedex/services/availability_commitment_service.py<gh_stars>0 """ Service Availability and Commitment Module This package contains the shipping methods defined by Fedex's ValidationAvailabilityAndCommitmentService WSDL file. Each is encapsulated in a class for easy access. For more details on each, refer to ...
en
0.735403
Service Availability and Commitment Module This package contains the shipping methods defined by Fedex's ValidationAvailabilityAndCommitmentService WSDL file. Each is encapsulated in a class for easy access. For more details on each, refer to the respective class's documentation. This class allows you validate servi...
2.692755
3
xverse/transformer/_woe.py
gb-andreygsouza/XuniVerse
0
8768
import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin import scipy.stats.stats as stats import pandas.core.algorithms as algos #from sklearn.utils.validation import check_is_fitted from sklearn.utils import check_array from ..transformer import MonotonicBinning pd.options.mode...
import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin import scipy.stats.stats as stats import pandas.core.algorithms as algos #from sklearn.utils.validation import check_is_fitted from sklearn.utils import check_array from ..transformer import MonotonicBinning pd.options.mode...
en
0.687306
#from sklearn.utils.validation import check_is_fitted Weight of evidence transformation for categorical variables. For numeric variables, monotonic operation is provided as default with this package. Parameters ---------- feature_names: 'all' or list (default='all') list of features to pe...
2.821338
3
cupy/linalg/product.py
okapies/cupy
1
8769
<filename>cupy/linalg/product.py import numpy import six import cupy from cupy import core from cupy import internal from cupy.linalg.solve import inv from cupy.util import collections_abc matmul = core.matmul def dot(a, b, out=None): """Returns a dot product of two arrays. For arrays with more than one ...
<filename>cupy/linalg/product.py import numpy import six import cupy from cupy import core from cupy import internal from cupy.linalg.solve import inv from cupy.util import collections_abc matmul = core.matmul def dot(a, b, out=None): """Returns a dot product of two arrays. For arrays with more than one ...
en
0.731944
Returns a dot product of two arrays. For arrays with more than one axis, it computes the dot product along the last axis of ``a`` and the second-to-last axis of ``b``. This is just a matrix product if the both arrays are 2-D. For 1-D arrays, it uses their unique axis as an axis to take dot product over...
3.268448
3
fibo.py
aligoren/pyalgo
22
8770
<filename>fibo.py def fibo(n): return n <= 1 or fibo(n-1) + fibo(n-2) def fibo_main(): for n in range(1,47): res = fibo(n) print("%s\t%s" % (n, res)) fibo_main() # profiling result for 47 numbers # profile: python -m profile fibo.py """ -1273940835 function calls (275 primitive calls) in 18966.707 s...
<filename>fibo.py def fibo(n): return n <= 1 or fibo(n-1) + fibo(n-2) def fibo_main(): for n in range(1,47): res = fibo(n) print("%s\t%s" % (n, res)) fibo_main() # profiling result for 47 numbers # profile: python -m profile fibo.py """ -1273940835 function calls (275 primitive calls) in 18966.707 s...
en
0.267884
# profiling result for 47 numbers # profile: python -m profile fibo.py -1273940835 function calls (275 primitive calls) in 18966.707 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 90 0.000 0.000 0.001 0.000 cp857.py:18(encode) 1 ...
3.494306
3
trt_util/common.py
yihui8776/TensorRT-DETR
0
8771
<filename>trt_util/common.py # # Copyright (c) 2021, NVIDIA CORPORATION. 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....
<filename>trt_util/common.py # # Copyright (c) 2021, NVIDIA CORPORATION. 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....
en
0.761653
# # Copyright (c) 2021, NVIDIA CORPORATION. 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 appl...
2.002341
2
src/init.py
inpanel/inpanel-desktop
1
8772
#!/usr/bin/env python3 # -*- coding:utf-8-*- import tkinter.messagebox from tkinter import Button, Label, Tk from utils.functions import set_window_center from utils.sqlite_helper import DBHelper from inpanel import App class InitWindow(Tk): """初始化窗口""" def __init__(self): Tk.__init__(self) ...
#!/usr/bin/env python3 # -*- coding:utf-8-*- import tkinter.messagebox from tkinter import Button, Label, Tk from utils.functions import set_window_center from utils.sqlite_helper import DBHelper from inpanel import App class InitWindow(Tk): """初始化窗口""" def __init__(self): Tk.__init__(self) ...
zh
0.943025
#!/usr/bin/env python3 # -*- coding:utf-8-*- 初始化窗口 # 初始化成功的提示窗口 加载控件 初始化 # 默认用户 是否重试 初始化成功弹窗 打开应用程序
3.180834
3
Toolkits/CMake/hunter/packages/sugar/python/sugar/sugar_warnings_wiki_table_generator.py
roscopecoltran/SniperKit-Core
102
8773
<reponame>roscopecoltran/SniperKit-Core #!/usr/bin/env python3 # Copyright (c) 2014, <NAME> # All rights reserved. """ * Wiki table for `leathers` C++ project Expected format: ### Main table Name | Clang | GCC | MSVC | -----------------------------|----------|----------|------| sta...
#!/usr/bin/env python3 # Copyright (c) 2014, <NAME> # All rights reserved. """ * Wiki table for `leathers` C++ project Expected format: ### Main table Name | Clang | GCC | MSVC | -----------------------------|----------|----------|------| static-ctor-not-thread-safe | *no* | *n...
en
0.282369
#!/usr/bin/env python3 # Copyright (c) 2014, <NAME> # All rights reserved. * Wiki table for `leathers` C++ project Expected format: ### Main table Name | Clang | GCC | MSVC | -----------------------------|----------|----------|------| static-ctor-not-thread-safe | *no* | *no* ...
2.218365
2
neutron/plugins/ofagent/agent/ports.py
armando-migliaccio/neutron-1
0
8774
# Copyright (C) 2014 VA Linux Systems Japan K.K. # Copyright (C) 2014 <NAME> <yamamoto at valinux co jp> # 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 # # ...
# Copyright (C) 2014 VA Linux Systems Japan K.K. # Copyright (C) 2014 <NAME> <yamamoto at valinux co jp> # 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 # # ...
en
0.787011
# Copyright (C) 2014 VA Linux Systems Japan K.K. # Copyright (C) 2014 <NAME> <yamamoto at valinux co jp> # 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 # # ...
1.857872
2
pdf/wechat/step.py
damaainan/html2md
0
8775
# -*- coding=utf-8 -*- from zwechathihu.mypdf import GenPdf from db.mysqlite import simpleToolSql data=[{"url": "http://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484852&idx=1&sn=85b50b8b0470bb4897e517955f4e5002&chksm=9bd7fbbcaca072aa75e2a241064a403fde1e579d57ab846cd8537a54253ceb2c8b93cc3bf38e&scene=21#wechat_...
# -*- coding=utf-8 -*- from zwechathihu.mypdf import GenPdf from db.mysqlite import simpleToolSql data=[{"url": "http://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484852&idx=1&sn=85b50b8b0470bb4897e517955f4e5002&chksm=9bd7fbbcaca072aa75e2a241064a403fde1e579d57ab846cd8537a54253ceb2c8b93cc3bf38e&scene=21#wechat_...
en
0.366692
# -*- coding=utf-8 -*- #wechat_redirect", "name": "001学习算法和刷题的框架思维"} # path = '***/' || '' # for val in data: # # print(val["url"]) # # print(val["name"]) # pdf = GenPdf() # title = val["name"].replace("/", "-") # print(title) # pdf.deal(val["url"], title, '') # sql = simpleToolSql("url") # # s...
2.798182
3
pipeline/validators/handlers.py
ZhuoZhuoCrayon/bk-nodeman
31
8776
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
en
0.863967
# -*- coding: utf-8 -*- Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compli...
1.57152
2
NumPy/Array Basics/Random Shuffle/tests/test_task.py
jetbrains-academy/Python-Libraries-NumPy
0
8777
import unittest import numpy as np from task import arr, permuted_2d, fully_random class TestCase(unittest.TestCase): def test_shape(self): self.assertEqual((5, 20), arr.shape, msg="Wrong shape of the array 'arr'.") self.assertEqual((5, 20), permuted_2d.shape, msg="Wrong shape of the array 'permu...
import unittest import numpy as np from task import arr, permuted_2d, fully_random class TestCase(unittest.TestCase): def test_shape(self): self.assertEqual((5, 20), arr.shape, msg="Wrong shape of the array 'arr'.") self.assertEqual((5, 20), permuted_2d.shape, msg="Wrong shape of the array 'permu...
en
0.950242
# This test checks if in each row the minimum element goes first and maximum - last. # This test checks that differences between all neighboring elements in rows of the array # are not equal to 1 (in non-shuffled rows they would be). # This test checks if elements were also randomized between the rows.
3.429708
3
resources/lib/channelui.py
lausitzer/plugin.video.mediathekview
0
8778
# -*- coding: utf-8 -*- """ The channel model UI module Copyright 2017-2018, <NAME> and <NAME> SPDX-License-Identifier: MIT """ # pylint: disable=import-error import os import xbmcgui import xbmcplugin import resources.lib.mvutils as mvutils from resources.lib.channel import Channel class ChannelUI(Channel): ...
# -*- coding: utf-8 -*- """ The channel model UI module Copyright 2017-2018, <NAME> and <NAME> SPDX-License-Identifier: MIT """ # pylint: disable=import-error import os import xbmcgui import xbmcplugin import resources.lib.mvutils as mvutils from resources.lib.channel import Channel class ChannelUI(Channel): ...
en
0.52842
# -*- coding: utf-8 -*- The channel model UI module Copyright 2017-2018, <NAME> and <NAME> SPDX-License-Identifier: MIT # pylint: disable=import-error The channel model view class Args: plugin(MediathekView): the plugin object sortmethods(array, optional): an array of sort methods for...
2.299552
2
getconf.py
smk762/Dragonhound
3
8779
#!/usr/bin/env python3 #Credit to @Alright for the RPCs import re import os import requests import json import platform # define function that fetchs rpc creds from .conf def def_credentials(chain): operating_system = platform.system() if operating_system == 'Darwin': ac_dir = os.environ['HOME'] + '/...
#!/usr/bin/env python3 #Credit to @Alright for the RPCs import re import os import requests import json import platform # define function that fetchs rpc creds from .conf def def_credentials(chain): operating_system = platform.system() if operating_system == 'Darwin': ac_dir = os.environ['HOME'] + '/...
en
0.441511
#!/usr/bin/env python3 #Credit to @Alright for the RPCs # define function that fetchs rpc creds from .conf # define config file path #define rpc creds #print("Reading config file for credentials:", coin_config_file) # define function that posts json data # Return current -pubkey= # return latest batontxid from all publ...
2.527189
3
cwr/parser/decoder/dictionary.py
orenyodfat/CWR-DataApi
37
8780
# -*- coding: utf-8 -*- from cwr.acknowledgement import AcknowledgementRecord, MessageRecord from cwr.agreement import AgreementRecord, AgreementTerritoryRecord, \ InterestedPartyForAgreementRecord from cwr.group import Group, GroupHeader, GroupTrailer from cwr.info import AdditionalRelatedInfoRecord from cwr.pars...
# -*- coding: utf-8 -*- from cwr.acknowledgement import AcknowledgementRecord, MessageRecord from cwr.agreement import AgreementRecord, AgreementTerritoryRecord, \ InterestedPartyForAgreementRecord from cwr.group import Group, GroupHeader, GroupTrailer from cwr.info import AdditionalRelatedInfoRecord from cwr.pars...
en
0.864843
# -*- coding: utf-8 -*- Classes for transforming dictionaries into instances of the CWR model. There is a decoder for each of the model classes, and all of them expect a dictionary having at least one key for each field, having the same name as the field, which will refer to a valid value. As said, the values on the ...
1.797038
2
prebuilt/twrp_fonts.py
imranpopz/android_bootable_recovery-1
95
8781
<gh_stars>10-100 #!/usr/bin/env python # -*- coding: utf8 -*- import codecs,os,gzip,ctypes,ctypes.util,sys from struct import * from PIL import Image, ImageDraw, ImageFont # ====== Python script to convert TrueTypeFonts to TWRP's .dat format ====== # This script was originally made by https://github.com/suky for his c...
#!/usr/bin/env python # -*- coding: utf8 -*- import codecs,os,gzip,ctypes,ctypes.util,sys from struct import * from PIL import Image, ImageDraw, ImageFont # ====== Python script to convert TrueTypeFonts to TWRP's .dat format ====== # This script was originally made by https://github.com/suky for his chinese version of...
en
0.891531
#!/usr/bin/env python # -*- coding: utf8 -*- # ====== Python script to convert TrueTypeFonts to TWRP's .dat format ====== # This script was originally made by https://github.com/suky for his chinese version of TWRP # and then translated to English by feilplane at #twrp of irc.freenode.net. # However, it was not compati...
2.422889
2
open/users/serializers.py
lawrendran/open
105
8782
import pytz from rest_auth.serializers import TokenSerializer from rest_framework.authtoken.models import Token from rest_framework.exceptions import ValidationError from rest_framework.fields import ( CharField, CurrentUserDefault, HiddenField, UUIDField, ChoiceField, ) from rest_framework.serializ...
import pytz from rest_auth.serializers import TokenSerializer from rest_framework.authtoken.models import Token from rest_framework.exceptions import ValidationError from rest_framework.fields import ( CharField, CurrentUserDefault, HiddenField, UUIDField, ChoiceField, ) from rest_framework.serializ...
en
0.965376
# TODO - this view and serializer is on hold as you figure out registration (later) # need to make email optional ... prob should think through signup form a little # TODO test - does this work with just username / no email, etc. # most of this is actually redundant, i don't need to have a validation step, but i do thi...
2.281519
2
tests/en/test_asr.py
rhasspy/rhasspy-test
0
8783
"""Automated speech recognition tests.""" import os import sys import unittest from pathlib import Path import requests from rhasspyhermes.asr import AsrTextCaptured from rhasspyhermes.nlu import NluIntent class AsrEnglishTests(unittest.TestCase): """Test automated speech recognition (English)""" def setUp...
"""Automated speech recognition tests.""" import os import sys import unittest from pathlib import Path import requests from rhasspyhermes.asr import AsrTextCaptured from rhasspyhermes.nlu import NluIntent class AsrEnglishTests(unittest.TestCase): """Test automated speech recognition (English)""" def setUp...
en
0.627629
Automated speech recognition tests. Test automated speech recognition (English) Test speech-to-text HTTP endpoint Text speech-to-text HTTP endpoint (Rhasspy JSON format) Text speech-to-text HTTP endpoint (Hermes format) # Intent name and slots
3.295789
3
speech/melgan/model/multiscale.py
OthmaneJ/deep-tts
213
8784
import torch import torch.nn as nn import torch.nn.functional as F from .discriminator import Discriminator from .identity import Identity class MultiScaleDiscriminator(nn.Module): def __init__(self): super(MultiScaleDiscriminator, self).__init__() self.discriminators = nn.ModuleList( ...
import torch import torch.nn as nn import torch.nn.functional as F from .discriminator import Discriminator from .identity import Identity class MultiScaleDiscriminator(nn.Module): def __init__(self): super(MultiScaleDiscriminator, self).__init__() self.discriminators = nn.ModuleList( ...
en
0.784948
# [(feat, score), (feat, score), (feat, score)]
2.331615
2
main.py
AntonioLourencos/jogo-da-velha
10
8785
<gh_stars>1-10 from game import about_button, start_button, play_sound, center_pos import pygame WHITE = (255,255,255) BLACK = (0,0,0) GREEN = (0, 255, 0) pygame.init() pygame.font.init() pygame.mixer.init() FONT = pygame.font.Font("assets/font.ttf", 70) FONT_MIN = pygame.font.Font("assets/font.ttf", 30) window = p...
from game import about_button, start_button, play_sound, center_pos import pygame WHITE = (255,255,255) BLACK = (0,0,0) GREEN = (0, 255, 0) pygame.init() pygame.font.init() pygame.mixer.init() FONT = pygame.font.Font("assets/font.ttf", 70) FONT_MIN = pygame.font.Font("assets/font.ttf", 30) window = pygame.display.s...
none
1
2.94631
3
schedule/views.py
1donggri/teamProject
0
8786
from django.shortcuts import render, redirect from .models import Post from .forms import ScheduleForm from django.core.paginator import Paginator # Create your views here. def view_schedule(request): all_posts = Post.objects.all().order_by('pub_date') page = int(request.GET.get('p', 1)) pagenator = Pagina...
from django.shortcuts import render, redirect from .models import Post from .forms import ScheduleForm from django.core.paginator import Paginator # Create your views here. def view_schedule(request): all_posts = Post.objects.all().order_by('pub_date') page = int(request.GET.get('p', 1)) pagenator = Pagina...
ko
0.92538
# Create your views here. # form의 모든 validators 호출 유효성 검증 수행 # user_id = request.session.get('user') # user = User.objects.get(pk=user_id) # # 검증에 성공한 값들은 사전타입으로 제공 (form.cleaned_data) # # 검증에 실패시 form.error 에 오류 정보를 저장
2.196984
2
archetype/settings/local_stg.py
kingsdigitallab/archetype-django
1
8787
<reponame>kingsdigitallab/archetype-django from .base import * # noqa CACHE_REDIS_DATABASE = '1' CACHES['default']['LOCATION'] = '127.0.0.1:6379:' + CACHE_REDIS_DATABASE INTERNAL_IPS = INTERNAL_IPS + ('', ) ALLOWED_HOSTS = [''] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2...
from .base import * # noqa CACHE_REDIS_DATABASE = '1' CACHES['default']['LOCATION'] = '127.0.0.1:6379:' + CACHE_REDIS_DATABASE INTERNAL_IPS = INTERNAL_IPS + ('', ) ALLOWED_HOSTS = [''] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app_archetype_stg', ...
none
1
1.366344
1
website/sites/admin.py
vnaskos/Website
0
8788
<reponame>vnaskos/Website from django.contrib import admin # Register your models here.] from website.sites.models import Post @admin.register(Post) class TestAdmin2(admin.ModelAdmin): pass
from django.contrib import admin # Register your models here.] from website.sites.models import Post @admin.register(Post) class TestAdmin2(admin.ModelAdmin): pass
en
0.876766
# Register your models here.]
1.351805
1
mcts.py
korbi98/TicTacToeGo_Zero
0
8789
<reponame>korbi98/TicTacToeGo_Zero<filename>mcts.py # Monte Carlo tree search for TicTacToe import numpy as np from tictactoe import Tictactoe import copy from random import choice from tree import Node import time class MCTS: ''' Class defining a simple monte carlo tree search algorithm. Attributes: ...
# Monte Carlo tree search for TicTacToe import numpy as np from tictactoe import Tictactoe import copy from random import choice from tree import Node import time class MCTS: ''' Class defining a simple monte carlo tree search algorithm. Attributes: - game: instance of TicTacToe game - cu...
en
0.79936
# Monte Carlo tree search for TicTacToe Class defining a simple monte carlo tree search algorithm. Attributes: - game: instance of TicTacToe game - current_player: player to perform next move - number_of_rollouts: number of simulations for generating one move - tree: list containing...
3.889465
4
grimer/metadata.py
pirovc/grimer
5
8790
import pandas as pd from pandas.api.types import is_numeric_dtype from grimer.utils import print_log class Metadata: valid_types = ["categorical", "numeric"] default_type = "categorical" def __init__(self, metadata_file, samples: list=[]): # Read metadata and let pandas guess dtypes, index as str...
import pandas as pd from pandas.api.types import is_numeric_dtype from grimer.utils import print_log class Metadata: valid_types = ["categorical", "numeric"] default_type = "categorical" def __init__(self, metadata_file, samples: list=[]): # Read metadata and let pandas guess dtypes, index as str...
en
0.668764
# Read metadata and let pandas guess dtypes, index as str # Enforce string index # Define all COLUMN TYPES as default # Set types # types defined on file # guessed types from read_table # Convert datatypes to adequate numeric values (int, float) # Re-convert everython to object to standardize (int64 NA is not seriazabl...
2.946081
3
allennlp/training/metric_tracker.py
MSLars/allennlp
11,433
8791
from typing import Optional, Dict, Any, List, Union from allennlp.common.checks import ConfigurationError class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `st...
from typing import Optional, Dict, Any, List, Union from allennlp.common.checks import ConfigurationError class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `st...
en
0.811103
This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `state_dict` / `load_state_dict` interface, so that it can be checkpointed along with your model and optimizer. Some metrics improve by ...
2.698195
3
authors/apps/profiles/renderers.py
MuhweziDeo/Ah-backend-xmen
4
8792
from authors.apps.utils.renderers import AppJSONRenderer import json from rest_framework.renderers import JSONRenderer class UserProfileJSONRenderer(AppJSONRenderer): name = 'profile' class UserProfileListRenderer(JSONRenderer): """ Returns profiles of existing users """ charset = 'utf-8' ...
from authors.apps.utils.renderers import AppJSONRenderer import json from rest_framework.renderers import JSONRenderer class UserProfileJSONRenderer(AppJSONRenderer): name = 'profile' class UserProfileListRenderer(JSONRenderer): """ Returns profiles of existing users """ charset = 'utf-8' ...
en
0.643342
Returns profiles of existing users present a list of user profiles in json format
2.524953
3
json_analyzer.py
bantenz/NetworkConfigParser
0
8793
<reponame>bantenz/NetworkConfigParser<gh_stars>0 import json from deepdiff import DeepDiff import pprint def get_json(file_name): with open(file_name) as json_file: json_data = json.load(json_file) return json_data def compare_json(Hostname, Command, Data1, Data2): if (Data1 == Data2): ...
import json from deepdiff import DeepDiff import pprint def get_json(file_name): with open(file_name) as json_file: json_data = json.load(json_file) return json_data def compare_json(Hostname, Command, Data1, Data2): if (Data1 == Data2): print ("%s - %s output is same" % (Hostname, Com...
en
0.793427
# If this Python file runs by itself, run below command. If imported, this section is not run
3.143137
3
fiwareglancesync/sync.py
telefonicaid/fiware-glancesync
0
8794
<reponame>telefonicaid/fiware-glancesync #!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with ...
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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...
en
0.865413
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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...
1.987208
2
models/object_detection/pytorch/ssd-resnet34/training/cpu/mlperf_logger.py
Pandinosaurus/models-intelai
0
8795
### This file is originally from: [mlcommons repo](https://github.com/mlcommons/training/tree/9947bdf21ee3f2488fa4b362eec2ce7deb2ec4dd/single_stage_detector/ssd/mlperf_logger.py) # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may ...
### This file is originally from: [mlcommons repo](https://github.com/mlcommons/training/tree/9947bdf21ee3f2488fa4b362eec2ce7deb2ec4dd/single_stage_detector/ssd/mlperf_logger.py) # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may ...
en
0.840162
### This file is originally from: [mlcommons repo](https://github.com/mlcommons/training/tree/9947bdf21ee3f2488fa4b362eec2ce7deb2ec4dd/single_stage_detector/ssd/mlperf_logger.py) # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may ...
2.0774
2
omtk/models/model_avar_surface_lips.py
CDufour909/omtk_unreal
0
8796
import math import pymel.core as pymel from omtk.core.classNode import Node from omtk.libs import libAttr from omtk.libs import libRigging from . import model_avar_surface class SplitterNode(Node): """ A splitter is a node network that take the parameterV that is normally sent through the follicles and sp...
import math import pymel.core as pymel from omtk.core.classNode import Node from omtk.libs import libAttr from omtk.libs import libRigging from . import model_avar_surface class SplitterNode(Node): """ A splitter is a node network that take the parameterV that is normally sent through the follicles and sp...
en
0.848686
A splitter is a node network that take the parameterV that is normally sent through the follicles and split it between two destination: the follicles and the jaw ref constraint. The more the jaw is opened, the more we'll transfer to the jaw ref before sending to the follicle. This is mainly used to ensure t...
2.627216
3
project/server/main/feed.py
dataesr/harvest-theses
0
8797
<filename>project/server/main/feed.py import datetime import os import pymongo import requests from urllib import parse from urllib.parse import quote_plus import json from retry import retry from bs4 import BeautifulSoup import math from project.server.main.logger import get_logger from project.server.main.utils_swi...
<filename>project/server/main/feed.py import datetime import os import pymongo import requests from urllib import parse from urllib.parse import quote_plus import json from retry import retry from bs4 import BeautifulSoup import math from project.server.main.logger import get_logger from project.server.main.utils_swi...
en
0.377705
# 1. save raw data to OS # 2.transform data and save in mongo # insert_data(collection_name, current_file_parsed) # 1. save aurehal structures # 2. drop mongo #logger.debug(f'dropping {collection_name} collection before insertion') #myclient = pymongo.MongoClient('mongodb://mongo:27017/') #myclient['theses'][collection...
2.335372
2
DQM/L1TMonitor/python/L1TGCT_cfi.py
ckamtsikis/cmssw
852
8798
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer l1tGct = DQMEDAnalyzer('L1TGCT', gctCentralJetsSource = cms.InputTag("gctDigis","cenJets"), gctForwardJetsSource = cms.InputTag("gctDigis","forJets"), gctTauJetsSource = cms.InputTag("gctDigis","tauJets"), ...
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer l1tGct = DQMEDAnalyzer('L1TGCT', gctCentralJetsSource = cms.InputTag("gctDigis","cenJets"), gctForwardJetsSource = cms.InputTag("gctDigis","forJets"), gctTauJetsSource = cms.InputTag("gctDigis","tauJets"), ...
none
1
1.445069
1
utilities.py
gandhiy/lipMIP
11
8799
<reponame>gandhiy/lipMIP """ General all-purpose utilities """ import sys import torch import torch.nn.functional as F import numpy as np import gurobipy as gb import matplotlib.pyplot as plt import io import contextlib import tempfile import time import re import pickle import inspect import glob import os COMPLETE...
""" General all-purpose utilities """ import sys import torch import torch.nn.functional as F import numpy as np import gurobipy as gb import matplotlib.pyplot as plt import io import contextlib import tempfile import time import re import pickle import inspect import glob import os COMPLETED_JOB_DIR = os.path.join(...
en
0.674301
General all-purpose utilities # =============================================================================== # = Helpful all-purpose functions = # =============================================================================== # Make default args from attributes # Update...
2.123502
2