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 |
|---|---|---|---|---|---|---|
# Copyright 2020-2022 Cambridge Quantum Computing
#
# 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 a... | modules/pytket-qsharp/pytket/extensions/qsharp/backends/estimator.py | 2,337 | Backend for estimating resources of a circuit using the QDK.
Calculate resource estimates for circuit.
:param circuit: Circuit to calculate or result handle to retrieve for
:type circuit: Union[Circuit, ResultHandle]
:return: Resource estimate
:rtype: Dict[str, int]
Copyright 2020-2022 Cambridge Quantum Computing Li... | 926 | en | 0.791702 |
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# L... | tests/benchmarks/constructs/LoopSmallRange.py | 1,325 | Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com Python test originally created or extracted from other peoples work. The parts from me are licensed as below. It is at least Free Software where it's copied from other people. In these cases, that will normally be indicated. Licensed under the Ap... | 985 | en | 0.90752 |
# Cliente
import socket
HOST = socket.gethostname() # Endereco IP do Servidor
PORT = 9999 # Porta que o Servidor esta
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dest = (HOST, PORT)
print('Para sair, digite $ + Enter')
msg = input("Entre com a mensagem:\n")
udp.sendto (msg.encode('utf-8'), dest)
while msg !=... | Projeto_de_Bloco/Etapa8/Ex03_cli.py | 507 | Cliente Endereco IP do Servidor Porta que o Servidor esta terminação do programa | 80 | pt | 0.873478 |
import sys
import random
import numpy as np
import cv2
src = cv2.imread('vlcsnap-2021-02-04-10h00m02s260.png')
#src = cv2.imread('2_11_11.png')
if src is None:
print('Image load failed!')
sys.exit()
src = cv2.resize(src, (0, 0), fx=0.5, fy=0.5)
src_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
h, w = src.sha... | contours.py | 1,312 | src = cv2.imread('2_11_11.png') 이진화 외곽선 검출 너무 작은 객체는 제외 외곽선 근사화 컨벡스가 아니면 제외 | 75 | ko | 0.99807 |
# -*- coding: utf-8 -*-
#
# 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 values have a default; values that are commented out
# serve to show the default.
import sys
imp... | docs/conf.py | 8,043 | -*- coding: utf-8 -*- 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 values have a default; values that are commented out serve to show the default. If extensions (or modules to docu... | 6,076 | en | 0.705783 |
# -*- coding: utf-8 -*-
import scrapy
from city_scrapers.spider import Spider
from datetime import datetime, timedelta
from dateutil.parser import parse as dateparse
import re
class Chi_school_community_action_councilSpider(Spider):
name = 'chi_school_community_action_council'
long_name = 'Chicago Public Schoo... | city_scrapers/spiders/chi_school_community_action_council.py | 8,916 | Parse or generate all-day status. Defaults to False.
Parse or generate classification (e.g. public health, education, etc).
Parse or generate community area.
Parse or generate event description.
Parse end date and time.
Parse or generate location. Latitude and longitude can be
left blank and will be geocoded later.
Par... | 2,087 | en | 0.754198 |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google 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/licenses/LICENSE-2.0
#
# Unless requi... | lib/surface/iot/registries/credentials/list.py | 2,188 | List credentials for a registry.
Run the list command.
Command to list all credentials for a registry.
-*- coding: utf-8 -*- Copyright 2017 Google 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 obtai... | 698 | en | 0.869911 |
from torch import nn
from pytorch_widedeep.wdtypes import * # noqa: F403
from pytorch_widedeep.models.tabular.mlp._layers import MLP
from pytorch_widedeep.models.tabular._base_tabular_model import (
BaseTabularModelWithAttention,
)
from pytorch_widedeep.models.tabular.transformers._encoders import SaintEncoder
... | pytorch_widedeep/models/tabular/transformers/saint.py | 11,763 | Defines a `SAINT model <https://arxiv.org/abs/2106.01342>`_ that
can be used as the ``deeptabular`` component of a Wide & Deep model or
independently by itself.
Parameters
----------
column_idx: Dict
Dict containing the index of the columns that will be passed through
the model. Required to slice the tensors.... | 5,955 | en | 0.673116 |
#!/usr/bin/env python
# encoding: utf-8
import socket
import sys
import tempfile
import time
import subprocess
import os
# function to get free port from ycmd
def GetUnusedLocalhostPort():
sock = socket.socket()
# This tells the OS to give us any free port in the range [1024 - 65535]
sock.bind(('', 0))
port =... | vim/bundle/vim-javacomplete2/autoload/javavibridge.py | 3,893 | !/usr/bin/env python encoding: utf-8 function to get free port from ycmd This tells the OS to give us any free port in the range [1024 - 65535] A wrapper for subprocess.Popen that works around a Popen bug on Windows. | 216 | en | 0.795214 |
"""This file defines the database connection, plus some terminal commands for
setting up and tearing down the database.
Do not import anything directly from `backend.database._core`. Instead, import
from `backend.database`.
"""
from typing import Optional
import os
import pandas as pd
import click
from flask import ... | backend/database/core.py | 4,870 | Create the database from nothing.
Collection of database commands.
Delete the database.
Run SQL from a file. It will return a Pandas DataFrame if it selected
anything; otherwise it will return None.
I do not recommend you use this function too often. In general we should be
using the SQLAlchemy ORM. That said, it's a ... | 841 | en | 0.827592 |
#! /usr/bin/env python
# -*- coding: latin-1; -*-
'''
Copyright 2018 University of Liège
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 re... | tests/PFEM_Metafor/waterColoumnFallWithFlexibleObstacle_obstacle_Mtf_E_1_0e6_EAS.py | 3,555 | default model parameters
Copyright 2018 University of Liège
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... | 1,441 | en | 0.680677 |
#!/usr/bin/env python
import numpy
import scipy
from scipy import io
data_dict = scipy.io.loadmat('../data/hmsvm_data_large_integer.mat', struct_as_record=False)
parameter_list=[[data_dict]]
def structure_discrete_hmsvm_bmrm (m_data_dict=data_dict):
import shogun as sg
try:
_ = sg.create_machine("DualLibQPBMSO... | examples/undocumented/python/structure_discrete_hmsvm_bmrm.py | 1,228 | !/usr/bin/env python given by the data file usedprint sosvm.get_w()print('Accuracy = %.4f' % acc) | 97 | en | 0.346604 |
###
# Copyright (c) 2003-2005, Jeremiah Fincher
# Copyright (c) 2009, James McCoy
# 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 copyr... | plugins/String/test.py | 6,964 | Groups a given sequence into sublists of length groupSize.
Copyright (c) 2003-2005, Jeremiah Fincher Copyright (c) 2009, James McCoy 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 o... | 1,937 | en | 0.896877 |
# Copyright 2013: Mirantis 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/licenses/LICENSE-2.0
#
# Unless required b... | rally/common/objects/__init__.py | 963 | Contains the Rally objects.
Copyright 2013: Mirantis 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/licenses/LICENSE-2.0 Unless ... | 655 | en | 0.8563 |
from itertools import combinations
from typing import Callable, Dict, Set, Tuple, Union
import networkx as nx
import pandas as pd
from causal_networkx import ADMG
from causal_networkx.discovery.classes import ConstraintDiscovery
def _has_both_edges(dag, i, j):
return dag.has_edge(i, j) and dag.has_edge(j, i)
... | causal_networkx/discovery/pcalg.py | 8,254 | Peter and Clarke (PC) algorithm for causal discovery.
Assumes causal sufficiency, that is, all confounders in the
causal graph are observed variables.
Parameters
----------
ci_estimator : Callable
The conditional independence test function. The arguments of the estimator should
be data, node, node to compare,... | 3,168 | en | 0.627399 |
# Copyright 2016 Rackspace
# Copyright 2016 Intel 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/LICE... | glance-18.0.0/glance/tests/functional/db/test_migrations.py | 7,328 | Copyright 2016 Rackspace Copyright 2016 Intel 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 re... | 744 | en | 0.864849 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Arne Neumann <discoursegraphs.programming@arne.cl>
"""
The ``brat`` module converts discourse graphs into brat annotation
files.
"""
import os
import codecs
import math
import itertools
from collections import defaultdict
import brewer2mpl
from unidecode import... | src/discoursegraphs/readwrite/brat.py | 5,238 | converts a document graph with pointing chains into a string representation
of a brat *.ann file.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which might contain pointing chains (e.g. coreference links)
layer : str or None
the name of the layer that contains the pointing chains (e.... | 1,024 | en | 0.62629 |
# Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Bob Callaway. All rights reserved.
#
# Licensed under the Apac... | cinder/tests/unit/volume/drivers/netapp/dataontap/client/test_api.py | 6,343 | Copyright (c) 2014 Ben Swartzlander. All rights reserved. Copyright (c) 2014 Navneet Singh. All rights reserved. Copyright (c) 2014 Clinton Knight. All rights reserved. Copyright (c) 2014 Alex Meade. All rights reserved. Copyright (c) 2014 Bob Callaway. All rights reserved. Licensed under the Apache License, Ve... | 829 | en | 0.867821 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0... | offline_messages/migrations/0001_initial.py | 961 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
from functools import partial
from typing import List, Optional, Union
from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer,
BartTokenizer, BertModel, BertTokenizer,
CamembertModel, CamembertTokenizer, CTRLModel,
... | summarizer/bert.py | 7,082 | Summarizer based on the BERT model.
Newer style that has keywords for models and tokenizers, but allows the user to change the type.
This is the parent Bert Summarizer model. New methods should implement this class.
:param model: This parameter is associated with the inherit string parameters from the transformers lib... | 2,457 | en | 0.755166 |
from json import load
from typing import Union
import pygame as pg
from pygame import Surface, event
from pygame.display import set_mode, set_caption, set_icon, get_surface, update
from pygame.key import get_pressed as get_key_pressed
from pygame.mouse import get_pressed as get_mouse_pressed
from pygame.time import Cl... | source/scripts/manager.py | 4,420 | load load config get config load images create and initialize create music create scenes initialize scenes noinspection PyAttributeOutsideInit | 147 | en | 0.311266 |
from __future__ import absolute_import
from __future__ import print_function
import graph_tool.all as gt
import numpy as np
from .base import LabelGraphClustererBase
from .helpers import _membership_to_list_of_communities, _overlapping_membership_to_list_of_communities
class StochasticBlockModel:
"""A Stochastic... | yyskmultilearn/cluster/graphtool.py | 9,395 | Fits a Stochastic Block Model to the Label Graph and infers the communities
This clusterer clusters the label space using by fitting a stochastic block
model to the label network and inferring the community structure using graph-tool.
The obtained community structure is returned as the label clustering. More informati... | 5,829 | en | 0.72783 |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | tests/unit/bokeh/sampledata/test_glucose.py | 2,001 | ----------------------------------------------------------------------------- Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. All rights reserved. The full license is in the file LICENSE.txt, distributed with this software.------------------------------------------------------------------------------... | 1,609 | en | 0.230668 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019 - 2021 Geode-solutions
#
# 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, co... | bindings/python/tests/mesh/test-py-ply.py | 1,993 | -*- coding: utf-8 -*- Copyright (c) 2019 - 2021 Geode-solutions 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, me... | 1,084 | en | 0.87551 |
# YouTube: https://youtu.be/8lP9h4gaKYA
# Publicação: https://caffeinealgorithm.com/blog/20210914/funcao-print-e-strings-em-python/
print('Estamos a usar a função print() e eu sou uma string.')
print("Continuo a ser uma string.")
print('A Maria disse que o Miguel estava "doente".') # A Maria disse que o Miguel es... | Programar em Python/02-Funcao-print-e-Strings.py | 454 | YouTube: https://youtu.be/8lP9h4gaKYA Publicação: https://caffeinealgorithm.com/blog/20210914/funcao-print-e-strings-em-python/ A Maria disse que o Miguel estava "doente". I'm writing in English. Caffeine Algorithm | 214 | pt | 0.435382 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
DESTRUIDO = 'Destruido'
ATIVO = 'Ativo'
GRAVIDADE = 10 # m/s^2
class Ator():
"""
Classe que representa um ator. Ele representa um ponto cartesiano na tela.
"""
_caracter_ativo = 'A'
_caracter_destruido = ' '
def _... | atores.py | 5,030 | Classe que representa um ator. Ele representa um ponto cartesiano na tela.
Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status
:param x: Posição horizontal inicial do ator
:param y: Posição vertical inicial do ator
Método de inicialização de pássaro.
Deve chamar a inicialização d... | 2,159 | pt | 0.985207 |
import sys
sys.path.append("..")
import os
import torch
import torchvision as tv
import numpy as np
from torch.utils.data import DataLoader
from torchvision import models
import torch.nn as nn
from utils import makedirs, tensor2cuda, load_model
from argument import parser
from visualization import VanillaBackprop
impo... | visualization/visualize.py | 3,405 | model_bns = resnet50dsbn(pretrained=args.pretrain, widefactor=args.widefactor) model_bns.fc = nn.Linear(model_bns.fc.in_features, num_classes) load_model(model_bns, args.load_checkpoint) model_bns.cuda() VBP = VanillaBackprop(model_bns) grad_bn0 = VBP.generate_gradients(data, label, [0]) data: (1,3,96,96) label: (1,3)... | 631 | en | 0.267578 |
import numpy as np
import numpy.ma as npma
from scipy import stats
import matplotlib.pyplot as plt
import baspy as bp
import fnmatch
"""
Created on Wed Nov 27 18:34 2019
@author: Christine McKenna
========================================================================
Purpose: Plots Supp Fig 2, a pdf of all possibl... | analysis_figure_code/SuppFig2/SuppFig2.py | 3,785 | Required directories ------ Load in CMIP6 data ------ Load models Load catalogue so can extract runids Process data, one model and RunID at a time Get data for model Only keep r1i1p1f? Get data for each RunID Load gsat data Remove any drift Calculate trends If model used in Supp Fig 8 save pdf of 20y trends ------ Plot... | 358 | en | 0.631965 |
import requests
def gen_from_urls(urls: tuple) -> tuple:
for resp in (requests.get(url) for url in urls):
# yield returns only 1 items at a time.
yield len(resp.content), resp.status_code, resp.url
if __name__ == "__main__":
urls = (
"https://www.oreilly.com/",
"https://twitt... | SRC/Chapter_13-Advanced-Iteration/12_function_yield.py | 463 | yield returns only 1 items at a time. | 37 | en | 0.823327 |
# Copyright 2015 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 ... | ros2_batch_job/__main__.py | 32,556 | Use curl to fetch a repos file and display the contents.
Copyright 2015 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/LICEN... | 5,143 | en | 0.868553 |
"""database session management."""
import logging
import os
from contextlib import contextmanager
from typing import Iterator
import attr
import psycopg2
import sqlalchemy as sa
from fastapi_utils.session import FastAPISessionMaker as _FastAPISessionMaker
from sqlalchemy.orm import Session as SqlSession
from stac_fas... | stac_fastapi/sqlalchemy/stac_fastapi/sqlalchemy/session.py | 2,120 | FastAPISessionMaker.
Database session management.
Post init handler.
Override base method to include exception handling.
Create from environment.
Create a Session object from settings.
database session management. | 213 | en | 0.710843 |
# -*- coding: utf-8 -*-
import pkg_resources
import platform
API_YOUTU_END_POINT = 'http://api.youtu.qq.com/'
API_TENCENTYUN_END_POINT = 'https://youtu.api.qcloud.com/'
API_YOUTU_VIP_END_POINT = 'https://vip-api.youtu.qq.com/'
APPID = 'xxx'
SECRET_ID = 'xxx'
SECRET_KEY = 'xx'
USER_ID = 'xx'
_config = {
'end_poin... | TencentYoutuyun/conf.py | 855 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
def updateParams(k, alpha, N,sum_log_di, x, h):
div_xByAlpha = np.divide(x,alpha)
powK_div_xByAlpha = np.power(div_xByAlpha, k)
log_div_xByAlpha = np.log(div_xByAlpha)
sum_powK_div_diByAlpha = np.sum(... | 01/Task13.py | 2,076 | N = d.shape[0]loading histograms | 32 | en | 0.30444 |
from nose.tools import eq_, ok_
from nose.plugins.skip import SkipTest
# Skip test on PY3
from flask_admin._compat import PY2, as_unicode
if not PY2:
raise SkipTest('MongoEngine is not Python 3 compatible')
from wtforms import fields
from flask_admin import form
from flask_admin.contrib.mongoengine import ModelV... | sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/tests/mongoengine/test_basic.py | 27,408 | Skip test on PY3 Make some test clients Test in-line edit field rendering Form - Test basic in-line edit functionality confirm the value has changed Test validation error Test invalid primary key Test editing column not in column_editable_list Test in-line editing for relations confirm the value has changed fill DB wit... | 1,369 | en | 0.542387 |
"""
This file offers the methods to automatically retrieve the graph Mycobacterium sp. 1554424.7.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--pr... | bindings/python/ensmallen/datasets/string/mycobacteriumsp15544247.py | 3,505 | Return new instance of the Mycobacterium sp. 1554424.7 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to preprocess the g... | 2,708 | en | 0.70372 |
"""
How to use RxPY to prepare batches for asyncio client.
"""
import asyncio
from csv import DictReader
import rx
from rx import operators as ops
from rx.scheduler.eventloop import AsyncIOScheduler
from influxdb_client import Point
from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync
def cs... | examples/asynchronous_batching.py | 2,087 | Parse your CSV file into generator
How to use RxPY to prepare batches for asyncio client. | 89 | en | 0.810447 |
# Copyright 2021 ZBW – Leibniz Information Centre for Economics
#
# 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 b... | tests/label_calibration/test_simple.py | 1,591 | Copyright 2021 ZBW – Leibniz Information Centre for Economics 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... | 593 | en | 0.843646 |
import os
import requests
WEBHOOK_URL = os.environ['DJANGO_WEBHOOK_URL']
def send_message(author_name: str, message: str) -> bool:
json_data = {
# 'content': f'**{name}**\n\n{message}'
'embeds': [
{
'author': {
'name': author_name,
}... | round/webhooks.py | 535 | 'content': f'**{name}**\n\n{message}' | 37 | it | 0.114443 |
"""
ASGI config for anyberry project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETT... | web-api/anyberry/asgi.py | 393 | ASGI config for anyberry project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ | 214 | en | 0.732686 |
"""
The MIT License (MIT)
Copyright (c) 2017 Andreas Poppele
Copyright (c) 2017 Roland Jaeger
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... | gitScrabber/scrabTasks/file/languageDetector.py | 9,248 | Calculates the main language (maximum of files extensions)
:param report: The report
:returns: The main language.
Calculates the used languages by throwing away the extension counts and
collapsing them to the language. Only languages that have at least one
file extension are kept and will appear in the report
:p... | 2,824 | en | 0.873942 |
# Core Pkgs
import streamlit as st
# EDA Pkgs
import pandas as pd
import numpy as np
from PIL import Image
# Utils
import os
import joblib
import hashlib
# passlib,bcrypt
# Data Viz Pkgs
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
# DB
from managed_db import *
# Password
def generate_ha... | app.py | 10,986 | Hep Mortality Prediction App
Core Pkgs EDA Pkgs Utils passlib,bcrypt Data Viz Pkgs DB Password Load ML Models ML Interpretation Avatar Image using a url st.title("Hepatitis Mortality Prediction App"),"Metrics"] st.text("What is Hepatitis?") if password == "12345": Freq Dist Plot ML st.write(prediction) prediction_lab... | 557 | en | 0.431717 |
# Modification 2020 RangiLyu
# Copyright 2018-2019 Open-MMLab.
# 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 applicabl... | mmdet3d/models/dense_heads/assigner/assign_result.py | 8,442 | Stores assignments between predicted and truth boxes.
Attributes:
num_gts (int): the number of truth boxes considered when computing this
assignment
gt_inds (LongTensor): for each predicted box indicates the 1-based
index of the assigned truth box. 0 means unassigned and -1 means
ignor... | 3,185 | en | 0.771685 |
"""
Interface item implementation. There are several notations supported
- class box with interface stereotype
- folded interface
- ball is drawn to indicate provided interface
- socket is drawn to indicate required interface
Interface item can act as icon of assembly connector, see
`gaphor.diagram.connector`... | gaphor/diagram/classes/interface.py | 13,001 | Interface item supporting class box, folded notations and assembly
connector icon mode.
When in folded mode, provided (ball) notation is used by default.
Interface connection port.
It is simple line port, which changes glue behaviour depending on
interface folded state. If interface is folded, then
`InterfacePort.glu... | 3,699 | en | 0.854653 |
from optparse import OptionParser
import os,sys
import itertools
import re
def readSrc(src_dir):
lines=[]
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.endswith(".cpp"):
lines+=["New_file "+ file]
lines_file = open(os.path.join(root, ... | Outils/TRIOXDATA/XTriou/Extract_xdata.py | 8,702 | Main function.
on rajoute un blanc pour avoir le dernier mot des commentaires revoir les comm ne marchent pas pour mpcube elif (re.findall("//.*//[ ]*"+xd,line)): continue traitement des classes print dico[nameClass] print li print desc21/0 print nameClass, line 1/0 traitement des parametres traitement des dictionn... | 385 | fr | 0.62502 |
__all__ = [
'BaseClassificationAggregator',
'BaseImageSegmentationAggregator',
'BaseEmbeddingsAggregator',
'BaseTextsAggregator',
'BasePairwiseAggregator',
]
import attr
from .. import annotations
@attr.s
@annotations.manage_docstring
class BaseClassificationAggregator:
""" This is a base cla... | build/lib/crowdkit/aggregation/base/__init__.py | 3,219 | This is a base class for all classification aggregators
This is a base class for all embeddings aggregators
This is a base class for all image segmentation aggregators
This is a base class for all pairwise comparison aggregators
This is a base class for all texts aggregators | 275 | en | 0.869516 |
#
# 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/examples/snippets/util.py | 2,317 | Asserts a PCollection of strings matches the expected stdout elements.
Args:
actual (beam.PCollection): A PCollection.
expected (List[str]): A list of stdout elements, one line per element.
normalize_fn (Function[any]): A function to normalize elements before
comparing them. Can be used to sort lists befor... | 1,367 | en | 0.868172 |
import numpy as np
__all__ = ["Kernel", "Uncorrelated", "ExpSquared", "Matern"]
class Kernel(object):
def __init__(self, parnames=[], name=''):
"""
:param parnames:
A list of names of the kernel params, used to alias the intrinsic
parameter names. This way different inst... | prospect/likelihood/kernels.py | 3,070 | Return a covariance matrix, given a metric. Optionally, multiply
the output kernel by a weight function to induce non-stationarity.
:param parnames:
A list of names of the kernel params, used to alias the intrinsic
parameter names. This way different instances of the same kernel
can have different paramet... | 711 | en | 0.724668 |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
from spack.version import Version
class Meme(AutotoolsPackage):
"""The MEME Suite allows the bio... | var/spack/repos/builtin/packages/meme/package.py | 2,109 | The MEME Suite allows the biologist to discover novel motifs in
collections of unaligned nucleotide or protein sequences, and to perform a
wide variety of other motif-based analyses.
Copyright 2013-2020 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for ... | 435 | en | 0.830507 |
# -*- coding: utf-8 -*-
"""
Created on Sun May 20 11:35:03 2018
@author: DanielM
"""
import os
import numpy as np
import shelve
# Setup some parameters given by paradigm_frequency_inhibition.py
stim_delay = 100 # ms
dt = 0.01 # ms
stim_dtp = stim_delay / dt
data_path = "C:\\Users\\Daniel\\pyDentateData\\tuning\\r... | analysis/tuning_get_seclamp_currents_frequency.py | 904 | Created on Sun May 20 11:35:03 2018
@author: DanielM
-*- coding: utf-8 -*- Setup some parameters given by paradigm_frequency_inhibition.py ms ms | 147 | en | 0.692833 |
# -*- coding: utf-8 -*-
"""Top-level package for medium-shell."""
__author__ = 'Colin Bitterfield'
__email__ = 'cbitterfield@gmail.com'
__version__ = '0.1.0'
| medium-shell/__init__.py | 160 | Top-level package for medium-shell.
-*- coding: utf-8 -*- | 59 | en | 0.853277 |
class Person(object):
""" Class Person for testing python.
Following packages need to be installed:
- requests
:param name: person's name, string
:param age: person's age, integer
:param phone: person's phone, string
:rtype: object
"""
def __init__(self, name, age, phone):
... | person.py | 3,666 | Class Employee for testing python.
:param name: person's name, string
:param age: person's age, integer
:param phone: person's phone, string
:param phone: person's title, string
:param phone: person's salary, string
:param phone: person's location, string
:rtype: object
Class Person for testing python.
Following pack... | 1,591 | en | 0.673624 |
# coding: utf8
from spacy.symbols import POS, TAG, DEP, LEMMA, HEAD
from spacy.language import Language
from spacy.tokens import Doc
from spacy.util import get_lang_class
import numpy
import re
class StanfordNLPLanguage(Language):
def __init__(self, snlp, meta=None, **kwargs):
"""Initialize the Language c... | spacy_stanfordnlp/language.py | 6,443 | Because we're only running the StanfordNLP pipeline once and don't split
it up into spaCy pipeline components, we'll set all the attributes within
a custom tokenizer. The tokenizer is currently expected to
implement serialization methods so we're mocking them up here. When loading
the serialized nlp object back in, you... | 2,129 | en | 0.668757 |
import socket
from pywincffi.core import dist
from pywincffi.dev.testutil import TestCase, mock_library
from pywincffi.exceptions import WindowsAPIError
from pywincffi.kernel32 import CloseHandle
from pywincffi.wintypes import LPWSANETWORKEVENTS, socket_from_object
from pywincffi.ws2_32 import (
WSAGetLastError, W... | tests/test_ws2_32/test_events.py | 4,879 | Has some common methods used by tests in this module
Tests for ``pywincffi.ws2_32.events.WSACreateEvent``
Tests for ``pywincffi.ws2_32.events.WSAEnumNetworkEvents``
Tests for ``pywincffi.ws2_32.events.WSAEventSelect``
Tests for ``pywincffi.ws2_32.events.WSAGetLastError``
Creates a local socket listening on a random por... | 690 | en | 0.700993 |
try :
from facepy import GraphAPI
from facepy.exceptions import OAuthError
import time
from sys import stdout
except ImportError:
print("Import Error")
token = 'Enter-Token-Here'
OWNER_NAME = ''
photos_together = {}
no_of_comments = {}
words_in_comment = {}
no_of_messages = {}
total_chat_length = {... | friendship_py3.py | 8,291 | Until we get an empty result pageIterating through all the tags in the current result pageIf the tag was encountered before incrementElse initialize new countGet the nect result pageIgnore Comment by owner on his own photosIf a comment by this person was encountered beforeIf this is a new commentorThis can happen in me... | 391 | en | 0.911373 |
from rest_framework import permissions
class PolyaxonPermission(permissions.BasePermission):
"""
Polyaxon Base permission system.
"""
def has_object_permission(self, request, view, obj):
return False
| polyaxon/scopes/permissions/base.py | 227 | Polyaxon Base permission system. | 32 | en | 0.494616 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import typing # NOQA: F401
from nixnet import _cconsts
from nixnet import _errors
from nixnet import _props
from nixnet import constants
from nixnet.database import _collection
from nixnet.database import _d... | nixnet/database/_subframe.py | 8,889 | Database subframe
Check this subframe's configuration status.
By default, incorrectly configured subframes in the database are not returned from
:any:`Frame.mux_subframes` because they cannot be used in the bus communication.
You can change this behavior by setting :any:`Database.show_invalid_from_open` to `True`.
Wh... | 5,324 | en | 0.706002 |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... | Data-Engineering-with-Databricks/06 - Incremental Data Processing/DE 6.1 - Incremental Data Ingestion with Auto Loader.py | 11,807 | Databricks notebook source MAGIC %md-sandbox MAGIC MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> MAGIC </div> COMMAND ---------- MAGIC %md MAGIC MA... | 10,104 | en | 0.782738 |
import numpy as np
def log_gaussian(x, mean, sigma):
"""
Computes the log-probability of X=x for a Gaussian of mean=mean and sigma=sigma
Parameters
----------
x
mean
sigma
Returns
-------
"""
log_pdf = -(x - mean) ** 2 / (2 * sigma ** 2)
log_pdf = log_pdf - np.log((n... | lstchain/image/pdf.py | 910 | Computes the log-probability of X=x for a Gaussian of mean=mean and sigma=sigma
Parameters
----------
x
mean
sigma
Returns
------- | 131 | en | 0.506436 |
from django.contrib.auth.models import AbstractUser
from django.db import models
import uuid
# class Role(models.Model):
# '''
# The Role entries are managed by the system,
# automatically created via a Django data migration.
# '''
# name = models.CharField(max_length=50, default=1)
# de... | user/models.py | 1,823 | Base model for patient
and doctor
class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' name = models.CharField(max_length=50, default=1) def __str__(self): return self.nameIDRolePersonalContact DetailsAddressS... | 325 | en | 0.556077 |
'''
'''
import hashlib
import uuid
import logging
from cassandra.cluster import Cluster
from cassandra.policies import DCAwareRoundRobinPolicy
from subprocess import PIPE, Popen
from kazoo.client import KazooClient
from multiprocessing import Process
class CassandraAware:
def init__(self):
self.cluster ... | clique3.py | 8,543 | fxxx verify the transaction sanity insert into candidate insert into candidate | 78 | en | 0.744145 |
from ctypes import cdll, c_int, c_ulonglong, c_char_p
import time
import json
import thread
def runList(ll, interpID, inputList):
strList = json.dumps(inputList)
listID = ll.elconn_list_from_json(strList.encode())
resultID = ll.elconn_call(interpID, listID)
return resultID
# === load library
ll = cd... | connective/connective/python/elconn_trial_script.py | 3,090 | === load library === set return types === set argument types == Manual Test 1 == Using the interpreter == Manual Test 2 == Connecting to remote interpreter == Manual Test 3 == Value on server == Manual Test 3 == Directory with value on server == Manual Test 5 == Request queue -- schedule something to be enqueued later ... | 353 | en | 0.671862 |
from lxml import html
from Proxy import Proxy
import urllib.request
import urllib.parse
import urllib.error
import data
import sys
import bcolors
class Search :
#Initializes variables
def __init__(self, useproxy, retries = None, verbose = False, sleep = 5):
self.urls = [] # contains scraped urls
... | dev/Search.py | 3,055 | Initializes variables contains scraped urls contains blacklisted proxies dictates use of proxy sets the number of search retries, if None => unlimited sets verbosity level dictates sleep while searching for urls Returns the HTML page of a website. It incorporates error checking and retries If an unknown error was raise... | 420 | en | 0.811896 |
# !pip install transformers
import torch
from transformers.file_utils import is_tf_available, is_torch_available, is_torch_tpu_available
from transformers import BertTokenizerFast, BertForSequenceClassification
from transformers import Trainer, TrainingArguments
import numpy as np
import random
from sklearn.datasets i... | machine-learning/nlp/bert-text-classification/train.py | 4,683 | Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if
installed).
Args:
seed (:obj:`int`): The seed to set.
!pip install transformers safe to call this function even if cuda is not available the model we gonna train, base uncased BERT check text classific... | 1,546 | en | 0.776471 |
# DADSA - Assignment 1
# Reece Benson
import json
from classes import Player as Player
from classes import Season as Season
from classes import Tournament as Tournament
from classes import Round as Round
from classes import Match as Match
class Handler():
# Define the variables we will be using
app = None
... | .history/classes/Handler_20171106200011.py | 2,535 | DADSA - Assignment 1 Reece Benson Define the variables we will be using Define our Application within this Handler class Used to load all data into memory This function will create our seasons and implement the genders & playersTODO: Implement load_seasons() Used to load prize money Make our prize_money a dictionary Ma... | 672 | en | 0.903276 |
'''
Test script for GrFNN, plotting the entrainment for a sin wave of changing frequency.
@author T. Kaplan
'''
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import time
from gfnn import FrequencyType, FrequencyDist, ZParams, GrFNN
from plot import spectro_plot
# Constr... | model/sin_example_gfnn.py | 1,265 | Test script for GrFNN, plotting the entrainment for a sin wave of changing frequency.
@author T. Kaplan
Construct our model by instantiating the class defined above Stimulus - 50 seconds of FHz sin, at a changing frequency (4->2) Prepare an initial plot Update plot: | 269 | en | 0.695264 |
'''
Adapted from https://github.com/IntelligentQuadruped, with permission
Description: Module to connect to camera and retrieve RGB and depth data. Currently supports the Intel RealSense R200 Camera.
'''
import numpy as np
import logging
import time
import cv2
import matplotlib.pyplot as plt
from skimage.transform imp... | Camera/camera.py | 6,258 | Object to get data from R200
Intitalizes Camera object
Establishes connection to R200 camera
Disconnects from R200 camera
Retrieves depth frames (and RGB if true) from R200 input, cleans and averages depth images
Unit tests
Takes in a depth image and rescales it
Args:
height_ratio: Determines fraction of rows to ... | 939 | en | 0.643184 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-08 21:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_auto_20171108_2343'),
]
operations = [
migrations.AddField(
... | mpesa_api/core/migrations/0012_onlinecheckout_transaction_date.py | 476 | -*- coding: utf-8 -*- Generated by Django 1.11.6 on 2017-11-08 21:18 | 68 | en | 0.674797 |
#!/usr/bin/env python
# Copyright 2012 La Honda Research Center, 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 ap... | tools/clean_file_locks.py | 1,670 | Main loop.
process command line options.
clean_file_locks.py - Cleans stale interprocess locks
This rountine can be used to find and delete stale lock files from
nova's interprocess synchroization. It can be used safely while services
are running.
!/usr/bin/env python Copyright 2012 La Honda Research Center, Inc. Li... | 835 | en | 0.855426 |
# Copyright 2018 Yegor Bitensky
# 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 writing, ... | tests/utils.py | 683 | Copyright 2018 Yegor Bitensky 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 writing, software distri... | 551 | en | 0.862185 |
import redis
import json
from itertools import zip_longest
from common.config import REDIS_ADDR, REDIS_PORT, REDIS_DB
def batcher(iterable, n):
args = [iter(iterable)] * n
return zip_longest(*args)
def insert2redis(ids, dataList):
# dataList [{"videoId": id, "feat": feat, "name": name}]
r = redis.Re... | solutions/video_similarity_search/search-video-demo/search/controller/database.py | 1,942 | dataList [{"videoId": id, "feat": feat, "name": name}] TODO return error | 72 | en | 0.232107 |
"""
show_interface.py
IOSXE parsers for the following show commands:
* show interfaces
* show ip interfaces <interface>
* show ip interface brief
* show ip interface brief | include Vlan
* show interfaces switchport
* show ip interface
* show interfaces <interface>
* show ipv6 i... | src/genie/libs/parser/iosxe/show_interface.py | 155,737 | parser for
* show interface {interface} transceiver detail
Schema for:
show interface {interface} transceiver detail
parser for show interfaces
show interfaces <interface>
Parser for:
show interfaces accounting
show interfaces <interface> accounting
Schema for show interfaces accounting
parser for show interfaces <WOR... | 20,215 | en | 0.689947 |
import os
from setuptools import setup, find_packages
from guizero import __name__, __package__, __version__, __author__
## This is a Python 3 package only
from sys import version_info
if version_info.major != 3:
print("This package will only work with Python 3. \n"
"If you already have Python 3 installe... | setup.py | 2,892 | This is a Python 3 package only | 31 | en | 0.873223 |
import os
import logging
import seqlog
from seqlog import StructuredRootLogger, StructuredLogger, ConsoleStructuredLogHandler
if bool(os.environ.get('PROD')):
# Production logging setup
url = os.environ.get('SEQ_URL')
key = os.environ.get('SEQ_BOT_KEY')
if not key:
raise Exception('SEQ_BOT_K... | ClemBot.Bot/bot/__init__.py | 1,131 | Production logging setup Initialize the seq logging url before the secrets are loaded this is ok because seq logging only happens in prod seconds Development logging setup | 171 | en | 0.876975 |
import filecmp
import os
from os.path import abspath, dirname, join, exists
import pytest
from image_diet import storage
THIS_DIR = abspath(dirname(__file__))
@pytest.fixture
def dietstorage():
dietstorage = storage.DietStorage()
# Filesystem storage parameters
dietstorage.location = THIS_DIR
diets... | tests/test_storage.py | 5,087 | Filesystem storage parameters Original test_file , working copy (can be changed), internal copy if it exists and content of original file Delete configuration section so that DietException will be raised | 203 | en | 0.701772 |
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... | project/example/urls.py | 1,070 | project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | 704 | en | 0.590678 |
import uuid
import requests;
import os;
from PIL import Image
from io import BytesIO
__name__ = "download_images"
def download(link, counter, size, root_folder, class_name):
IMG_SIZE = size, size
response = requests.get(link, timeout=3.000)
file = BytesIO(response.content)
img = Image.open(file)
i... | idt/utils/download_images.py | 815 | Split last part of url to get image nameCheck if another file of the same name already exists | 93 | en | 0.831035 |
import time
import cv2
import numpy as np
j = 1
while 1:
path = 'Bearing/' + str(j) + '.jpg'
img = cv2.imread(path)
img_copy = img.copy()
img = cv2.blur(img, (1, 1))
gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
# flag, img_copy = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
imgra... | ellcircle_detect.py | 1,772 | flag, img_copy = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) Canny边缘检测,参数可更改 cv2.imshow("imgray",imgray) contours为轮廓集,可以计算轮廓的长度、面积等 S1 = cv2.contourArea(cnt) 格林公式计算的实际面积 拟合椭圆 ellipse = [ center(x, y) , long short (a, b), angle ] S2 = math.pi * ell[1][0] * ell[1][1] 理论面积 and a > 0 and b > 0 and a < 0 and b < 0:... | 327 | en | 0.339701 |
# Generated by Django 2.0.8 on 2018-09-21 10:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_challenges', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='challenge',
name='challenge_co... | app_challenges/migrations/0002_auto_20180921_1031.py | 459 | Generated by Django 2.0.8 on 2018-09-21 10:31 | 45 | en | 0.571861 |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import base64
import hashlib
import math
from ccxt.base.errors import ExchangeError
f... | python/ccxt/async_support/btcmarkets.py | 25,073 | -*- coding: utf-8 -*- PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.mdhow-to-contribute-code Australia market data cached for 1 second(trades cached for 2 seconds) they promise it's coming soon... todo: find more statuses { statu... | 1,992 | en | 0.602371 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 该例程将发布/person_info话题,自定义消息类型learning_communication::PersonMsg
import rospy
from learning_communication.msg import PersonMsg
def velocity_publisher():
# ROS节点初始化
rospy.init_node('person_publisher', anonymous=True)
# 创建一个Publisher,发布名为/person_info的topic,消息类型为Person... | 3.ROS_communication/learning_communication/scripts/person_publisher.py | 1,089 | !/usr/bin/env python -*- coding: utf-8 -*- 该例程将发布/person_info话题,自定义消息类型learning_communication::PersonMsg ROS节点初始化 创建一个Publisher,发布名为/person_info的topic,消息类型为PersonMsg,队列长度10设置循环的频率 初始化PersonMsg类型的消息 发布消息 按照循环频率延时 | 211 | zh | 0.508402 |
# Copyright 2018 The TensorFlow Probability 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... | tensorflow_probability/python/internal/backend/numpy/numpy_array.py | 14,452 | Converts a list to array using the first element for dtype.
This method is used to match the behavior of `tf.concat`.
Args:
args_list: A list or tuple of arguments.
dtype_hint: An optional hint used when converting the args to tensors.
Returns:
A list of tensors.
gather.
gather_nd.
Match TF behavior with np.lin... | 2,714 | en | 0.586171 |
import netrc, os, unittest, sys, textwrap
from test import test_support
temp_filename = test_support.TESTFN
class NetrcTestCase(unittest.TestCase):
def make_nrc(self, test_data):
test_data = textwrap.dedent(test_data)
mode = 'w'
if sys.platform != 'cygwin':
mode += ... | Python27/Lib/test/test_netrc.py | 4,766 | This test is incomplete since we are normally not run as root and therefore can't test the file ownership being wrong. | 118 | en | 0.993747 |
"""pycodestyle support."""
from pycodestyle import BaseReport, StyleGuide, get_parser, _parse_multi_options
from pylama.lint import Linter as Abstract
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Linter(Abstract):
"""pycodestyle runner."""
@staticmethod
... | vimfiles/bundle/vim-python/submodules/pylama/pylama/lint/pylama_pycodestyle.py | 2,038 | pycodestyle runner.
Save errors.
Get errors.
:return list: List of errors.
Prepare storage for errors.
Check code with pycodestyle.
:return list: List of errors.
pycodestyle support. | 184 | en | 0.658837 |
# Microsoft Azure Linux Agent
#
# Copyright 2014 Microsoft Corporation
#
# 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 b... | azurelinuxagent/common/conf.py | 6,474 | Parse amd store key:values in /etc/waagent.conf.
Load conf file from: conf_file_path
Module conf loads and parses configuration file
Microsoft Azure Linux Agent Copyright 2014 Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the ... | 759 | en | 0.799127 |
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
import plotly.graph_objs as go
import networkx as nx
import pickle
import boto3
import io
import numpy
import pandas
############################
# Load data
BUCKET_NAME = 'blog-seq-da... | src/dash_app/my_app_v8.py | 2,926 | -*- coding: utf-8 -*- Load data replace with your bucket name list of topics replace with your object key article info replace with your object key topic sequence replace with your object key Layout section Callbacks | 218 | en | 0.70021 |
# -*- coding: utf-8 -*-
# @Time : 2020/7/7 9:11
# @Author : lightsmile
# @Software: PyCharm
from lightutils import get_file_name
if __name__ == '__main__':
print(get_file_name("hello_world.py"))
| examples/get_file_name_demo.py | 205 | -*- coding: utf-8 -*- @Time : 2020/7/7 9:11 @Author : lightsmile @Software: PyCharm | 87 | en | 0.39872 |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bethel Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BethelTestFramework
from test_framework.staticr_util import *
import... | qa/rpc-tests/staticr-tx-send.py | 1,352 | Tests the tx sending after softfork activation.
!/usr/bin/env python3 Copyright (c) 2018 The Bethel Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.check that a transaction can be sent after the reward changes to static... | 385 | en | 0.721695 |
import time
import base64
from datetime import datetime
import sys
import json
from redis_support_py3.graph_query_support_py3 import Query_Support
from redis_support_py3.construct_data_handlers_py3 import Generate_Handlers
from modbus_redis_server_py3.modbus_serial_ctrl_py3 import ModbusSerialCtrl... | code/modbus_server_py3.py | 5,155 | from redis_support_py3.redis_rpc_server_py3 import Redis_Rpc_Server fill in proceedures find data structures finding IO_LINKSprint(msg_mgr.ping_devices([100])) | 163 | en | 0.30908 |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import ... | Plugins/UnrealEnginePython/Binaries/Win64/Lib/site-packages/tensorflow/contrib/rnn/ops/gen_lstm_ops.py | 35,128 | Computes the LSTM cell forward propagation for all the time steps.
This is equivalent to applying LSTMBlockCell in a loop, like so:
```python
for x1 in unpack(x):
i1, cs1, f1, o1, ci1, co1, h1 = LSTMBlock(
x1, cs_prev, h_prev, w, wci, wcf, wco, b)
cs_prev = cs1
h_prev = h1
i.append(i1)
cs.append(cs1)
... | 15,770 | en | 0.693264 |
import numpy as np
from torch import nn
import torch.optim as optim
import torch
import matplotlib.pyplot as plt
import pandas as pd
import data_loader as dl
import time
import copy
import utility
import yaml
import trainer
from PIL import Image
from os import path
Image.MAX_IMAGE_PIXELS = None
from scipy.io import sav... | main.py | 5,443 | train on resnext train for 4 resolutions Load the meta data file Generate the ZCA matrix if enabled train for every res Define normalization Define specific transforms Create a train and valid dataset Get a train and valid data loader train for every net If old model exists, take state from it Gather the parameters to ... | 413 | en | 0.66418 |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
from django.core.urlresolvers import reverse
from django.http import QueryDict
from .crypto import generate_randomness
from .models import SQRLNut
from .utils import get_user_ip
class SQRLInitialization(object):
"""
SQ... | sqrl/sqrl.py | 4,674 | SQRL class for initializing SQRL transaction.
This class is mainly responsible for initially creating and storing
:obj:`.models.SQRLNut`. Also this class has helper properties
for getting SQRL urls.
Parameters
----------
request : HttpRequest
Django standard request object
nut : SQRLNut, optional
SQRLNut for ... | 2,136 | en | 0.77249 |
from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2
from .nn import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_modu... | diff_dalle/unet.py | 36,610 | An attention block that allows spatial positions to attend to each other.
Originally ported from here, but adapted to the N-d case.
https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/m... | 5,724 | en | 0.772223 |
'''
This file is automatically generated; Do not edit it. :)
'''
VERSION_INFO = {
'final': True,
'version': '1.19.0',
'branch_nick': 'feature-0-Rucio_1_19_0_release_preparation',
'revision_id': 'dd9f8f94d94996ab5b3aa45b4c23ccc77cff604a',
'revno': 7719
}
| lib/rucio/vcsversion.py | 275 | This file is automatically generated; Do not edit it. :) | 56 | en | 0.861448 |
#! /usr/bin/env python
""" cryptopy.cipher.aes_sbox_analysis
AES Sbox Analysis - a simple analysis of the AES Sbox that determines
the number and size of the permutation subgroups in the transformation.
Could be extended to examine any Sbox ...
Copyright (c) 2002 by Paul A. Lambert
Read LI... | lib/cryptopy/cipher/aes_sbox_analysis.py | 3,466 | ! /usr/bin/env python The AES Sbox a dictionary of the cycles indexed by the first cycle element Make this test module runnable from the command prompt | 151 | en | 0.648152 |
import csv # csv reader functions
from collections.abc import Counter # count uniques in a file quickly, O(nlogn)
from decimal import Decimal # just to show decimals with lower precision
# Global Variables #
from cfltools.settings import APPFOLDER
class IpAddress:
def __init__(self, ip, numOccurances):
... | cfltools/depreciated/getuniqueip.py | 11,585 | Dynamically determine which column of a log file contains dates.
Parameters:
row: A row of a logfile
Returns:
iterator: An integer defining the row that contains a valid date
string.
Naive method to determine the time range during which an IP
address appears in a logfile.
This is sort of hacky. I'm us... | 1,896 | en | 0.898437 |
# -*- coding: utf-8 -*-
"""Top-level package for {{ cookiecutter.project_name }}."""
__project__ = "{{ cookiecutter.project_name }}"
__author__ = "{{ cookiecutter.full_name }}"
__email__ = "{{ cookiecutter.email }}"
__version__ = "{{ cookiecutter.version }}"
| {{cookiecutter.project_name}}/{{cookiecutter.project_slug}}/__init__.py | 261 | Top-level package for {{ cookiecutter.project_name }}.
-*- coding: utf-8 -*- | 78 | en | 0.759411 |
# custom PosLemmaTagger based on Chatterbot tagger
import string
from chatterbot import languages
import spacy
from chatterbot import tagging
class CustomPosLemmaTagger(tagging.PosLemmaTagger):
def __init__(self, language=None):
super(CustomPosLemmaTagger, self).__init__(language=None)
def get_big... | tagging.py | 1,508 | Return a string of text containing part-of-speech, lemma pairs.
custom PosLemmaTagger based on Chatterbot tagger | 114 | en | 0.547869 |
"""Download handlers for different schemes"""
import logging
from twisted.internet import defer
from scrapy import signals
from scrapy.exceptions import NotConfigured, NotSupported
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import create_instance, load_object
from scrapy.utils.python imp... | scrapy/core/downloader/handlers/__init__.py | 3,766 | Lazy-load the downloadhandler for a scheme
only on the first request for that scheme.
仅在对该协议的第一个请求时才延迟加载该协议的下载处理程序。
Download handlers for different schemes
stores acceptable schemes on instancing | 存储实例化可接受的协议 stores instanced handlers for schemes | 存储实例化可接受的处理函数 remembers failed handlers | 存储失败的处理程序 返回不为None的处理函数路径 ... | 513 | zh | 0.854167 |
#!/usr/bin/env python
# -*- coding:utf-8 _*-
# @author : Lin Luo / Bruce Liu
# @time : 2020/1/3 21:35
# @contact : 15869300264@163.com / bruce.w.y.liu@gmail.com
import argparse
parser = argparse.ArgumentParser()
parser.add_argument_group()
parser.add_argument('-c', '--config', help='config file for run and operati... | utils/args.py | 1,012 | !/usr/bin/env python -*- coding:utf-8 _*- @author : Lin Luo / Bruce Liu @time : 2020/1/3 21:35 @contact : 15869300264@163.com / bruce.w.y.liu@gmail.com group.add_argument('-e', '-examine', help='examine the status of ip', required=False) | 241 | en | 0.152406 |
import numpy as np
from yt.data_objects.selection_objects.data_selection_objects import (
YTSelectionContainer,
YTSelectionContainer3D,
)
from yt.data_objects.static_output import Dataset
from yt.funcs import ensure_list, validate_iterable, validate_object
from yt.geometry.selection_routines import points_in_c... | yt/data_objects/selection_objects/cut_region.py | 8,890 | This is a data object designed to allow individuals to apply logical
operations to fields and filter as a result of those cuts.
Parameters
----------
data_source : YTSelectionContainer3D
The object to which cuts will be applied.
conditionals : list of strings
A list of conditionals that will be evaluated. In ... | 1,724 | en | 0.864134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.