id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4970942 | # Generated by Django 2.2.2 on 2019-06-25 08:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projectoffice', '0003_auto_20190613_1007'),
]
operations = [
migrations.RemoveField(
model_name='customercommchannel',
... | StarcoderdataPython |
1655212 | <gh_stars>1-10
from pathlib import Path
from typing import List
from git import Commit, InvalidGitRepositoryError, Repo # type: ignore[attr-defined]
from gitdb.exc import BadName
from loguru import logger
from pyadr.git.exceptions import (
PyadrGitBranchAlreadyExistsError,
PyadrGitIndexNotEmptyError,
Pya... | StarcoderdataPython |
11356208 | # -*- coding: utf-8 -*-
#
# Hooks module for py2exe.
# Inspired by cx_freeze's hooks.py, which is:
#
# Copyright © 2007-2013, <NAME>.
# Copyright © 2001-2006, Computronix (Canada) Ltd., Edmonton, Alberta, Canada.
# All rights reserved.
#
import os, sys
# Exclude modules that the standard library imports (cond... | StarcoderdataPython |
1775131 | <filename>module/tests/models/test_user_model.py
"""Test the User model"""
from module.tests import setup_database, dataset
from module.server.models.user import User, State, load_user
def test_create_and_add_user(dataset):
"""Creating an user object with parameters"""
db = dataset
# User object
usr... | StarcoderdataPython |
4888742 | import numpy as np
import sys
from collections import deque
from keras import initializers
from keras.models import Sequential, load_model
from keras.layers import Dense, Activation, Input
from keras.optimizers import Adam
from keras.callbacks import TensorBoard
import tensorflow as tf
import time
import random
from ... | StarcoderdataPython |
1765550 | <filename>10_het/9_konverzios-fuggvenyek.py<gh_stars>0
#!/usr/bin/env python3
import math
def szamrendszerbol(szamstr, rendszer):
res = 0
for b in range(len(szamstr)):
if szamstr[b].isdecimal():
res += int(szamstr[b]) * rendszer ** (len(szamstr) - 1 - b)
else:
if ord(szamstr[b].upper()) - 65 <... | StarcoderdataPython |
11244351 | import sqlalchemy as sa
from sqlalchemy import orm
from .base import Base
__all__ = ['Book']
class Book(Base):
__tablename__ = 'book'
id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
name = sa.Column(sa.String(256), nullable=False)
shelf_id = sa.Column(sa.Integer(), sa.ForeignKey(... | StarcoderdataPython |
1970002 | <filename>twoline_logwatch/watcher.py
import copy
import json
import logging
from multiprocessing import Process, Queue
import re
import select
import subprocess
import time
import requests
logger = logging.getLogger(__name__)
def get_processed_patterns(patterns):
processed = {}
for pattern_regex, message... | StarcoderdataPython |
3427769 | from .base import * # noqa
from .base import env
SECRET_KEY = env("SECRET_KEY")
ALLOWED_HOSTS = ["*"]
# REST FRAMEWORK
# ----------------------------------------------------------------------------------------------------------------------
# http://www.django-rest-framework.org/api-guide/settings/
REST_FRAMEWORK = ... | StarcoderdataPython |
3237060 | <reponame>TheoChevalier/gaia
# 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/.
from argparse import ArgumentParser
import threading
import sys
import socket
import os
imp... | StarcoderdataPython |
6524254 | <filename>model/src/detect_flood.py<gh_stars>0
# ## A Transfer Learning Supervised Machine Learning Model for Flooded Road Recognition
# ### <NAME>, Marda Science / USGS
# #### May, 2021; contribution to the COMET "Sunny Day Flooding" project
# adapted from <NAME>'s codes at https://github.com/ebgoldstein/NCTrafficCame... | StarcoderdataPython |
3434923 | <reponame>IsaacChanghau/AmusingPythonCodes
import tensorflow as tf
from ...utils.nn import weight, bias
from ...utils.attn_gru import AttnGRU
class EpisodeModule:
""" Inner GRU module in episodic memory that creates episode vector. """
def __init__(self, num_hidden, question, facts, is_training, bn):
... | StarcoderdataPython |
8109104 | from cwlab.database.connector import db
from cwlab.database.sqlalchemy.models import User, Exec, Job, Run
import sqlalchemy
from datetime import datetime
class JobManager():
def create_job(
self,
job_name,
username,
wf_target
):
job = Job(
job_name=job_na... | StarcoderdataPython |
12866512 | #!/usr/bin/python3
"""transliteration of <NAME>'s pixel sorting script"""
from copy import copy
from random import random, gauss
from PIL import Image
from numpy import int32
from argparse import ArgumentParser
# PROGRAM CONSTANTS
# rgb(103, 105, 128)
BLACK_VALUE = int32(-10000000)
# rgb(164, 114, 128)
WHITE_VALUE =... | StarcoderdataPython |
8091142 | <filename>tests/integration/conftest.py
from unittest import mock
import arq
import httpx
import psycopg2
import pytest
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from service import config
from service.jobs import redis_pool_factory
from service.kafka import kafka_producer_factory, kafka_consumer_fac... | StarcoderdataPython |
3564324 | import typing
import socket
import threading
import time
import webbrowser
def _check_usage(host: str, port: int) -> bool:
"""
Checks to see whether or not the specified port is utilized
and returns a boolean indicating whether it is or not.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_ST... | StarcoderdataPython |
11233317 | #!/usr/bin/python
# (c) 2012, <NAME> <jpmens () gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) a... | StarcoderdataPython |
8199450 | from .antiphoneclapper import AntiPhoneClapper
async def setup(bot):
bot.add_cog(AntiPhoneClapper(bot))
| StarcoderdataPython |
9662810 | # -*- coding: utf-8 -*-
"""
Korean -- A library for Korean morphology
=========================================
Sometimes you should localize your project to Korean. But common i18n solutions
such as gettext are not working with non Indo-European language well. Korean
also has many morphological difference. "korean" a... | StarcoderdataPython |
11375055 | <gh_stars>1-10
metadata_template = {
"name": "",
"description": "",
"image": "",
"attributes": [
{"trait_type": "nickname", "value": ""},
{"trait_type": "Level", "value": 1},
{"trait_type": "HP", "value": 1},
{"trait_type": "Atk", "value": 1},
{"trait_type": "Def"... | StarcoderdataPython |
4969803 | <gh_stars>0
from django.apps import AppConfig
class MailclientConfig(AppConfig):
name = 'mailclient'
| StarcoderdataPython |
228607 | <reponame>carr-elagheb/moler
# -*- coding: utf-8 -*-
"""
threaded.network_down_detector.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A fully-functional connection-observer using socket & threading.
Works on Python 2.7 as well as on 3.6
This example demonstrates basic concept of connection observer - entity
that is fully respo... | StarcoderdataPython |
11273689 | #!/usr/bin/env python
NAME = 'TransIP Web Firewall (TransIP)'
def is_waf(self):
# TransIP WAF has these two firewall fingerprints.
# The blockpage is the regular 403 page, no fingerprints
# on blockpage.
if self.matchheader(('X-TransIP-Backend', '.+')):
return True
if self.matchheader(('... | StarcoderdataPython |
8101239 | import numpy as np
import cv2
def display_lines(image, lines):
try:
line_image=np.zeros_like(image)
if lines is not None:
for line in lines:
x1, y1, x2, y2=line.reshape(4)
cv2.line(line_image, (x1,y1), (x2,y2), (255,0,0), 3)
return line_image
... | StarcoderdataPython |
6550577 | <filename>Easy/ArrayPartition.py
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 27 22:38:34 2021
@author: Srijhak
"""
def arrayPairSum(nums):
nums.sort()
i=0
sum=0
while i < len(nums):
sum+=i
i+=2
return sum
nums = [1,6,7,8,4,2,9]
print(arrayPairSum(nums)) | StarcoderdataPython |
1975978 | import logging
import os
import sys
from pydocstyle import log
from pydocstyle import run_pydocstyle
# override default logging level which seems to be DEBUG
log.setLevel(logging.WARNING)
def empty(*args, **kwargs):
pass
log.setLevel = empty
def test_pydocstyle():
base_path = os.path.dirname(os.path.dir... | StarcoderdataPython |
3219665 | import numba as nb
import numpy as np
from dsa.topology.graph.jit.csgraph_to_directed import csgraph_to_directed
from dsa.topology.graph.jit.sort_csgraph import sort_csgraph
# TODO cut below
# DFS
@nb.njit
def connected_components_dfs(n: int, g: np.ndarray):
g = csgraph_to_directed(g)
g, edge_idx, _ = sort_c... | StarcoderdataPython |
5152440 | import random
from utils import SvmAccuracy
# class Particle for PSO part
class Particle:
# each particle has a featureset, personal best, current cost, personal best cost, velocity
def __init__(self, feature, dataset):
self.feature = feature
self.pbest = feature
self.current_cost = self... | StarcoderdataPython |
9708229 | from .base import TestCase
class TestRequestIdMiddleware(TestCase):
def test_issue_request_id(self):
response = self.client.get(
'/api/v1/404',
)
assert response.status_code == 404
assert response.headers['X-Request-Id'] == 'a823a206-95a0-4666-b464-93b9f0606d7b'
... | StarcoderdataPython |
201052 | #!/bin/zsh
import random
print(random.randrange(1, 10)) | StarcoderdataPython |
4867661 | <gh_stars>0
s = 0
c = 1
while True:
a = int (input ("Enter number: "))
s += a
if (a != 0): c *= a
if a == 0:
print ("summ: ", s)
print ("composition: ", c)
break | StarcoderdataPython |
3361395 | """
This file is build based on the code by <NAME> found in evaluate_suffix_only.py
here the beam search algorithm is implemented with a modified queueing algorithm.
Author: <NAME>
"""
from __future__ import division
import csv
import os.path
import time
from queue import PriorityQueue
from datetime import datetime,... | StarcoderdataPython |
4845103 | <reponame>isabella232/smore<filename>smore/common/torchext/dist_func/beta_dist.py
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/l... | StarcoderdataPython |
9620025 | <gh_stars>1-10
## Raw data
AUDIO_DIR = 'data/OpenBMAT/raw/audio'
ANNO_DIR = 'data/OpenBMAT/raw/annotations/tsv/RMLE_mapping/annotator_a'
MEAN_STD_PATH = 'data/OpenBMAT/mean_std'
SPLITS_CSV = 'data/OpenBMAT/raw/splits/splits.csv'
NUM_CLASSES1 = 2
NUM_CLASSES2 = 3
## Preprocessing
SAMPLING_RATE = 8000
N_MELS =... | StarcoderdataPython |
234173 | <gh_stars>0
import atexit
import glob
import logging
import os
import shutil
import subprocess
import tempfile
from contextlib import contextmanager, _GeneratorContextManager
from typing import Sequence, Union, List, IO, Any, Generator
from blocks.datafile import LocalDataFile
from blocks.filesystem.base import FileSy... | StarcoderdataPython |
307271 | <filename>dictionary_3.py
#Import library
import json
#Loading the json data as python dictionary
#Try typing "type(data)" in terminal after executing first two line of this snippet
data = json.load(open(r"C:\Users\admin\Downloads\data.json"))
#Function for retriving definition
def retrive_definition(word):
#Remov... | StarcoderdataPython |
380792 | <filename>main.py
import code
from core.Init import *
def interact(): # Calls the interactif mode
code.interact(banner=banner, local=globals()) | StarcoderdataPython |
5027758 | <filename>setup.py
import pathlib
from setuptools import setup
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name="alkh",
version="0.1.1",
description="algorithmic python debugging",
long_description=README,
long_description_content_type="text/markdown",
... | StarcoderdataPython |
3224419 | import json
import os
import argparse
import pandas as pd
from .utils.simulators.dataset_simulator import DatasetSimulator
from .utils.data.dataset2xy import dataset2Xy
from .utils.data.load import load_dataset
from .utils.runners.runners_factory import get_runner
from .consts import scan_spaces, network_conf
... | StarcoderdataPython |
3253216 | <reponame>tclax/PyBattleship<filename>Tile.py
#Represents a tile. A tile has am x,y coordinate, and a code value
class Tile:
def __init__(self, x, y, code):
self.x = x
self.y = y
self.code = code
self.hasNorthTile = False
self.hasSouthTile = False
self.hasWestTile = ... | StarcoderdataPython |
4977519 | <gh_stars>1-10
import csv
print('')
print('====================================================================================================')
print('== 문제 14. (오늘의 마지막 문제) 이름과 월급 + 커미션을 출력하시오!')
print('====================================================================================================')
file = ope... | StarcoderdataPython |
6511792 | """This file defines the configuration variables."""
# Logging
LOGLEVEL = 20 # logging.INFO
LOG_FORMAT = "%(name)-20s %(levelname)-8s %(message)s"
FILE_LOGLEVEL = 10 # logging.DEBUG
FILE_LOG_FORMAT = "%(asctime)s %(name)-20s %(levelname)-8s %(message)s"
# Tensorflow dataset
SHUFFLE_BUFFER_SIZE = 5000
PREFETCH_SIZE = 1... | StarcoderdataPython |
1987770 | <filename>tests/test_example/test_todo.py
import pytest
def test_todo():
"""Example test with parametrization."""
assert True
| StarcoderdataPython |
9773546 | <reponame>hawkrives/AAO-React-Native
#!/usr/bin/env python2
"""Usage: analyze-gym.py < travis-ios-log.log
You can download log files with the `travis` gem:
$ travis logs 3498.3 > 3498.3.log
Then just pass that logfile to this script's stdin.
$ python3 analyze-gym.py < 3498.3.log
Options:
-h, --help Print... | StarcoderdataPython |
8110778 | """
Integration with CMake.
"""
from typing import Optional
import subprocess
import sys
def generator_settings_for_compiler(cmake_path: str, compiler_path: Optional[str]):
"""Makes settings to give the generator for a specific compiler."""
settings = []
if compiler_path is not None:
settings = [f... | StarcoderdataPython |
3535827 | <filename>src/report/pt_store.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import web
from config import setting
import helper
db = setting.db_web
url = ('/report/pt_store')
# SKU -------------------
class handler: # PlatSkuStore
def GET(self):
if helper.logged(helper.PRIV_USER,'REPORT_REPORT2'... | StarcoderdataPython |
1707305 | # coding: utf8
import numpy as np
from numpy import random
import matplotlib.pyplot as plt
from keras.layers import Input, Dense
from keras.optimizers import SGD
from keras.models import Model
X = random.uniform(0, 30, 100) # 随机生成在[0,30]区间内服从均匀分布的100个数
y = 1.85 * X + random.normal(0, 2, 100) # 对X乘以固定系数后加上随机扰动
plt... | StarcoderdataPython |
8116025 | <filename>src/pyquickhelper/sphinxext/sphinx_githublink_extension.py
# -*- coding: utf-8 -*-
"""
@file
@brief Defines a :epkg:`sphinx` extension to display a link on github.
"""
import os
import sphinx
from docutils import nodes
from docutils.parsers.rst.roles import set_classes
class githublink_node(nodes.Element):
... | StarcoderdataPython |
213703 | # This Python file uses the following encoding: utf-8
# beautifulsoup4
# 独学プログラマーのスクレイピング
import requests
from bs4 import BeautifulSoup
site = requests.get("https://www.google.com")
print(site)
data = BeautifulSoup(site.text, "html.parser")
print(data.title) #タイトルを出力する
print(data.title.text) #タイトルタグの中身のみを出力する
print(d... | StarcoderdataPython |
8054667 | <reponame>DEvHiII/aoc-2018
#!/usr/bin/env python3
import sys
# tag::countLetters[]
def countLetters(id):
if (type(id) is str):
result = {2: [], 3: []}
chars = "abcdefghijklmnopqrstuvwxyz"
for char in chars:
count = id.count(char)
if count == 2 or count == 3:
... | StarcoderdataPython |
6664020 | # Generated by Django 2.2.2 on 2019-06-05 05:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20190602_1130'),
]
operations = [
migrations.RemoveField(
model_name='dashboardportlet',
name='dashboard',... | StarcoderdataPython |
1696132 | <filename>lab/layers/plot.py
from collections import OrderedDict
from math import trunc
import math
import statistics
import joypy
import matplotlib
import numpy as np
from numpy.core.fromnumeric import shape
import pandas as pd
from pandas.core import groupby
import torch
import torch.nn as nn
from datasets import (Ch... | StarcoderdataPython |
5182228 | <reponame>acdh-oeaw/apis-core
from django.test import TestCase
from django.contrib.auth.models import User, Group
from django.urls import reverse
from .models import Person, Event
from apis_core.apis_metainfo.models import Text, Collection
from apis_core.apis_vocabularies.models import ProfessionType
from reversion im... | StarcoderdataPython |
5131015 | <reponame>mwmajew/Tonic<gh_stars>10-100
1#!/usr/bin/env python
''' Async TCP server to make first tests of newly received GPS trackers '''
import asyncore
import socket
import logging
import json
from server_management import BaseServer, BaseClientHandler
from imu_interceptor import ImuEuler
class ImuClie... | StarcoderdataPython |
8074143 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import MySQLdb
import os #para reinico router
import telebot # Librería de la API del bot.
from telebot import types # Tipos para la API del bot.
import token
###### FV_Diario es un grupo que he creado en Telegram para envio cada hora
###### de un mensaje con l... | StarcoderdataPython |
1972913 | """
Implementation of the method proposed in the paper:
'Adversarial Attacks on Node Embeddings via Graph Poisoning'
<NAME> and <NAME>, ICML 2019
http://proceedings.mlr.press/v97/bojchevski19a.html
Copyright (C) owned by the authors, 2019
"""
import numba
import numpy as np
import scipy.sparse as sp
import scipy.lin... | StarcoderdataPython |
8146222 | from django.contrib import admin
from profiles_api.models import UserProfile, Feed
class FeedAdmin(admin.ModelAdmin):
readonly_fields = ["created_on"]
admin.site.register(UserProfile)
admin.site.register(Feed, FeedAdmin)
| StarcoderdataPython |
11335811 | n = int(input())
is_found = False
count = 0
for i in range(1, n):
if n % i == 0:
count += 1
if count > 2:
print("False")
else:
print("True")
| StarcoderdataPython |
12819231 | <gh_stars>10-100
import re
class Handshake:
EVENTS = ['wink', 'double blink', 'close your eyes', 'jump']
def commands(self, inp):
if not self.valid_inp(inp):
return []
return self.commands_for_num(self.to_num(inp))
def commands_for_num(self, num):
if self.testBit(num... | StarcoderdataPython |
4971068 | print('='*8,'Função de Contador','='*8)
def contador(i, f, p):
from time import sleep
if p < 0:
p = -p
elif p == 0:
p = 1
print(f'Contagem de {i} até {f} pulando de {p} em {p}:')
if i > f:
p = -p
for c in range(i, f - 1, p):
print(f'\033[32m{c}\033[m', end... | StarcoderdataPython |
12838239 | <reponame>jerry-le/computer-vision
import cv2
import numpy as np
from __utils__.general import show_image
img = cv2.imread('../../asserts/images/zigzac.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray, None)
cv2.drawKeypoints(gray, kp, img)
show_image(img)... | StarcoderdataPython |
9669873 | from rest_framework import serializers
from .models import IncomeExpense
class IncomeExpenseSerializer(serializers.ModelSerializer):
class Meta:
model = IncomeExpense
fields = ('id','description' ,'date', 'income', 'expense','category','status') | StarcoderdataPython |
387754 | # Copyright 2014 IBM Corp.
#
# 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 ... | StarcoderdataPython |
5100008 | import sqlite3
import pymssql
import sys
#Creamos una base de datos de SQLite llamada Nortwind.db
conn = sqlite3.connect('.\\Ficheros\\Northwind.db')
cursor = conn.cursor()
#Creamos una tabla llamada Customers
command = "SELECT count() FROM sqlite_master WHERE type = 'table' AND name = 'Customers'"
cursor.execute(comm... | StarcoderdataPython |
210583 | <reponame>Jumpscale/lib9<gh_stars>1-10
from .utils import _find_second, _check_broken_links
from js9 import j
class Task():
"""Represents a task
"""
LIST_TITLE = "Tasks"
def __init__(self, url="", description="", state="open", body="", update_func=None):
"""Task constructor
... | StarcoderdataPython |
131240 | """Config flow for AirNow integration."""
import logging
from pyairnow import WebServiceAPI
from pyairnow.errors import AirNowError, InvalidKeyError
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_RAD... | StarcoderdataPython |
1844289 | #!/usr/bin/env python3
import itertools
def swap_position(word, x, y):
word[x], word[y] = word[y], word[x]
return word
def swap_letter(word, x, y):
return swap_position(word, word.index(x), word.index(y))
def rotate_steps(word, direction, x):
if direction == 'right':
return word[-x:] + word[... | StarcoderdataPython |
257211 | import os
import sys
import errno
sys.path.append('../../common')
from env_indigo import *
from rendering import *
if not os.path.exists(joinPathPy("out", __file__)):
try:
os.makedirs(joinPathPy("out", __file__))
except OSError as e:
if e.errno != errno.EEXIST:
raise
... | StarcoderdataPython |
1996845 | <reponame>jchomarat/azure-monitor-opencensus-python
"""Test src/app_logger.py."""
import logging
import uuid
import unittest
from monitoring.src.logger import AppLogger, get_disabled_logger
test_instrumentation_key = str(uuid.uuid1())
test_invalid_instrumentation_key = "invalid_instrumentation_key"
class TestAppLo... | StarcoderdataPython |
5067869 | '''
Database interaction.
Copyright 2020 Voxel51, Inc.
voxel51.com
'''
from collections import defaultdict
import os
import pymysql
import pandemic51.config as panc
import pandemic51.core.pdi as panp
def connect_database():
'''Creates a database connection.
Returns:
a db connection
'''
ret... | StarcoderdataPython |
6423261 | class ToyotaOpening:
_closed: bool
def __init__(self, closed=False):
self._closed = closed
@property
def closed(self):
return self._closed
@closed.setter
def closed(self, value):
self._closed = value
def __repr__(self) -> str:
return f"{self.__class__.__na... | StarcoderdataPython |
1993092 | # Generated by Django 2.1.7 on 2019-08-12 14:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('curate', '0043_add_default_for_article_type'),
]
operations = [
migrations.CreateModel(
name='T... | StarcoderdataPython |
3363486 |
# coding: utf-8
# In[1]:
import os
import synonyms
import json
#from multiprocessing import Pool
import time
def remove_ambiguity(context, possible_entities, kb):
if len(possible_entities) == 1:
return possible_entities[0]
score = []
# print(possible_entities)
for e in possible_entities:
... | StarcoderdataPython |
8109961 | from redfish import connection
host = '127.0.0.1'
user_name = 'Admin'
password = 'password'
server = connection.RedfishConnection(host, user_name, password) | StarcoderdataPython |
375144 | import numpy as np
from ratpacdbplot.ratdbio import getratdbpoints
def test_getpoints_with_callable():
X, Y = getratdbpoints(
[
lambda it: it["RSLENGTH_value1"]
if it["name"] == "OPTICS" and it["index"] == "wbls_ly500_WM_0121"
else None,
lambda it: it["RSLEN... | StarcoderdataPython |
1639424 | from django.contrib.auth.forms import AuthenticationForm
from django import forms
from .models import ConsultantSurvey, Member, FellowSurvey
class LoginForm(AuthenticationForm):
""" Main Login Form """
username = forms.CharField(label="Username", max_length=30,
widget=forms.Text... | StarcoderdataPython |
1605271 | def f(a):
a.while<caret> | StarcoderdataPython |
11350316 | # -*- coding: utf-8 -*-
from __future__ import division
# Copyright (C) 2012 <NAME>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opti... | StarcoderdataPython |
5040479 | <filename>Sailor.py
from Sensors import Sensors
from ServoControl import ServoControl
from Bearing import Bearing
import math
class Sailor:
def __init__(self,sensorService):
self.lastRudderAdjustment = None
self.sensorService = sensorService
self.servoControl = ServoControl(6,6)
sel... | StarcoderdataPython |
8185622 | <gh_stars>0
import FWCore.ParameterSet.Config as cms
import HeavyIonsAnalysis.VertexAnalysis.PAPileUpVertexFilter_cfi
pileupVertexFilterCutG = HeavyIonsAnalysis.VertexAnalysis.PAPileUpVertexFilter_cfi.pileupVertexFilter.clone()
pileupVertexFilterCutGloose = pileupVertexFilterCutG.clone(
dzCutByNtrk = cms.vdouble... | StarcoderdataPython |
9660422 | <filename>braintree/exceptions/gateway_timeout_error.py
from braintree.exceptions.braintree_error import BraintreeError
class GatewayTimeoutError(BraintreeError):
"""
Raised when a gateway response timeout occurs.
"""
pass
| StarcoderdataPython |
6497905 | <reponame>mail2nsrajesh/python-ceilometerclient
# Copyright 2012 OpenStack Foundation
# 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.ap... | StarcoderdataPython |
1922556 | <filename>Python Simulator/examples/my_network_out.py
inet['network'] = Network()
inet['simulator'] = Simulator(network)
network = inet['network']
simulator = inet['simulator']
RandomSpiker_1 = network.createRandomSpiker(5.0, 5.0)
LIF_1 = network.createLIF(0.9, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0)
LIF_2 = network.create... | StarcoderdataPython |
6482470 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 13:04:07 2019
@author: <NAME>
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
###############################################################################
# This preprocessing m... | StarcoderdataPython |
6458350 | <reponame>nevmenandr/thai-language<filename>limit_corpus/limit.py
# -*- coding: utf-8 -*-
import os
import time
import shutil
# import random
__author__ = 'gree-gorey'
def copy(path, path_to_write, folder_limit, limit):
i = 0
# собираем все папки разных ресурсов
sources = []
for root, dirs, files in... | StarcoderdataPython |
70740 | <reponame>kdougla01/SENDReg
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField, validators
class LoginForm(FlaskForm):
"""Login form to access writing and settings pages"""
username = StringField('Username', [validators.DataRequired()])
password = P... | StarcoderdataPython |
9680261 | <reponame>Oskari-Tuormaa/cpymad<gh_stars>10-100
"""
Simple RPC module for libmadx.
This module is used to execute several instances of the `libmadx` module
in remote processes and communicate with them via remote procedure calls
(RPC). Use the :meth:`LibMadxClient.spawn` to create a new instance.
The remote backend i... | StarcoderdataPython |
394513 | <filename>intro-python/part1/hands_on_exercise.py
"""Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print("{_type} {_value}".format(_type=type(pi), _value=pi))
# TODO: Write a conditional to print... | StarcoderdataPython |
3292009 | import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.append('\n')
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
versi... | StarcoderdataPython |
1886038 | <reponame>lanesmith/PostREISE
from bokeh.io import show
from powersimdata import Scenario
from postreise.plot.plot_utilization_map import map_utilization
scenario = Scenario("3287")
util_map = map_utilization(scenario, state_borders_kwargs={"background_map": False})
show(util_map)
| StarcoderdataPython |
8033055 | <reponame>renaisaalves/Python-CursoemVideo
#AULA17: LISTAS
num = [2, 5, 9, 3]
num[2] = 3 #A posição 2 vai deixar de ser um [9] e vai passar a valer [3]
num.append(7) #Vai adicionar o valor [7] na última posição da lista
num.sort() #Coloca os valores em ordem
num.sort(reverse=True) #Coloca os valores em ordem inversa
n... | StarcoderdataPython |
3473690 | # coding: utf-8
# Author: 阿财(<EMAIL>)(<EMAIL>)
# Created date: 2020-02-27
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 So... | StarcoderdataPython |
5009450 | from django.contrib import admin
# Register your models here.
from .models import Fratio
admin.site.register(Fratio)
| StarcoderdataPython |
8182772 | import torch
import numpy as np
class EarlyStopping:
def __init__(self, patience=5, verbose=False, path='checkpoint_model.pth'):
self.patience = patience # stop cpunter
self.verbose = verbose
self.counter = 0 # current counter
self.best_score = None # best sco... | StarcoderdataPython |
31178 | # alevel.py Test/demo program for Adafruit ssd1351-based OLED displays
# Adafruit 1.5" 128*128 OLED display: https://www.adafruit.com/product/1431
# Adafruit 1.27" 128*96 display https://www.adafruit.com/product/1673
# The MIT License (MIT)
# Copyright (c) 2018 <NAME>
# Permission is hereby granted, free of charge, ... | StarcoderdataPython |
4958791 | <filename>news/views.py
from django.shortcuts import render
from django.http import HttpResponse
from news.models import *
# Create your views here.
def index(request):
context = {}
context["header_list"] = HeaderModel.objects.all()
context["news_list"] = News.objects.all()
return render(request, "in... | StarcoderdataPython |
3297085 | """
Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
subdir1
subdir2
file.ext
The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
The string "dir\... | StarcoderdataPython |
3479074 | <filename>twnews/__init__.py
"""
twnews 套件載入前作業,用來解決 Windows 環境會發生的編碼問題
"""
import sys
import locale
import _locale
# 以下是魔法不要亂改
if locale.getpreferredencoding() == 'cp950':
# pylint: disable=protected-access, global-statement
# 編碼是 CP950 就強制轉 UTF-8
_locale._getdefaultlocale = (lambda *args: ['zh_TW', 'ut... | StarcoderdataPython |
12817843 | <gh_stars>0
"""Display the contents of the file being edited with small font on the side."""
from __future__ import annotations
import sys
import tkinter
from porcupine import get_tab_manager, settings, tabs, textwidget, utils
LINE_THICKNESS = 1
# We want self to have the same text content and colors as the main
#... | StarcoderdataPython |
3581686 | import couchdb
import os,json
couchdb_address = 'http://openwhisk:openwhisk@10.2.64.8:5984/'
db = couchdb.Server(couchdb_address)
def active_storage(avtive_type, user_object,document_id,filename,file_path=None,content_type=None, save_path=None):
if avtive_type == 'PUT':
content = open(file_path, 'rb')
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.