content stringlengths 5 1.05M |
|---|
def loaddata():
data = pd.read_csv('../../data/raw/olympic_dataset.csv', low_memory=False, encoding = 'utf-8')
return data
def nocMedals (data, noc)
newdata=data[data['NOC']== team].dropna()
return newdata
def nocathletes(data, noc
newdata=data[data['NOC'] == team]
return newdata
def athletes... |
""" This process performs a backup of all the application entities for the given
app ID to the local filesystem.
"""
import cPickle
import errno
import logging
import multiprocessing
import os
import random
import re
import shutil
import time
from appscale.datastore import appscale_datastore_batch
from appscale.datast... |
from networkx.drawing.nx_agraph import graphviz_layout |
"""classifier.py: do text classification by SVM on unbalanced data, using sklearn, evaluate the classifier with 5/10 cross validation"""
__author__ = "YuanSun"
from __future__ import division
import sys
import random
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pylab as pl
... |
'''
This function fits the spectral correlation to multiple lorentzians.
'''
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt
'''
These functions are in the spectral domain.
'''
def fit_with_lorentzian(zeta_in, spectral_corr, params):
if len(params) == 4:
... |
import pickle
import sys
# Very large compute graphs require that Python recurses the pointer chain
# to depths upward of 10000 (Python default is only 1000)
sys.setrecursionlimit(50000)
def saveGraph(graph, path):
if path.split('.')[-1] != 'ccg':
print('WARN: Catamount graphs should save to .ccg filename... |
import os
from xu.compa.xhash import Xash, XashList
def path2Xash(path):
folder = os.path.dirname(path)
data = os.path.basename(path)
name, ext = os.path.splitext(data)
return Xash(name, ext, folder)
def createXash(name: str, categoryId: str, tagList: dict, ext=""):
text = categoryId + name
... |
# coding = utf-8
# time : 2017/12/3 22:50
# __author__ = 'lzrture'
import requests
from lxml import etree
import time
from retrying import retry
import xlwt
class CountyLeader:
def __init__(self):
self.headers = {
"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) \
AppleWebKit/537.36 ... |
"""Module containing functions for calling sambamba."""
from .util import run_command
def sambamba_sort(input_bam,
output_bam,
threads=1,
tmp_dir=None,
log_path=None):
"""Sorts bam file using sambamba.
Parameters
----------
inpu... |
lista = []
positivos = 0
for i in range(0, 6):
lista.append(float(input()))
if lista[i] > 0:
positivos += 1
print(f"{positivos} valores positivos")
|
from networkx.algorithms.operators.all import *
from networkx.algorithms.operators.binary import *
from networkx.algorithms.operators.product import *
from networkx.algorithms.operators.unary import *
|
from tsutils.menu.closable_embed_base import ClosableEmbedMenuBase
from padinfo.view.awakening_help import AwakeningHelpView
from padinfo.view.experience_curve import ExperienceCurveView
from padinfo.view.id_traceback import IdTracebackView
class ClosableEmbedMenu(ClosableEmbedMenuBase):
view_types = {
A... |
# coding: utf-8
import logging
import os
CARDPAY_API_URL = os.getenv('CARDPAY_API_URL', 'https://sandbox.cardpay.com')
TERMINAL_CURRENCY = os.getenv('TERMINAL_CURRENCY', 'USD')
PAYMENTPAGE_TERMINAL_CODE = os.getenv('PAYMENTPAGE_TERMINAL_CODE', '18397')
PAYMENTPAGE_PASSWORD = os.getenv('PAYMENTPAGE_PASSWORD', 'FpK2cy... |
import autograd.numpy as np
import scipy.interpolate
from autograd import primitive
from scipy.sparse import csr_matrix
import wh
__euler_mascheroni = 0.57721566490153286060651209008240243104215933593992
__sparse_fmt = csr_matrix
__interp1d_kind = 'linear'
__gtilde_subsample = 1
__gtilde_pickle_fn = 'VBHP/gtilde.pkl'... |
# coding=utf-8
import unittest,time
from selenium import webdriver
from shadon.log import logger
from shadon.global_control import Global_control
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from s... |
from aoc_wim.aoc2019 import q24
test_bugs = """\
....#
#..#.
#..##
..#..
#....
"""
def test_example_b():
result = q24.part_b(test_bugs, t=10)
assert result == 99
|
import asyncio
import datetime
import logging
import ssl
from typing import List
import aiohttp
import pytz
from bitpanda import enums
from bitpanda.Pair import Pair
from bitpanda.subscriptions import Subscription, SubscriptionMgr
logger = logging.getLogger(__name__)
class BitpandaClient(object):
REST_API_URI ... |
from pymongo import MongoClient
from lib import DadosAbertos
import schedule
import time
import os
import sys
def coleta():
# hostname do mongodb, consultado via variavel de ambiente
server_mongo = 'mongodb'
# Conexao ao mongoDB
conn = MongoClient(server_mongo, 27017)
# Conexao ao da... |
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
from airflow.hooks.base_hook import BaseHook
import psycopg2
default_args = {
"owner": "airflow",
"depends_on_past": False,
"start_date": datetime(2018, 10, 14),
"email": ["bansals... |
from floodsystem.geo import rivers_with_station
from floodsystem.geo import stations_by_river
from floodsystem.stationdata import build_station_list
def run():
rivers = []
riverset = set()
stations = build_station_list()
riverswithstations = rivers_with_station(stations)
for i in riverswithstations... |
import re
def url_validator(url: str) -> bool:
"""
validate given string for valid url
:param str url: string url
:return: true if string is valid else false
:rtype: bool
"""
_valid = False
if url and isinstance(url, str) and re.match(r'(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\... |
import flask.ext.api
import os
static_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../ui/"))
app = flask.ext.api.FlaskAPI("NewsBuddy", static_folder=static_path, static_url_path="") |
import unittest
from app.models import Quotes
from app import db
class QuotesTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Quote class
'''
def setUp(self):
'''
Set up method that will run before every Test.
'''
self.new_quote = Quotes("David", "Let it all work out..")
... |
import discord
import sys
import os
import io
import json
import aiohttp
import ezjson
from discord.ext import commands
class League_Of_Legends:
def __init__(self, bot):
self.bot = bot
with open('data/apikeys.json') as f:
lol = json.load(f)
self.token = lol.get("... |
import numpy as np
import cv2
try:
xrange
except NameError:
xrange = range
class PatchGenerator:
def __init__(self,stepsize, imsize, winsize=None):
self.stepsize = stepsize
self.imsize = imsize
if len(self.imsize)==2:
self.imsize=(imsize[0],imsize[1],1)
if wins... |
import re
import asyncio
all_clients = {}
re_http_forward_proxy = re.compile(
r'^http://([^:/]+)(?::([^/]*))?/(.*)')
async def read_http_header(reader):
header = b''
while True:
line = await reader.readline()
if not line:
return
header += line
if line == b'\r... |
class CtrlBase(object):
"""
The base of a MVC controller.
The only necessary method is get_view, this returns the filename (relative to the site_root)
to build the response from.
"""
def get_view(self):
"""
:return: The filename (relative to the site_root) of the view
"""... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# freeseer - vga/presentation capture software
#
# Copyright (C) 2011 Free and Open Source Software Learning Centre
# http://fosslc.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import matplotlib.pyplot as plt
import cv2
import numpy as np
from skimage.feature import hog
from skimage import data, exposure
class Feature:
def __init__(self, path):
self.path=path
def hog(self):
image = cv2.imread(self.path)
fd, hog_image = hog(image, orientations=8, pixels_per_c... |
from nmigen import *
from nmigen.hdl.rec import *
from utils import bitcount
from vga_timing import VGATiming
class VGALayout(Layout):
def __init__(self, w: int, h: int):
super().__init__([
("hsync", 1),
("vsync", 1),
("visible", 1),
("x", bitcount(w)),
... |
import copy
import math
import os
class SUTDHMM:
def __init__(self, k=1, special_word='#UNK#', dummy_word='#DUM#', pre_prob={}, default_emission=0.0):
# 2 layer dictionary depth-0 key is the label, depth-1 key is the word
self.emission_params = {}
self.y_count = {}
self.y_labels = ... |
import os
import signal
import subprocess
from time import sleep
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.constants import Defaults
class SimpleModbusSlave:
def __init__(self, ip='0.0.0.0', port=502, discrete_inputs=10, coils=10, input_registers=10, holding_registers=10):
... |
import json
from project.api.models import User
from project import db
from project.tests.base import BaseTestCase
import datetime
from project.tests.utils import add_user
class TestUserService(BaseTestCase):
"""Tests for the Users Service."""
def test_users(self):
"""Ensure the /ping route behaves ... |
import os
import posixpath
import errno
import json
import resource
import sys
import shutil
import textwrap
import urllib.parse
import urllib.request
import warnings
import logging
# External modules
import click
import yaml
# We import botocore here so we can catch when the user tries to
# access AWS without having ... |
from __future__ import division
import copy
import tensorflow as tf
def tri_vec_shape(N):
return [N * (N + 1) // 2]
def init_list(init, dims):
def empty_list(dims):
if not dims:
return None
else:
return [copy.deepcopy(empty_list(dims[1:])) for i in range(dims[0])]
... |
#!/usr/local/bin/python3
import collections
class Point(collections.namedtuple("_Point", ["x", "y", "name"])):
def distance_to(self, x, y):
return abs(x - self.x) + abs(y - self.y)
points = []
with open("input.txt") as f:
for line in f.readlines():
[x, y] = map(int, line.strip().split(", "))... |
#!/usr/bin/env python3
# encoding: utf-8
""" Configuration parser for reading, writing and manipulating
.ini files. This implementation features some customisations
such as sorting of keys, and convenience functions that
wrap load() and save() operations.
"""
from configparser import SafeConfigParser... |
# Generated by Django 2.1.7 on 2019-05-07 16:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('analytics', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='objectviewed',
name='session_id',
... |
from pyschedule import Scenario, solvers, plotters
def plot(S) :
if solvers.mip.solve(S):
# %matplotlib inline
plotters.matplotlib.plot(S,task_colors=task_colors,fig_size=(10,5))
else:
print('no solution exists')
if __name__ == "__main__":
S = Scenario('bike_paint_shop', horizon=10... |
from keckdrpframework.primitives.base_primitive import BasePrimitive
from kcwidrp.primitives.kcwi_file_primitives import kcwi_fits_reader, \
kcwi_fits_writer
import os
class CorrectIllumination(BasePrimitive):
"""Subtract master bias frame"""
def __init__(self, action, context):
BasePrimitive.__... |
"""
Stein Variational Gradient Descent implementation.
"""
import torch
import utils
import math
import numpy as np
def get_diff_sq(a, b):
"""
Computes squared pairwise differences between a and b.
:param a: tensor a
:param b: tensor b
:return: squared pairwise differences between a and b
"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2018 Ryan Collins <rlcollins@g.harvard.edu>
# Distributed under terms of the MIT license.
"""
Extract & classify trio allele counts for all complete sets of non-null genotypes
"""
import argparse
import sys
from collections import defaultdict
import pysam
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib # send mail
import socket # get host name
import commands
import datetime
import base64
# using SendGrid's Python Library
# https://github.com/sendgrid/sendgrid-python
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
... |
#coding:utf-8
import os
from cactus.tests.deployment import BaseDeploymentTestCase, DummyDeploymentEngine, DummySite, DummyUI, DummyFile
class FileChangedTestCase(BaseDeploymentTestCase):
def setUp(self):
super(FileChangedTestCase, self).setUp()
self.ui = DummyUI()
self.site = DummySite(s... |
#!/bin/sh
while true
do
./rocket-bot.py
sleep 1
done
|
#!/usr/bin/env python
from cyverse_irods.CyRODS import CyVerseiRODS
from datetime import datetime
from os import path, walk
import argparse
ap = argparse.ArgumentParser(description="CyVerse/iRODS interaction")
ap.add_argument("--upload", action='store_true')
ap.add_argument("--localsource")
ap.add_argument("--remoted... |
from src.grid.grid import Grid
from pyomo.environ import *
def create_model(grid: Grid, normalize: bool = False):
"""
Create a Pyomo model for the OPF problem.
grid -- Grid object specifying the topology and parameters of the grid.
Load power bounds are specified in the grid.loads[i].p_max
... |
import numpy
import random
from tqdm import tqdm
from NeuralNetworks.Model.losses import loss_from_function
class Sequential:
def __init__(self):
self.layers = list()
self.lr = 0.01
pass
def add(self, layer):
self.layers.append(layer)
pass
def comp... |
#!/usr/bin/env python
from board import SCL, SDA
import busio
import adafruit_ssd1306
# create I2C interface
i2c = busio.I2C(SCL, SDA)
# create OLED class
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
# clear display
disp.fill(0)
disp.show()
|
from httpx import Response
from ..exceptions import HTTPException
def http_status_handler(response: Response) -> None:
status_code = response.status_code
if status_code == 200:
return
exception = HTTPException(
status_code=status_code, detail={
400: 'Bad request',
... |
#!/usr/bin/env python
import sys
from pubsubcommon import *
def callback(body, message):
sys.stdout.write('Message received was: %s\n' % (body, ))
message.ack()
while True:
with kombu.Connection(**conn_dict) as conn:
with conn.Consumer(queue, callbacks=[callback]):
for _ in kombu.ev... |
from zeroSumGA import PlanetWarsProblem, PlanetWarsTimeLine
from pygga import PyGGA
from build import zeroSumBuilder
from argparse import ArgumentParser
class zeroSumGaParser(object):
def __new__(self):
argparser = ArgumentParser()
argparser.add_argument('-generations', default=10, type=int)
... |
from flask import Flask
from .config import configs
from .KV import kv
from .db import db
from .user_helper import login_manager
def create_app(env):
app = Flask(__name__, template_folder="../templates", static_folder="../static")
app.config.from_object(configs[env])
login_manager.init_app(app)
kv.in... |
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
from agents import (
ModelBasedAgent,
AbstractFeatureProvider,
ViewsFeaturesProvider,
Model
)
from reco_gym import Configuration
logreg_poly_args = {
'num_products': 10,
... |
import collections
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
# This shortcut create a class named "Balance" with 2 attributes :
# "income" & "outcome"
Balance = collections.namedtuple('Balance', 'income outcome')
class GuziCreator:
def create_guzi(user, date, index):
... |
#!/usr/bin/env python3
import urwid
import urwid
def menu_button(caption, callback):
button = urwid.Button(caption)
urwid.connect_signal(button, 'click', callback)
return urwid.AttrMap(button, None, focus_map='reversed')
def sub_menu(caption, choices):
contents = menu(caption, choices)
def open_m... |
from callbench.callables import *
obj = Callable()
meth = obj.meth
umeth = Callable.meth
try:
fastmeth = obj.fastmeth
ufastmeth = Callable.fastmeth
except AttributeError:
pass
def have_PEP_580(obj):
return bool(type(obj).__flags__ & 2048)
def have_PEP_590(obj):
return bool(type(obj).__flags__... |
# BSD 3-Clause License; see https://github.com/jpivarski/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import sys
import pytest
import numpy
import awkward1
def test_record():
array1 = awkward1.Array([{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}, {"x": 3, "y": 3.3}], checkvalid=True).layout
... |
# Copyright (c) 2017 SUSE LLC
import logging
import re
import subprocess
# Run a command, and return the result in string format, stripped. Return None if command fails.
def _run_cmd(cmd_array):
try:
return subprocess.check_output(cmd_array).decode("utf-8").strip()
except subprocess.CalledProcessErro... |
import FWCore.ParameterSet.Config as cms
#------------------------------------------------
#AlCaReco filtering for pi0 calibration:
#------------------------------------------------
# create sequence for rechit filtering for pi0 calibration
from Calibration.EcalAlCaRecoProducers.alCaPi0HLTRegRecHits_cfi import *
seqAl... |
# Copyright 2021 Google 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 writing, ... |
# -*- coding: utf-8 -*-
"""
Basic example for python-highcharts
All datasets need to input using "add_data_set" method
Highchart options can be either set by "set_options" method as showing here or
construct a option dictionary object and input using "set_dict_options" method
"""
from highcharts import Highchart # i... |
from datetime import timedelta
from django.shortcuts import reverse
from provider import constants
from provider.views import CaptureViewBase, AuthorizeViewBase, RedirectViewBase
from provider.views import AccessTokenViewBase, OAuthError
from provider.utils import now
from provider.oauth2 import forms
from provider.oau... |
#%%
import os
import glob
import itertools
import re
import numpy as np
import pandas as pd
import collections
import skbio
import git
#%%
# Find project parental directory
repo = git.Repo("./", search_parent_directories=True)
homedir = repo.working_dir
# Define data directory
datadir = f"{homedir}/data/processed_seq... |
from django.urls import path
from .views import HomePageView, AboutPageView, StatsPageView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('about/', AboutPageView.as_view(), name='about'),
path('stats/', StatsPageView.as_view(), name='stats'),
] |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Project'
db.create_table(u'ide_project', (
(u'id', self.gf('django.db.models.fie... |
from django.core.validators import BaseValidator
from django.utils.translation import ugettext_lazy as _
class ProbablyLengthValidator(BaseValidator):
message = _('Ensure this value has at %(limit_value)s characters (it has %(show_value)d).')
code = 'probably_length'
def compare(self, a, b):
retu... |
"""
Departures
http://doc.navitia.io/#departures
Also known as /departures service.
This endpoint retrieves a list of departures from a specific datetime of a selected object. Departures are ordered chronologically in ascending order as:
url Result
/coverage/{region_i... |
# -*- coding: utf-8 -*-
import numpy as np
def get_field(self, args=None):
"""Get the value of variables stored in Solution.
Parameterss
----------
self : Solution
an Solution object
args : dict
dict of selected entries (not used)
Returns
-------
field: ndarray
... |
from django.apps import AppConfig
class DriversConfig(AppConfig):
name = 'drivers'
|
'''
<풀이 메모>
탐색, O(logN), 오름차순 정렬이라 이분 탐색 문제인 것은 명확했다.
case study, 그림 그려서 어떻게 이분 탐색해야할지,
if 문 분기 3가지에 대해서 파악했다.
bisect로는 어떻게 풀어야할지 감이 안와서, 반복문으로 직접 구현했다.
'''
n = int(input())
data = list(map(int, input().split()))
length = len(data)
# debug
# print(n)
# print(data)
result = -1
# bisect
start = 0
end = length - 1
wh... |
# -*- coding: utf-8 -*-
"""
Python toolboxes for math functions, personalized plots and other things.
Notes
-----
Developed for Python 3.6.1
@author: d-bouvier (bouvierdamien@gmail.com)
"""
__author__ = "Damien Bouvier"
__maintainer__ = "Damien Bouvier"
__version__ = "0.3"
__author_email__ = 'bouvierdamien@gmail.com'... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^all/$', 'article.views.articles'),
url(r'^get/(?P<article_id>\d+)/$','article.views.article'),
url(r'^like/(?P<article_id>\d+)/$','article.views.like_article'),
url(r'^create/$','article.views.create'),
)
|
# Generated by Django 4.0.2 on 2022-04-02 06:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stats', '0006_alter_drone_admin_id_alter_drone_flight_and_more'),
]
operations = [
migrations.RenameField(
model_name='drone',
... |
import numpy as np
class Layer_Dense:
def __init__(
self,
n_inputs,
n_neurons,
weight_regulaizer_l1=0,
weight_regulaizer_l2=0,
bias_regularizer_l1=0,
bias_regularizer_l2=0,
):
self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)
sel... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2013 ARM Limited
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 ... |
import time
from datetime import datetime, timedelta
from pymysql import connect
from ..general import Log
class MySql:
@staticmethod
def execute_query(environment_configuration, query, wait_time=0):
Log.info('Sending "%s" query to the "%s" database' % (query, environment_configuration['database'])... |
from django.contrib.auth.decorators import user_passes_test
from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from google.appengine.ext import db
from projects.models i... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
# Third Party Stuff
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
fr... |
from datetime import datetime
class SingleResult:
"""
This class represents the result data of a single earthquake event. In the USGS REST API,
searching for a range (time/location) gives a collection of events, which is named as
**FeatureCollection** in GeoJSON standard. Searching with a particular e... |
import logging
from . import OrController
class TriggerController(OrController):
"""A controller for triggering actions
An interface for using trigger controller
is "compatible" with how we use OpenRAVE controllers
"""
def __init__(self, namespace, controller_name, simulated=False):
self... |
from typing import Union
import numpy as np
from pandas import DataFrame, Series
from radvel.kepler import rv_drive
from radvel.orbit import timetrans_to_timeperi
from scipy.stats import norm, truncnorm
from ephemere import constants as const
def get_tp_param(planet: Series, n_samples: int = 0) -> Union[np.ndarray,... |
from sqlalchemy import Column, Integer, String, Date, DateTime, ForeignKey, func, Text, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
import datetime
Base = declarative_base()
class Person(Base):
__tablename__ = 'Persons'
PersonID = Column(String(50... |
import discord
from discord.ext import commands
from cogs.utils.dataIO import fileIO, dataIO
from cogs.utils.chat_formatting import box
from cogs.utils import checks
from __main__ import send_cmd_help
import logging
import os
log = logging.getLogger("red.streetcred")
class StreetCred:
"""Original ... |
#!/usr/bin/env python
# coding:utf-8
# Author: Alejandro Nolla - z0mbiehunt3r
# Purpose: Example for detecting language using a stopwords based approach
# Created: 15/05/13
try:
from nltk import wordpunct_tokenize
from nltk.corpus import stopwords
except ImportError:
print('[!] You need to install nltk (ht... |
def solution(l, t):
# Your code here
c = 0
ra = 0
m = set(l)
s = 0
d = 0
if len(m) != len(l):
if sum(l) == t:
ra = ([0,len(l)-1])
else:
for i in l:
if ra == 0:
ra = rs(l[d:], t, l, d)
d += 1
... |
import re
from collections import Counter
with open("puzzles/day2/puzzle_input.txt") as f:
text = f.read()
data = [row.split(":") for row in text.split("\n")]
def checksum(check, password):
m = re.search("(\d+)-(\d+) ([a-z])", check)
lower, higher, char = m.groups()
count = Counter(password).get(ch... |
# Copyright © 2021 to 2022 IOTIC LABS LTD. info@iotics.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/Iotic-Labs/iotics-host-lib/blob/master/LICENSE
#
# Unless... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
'''
Accepted
'''
class Solution:
def invertTreeHelper(self, root):
if root is not None:
# the root of the cur... |
#!/bin/python3
import sys
'''
Function
greatestCommonDivisor(n1,n2)
Parameters
n1 => larger number
n2 => smaller number
'''
def greatestCommonDivisor(n1,n2):
if n2==0:
return n1
return greatestCommonDivisor(n2,n1%n2)
'''
Function
sumOfMultiples(a,n)
Par... |
import itertools
from cartographer.utils.version import get_default_version
class PostedDocument(object):
"""This is a reader for JSON API Documents"""
def __init__(self, json_data, version=None):
self.json_data = json_data
if version is None:
version = get_default_version()
... |
import random
print("\nGuess-the-number\n")
name = input("Enter your name:\n")
comp = random.randrange(100)
points = 10
com = 0
def score():
global guess,com,points
if guess> comp:
com = 1
points -= 1
elif guess < comp:
com= 0
points -= 1
def... |
import pytest # type: ignore
from helpers import mock_legacy_venv, run_pipx_cli
def test_upgrade(pipx_temp_env, capsys):
assert run_pipx_cli(["upgrade", "pycowsay"])
assert not run_pipx_cli(["install", "pycowsay"])
assert not run_pipx_cli(["upgrade", "pycowsay"])
@pytest.mark.parametrize("metadata_ver... |
"""
Copyright 2021 InfAI (CC SES)
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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://github.com/mozman/svgwrite/blob/master/examples/ltattrie/text_font_size.py
# pip install svgwrite
import svgwrite
# http://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#font-size-props
def create_svg(name):
svg_size ... |
balance = 235
annualInterestRate = 0.25
remainingBalance = balance
monthlyInterestRate = annualInterestRate/12.0
mmp = 0
totalPaid = 0
while remainingBalance > 0:
remainingBalance = balance
month = 0
mmp += 10
while month < 12 and remainingBalance > 0:
month += 1
remainingBalance = rema... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras import initializers
from keras.engine.topology import InputSpec
from keras import backend as K
from ..utils.caps_utils import mixed_shape
from .. import probability_transform... |
# more experimaentation with strings in Python
#use of formattter to input values into strings
x = "There are %d types of programmers." % 2
language = "python"
fakes = "dont"
y = "Those who know %s and those who %s." % (language, fakes)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilariou... |
#!/usr/bin/env python
"""Plot depth for a set of heterozygous calls relative to quality and allele ratio.
Used to help identify cutoff for filtering false positives by comparing
distribution to true positives.
Usage:
plot_depth_ratio.py <VCF file of het calls> '<Plot title>'
"""
import os
import sys
import vcf
imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.