id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1721755 | #
# Analytics server
#
import pickle
import jsonpickle
import platform
import json
import io
import os
import sys
import pika
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
import datetime
sns.set()
from sklearn.metrics import r2_score, median_absolu... | StarcoderdataPython |
98933 | <filename>mask2former_video/video_maskformer_model.py<gh_stars>0
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import math
from typing import Tuple
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.data import Metadata... | StarcoderdataPython |
1691047 | '''
Exercício Python 33: Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
'''
A = int(input('Digite o primeiro valor: '))
B = int(input('Digite o segundo valor: '))
C = int(input('Digite o terceiro valor: '))
Menor = A
if B < A and B < C:
Menor = B
if C < A and C < B:
Menor = C
Maio... | StarcoderdataPython |
3302047 | """
Contains functions mplementing different numerical integration schemes.
AUTHOR: <NAME>
DATE: 2020-01-17
"""
import sys
import numpy as np
from scipy.integrate import complex_ode
def evolve_DOP853(J, chi, psi, t_min, t_max, Nt, callback_fun):
t, dt = np.linspace(t_min, t_max, Nt, endpoint=True, retstep=True)
... | StarcoderdataPython |
106919 | <gh_stars>0
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core import mail
from django.urls import reverse
from django.test import TestCase
from django.test.client import Client
from helpdesk.models import Queue, Ticket, FollowUp
from helpdesk import settings as... | StarcoderdataPython |
90371 | #!/usr/bin/python
print('importing modules')
import random
import math
import numpy
import os
import sys
from time import sleep
from argparse import ArgumentParser
from scipy.optimize import fmin_l_bfgs_b as minimize
from PyNEC import *
import multiprocessing as mp
from Queue import Empty
import matplotlib as mpl
mpl.u... | StarcoderdataPython |
4814925 | <filename>finbyz_reports/finbyz/report/finbyz_accounts_receivable_summary/finbyz_accounts_receivable_summary.py
# Copyright (c) 2013, saurabh and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from erpnext.accounts.report.accoun... | StarcoderdataPython |
53468 | import os
import sys
import json
accasim = os.path.abspath(os.path.join('../../accasim'))
sys.path.insert(0, accasim)
import unittest
from accasim.base.resource_manager_class import Resources
class ResourcesTests(unittest.TestCase):
def load_sys_config(self):
fp = 'data/system_def.con... | StarcoderdataPython |
87688 | <filename>sql_to_python.py
#sql_to_python: Simple module using Python to pull SQL data
| StarcoderdataPython |
160192 | import pytest
import scryptlib.utils
import scryptlib.contract
from scryptlib.types import Sig, PubKey, PubKeyHash
import bitcoinx
from bitcoinx import SigHash, PrivateKey, pack_byte
key_priv = PrivateKey.from_arbitrary_bytes(b'test123')
key_pub = key_priv.public_key
pubkey_hash = key_pub.hash160()
wrong_key_priv ... | StarcoderdataPython |
1742265 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2019-03-26 17:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations... | StarcoderdataPython |
118832 | # The following is an implementation of the base encoder from
# the pywallet (https://github.com/jackjack-jj/pywallet), which
# is not subject to any license. Through Simple Wallet, this is
# subject to the following license.
# Copyright (c) 2022 Mystic Technology LLC
# Permission is hereby granted, free of charge, t... | StarcoderdataPython |
90240 | #!/usr/bin/env python
from butter.clone import unshare, setns
import pytest
@pytest.mark.clone
def test_setns(mock):
m = mock.patch('butter.clone._lib')
m = mock.patch('butter.clone._lib.setns')
m.return_value = 0
setns(fd=5)
| StarcoderdataPython |
39626 | <reponame>mmanzi/gradientdomain-mitsuba
import os, sys, subprocess, copy, re
def get_output(script, args = None, shellenv = None):
if sys.platform == 'win32':
cmdLine = '"%s" %s & set' % (script, (args if args else ''))
shell = False
elif sys.platform.startswith('linux'):
cmdLine = 'source "%s" %s ; set' % (sc... | StarcoderdataPython |
3216017 | import os
import shutil
import logging
import pandas as pd
import matplotlib
matplotlib.use("agg") # no need for tk
from supervised.automl import AutoML
from frameworks.shared.callee import call_run, result, output_subdir, utils
log = logging.getLogger(os.path.basename(__file__))
def run(dataset, config):
log... | StarcoderdataPython |
68825 | import gtk
import gtk.gdk as gdk
import gobject
class Fixed(gtk.Container):
def __init__(self):
gtk.Container.__init__(self)
self._children = []
self._changed = False
def max_xy(self):
X = 0
Y = 0
for x, y, child in self._children:
w, h = child.size_request()
X = max(X, x+w)
Y = max(Y, y+h)
... | StarcoderdataPython |
1646554 | import json
from typing import List
class RelationTypeConstraintStore:
def __init__(self):
self.constraints = {}
def load_from_json(self, constraint_json_file: str):
with open(constraint_json_file, 'rt') as f:
self.constraints = json.load(f)
self._verify_integrity()
... | StarcoderdataPython |
1799326 | <filename>nanoservice/reqrep.py
'''
The MIT License (MIT)
Copyright (c) 2016 <NAME>
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... | StarcoderdataPython |
1720691 | <reponame>ExiledNarwal28/cardbot
from random import sample
import inject
from app.cards.factories.card_factories import CardFactory
from app.cards.entities.cards import NORMAL_DECK_LENGTH
from app.cards.entities.decks import Deck
class DeckFactory:
card_factory = inject.attr(CardFactory)
def create(self):
... | StarcoderdataPython |
4821462 | import json
from logging import getLogger
from django.contrib.auth import logout
from django.urls import reverse_lazy
from django.utils.safestring import mark_safe
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from es_user.vouch_proxy import VouchProxyJWT
from es_use... | StarcoderdataPython |
3275487 | <gh_stars>0
#pylint: disable=missing-module-docstring
from unittest import TestCase
from src.cell import Cell
#pylint: disable=missing-class-docstring
class CellTest(TestCase):
#pylint: disable=missing-function-docstring
def test_cell_starts_not_digged(self):
cell = Cell()
self.assertFalse(cell... | StarcoderdataPython |
3264552 | <reponame>rossi1/RES<filename>real_estate_api/supplier/permission.py
from rest_framework.permissions import BasePermission
class IsSupplier(BasePermission):
def has_permission(self, request, view):
return request.user.is_supplier | StarcoderdataPython |
3261523 | <reponame>gojek/CureIAM<filename>CureIAM/models/__init__.py
"""A package for models as data store packaged with this project.
"""
| StarcoderdataPython |
3387772 | <gh_stars>10-100
import gym
import numpy as np
from copo.algo_copo.constants import *
from ray.rllib.models import ModelCatalog
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.utils import get_activation_fn
from ray.rllib.policy.sample_ba... | StarcoderdataPython |
3375215 | #!/usr/local/greenplum-db-6.10.0/ext/python/bin/python
# coding=utf-8
from .deepwalk import DeepWalk
from .line import LINE
| StarcoderdataPython |
1685957 | <filename>zbpy/indexedfieldentity.py<gh_stars>0
from .zbprotocol_pb2 import TableIndexField, TableIndexFields
class IndexedField():
def __init__(self, field_name, index_type, lang_code=''):
"""
Initializes IndexedField.
Parameters:
field_name: string
index_type: ... | StarcoderdataPython |
4827516 | # -*- coding: utf-8 -*-
from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, TypeVar
if TYPE_CHECKING:
from . import Declaration
T = TypeVar("T", bound=Callable[..., Any])
class FormatHandler(Generic[T]):
__slots__ = "_types"
_types: Dict[str, T]
def __init__(self):
self._types... | StarcoderdataPython |
1732471 | from libra.discovery_set import DiscoverySet
def test_discovery_set():
key = DiscoverySet.change_event_key()
assert len(key) == 40
assert key == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 21, 192]
| StarcoderdataPython |
1696050 | # Generated by Django 3.1.5 on 2021-04-22 13:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Course',
fields=[
... | StarcoderdataPython |
1684747 | """A Stack object for incremental sampling
"""
import argparse
import timeit
from typing import Dict, List, Tuple
from graph_tool import Graph
from graph_tool.inference import BlockState
from graph_tool.inference import minimize_blockmodel_dl
from evaluation import Evaluation
from sample import Sample
fro... | StarcoderdataPython |
1797371 |
# major libraries import
from numpy import array, concatenate
#project libraries import
from Regulator import Regulator
#from TTi import PStsx3510P
#from Agilent import A34401_temp
class PIDHeater(Regulator):
"""
Provides P-I-D temperature regulation using 10 A power source
and temperature platinum resi... | StarcoderdataPython |
3382482 | import argparse
import os
import torch
import logging
from init_tool import init_all
from config_parser import create_config
from train_tool import train
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logg... | StarcoderdataPython |
1651321 | <filename>src/original/McGill_Can/vfa.py
import numpy as np
from numpy.linalg import norm
def despot(signal, alpha, TR):
# Ref: <NAME>., <NAME>., & <NAME>. (2005). MRM 53(1), 237–241. https://doi.org/10.1002/mrm.20314
# Based on Matlab code by <NAME>, McGill University
x = signal / np.tan(alpha)
y = si... | StarcoderdataPython |
98568 | <filename>v2.5.7/toontown/estate/DistributedTargetAI.py<gh_stars>1-10
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
import CannonGlobals, random
class DistributedTargetAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCa... | StarcoderdataPython |
4803346 | <reponame>Rohitm619/Softuni-Python-Basic
print ("Hello SoftUni") | StarcoderdataPython |
1718457 | <gh_stars>1-10
#The MIT License
#
#Copyright (c) 2017 DYNI machine learning & bioacoustics team - Univ. Toulon
#
#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 wi... | StarcoderdataPython |
53293 | <reponame>kdart/pycopia
# python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, Ro... | StarcoderdataPython |
89320 | <filename>src/assignments/main_assignment7.py<gh_stars>0
from src.assignments.assignment7 import sum_list_values
'''
Create a function named process_list that calls the sum_list_values function.
Prints the list values and the sum of the element in the list as follows:
joe 10 15 20 30 40 sum: 115
process_list(['joe', 1... | StarcoderdataPython |
3205944 | <reponame>skateman/insights-core<filename>insights/specs/datasources/ipcs.py
"""
Custom datasources to get the semid of all the inter-processes.
"""
from insights.core.context import HostContext
from insights.core.plugins import datasource
from insights.specs import Specs
from insights.core.dr import SkipComponent
@... | StarcoderdataPython |
28434 | <gh_stars>0
#
# Copyright (c) 2013 Docker, 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
#
# U... | StarcoderdataPython |
1631611 | '''A library of Python timeslot functions and terms for use within an ASP
program. When reasoning with time it is often unnecessary (and expensive) to
reason at the minute (or smaller) granularity. Instead it is often useful to
reason in multi-minute time blocks, such as 15 minute blocks.
This library prov... | StarcoderdataPython |
3332969 | <filename>hue_control/hue_light.py<gh_stars>0
################################################################################################################################
# *** Copyright Notice ***
#
# "Price Based Local Power Distribution Management System (Local Power Distribution Manager) v1.0"
# Copyright (c... | StarcoderdataPython |
164411 | <gh_stars>0
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PR... | StarcoderdataPython |
138637 | <reponame>cupcicm/substra<filename>tests/sdk/test_describe.py
import pytest
import substra
from .. import datastore
from .utils import mock_requests, mock_requests_response
@pytest.mark.parametrize(
'asset_name', ['dataset', 'algo', 'objective']
)
def test_describe_asset(asset_name, client, mocker):
item = ... | StarcoderdataPython |
3264305 | <reponame>betodealmeida/nefelibata
from pathlib import Path
import pytest
from nefelibata.builders.index import IndexBuilder
from nefelibata.post import Post
__author__ = "<NAME>"
__copyright__ = "<NAME>"
__license__ = "mit"
test_template = """
{%- for post in posts -%}
{{ post.title }}
{% endfor -%}
{{ next }}
""... | StarcoderdataPython |
1682718 | <gh_stars>1-10
import sys
import time
import argparse
import textwrap
from art import tprint
from .dribbble_user import *
__version__ = "0.0.1"
t1 = time.perf_counter()
def main(argv=None):
argv = sys.argv if argv is None else argv
argparser = argparse.ArgumentParser(
prog="drbl_py",
forma... | StarcoderdataPython |
172832 | import warnings
from numba.errors import NumbaDeprecationWarning, \
NumbaPendingDeprecationWarning, NumbaPerformanceWarning
warnings.simplefilter('ignore', category=NumbaDeprecationWarning)
warnings.simplefilter('ignore', category=NumbaPendingDeprecationWarning)
warnings.simplefilter('ignore', category=NumbaPerfo... | StarcoderdataPython |
4816989 | # Copyright (c) 2019 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 required by applicabl... | StarcoderdataPython |
1635870 | """
# Data Structures and Algorithms - Part B
# Created by <NAME> (16021424)
"""
class Colours():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
GRAY = '\033[1;30m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m' | StarcoderdataPython |
141539 | # Tic-Tac-Toe
import random
def drawBoard(board):
# this function prints the board
# "board" is a list of strings
print(board[7] + '|' + board[8] + '|' + board[9])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[1] + '|' + board[2] + '|' + board... | StarcoderdataPython |
3360892 | import json
def generate_json(split):
source_path = "../../dataset/final_data/commongen/commongen." + split + ".src_alpha.txt"
target_path = "../../dataset/final_data/commongen/commongen." + split + ".tgt.txt"
out_path = "commongen." + split + ".json"
with open(source_path) as source, open(target_pat... | StarcoderdataPython |
3265163 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和值: 2
你应该返回如下子树:
2
/ \
1 3
在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
来源:力扣(LeetCode... | StarcoderdataPython |
68755 | from csv import DictReader
from functools import lru_cache
from itertools import groupby
from pathlib import Path
from typing import TextIO
import click
import h5py
from skelshop.corpus import index_corpus_desc
from skelshop.face.consts import DEFAULT_METRIC
from skelshop.iden.idsegs import ref_arg
from skelshop.util... | StarcoderdataPython |
1681188 | import streamlit as st
from build import build_model
from build import Scatterplot
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import plotly.graph_objects as go
import plotly_express as px
from sklearn.model_selection import train_test_split
from sklearn.data... | StarcoderdataPython |
3382792 | <reponame>KPMcKenna/GBMaker
import warnings
from pymatgen.core import Structure
def formatwarning(
message,
catagory,
*_,
):
return f"{catagory.__name__}\n{message}\n"
warnings.formatwarning = formatwarning
class Warnings:
@classmethod
def UnitCell(cls, unit_cell: Structure):
warni... | StarcoderdataPython |
1768984 | import math
import sys
def main(filepath):
with open(filepath, 'r') as f:
for line in f.readlines():
if line:
line = line.strip()
line = line.split(';')
n = int(line[0])
grid = map(int, line[1].split(','... | StarcoderdataPython |
1779940 | from __future__ import annotations
from typing import Dict, Union, cast
from deprecation import deprecated
from httpx import Response, Timeout
from .. import __version__
from ..base_client import (
DEFAULT_POSTGREST_CLIENT_HEADERS,
DEFAULT_POSTGREST_CLIENT_TIMEOUT,
BasePostgrestClient,
)
from ..utils imp... | StarcoderdataPython |
4815997 | <filename>utils/MathUtils.py
# 数学算法
from _pydecimal import Context, ROUND_HALF_UP
class MathUtils(object):
# 绝对值
@staticmethod
def absValue(value):
return abs(value)
# 十进制转二进制
@staticmethod
def toBin(value):
return bin(value)
# 十进制转八进制
@staticmethod
def toOct(val... | StarcoderdataPython |
82802 | # October 2018
'''
cifero.sheets
Modules syll and translit use cifero.sheets.sheetsdict in their functions.
'''
################################################################################
# default cipher sheets
# better not change these
# these aren't linked to the main program.
ipa_sheet = {
'title': 'IP... | StarcoderdataPython |
102514 | """
Tests find_lcs_optimized function
"""
import timeit
import unittest
from lab_2.main import find_lcs_length, find_lcs_length_optimized
class FindLcsOptimizedTest(unittest.TestCase):
"""
Checks for find_lcs_optimized function
"""
def test_find_lcs_length_optimized_works_faster(self):
"""
... | StarcoderdataPython |
3325775 | <filename>datasets/test/soy_small/importer.py
'''Fetcher for the Soybean (Small) dataset'''
import numpy as np
import pandas as pd
## Config ----------------------------------------------------------------------
URL = 'https://archive.ics.uci.edu/ml/machine-learning-databases/soybean/soybean-small.data'
INT_FMT = '... | StarcoderdataPython |
4801530 | <filename>core/migrations/0014_note_period.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-30 10:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20170430_0830'),
]
op... | StarcoderdataPython |
1670237 | import pandas as pd
import sqlalchemy as sql
import sqlalchemy.sql.functions as db_func
import sqlalchemy.sql.expression as db_expr
from sqlalchemy.orm import aliased
from sqlalchemy.types import ARRAY, INT, VARCHAR, FLOAT
from schools3.config.data import db_tables
from schools3.config.data.features import features_con... | StarcoderdataPython |
1684962 | def count_parameters(model):
"""Counts the number of parameters in a model."""
return sum(param.numel() for param in model.parameters() if param.requires_grad_)
class AttrDict(dict):
def __setattr__(self, key, value):
self[key] = value
def __getattr__(self, item):
return self[item]
| StarcoderdataPython |
1748757 | """Casambi implementation."""
import logging
import time
import random
import re
from typing import Tuple
from pprint import pformat
from asyncio import TimeoutError, sleep
from aiohttp import client_exceptions
from .errors import (
AiocasambiException,
LoginRequired,
ResponseError,
RateLimit,
Ca... | StarcoderdataPython |
3234682 | '''
To render 3d scenes (or even high dimensional), the first thing we need is
the ability to rotate the objects we render and view them from different angles.
This can be done with rotation matrices or quaternions.
We favor the rotation matrix since they are simpler and can be used in spaces of arbitrary dimensionalit... | StarcoderdataPython |
1670125 | import os
import simpy
import numpy as np
from pathlib import Path
from RideSimulator.Grid import Grid
from RideSimulator.Trip import Trip
lat_points, lon_points, trip_distances, trips_per_min = None, None, None, None
def read_data(directory="data", lon_file="lon_points", lat_file="lat_points", distance_file="trip_d... | StarcoderdataPython |
3344371 | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... | StarcoderdataPython |
3339431 | from PyQt4 import Qt, QtCore
class OkCover(Qt.QWidget):
def __init__(self, parent=None):
Qt.QWidget.__init__(self, parent)
self.setWindowFlags(Qt.Qt.FramelessWindowHint)
self.setGeometry(QtCore.QRect(0, 0, 200, self.parent().height()))
#palette
palette = Qt.QPalette()
... | StarcoderdataPython |
196211 | """
Module description:
"""
__version__ = '0.3.0'
__author__ = '<NAME>, <NAME>, <NAME>, <NAME>'
__email__ = '<EMAIL>, <EMAIL>, <EMAIL>'
from .AMR import AMR | StarcoderdataPython |
196785 | <filename>hifive/api/rest/HFBaseWeatherRequest.py
'''
Created by yong.huang on 2016.11.04
'''
from hifive.api.base import RestApi
class HFBaseWeatherRequest(RestApi):
def __init__(self,domain=None,port=80):
domain = domain or 'hifive-gateway-test.hifiveai.com';
RestApi.__init__(self,domain, port)
self.clientId =... | StarcoderdataPython |
10649 | <reponame>oyasr/mudawen<gh_stars>0
import os
from dotenv import load_dotenv
load_dotenv()
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.getenv('SECRET_KEY') or os.urandom(32)
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_RECORD_QUERIES = True
MAIL_SERVER = os.... | StarcoderdataPython |
1792033 | #
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... | StarcoderdataPython |
77238 | <filename>generator.py<gh_stars>0
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib.layers import batch_norm, fully_connected, flatten
from tensorflow.contrib.layers import xavier_initializer
from ops import *
import numpy as np
class Generator(object):
def __init__(self, sega... | StarcoderdataPython |
3357483 | import pytest
from .node import Node
from .bst import BST
@pytest.fixture
def bst_ten_values_random():
""" returns a BST for a list of known values """
return BST([5,8,3,4,1,2,9,6,7,0])
@pytest.fixture
def bst_empty():
""" returns empty BST """
return BST() | StarcoderdataPython |
4836013 | <gh_stars>0
from __future__ import division
from protos import common_pb2
from protos import state_pb2
def do_something():
""" basic example of consumer of proto files """
print('do something with the protos...')
pos = common_pb2.Vec3()
pos.x = 12
print('pos val:',pos.x, pos.y, pos.z)
age... | StarcoderdataPython |
3338778 | # -*- coding: utf-8 -*-
# CMCBot Pipelines
from scrapy.exceptions import DropItem
from time import time, gmtime, strftime
from datetime import datetime
from hashlib import md5
from scrapy import log
from scrapy.exceptions import DropItem
from twisted.enterprise import adbapi
import logging
class ConvertLastUpdatedPi... | StarcoderdataPython |
3235483 | <gh_stars>0
import ida_bytes
filename = 'C:\\Users\\User\\Desktop\\result.bin'
ea_begin = 0x001C0020
print('\n\nBegin')
with open(filename, 'rb') as input:
bytes = input.read()
print('Size of file = ', len(bytes))
ida_bytes.patch_bytes(ea_begin, bytes)
print('End')
| StarcoderdataPython |
101426 | <reponame>vinay4711/Hands-On-Natural-Language-Processing-with-Python<gh_stars>100-1000
from sklearn import metrics
from itertools import chain
from six.moves import range, reduce
import numpy as np
import tensorflow as tf
from data_utils import tokenize, parse_dialogs_per_response
from memory_network import MemoryNetw... | StarcoderdataPython |
114421 | <reponame>Joacchim/BookMyComics<gh_stars>0
import sys
def read_file(path):
try:
with open(path, 'r') as f:
return f.read()
except Exception as e:
print('Failed to read "{}": {}'.format(path, e))
return None
def write_file(content, path):
try:
with open(path, '... | StarcoderdataPython |
1782287 | <gh_stars>1-10
""" python port of zombie/scripting/objects/Recipe.class
Original code copyright TheIndieStone.
python port by Fenris_Wolf
"""
import re
from zomboid.java import ArrayList, HashMap
from .base import BaseScriptObject
class Result:
type : str = None
count : int = 1
drainableCount : ... | StarcoderdataPython |
3384413 | # coding: utf-8
# (C) Copyright IBM Corp. 2020.
#
# 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... | StarcoderdataPython |
1730981 | def CalculateHowManyRelationsWithShortestPathInDataset (Sentences):
POS_NEG_DICT = {"Positives":0 , "Negatives":0};
CLASS_TP_DICT = {"NEG":0} ;
for sentence in Sentences:
for pair in sentence["PAIRS"]:
if (pair.has_key("TOPKP")) and (pair.has_key("TOPKP_Features")):
if ... | StarcoderdataPython |
4812712 | <reponame>codehacken/Kb4ML<gh_stars>0
__author__ = 'ashwin'
__email__ = '<EMAIL>'
"""
All Test Code.
"""
from lib.models.classify import NaiveBayes
data_sep = ","
elim_var = ['$continuous$']
def test_naive_bayes(train_file_reader, test_file_reader):
# Create a Bernoulli NB.
naive_bayes = NaiveBayes()
# ... | StarcoderdataPython |
154124 | def upper(val):
return val.upper()
| StarcoderdataPython |
3271445 | import random as rand
from math import exp, sqrt
from knapsack.hyper.single.problem import solve, validate
def temperature_ksp(t, iteration):
return sqrt(t)
def change_state_candidate_ksp(validator, seq, **kwargs):
while True:
copy = list(seq)
n = len(copy)
position_to_invert = rand... | StarcoderdataPython |
1620701 | <filename>Inventationery/apps/DirParty/admin.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2015-11-16 19:08:22
# @Last Modified by: harmenta
# @Last Modified time: 2015-11-17 13:35:09
from django.contrib import admin
from .models import DirPartyModel
# Register your models here.
admin... | StarcoderdataPython |
3387998 | <reponame>ScriptErrorVGM/Project2021
def main():
def isPrime(n):
if not n < 0 :
if n == 1:
return False
if n % 2 == 0:
return n == 2 and n > 0
d = 3
while d * d <= n and n % d != 0:
d += 2
r... | StarcoderdataPython |
1783483 | #%%
import sys
sys.path.append("../..")
import scipy
import numpy as np
from numpy.linalg import matrix_rank, matrix_power, cholesky, inv
import util.geometry_util as geo_util
from solvers.rigidity_solver.gradient import gradient_analysis
from solvers.rigidity_solver.internal_structure import tetrahedronize
from sol... | StarcoderdataPython |
92484 | from .CSVFileUploadService import *
from .TaskExecutionService import * | StarcoderdataPython |
3335376 | <reponame>OctavianLee/Dahlia
# -*- coding: utf-8 -*-
from .templates import SortTemplate
class PigeonholeSort(SortTemplate):
"""Creates a class to implement the pigeonhole sort.
"""
def sort(self):
"""Uses the pigeonhole sort algorithm to sort.
This is a pigeonhole sort algorithm.
... | StarcoderdataPython |
1755870 | import requests, re, json, time
class watcher:
def twitterWatcher(self, user):
dicTweet = {}
if not user.startswith('http'):
urlAccount = "https://twitter.com/"+user
else:
urlAccount = user
req = requests.get(urlAccount)
page = req.text
if req.status_code == 200:
try:
tweets = re.fin... | StarcoderdataPython |
12637 | <reponame>threefoldtech/Threefold-Circles
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# Copyright (C) 2014-2017 <NAME> <<EMAIL>>
# This program is free software: you can redistribute it and/or modify
# it under ... | StarcoderdataPython |
46630 | <filename>dlex/tf/instance_v1.py
import logging
import os
import random
from collections import OrderedDict, namedtuple
from datetime import datetime
import tensorflow.compat.v1 as tf
from dlex import FrameworkBackend, TrainingProgress
from dlex.configs import Params
from dlex.datasets.tf import Dataset
from dlex.tf.m... | StarcoderdataPython |
146502 | <gh_stars>0
"""empty message
Revision ID: 1096526e6a14
Revises: c93540c85c6c
Create Date: 2020-10-02 14:43:04.971989
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '1096526e6a14'
down_revision = 'c93540c85c6c'
branch_labels... | StarcoderdataPython |
1776847 | <filename>tests/sentry/api/endpoints/test_assistant.py
from __future__ import absolute_import
from copy import deepcopy
from exam import fixture
from django.core.urlresolvers import reverse
from django.utils import timezone
from sentry.assistant import manager
from sentry.models import AssistantActivity
from sentry.... | StarcoderdataPython |
3219040 | <gh_stars>1-10
# coding: utf8
from __future__ import absolute_import
from pycropml.transpiler.errors import PseudoCythonTypeCheckError
from pycropml.transpiler.helpers import serialize_type
from Cython.Compiler import ExprNodes
from six.moves import zip
# based on pseudo
V = '_' # we don't really typecheck or care fo... | StarcoderdataPython |
33687 | <gh_stars>0
from django.conf.urls import include, url
from django.contrib import admin
from httpproxy.views import HttpProxy
from django.views.generic.base import RedirectView
from django.http import HttpResponse
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^transcripts/', include('nuremberg.transcr... | StarcoderdataPython |
3204885 | #!/usr/bin/python
# -*- coding:utf-8 -*-
from gsiot.v3 import *
from gsiot.v3.file.jsonfile import gsJsonFile
class dbFile(gsJsonFile):
def __init__(self,filename):
gsJsonFile.__init__(self,filename)
self.fields=[]
self.flag=False
self.Readfile()
def Savefile(self):
try:... | StarcoderdataPython |
3206264 | from django.contrib import admin
from froide.account.models import Profile
class ProfileAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
search_fields = ['user__username', 'user__first_name', 'user__last_name', 'user__email']
list_display = ('user', 'address')
admin.site.register(Profile, ProfileAdmin)... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.