text string | size int64 | token_count int64 |
|---|---|---|
import socket
from datetime import datetime
# Author @inforkgodara
ip_address = input("IP Address: ")
splitted_ip_digits = ip_address.split('.')
dot = '.'
first_three_ip_digits = splitted_ip_digits[0] + dot + splitted_ip_digits[1] + dot + splitted_ip_digits[2] + dot
starting_number = int(input("Starting IP Number: "... | 973 | 339 |
class CyclesMeshSettings:
pass
| 38 | 15 |
#__init__.py backend
import os
import sys
import logging
from importlib import import_module
L = logging.getLogger('backend')
def create_widget(node):
'''
create widget based on xml node
'''
_widget = None
if 'impl' in node.attrib:
try:
_widget = create_widget_from_impl(node.a... | 1,528 | 496 |
import FWCore.ParameterSet.Config as cms
from CondTools.Geometry.HGCalEEParametersWriter_cfi import *
from Configuration.ProcessModifiers.dd4hep_cff import dd4hep
dd4hep.toModify(HGCalEEParametersWriter,
fromDD4Hep = cms.bool(True)
)
HGCalHESiParametersWriter = HGCalEEParametersWriter.clone(
nam... | 638 | 244 |
#
# File:
# TRANS_streamline.py
#
# Synopsis:
# Illustrates how to create a streamline plot
#
# Categories:
# streamline plot
#
# Author:
# Karin Meier-Fleischer, based on NCL example
#
# Date of initial publication:
# September 2018
#
# Description:
# This example shows how to create a stream... | 1,895 | 766 |
#function to normalise image
#setting new mean = 1, and new varriance = 1
import numpy as np
import math
def normalise(img,new_mean = 1.0,new_variance = 1.0):
print("Normalising the image")
print("setting new mean = "+str(new_mean)+" and new varriance = "+str(new_variance))
r,c = img.shape
mean = np... | 889 | 331 |
import unittest
from photoprism import Client
class TestClass(unittest.TestCase):
def test_upload():
client = Client()
client.upload_photo('20210104_223259.jpg', b'TODO', album_names=['Test Album'])
| 222 | 79 |
# Simulate user activity for Windows
# Can trigger Brave Ads
import random
from time import sleep
import pydirectinput
import os
# clear log function
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# main simulate function
def simulate():
while True:
# u can change x,y with your screen ... | 1,778 | 553 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
counties_drop_list = ["Year", "Los Angeles County", "Merced County", "Riverside County", "San Diego County", "San Mateo County", "Santa Barbara County", "Santa Clara County", "Santa Cruz County"]
df = pd.read_csv("population_all.csv")
df = pd.con... | 1,688 | 696 |
# coding: utf-8
import os
base_dir = os.path.dirname(os.path.realpath(__file__))
music_dir = os.path.join(base_dir, 'music-3')
data_dir = os.path.join(base_dir, 'data-3')
weights_dir = os.path.join(data_dir, 'weights')
weights_file = os.path.join(weights_dir, 'weights')
if not os.path.exists(data_dir):
os.maked... | 1,786 | 766 |
# -*- coding: utf-8 -*-
import pytest
from pymarc import Field, Record
@pytest.fixture
def fake_subfields():
return ["a", "subA", "x", "subX1", "x", "subX2", "z", "subZ."]
@pytest.fixture
def fake_subjects(fake_subfields):
return [
Field(tag="600", indicators=["1", "0"], subfields=fake_subfields)... | 1,184 | 445 |
from TOKEN import LexToken
class Lexer:
def __init__(self,text):
self.my_bool = False
self.result = ''
self.names = {
"case" : "CASE",
"class" : "CLASS",
"else" : "ELSE",
"esac" : "ESAC",
"fi" : "FI",
"if" : "IF",
... | 8,132 | 2,360 |
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from sklearn import feature_selection as fs
from sklearn import naive_bayes
from sklearn import model_selection
from sklearn import metrics
from sklearn import linear_model
from sklearn import svm
from imblearn.under_sampling import Ne... | 5,578 | 2,037 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from pprint import pformat
import re
from ansible import errors
def stringfilter(items, queries, attribute=None):
"""Filter a `items` list according to a list of `queries`. Values from
`items` are kept if they match at l... | 3,204 | 885 |
from wireless_msgs.msg import Connection
from .translator import Translator, TableTranslatorMixin
class ConnectionTranslator(Translator, TableTranslatorMixin):
messageType = Connection
geomType = Translator.GeomTypes.NoGeometry
@staticmethod
def translate(msg):
# Some forks of wireless_msgs... | 1,082 | 303 |
l = ["+", "-"]
def backRec(x):
for j in l:
x.append(j)
if consistent(x):
if solution(x):
solutionFound(x)
backRec(x)
x.pop()
def consistent(s):
return len(s) < n
def solution(s):
summ = list2[0]
if not len(s) == n -... | 671 | 276 |
import numpy as np
def sigmoid(X):
"""sigmoid
Compute the sigmoid function
Parameters
----------
X: numpy array
Output:
-------
Numpy array of the same size of X
"""
return 1/(1+np.exp(-X))
class binary_RBM ():
def __init__ (self, q, max_iter=300, batch_size=64, stop_cr... | 8,098 | 2,457 |
'''
Anagrams
Given two strings, a and b , that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings.
Input :
test cases,t
two strings a and b, for each test case
Output:
Desired O/p
Cons... | 745 | 266 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: green.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import Dict, List
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
class GreenColors(betterproto.Enum):
MOLDY = 0
... | 2,031 | 640 |
"""For each repo in DEPS, git config an appropriate depot-tools.upstream.
This will allow git new-branch to set the correct tracking branch.
"""
import argparse
import hashlib
import json
import os
import sys
import textwrap
import gclient_utils
import git_common
def _GclientEntriesToString(entries):
entries_str ... | 2,874 | 960 |
# Copyright (c) 2019, Grégoire Payen de La Garanderie, Durham University
#
# 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 requir... | 3,269 | 1,102 |
import os
import socket
import codecs
import urllib3
from urllib.parse import urlparse
def __process__(command):
try:
process = os.popen(command)
results = str(process.read())
return results
except Exception as e:
raise e
def create_dir(directory):
if not os.path.exists(directory):
os.makedirs(direct... | 1,833 | 716 |
# coding: utf-8
"""
Finnhub API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fro... | 8,504 | 2,806 |
from collections import defaultdict
from typing import List, Any, Tuple
from util.helpers import solution_timer
from util.input_helper import read_entire_input
from util.console import console
from year_2019.intcode import IntCode, parse
data = read_entire_input(2019,11)
def run_robot(data:List[str], init=0):
deb... | 1,876 | 671 |
# 子弹
import pygame
class Life(pygame.sprite.Sprite):
def __init__(self, img, init_pos):
pygame.sprite.Sprite.__init__(self)
self.image = img
self.rect = self.image.get_rect()
self.rect.topleft = init_pos
def update(self):
self.kill()
| 287 | 105 |
"""
Scrapes OIT's Web Feeds to add courses and sections to database.
Procedure:
- Get list of departments (3-letter department codes)
- Run this: http://etcweb.princeton.edu/webfeeds/courseofferings/?term=current&subject=COS
- Parse it for courses, sections, and lecture times (as recurring events)
"""
from mobileapp... | 6,588 | 1,808 |
'''
Created on 13 déc. 2021
@author: slinux
'''
import inspect
from wxRavenGUI.view import wxRavenAddView
from wxRavenGUI.application.wxcustom.CustomDialog import wxRavenCustomDialog
import wx
import wx.aui
import logging
from .jobs import *
class ViewsManager(object):
'''
classdocs
'''
parentf... | 34,590 | 9,970 |
#!/usr/bin/env python
import datetime
import optparse
import os
import os.path
import struct
import sys
# sudo pip3 install piexif
import piexif
# Make this negative to subtract time, e.g.:
# -datetime.timedelta(hours=5, minutes=9)
#TIME_ADJUSTMENT = datetime.timedelta(hours=5, minutes=9)
#TIME_ADJUSTMENT = datetim... | 4,714 | 1,676 |
def old(name,age):
print(f"my name is {name} and age is {age}")
old as new
new("pooja",23)
| 99 | 44 |
# Copyright (c) 2017-2021 Neogeo-Technologies.
# 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... | 2,449 | 775 |
import os
import sys
import numpy as np
import pandas as pd
import tensorflow as tf
from losses import focal_loss,weighted_binary_crossentropy
from utils import Dataset
class DeepFM(object):
def __init__(self, params):
self.feature_size = params['feature_size']
self.field_size = params['field_size'... | 14,785 | 5,043 |
import numpy as np
from math import log
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, mean_squared_error, mean_absolute_error, classification_report
from math import sqrt
import json
from pprint import pprint
import argparse
parser = argparse.ArgumentParser(f... | 3,815 | 1,349 |
from django.urls import path
from .views import ProcessWebHookAPIView
urlpatterns = [
path(
'webhook/<hook_id>/',
ProcessWebHookAPIView.as_view(),
name='hooks-handler'
),
]
| 207 | 70 |
import logging
import os
from datetime import timedelta
from airflow import settings
from airflow.hooks.base_hook import BaseHook
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.utils.dates import days_ago
CHECK_INTERVAL = 10 # Sleep time (in seconds) between sy... | 3,534 | 1,246 |
# -*- coding: utf-8 -*-
# @Time : 2020/12/23 2:27 PM
# @Author : Kevin
import config
from utils.sentence_process import cut_sentence_by_character
from search.sort.word_to_sequence import Word2Sequence
import pickle
def prepare_dict_model():
lines=open(config.sort_all_file_path,"r").readlines()
ws=Word2Se... | 1,092 | 407 |
from enum import Enum
class BodyPart(Enum):
HEAD = 0
BODY = 1
ARMS = 2
WAIST = 3
LEGS = 4
CHARM = 5
class EquipmentPiece:
def __init__(self, name, body_part, skills):
self.name = name
self.body_part = body_part
self.skills = skills
class ArmourPiece(EquipmentPie... | 681 | 247 |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import, print_function, unicode_literals
import os
import shutil
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
import uuid
from ddt import ddt as DataDrivenTestCase, data as ddt_da... | 11,984 | 3,858 |
#
# @lc app=leetcode id=687 lang=python3
#
# [687] Longest Univalue Path
#
# @lc code=start
from collections import deque
def construct_tree(values):
if not values:
return None
root = TreeNode(values[0])
queue = deque([root])
leng = len(values)
nums = 1
while nums < leng:
... | 1,632 | 543 |
#!/usr/bin/python3
"""Tests for reflinks script."""
#
# (C) Pywikibot team, 2014-2022
#
# Distributed under the terms of the MIT license.
#
import unittest
from scripts.reflinks import ReferencesRobot, XmlDumpPageGenerator, main
from tests import join_xml_data_path
from tests.aspects import ScriptMainTestCase, TestCas... | 6,803 | 1,868 |
import asyncio
class IOLoop(object):
self.event_loop = asyncio.get_event_loop()
def __init__(self):
pass
def start(self):
if self._running:
raise RuntimeError("IOLoop is already running")
if self._stopped:
self._stopped = False
return
| 319 | 100 |
"""
Triangle Challenge
Given the perimeter and the area of a triangle, devise a function that returns the length of the sides of all triangles that fit those specifications. The length of the sides must be integers. Sort results in ascending order.
triangle(perimeter, area) ➞ [[s1, s2, s3]]
Examples
triangle(12, 6) ➞ ... | 1,756 | 889 |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 4 17:01:28 2021
@author: fahim
"""
from keras.models import Model
from keras.layers import Input, Add, Activation, ZeroPadding2D, BatchNormalization, Conv2D, AveragePooling2D, MaxPooling2D
from keras.initializers import glorot_uniform
def identity_block(X, f, filters, ... | 4,232 | 1,917 |
# block between mission & 6th and howard & 5th in SF.
# appears to have lots of buses.
# https://www.openstreetmap.org/way/88572932 -- Mission St
# https://www.openstreetmap.org/relation/3406710 -- 14X to Daly City
# https://www.openstreetmap.org/relation/3406709 -- 14X to Downtown
# https://www.openstreetmap.org/relat... | 808 | 337 |
# -*- coding: utf-8 -*-
"""Console script for bioinf."""
import sys
import click
from .sequence import Sequence
from .sequence_alignment import NeedlemanWunschSequenceAlignmentAlgorithm
from .utils import read_config, read_sequence
@click.group()
def main(args=None):
"""Console script for bioinf."""
@main.comm... | 1,137 | 368 |
import pytest
from package_one.module_one import IntegerAdder
@pytest.fixture
def adder():
print("Test set-up!")
yield IntegerAdder()
print("Test tear-down")
def test_integer_adder(adder):
assert adder.add(1, 2) == 3
"""
In case you'd like to declare a fixture that executes only once per module, then... | 703 | 264 |
from __future__ import unicode_literals
import unittest
from mopidy.local import json
from mopidy.models import Ref
class BrowseCacheTest(unittest.TestCase):
def setUp(self):
self.uris = [b'local:track:foo/bar/song1',
b'local:track:foo/bar/song2',
b'local:track:... | 1,179 | 381 |
# -*- coding: utf-8 -*-
# pylint:disable=missing-module-docstring, missing-function-docstring
import os
from oximachinerunner import OximachineRunner
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
def test_oximachine():
runner = OximachineRunner()
output = runner.run_oximachine(
os.path.join... | 2,214 | 854 |
# coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlVerlichtingstoestelModelnaam(KeuzelijstField):
"""De modelnaam van het verlich... | 11,643 | 3,734 |
import UserInterface
import surfaceFunction, eventFunction
print('Modal library imported')
class Modal(UserInterface.UserInterface):
def __init__(self,name,size,father,
type = None,
position = None,
text = None,
textPosition = None,
fontSize = None,
scale = None,
... | 4,007 | 1,109 |
#!/usr/bin/env python
# encoding: utf-8
"""Expand tilde in filenames.
"""
import os.path
for user in ['', 'dhellmann', 'postgres']:
lookup = '~' + user
print lookup, ':', os.path.expanduser(lookup)
| 209 | 80 |
import string
from unittest2 import TestCase
import os
from hypothesis import given
from hypothesis.strategies import text, lists
from mock import patch, Mock
from githooks import repo
class FakeDiffObject(object):
def __init__(self, a_path, b_path, new, deleted):
self.a_path = a_path
self.b_pat... | 5,103 | 1,761 |
class Zoo:
def __init__(self, name, locations):
self.name = name
self.stillActive = True
self.locations = locations
self.currentLocation = self.locations[1]
def changeLocation(self, direction):
neighborID = self.currentLocation.neighbors[direction]
self.currentLo... | 1,164 | 353 |
# -*- coding: utf-8 -*-
from hmac import HMAC
from hashlib import sha256
import random
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def pbkd(password,salt):
"""
password must be a string in ascii, for some reasons
string of type unicode provokes the follow... | 1,056 | 366 |
# Useful tutorial on tensorflow.contrib.data:
# https://kratzert.github.io/2017/06/15/example-of-tensorflows-new-input-pipeline.html
import glob # Used to generate image filename list
import tensorflow as tf
def input_parser(image_path, label):
"""
Convert label to one_hot, read image from file & perform ... | 2,312 | 749 |
import os
import subprocess
import pathlib
def reemplazar(string):
return string.replace('self.', 'self.w.').replace('Form"', 'self.w.centralWidget"').replace('Form.', 'self.w.centralWidget.').replace('Form)', 'self.w.centralWidget)').replace('"', "'")
try:
url_archivo = input('Archivo: ').strip().strip('"'... | 2,999 | 1,056 |
import KratosMultiphysics as KM
import KratosMultiphysics.HDF5Application.temporal_output_process_factory as output_factory
import KratosMultiphysics.HDF5Application.file_utilities as file_utils
def Factory(settings, Model):
"""Return a process for writing simulation results for a single mesh to HDF5.
It also ... | 2,450 | 713 |
"""
This script requires developers to add the following information:
1. add file and function name to srcfiles_srcfuncs
2. add file and directory name to srcdir_srcfiles
3. add expected display name for the function to display_names
"""
import os
import itertools
from shutil import copyfile... | 2,551 | 813 |
from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop
from entities import BaseEntity
from constants import Gender, UserStatus, Device, APIStatus
from errors import DataError
class User(BaseEntity):
name = ndb.StringProperty()
mail = ndb.StringProperty()
gender = msgprop.EnumPr... | 1,442 | 460 |
__all__ = ['Order', 'Item']
from django.db import models
from django.contrib.auth import get_user_model
from paytm import conf as paytm_conf
from paytm.helpers import sha256
class Item(models.Model):
price = models.FloatField()
name = models.CharField(max_length=255)
tag = models.CharField(max_length=255... | 3,327 | 1,165 |
from .models import TFFMClassifier, TFFMRegressor, TFFMRankNet
__all__ = ['TFFMClassifier', 'TFFMRegressor', 'TFFMRankNet']
| 125 | 52 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
import re
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar a... | 7,617 | 2,453 |
import sys, unittest, glfw
sys.path.insert(0, '..')
from OpenGL.GL import *
from engine.base.shader import Shader
from engine.base.program import *
import helper
class ProgramTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.window = helper.initAndGetWindow()
@classmethod
def tear... | 1,456 | 447 |
import aiohttp
import asyncio
# Grab the movie genre in a slightly painful way
async def get_genre(movie_title, session):
search_string = "+".join(movie_title.split())
url = f'https://www.google.com/search?q={search_string}'
async with session.get(url) as resp:
html = await resp.text()
... | 1,253 | 390 |
# core modules
from math import pi
# 3rd party modules
import matplotlib.pyplot as plt
import pandas as pd
# internal modules
import analysis
def main(path):
df = analysis.parse_file(path)
df = prepare_df(df, grouping=(df['date'].dt.hour))
print(df.reset_index().to_dict(orient='list'))
df = pd.DataF... | 2,623 | 993 |
from datetime import datetime
from threading import Lock
from Database import Database
class LoggedSensor:
"""
This is a common base class for all sensors that have data to be stored/logged.
"""
registered_type_ids = []
def __init__(self, type_id, max_measurements=200, holdoff_time=None):
... | 1,894 | 541 |
#!/usr/bin/env python
import unittest
from algorithms.sets.cartesian_product import cartesian
class TestFatorial(unittest.TestCase):
def setUp(self):
self.set_a = [1, 2]
self.set_b = [4, 5]
def test_cartesian_product(self):
self.assertEqual(cartesian.product(self.set_a, self.set_b),... | 1,046 | 450 |
import boto3
from botocore.exceptions import ClientError
import gzip
import io
import os
import csv
import re
class S3Data(object):
def __init__(self, bucket_name_, prefix_, file_, df_schema_, compression_type_,
check_headers_, file_type_, access_key_=None, secret_key_=None,
regi... | 14,501 | 4,015 |
from datetime import datetime
import timebomb.models as models
def test_Notification():
notif = models.Notification("message")
assert notif.content == "message"
assert notif.read is False
assert str(notif) == "message"
def test_Player():
player = models.Player("name", "id")
assert player.... | 5,520 | 1,801 |
from django.contrib import admin
from .models import Tag, Sentence, Review
admin.site.register(Tag)
class ReviewInline(admin.StackedInline):
model = Review
extra = 0
readonly_fields = (
'modified_time',
'last_review_date',
)
class SentenceAdmin(admin.ModelAdmin):
# docs.djangop... | 1,801 | 546 |
"""
One off script to Map evidence codes between ECO and GO
https://github.com/evidenceontology/evidenceontology/blob/master/gaf-eco-mapping.txt
"""
import datetime
from wikidataintegrator import wdi_core, wdi_login
from scheduled_bots.local import WDPASS, WDUSER
login = wdi_login.WDLogin(WDUSER, WDPASS)
go_evidenc... | 1,930 | 1,034 |
import pytest
from django.contrib.auth import get_user_model
from emenu.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> get_user_model(): # type: ignore
return UserFactory()
| 315 | 105 |
from __future__ import unicode_literals
import json
import numpy as np
from builtins import str
from abc import ABCMeta, abstractmethod
from pychemia import HAS_PYMONGO
from pychemia.utils.computing import deep_unicode
if HAS_PYMONGO:
from pychemia.db import PyChemiaDB
class Population:
__metaclass__ = ABCMe... | 6,322 | 2,000 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pynessie` package."""
import pytest
import requests_mock
import simplejson as json
from click.testing import CliRunner
from pynessie import __version__
from pynessie import cli
from pynessie.model import ReferenceSchema
def test_command_line_interface(reque... | 2,034 | 681 |
from .request_context import RequestContext
from .tracker import ContextTracker
from .request import DjangoRequest, FlaskRequest
| 129 | 30 |
import re
from django.db.models import Q, Count, Sum, Case, When, IntegerField, Value
from iaso.models import OrgUnit, Instance, DataSource
def build_org_units_queryset(queryset, params, profile):
validation_status = params.get("validation_status", OrgUnit.VALIDATION_VALID)
has_instances = params.get("hasIn... | 8,183 | 2,500 |
import pandas as pd
import numpy as np
import xgboost as xgb
from tqdm import tqdm
from sklearn.svm import SVC
from keras.models import Sequential
from keras.layers.recurrent import LSTM, GRU
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.embeddings import Embedding
from keras.layers.normali... | 7,551 | 2,671 |
from django.apps import AppConfig
class CbtConfig(AppConfig):
name = 'cbt'
| 81 | 28 |
# Code generated by sqlc. DO NOT EDIT.
import dataclasses
from typing import Optional
@dataclasses.dataclass()
class Author:
id: int
name: str
bio: Optional[str]
| 176 | 54 |
__version__ = "0.0.1"
default_app_config = "wagtail_site_inheritance.apps.WagtailSiteInheritanceAppConfig"
| 108 | 44 |
import os.path
import numpy as np
def sinc2d(x, y):
if x == 0.0 and y == 0.0:
return 1.0
elif x == 0.0:
return np.sin(y) / y
elif y == 0.0:
return np.sin(x) / x
else:
return (np.sin(x) / x) * (np.sin(y) / y)
def a(x):
return x + 1
def b(x):
return 2 * x
def c... | 779 | 335 |
"""Adds a chook to a git repository.
Usage:
chooks add [--stdin | --argument] [--once | --filter=FILTER...] [--global]
[--fatal] [--hook=NAME...] [--name=NAME] [--disabled]
[--] <command> [<args>...]
Options:
--stdin Supply input files to this chook via stdin.
--filter=<filt... | 1,970 | 592 |
# Copyright 2020 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | 1,095 | 328 |
#! /usr/bin/env python
# Copyright (c) 2015 William Lees
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, m... | 3,432 | 1,091 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Professional(models.Model):
# User
user = models.OneToOneField('users.User', primary_key=True, related_name='professional', verbose_name=_("User"))
class Meta:
ordering = ('user__first_name', 'user__last_na... | 481 | 150 |
import unittest
import datetime
from weightTrack import WeightNote
class TestWeightNote(unittest.TestCase):
### Testing getter methods ###
def test_shouldGetWeight(self):
testWeight = WeightNote(100, "Ate breakfast")
self.assertEqual(testWeight.getWeight(), 100, "Should be 100")
# Note:... | 1,882 | 542 |
__author__ = 'hhwang'
| 22 | 11 |
# -*- encoding: utf-8 -*-
import datetime
def formata_data(data):
data = datetime.datetime.strptime(data, '%d/%m/%Y').date()
return data.strftime("%Y%m%d")
def formata_valor(valor):
return str("%.2f" % valor).replace(".", "")
| 243 | 96 |
import argparse
import torch
import syft as sy
from syft import WebsocketServerWorker
def get_args():
parser = argparse.ArgumentParser(description="Run websocket server worker.")
parser.add_argument(
"--port",
"-p",
type=int,
default=8777,
help="port number of the webso... | 1,105 | 359 |
import skimage.io
import skvideo.io
import os
import h5py
from sklearn.externals import joblib
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import f1_score
import scipy.misc
import scipy.signal
import numpy as np
from sporco import util
import... | 7,687 | 3,292 |
UNKNOWN = u''
def describe_track(track):
"""
Prepare a short human-readable Track description.
track (mopidy.models.Track): Track to source song data from.
"""
title = track.name or UNKNOWN
# Simple/regular case: normal song (e.g. from Spotify).
if track.artists:
artist = next(it... | 1,126 | 360 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... | 11,162 | 3,615 |
#!/usr/bin/env python
""" generated source for module Test_CanonicalJSON """
# package: org.ggp.base.util.crypto
import junit.framework.TestCase
import org.ggp.base.util.crypto.CanonicalJSON.CanonicalizationStrategy
#
# * Unit tests for the CanonicalJSON class, which provides a
# * standard way for GGP systems t... | 1,925 | 730 |
# -*- coding: utf-8 -*-
class Tile(int):
TILES = '''
1s 2s 3s 4s 5s 6s 7s 8s 9s
1p 2p 3p 4p 5p 6p 7p 8p 9p
1m 2m 3m 4m 5m 6m 7m 8m 9m
ew sw ww nw
wd gd rd
'''.split()
def as_data(self):
return self.TILES[self // 4]
class TilesConverter(object):
@stat... | 3,217 | 1,160 |
import garm.indicators as gari
import ham.time_utils as hamt
import ohlcv
import luigi
import strategies as chs
from luigi.util import inherits
@inherits(chs.Strategy)
class BuyAndHold(chs.Strategy):
FN = gari.buy_and_hold_signals
def requires(self):
for m in hamt.months(self.start_date, self.end_da... | 461 | 156 |
from py2api.constants import TRANS_NOT_FOUND, _OUTPUT_TRANS, _ATTR, _VALTYPE, _ELSE
class OutputTrans(object):
"""
OutputTrans allows to flexibly define a callable object to convert the output of a function or method.
For more information, see InputTrans
"""
def __init__(self, trans_spec=None):
... | 4,866 | 1,471 |
import pytesseract
import os
import time
import requests
import json
from PIL import Image,ImageFont,ImageDraw
# 读取配置文件
with open('config.json') as json_file:
config = json.load(json_file)
# 默认的文件保存的目录
MAIN_PATH = './imageApi/image/'
# FONT,用于将文字渲染成图片
FONT = config['font']
def strToImg(text,mainPath):
'''
... | 1,778 | 801 |
#!/usr/bin/env python3
# url: http://www.pythonchallenge.com/pc/return/5808.html
import requests
import io
import PIL.Image
url = 'http://www.pythonchallenge.com/pc/return/cave.jpg'
un = 'huge'
pw = 'file'
auth = un, pw
req = requests.get(url, auth=auth)
img_io = io.BytesIO(req.content)
img = PIL.Image.open(img_io)
... | 804 | 351 |
# coding: utf-8
# ### Open using Databricks Platform/Py-spark. It holds the code for developing the RandomForest Classifier on the chosen subset of important features.
# In[1]:
import os, sys
import pandas as pd
import numpy as np
from sklearn.metrics import matthews_corrcoef
import pyspark
from numpy import array... | 2,258 | 890 |
#!/usr/bin/env python3
# coding=utf-8
import os as os
import sys as sys
import io as io
import traceback as trb
import argparse as argp
import gzip as gz
import operator as op
import functools as fnt
def parse_command_line():
"""
:return:
"""
parser = argp.ArgumentParser()
parser.add_argument('--... | 4,997 | 1,399 |
#-*- coding: utf-8 -*-
from django.db import models
# Create your models here.
class Feature(models.Model):
day = models.SmallIntegerField()
month = models.SmallIntegerField()
year = models.SmallIntegerField()
momentum = models.FloatField(
null=True, blank=True)
day5disparity = models.Flo... | 4,219 | 1,405 |