content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
c.NbServer.base_url = '/paws-public/'
c.NbServer.bind_ip = '0.0.0.0'
c.NbServer.bind_port = 8000
c.NbServer.publisher_class = 'paws.PAWSPublisher'
c.NbServer.register_proxy = False
c.PAWSPublisher.base_path = '/data/project/paws/userhomes'
| c.NbServer.base_url = '/paws-public/'
c.NbServer.bind_ip = '0.0.0.0'
c.NbServer.bind_port = 8000
c.NbServer.publisher_class = 'paws.PAWSPublisher'
c.NbServer.register_proxy = False
c.PAWSPublisher.base_path = '/data/project/paws/userhomes' |
del_items(0x800A0E14)
SetType(0x800A0E14, "char StrDate[12]")
del_items(0x800A0E20)
SetType(0x800A0E20, "char StrTime[9]")
del_items(0x800A0E2C)
SetType(0x800A0E2C, "char *Words[118]")
del_items(0x800A1004)
SetType(0x800A1004, "struct MONTH_DAYS MonDays[12]")
| del_items(2148142612)
set_type(2148142612, 'char StrDate[12]')
del_items(2148142624)
set_type(2148142624, 'char StrTime[9]')
del_items(2148142636)
set_type(2148142636, 'char *Words[118]')
del_items(2148143108)
set_type(2148143108, 'struct MONTH_DAYS MonDays[12]') |
# Excel Column Number
# https://www.interviewbit.com/problems/excel-column-number/
#
# Given a column title as appears in an Excel sheet, return its corresponding
# column number.
#
# Example:
#
# A -> 1
#
# B -> 2
#
# C -> 3
#
# ...
#
# Z -> 26
#
# AA -> 27
#
# AB -> 28
#
# # # # # # # # # # # # # # # # # # # # # # # ... | class Solution:
def title_to_number(self, A):
res = 0
for char in A:
diff = ord(char) - ord('A') + 1
res = res * 26 + diff
return res
if __name__ == '__main__':
s = solution()
print(s.titleToNumber('AA'))
print(s.titleToNumber('A')) |
ENV = 'testing'
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_example_test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ERROR_404_HELP = False
| env = 'testing'
debug = True
testing = True
sqlalchemy_database_uri = 'postgresql://localhost/flask_example_test'
sqlalchemy_track_modifications = False
error_404_help = False |
"""
Implementation of a labeled property graph.
"""
# ===================================
# TODO: Number of relationships a node has
# TODO: Number of nodes that have a given relationship
# TODO: Number of nodes with a relationship
# TODO: Number of nodes with a label
# TODO: Traversals:
# - Depth first
# - Breadth-fi... | """
Implementation of a labeled property graph.
"""
class Node:
"""Node object that will have a relationship to other nodes."""
def __init__(self, name):
"""Initialized nodes contain properties and methods to view them."""
self.name = name
self.properties = {}
self.labels = []... |
#!/usr/bin/env python3
"""
Normal distriution
"""
class Normal:
"""
Normal distribution class
"""
def __init__(self, data=None, mean=0., stddev=1.):
if data is None:
self.mean = float(mean)
if stddev <= 0:
raise ValueError("stddev must be a positive valu... | """
Normal distriution
"""
class Normal:
"""
Normal distribution class
"""
def __init__(self, data=None, mean=0.0, stddev=1.0):
if data is None:
self.mean = float(mean)
if stddev <= 0:
raise value_error('stddev must be a positive value')
self... |
# Copyright 2018 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.
def ChangeToStr(change):
"""Turn a pinpoint change dict into a string id."""
change_id = ','.join(
'{repository}@{git_hash}'.format(**commit)
... | def change_to_str(change):
"""Turn a pinpoint change dict into a string id."""
change_id = ','.join(('{repository}@{git_hash}'.format(**commit) for commit in change['commits']))
if 'patch' in change:
change_id += '+' + change['patch']['url']
return change_id
def iter_test_output_isolates(job, o... |
# Copyright (C) 2018 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 writ... | load('//tools/build/rules:cc.bzl', 'cc_stripped_binary')
def _symbol_exports(name, exports):
native.genrule(name=name + '_syms', srcs=[exports], outs=[name + '_syms.S'], cmd='cat $< | awk \'{print ".global",$$0}\' > $@')
native.genrule(name=name + '_ldscript', srcs=[exports], outs=[name + '.ldscript'], cmd='('... |
class TwythonError(Exception):
@property
def msg(self) -> str: ...
class TwythonRateLimitError(TwythonError):
@property
def retry_after(self) -> int: ...
class TwythonAuthError(TwythonError): ... | class Twythonerror(Exception):
@property
def msg(self) -> str:
...
class Twythonratelimiterror(TwythonError):
@property
def retry_after(self) -> int:
...
class Twythonautherror(TwythonError):
... |
try:
sc = input("Enter your score between 0.0 and 1.0: ")
#sc = 0.85
score = float(sc)
except:
if score > 1.0 or score < 0.0:
print("Error, input should be between 0.0 and 1.0")
quit()
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif s... | try:
sc = input('Enter your score between 0.0 and 1.0: ')
score = float(sc)
except:
if score > 1.0 or score < 0.0:
print('Error, input should be between 0.0 and 1.0')
quit()
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif score < 0.6:
... |
passw = input()
def Is_Valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if ... | passw = input()
def is__valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if... |
# Algebraic-only implementation of two's complement in pure Python
#
# Written by: Patrizia Favaron
def raw_to_compl2(iRaw, iNumBits):
# Establish minimum and maximum possible raw values
iMinRaw = 0
iMaxRaw = 2**iNumBits - 1
# Clip value arithmetically
if iRaw < iMinRaw:
iRaw = iMinRaw
if iRaw > iMaxRaw:
... | def raw_to_compl2(iRaw, iNumBits):
i_min_raw = 0
i_max_raw = 2 ** iNumBits - 1
if iRaw < iMinRaw:
i_raw = iMinRaw
if iRaw > iMaxRaw:
i_raw = iMaxRaw
i_max_value = 2 ** (iNumBits - 1) - 1
if iRaw <= iMaxValue:
i_value = iRaw
else:
i_value = iRaw - 2 ** iNumBits... |
"""The base command."""
class Base(object):
"""A base command."""
def __init__(self, options, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.configuration = self.get_configuration(
options=options
)
def run(self):
raise NotImplementedErro... | """The base command."""
class Base(object):
"""A base command."""
def __init__(self, options, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.configuration = self.get_configuration(options=options)
def run(self):
raise not_implemented_error('You must implement... |
with open('./input.txt') as input:
hits = {}
for line in input:
(x1, y1), (x2, y2) = [ map(int, point.split(',')) for point in line.strip().split(' -> ')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in hits:
hits[... | with open('./input.txt') as input:
hits = {}
for line in input:
((x1, y1), (x2, y2)) = [map(int, point.split(',')) for point in line.strip().split(' -> ')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in hits:
hits[x1, y] +... |
def get_cat_vars_dict(df, categorical_cols, feature_names, target_name):
cat_vars_dict = {}
for col in [ col for col in categorical_cols if col != target_name]:
cat_vars_dict[feature_names.index(col)] = len(df[col].unique())
return cat_vars_dict | def get_cat_vars_dict(df, categorical_cols, feature_names, target_name):
cat_vars_dict = {}
for col in [col for col in categorical_cols if col != target_name]:
cat_vars_dict[feature_names.index(col)] = len(df[col].unique())
return cat_vars_dict |
class RestApi(object):
def __init__(self, app):
self.app = app
self.frefix_url = self.app.config.get("API_URL_PREFIX") or ""
self.views = []
def register_api(self, bleuprint, view, endpoint, url):
view_func = view.as_view(endpoint)
links = {}
# detail_url = "{}<... | class Restapi(object):
def __init__(self, app):
self.app = app
self.frefix_url = self.app.config.get('API_URL_PREFIX') or ''
self.views = []
def register_api(self, bleuprint, view, endpoint, url):
view_func = view.as_view(endpoint)
links = {}
links['self'] = url... |
class Kanji():
def __init__(self):
self.kanji = None
self.strokes = 0
self.pronunciation = None
self.definition = ""
self.kanji_shinjitai = None
self.strokes_shinjitai = 0
def __unicode__(self):
if self.kanji_shinjitai:
ks = " (%s)" % self.ka... | class Kanji:
def __init__(self):
self.kanji = None
self.strokes = 0
self.pronunciation = None
self.definition = ''
self.kanji_shinjitai = None
self.strokes_shinjitai = 0
def __unicode__(self):
if self.kanji_shinjitai:
ks = ' (%s)' % self.kanj... |
def p_error( p ):
print
print( "SYNTAX ERROR %s" % str( p ) )
print
raise Exception | def p_error(p):
print
print('SYNTAX ERROR %s' % str(p))
print
raise Exception |
numeros = []
par = []
impar = []
while True:
n = (int(input('Digite um numero: ')))
numeros.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0]
while resp not in 'SN':
resp = str(input('Tente novam... | numeros = []
par = []
impar = []
while True:
n = int(input('Digite um numero: '))
numeros.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0]
while resp not in 'SN':
resp = str(input('Tente novament... |
def get_label_dict(dataset_name):
label_dict = None
if dataset_name == 'PASCAL':
label_dict = {
'back_ground': 0,
'aeroplane': 1,
'bicycle': 2,
'bird': 3,
'boat': 4,
'bottle': 5,
'bus': 6,
'car': 7,
... | def get_label_dict(dataset_name):
label_dict = None
if dataset_name == 'PASCAL':
label_dict = {'back_ground': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4, 'bottle': 5, 'bus': 6, 'car': 7, 'cat': 8, 'chair': 9, 'cow': 10, 'diningtable': 11, 'dog': 12, 'horse': 13, 'motorbike': 14, 'person': 15,... |
class BatchRunner:
def __init__(self,model,iter_n):
self.model = model
self.iter_n = iter_n
def run_model(self,start,end):
"""
Runs the model
"""
for i in range(start,end):
self.model.reset(i)
self.model.episode()
print(... | class Batchrunner:
def __init__(self, model, iter_n):
self.model = model
self.iter_n = iter_n
def run_model(self, start, end):
"""
Runs the model
"""
for i in range(start, end):
self.model.reset(i)
self.model.episode()
p... |
start = 0
end = 1781
instance = 0
for i in range(150):
f = open(f"ec2files/ec2file{i}.py", "w")
f.write(f"from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()")
start = end + 1
end = start + 1781
instance += 1
f.close()... | start = 0
end = 1781
instance = 0
for i in range(150):
f = open(f'ec2files/ec2file{i}.py', 'w')
f.write(f'from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()')
start = end + 1
end = start + 1781
instance += 1
f.close() |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Utility scripts to abstract and assist with scripts run in the CI."""
| """Utility scripts to abstract and assist with scripts run in the CI.""" |
class Vector2D:
def __init__(self, v):
"""
:type v: List[List[int]]
"""
self.iter = itertools.chain.from_iterable(v)
self.cnt = sum(len(lst) for lst in v)
def next(self):
"""
:rtype: int
"""
self.cnt -= 1
return next(self... | class Vector2D:
def __init__(self, v):
"""
:type v: List[List[int]]
"""
self.iter = itertools.chain.from_iterable(v)
self.cnt = sum((len(lst) for lst in v))
def next(self):
"""
:rtype: int
"""
self.cnt -= 1
return next(self.iter)
... |
class Config(object):
SECRET_KEY = "aaaaaaa"
debug = False
class Production(Config):
debug = True
CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = "mysql://username:password@127.0.0.1/DBname"
migration_directory = "migrations"
| class Config(object):
secret_key = 'aaaaaaa'
debug = False
class Production(Config):
debug = True
csrf_enabled = False
sqlalchemy_database_uri = 'mysql://username:password@127.0.0.1/DBname'
migration_directory = 'migrations' |
# This program creates an object of the pet class
# and asks the user to enter the name, type, and age of pet.
# The program retrieves the pet's name, type, and age and
# displays the data.
class Pet:
def __init__(self, name, animal_type, age):
# Gets the pets name
self.__name = name
... | class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
... |
#
# PySNMP MIB module SCSPATMARP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCSPATMARP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:01:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ... |
# coding=utf-8
__author__ = 'lxn3032'
class ControllerBase(object):
def __init__(self, period, ValueType=float):
self.ValueType = ValueType
self.T = period
self.error_1 = ValueType(0)
self.error_2 = ValueType(0)
self.current_value = ValueType(0)
self.target_value = ... | __author__ = 'lxn3032'
class Controllerbase(object):
def __init__(self, period, ValueType=float):
self.ValueType = ValueType
self.T = period
self.error_1 = value_type(0)
self.error_2 = value_type(0)
self.current_value = value_type(0)
self.target_value = value_type(0... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 20,
"id": "informative-england",
"metadata": {},
"outputs": [],
"source": [
"### This is the interworkings and mathematics behind the equity models\n",
"\n",
"### Gordon (Constant) Growth Model module ###\n",
"def Gordongrowth(d... | {'cells': [{'cell_type': 'code', 'execution_count': 20, 'id': 'informative-england', 'metadata': {}, 'outputs': [], 'source': ['### This is the interworkings and mathematics behind the equity models\n', '\n', '### Gordon (Constant) Growth Model module ###\n', 'def Gordongrowth(dividend, costofequity, growthrate):\n', '... |
# -*- coding: utf-8 -*-
"""Dot.notation attributes for dictionaries.
Includes recursive DotDict behavior for nested dictionaries.
"""
class DotDict(dict):
"""DotDict creates an interface for using dictionaries as attr containers.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, *... | """Dot.notation attributes for dictionaries.
Includes recursive DotDict behavior for nested dictionaries.
"""
class Dotdict(dict):
"""DotDict creates an interface for using dictionaries as attr containers.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for (key... |
class SYCSException(Exception):
pass
class CredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('username or password not provided.')
class InvalidCredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('wrong u... | class Sycsexception(Exception):
pass
class Credentialsexception(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('username or password not provided.')
class Invalidcredentialsexception(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('wrong u... |
def solution(A, B, s):
A.sort()
B.sort()
i = len(A) - 1
j = len(B) - 1
while 0 <= j <= len(B) - 1 and i:
pass
| def solution(A, B, s):
A.sort()
B.sort()
i = len(A) - 1
j = len(B) - 1
while 0 <= j <= len(B) - 1 and i:
pass |
a = int(input())
for i in range(1, a+1):
if a % i == 0:
print(i)
| a = int(input())
for i in range(1, a + 1):
if a % i == 0:
print(i) |
# 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... | class Relorientation(object):
"""
Const Class
These values define the reference position of relative orientations.
**since**
LibreOffice 7.0
See Also:
`API RelOrientation <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1text_1_1RelOrientation.html>... |
class When_we_have_a_test:
@classmethod
def examples(cls):
yield 1
yield 3
def when_things_happen(self):
pass
def it_should_do_this_test(self, arg):
assert arg < 3
| class When_We_Have_A_Test:
@classmethod
def examples(cls):
yield 1
yield 3
def when_things_happen(self):
pass
def it_should_do_this_test(self, arg):
assert arg < 3 |
# Copyright 2021 Adobe. All rights reserved.
# This file is licensed to you 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 ... | """Error and log messages"""
decisioning_engine_not_ready = 'Unable to fulfill request; decisioning engine not ready.'
def attribute_not_exist(key_name, mbox_name):
"""Mbox attribute does not exist error string"""
return "Attribute '{}' does not exist for mbox '{}'".format(key_name, mbox_name)
def property_to... |
class Solution:
def validTree(self, n: int, edges: list[list[int]]) -> bool:
if not n:
return True
adj = {i: [] for i in range(n)}
for n1, n2 in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i, prev):
if ... | class Solution:
def valid_tree(self, n: int, edges: list[list[int]]) -> bool:
if not n:
return True
adj = {i: [] for i in range(n)}
for (n1, n2) in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i, prev):
i... |
def get_accounts_for_path(client, path):
ou = client.convert_path_to_ou(path)
response = client.list_children_nested(ParentId=ou, ChildType="ACCOUNT")
return ",".join([r.get("Id") for r in response])
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apa... | def get_accounts_for_path(client, path):
ou = client.convert_path_to_ou(path)
response = client.list_children_nested(ParentId=ou, ChildType='ACCOUNT')
return ','.join([r.get('Id') for r in response])
macros = {'get_accounts_for_path': get_accounts_for_path} |
# Busiest Time in The Mall
def find_busiest_period(data):
peak_time = peak_vis = cur_vis = i = 0
while i < len(data):
time, v, enter = data[i]
cur_vis += v if enter else -v
if i == len(data)-1 or time != data[i+1][0]:
if cur_vis > peak_vis:
peak_vis = cur_vis
peak_time = ti... | def find_busiest_period(data):
peak_time = peak_vis = cur_vis = i = 0
while i < len(data):
(time, v, enter) = data[i]
cur_vis += v if enter else -v
if i == len(data) - 1 or time != data[i + 1][0]:
if cur_vis > peak_vis:
peak_vis = cur_vis
peak_... |
def test__delete__401_when_no_auth_headers(client):
r = client.delete('/themes/1')
assert r.status_code == 401, r.get_json()
def test__delete__401_when_incorrect_auth(client, faker):
r = client.delete('/themes/1', headers={
'Authentication': 'some_incorrect_token'})
assert r.status_code == 4... | def test__delete__401_when_no_auth_headers(client):
r = client.delete('/themes/1')
assert r.status_code == 401, r.get_json()
def test__delete__401_when_incorrect_auth(client, faker):
r = client.delete('/themes/1', headers={'Authentication': 'some_incorrect_token'})
assert r.status_code == 401, r.get_js... |
# Python 3.8.3
with open("input.txt", "r") as f:
puzzle_input = [int(i) for i in f.read().split()]
def fuel_needed(mass):
fuel = mass // 3 - 2
return fuel + fuel_needed(fuel) if fuel > 0 else 0
sum = 0
for mass in puzzle_input:
sum += fuel_needed(mass)
print(sum)
| with open('input.txt', 'r') as f:
puzzle_input = [int(i) for i in f.read().split()]
def fuel_needed(mass):
fuel = mass // 3 - 2
return fuel + fuel_needed(fuel) if fuel > 0 else 0
sum = 0
for mass in puzzle_input:
sum += fuel_needed(mass)
print(sum) |
"""defines errors for canvasplus."""
"""Luke-zhang-04
CanvasPlus v1.3.0 (https://github.com/Luke-zhang-04/CanvasPlus)
Copyright (C) 2020 Luke Zhang
Licensed under the MIT License
"""
class Error(Exception):
"""Base class for other exceptions."""
pass
class InvalidUnitError(Error):
"""Raised when unit i... | """defines errors for canvasplus."""
'Luke-zhang-04\nCanvasPlus v1.3.0 (https://github.com/Luke-zhang-04/CanvasPlus)\nCopyright (C) 2020 Luke Zhang\nLicensed under the MIT License\n'
class Error(Exception):
"""Base class for other exceptions."""
pass
class Invaliduniterror(Error):
"""Raised when unit is n... |
# Date: 2020/11/12
# Author: Luis Marquez
# Description:
# This is a simple program in which the binary search will be implemented to calculate a square root result
#
#BINARY_SEARCH(): This function realize a binary search
def binary_search():
#objective: The number in which the root will be cal... | def binary_search():
objective = int(input(f'\nType a number: '))
print(f'\n')
epsilon = 0.01
low = 0.0
high = max(1.0, objective)
answer = (high + low) / 2
while abs(answer ** 2 - objective) >= epsilon:
print(f'Low={round(low, 2)} \t high={round(high, 2)} \t Answer={round(answer, 2)... |
class Config(object):
DESCRIPTION = 'Mock generator for c code'
VERSION = '0.5'
AUTHOR = 'Freddy Hurkmans'
LICENSE = 'BSD 3-Clause'
# set defaults for parameters
verbose = False
max_nr_function_calls = '25'
charstar_is_input_string = False
UNITY_INCLUDE = '#include "unity.h"'
#... | class Config(object):
description = 'Mock generator for c code'
version = '0.5'
author = 'Freddy Hurkmans'
license = 'BSD 3-Clause'
verbose = False
max_nr_function_calls = '25'
charstar_is_input_string = False
unity_include = '#include "unity.h"'
custom_includes = []
ctype_to_uni... |
left_eye_connection = [
# Left eye.
(263, 249),
(249, 390),
(390, 373),
(373, 374),
(374, 380),
(380, 381),
(381, 382),
(382, 362),
(263, 466),
(466, 388),
(388, 387),
(387, 386),
(386, 385),
(385, 384),
(384, 398),
(398, 362)
]
left_eyebrow_connection... | left_eye_connection = [(263, 249), (249, 390), (390, 373), (373, 374), (374, 380), (380, 381), (381, 382), (382, 362), (263, 466), (466, 388), (388, 387), (387, 386), (386, 385), (385, 384), (384, 398), (398, 362)]
left_eyebrow_connection = [(276, 283), (283, 282), (282, 295), (295, 285), (300, 293), (293, 334), (334, ... |
# --------------------------------------------------------
# GA3C for Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
class Config(object):
#########################################################################
# Game configuration
... | class Config(object):
atari_game = 'PongDeterministic-v0'
play_mode = False
train_models = True
load_checkpoint = False
load_episode = 32000
agents = 32
predictors = 2
trainers = 2
device = 'gpu:0'
dynamic_settings = True
dynamic_settings_step_wait = 20
dynamic_settings_i... |
INPUT_BUCKET = 'input-image-files'
OUTPUT_BUCKET = 'output-image-files'
INPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue'
OUTPUT_QUEUE = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue'
| input_bucket = 'input-image-files'
output_bucket = 'output-image-files'
input_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Request-Queue'
output_queue = 'https://sqs.us-east-1.amazonaws.com/378107157540/Response-Queue' |
f='11'
for i in range(5):
c=1
s=''
for j in range(len(f)-1):
if f[j]==f[j+1]:
c+=1
else:
s=(str(c)+(f[j]))
s=str(c)+(f[j])
f=str(s)
print(f)
| f = '11'
for i in range(5):
c = 1
s = ''
for j in range(len(f) - 1):
if f[j] == f[j + 1]:
c += 1
else:
s = str(c) + f[j]
s = str(c) + f[j]
f = str(s)
print(f) |
"""API routes"""
ROUTE_CVE_ANNOUNCEMENTS = "/api/v3/cve_announcements"
ROUTE_GROUPS = "/api/v3/groups"
ROUTE_HOSTS = "/api/v3/hosts"
ROUTE_NODES = "/api/v3/nodes"
ROUTE_PING = "/api/v3/ping"
ROUTE_REMOTE_ACCESSES = "/api/v3/remote_accesses"
ROUTE_SECURITY_ISSUES = "/api/v3/security_issues"
ROUTE_SERVERS = "/api/v3/ser... | """API routes"""
route_cve_announcements = '/api/v3/cve_announcements'
route_groups = '/api/v3/groups'
route_hosts = '/api/v3/hosts'
route_nodes = '/api/v3/nodes'
route_ping = '/api/v3/ping'
route_remote_accesses = '/api/v3/remote_accesses'
route_security_issues = '/api/v3/security_issues'
route_servers = '/api/v3/serv... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class ComposeModeException(Exception):
""" Base exception for compose-mode """
class ComposeModeYmlNotFound(ComposeModeException):
""" Exception raised when no configuration file was found """
def main():
pass
if __name__ == '__main__':
main()
| class Composemodeexception(Exception):
""" Base exception for compose-mode """
class Composemodeymlnotfound(ComposeModeException):
""" Exception raised when no configuration file was found """
def main():
pass
if __name__ == '__main__':
main() |
query = """
type Query {
photo(photoId: ID!): Photo!
photos(page: Int, profileId: ID, photosPerPage: Int): PhotoPagination!
profile(profileId: ID!): Profile!
profiles(page: Int, perPage: Int): ProfilePagination!
identifyFace(faceId: ID!): [IdentifyFaceResult]!
task(taskCollectionId: ID!): Task
... | query = '\ntype Query {\n photo(photoId: ID!): Photo!\n photos(page: Int, profileId: ID, photosPerPage: Int): PhotoPagination!\n profile(profileId: ID!): Profile!\n profiles(page: Int, perPage: Int): ProfilePagination!\n identifyFace(faceId: ID!): [IdentifyFaceResult]!\n task(taskCollectionId: ID!): T... |
a=input("ENTER THE NUMBER\n")
if a[0]==a[1] or a[0]==a[2] or a[0]==a[3] or a[0]==a[4] or a[1]==a[2] or a[1]==a[3] or a[1]==a[4] or a[2]==a[3] or a[2]==a[4]:
print("THE ENTERED NUMBER IS NOT A UNIQUE NUMBER")
else:
print(a,"IS AN UNIQUE NUMBER")
| a = input('ENTER THE NUMBER\n')
if a[0] == a[1] or a[0] == a[2] or a[0] == a[3] or (a[0] == a[4]) or (a[1] == a[2]) or (a[1] == a[3]) or (a[1] == a[4]) or (a[2] == a[3]) or (a[2] == a[4]):
print('THE ENTERED NUMBER IS NOT A UNIQUE NUMBER')
else:
print(a, 'IS AN UNIQUE NUMBER') |
def isPrime(n: int)->bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
A no. is prime if it is divisible only by 1 & itself.
1- is neither Prime nor Composite
- check for n being a even number i.e divisble by 2
- check for n being divi... | def is_prime(n: int) -> bool:
"""
Give an Integer 'n'. Check if 'n' is Prime or Not
:param n:
:return: bool - True or False
A no. is prime if it is divisible only by 1 & itself.
1- is neither Prime nor Composite
- check for n being a even number i.e divisble by 2
- check for n being div... |
# The goal of this exercise is to get hands-on experience working with
# list comprehensions, and other comprehensions. Write a complementary
# function to each of the below, which accomplishes the same logic in
# a one-liner (using list/set/dict comprehensions).
# Exercise 1
# Adds 5 to each element
def add_five(nu... | def add_five(numbers):
out = []
for num in numbers:
out.append(num + 5)
return out
def add_five_one_liner(numbers):
pass
def drop_small(numbers):
out = []
for num in numbers:
if not num < 4:
out.append(num)
return out
def drop_small_one_liner(numbers):
pass... |
n = len(x)
if n % 2:
median_ = sorted(x)[round(0.5*(n-1))]
else:
x_ord, index = sorted(x), round(0.5 * n)
median_ = 0.5 * (x_ord[index-1] + x_ord[index])
median_ | n = len(x)
if n % 2:
median_ = sorted(x)[round(0.5 * (n - 1))]
else:
(x_ord, index) = (sorted(x), round(0.5 * n))
median_ = 0.5 * (x_ord[index - 1] + x_ord[index])
median_ |
def agreeanswer():
i01.disableRobotRandom(30)
i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.90)
i01.setTorsoSpeed(1.0, 1.0, 1.0)... | def agreeanswer():
i01.disableRobotRandom(30)
i01.setHandSpeed('left', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed('right', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('left', 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed('right', 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 0.9)
i01.setTorsoSpeed(1... |
# GENERAL TREE STRUCTURE SETUP
# Santiago Garcia Arango, July 2020
"""
The goal is to create a tree structure to organize better the information.
The final result should be able to create a tree and print it like this:
(from the "root", be able to go deep in a tree structure)
UNIVERITY (level 0)
|__MANAGEMENT (lev... | """
The goal is to create a tree structure to organize better the information.
The final result should be able to create a tree and print it like this:
(from the "root", be able to go deep in a tree structure)
UNIVERITY (level 0)
|__MANAGEMENT (level 1)
| |__BUSSINESS (level 2)
| |__ECONOMICS
| |... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1node = l1
l2node = l2
prenode = None
r... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l1node = l1
l2node = l2
prenode = None
... |
def linear_search(arr, value):
"""
My Python implementation of linear search
Searches an array and returns either the index of the value (if found) or -1 (if not found)
Time complexity: O(n)
Space complexity: O(1)
"""
for i in range(len(arr)): # O(n)
if arr[i] == val... | def linear_search(arr, value):
"""
My Python implementation of linear search
Searches an array and returns either the index of the value (if found) or -1 (if not found)
Time complexity: O(n)
Space complexity: O(1)
"""
for i in range(len(arr)):
if arr[i] == value:
retur... |
# Filename: route.py
"""
Transit Route Module
"""
# Standard libraries
class Route(object):
"""
A representation of a route. Every route has:
* name - string
* id - unique identification (string) for the route for the agency
* stops - list of stops relevant for the route
"""
def __init__... | """
Transit Route Module
"""
class Route(object):
"""
A representation of a route. Every route has:
* name - string
* id - unique identification (string) for the route for the agency
* stops - list of stops relevant for the route
"""
def __init__(self, name, uid):
"""
Const... |
database_path = "{projects}/brewmaster/server/data/"
heater_port = 12
port_number = 5000
stirrer_port = 13
temp_sensor_path = "/sys/bus/w1/devices/{your_sensor_id}/w1_slave"
use_fake = True
| database_path = '{projects}/brewmaster/server/data/'
heater_port = 12
port_number = 5000
stirrer_port = 13
temp_sensor_path = '/sys/bus/w1/devices/{your_sensor_id}/w1_slave'
use_fake = True |
# def favcolors(mameet,qj,mustafa):
# print(mameet, qj,mustafa)
# favcolors(qj='green',mameet='black',mustafa='blue')
# # ,,
def favcolors(**kwargs):
print(kwargs)
for key,val in kwargs.items():
print('Favourite color of',key,'is',val)
# favcolors(qj='green',mameet='black',mustafa='blue',fatima='... | def favcolors(**kwargs):
print(kwargs)
for (key, val) in kwargs.items():
print('Favourite color of', key, 'is', val)
def favcolors2(num1, *args, qj, **kwargs):
print('num1:', num1)
print('args:', args)
print('def arguments:', qj)
print('kwargs:', kwargs)
favcolors2(10, 20, 'aaaa', qj='g... |
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
# Formatting for date objects.
DATE_FORMAT = 'N j, Y'
# Formatting for time objects.
TIME_FORMAT = 'P'
# Formatti... | date_format = 'N j, Y'
time_format = 'P'
datetime_format = 'N j, Y, P'
year_month_format = 'F Y'
month_day_format = 'F j'
short_date_format = 'm/d/Y'
short_datetime_format = 'm/d/Y P'
first_day_of_week = 0
date_input_formats = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d... |
ENTRY_POINT = 'minSubArraySum'
#[PROMPT]
def minSubArraySum(nums):
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
minSubArraySum([-1, -2, -3]) == -6
"""
#[SOLUTION]
max_sum = 0
s = 0
f... | entry_point = 'minSubArraySum'
def min_sub_array_sum(nums):
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
minSubArraySum([-1, -2, -3]) == -6
"""
max_sum = 0
s = 0
for num in nums:
... |
number_of_rooms = int(input())
free_chairs = 0
insufficiency = False
for i in range(1, number_of_rooms + 1):
list_of_chairs_and_people = input().split()
chairs = len(list_of_chairs_and_people[0])
needed_ones = int(list_of_chairs_and_people[1])
if chairs >= needed_ones:
free_chairs += cha... | number_of_rooms = int(input())
free_chairs = 0
insufficiency = False
for i in range(1, number_of_rooms + 1):
list_of_chairs_and_people = input().split()
chairs = len(list_of_chairs_and_people[0])
needed_ones = int(list_of_chairs_and_people[1])
if chairs >= needed_ones:
free_chairs += chairs - ne... |
def funcion():
return 5
def generador():
yield 1,2,3,4,5,6,7,8,9
print(generador())
print(generador())
print(generador())
| def funcion():
return 5
def generador():
yield (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(generador())
print(generador())
print(generador()) |
# vim: set ts=8 sts=4 sw=4 tw=99 et:
#
# This file is part of AMBuild.
#
# AMBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | class Basegenerator(object):
def __init__(self, cm):
self.cm = cm
@property
def backend(self):
raise exception('Must be implemented!')
def add_symlink(self, context, source, output_path):
raise exception('Must be implemented!')
def add_folder(self, context, folder):
... |
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | def one_level_function():
return 0
def multiline_args_tuple(a, b, c):
return 0
def nested_if_statements():
if True:
if True:
return 0
def nested_for_statements():
for x in range(1):
for y in range(1):
return 0
def nested_with_statements():
with open(__file... |
# -*- coding: utf-8 -*-
class InternalCompilerError(Exception):
"""
An internal compiler error is unrecoverable and fatal.
It should never happen for any user input.
"""
def __init__(self, message=''):
self.message = message
pass
def __str__(self):
return self.message... | class Internalcompilererror(Exception):
"""
An internal compiler error is unrecoverable and fatal.
It should never happen for any user input.
"""
def __init__(self, message=''):
self.message = message
pass
def __str__(self):
return self.message
def internal_assert(a, b... |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.authentication
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Authentication(object):
"""Implementation of the 'Authentication' model.
TODO: type model description here.
Attri... | """
idfy_rest_client.models.authentication
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Authentication(object):
"""Implementation of the 'Authentication' model.
TODO: type model description here.
Attributes:
auth_before_sign (bool): If... |
"""
This is the PyTurbSim 'stress models' package.
For more information or to use this package import the stressModels.api
package, e.g.:
>>> import pyts.stressModels.api as rm
**Currently the stress package does not function properly, unless no coherence is used. Fixing this is near the top of the list of things t... | """
This is the PyTurbSim 'stress models' package.
For more information or to use this package import the stressModels.api
package, e.g.:
>>> import pyts.stressModels.api as rm
**Currently the stress package does not function properly, unless no coherence is used. Fixing this is near the top of the list of things t... |
class BusInPOZ:
def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in):
self.intersection_of_interest = intersection
self.bus_id = check_in_bus_info.idVeh
self.check_in_time = check_in_time
self.check_in_phase = chec... | class Businpoz:
def __init__(self, intersection, check_in_bus_info, check_in_phase, check_in_phasetime, check_in_time, last_check_in):
self.intersection_of_interest = intersection
self.bus_id = check_in_bus_info.idVeh
self.check_in_time = check_in_time
self.check_in_phase = check_in... |
# -*- coding: utf-8 -*-
__version__ = '0.5.0.dev0'
PROJECT_NAME = "gx-tool-db"
PROJECT_OWNER = PROJECT_USERAME = "galaxyproject"
PROJECT_AUTHOR = 'Galaxy Project and Community'
PROJECT_EMAIL = 'jmchilton@gmail.com'
PROJECT_URL = "https://github.com/galaxyproject/gx-tool-db"
RAW_CONTENT_URL = "https://raw.github.com... | __version__ = '0.5.0.dev0'
project_name = 'gx-tool-db'
project_owner = project_userame = 'galaxyproject'
project_author = 'Galaxy Project and Community'
project_email = 'jmchilton@gmail.com'
project_url = 'https://github.com/galaxyproject/gx-tool-db'
raw_content_url = 'https://raw.github.com/%s/%s/main/' % (PROJECT_USE... |
"""
https://leetcode.com/problems/design-hashset/
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a ... | """
https://leetcode.com/problems/design-hashset/
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a ... |
#! Line breaks in 'print' function.
print(
"""1 line
2 line
3 line"""
)
print(
'1 line\n'
'2 line\n'
'3 line')
# Separator parameter.
print(
'1 line\n',
'2 line\n',
'3 line',
sep='______\n')
# End paramerer.
print('hello', 'kato', sep=' ', end="!")
| print('1 line\n 2 line\n 3 line')
print('1 line\n2 line\n3 line')
print('1 line\n', '2 line\n', '3 line', sep='______\n')
print('hello', 'kato', sep=' ', end='!') |
class Vertex:
def __init__(self, x=None, y=None):
self.pos = [x, y]
self.x = x
self.y = y
self.data = None
def __str__(self):
return f"{self.pos}"
def __repr__(self):
return f"{self.pos}"
def __hash__(self):
return hash(''.join([str(x) for x... | class Vertex:
def __init__(self, x=None, y=None):
self.pos = [x, y]
self.x = x
self.y = y
self.data = None
def __str__(self):
return f'{self.pos}'
def __repr__(self):
return f'{self.pos}'
def __hash__(self):
return hash(''.join([str(x) for x in... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.dfs... | class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return max(self.dfs(root))
def dfs(self, root):
if not root:
return (0, 0)
(left_skip_level, left_include_level) = self.dfs(root.left)
(right_skip_l... |
#$Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/xmlBase/xmlBaseLib.py,v 1.4 2009/01/23 00:21:04 ecephas Exp $
def generate(env, **kw):
if not kw.get('depsOnly',0):
env.Tool('addLibrary', library = ['xmlBase'], package = 'xmlBase')
if env['PLATFORM']=='win32' and env.get('CONTAINERNAME','')... | def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library=['xmlBase'], package='xmlBase')
if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease':
env.Tool('findPkgPath', package='xmlBase')
env.Tool('facilitiesLib')
env.Tool('a... |
# Python program to print the first non-repeating character
NO_OF_CHARS = 256
# Returns an array of size 256 containg count
# of characters in the passed char array
def getCharCountArray(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
# The function returns in... | no_of_chars = 256
def get_char_count_array(string):
count = [0] * NO_OF_CHARS
for i in string:
count[ord(i)] += 1
return count
def first_non_repeating(string):
count = get_char_count_array(string)
index = -1
k = 0
for i in string:
if count[ord(i)] == 1:
index = ... |
class Solution:
def reverse(self, x: int) -> int:
if x < 0 and x >= (-2**31):
# x_str = str(x)
# x_str_rev = '-'
# access from the 2nd last element excluding "-" sign
x_str_rev = '-' + str(x)[len(str(x)):0:-1]
if int(x_str_rev) < (-2**31):
... | class Solution:
def reverse(self, x: int) -> int:
if x < 0 and x >= -2 ** 31:
x_str_rev = '-' + str(x)[len(str(x)):0:-1]
if int(x_str_rev) < -2 ** 31:
return_value = 0
else:
return_value = int(x_str_rev)
elif x >= 0 and x <= 2 ** 3... |
# This problem was asked by Palantir.
# Given a number represented by a list of digits, find the next greater permutation of a
# number, in terms of lexicographic ordering. If there is not greater permutation possible,
# return the permutation with the lowest value/ordering.
# For example, the list [1,2,3] should retur... | def next_perm(arr):
n = len(arr)
i = n - 1
while i > 0:
(arr[i], arr[i - 1]) = (arr[i - 1], arr[i])
if arr[i - 1] > arr[i]:
return arr
i -= 1
return sorted(arr)
print(next_perm([1, 4, 3, 2])) |
def length_of_longest_substring(s):
dici = {}
max_s_rep = repeticao_na_fila = 0
for i, value in enumerate(s):
if value in dici:
num_repetidos = dici[value] + 1
if num_repetidos > repeticao_na_fila:
repeticao_na_fila = num_repetidos
num_repeticoes = i +... | def length_of_longest_substring(s):
dici = {}
max_s_rep = repeticao_na_fila = 0
for (i, value) in enumerate(s):
if value in dici:
num_repetidos = dici[value] + 1
if num_repetidos > repeticao_na_fila:
repeticao_na_fila = num_repetidos
num_repeticoes = i... |
#!/usr/bin/python3
f = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world.s", "r")
g = open("/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c", "w")
for data in f:
data = data.strip("\n")
if (data == "") or ("//" in data):
continue
#New text to print to terminal
if (".ascii" in data):
print("__as... | f = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world.s', 'r')
g = open('/home/bccue/Cores-SweRV/testbench/asm/hello_world_c.c', 'w')
for data in f:
data = data.strip('\n')
if data == '' or '//' in data:
continue
if '.ascii' in data:
print('__asm (".ascii \\"===========================... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
default_app_config = 'mosquitto.apps.Config'
| default_app_config = 'mosquitto.apps.Config' |
#Loading one line from file and starting a dictionary
for line in open('rosalind_ini6.txt', 'r').readlines():
contents = line.split()
dictionary = dict()
#Checking if a word from line is in dictionary, then sum the occurrences
for i in range(0, len(contents), 1):
if (contents[i] not in dictionary):
... | for line in open('rosalind_ini6.txt', 'r').readlines():
contents = line.split()
dictionary = dict()
for i in range(0, len(contents), 1):
if contents[i] not in dictionary:
dictionary[contents[i]] = 1
else:
dictionary[contents[i]] += 1
for (key, value) in dictionary.items():
print(key, val... |
# Python file
# Save this with extension .py
# Made By Arnav Naik
# A beginner's guide to Python
print("Welcome To The Trivia!!")
# Scoring
total_q = 4
print("Total Questions: ", total_q)
def question_1():
global score
score = int(0)
# Question1
question1 = str(input("1. What's the bes... | print('Welcome To The Trivia!!')
total_q = 4
print('Total Questions: ', total_q)
def question_1():
global score
score = int(0)
question1 = str(input("1. What's the best programming language? "))
ans1u = 'python'
ans1 = 'Python'
if question1 == ans1u or question1 == ans1:
question_1()
print('Correct!!')... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head: return None
cur = head
st... | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return None
cur = hea... |
class Solution:
def toLowerCase(self, str: str) -> str:
res = []
for i in range(len(str)):
if 65 <= ord(str[i]) <= 92:
res.append(chr(ord(str[i]) + 32))
else:
res.append(str[i])
return "".join(res)
def toLowerCase2(self, str: str) ... | class Solution:
def to_lower_case(self, str: str) -> str:
res = []
for i in range(len(str)):
if 65 <= ord(str[i]) <= 92:
res.append(chr(ord(str[i]) + 32))
else:
res.append(str[i])
return ''.join(res)
def to_lower_case2(self, str: ... |
class NotInitedException(Exception):
"""Deprecated! was used to state that the database in the general config was not inited yet"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class MissingUserException(Exception):
"""The requested User could not be found"""
... | class Notinitedexception(Exception):
"""Deprecated! was used to state that the database in the general config was not inited yet"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class Missinguserexception(Exception):
"""The requested User could not be found"""
... |
# --------------
# Code starts here
# Create the lists
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio' ]
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
# Concatenate both the strings
new_class = (class_1 + class_2)
print (new_class)
# Append the list
new_class.append('Peter... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
mathematics = {'Geoffrey Hinton... |
#!/usr/bin/env python3
# Created by Tiago Minuzzi, 2020.
# Files
in_fasta = "teste.fasta"
in_ids = "ids.txt"
out_fasta = "res_fas.fa"
# Empty dictionary to store sequences
fas_dict = {}
# Read reference fasta file
with open(in_fasta, "r") as fasta:
fasta=fasta.readlines()
for linha in fasta:
linha = linha.strip()
... | in_fasta = 'teste.fasta'
in_ids = 'ids.txt'
out_fasta = 'res_fas.fa'
fas_dict = {}
with open(in_fasta, 'r') as fasta:
fasta = fasta.readlines()
for linha in fasta:
linha = linha.strip()
if linha.startswith('>'):
kl = linha[1:]
fas_dict[kl] = ''
else:
f... |
#strings = """ We love our mom she helps us is in varius ways.
#She makes food for us.
#She takes us to school.
#She always takes care of us.
#""" #multiline strings
#print (strings)
sentence1 = 'Tamim is a great player'
sentence2 = "\"Bangldesh\" is a developing country"
print (sentence1)
print (sentence2)
length ... | sentence1 = 'Tamim is a great player'
sentence2 = '"Bangldesh" is a developing country'
print(sentence1)
print(sentence2)
length = len(sentence1)
sentence1 = 'Tamim is a great player'
sentence2 = '"Bangldesh" is a developing country'
length = len(sentence1)
print(length)
pizza = 'We love pizza'
pizza_slice = pizza[6:]
... |
class State:
def __init__(self, goal, task, visual, ):
self.goal = None
self.task = None
self.visual = None
self.features = None | class State:
def __init__(self, goal, task, visual):
self.goal = None
self.task = None
self.visual = None
self.features = None |
for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='')
| for i in range(1, 10):
print(i, end=', ')
print()
for i in range(0, 10, 2):
print(i, ' ', end='')
print()
for i in range(10, 1, -2):
print(i, ' ', end='') |
class BatchCancelled(Exception):
"""
Error used when a batch has been cancelled.
"""
pass
| class Batchcancelled(Exception):
"""
Error used when a batch has been cancelled.
"""
pass |
#!/usr/bin/env python
"""iexport.py: export the unallocated spaces."""
class Run:
"""Keeps track of a single run"""
def __init__(self,start,len):
self.start = start
self.len = len
self.end = start+len-1
def __str__(self):
return "Run<%d--%d> (len %d)" % (self.start,self.end... | """iexport.py: export the unallocated spaces."""
class Run:
"""Keeps track of a single run"""
def __init__(self, start, len):
self.start = start
self.len = len
self.end = start + len - 1
def __str__(self):
return 'Run<%d--%d> (len %d)' % (self.start, self.end, self.len)
... |
"""
Union find algorithm
"""
def get_parent(arr, i):
if arr[i] == i:
return i
arr[i] = get_parent(arr, arr[i])
return arr[i]
def union_parent(arr, a, b):
a = get_parent(arr, a)
b = get_parent(arr, b)
if a < b:
arr[b] = a
else:
arr[a] = b
def find_parent(arr, a, ... | """
Union find algorithm
"""
def get_parent(arr, i):
if arr[i] == i:
return i
arr[i] = get_parent(arr, arr[i])
return arr[i]
def union_parent(arr, a, b):
a = get_parent(arr, a)
b = get_parent(arr, b)
if a < b:
arr[b] = a
else:
arr[a] = b
def find_parent(arr, a, b):... |
# Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko
# Copyright 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: AGPL-3.0-or-later
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[0;33m'
FAIL = '\033[91m'
ENDC = '\033[0m'
CLRSCR = ... | header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[0;33m'
fail = '\x1b[91m'
endc = '\x1b[0m'
clrscr = '\x1b[1;1H'
realclrscr = '\x1b[2J'
bold = '\x1b[1m'
flush_line = '\r\x1b[K'
def move_cursor_up(num):
return '\x1b[' + str(num) + 'A'
def move_cursor_down(num):
return '\x1b[' + str(n... |
# Longest Increasing Subsequence
# We have discussed Overlapping Subproblems and Optimal Substructure properties.
# Let us discuss Longest Increasing Subsequence (LIS) problem as an example
# problem that can be solved using Dynamic Programming.
# The Longest Increasing Subsequence (LIS) problem is to find the length... | def longest_increasing_sequence(list1):
n = len(list1)
list2 = [1 for i in range(n)]
for i in range(1, n):
for j in range(i):
if list1[i] > list1[j] and list2[i] < list2[j] + 1:
list2[i] = list2[j] + 1
return max(list2)
print(longest_increasing_sequence([50, 3, 10, 7,... |
##Ejercicio 2
# el siguiente codigo busca la raiz entera de un numero dado usando BS
# Busqueda Binaria
# Entrada:
# 16 (si se desea encontrar de un numero
# mayor 20 incrementar el tamanio del array)
# Salida:
# Does not exist
#or
# "The element was found " +48
#
# El ejercicio incluye el ordenamiento del arra... | def binary_search(list, n):
baja = 0
alta = len(list) - 1
while baja <= alta:
middle = (alta + baja) // 2
middle_element = list[middle]
cuadrado = middle_element * middle_element
if cuadrado == n:
return middle
if cuadrado < n:
baja = middle + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.