id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4970496 | <reponame>theSage21/gmailcopy
import sqlite3
import arrow
def convert_arrowdatetime(s):
return arrow.get(s)
def adapt_arrowdatetime(adt):
return adt.isoformat()
sqlite3.register_adapter(arrow.arrow.Arrow, adapt_arrowdatetime)
sqlite3.register_converter("timestamp", convert_arrowdatetime)
| StarcoderdataPython |
12800360 | #!/usr/bin/env python
# coding: utf-8
import os
import struct
import sys
import socket
current_path = os.path.dirname(os.path.abspath(__file__))
launcher_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, "launcher"))
root_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir)... | StarcoderdataPython |
5117496 | """
Django settings for ebdjango project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
... | StarcoderdataPython |
9744220 | import pygame.cdrom as face
def main():
face.init()
count = face.get_count()
if count == 0:
raw_input('There is no cdrom drive.')
elif count == 1:
cmd(face.CD(0))
else:
num = which_CD(count)
if num != -1:
cmd(face.CD(num))
face.quit()
def which_CD(ma... | StarcoderdataPython |
1961216 | import os;
import util;
def main():
path_meta='/disk2/res11/tubePatches';
out_commands='/disk2/res11/commands_deleteAllImages.txt';
dirs=[os.path.join(path_meta,dir_curr) for dir_curr in os.listdir(path_meta) if os.path.isdir(os.path.join(path_meta,dir_curr))];
print len(dirs);
commands=[];
for dir_curr in dirs:... | StarcoderdataPython |
157375 | default_app_config = 'business.staff_accounts.apps.UserManagementConfig'
"""
This APP is for management of users
Functions:-
Adding staff Users and giving them initial details
-Department
-Staff Type
-Departmental,General Managers have predefined roles depending on the departments they can... | StarcoderdataPython |
113423 | <reponame>Ezra/musa-guesser
# -*- encoding: utf-8 -*-
"""
Provide conversion between Musa and other scripts, initially IPA
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "<NAME>"
__version__ = "0.1.0"
__license__ = "BSD"
import codecs
import collections
import csv... | StarcoderdataPython |
8194189 | <gh_stars>10-100
# Write your code here
n,x = input().split()
n = int(n)
x = int(x)
l = list(map(int,input().split()))
count = 0
flag = 0
for i in l:
if i <= x :
count += 1
else :
flag += 1
if flag == 2:
break
print(count)
| StarcoderdataPython |
1653609 | """Setup the file structure for the software. Specifies several folders:
software_dir: path of installation
"""
import inspect
import os
import warnings
from socket import getfqdn
import pandas as pd
from immutabledict import immutabledict
import typing as ty
import dddm
import numpy as np
export, __all__ = dddm.exp... | StarcoderdataPython |
5025839 | """Start up a fake bulb to test features without a real bulb."""
import json
import socketserver
import threading
from typing import Any, Callable, Dict
def get_initial_pilot() -> Dict[str, Any]:
return {
"method": "getPilot",
"env": "pro",
"result": {
"mac": "ABCABCABCABC",
... | StarcoderdataPython |
4906969 | <gh_stars>10-100
'''
Description:
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.v... | StarcoderdataPython |
3261931 | """
PyTorch-based implementations for the CATE estimators.
"""
from .flextenet import FlexTENet
from .pseudo_outcome_nets import (
DRLearner,
PWLearner,
RALearner,
RLearner,
ULearner,
XLearner,
)
from .representation_nets import DragonNet, TARNet
from .slearner import SLearner
from .snet import ... | StarcoderdataPython |
3523733 | import abc
import logging
import os
import types
from substratools import utils
from substratools.workspace import Workspace
logger = logging.getLogger(__name__)
REQUIRED_FUNCTIONS = set([
'get_X',
'get_y',
'fake_X',
'fake_y',
'get_predictions',
'save_predictions',
])
class Opener(abc.ABC)... | StarcoderdataPython |
6651784 | """
This module defines client service methods for celery result (for client
processing)
"""
from celery.result import ResultBase, AsyncResult
from conf.appconfig import TASK_SETTINGS
from deployer import util
from deployer.tasks.exceptions import TaskExecutionException
class TaskClient:
def __init__(self, cele... | StarcoderdataPython |
1750768 | # Generated by Django 4.0 on 2022-01-25 21:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_ticketimage_external_url_alter_warehousereply_files'),
]
operations = [
migrations.RemoveField(
model_name='warehouse... | StarcoderdataPython |
6460734 | # SPDX-License-Identifier: ISC
# Copyright (c) 2013 <NAME> <<EMAIL>>
import unittest
class TestFilterRegistry(unittest.TestCase):
def test_all_filters_exist(self):
from afew import FilterRegistry
self.assertTrue(hasattr(FilterRegistry.all_filters, 'get'))
def test_entry_point_registration(s... | StarcoderdataPython |
1602337 | from __future__ import print_function
import pendulum
import requests
import furl
from .constant import BASE_API_URL
class Public:
def __init__(self, url=None):
self.url = url if url is not None else BASE_API_URL
def ping(self):
""" See https://apidocs.stex.com/#/Public/get_public_ping """
... | StarcoderdataPython |
3384325 | <reponame>cotobadesign/cotoba-agent-oss
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to u... | StarcoderdataPython |
78105 | <reponame>SidneyAn/nfv
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.event_log.objects.v1._event_log_data import EventLogData # noqa: F401
from nfv_common.event_log.objects.v1._event_log_data import EventLogStateData # noqa: F401
from nfv_common.event_l... | StarcoderdataPython |
3483737 | import re
number_of_strings = int(input())
char_ascii_num_list = list()
pattern = r"\!(?P<command>[A-Z][a-z]{2,})\!:\[(?P<text>[A-Za-z]{8,})\]"
for i in range(number_of_strings):
message = input()
matches = re.match(pattern, message)
if not matches:
print("The message is invalid")
else:
... | StarcoderdataPython |
3415328 | from typing import Union
from fspider.downloadermiddlewares import DownloaderMiddleware
from fspider.http.request import Request
from fspider.http.response import Response
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh-HK;q... | StarcoderdataPython |
1803127 | <filename>src/tenyksscripts/scripts/portlandtime.py
from datetime import datetime
from dateutil.tz import tzlocal
import pytz
import random
def run(data, settings):
if data['payload'] == 'portland time':
if random.random() > 0.3:
tz = pytz.timezone('America/Los_Angeles')
now = datet... | StarcoderdataPython |
3426412 | from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = settings.AWS_STATIC_LOCATION
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
default_acl = 'public-read'
| StarcoderdataPython |
5020084 | """
Test that an alias can reference other aliases without crashing.
"""
from __future__ import print_function
import os
import time
import re
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
class NestedAliasTestCase(TestBase):
mydir = TestBase.compute_mydir(__file... | StarcoderdataPython |
5176533 | """
"Macro-profiling" section example of invoking cProfile
Python profiles from Python script
"""
import time
import cProfile
def medium():
time.sleep(0.01)
def light():
time.sleep(0.001)
def heavy():
for i in range(100):
light()
medium()
medium()
time.sleep(2)
def main(... | StarcoderdataPython |
1629511 | import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import layers
import numpy as np
import csv
import sys
import os
# Import utility functions from 'utils.py' file
from utils import checkFolders, show_variables, add_suffix, backup_configs
# Import convolution layer definitions from 'convolution l... | StarcoderdataPython |
1706798 | <filename>tests/test_entities.py
"""Tests entities."""
import unittest
from monitor.entities import IssueMeta, IssueCommentMeta, GitHubAuthorAssociations
class TestEntities(unittest.TestCase):
"""Tests entities."""
def test_issue(self):
"""Tests meta issue class."""
issue = IssueMeta(title="... | StarcoderdataPython |
3453184 | """"
Module to inspect phone-call events in real time.
This is the command line interface for the core.fritzmonitor module
and should serve as an example how to use an instance of FritzMonitor.
To run this, the CallMonitor service of the box has to be activated.
This can be done with any registered Phone by typing th... | StarcoderdataPython |
3301954 | <filename>tools/iotjs-create-module.py
#!/usr/bin/env python
# Copyright 2018-present Samsung Electronics Co., Ltd. and other contributors
#
# 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
#
#... | StarcoderdataPython |
1847010 | from selenium import webdriver
from bs4 import BeautifulSoup
import time
import csv
import requests
START_URL = "https://exoplanets.nasa.gov/exoplanet-catalog/"
browser = webdriver.Chrome("C:/Users/letsg/OneDrive/Desktop/Scraper-master/Scraper-master/chromedriver.exe")
browser.get(START_URL)
time.sleep(10)
def scrape()... | StarcoderdataPython |
90928 |
import numpy as np
def unflatten(w, weights):
sizes = [x.size for x in weights]
split_idx = np.cumsum(sizes)
update_ravelled = np.split(w, split_idx)[:-1]
shapes = [x.shape for x in weights]
update_list = [np.reshape(u, s) for s, u in zip(shapes, update_ravelled)]
return update_list
def flatt... | StarcoderdataPython |
1837019 | <reponame>iwanimsand/pyPS4Controller<filename>pyPS4Controller/__main__.py
from pyPS4Controller.cli import Cli
def main():
Cli()
| StarcoderdataPython |
394041 | from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import get_template
from django.conf import settings
from functools import wraps
from .models import Product
def disable_fo... | StarcoderdataPython |
1947769 | <filename>litex/build/xilinx/yosys_nextpnr.py
#
# This file is part of LiteX.
#
# Copyright (c) 2020 Antmicro <www.antmicro.com>
# Copyright (c) 2020 <NAME> <<EMAIL>>
# Copyright (c) 2022 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
import os
import subprocess
import sys
import math
from typing import Name... | StarcoderdataPython |
147282 | <gh_stars>100-1000
"""
Classification of spoken digit recordings
=========================================
In this example we use the 1D scattering transform to represent spoken digits,
which we then classify using a simple classifier. This shows that 1D scattering
representations are useful for this type of problem.
... | StarcoderdataPython |
3458624 | <reponame>Gitman1989/chromium
#!/usr/bin/python
# Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# drmemory_analyze.py
''' Given a ThreadSanitizer output file, parses errors and uniques them.'''
... | StarcoderdataPython |
4834310 | <reponame>orsveri/3DSSG<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__' and __package__ is None:
from os import sys
sys.path.append('../')
import torch
import torch.optim as optim
import torch.nn.functional as F
from model_base import BaseModel
from network_PointNet import Po... | StarcoderdataPython |
6644109 | import os
from geni.aggregate import cloudlab
from geni.rspec import pg
from geni import util
def baremetal_node(name, img, hardware_type):
node = pg.RawPC(name)
node.disk_image = img
node.hardware_type = hardware_type
return node
experiment_name = 'popper-examples'
img = "urn:publicid:IDN+clemson.... | StarcoderdataPython |
5088744 | """ Simple RAW image processing module"""
import sys
import os
import scipy
from scipy import signal
import numpy as np
from numpy.lib.stride_tricks import as_strided
import rawpy
""" Process RAW file into a image file.
Example usage:
raw = read("sample.ARW")
rgb = process(raw)
write(rgb, "output.ARW")
"""
def read... | StarcoderdataPython |
9654978 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""Tests for the All-CNN-C architecture on the CIFAR-100 dataset."""
import os
import sys
import unittest
import tensorflow as tf
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from deepobs.tensorflow import... | StarcoderdataPython |
3391694 | #-*- coding: utf-8 -*-
from .lib import (
uploadhandler,
post_data,
drupal_rce,
apache_struts2,
dvr,
wp_content_inject,
)
from .utils import (
exploit_modules,
description,
show,
log,
proto,
upload_debug,
json_respon
)
import readline,requests,re
log = log(__name... | StarcoderdataPython |
316588 | class EventNotFound(Exception):
"""Handles invalid event type provided to
publishers
Attributes:
event_type --> the event that's invalid
message --> additional message to log or print
"""
def __init__(self, event_type: str, message: str ="invalid event"):
... | StarcoderdataPython |
3295723 | #-------------------------------
print("FUNCTION BINARYSTRING")
import FunctionBinaryString.Convert
import FunctionBinaryString.Decode
import FunctionBinaryString.Encode
import FunctionBinaryString.GetByte
import FunctionBinaryString.Length
import FunctionBinaryString.Md5
import FunctionBinaryString.SetByte
import Func... | StarcoderdataPython |
6622886 | #!/usr/bin/env python
import unittest
from journals.databases.icat.sns.interface import SnsICatInterface
if __name__=="__main__":
conn = SnsICatInterface()
#print(conn.get_instruments())
print(conn.get_experiments('NOM'))
#print(conn.get_experiments_meta('NOM'))
#print(conn.get_experiments_id_an... | StarcoderdataPython |
8186460 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
USER = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 2,
"maxLength": 32
},
"password": {
"type": "s... | StarcoderdataPython |
3524184 | <gh_stars>1-10
from machine import Pin
import machine
import time
#utime is an library used for getting the current time and date
#measuring time intervals, and for delays
import utime
#set the input to trigger module to send ultrasonic waves
#the trigger pin (transmitter) must be set as OUTPUT
trig_pin = Pin(0, Pin.... | StarcoderdataPython |
4991478 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-21 07:19
from __future__ import unicode_literals
import PeopleApp.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('PeopleApp', '0007_batch_undergradua... | StarcoderdataPython |
11240574 | # -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~
A simple GIF encoder
~~~~~~~~~~~~~~~~~~~~
Structure of a GIF file: (in the order they appear)
1. always begins with the logical screen descriptor.
2. then follows the global color table.
3. then follows the loop control block (specify the number of loops).
... | StarcoderdataPython |
6477731 | <reponame>scottza/PyTOPKAPI
import datetime as dt
from configparser import SafeConfigParser
import h5py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import pytopkapi.utils as ut
def run(ini_file='plot_Qsim_Qobs_Rain.ini'):
config = SafeConfigParser()
config.read(in... | StarcoderdataPython |
8035170 | <gh_stars>0
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(range(len(nums)+1)) - sum(nums) | StarcoderdataPython |
6619993 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder
from sklearn.metrics import roc_curve as ROC
import matplotlib.pyplot as plt
from sklearn.... | StarcoderdataPython |
8112927 | <gh_stars>10-100
"""Single phase constant Vdc PV-DER code."""
from __future__ import division
import numpy as np
import math
import cmath
import scipy
import six
import pdb
import warnings
from pvder.DER_components import SolarPVDER,PVModule
from pvder.grid_components import BaseValues
from pvder import utility_func... | StarcoderdataPython |
6511546 | <filename>subtle_data_crimes/crime_2_jpeg/Fig7/DL/utils/sampling_funcs.py
import numpy as np
import sigpy as sp
import math
from subtle_data_crimes.functions import new_poisson
import matplotlib.pyplot as plt
# ===================== 2D Variable-density Sampling (based on <NAME>'s Sparse MRI toolbox) ==========... | StarcoderdataPython |
9690377 | """Synchronous SGD
Author: <NAME>
"""
from __future__ import print_function
import tensorflow as tf
import argparse
import time
import os
FLAGS = None
log_dir = '/logdir'
REPLICAS_TO_AGGREGATE = 2
def main():
# Configure
config=tf.ConfigProto(log_device_placement=False)
# Server Setup
cluster = tf.train.Clu... | StarcoderdataPython |
193181 | # Copyright (c) 2011, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions ... | StarcoderdataPython |
8164147 | from Cimpl import *
file = choose_file()
image = load_image(file)
def two_tone(image: Image, color1: str, color2: str) -> Image:
""" Author: <NAME>
Return an image with only two tones with specified colours from the user.
>>> image = load_image(choose_file())
>>> two_tone_image = two_tone(image, "... | StarcoderdataPython |
3381391 | '''Write a program to find whether a given number is a power of 2 or not.
Output Format:
Print 'YES' or 'NO' accordingly
Example:
Input:
64
Output:
YES
Input:
48
Output:
NO
Explanation:
In the first example, 64 is a power of 2 so the answer is YES.
The second number is not a power of 2 hence the answer is NO.'''... | StarcoderdataPython |
3498855 | class A:
x = 3
a = A()
a.x += 1
| StarcoderdataPython |
75050 | <gh_stars>0
from pathlib import Path
from typing import Optional, Union
from dataforseo_sdk.config import Config
from .rest_client import RestClient
class APIClient:
"""APIClient is a wrapper for the original RestClient
class provided by Data for SEO.
"""
def __init__(
self,
credenti... | StarcoderdataPython |
349942 | from kao_decorators import proxy_for
@proxy_for('_items', ['__iter__', '__contains__', '__getitem__', 'append', 'extend'])
class ListArg:
""" Represents a list of args taht hsould be returned as a comma separated list """
def __init__(self, items=None):
""" Initialize with the items """
... | StarcoderdataPython |
179129 | import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import calendar
import re
from tqdm import tqdm
import requests
from bs4 import BeautifulSoup
def get_uwyo_sounding(year, month, FROM, TO, stnm, save_csv = False ):
url = f'http://weather.uwyo.edu/cgi-bin/sounding?region=europe&T... | StarcoderdataPython |
46952 | # -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools.misc import format_date
class AccrualAccountingWizard(models.TransientModel):
_name = 'account.accrual.accounting.wizard'
_description = 'Create accrual entry.'
date = fields.Date(require... | StarcoderdataPython |
6426696 | <reponame>AtosNeves/Beecrowd
s = float(input())
if s <= 2000:
print("Isento")
elif 2000.01 <= s <= 3000:
s1 = s - 2000
s2 = s1 * 0.08
print(f"R$ {s2:.2f}")
elif 3000.01 <= s <= 4500:
a = 1000 * 0.08
s1 = s - 3000
s2 = s1 * 0.18
st = s2 + a
print(f"R$ {st:.2f}")
elif s > 4500:
... | StarcoderdataPython |
3549991 | from datetime import datetime
from uuid import UUID
from pydantic import BaseModel
from app.domain.models.WorkflowMetadata import WorkflowMetadataTypes
class WorkflowMetadata(BaseModel):
"""
Used as the response model for WorkflowMetadata.
"""
id: int
overforingspakke_id: int
workflow_type: ... | StarcoderdataPython |
11252277 | from datetime import datetime, date
from typing import Optional
from pydantic import BaseModel, validator
class ExchangeItem(BaseModel):
"""
Exchange item to convert from currency to another
attrs:
currency_from: Currency a given amount is exchanged from
currency_to: Currency to which a g... | StarcoderdataPython |
376904 | """
Discovery Module for LSL stream discovery and data retrieval
"""
import logging
from threading import current_thread, Thread
from pylsl import resolve_bypred, LostError, TimeoutError, resolve_streams
from .stream import Stream
class Discovery:
"""
Class representing the available LSL stream information and inc... | StarcoderdataPython |
9799609 | <reponame>yuehaowang/pylash_engine<filename>run.py
'''
This is a script tool for running demo and examples made with pylash.
With this tool, you can run demo and examples without installing pylash.
'''
import runpy, sys, os
__author__ = "<NAME>"
ENTRANCE_FILE = "Main.py"
PYLASH_ROOT_DIR = os.path.dirname(__file__)
A... | StarcoderdataPython |
22964 | # coding=utf-8
# init
| StarcoderdataPython |
9623364 | <filename>scripts/automation/trex_control_plane/interactive/trex/common/services/trex_service_ap.py
from trex.stl.api import *
from trex.utils.text_opts import *
from trex.utils.common import natural_sorted_key
from .trex_service import Service, ServiceFilter
from .trex_service_int import ServiceCtx, simpy, TXBuffer
im... | StarcoderdataPython |
3466046 | <gh_stars>0
from __future__ import annotations
from datetime import datetime
import json
import os
from pathlib import Path
from typing import Any, Iterable, Optional
import click
import requests
import toml
from tqdm import tqdm
from xdg import BaseDirectory
from swcc.api import SwccSession
def raise_for_status(r... | StarcoderdataPython |
1669357 | <reponame>cmsong111/NJ_code
arr = []
count = int(input())
for i in range(count):
x, y =map(int,input().split())
arr.append([y,x])
arr.sort()
for i in range(count):
print(arr[i][1],arr[i][0])
| StarcoderdataPython |
9608878 | import re
import time
import requests
import logging
import googlemaps
from io import BytesIO
from bs4 import BeautifulSoup
from typing import List, Tuple
from real_estate_it.model.search import Search
from real_estate_it.model.house import House
logger = logging.getLogger(__name__)
class Immobiliare:
def __in... | StarcoderdataPython |
9723650 | <filename>supertokens_python/normalised_url_domain.py
# Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License") as published by the Apache Software Foundation.
#
# You may not use this file except in compliance with ... | StarcoderdataPython |
3210369 | <reponame>neurothrone/project-dot
from http import HTTPStatus
from .. import BaseClientTestCase
class ClientOpenTestCase(BaseClientTestCase):
def test_index_route(self):
response = self.client.get("/",
follow_redirects=True)
self.assertEqual(response.status_code... | StarcoderdataPython |
6653935 | <gh_stars>10-100
import chainer
from chainer import functions
from chainer import initializers
from ..functions import affine_channel_2d
class AffineChannel2D(chainer.Link):
"""A simple channel-wise affine transformation operation"""
def __init__(self, channels):
super(AffineChannel2D, self).__init... | StarcoderdataPython |
3406443 | <gh_stars>10-100
""" File Submission Service and Interfaces.
The Submission service encapsulates the core functionality of accepting,
triaging and forwarding a submission to the dispatcher.
SubmissionServer is typically exposed via HTTP interface implemented by al_ui,
however the core logic is implemented in Submissi... | StarcoderdataPython |
1961426 | <reponame>BoniLindsley/phile
#!/usr/bin/env python3
# Standard library.
import asyncio
import collections.abc
import functools
import pathlib
import queue
import typing
import unittest
import unittest.mock
# External dependencies.
import watchdog.events
import watchdog.observers
# Internal packages.
import phile.asy... | StarcoderdataPython |
3402131 | <reponame>jerry-git/test-skeleton
import argparse
def cli():
parser = argparse.ArgumentParser(description='Test skeleton creator')
parser.add_argument('input', type=str, help='filepath of input .py file')
parser.add_argument(
'--save', action='store_true', help='save result as test_<input> file')
... | StarcoderdataPython |
349834 | import morphs
import numpy as np
import scipy as sp
import matplotlib.pylab as plt
import seaborn as sns
def _cf_4pl(x, A, K, B, M):
return A + (K - A) / (1 + np.exp(-B * (x - M)))
def _4pl(x, y, color=None, **kwargs):
data = kwargs.pop("data")
popt, pcov = sp.optimize.curve_fit(
_cf_4pl, data[... | StarcoderdataPython |
1688410 | <filename>1.py
def division(a, b):
try:
return a/b
except ZeroDivisionError:
raise ZeroDivisionError("На 0 делить нельзя")
| StarcoderdataPython |
3354358 | import socket
import time
def check_used(port: int) -> bool:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', port))
if result == 0:
sock.close()
return True
else:
return False
def alloc(start_from: int = 7000) -> int:
while ... | StarcoderdataPython |
1794339 | from sklearn.metrics import confusion_matrix, f1_score, roc_curve
import numpy as np
import pandas as pd
class analysis:
def __init__(self):
pass
def _getComplexParams(self, abs=False):
"""
Function for extracting the data associated with
the second component of the complex source.
To call:
_getComp... | StarcoderdataPython |
346521 | <filename>Ideas/Tennis Project/Source Code/Camera.py
import cv2
import numpy as np
class Camera:
CameraMatrix = [];
DistCoeffs = [];
Position = [];
RotationVec = [];
TranslationVec = [];
CourtCorners = [];
Homog = [];
# HALF_COURT_X = 4.115;
HALF_COURT_X = 5.485
HALF_COURT_Z = 11... | StarcoderdataPython |
3384076 | #list comprehension
x = [1, 2, 3, 4, 5]
y = []
for i in x:
y.append(i**2) #adicionar cada valor ao quadrado
print(x)
print(y)
#valor a adicionar + laço + condição
a = [6, 7, 8, 9, 10]
b = [i**2 for i in a]
print (a)
print (b)
#só os número impares
z = [i for i in a if i%2 == 1]
print (z)
| StarcoderdataPython |
9692124 | """Snakemake wrapper for PLASS Protein-Level Assembler."""
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, <NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
from os import path
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
#allow multiple input files for single assembly
left = s... | StarcoderdataPython |
4802647 | <reponame>PlanTL-SANIDAD/covid-predictive-model
import os
import pandas as pd
if __name__ == '__main__':
dp_df = pd.read_csv("../../raw/06.utf8.csv", delimiter=';', index_col=False)
diag_columns = [col for col in dp_df.columns if 'DIA_' in col]
proc_columns = [col for col in dp_df.columns if 'PROC_' in co... | StarcoderdataPython |
11377422 | <filename>core/views.py
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.views.generic import View
from ws4redis.redis_store import RedisMessage
from ws4redis.publisher import RedisPubl... | StarcoderdataPython |
1945222 | <reponame>sm2774us/amazon_interview_prep_2021
from functools import lru_cache
class Solution:
def numMusicPlaylists(self, N, L, K):
@lru_cache(None)
def dp(i, j): return +(j == 0) if not i else (dp(i-1, j-1) * (N-j+1) + dp(i-1, j) * max(j-K, 0)) % (10**9+7)
return dp(L, N) | StarcoderdataPython |
8168999 | # Copyright (C) 2009-2011 <NAME>
#
# The following terms apply to all files associated
# with the software unless explicitly disclaimed in individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that exi... | StarcoderdataPython |
252259 | <gh_stars>0
#!python
# coding=utf-8
from .consumer import EasyAvroConsumer
from .producer import EasyAvroProducer, schema
__version__ = "2.2.0"
__all__ = [
'EasyAvroConsumer',
'EasyAvroProducer',
'schema'
]
| StarcoderdataPython |
198467 | <reponame>solex/presto<gh_stars>0
from copy import deepcopy
import simplejson as json
from presto.utils.fields import Field, MultipleObjectsField, FormField
from presto.utils.exceptions import ValidationError
def get_declared_fields(bases, attrs):
"""
Create a list of Model field instances from the passed in ... | StarcoderdataPython |
5000400 | <gh_stars>0
from .resort import Resort
| StarcoderdataPython |
3471187 | """Sum the total area (in pixels) covered by a segmentation"""
import argparse
import numpy as np
from skimage.io import use_plugin, imread
use_plugin('freeimage')
def sum_segmented_area(segmentation_file):
im_array = imread(segmentation_file)
area = len(np.where(im_array != 0)[0])
return area
def m... | StarcoderdataPython |
3224183 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
#did this to see entire array
np.set_printoptions(threshold = np.nan)
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
... | StarcoderdataPython |
6490215 | <reponame>weinbe58/tfim_noise
from quspin.basis import spin_basis_1d,tensor_basis,boson_basis_1d
from quspin.operators import hamiltonian
from quspin.tools.evolution import evolve
import numpy as np
import cProfile,os,sys,time
import matplotlib.pyplot as plt
def anneal_bath_1(L,Nb,T,gamma=0.2,omega=1.0,path="."):
t... | StarcoderdataPython |
5132964 | #!/usr/bin/env python3
import fileinput
import re
import sys
"Usage gcode_edit.py gcodeprogram.gcode axis offset -- gcode_edit.py program.gcode X -25"
with fileinput.FileInput(sys.argv[1], inplace=True, backup='.bak') as file:
for line in file:
elements = re.split(' ', line)
for i in range... | StarcoderdataPython |
1897273 | # Generated with StressType
#
from enum import Enum
from enum import auto
class StressType(Enum):
""""""
AXIAL_BENDING = auto()
TRUE_WALL = auto()
AXIAL_STRESS = auto()
VON_MISES = auto()
def label(self):
if self == StressType.AXIAL_BENDING:
return "Axial bending stress"
... | StarcoderdataPython |
4908376 | <reponame>roiyeho/drl-book
import numpy as np
import matplotlib.pyplot as plt
import time
import os
import gym
class EnvRunner:
def __init__(self,
env,
agent,
n_episodes=1000,
test_env=None,
test_episode_max_len=10000,
... | StarcoderdataPython |
6516322 | import json
import random
import pygame
import os
from adventure import sound
from adventure import clock
from adventure import camera
from adventure import texture
from adventure import character
from bintrees import rbtree
FULL_SCREEN_FLAG = pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF;
BGCOLOR = (20, 20... | StarcoderdataPython |
4867925 | <gh_stars>1-10
import click
import wiktionarifier.scrape.core as sc
import wiktionarifier.scrape.db as sdb
import wiktionarifier.format.core as fc
@click.group()
def top():
pass
@click.command(help="Scrape entries from wiktionary for use as training data.")
@click.option("--output-dir", default="data/scraped", ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.