content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#!python3.6
#encoding: utf-8
# https://teratail.com/questions/52151
class Deco:
def __init__(self): self.value = 'value'
def deco(func):
def wrapper(self, *args, **kwargs):
print('----- start -----')
print('self.value =', self.value) # AttributeError: 'C' object has no attribute ... | class Deco:
def __init__(self):
self.value = 'value'
def deco(func):
def wrapper(self, *args, **kwargs):
print('----- start -----')
print('self.value =', self.value)
ret = func(self, *args, **kwargs)
print('----- end -----')
return r... |
expected_output = {
"Mgmt-intf": {
"address_family": {
"ipv4 unicast": {
"flags": "0x0",
"table_id": "0x1",
"vrf_label": {"allocation_mode": "per-prefix"},
}
},
"cli_format": "New",
"flags": "0x1808",
"in... | expected_output = {'Mgmt-intf': {'address_family': {'ipv4 unicast': {'flags': '0x0', 'table_id': '0x1', 'vrf_label': {'allocation_mode': 'per-prefix'}}}, 'cli_format': 'New', 'flags': '0x1808', 'interface': {'GigabitEthernet1': {'vrf': 'Mgmt-intf'}}, 'interfaces': ['GigabitEthernet1'], 'support_af': 'multiple address-f... |
class Solution:
def longestDupSubstring(self, s: str) -> str:
kMod = int(1e9) + 7
bestStart = -1
l = 1
r = len(s)
def val(c: str) -> int:
return ord(c) - ord('a')
# k := length of hashed substring
def getStart(k: int) -> Optional[int]:
maxPow = pow(26, k - 1, kMod)
hash... | class Solution:
def longest_dup_substring(self, s: str) -> str:
k_mod = int(1000000000.0) + 7
best_start = -1
l = 1
r = len(s)
def val(c: str) -> int:
return ord(c) - ord('a')
def get_start(k: int) -> Optional[int]:
max_pow = pow(26, k - 1, ... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "rightASSIGNrightNOTnonassocLESSEQ<=left+-left*/rightISVOIDleft~left@left.ASSIGN CASE CLASS COMMENT ELSE ESAC FALSE FI ID IF IN INHERITS INT ISVOID LESSEQ LET LOOP NEW N... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = "rightASSIGNrightNOTnonassocLESSEQ<=left+-left*/rightISVOIDleft~left@left.ASSIGN CASE CLASS COMMENT ELSE ESAC FALSE FI ID IF IN INHERITS INT ISVOID LESSEQ LET LOOP NEW NOT OF POOL RET STRING THEN TRUE TYPE WHILEprogram : class_listclass_list : class ';' class_lis... |
#
# PySNMP MIB module EXTRAHOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTRAHOP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:53:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) ... |
# ==============================================================================
# ARSC (A Relatively Simple Computer) License
# ==============================================================================
#
# ARSC is distributed under the following BSD-style license:
#
# Copyright (c) 2016-2017 Dzanan Bajgoric
# A... | class Symboltable:
def __init__(self):
self.symbols = dict()
def add_entry(self, symbol, addr):
if symbol in self.symbols:
raise key_error('Symbol "%s" already exists' % symbol)
try:
self.symbols[symbol] = int(addr)
except ValueError:
raise v... |
def SymbolToFromAtomicNumber(ATOM):
atoms = [ [1,"H"],[2,"He"],[3,"Li"],[4,"Be"],[5,"B"],[6,"C"],[7,"N"],[8,"O"],[9,"F"],[10,"Ne"], \
[11,"Na"],[12,"Mg"],[13,"Al"],[14,"Si"],[15,"P"],[16,"S"],[17,"Cl"],[18,"Ar"],[19,"K"],[20,"Ca"], \
[21,"Sc"],[22,"Ti"],[23,"V"],[24,"Cr"],[25,"Mn"],[26,"Fe"],[27... | def symbol_to_from_atomic_number(ATOM):
atoms = [[1, 'H'], [2, 'He'], [3, 'Li'], [4, 'Be'], [5, 'B'], [6, 'C'], [7, 'N'], [8, 'O'], [9, 'F'], [10, 'Ne'], [11, 'Na'], [12, 'Mg'], [13, 'Al'], [14, 'Si'], [15, 'P'], [16, 'S'], [17, 'Cl'], [18, 'Ar'], [19, 'K'], [20, 'Ca'], [21, 'Sc'], [22, 'Ti'], [23, 'V'], [24, 'Cr']... |
#!/usr/bin/python3
list = ["Binwalk","bulk-extractor","Capstone","chntpw","Cuckoo",
"dc3dd","ddrescue","DFF","diStorm3","Dumpzilla","extundelete",
"Foremost","Galleta","Guymager","iPhone Backup Analyzer","p0f",
"pdf-parser","pdfid","pdgmail","peepdf","RegRipper","Volatility","Xplico"] | list = ['Binwalk', 'bulk-extractor', 'Capstone', 'chntpw', 'Cuckoo', 'dc3dd', 'ddrescue', 'DFF', 'diStorm3', 'Dumpzilla', 'extundelete', 'Foremost', 'Galleta', 'Guymager', 'iPhone Backup Analyzer', 'p0f', 'pdf-parser', 'pdfid', 'pdgmail', 'peepdf', 'RegRipper', 'Volatility', 'Xplico'] |
#
# PySNMP MIB module CISCOSB-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-STACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) ... |
def config_fgsm(targeted, adv_ys):
if targeted:
yname = 'y_target'
else:
yname = 'y'
fgsm_params = {yname: adv_ys,
'eps': 0.3,
'clip_min': 0.,
'clip_max': 1.}
return fgsm_params
def config_bim(targeted, adv_ys):
if ta... | def config_fgsm(targeted, adv_ys):
if targeted:
yname = 'y_target'
else:
yname = 'y'
fgsm_params = {yname: adv_ys, 'eps': 0.3, 'clip_min': 0.0, 'clip_max': 1.0}
return fgsm_params
def config_bim(targeted, adv_ys):
if targeted:
yname = 'y_target'
else:
yname = 'y'... |
n = int(input())
for i in range(1,n+1):
if ((n % i) == 0):
print(i,end=" ")
| n = int(input())
for i in range(1, n + 1):
if n % i == 0:
print(i, end=' ') |
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py'
]
# model setting
model = dict(
backbone=dict(
init_cfg=None
),
roi_head=dict(
bbox_head=dict(
num_class... | _base_ = ['../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py']
model = dict(backbone=dict(init_cfg=None), roi_head=dict(bbox_head=dict(num_classes=1)))
dataset_type = 'CocoDataset'
classes = ('target',)
data_root = '../d... |
# 24. Swap Nodes in Pairs
# Runtime: 24 ms, faster than 96.60% of Python3 online submissions for Swap Nodes in Pairs.
# Memory Usage: 14 MB, less than 92.32% of Python3 online submissions for Swap Nodes in Pairs.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# ... | class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
else:
(head.val, head.next.val) = (head.next.val, head.val)
self.swapPairs(head.next.next)
return head |
'''
Created on 11 Apr 2020
@author: dkr85djo
'''
class md:
MAXCARDS = 106
class MDColourSet:
def __init__(self, value, names, hexcolour=b'#000000'):
self.value = value
self.names = names
self.hexcolour = hexcolour
def size(self):
return len(self.na... | """
Created on 11 Apr 2020
@author: dkr85djo
"""
class Md:
maxcards = 106
class Mdcolourset:
def __init__(self, value, names, hexcolour=b'#000000'):
self.value = value
self.names = names
self.hexcolour = hexcolour
def size(self):
return len(self.names)
class Mdcard:
... |
class Stack:
Top = -1
def __init__(self,size):
self.stack = [0 for i in range(size)]
def push(self, value):
if (Stack.Top!=len(self.stack)-1):
Stack.Top += 1
self.stack[Stack.Top] = value
else:
print("Overflow: Stack is Full")
def pop(self):
if (Stack.Top == -1):
pri... | class Stack:
top = -1
def __init__(self, size):
self.stack = [0 for i in range(size)]
def push(self, value):
if Stack.Top != len(self.stack) - 1:
Stack.Top += 1
self.stack[Stack.Top] = value
else:
print('Overflow: Stack is Full')
def pop(sel... |
BASIC_PLUGINS = [
{
"name": "kubejobs",
"source": "",
"component": "manager",
"plugin_source": "",
"module": "kubejobs"
},
{
"name": "kubejobs",
"source": "",
"component": "controller",
"p... | basic_plugins = [{'name': 'kubejobs', 'source': '', 'component': 'manager', 'plugin_source': '', 'module': 'kubejobs'}, {'name': 'kubejobs', 'source': '', 'component': 'controller', 'plugin_source': '', 'module': 'kubejobs'}, {'name': 'kubejobs', 'source': '', 'component': 'monitor', 'plugin_source': '', 'module': 'kub... |
refTable = [{'desc': 'Freedom of Movement', 'templates': ['free'], 'weight': 1.0},
{'desc': 'Visa not Required', 'templates': ['yes', 'yes '], 'weight': 0.9},
{'desc': 'Visa on Arrival',
'templates': ['Optional', 'yes-no'],
'weight': 0.7},
{'desc': 'Electronic Visa', 'templates': ['yes2'], 'weight': 0.5},
{'des... | ref_table = [{'desc': 'Freedom of Movement', 'templates': ['free'], 'weight': 1.0}, {'desc': 'Visa not Required', 'templates': ['yes', 'yes '], 'weight': 0.9}, {'desc': 'Visa on Arrival', 'templates': ['Optional', 'yes-no'], 'weight': 0.7}, {'desc': 'Electronic Visa', 'templates': ['yes2'], 'weight': 0.5}, {'desc': 'Vi... |
# builtins stub used in boolean-related test cases.
class object:
def __init__(self) -> None: pass
class type: pass
class bool: pass
class int: pass
| class Object:
def __init__(self) -> None:
pass
class Type:
pass
class Bool:
pass
class Int:
pass |
{
'%Y-%m-%d':'%Y-%m-%d',
'%Y-%m-%d %H:%M:%S':'%Y-%m-%d %H:%M:%S',
'%s rows deleted':'%s records cancellati',
'%s rows updated':'*** %s records modificati',
'Hello World':'Salve Mondo',
'Invalid Query':'Query invalida',
'Sure you want to delete this object?':'Sicuro che vuoi cancellare questo oggetto?',
'Welcome to web2... | {'%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '%s rows deleted': '%s records cancellati', '%s rows updated': '*** %s records modificati', 'Hello World': 'Salve Mondo', 'Invalid Query': 'Query invalida', 'Sure you want to delete this object?': 'Sicuro che vuoi cancellare questo oggetto?', 'Welcome t... |
def clean_split(text, delim=','):
text = text.strip()
return map(lambda o: o.strip(), text.split(delim))
def read_notes(file):
notes = {}
for line in file:
split = clean_split(line, ',')[:-1]
if split[-1] == '':
continue
notes[(split[0], int(split[1]))] = float(spli... | def clean_split(text, delim=','):
text = text.strip()
return map(lambda o: o.strip(), text.split(delim))
def read_notes(file):
notes = {}
for line in file:
split = clean_split(line, ',')[:-1]
if split[-1] == '':
continue
notes[split[0], int(split[1])] = float(split[2... |
# Game Objects
class Space(object):
def __init__(self,name):
self.name = name
def get_name(self):
return self.name
class Property(Space):
set_houses = {
"Violet":2,
"Light blue":3,
"Purple":3,
"Orange":3,
... | class Space(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
class Property(Space):
set_houses = {'Violet': 2, 'Light blue': 3, 'Purple': 3, 'Orange': 3, 'Red': 3, 'Yellow': 3, 'Green': 3, 'Blue': 2}
def __init__(self, name, color, price, rent,... |
class Hourly:
def __init__(self, temp, feels_like, pressure, humidity, wind_speed, date, city, weather):
self.temp=temp;
self.feels_like=feels_like;
self.pressure=pressure;
self.humidity=humidity;
self.wind_speed=wind_speed;
self.date=date;
self.city=city;
... | class Hourly:
def __init__(self, temp, feels_like, pressure, humidity, wind_speed, date, city, weather):
self.temp = temp
self.feels_like = feels_like
self.pressure = pressure
self.humidity = humidity
self.wind_speed = wind_speed
self.date = date
self.city = ... |
class InvalidQNameError(RuntimeError):
def __init__(self, qname):
message = "Invalid qname: " + qname
super(InvalidQNameError, self).__init__(message)
| class Invalidqnameerror(RuntimeError):
def __init__(self, qname):
message = 'Invalid qname: ' + qname
super(InvalidQNameError, self).__init__(message) |
# selection sort algorithm
# time complexity O(n^2)
# space complexity O(1)
def selectionsort(list, comp):
for x in range(len(list)):
curr = x
for y in range(x, len(list)):
if (comp(list[curr], list[y]) > 0):
curr = y
swap = list[x]
list[x] = li... | def selectionsort(list, comp):
for x in range(len(list)):
curr = x
for y in range(x, len(list)):
if comp(list[curr], list[y]) > 0:
curr = y
swap = list[x]
list[x] = list[curr]
list[curr] = swap
return list |
# Represents a single space within the board.
class Tile():
# Initializes the tile.
# By default, each tile is a wall until a board is built
def __init__(self):
self.isWall = True
# Renders the object character in this tile
def render(self):
if self.isWall == True:
return '0';
# Represents the game board... | class Tile:
def __init__(self):
self.isWall = True
def render(self):
if self.isWall == True:
return '0'
class Board:
def __init__(self, width, height):
self.width = width
self.height = height
self.board = []
for y in range(0, self.height):
... |
__title__ = 'dtanys'
__description__ = 'Python structured data parser.'
__url__ = 'https://github.com/luxuncang/dtanys'
__version__ = '1.0.5'
__author__ = 'ShengXin Lu'
__author_email__ = 'luxuncang@qq.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 ShengXin Lu' | __title__ = 'dtanys'
__description__ = 'Python structured data parser.'
__url__ = 'https://github.com/luxuncang/dtanys'
__version__ = '1.0.5'
__author__ = 'ShengXin Lu'
__author_email__ = 'luxuncang@qq.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 ShengXin Lu' |
class Clock:
def __init__(self, hour, minute):
self.total: int = hour * 60 + minute # in minutes
def __repr__(self):
hour, minute = (self.total // 60) % 24, self.total % 60
return '{:02d}:{:02d}'.format(hour, minute)
def __eq__(self, other):
return repr(self) == repr(oth... | class Clock:
def __init__(self, hour, minute):
self.total: int = hour * 60 + minute
def __repr__(self):
(hour, minute) = (self.total // 60 % 24, self.total % 60)
return '{:02d}:{:02d}'.format(hour, minute)
def __eq__(self, other):
return repr(self) == repr(other)
def ... |
file=open("circulations.txt")
data=[]
date=int(input())
for line in file:
[book,member,due]=line.strip().split()
if date>int(due):
data.append([book,member,due])
i=0
while i<len(data)-1:
j=0
while j<len(data)-1:
if int(data[j][2])>int(data[j+1][2]):
data[j], data[j+1] = ... | file = open('circulations.txt')
data = []
date = int(input())
for line in file:
[book, member, due] = line.strip().split()
if date > int(due):
data.append([book, member, due])
i = 0
while i < len(data) - 1:
j = 0
while j < len(data) - 1:
if int(data[j][2]) > int(data[j + 1][2]):
... |
BASE_URL = "https://api.stlouisfed.org"
SERIES_ENDPOINT = "fred/series/observations"
SERIES = ["GDPC1", "UMCSENT", "UNRATE"]
FILE_TYPE = "json"
| base_url = 'https://api.stlouisfed.org'
series_endpoint = 'fred/series/observations'
series = ['GDPC1', 'UMCSENT', 'UNRATE']
file_type = 'json' |
f90 = {}
cxx = {}
cc = {}
is_arch_valid = 1
flags_arch = '-g -pg -O3 -Wall'
# -lpthread: not needed?
# -rdynamic: required for backtraces
balancer = 'RotateLB'
flags_prec_single = '-fdefault-real-4 -fdefault-double-8'
flags_prec_double = '-fdefault-real-8 -fdefault-double-8'
flags_cxx_charm = '-balancer '... | f90 = {}
cxx = {}
cc = {}
is_arch_valid = 1
flags_arch = '-g -pg -O3 -Wall'
balancer = 'RotateLB'
flags_prec_single = '-fdefault-real-4 -fdefault-double-8'
flags_prec_double = '-fdefault-real-8 -fdefault-double-8'
flags_cxx_charm = '-balancer ' + balancer
flags_link_charm = '-rdynamic -module ' + balancer
cc = 'gcc'
f9... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeZeroSumSublists(self, head: ListNode) -> ListNode:
ptr = ListNode(-1)
ptr.next = head
current = head
head = ptr
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_zero_sum_sublists(self, head: ListNode) -> ListNode:
ptr = list_node(-1)
ptr.next = head
current = head
head = ptr
while head:
s... |
add_library('opencv_processing')
src = loadImage("test.jpg")
size(src.width, src.height, P2D)
opencv = OpenCV(this, src)
opencv.findCannyEdges(20, 75)
canny = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findScharrEdges(OpenCV.HORIZONTAL)
scharr = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findSobelEdge... | add_library('opencv_processing')
src = load_image('test.jpg')
size(src.width, src.height, P2D)
opencv = open_cv(this, src)
opencv.findCannyEdges(20, 75)
canny = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findScharrEdges(OpenCV.HORIZONTAL)
scharr = opencv.getSnapshot()
opencv.loadImage(src)
opencv.findSobelEdges(... |
#
# PySNMP MIB module RAPID-HA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPID-HA-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:51:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint, constraints_union) ... |
filt_dict = {
'db': [['Emissions', '(Kyoto Gases|co2)$', '(|Energy and Industrial Processes|AFOLU)$', '', '(world|r5.*)'],
['Policy cost', '(Additional Total Energy System Cost|consumption Loss|gdp Loss)', '', '', '(world|r5.*)'],
['Price', 'Carbon', '$', '', '(world|r5.*)'],
],
}
| filt_dict = {'db': [['Emissions', '(Kyoto Gases|co2)$', '(|Energy and Industrial Processes|AFOLU)$', '', '(world|r5.*)'], ['Policy cost', '(Additional Total Energy System Cost|consumption Loss|gdp Loss)', '', '', '(world|r5.*)'], ['Price', 'Carbon', '$', '', '(world|r5.*)']]} |
# https://leetcode.com/problems/insert-interval/
# Given a set of non-overlapping intervals, insert a new interval into the
# intervals (merge if necessary).
# You may assume that the intervals were initially sorted according to their start
# times.
###################################################################... | class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
if not intervals:
return [newInterval]
ans = []
inserted = False
for interval in intervals:
if interval[1] < newInterval[0]:
ans.append(in... |
#!/usr/bin/env python3
def merge(L1, L2):
L3 = L1+L2
for j in range(len(L3)):
for i in range(0, len(L3)-j-1):
if L3[i]> L3[i+1]:
L3[i],L3[i+1] = L3[i+1] , L3[i]
return (L3)
def main():
print((merge([1,2,3],[1,6,7])))
pass
if __name__ == "__main__":
main(... | def merge(L1, L2):
l3 = L1 + L2
for j in range(len(L3)):
for i in range(0, len(L3) - j - 1):
if L3[i] > L3[i + 1]:
(L3[i], L3[i + 1]) = (L3[i + 1], L3[i])
return L3
def main():
print(merge([1, 2, 3], [1, 6, 7]))
pass
if __name__ == '__main__':
main() |
class ControllerBase:
@staticmethod
def base():
return True
| class Controllerbase:
@staticmethod
def base():
return True |
'''
You are given an array of length n which only contains the elements 0,1 and 2.
You are supposed to sort the array in ascending order without the use of any sorting algorithms. Minimize time complexity.
Input Format:
The first line of input contains the value of n i.e. size of array.
The next line contains n space... | """
You are given an array of length n which only contains the elements 0,1 and 2.
You are supposed to sort the array in ascending order without the use of any sorting algorithms. Minimize time complexity.
Input Format:
The first line of input contains the value of n i.e. size of array.
The next line contains n space... |
class BlocoMemoria:
palavra: list
endBlock: int
atualizado: bool
custo: int
cacheHit: int
ultimoUso: int
def __init__(self):
self.endBlock = -1
self.atualizado = False
self.custo = 0
self.cacheHit = 0
ultimoUso: 2**31-1 | class Blocomemoria:
palavra: list
end_block: int
atualizado: bool
custo: int
cache_hit: int
ultimo_uso: int
def __init__(self):
self.endBlock = -1
self.atualizado = False
self.custo = 0
self.cacheHit = 0
ultimo_uso: 2 ** 31 - 1 |
AzToolchainInfo = provider(
doc = "Azure toolchain rule parameters",
fields = [
"az_tool_path",
"az_tool_target",
"azure_extension_dir",
"az_extensions_installed",
"jq_tool_path",
],
)
AzConfigInfo = provider(
fields = [
"debug",
"global_args",
... | az_toolchain_info = provider(doc='Azure toolchain rule parameters', fields=['az_tool_path', 'az_tool_target', 'azure_extension_dir', 'az_extensions_installed', 'jq_tool_path'])
az_config_info = provider(fields=['debug', 'global_args', 'subscription', 'verbose']) |
# Copyright 2018- The Pixie Authors.
#
# 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 w... | def _fetch_licenses_impl(ctx):
args = ctx.actions.args()
args.add('--github_token', ctx.file.oauth_token)
args.add('--modules', ctx.file.src)
if ctx.attr.use_pkg_dev_go:
args.add('--try_pkg_dev_go')
if ctx.attr.disallow_missing:
args.add('--fatal_if_missing')
args.add('--json_man... |
package(default_visibility = [ "//visibility:public" ])
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "net_import_library", "core_import_library")
net_import_library(
name = "net45",
src = "lib/netstandard1.0/System.Threading.Tasks.Extensions.dll",
)
core_import_library(
name = "netcore",
src = "lib/netstan... | package(default_visibility=['//visibility:public'])
load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'net_import_library', 'core_import_library')
net_import_library(name='net45', src='lib/netstandard1.0/System.Threading.Tasks.Extensions.dll')
core_import_library(name='netcore', src='lib/netstandard2.0/System.Threading.T... |
class Solution:
def repeatedStringMatch(self, A: str, B: str) -> int:
if B in A:
return 0
counter = 1
repeatedA = A
while len(repeatedA) < len(B)*2:
repeatedA += A
if B in repeatedA:
return counter
counter += 1
r... | class Solution:
def repeated_string_match(self, A: str, B: str) -> int:
if B in A:
return 0
counter = 1
repeated_a = A
while len(repeatedA) < len(B) * 2:
repeated_a += A
if B in repeatedA:
return counter
counter += 1
... |
WIDTH = 50
HEIGHT = 10
MAX_WIDTH = WIDTH - 2
MAX_HEIGHT = HEIGHT - 2
| width = 50
height = 10
max_width = WIDTH - 2
max_height = HEIGHT - 2 |
# coding: utf-8
class CorpusInterface(object):
def load_corpus(self, corpus):
pass
def read_corpus(self, filename):
pass
class Corpus(object):
def load_corpus(self, corpus):
raise NotImplementedError()
def read_corpus(self, filename):
raise NotImplementedError()
| class Corpusinterface(object):
def load_corpus(self, corpus):
pass
def read_corpus(self, filename):
pass
class Corpus(object):
def load_corpus(self, corpus):
raise not_implemented_error()
def read_corpus(self, filename):
raise not_implemented_error() |
x = int(input())
for i in range(1, 11):
resultado = i * x
print("{} x {} = {}".format(i, x, resultado))
| x = int(input())
for i in range(1, 11):
resultado = i * x
print('{} x {} = {}'.format(i, x, resultado)) |
patches = [
# Rename AWS::Lightsail::Instance.Disk to AWS::Lightsail::Instance.DiskProperty
{
"op": "move",
"from": "/PropertyTypes/AWS::Lightsail::Instance.Disk",
"path": "/PropertyTypes/AWS::Lightsail::Instance.DiskProperty",
},
{
"op": "replace",
"path": "/Prop... | patches = [{'op': 'move', 'from': '/PropertyTypes/AWS::Lightsail::Instance.Disk', 'path': '/PropertyTypes/AWS::Lightsail::Instance.DiskProperty'}, {'op': 'replace', 'path': '/PropertyTypes/AWS::Lightsail::Instance.Hardware/Properties/Disks/ItemType', 'value': 'DiskProperty'}, {'op': 'remove', 'path': '/PropertyTypes/AW... |
maximum = float("-inf")
def max_path_sum(root):
helper(root)
return maximum
def helper(root):
if not root:
return 0
left = helper(root.left)
right = helper(root.right)
maximum = max(maximum, left+right+root.val)
return root.val + max(left, right)
| maximum = float('-inf')
def max_path_sum(root):
helper(root)
return maximum
def helper(root):
if not root:
return 0
left = helper(root.left)
right = helper(root.right)
maximum = max(maximum, left + right + root.val)
return root.val + max(left, right) |
fruit = input()
size_set = input()
count_sets = float(input())
price_set = 0
if fruit == 'Watermelon':
if size_set == 'small':
price_set = count_sets * 56 * 2
elif size_set == 'big':
price_set = count_sets * 28.7 * 5
elif fruit == 'Mango':
if size_set == 'small':
price_set = count_s... | fruit = input()
size_set = input()
count_sets = float(input())
price_set = 0
if fruit == 'Watermelon':
if size_set == 'small':
price_set = count_sets * 56 * 2
elif size_set == 'big':
price_set = count_sets * 28.7 * 5
elif fruit == 'Mango':
if size_set == 'small':
price_set = count_se... |
def test_socfaker_timestamp_in_the_past(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_past()
def test_socfaker_timestamp_in_the_future(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_future()
def test_socfaker_timestamp_current(socfaker_fixture):
assert socfaker_fixture.timestamp... | def test_socfaker_timestamp_in_the_past(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_past()
def test_socfaker_timestamp_in_the_future(socfaker_fixture):
assert socfaker_fixture.timestamp.in_the_future()
def test_socfaker_timestamp_current(socfaker_fixture):
assert socfaker_fixture.timestamp... |
releases = [
{
"ocid": "A",
"id": "1",
"date": "2014-01-01",
"tag": ["tender"],
"tender": {
"items": [
{
"id": "1",
"description": "Item 1",
"quantity": 1
},
{
"id": "2",
"desc... | releases = [{'ocid': 'A', 'id': '1', 'date': '2014-01-01', 'tag': ['tender'], 'tender': {'items': [{'id': '1', 'description': 'Item 1', 'quantity': 1}, {'id': '2', 'description': 'Item 2', 'quantity': 1}]}}, {'ocid': 'A', 'id': '2', 'date': '2014-01-02', 'tag': ['tender'], 'tender': {'items': [{'id': '1', 'description'... |
__title__ = "PyMatting"
__version__ = "1.1.3"
__author__ = "The PyMatting Developers"
__email__ = "pymatting@gmail.com"
__license__ = "MIT"
__uri__ = "https://pymatting.github.io"
__summary__ = "Python package for alpha matting."
| __title__ = 'PyMatting'
__version__ = '1.1.3'
__author__ = 'The PyMatting Developers'
__email__ = 'pymatting@gmail.com'
__license__ = 'MIT'
__uri__ = 'https://pymatting.github.io'
__summary__ = 'Python package for alpha matting.' |
class Matrix:
def __init__(self, mat):
l_size = len(mat[0])
for line in mat:
if l_size != len(line):
raise ValueError('invalid matrix sizes')
self._raw = mat
@property
def raw(self):
return self._raw
@property
def trace(self):
if ... | class Matrix:
def __init__(self, mat):
l_size = len(mat[0])
for line in mat:
if l_size != len(line):
raise value_error('invalid matrix sizes')
self._raw = mat
@property
def raw(self):
return self._raw
@property
def trace(self):
i... |
# todo remove in next major release as we no longer support django < 3.2 anyway. Note this would make dj-stripe unuseable for djang0 < 3.2
# for django < 3.2
default_app_config = "djstripe.apps.DjstripeAppConfig"
| default_app_config = 'djstripe.apps.DjstripeAppConfig' |
with open("mynewtextfile.txt","w+") as f:
f.writelines("\nOtus we are learning python\nOtus we are learning python\nOtus we are learning python")
f.seek(0)
print(f.readlines())
print("Is readable:", f.readable())
print("Is writeable:", f.writable())
print("File no:", f.fileno())
print("Is co... | with open('mynewtextfile.txt', 'w+') as f:
f.writelines('\nOtus we are learning python\nOtus we are learning python\nOtus we are learning python')
f.seek(0)
print(f.readlines())
print('Is readable:', f.readable())
print('Is writeable:', f.writable())
print('File no:', f.fileno())
print('Is c... |
class Solution:
def traverse(self, node: TreeNode, deep: int):
if node is None: return deep
deep += 1
if node.left is None:
return self.traverse(node.right, deep)
elif node.right is None:
return self.traverse(node.left, deep)
else:
left_de... | class Solution:
def traverse(self, node: TreeNode, deep: int):
if node is None:
return deep
deep += 1
if node.left is None:
return self.traverse(node.right, deep)
elif node.right is None:
return self.traverse(node.left, deep)
else:
... |
def rotation_saxs(t = 1):
#sample = ['Hopper2_AGIB_AuPd_top', 'Hopper2_AGIB_AuPd_mid', 'Hopper2_AGIB_AuPd_bot'] #Change filename
sample = ['AGIB3N_1top', 'AGIB3N_1mid', 'AGIB3N_1cen'] #Change filename
#y_list = [-6.06, -6.04, -6.02] #hexapod is in mm
#y_list = [-10320, -10300, -10280] #SmarAct i... | def rotation_saxs(t=1):
sample = ['AGIB3N_1top', 'AGIB3N_1mid', 'AGIB3N_1cen']
y_list = [4760, 4810, 4860]
assert len(y_list) == len(sample), f'Number of X coordinates ({len(x_list)}) is different from number of samples ({len(samples)})'
dets = [pil1M, pil300KW]
prs_range = [-90, 90, 91]
waxs_ra... |
def factory(classToInstantiate):
def f(*arg):
def g():
return classToInstantiate(*arg)
return g
return f | def factory(classToInstantiate):
def f(*arg):
def g():
return class_to_instantiate(*arg)
return g
return f |
class EmailBuilder:
def __init__(self):
self.message = {}
def set_from_email(self, email):
self.message['from'] = email
return self
def set_receiver_email(self, email):
self.message['receiver'] = email
def set_cc_emails(self, emails):
self.message['cc'] = email... | class Emailbuilder:
def __init__(self):
self.message = {}
def set_from_email(self, email):
self.message['from'] = email
return self
def set_receiver_email(self, email):
self.message['receiver'] = email
def set_cc_emails(self, emails):
self.message['cc'] = emai... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 o... | test_request_transfer_icx = {'jsonrpc': '2.0', 'method': 'icx_sendTransaction', 'id': 1234, 'params': {'version': '0x3', 'from': 'hxbe258ceb872e08851f1f59694dac2558708ece11', 'to': 'hx5bfdb090f43a808005ffc27c25b213145e80b7cd', 'value': '0xde0b6b3a7640000', 'stepLimit': '0x12345', 'timestamp': '0x563a6cf330136', 'nid': ... |
#! /usr/bin/env python3
def main():
try:
name = input('\nHello! What is your name? ')
if name:
print(f'\nWell, {name}, it is nice to meet you!\n')
except:
print('\n\nSorry. Something went wrong, please try again.\n')
if __name__ == '__main__':
main()
| def main():
try:
name = input('\nHello! What is your name? ')
if name:
print(f'\nWell, {name}, it is nice to meet you!\n')
except:
print('\n\nSorry. Something went wrong, please try again.\n')
if __name__ == '__main__':
main() |
meta_pickups={
'aux_domains': lambda r, common, data: {
'pos': r['head_pos'], 'head': r['head'], 'head_word': r['head_word'],
**common, **data},
'root_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **common, **data},
'verb_domains': lambda r, common, data: {'pos': r['u... | meta_pickups = {'aux_domains': lambda r, common, data: {'pos': r['head_pos'], 'head': r['head'], 'head_word': r['head_word'], **common, **data}, 'root_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **common, **data}, 'verb_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **co... |
#
# PySNMP MIB module CISCO-WAN-BBIF-ATM-CONN-STAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-BBIF-ATM-CONN-STAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
things = ['a', 'b', 'c', 'd']
print(things)
print(things[1])
things[1] = 'z'
print(things[1])
print(things)
things = ['a', 'b', 'c', 'd']
print("=" * 50)
stuff = {'name' : 'Jinkyu', 'age' : 40, 'height' : 6 * 12 + 2}
print(stuff)
print(stuff['name'])
print(stuff['age'])
print(stuff['height'])
stuff['city'] = "SF"
print... | things = ['a', 'b', 'c', 'd']
print(things)
print(things[1])
things[1] = 'z'
print(things[1])
print(things)
things = ['a', 'b', 'c', 'd']
print('=' * 50)
stuff = {'name': 'Jinkyu', 'age': 40, 'height': 6 * 12 + 2}
print(stuff)
print(stuff['name'])
print(stuff['age'])
print(stuff['height'])
stuff['city'] = 'SF'
print(st... |
# https://leetcode.com/problems/surface-area-of-3d-shapes
class Solution:
def surfaceArea(self, grid):
N = len(grid)
ans = 0
for i in range(N):
for j in range(N):
if grid[i][j] == 0:
continue
height = grid[i][j]
... | class Solution:
def surface_area(self, grid):
n = len(grid)
ans = 0
for i in range(N):
for j in range(N):
if grid[i][j] == 0:
continue
height = grid[i][j]
ans += 2
for h in range(1, height + 1):
... |
tempo = int(input())
velocida_media = int(input())
gasto_carro = 12
distancia = velocida_media * tempo
print(f'{distancia / 12:.3f}') | tempo = int(input())
velocida_media = int(input())
gasto_carro = 12
distancia = velocida_media * tempo
print(f'{distancia / 12:.3f}') |
rows, cols = [int(n) for n in input().split(", ")]
matrix = []
for _ in range(rows):
matrix.append([int(n) for n in input().split(" ")])
for j in range(cols):
total = 0
for row in matrix:
total += row[j]
print(total)
| (rows, cols) = [int(n) for n in input().split(', ')]
matrix = []
for _ in range(rows):
matrix.append([int(n) for n in input().split(' ')])
for j in range(cols):
total = 0
for row in matrix:
total += row[j]
print(total) |
# Available methods
METHODS = {
# Dummy for HF
"hf": ["hf"],
"ricc2": ["rimp2", "rimp3", "rimp4", "ricc2"],
# Hardcoded XC-functionals that can be selected from the dft submenu
# of define.
"dft_hardcoded": [
# Hardcoded in V7.3
"s-vwn",
"s-vwn_Gaussian",
"pwlda",... | methods = {'hf': ['hf'], 'ricc2': ['rimp2', 'rimp3', 'rimp4', 'ricc2'], 'dft_hardcoded': ['s-vwn', 's-vwn_Gaussian', 'pwlda', 'b-lyp', 'b-vwn', 'b-p', 'pbe', 'tpss', 'bh-lyp', 'b3-lyp', 'b3-lyp_Gaussian', 'pbe0', 'tpssh', 'pw6b95', 'm06', 'm06-l', 'm06-2x', 'lhf', 'oep', 'b97-d', 'pbeh-3c', 'b97-3c', 'lh07t-svwn', 'lh0... |
class Config:
'''
General configuration parent class
'''
NEWS_API_BASE_URL ='https://newsapi.org/v2/sources?apiKey={}'
ARTICLE_API_BASE_URL = 'https://newsapi.org/v2/everything?sources={}&apiKey={}'
class ProdConfig(Config):
'''
Production configuration child class
Args:
Config: The parent con... | class Config:
"""
General configuration parent class
"""
news_api_base_url = 'https://newsapi.org/v2/sources?apiKey={}'
article_api_base_url = 'https://newsapi.org/v2/everything?sources={}&apiKey={}'
class Prodconfig(Config):
"""
Production configuration child class
Args:
Config: The parent... |
def main() -> None:
K, X = map(int, input().split())
assert 1 <= K <= 100
assert 1 <= X <= 10**5
if __name__ == '__main__':
main()
| def main() -> None:
(k, x) = map(int, input().split())
assert 1 <= K <= 100
assert 1 <= X <= 10 ** 5
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
description = "Setup for the LakeShore 340 temperature controller"
group = "optional"
includes = ["alias_T"]
tango_base = "tango://phys.kws3.frm2:10000/kws3"
tango_ls340 = tango_base + "/ls340"
devices = dict(
T_ls340 = device("nicos.devices.entangle.TemperatureController",
descr... | description = 'Setup for the LakeShore 340 temperature controller'
group = 'optional'
includes = ['alias_T']
tango_base = 'tango://phys.kws3.frm2:10000/kws3'
tango_ls340 = tango_base + '/ls340'
devices = dict(T_ls340=device('nicos.devices.entangle.TemperatureController', description='Temperature regulation', tangodevic... |
def response(status, message, data, status_code=200):
return {
"status": status,
"message": message,
"data": data,
}, status_code
| def response(status, message, data, status_code=200):
return ({'status': status, 'message': message, 'data': data}, status_code) |
x = 0
for n in range(10):
x = x + 1
assert x == 10
| x = 0
for n in range(10):
x = x + 1
assert x == 10 |
#Queue.py
#20 Oct 2017
#Written By Amin Dehghan
#DS & Algorithms With Python
class Queue:
def __init__(self):
self.items=[]
self.fronIdx=0
def __compress(self):
newlst=[]
for i in range(self.frontIdx,len(self.items)):
newlst.append(self.items[i])
... | class Queue:
def __init__(self):
self.items = []
self.fronIdx = 0
def __compress(self):
newlst = []
for i in range(self.frontIdx, len(self.items)):
newlst.append(self.items[i])
self.items = newlst
self.frontIdx = 0
def dequeue(self):
if ... |
patches = [
{
"op": "move",
"from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType",
"path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType",
},
{
"op": "replace",
"path": "/ResourceTypes/AWS::Transfer::Server/Propert... | patches = [{'op': 'move', 'from': '/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType', 'path': '/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType'}, {'op': 'replace', 'path': '/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType', 'value': 'String'}, {'o... |
def foo(x):
if x == 0:
return 1
elif x % 2 == 0:
return 2 * x * foo(x - 2)
else:
return (x -3) * x * foo(x + 1)
print(foo(4)) | def foo(x):
if x == 0:
return 1
elif x % 2 == 0:
return 2 * x * foo(x - 2)
else:
return (x - 3) * x * foo(x + 1)
print(foo(4)) |
def diff(n, mid) :
if (n > (mid * mid * mid)) :
return (n - (mid * mid * mid))
else :
return ((mid * mid * mid) - n)
# Returns cube root of a no n
def cubicRoot(n) :
# Set start and end for binary
# search
start = 0
end = n
# Set precision ... | def diff(n, mid):
if n > mid * mid * mid:
return n - mid * mid * mid
else:
return mid * mid * mid - n
def cubic_root(n):
start = 0
end = n
e = 1e-07
while True:
mid = (start + end) / 2
error = diff(n, mid)
if error <= e:
return mid
if ... |
# Base Parameters
assets = asset_list('FX')
# Trading Parameters
horizon = 'H1'
pair = 0
# Mass Imports
my_data = mass_import(pair, horizon)
# Parameters
long_ema = 26
short_ema = 12
signal_ema = 9
def ma(Data, lookback, close, where):
Data = adder(Data, 1)
for i in ... | assets = asset_list('FX')
horizon = 'H1'
pair = 0
my_data = mass_import(pair, horizon)
long_ema = 26
short_ema = 12
signal_ema = 9
def ma(Data, lookback, close, where):
data = adder(Data, 1)
for i in range(len(Data)):
try:
Data[i, where] = Data[i - lookback + 1:i + 1, close].mean()
... |
x = 'heLLo world'
print("Swap the case: " + x.swapcase())
print("Set all cast to upper: " + x.upper())
print("Set all cast to lower: " + x.lower())
print("Set all cast to lower aggresivly: " + x.casefold())
print("Set every word\'s first letter to upper: " + x.title())
print("Set the first word\'s first letter to... | x = 'heLLo world'
print('Swap the case: ' + x.swapcase())
print('Set all cast to upper: ' + x.upper())
print('Set all cast to lower: ' + x.lower())
print('Set all cast to lower aggresivly: ' + x.casefold())
print("Set every word's first letter to upper: " + x.title())
print("Set the first word's first letter to upper i... |
'''
constants for the project
'''
TRAIN_LOSS = 0
TRAIN_ACCURACY = 1
VAL_LOSS = 2
VAL_ACCURACY = 3
| """
constants for the project
"""
train_loss = 0
train_accuracy = 1
val_loss = 2
val_accuracy = 3 |
# -*- coding: utf-8 -*-
STATSD_ENABLED = False
STATSD_HOST = "localhost"
STATSD_PORT = 8125
STATSD_LOG_PERIODIC = True
STATSD_LOG_EVERY = 5
STATSD_HANDLER = "scrapy_statsd_extension.handlers.StatsdBase"
STATSD_PREFIX = "scrapy"
STATSD_LOG_ONLY = []
STATSD_TAGGING = False
STATSD_TAGS = {"spider_name": True}
STATSD_IGNOR... | statsd_enabled = False
statsd_host = 'localhost'
statsd_port = 8125
statsd_log_periodic = True
statsd_log_every = 5
statsd_handler = 'scrapy_statsd_extension.handlers.StatsdBase'
statsd_prefix = 'scrapy'
statsd_log_only = []
statsd_tagging = False
statsd_tags = {'spider_name': True}
statsd_ignore = [] |
N, r = map(int, input().split())
for i in range(N):
R = int(input())
if R>=r:
print('Good boi')
else:
print('Bad boi') | (n, r) = map(int, input().split())
for i in range(N):
r = int(input())
if R >= r:
print('Good boi')
else:
print('Bad boi') |
# WRITE YOUR SOLUTION HERE:
class Employee:
def __init__(self, name: str):
self.name = name
self.subordinates = []
def add_subordinate(self, employee: 'Employee'):
self.subordinates.append(employee)
def count_subordinates(employee: Employee):
count = len(employee.subordinates)
... | class Employee:
def __init__(self, name: str):
self.name = name
self.subordinates = []
def add_subordinate(self, employee: 'Employee'):
self.subordinates.append(employee)
def count_subordinates(employee: Employee):
count = len(employee.subordinates)
if len(employee.subordinate... |
#!/usr/bin/env python3
def palindrome(x):
return str(x) == str(x)[::-1]
def number_palindrome(n, base):
if base == 2:
binary = bin(n)[2:]
return palindrome(binary)
if base == 10:
return palindrome(n)
return False
def double_base_palindrome(x):
return number_palindrome(x... | def palindrome(x):
return str(x) == str(x)[::-1]
def number_palindrome(n, base):
if base == 2:
binary = bin(n)[2:]
return palindrome(binary)
if base == 10:
return palindrome(n)
return False
def double_base_palindrome(x):
return number_palindrome(x, 10) and number_palindrome... |
#for request headers
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
} | headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'} |
# Create an array for the points of the line
line_points = [ {"x":5, "y":5},
{"x":70, "y":70},
{"x":120, "y":10},
{"x":180, "y":60},
{"x":240, "y":10}]
# Create style
style_line = lv.style_t()
style_line.init()
style_line.set_line_width(8)
style_line.... | line_points = [{'x': 5, 'y': 5}, {'x': 70, 'y': 70}, {'x': 120, 'y': 10}, {'x': 180, 'y': 60}, {'x': 240, 'y': 10}]
style_line = lv.style_t()
style_line.init()
style_line.set_line_width(8)
style_line.set_line_color(lv.palette_main(lv.PALETTE.BLUE))
style_line.set_line_rounded(True)
line1 = lv.line(lv.scr_act())
line1.s... |
# In case it's not obvious, a list comprehension produces a list, but
# it doesn't have to be given a list to iterate over.
#
# You can use a list comprehension with any iterable type, so we'll
# write a comprehension to convert dimensions from inches to centimetres.
#
# Our dimensions will be represented by a tuple, f... | inch_measurement = (3, 8, 20)
cm_measurement = [x * 2.54 for x in inch_measurement]
print(cm_measurement)
cm_measurement = [(x, x * 2.54) for x in inch_measurement]
print(cm_measurement)
cm_measurement = tuple((x * 2.54 for x in inch_measurement))
print(cm_measurement) |
r=s=t=1 #--- I1
print(r + s + t)
r=s=t='1' #--- I2
print(r + s + t)
| r = s = t = 1
print(r + s + t)
r = s = t = '1'
print(r + s + t) |
_base_ = '../../base.py'
# model settings
model = dict(
type='Classification',
pretrained=None,
backbone=dict(
type='ResNet',
depth=50,
out_indices=[4], # 4: stage-4
norm_cfg=dict(type='BN')),
head=dict(
type='ClsHead', with_avg_pool=True, in_channels=2048, num_c... | _base_ = '../../base.py'
model = dict(type='Classification', pretrained=None, backbone=dict(type='ResNet', depth=50, out_indices=[4], norm_cfg=dict(type='BN')), head=dict(type='ClsHead', with_avg_pool=True, in_channels=2048, num_classes=10))
data_source_cfg = dict(type='Cifar10', root='/root/data/zq/data/cifar/')
datas... |
class BruteForceProtectionException(Exception):
pass
class BruteForceProtectionBanException(BruteForceProtectionException):
pass
class BruteForceProtectionCaptchaException(BruteForceProtectionException):
pass
| class Bruteforceprotectionexception(Exception):
pass
class Bruteforceprotectionbanexception(BruteForceProtectionException):
pass
class Bruteforceprotectioncaptchaexception(BruteForceProtectionException):
pass |
model = Model()
i1 = Input("input", "TENSOR_FLOAT32", "{1, 2, 2, 1}")
axis = Parameter("axis", "TENSOR_INT32", "{1}", [2])
keepDims = False
output = Output("output", "TENSOR_FLOAT32", "{1, 2, 1}")
model = model.Operation("REDUCE_MIN", i1, axis, keepDims).To(output)
# Example 1. Input in operand 0,
input0 = {i1: # inp... | model = model()
i1 = input('input', 'TENSOR_FLOAT32', '{1, 2, 2, 1}')
axis = parameter('axis', 'TENSOR_INT32', '{1}', [2])
keep_dims = False
output = output('output', 'TENSOR_FLOAT32', '{1, 2, 1}')
model = model.Operation('REDUCE_MIN', i1, axis, keepDims).To(output)
input0 = {i1: [2.0, 1.0, 3.0, 4.0]}
output0 = {output... |
# https://leetcode.com/problems/subrectangle-queries
class SubrectangleQueries:
def __init__(self, rectangle):
self.rectangle = rectangle
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
for row in range(row1, row2 + 1):
for col in range(col1, col2 + 1):
... | class Subrectanglequeries:
def __init__(self, rectangle):
self.rectangle = rectangle
def update_subrectangle(self, row1, col1, row2, col2, newValue):
for row in range(row1, row2 + 1):
for col in range(col1, col2 + 1):
self.rectangle[row][col] = newValue
def get... |
entries = [
{
"env-title": "atari-alien",
"env-variant": "No-op start",
"score": 6482.10,
},
{
"env-title": "atari-amidar",
"env-variant": "No-op start",
"score": 833,
},
{
"env-title": "atari-assault",
"env-variant": "No-op start",
... | entries = [{'env-title': 'atari-alien', 'env-variant': 'No-op start', 'score': 6482.1}, {'env-title': 'atari-amidar', 'env-variant': 'No-op start', 'score': 833}, {'env-title': 'atari-assault', 'env-variant': 'No-op start', 'score': 11013.5}, {'env-title': 'atari-asterix', 'env-variant': 'No-op start', 'score': 36238.5... |
class BaseViewTemplate():
def get_template(self):
if self.request.user.is_authenticated:
template = "core/base.html"
else:
template = "core/base-nav.html"
return template
| class Baseviewtemplate:
def get_template(self):
if self.request.user.is_authenticated:
template = 'core/base.html'
else:
template = 'core/base-nav.html'
return template |
{
"roadMapId" : "2",
"mapIds" : {
"1" : {
"parameter" : [
"-l"
],
"code" : "import json\ndef eventHandler(event, context, callback):\n\tjsonString = json.dumps(event)\n\tprint(jsonString)\n\tif event[\"present\"] == \"person\":\n\t\tprint(\"OK\")... | {'roadMapId': '2', 'mapIds': {'1': {'parameter': ['-l'], 'code': 'import json\ndef eventHandler(event, context, callback):\n\tjsonString = json.dumps(event)\n\tprint(jsonString)\n\tif event["present"] == "person":\n\t\tprint("OK")\n\telse:\n\t\tprint("None")', 'deviceId': 'deviceId1', 'serverId': 'serverId1', 'brokerId... |
# program to converte API text file to markdown for wiki.
all_apis = []
with open("stepspy_api.txt","rt") as fid_api:
api = []
line = fid_api.readline().strip()
api.append(line)
while True:
line = fid_api.readline()
if len(line)==0:
if len(api) != 0:
all_apis.... | all_apis = []
with open('stepspy_api.txt', 'rt') as fid_api:
api = []
line = fid_api.readline().strip()
api.append(line)
while True:
line = fid_api.readline()
if len(line) == 0:
if len(api) != 0:
all_apis.append(tuple(api))
break
else:
... |
type_input = input()
symbol = input()
def int_type(num):
number = int(num)
result = number * 2
print(result)
def real_type(num):
number = float(num)
result = number * 1.5
print(f"{result:.2f}")
def string_type(text):
string = "$" + text + "$"
print(string)
if type_input == "int":... | type_input = input()
symbol = input()
def int_type(num):
number = int(num)
result = number * 2
print(result)
def real_type(num):
number = float(num)
result = number * 1.5
print(f'{result:.2f}')
def string_type(text):
string = '$' + text + '$'
print(string)
if type_input == 'int':
... |
class Wrapper:
"Wrapper to disable commit in sqla"
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
if attr in ["commit", "rollback"]:
return lambda *args, **kwargs: None
obj = getattr(self.obj, attr)
if attr not in ["cursor", "execute"]:
... | class Wrapper:
"""Wrapper to disable commit in sqla"""
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
if attr in ['commit', 'rollback']:
return lambda *args, **kwargs: None
obj = getattr(self.obj, attr)
if attr not in ['cursor', 'execute']:... |
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
if not words or not pattern:
return result
for word in words:
mapping = {}
isMapped = True
for i, c in enum... | class Solution:
def find_and_replace_pattern(self, words: List[str], pattern: str) -> List[str]:
result = []
if not words or not pattern:
return result
for word in words:
mapping = {}
is_mapped = True
for (i, c) in enumerate(word):
... |
CONSUMER_KEY = 'WVQrIJcorH11hQoP6mHKvXIZJ'
CONSUMER_SECRET = 'Ui3V1dEsa5owJnhu3nLNyqdz2hFf6HmvICPObiShmkzBszKnah'
ACCESS_TOKEN = '218405160-0iabe9XqpwAJ4z4BYsaXwH3ydKpFZhnzj5xpHxpI'
ACCESS_SECRET = 'PdPNfcgkc5x7TO54cxVjGOjSrqY2jbcaayV46ys9IkLj3'
| consumer_key = 'WVQrIJcorH11hQoP6mHKvXIZJ'
consumer_secret = 'Ui3V1dEsa5owJnhu3nLNyqdz2hFf6HmvICPObiShmkzBszKnah'
access_token = '218405160-0iabe9XqpwAJ4z4BYsaXwH3ydKpFZhnzj5xpHxpI'
access_secret = 'PdPNfcgkc5x7TO54cxVjGOjSrqY2jbcaayV46ys9IkLj3' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.