content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
from rest_framework import serializers
from .models import Canteen
from accounts.serializers import UserForSerializer
from model_location.serializers import CityViewSerializer
from model_media.serializers import MediaViewSerializer
# Canteen model serializer
class CanteenSerializer(serializers.ModelSerializer):
c... | models/model_canteen/serializers.py | 696 | Canteen model serializer Canteen model serializer to view | 57 | en | 0.829794 |
# MIT License
#
# Copyright (c) 2019 Red Hat, Inc.
# 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, including without limitation the rights
# to use, copy, modify, merge,... | packit/cli/__init__.py | 1,107 | MIT License Copyright (c) 2019 Red Hat, Inc. 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, including without limitation the rights to use, copy, modify, merge, publish, distr... | 1,065 | en | 0.863681 |
import os
import random
from riscv_definitions import *
NONE = 0
CF_J = 1
CF_BR = 2
CF_RET = 3
MEM_R = 4
MEM_W = 5
CSR = 6
PREFIX = '_p'
MAIN = '_l'
SUFFIX = '_s'
class Word():
def __init__(self, label: int, insts: list, tpe=NONE, xregs=[], fregs=[], imms=[], symbols=[], populated=False):
se... | Fuzzer/src/word.py | 7,388 | Need to update rm = random.choice([ 'rne', 'rtz', 'rdn', 'rup', 'rmm', 'dyn']) Unset rounding mode testing | 127 | en | 0.280481 |
"""URLs for the ``django-frequently`` application."""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',
views.EntryCategoryListView.as_view(),
name='frequently_list'),
url(r'^your-question/$',
views.EntryCreateView.as_view(),
name='frequently_sub... | frequently/urls.py | 457 | URLs for the ``django-frequently`` application. | 47 | en | 0.894827 |
# Support various prediction methods for predicting cluster membership
# of new or unseen points. There are several ways to interpret how
# to do this correctly, so we provide several methods for
# the different use cases that may arise.
import numpy as np
from sklearn.neighbors import KDTree, BallTree
from .dist_met... | hdbscan/prediction.py | 21,034 | Extra data that allows for faster prediction if cached.
Parameters
----------
data : array (n_samples, n_features)
The original data set that was clustered
condensed_tree : CondensedTree
The condensed tree object created by a clustering
min_samples : int
The min_samples value used in clustering
tree_ty... | 7,951 | en | 0.819102 |
"""
Views for PubSite app.
"""
from django.conf import settings
from django.contrib.auth.views import (
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView,
)
from django.shortcuts import render
import requests
import logging
logger = logging.getLogger(__name__... | sigmapiweb/apps/PubSite/views.py | 4,610 | View for the static chapter history page.
View for the static chapter service page.
View for the campaign service page.
View for the static index page
View for 403 (Permission Denied) error.
No code here means requests will always preserve the Authorization
header when redirected.
Be careful not to leak your credential... | 1,019 | en | 0.732355 |
import requests
import datetime
class BearerAuth(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers["authorization"] = "Bearer " + self.token
return r
class MintMobile:
def __init__(self, phone_number, password):
self.pho... | custom_components/mintmobile/api.py | 3,928 | print("Logging Into " + self.phone_number)self.info[activeMembers['id']]={"phone_number":activeMembers['msisdn'],"line_name":activeMembers['nickName']} | 151 | en | 0.683048 |
import re
class Normalizer:
"""Normalizer return the text replaced with 'repl'.
If 'repl' is None, normalization is not applied to the pattern corresponding to 'repl'.
Args:
url_repl (str): replace all urls in text with this
tag_repl (str): replace all tags in text with this
emoji_... | prenlp/data/normalizer.py | 91,819 | Normalizer return the text replaced with 'repl'.
If 'repl' is None, normalization is not applied to the pattern corresponding to 'repl'.
Args:
url_repl (str): replace all urls in text with this
tag_repl (str): replace all tags in text with this
emoji_repl (str): replace all emojis in text with this
ema... | 1,732 | en | 0.620159 |
"""BERT Training Script."""
import functools
from typing import Any, Callable, Dict, Tuple, Optional, Type
from absl import logging
from clu import metric_writers
from clu import periodic_actions
from flax import jax_utils
import flax.linen as nn
import jax
from jax.experimental import optimizers as jax_optimizers
im... | scenic/projects/baselines/bert/trainer.py | 20,582 | Runs a single step of training.
Note that in this code, the buffer of the second argument (batch) is donated
to the computation.
Assumed API of metrics_fn is:
```metrics = metrics_fn(logits, batch)
where batch is yielded by the batch iterator, and metrics is a dictionary
mapping metric name to a vector of per example... | 6,623 | en | 0.887796 |
__source__ = 'https://leetcode.com/problems/delete-node-in-a-linked-list/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/delete-node-in-a-linked-list.py
# Time: O(1)
# Space: O(1)
#
# Description: Leetcode # 237. Delete Node in a Linked List
#
# Write a function to delete a node (except the tai... | cs15211/DeleteNodrinaLinkedList.py | 2,221 | https://github.com/kamyu104/LeetCode/blob/master/Python/delete-node-in-a-linked-list.py Time: O(1) Space: O(1) Description: Leetcode 237. Delete Node in a Linked List Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 ->... | 672 | en | 0.806736 |
from unittest import TestCase
from btcmagic import transaction, convert
import os
import json
class TestTransaction(TestCase):
def setUp(self):
self.tx_bin = convert.hex_to_bytes(
'0100000001637aaf20d708fcff67bb688af6e41d1807e6883f736c50eacb6042bf6e6c829c010000008c493046022100da1e59d78bb88ca7c... | btcmagic/test_transaction.py | 3,355 | Ignore first header row in the JSON. This must be unsigned int It's reversed for some reason? | 93 | en | 0.925768 |
from os import environ
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
DEBUG = True
CRON_ENABLED = False
if 'SIMONE_DB_NAME' in environ:
DATABASES = {
'default': {
'ENGINE': 'mysql.connector.d... | simone/settings/dev.py | 1,698 | Build paths inside the project like this: BASE_DIR / 'subdir'. comment out to see db queries super noisy | 104 | en | 0.491747 |
"""Nyamuk event."""
import socket
import nyamuk_const as NC
#mqtt event
EV_CONNACK = NC.CMD_CONNACK
EV_PUBLISH = NC.CMD_PUBLISH
EV_SUBACK = NC.CMD_SUBACK
#non mqtt event
EV_NET_ERR = 1000
class BaseEvent:
"""Event Base Class."""
def __init__(self, tipe):
self.type = tipe
class EventConnack(BaseEven... | nyamuk/event.py | 2,060 | Event Base Class.
CONNACK received.
Network error event.
PINGRESP received.
PUBACK received.
PUBCOMP received.
PUBLISH received.
PUBREC received.
PUBREL received.
SUBACK received.
UNSUBACK received.
Nyamuk event.
mqtt eventnon mqtt event v3.1.1 only | 250 | en | 0.984124 |
# Generated by Django 2.2.7 on 2019-11-20 17:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0002_question_image'),
]
operations = [
migrations.RemoveField(
model_name='question',
name='answer',
... | quiz/migrations/0003_auto_20191120_2238.py | 541 | Generated by Django 2.2.7 on 2019-11-20 17:08 | 45 | en | 0.614117 |
#!/usr/bin/python
# coding: utf-8
"""A simple webserver."""
# python 2.7 compatibility
from __future__ import print_function, unicode_literals
# based on tornado
import tornado.ioloop
import tornado.web
import tornado.websocket
import sys
import json
def make_app():
"""Create and return the main Tornado web app... | 6/server.py | 2,720 | ClientSocket represents an active websocket connection to a client.
Create and return the main Tornado web application.
It will listen on the port assigned via `app.listen(port)`,
and will run on Tornado's main ioloop,
which can be started with `tornado.ioloop.IOLoop.current().start()`.
Called when a client conne... | 827 | en | 0.826251 |
"""Dataset, producer, and config metadata."""
import logging
import warnings
import sqlalchemy as sa
from .._globals import REGISTRY as registry
from .. import _tools
from .. import backend as _backend
__all__ = ['Dataset', 'Producer', 'Config']
log = logging.getLogger(__name__)
@registry.mapped
class Dataset:... | treedb/backend/models.py | 5,941 | Configuration setting from ``glottolog/config/*.ini``.
Git commit loaded into the database.
Name and version of the package that created a __dataset__.
Dataset, producer, and config metadata.
pragma: no cover pragma: no cover pragma: no cover pragma: no cover | 261 | en | 0.634529 |
import logging
import multiprocessing
import os
import signal
import sys
import time
from typing import Any
from datastore.reader.app import register_services
from gunicorn.app.base import BaseApplication
from .shared.env import is_dev_mode
from .shared.interfaces.logging import LoggingModule
from .shared.interfaces.... | openslides_backend/main.py | 4,739 | Standalone application class for Gunicorn. It prepares Gunicorn for using
OpenSlidesBackendWSGIApplication via OpenSlidesBackendWSGIContainer either
with action component or with presenter component.
ATTENTION: We use the Python builtin logging module. To change this use something like "import custom_logging as loggi... | 644 | en | 0.739255 |
import logging
from datetime import datetime
from dateutil import parser as DatetimeParser
def dicom_name(names: list) -> str:
s = "^".join(names).upper()
return s
def dicom_date(dt: datetime) -> str:
s = dt.strftime("%Y%m%d")
return s
def dicom_time(dt: datetime) -> str:
s = dt.strftime("%H%M... | package/diana/utils/dicom/strings.py | 1,384 | GE Scanner dt format Wrong format Siemens scanners use fractional seconds Wrong format Unknown format, fall back on guessing Parser does _not_ like fractional seconds Wrong format | 179 | en | 0.57792 |
# -*- encoding: utf-8 -*-
#
# Copyright © 2013 Red Hat, 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 requi... | cgtsclient/v1/sm_service_nodes.py | 1,763 | -*- encoding: utf-8 -*- Copyright © 2013 Red Hat, 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 ... | 652 | en | 0.855674 |
import codecs
import csv
import datetime
import logging
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from todo.models import Task, TaskList
log = logging.getLogger(__name__)
class CSVImporter:
"""Core upsert functionality for CSV import, for re-use by `import_csv`... | todo/operations/csv_importer.py | 7,623 | Core upsert functionality for CSV import, for re-use by `import_csv` management command, web UI and tests.
Supplies a detailed log of what was and was not imported at the end. See README for usage notes.
Expects a file *object*, not a file path. This is important because this has to work for both
the management command... | 1,484 | en | 0.89412 |
import fiftyone as fo
import fiftyone.zoo as foz
# Load Dataset
dataset = foz.load_zoo_dataset("coco-2017", split="validation")
# Randomly select 20 samples on which to generate predictions
view = dataset.take(20)
# Load zoo model
model = foz.load_zoo_model("keypoint-rcnn-resnet50-fpn-coco-torch")
# Run Inferen... | scripts/fiftyone_sample.py | 481 | Load Dataset Randomly select 20 samples on which to generate predictions Load zoo model Run Inference Launch the FiftyOne App to visualize your dataset | 151 | en | 0.736952 |
#!/usr/bin/env python3
import argparse
from botocore.exceptions import ClientError
import os
from pacu.core.lib import downloads_dir
module_info = {
# Name of the module (should be the same as the filename)
"name": "lightsail__generate_temp_access",
# Name and any other notes about the author
"author"... | pacu/modules/lightsail__generate_temp_access/main.py | 8,140 | !/usr/bin/env python3 Name of the module (should be the same as the filename) Name and any other notes about the author Category of the module. Make sure the name matches an existing category. One liner description of the module functionality. This shows up when a user searches for modules. Full description about what ... | 882 | en | 0.803181 |
# -*- coding: utf-8 -*-
import sys
import argparse
from cgate.reader import readfile, readschema, get_dtype
from cgate.validation import validate
def main():
parser = argparse.ArgumentParser()
parser.add_argument('target', help='Table name or File path')
parser.add_argument('--schema', '-s', help='Cerber... | cgate/cgate.py | 973 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Generated by Django 2.2.6 on 2020-09-03 03:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comment', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='target',
... | comment/migrations/0002_auto_20200903_0323.py | 406 | Generated by Django 2.2.6 on 2020-09-03 03:23 | 45 | en | 0.737223 |
from django.contrib import admin
# Register your models here.
from .models import Join
class JoinAdmin(admin.ModelAdmin):
list_display = ['email', 'friend', 'timestamp', 'updated']
class Meta:
model = Join
admin.site.register(Join, JoinAdmin)
| trader/joins/admin.py | 263 | Register your models here. | 26 | en | 0.957485 |
import logging
import os
import boto3
from lib.cleanup_resource_handler import CleanupResourceHandler
from lib.queue_handler import QueueHandler
logging.getLogger().setLevel(logging.INFO)
def queue_handler(event, context):
"""
Handler for the event queue lambda trigger
"""
ec2_client = boto3.clien... | packages/@aws-cdk-containers/ecs-service-extensions/lib/extensions/assign-public-ip/lambda/index.py | 896 | Event handler for the custom resource.
Handler for the event queue lambda trigger | 81 | en | 0.802655 |
# inclass/mongo_queries.py
import pymongo
import os
from dotenv import load_dotenv
import sqlite3
load_dotenv()
DB_USER = os.getenv("MONGO_USER", default="OOPS")
DB_PASSWORD = os.getenv("MONGO_PASSWORD", default="OOPS")
CLUSTER_NAME = os.getenv("MONGO_CLUSTER_NAME", default="OOPS")
connection_uri = f"mongodb+srv://{D... | assignment3/a3_mongo_queries_abw.py | 10,194 | inclass/mongo_queries.py print(dir(client)) print("DB NAMES:", client.list_database_names()) > ['admin', 'local'] "ds14_db" or whatever you want to call it print("----------------") print("DB:", type(db), db) collection = db.ds14_pokemon_collection "ds14_collection" or whatever you want to call it print("-------------... | 8,333 | en | 0.531613 |
###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | src/tactic/ui/container/tab_wdg.py | 93,668 | Copyright (c) 2005, Southpaw Technology All Rights Reserved PROPRIETARY INFORMATION. This software is proprietary to Southpaw Technology, and is not to be reproduced, transmitted, or disclosed in any way without written permission. save state overrides if it is not defined in the database, look at ... | 1,761 | en | 0.605619 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... | sdk/python/pulumi_azure_native/recoveryservices/v20181220/outputs.py | 17,512 | :param str object_type: Type of the specific object - used for deserializing
Expected value is 'WorkloadCrrAccessToken'.
:param str access_token_string: Access token used for authentication
:param str b_ms_active_region: Active region name of BMS Stamp
:param str backup_management_type: Backup Management Type
:p... | 3,173 | en | 0.630396 |
import os
import numpy as np
from netCDF4 import Dataset
def load_region(region_id, local=False, return_regions=False):
if local:
_vr = Dataset(
os.path.join(os.path.dirname(os.path.abspath(__file__)), r"data/terrain_parameters/VarslingsOmr_2017.nc"),
"r")
# flip up-down b... | aps/load_region.py | 2,930 | flip up-down because Meps data is upside down_regions = np.flipud(_vr.variables["LokalOmr_2018"][:]) flip up-down because Meps data is upside down_regions = np.flipud(_vr.variables["skredomr19_km"][:]) just to get the bounding box get the lower left and upper right corner of a rectangle around the regionreg_mask = np.m... | 822 | en | 0.090889 |
# Generated by Django 2.1.11 on 2020-06-24 06:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0008_auto_20190919_1521'),
]
operations = [
migrations.AddField(
model_name='product',
name='is_deleted... | products/migrations/0009_product_is_deleted.py | 394 | Generated by Django 2.1.11 on 2020-06-24 06:55 | 46 | en | 0.69865 |
import time
import torch
from hpc_rll.origin.td import iqn_nstep_td_error, iqn_nstep_td_data
from hpc_rll.rl_utils.td import IQNNStepTDError
from testbase import mean_relative_error, times
assert torch.cuda.is_available()
use_cuda = True
tau = 33
tauPrime = 34
T = 10
B = 64
N = 8
gamma = 0.95
kappa = 0.9
def iqn_val... | tests/test_iqn_nstep_td_error.py | 6,308 | torch.cuda.cudart().cudaProfilerStart()torch.cuda.cudart().cudaProfilerStop() | 77 | zh | 0.110549 |
#!/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.
"""Utilities for manipulating blocks and transactions."""
from test_framework.mininode import *
from test... | test/functional/test_framework/blocktools.py | 3,564 | Utilities for manipulating blocks and transactions.
!/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. Create a block (with regtest difficulty) Will break after a ... | 734 | en | 0.655877 |
# -*- coding: utf-8 -*-
import datetime
from unittest.mock import Mock
import pytest
from h.activity import bucketing
from tests.common import factories
UTCNOW = datetime.datetime(year=1970, month=2, day=21, hour=19, minute=30)
FIVE_MINS_AGO = UTCNOW - datetime.timedelta(minutes=5)
YESTERDAY = UTCNOW - datetime.ti... | tests/h/activity/bucketing_test.py | 13,834 | Test bucketing multiple annotations from different days of same month.
Annotations from different days of the same month should go into one
bucket.
-*- coding: utf-8 -*- noqa: N801 | 183 | en | 0.858458 |
# models.py
from flask_login import UserMixin
from . import db
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True) # primary keys are required by SQLAlchemy
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(1000))
... | webapp/models.py | 356 | models.py primary keys are required by SQLAlchemy | 49 | en | 0.893456 |
# -*- coding: utf-8 -*-
from . import fields
from . import integrators
from . import points
from . import system
from . import utils
from . import visualizer
from .system import NBodySystem
from .visualizer import Visualizer, run | fieldbillard/__init__.py | 232 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import json
import logging
import requests
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, OpenPortEvent, Service
from kube_hunter.core.types import Discovery
class EtcdAccessEvent(Service, Event):
"""Etcd is a DB that stores cluster's data, it contains configuration ... | kube_hunter/modules/discovery/etcd.py | 760 | Etcd is a DB that stores cluster's data, it contains configuration and current
state information, and might contain secrets
Etcd service
check for the existence of etcd service | 176 | en | 0.843072 |
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2021-present Kaleidos Ventures SL
from __future__ import unicode_literals
fro... | taiga/projects/tasks/migrations/0009_auto_20151104_1131.py | 1,711 | -*- coding: utf-8 -*- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2021-present Kaleidos Ventures SL Updates the finished date from tasks according to the his... | 471 | en | 0.871513 |
from gpiozero import CPUTemperature
from tabulate import tabulate
from math import floor
import numpy as np
import termplotlib as tpl
import time
import shutil
def roundNum(num, digits):
return floor(num * 10 ** digits) / (10 ** digits)
def CtoF(temp):
fahrenheit = (temp + 1.8) + 32
rounded = roundNum(fah... | monitor_temp.py | 2,789 | takes data every {tickRate} secondsOKGREEN at end is to make sure table lines are green, not cyan width=width-2, height=height-5, label='CPU Temperature', xlabel='Time (s)', , ylim=[np.amin(temps)-2, np.amax(temps)+2], title='CPU Temperature over last 5 minutes' | 262 | en | 0.473205 |
#
# 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 us... | sdks/python/apache_beam/testing/benchmarks/nexmark/nexmark_launcher.py | 9,122 | Nexmark launcher.
The Nexmark suite is a series of queries (streaming pipelines) performed
on a simulation of auction events. The launcher orchestrates the generation
and parsing of streaming events and the running of queries.
Model
- Person: Author of an auction or a bid.
- Auction: Item under auction.
- Bid: ... | 2,493 | en | 0.748332 |
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from rlstructures.logger import Logger, TFLogger
from rlstructures import DictTensor, TemporalDictTensor
from rlstructures import logging... | tutorial/deprecated/tutorial_a2c_with_infinite_env/a2c.py | 10,403 | Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Creation of the Logger (that saves in tensorboard and CSV) Creation of one env instance to get the dimensionnality of observations and number of action... | 2,527 | en | 0.880288 |
"""Utility functions for parcinging Freesurfer output files."""
from os.path import join
import nibabel as nb
import numpy as np
def _vectorize_fs_surf(file_path):
"""
Read surface information from a file and turn it into a vector.
Parameters
----------
file_path : str
The path to a file... | camcan/utils/file_parsing.py | 2,013 | Read surface information from a file and turn it into a vector.
Parameters
----------
file_path : str
The path to a file with surface data.
Returns
-------
vectorized_data : numpy.ndarray
Extracted data.
Read area information for the given subject and turn it into a vector.
Data for left and right hemisphere... | 952 | en | 0.677209 |
import builtins
import os
import sys
from array import array
from collections import Counter, defaultdict, deque
from dataclasses import dataclass, fields, is_dataclass
from itertools import islice
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Set,
... | rich/pretty.py | 24,145 | A node in a repr tree. May be atomic or a container.
A rich renderable that pretty prints an object.
Args:
_object (Any): An object to pretty print.
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
indent_size (int, optional): Nu... | 5,217 | en | 0.629515 |
import json
import os
import sys
import time
import torch
from training.training import Trainer
from data.conversion import GridDataConverter, PointCloudDataConverter, ERA5Converter
from data.dataloaders import mnist, celebahq
from data.dataloaders_era5 import era5
from data.dataloaders3d import shapenet_voxels, shapen... | main.py | 6,283 | Get config file from command line arguments Open config file Create a folder to store experiment results Save config file in experiment directory Setup dataloader Setup data converter Setup encoding for function distribution Setup generator models Setup discriminator Setup trainer | 281 | en | 0.627002 |
#! /usr/bin/env python
# Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
# host keys.
# usage:
# kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
# Creates a Windows .REG file (double-click to install).
# kh2reg.py --unix known_hosts1 2 3 4 ... > sshhostkeys
# Cr... | contrib/kh2reg.py | 5,752 | ! /usr/bin/env python Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY host keys. usage: kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg Creates a Windows .REG file (double-click to install). kh2reg.py --unix known_hosts1 2 3 4 ... > sshhostkeys Creates data suita... | 1,574 | en | 0.833724 |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | lte/gateway/python/magma/pipelined/qos/qos_tc_impl.py | 14,093 | Creates/Deletes queues in linux. Using Qdiscs for flow based
rate limiting(traffic shaping) of user traffic.
Queues are created on an egress interface and flows
in OVS are programmed with qid to filter traffic to the queue.
Traffic matching a specific flow is filtered to a queue and is
rate limited based on configured ... | 2,034 | en | 0.803903 |
# coding=utf-8
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import shutil
import mock
import pytest
from callee import Contains
from .conftest import git_out, search... | tests/test_integration_git.py | 31,249 | coding=utf-8 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. join args to catch unicode errors ping diffusion.repository.search user search differential.creatediff differentia... | 3,146 | en | 0.721162 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`accelerometer`
==================
Updated by lkasso <hello@mbientlab.com>
Created by hbldh <henrik.blidh@nedomkull.com>
Created on 2016-04-10
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
impor... | examples/accelerometer.py | 1,353 | Handle a (epoch, (x,y,z)) accelerometer tuple.
:mod:`accelerometer`
==================
Updated by lkasso <hello@mbientlab.com>
Created by hbldh <henrik.blidh@nedomkull.com>
Created on 2016-04-10
!/usr/bin/env python -*- coding: utf-8 -*- | 239 | en | 0.520104 |
# Natural Language Toolkit: SVM-based classifier
#
# Copyright (C) 2001-2022 NLTK Project
# Author: Leon Derczynski <leon@dcs.shef.ac.uk>
#
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
nltk.classify.svm was deprecated. For classification based
on support vector machines SVMs use nltk.cl... | nltk/classify/svm.py | 508 | nltk.classify.svm was deprecated. For classification based
on support vector machines SVMs use nltk.classify.scikitlearn
(or `scikit-learn <https://scikit-learn.org>`_ directly).
Natural Language Toolkit: SVM-based classifier Copyright (C) 2001-2022 NLTK Project Author: Leon Derczynski <leon@dcs.shef.ac.uk> URL: <htt... | 380 | en | 0.739263 |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
with open('VERSION.py') as f:
exec(f.read())
setup(
name='upsere analysis',
version=__version__,
description='10X Genomics CLI',
... | setup.py | 838 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/python
################################################################################
# 20de4144-5cc5-11e4-af55-00155d01fe08
#
# Justin Dierking
# justindierking@hardbitsolutions.com
# phnomcobra@gmail.com
#
# 10/24/2014 Original Construction
################################################################... | pcat2py/class/20de4144-5cc5-11e4-af55-00155d01fe08.py | 1,362 | !/usr/bin/python 20de4144-5cc5-11e4-af55-00155d01fe08 Justin Dierking justindierking@hardbitsolutions.com phnomcobra@gmail.com 10/24/2014 Original Construction Initialize Compliance Get Registry DWORD Output Lines | 213 | en | 0.3191 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import io
import os
import sys
from setuptools import find_packages, setup
def read_req(req_file):
with open(os.path.join('requirements', req_file)) as req:
return [line.strip() for line in req.readlines() if line.strip(... | setup.py | 3,611 | !/usr/bin/env python -*- coding: utf-8 -*- noinspection PyUnresolvedReferences noqa: F401 don't silently fail on travis - we don't want to accidentally push a dummy version to PyPI | 180 | en | 0.839002 |
from tourapi.list import TourAPI
from tourapi.config import ServiceKey, MobileOS, MobileApp, Languages
from mysql_config import MysqlHost, MysqlUser, MysqlPass, MysqlDB
import pymysql
import json
def upload_category_codes(codes, language="Kor", level=0, cat1="", cat2="", cat3=""):
global conn, curs
query = """
... | 02_category_code.py | 1,373 | print(code["name"], code["code"]) 대분류 카테고리 | 42 | ko | 0.967001 |
import os
import shutil
import subprocess
import re
import string
import pathlib
import timeit
import jmhbenchmark
class JHaskellBenchmark(jmhbenchmark.JMHBenchmark):
def __init__(self, name, source_path, compiler_args=None):
if compiler_args is None:
compiler_args = []
source_path = ... | benchmarks/jhaskellbenchmark.py | 3,270 | Build the source program For JHaskell, time for each stage of the compiler Record the output of each invocationthis_run_data.append(("Other", overall_time * 1000 - cumulative_time)) | 181 | en | 0.609848 |
import copy
import logging
from collections import defaultdict
import dask.dataframe as dd
import numpy as np
import pandas as pd
from pandas.api.types import is_dtype_equal, is_numeric_dtype
import featuretools.variable_types.variable as vtypes
from featuretools.entityset import deserialize, serialize
from featureto... | featuretools/entityset/entityset.py | 43,227 | Stores all actual data for a entityset
Attributes:
id
entity_dict
relationships
time_type
Properties:
metadata
Get entity instance from entityset
Args:
entity_id (str): Id of entity.
Returns:
:class:`.Entity` : Instance of entity. None if entity doesn't
exist.
Creates EntitySet
... | 11,731 | en | 0.748461 |
from __future__ import unicode_literals
from future.builtins import int, zip
from functools import reduce
from operator import ior, iand
from string import punctuation
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Manager, Q, CharField, TextField
from django.db.models.loading im... | mezzanine/core/managers.py | 16,435 | Extends Django's site manager to first look up site by ID stored in
the request, the session, then domain for the current request
(accessible via threadlocals in ``mezzanine.core.request``), the
environment variable ``MEZZANINE_SITE_ID`` (which can be used by
management commands with the ``--site`` arg, finally falling... | 5,542 | en | 0.893695 |
import pdfplumber
import re
import pandas as pd
from datetime import datetime
import sys
# AUTHOR: Simon Rosen
# -----------------------------------
# DEPENDENCIES
# This module requires 'pdfplumber'
#
# Install: pip install pdfplumber
# -----------------------------------
def extract_data(file_path):
... | scripts/gp_pdf_extractor.py | 12,011 | AUTHOR: Simon Rosen ----------------------------------- DEPENDENCIES This module requires 'pdfplumber' Install: pip install pdfplumber ----------------------------------- Helper functions text - string you are finding substring in print("text: {}\n string1: {}, string2:{}".format("text", string1, string2))... | 1,460 | en | 0.541883 |
#
# 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... | tests/providers/google/cloud/hooks/test_bigquery.py | 85,313 | Ensure `use_legacy_sql` param in `BigQueryHook` propagates properly.
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... | 997 | en | 0.839319 |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Config": "00_learner.ipynb",
"energy_score": "00_learner.ipynb",
"EnsemblePredict": "00_learner.ipynb",
"EnsembleLearner": "00_learner.ipynb",
"ARCHITECTURES": "01_models.... | deepflash2/_nbdev.py | 3,783 | AUTOGENERATED BY NBDEV! DO NOT EDIT! | 36 | en | 0.8261 |
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Group(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
description = models.TextField()
class Post(models.Model):
text = models.TextField()
pub_d... | posts/models.py | 1,397 | тот который подписываетсятот на которого подписываются | 54 | ru | 0.999288 |
import sys
import numpy as np
from numpy.lib import recfunctions as recFunc
from ..frequency_domain.survey import Survey
from ...data import Data as BaseData
from ...utils import mkvc
from .sources import Planewave_xy_1Dprimary, Planewave_xy_1DhomotD
from .receivers import Point3DImpedance, Point3DTipper
from .utils.p... | SimPEG/electromagnetics/natural_source/survey.py | 9,624 | Data class for NSEMdata. Stores the data vector indexed by the survey.
Function to transform a numpy record array to a nd array.
dupe of SimPEG.electromagnetics.natural_source.utils.rec_to_ndarr to avoid circular import
Class method that reads in a numpy record array to NSEMdata object.
:param recArray: Record array w... | 3,241 | en | 0.588412 |
# (C) Copyright 1996-2016 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergov... | regression/era/era.py | 1,527 | (C) Copyright 1996-2016 ECMWF. This software is licensed under the terms of the Apache Licence Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. In applying this licence, ECMWF does not waive the privileges and immunities granted to it by virtue of its status as an intergovernmental or... | 506 | en | 0.886521 |
#!/usr/bin/env python3
"""A utility script for automating the beets release process.
"""
import click
import os
import re
import subprocess
from contextlib import contextmanager
import datetime
BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CHANGELOG = os.path.join(BASE, 'docs', 'changelog.rst')
... | extra/release.py | 9,525 | Bump the version number.
Update the version number in setup.py, docs config, changelog,
and root module.
Get the most recent version's changelog as Markdown.
Get the latest changelog entry as hacked up Markdown.
A context manager that temporary changes the working directory.
Enter today's date as th... | 2,015 | en | 0.795307 |
import re
from Error import Error4,Error6,Error9
from DataBase import BaseDatos,BdRow
from .precompilada import precompilada
from typing import Pattern
def getEtiqueta(linea:str)->str:
"""Obtiene el nombre de la captura
Args:
linea (str): Linea donde se va a buscar la etiqueta
Returns:
st... | Precompilar/relativo.py | 4,178 | Convierte a binario un numero de complemento A2 en caso de negativo, normal en caso de ser positivo
Args:
n (int): E.g 7
bits (int): eg 3
Returns:
str: E.g '001'
Resta la diferencia entre dos PC en hexadecimal
sustraendo - minuendo
- Si
- Sustraendo - minuendo
- En caso de error regresa 'e10' operando mu... | 1,647 | es | 0.832802 |
# Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 requi... | examples/Rest/ex17_mount_virtual_media_iso.py | 2,563 | Copyright 2016 Hewlett Packard Enterprise Development LP 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... | 967 | en | 0.833323 |
from gpiozero import Servo
from gpiozero import LED
from time import sleep
from WeatherDataCW import WeatherData
class WeatherDashboard:
servo_pin = 17
led_pin = 14
servoCorrection=0.5
maxPW=(2.0+servoCorrection)/1000
minPW=(1.0-servoCorrection)/1000
def __init__(self, servo_position=... | WeatherDashboardCW.py | 1,779 | adjust for servos that turn counter clockwise by default | 56 | en | 0.846388 |
# Generated by Django 2.0.3 on 2018-05-28 23:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0003_task_order'),
]
operations = [
migrations.AlterField(
model_name='task',
name='order',
field... | backend/api/migrations/0004_auto_20180528_2342.py | 371 | Generated by Django 2.0.3 on 2018-05-28 23:42 | 45 | en | 0.619848 |
import datetime
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.db.models import Sum
import commonware.log
import waffle
import amo
import mkt.constants.comm as comm
from amo.utils import cache_ns_key
from mkt.comm.utils import create_comm_note
from mkt.s... | mkt/reviewers/models.py | 14,819 | Returns common SQL to leaderboard calls.
Returns reviewers ordered by highest total points first.
Awards points to user based on moderated review.
Awards points to user based on an event and the queue.
`event` is one of the `REVIEWED_` keys in constants.
`status` is one of the `STATUS_` keys in constants.
Call the cor... | 1,747 | en | 0.8706 |
_base_ = [
'../../_base_/schedules/schedule_1200e.py', '../../_base_/runtime_10e.py'
]
model = dict(
type='DBNet',
pretrained='torchvision://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=-1,
norm_c... | configs/textdet/dbnet/dbnet_r18_fpnc_1200e_icdar2015.py | 3,143 | for visualizing img, pls uncomment it. img_norm_cfg = dict(mean=[0, 0, 0], std=[1, 1, 1], to_rgb=True) img aug random crop for visualizing img and gts, pls set visualize = True for debugging top k imgs select_first_k=200, select_first_k=100, select_first_k=100, | 261 | en | 0.592518 |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RVgam(RPackage):
"""Vector Generalized Linear and Additive Models.
An impleme... | var/spack/repos/builtin/packages/r-vgam/package.py | 2,652 | Vector Generalized Linear and Additive Models.
An implementation of about 6 major classes of statistical regression
models. The central algorithm is Fisher scoring and iterative reweighted
least squares. At the heart of this package are the vector generalized
linear and additive model (VGLM/VGAM) classes. VGLMs can be... | 1,384 | en | 0.849033 |
from django import db
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.contrib.contenttypes.views import shortcut
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest
from django.test... | django/contrib/contenttypes/tests.py | 2,909 | Make sure that the content type cache (see ContentTypeManager)
works correctly. Lookups for a particular content type -- by model or
by ID -- should hit the database only on the first lookup.
Check that the shortcut view (used for the admin "view on site"
functionality) returns a complete URL regardless of whether the ... | 642 | en | 0.874293 |
"""
BasicSR/codes/dataops/common.py (8-Nov-20)
https://github.com/victorca25/BasicSR/blob/dev2/codes/dataops/common.py
"""
import os
import math
import pickle
import random
import numpy as np
import torch
import cv2
import logging
import copy
from torchvision.utils import make_grid
#from dataops.colors import *
from... | mmedit/models/inpaintors/vic/common.py | 33,981 | get image path list from image folder
get image path list from lmdb
bgr version of matlab rgb2ycbcr
Python opencv library (cv2) cv2.COLOR_BGR2YCrCb has
different parameters with MATLAB color convertion.
only_y: only return Y channel
separate: if true, will returng the channels as
separate images
Input:
uint8, [... | 8,037 | en | 0.695498 |
# -*- coding: utf-8 -*-
from numpy import NaN as npNaN
from pandas import DataFrame, Series
# from pandas_ta.overlap.ma import ma
from .ma import ma
from pandas_ta.utils import get_offset, verify_series
def hilo(high, low, close, high_length=None, low_length=None, mamode=None, offset=None, **kwargs):
"""Indicator... | pandas_ta/overlap/hilo.py | 4,446 | Indicator: Gann HiLo (HiLo)
-*- coding: utf-8 -*- from pandas_ta.overlap.ma import ma Validate Arguments Calculate Result Offset Handle fills Name & Category | 159 | en | 0.391075 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
goods = []
while True:
command = input(">>> ").lower()
if command == 'exit':
break
elif command == 'add':
name = input("Название товара: ")
shop = input("Названи... | pythonProject/ind.py | 2,745 | !/usr/bin/env python3 -*- coding: utf-8 -*- Отсортировать список в случае необходимости. | 88 | ru | 0.907529 |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 08:32:13 2019
@author: Thiago
"""
import numpy as np
import pylab as pl
#%%
#Simulação de uma va
def va_estoque():
p=np.array([0.1, 0.2, 0.6, 0.1])
x=np.random.rand()
if 0 < x <= p[0]:
return 1
elif p[0] < x <= p[0]+p[1]:
return 2
... | aulas/05-06/variaveis_aleatorias.py | 1,683 | Created on Wed Jun 5 08:32:13 2019
@author: Thiago
-*- coding: utf-8 -*-%%Simulação de uma va%%simulação estoque%%simulação Urna de Ehrenfest%%Lei dos grandes números%%processos ergodicos%% | 193 | pt | 0.936932 |
"""Test GeoTIFF as process output."""
import numpy as np
import numpy.ma as ma
import os
import pytest
import rasterio
from rasterio.io import MemoryFile
from rio_cogeo.cogeo import cog_validate
import shutil
from tilematrix import Bounds
import warnings
import mapchete
from mapchete.errors import MapcheteConfigError... | test/test_formats_geotiff.py | 17,980 | Send GTiff via flask.
Check GeoTIFF proces output as input data.
Check GeoTIFF as output data.
Write and read output.
Pass on metadata tags from user process to rasterio.
Test GeoTIFF as process output.
get_path prepare_path profile write tiles_exist read read empty empty deflate with predictor with pytest.deprecated... | 1,602 | en | 0.604066 |
# Copyright (c) 2012, Cloudscaling
# 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... | manila/hacking/checks.py | 9,211 | Provides a simple framework for writing AST-based checks.
Subclasses should implement visit_* methods like any other AST visitor
implementation. When they detect an error for a particular node the
method should call ``self.add_error(offending_node)``. Details about
where in the code the error occurred will be pulled f... | 2,647 | en | 0.874736 |
# -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | src/secondaires/navigation/equipage/volontes/tenir_gouvernail.py | 3,986 | Classe représentant une volonté.
Cette volonté choisit un matelot pour tenir le gouvernail
du navire.
Retourne le matelot le plus apte à accomplir la volonté.
On fait crier l'ordre au personnage.
Exécute la volonté.
Extrait les arguments de la volonté.
Fichier contenant la volonté TenirGouvernail
-*-coding:Utf-8 -* ... | 1,805 | en | 0.714943 |
#https://blog.csdn.net/orangefly0214/article/details/81387077
import MultiTemplate
from MultiTemplate import TaskTemplate
# https://blog.csdn.net/u013812710/article/details/72886491
# https://blog.csdn.net/ismr_m/article/details/53100896
#https://blog.csdn.net/bcfdsagbfcisbg/article/details/78134172
import kubernetes
i... | experiment code/CPU Experiments Code/task_submit_save.py | 30,278 | https://blog.csdn.net/orangefly0214/article/details/81387077 https://blog.csdn.net/u013812710/article/details/72886491 https://blog.csdn.net/ismr_m/article/details/53100896https://blog.csdn.net/bcfdsagbfcisbg/article/details/78134172 v1.create_namespace()self.node_list = ['k8s-master','k8s-worker0','k8s-worker2','k8swo... | 471 | en | 0.544803 |
# -*- coding: utf-8 -*-
from datetime import datetime
import time
import unittest
from webapp2_caffeine.cache import CacheContainer
from webapp2_caffeine.cache import flush
class DummyCache(CacheContainer):
key = 'dummy_cache'
@property
def fresh_value(self):
return datetime.now()
class Cache... | tests/test_cache.py | 1,750 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Ttm 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.blocktools import create_block, create_coinbase, get_masternode_payment
from test_framewor... | test/functional/feature_block_reward_reallocation.py | 9,333 | !/usr/bin/env python3 Copyright (c) 2015-2020 The Ttm Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. 536870912 == 0x20000000, i.e. not signalling for anything CbTx Add quorum commitments from template create and send n... | 812 | en | 0.847823 |
import os
from datetime import datetime
import numpy as np
import xarray as xr
from pyoos.collectors.usgs.usgs_rest import UsgsRest
from pyoos.parsers.waterml import WaterML11ToPaegan
def get_usgs_data(station_id, start_date, end_date, parameter="00060", cache_dir=None):
"""Get river discharge data from the USGS... | src/ewatercycle/observation/usgs.py | 3,905 | Get river discharge data from the USGS REST web service.
See `U.S. Geological Survey Water Services
<https://waterservices.usgs.gov/>`_ (USGS)
Parameters
----------
station_id : str
The station id to get
start_date : str
String for start date in the format: 'YYYY-MM-dd', e.g. '1980-01-01'
end_date : str
S... | 1,516 | en | 0.448194 |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... | sdks/python/http_client/v1/polyaxon_sdk/api/users_v1_api.py | 47,203 | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
Create token # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_token(body, async_req... | 20,775 | en | 0.639755 |
#!/home/anitha/Track/virtual/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| virtual/bin/django-admin.py | 146 | !/home/anitha/Track/virtual/bin/python | 38 | en | 0.283846 |
import concurrent.futures
import datetime
import io
import logging
import os
import random
import time
import typing as t
import discord
import discord.ext.commands as commands
from PIL import Image, ImageDraw, ImageSequence, ImageFont
import bot.extensions as ext
from bot.consts import Colors
from bot... | bot/cogs/memes_cog/memes_cog.py | 7,666 | Open crab.gif and add our font Draw text on each frame of the gif Gonna be honest I don't quite understand how it works but I got it from the Pillow docs/issues draws the text on to the frame. Tries to center horizontally and tries to go as close to the bottom as possible crab.gif dimensions - 352 by 200 Immediately gr... | 517 | en | 0.936863 |
#! /usr/bin/env python3
# -*- coding: utf8 -*-
# Virtual dancers that consumes real GigglePixel packets
#
# To use, start this up and then bring up a server broadcasting GigglePixel.
# When this receives a palette packet, the dancing pair (whose humble wearables
# are only capable of displaying one color at a time api... | python-lib/example-consumer.py | 2,240 | ! /usr/bin/env python3 -*- coding: utf8 -*- Virtual dancers that consumes real GigglePixel packets To use, start this up and then bring up a server broadcasting GigglePixel. When this receives a palette packet, the dancing pair (whose humble wearables are only capable of displaying one color at a time apiece) will ligh... | 722 | en | 0.865394 |
from __future__ import unicode_literals
import io
import os
import re
import sys
from botocore.awsrequest import AWSPreparedRequest
from moto.core.utils import (
amzn_request_id,
str_to_rfc_1123_datetime,
py2_strip_unicode_keys,
)
from urllib.parse import (
parse_qs,
parse_qsl,
urlparse,
... | moto/s3/responses.py | 103,140 | Verify whether the provided metadata in the URL is also present in the headers
:param url: .../file.txt&content-type=app%2Fjson&Signature=..
:param headers: Content-Type=app/json
:return: True or False
strip the first '/' left by urlparse GOlang sends a request as url/?delete= (treating it as a normal key=value, even... | 4,160 | en | 0.857884 |
# -*- coding: utf-8 -*-
#
# Python Github documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 3 23:23:15 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | docs/conf.py | 8,480 | -*- coding: utf-8 -*- Python Github documentation build configuration file, created by sphinx-quickstart on Tue Feb 3 23:23:15 2015. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configuration v... | 7,108 | en | 0.660438 |
from setuptools import setup
setup(
name='dst',
version='0.1.5',
author='Jeroen Janssens',
author_email='jeroen@jeroenjanssens.com',
packages=['dst'],
url='http://datasciencetoolbox.org',
license='BSD',
description='Data Science Toolbox -- Start doing data science in minutes.',
long_... | manager/setup.py | 1,216 | https://pypi.python.org/pypi?:action=list_classifiers | 53 | en | 0.278693 |
#!coding:utf8
#author:yqq
#date:2020/4/30 0030 17:11
#description:
import os
import pymysql
SQL_PASSWD = os.environ.get('SQL_PWD')
def open(host : str,usr : str, passwd : str,db_name : str):
conn = pymysql.connect(host=host, user=usr,
password=passwd, db=db_name,
charset='utf8', ... | Python3/Tornado/apps/pg/PG_Admin/lib/sql.py | 1,105 | !coding:utf8author:yqqdate:2020/4/30 0030 17:11description:fixed bug by yqq 2019-05-01 | 86 | en | 0.434222 |
# Copyright 2018 Open Source Robotics Foundation, 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... | doc/extensions/empy_helpers/__init__.py | 3,028 | Copyright 2018 Open Source Robotics Foundation, 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 w... | 973 | en | 0.822695 |
"""
This magical module will rewrite all public methods in the public interface
of the library so they can run the loop on their own if it's not already
running. This rewrite may not be desirable if the end user always uses the
methods they way they should be ran, but it's incredibly useful for quick
scripts and the ru... | telethon/sync.py | 2,405 | Converts all the methods in the given types (class definitions)
into synchronous, which return either the coroutine or the result
based on whether ``asyncio's`` event loop is running.
This magical module will rewrite all public methods in the public interface
of the library so they can run the loop on their own if it's... | 982 | en | 0.933085 |
"""
Plotting code for nilearn
"""
# Original Authors: Chris Filo Gorgolewski, Gael Varoquaux
import os
import sys
import importlib
###############################################################################
# Make sure that we don't get DISPLAY problems when running without X on
# unices
def _set_mpl_backend():
... | nilearn/plotting/__init__.py | 3,118 | Plotting code for nilearn
Original Authors: Chris Filo Gorgolewski, Gael Varoquaux Make sure that we don't get DISPLAY problems when running without X on unices We are doing local imports here to avoid polluting our namespace No need to fail when running tests When matplotlib was successfully imported we need to chec... | 455 | en | 0.855367 |
import asyncio
import logging
import voluptuous as vol
from homeassistant.components.system_log import CONF_LOGGER
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant, Event
from homeassistant.helpers import config_v... | custom_components/xiaomi_gateway3/__init__.py | 8,812 | update global debug_mode for all gateways AA:BB:CC:DD:EE:FF => aabbccddeeff utils.migrate_unique_id(hass) entry for MiCloud login migrate data (also after first setup) to options add options handler check unload cloud integration remove all stats entities if disable stats init setup for each supported domains load devi... | 784 | en | 0.70239 |
# User class to hold name and __data
class User:
### Instance Variables ###
__userName = ""
__validUser = None
__data = []
__weights = []
__notes = []
__dates = []
__intWeights = []
__avgWeight = 0
__minWeight = 0
__maxWeight = 0
##########################
### G... | User.py | 2,065 | User class to hold name and __data Instance Variables Getters Setters | 71 | en | 0.596517 |
# Generated by Django 3.2.4 on 2021-07-04 11:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations ... | app/core/migrations/0001_initial.py | 2,470 | Generated by Django 3.2.4 on 2021-07-04 11:51 | 45 | en | 0.759579 |
from simplecoremidi import send_midi
from time import sleep
def play_a_scale():
root_note = 60 # This is middle C
channel = 1 # This is MIDI channel 1
note_on_action = 0x90
major_steps = [2, 2, 1, 2, 2, 2, 1, 0]
velocity = 127
note = root_note
for step in major_steps:
send_midi((... | simplecoremidi/examples/play_a_scale.py | 667 | This is middle C This is MIDI channel 1 A note-off is just a note-on with velocity 0 | 84 | en | 0.973469 |
# if funktioniert (fast) wie in allen anderen Sprachen
# - Einrückungen ersetzen { } Gilt für Python generell!
# - Es gibt ein elif statt einem else if
weight = 50 # kg
height = 190 # cm
bmi = weight / (height/100)**2
# bmi < 18.5 : Untergewicht
# bmi > 25 : Übergewicht
# sonst : Normalgewicht
if bmi < 18.5... | Crashkurs Python/03_if.py | 449 | if funktioniert (fast) wie in allen anderen Sprachen - Einrückungen ersetzen { } Gilt für Python generell! - Es gibt ein elif statt einem else if kg cm bmi < 18.5 : Untergewicht bmi > 25 : Übergewicht sonst : Normalgewicht | 229 | de | 0.978166 |
import sys
import os
import math
import shutil
import disk_sort
import struct
import operator
import logging
from decimal import Decimal
from fractions import Fraction
import numpy
from scipy.linalg import eig
import scipy.ndimage
import cProfile
import pstats
from osgeo import gdal, ogr
import pygeoprocessing.geopr... | invest_natcap/scenario_generator/scenario_generator.py | 59,952 | get eigenvalues and vectors get primary eigenvalue and vector priority vector = normalized primary eigenvector turn into list of real part values return nice rounded Decimal values with labels Compute pixel distance Convert to meters Compute raster stats so the raster is viewable in QGIS and Arcdef calculate_distance_r... | 5,961 | en | 0.574289 |
# Script that uses meshgrid to get map coordinates and then plots
# the DEM in 3d.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from osgeo import gdal
ds = gdal.Open(r'D:\osgeopy-data\Washington\dem\sthelens_utm.tif')
band = ds.GetRasterBand(1)
ov_band = band.GetOverview... | Chapter13/listing13_7.py | 1,370 | Script that uses meshgrid to get map coordinates and then plots the DEM in 3d. Calculate bounding coordinates. Get the x and y arrays. Make the 3D plot. Change the viewpoint and turn the ticks off. ax.view_init(elev=55, azim=60) plt.axis('off') Create an animation. import matplotlib.animation as animation def animate... | 578 | en | 0.634263 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.