code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python comment coding: utf-8 comment @Author : Mr.K comment @Software: PyCharm Community Edition comment @Time : 2019/11/23 2:41 comment @Description: #使用selenium实现浏览器模拟UI登录,配合unittest框架实现UI功能测试 import time import unittest from congfig import * import HTMLTestReportCN from bs4 import BeautifulSoup...
#!/usr/bin/env python # coding: utf-8 # @Author : Mr.K # @Software: PyCharm Community Edition # @Time : 2019/11/23 2:41 # @Description: #使用selenium实现浏览器模拟UI登录,配合unittest框架实现UI功能测试 import time import unittest from congfig import * import HTMLTestReportCN from bs4 import BeautifulSoup from selenium import webdrive...
Python
zaydzuhri_stack_edu_python
function save_distribution self filename begin save distribution filename end function
def save_distribution(self,filename): torch.save(self.distribution,filename)
Python
nomic_cornstack_python_v1
class Solution extends object begin function findDuplicate self paths begin string :type paths: List[str] :rtype: List[List[str]] set dict = dict set result = list for path in paths begin set left = 0 set right = 0 set white = list for i in range length path begin if path at i == string begin append white i end if ...
class Solution(object): def findDuplicate(self, paths): """ :type paths: List[str] :rtype: List[List[str]] """ dict = {} result=[] for path in paths: left = 0 right = 0 white = [] for i in range(len(path...
Python
zaydzuhri_stack_edu_python
function degree_preserving_mutation network maximum=0 def_mutation=false begin import numpy as num import logging set adj = adjacency set n_nodes = length adj debug string Adjacency Matrix: debug adj if maximum == 0 begin set maximum = 10 * length adj ^ 2 end set columns = sum axis=0 set rows = sum axis=1 set colsnotze...
def degree_preserving_mutation(network, maximum = 0, def_mutation = False): import numpy as num import logging adj = network.adjacency n_nodes = len(adj) logging.debug( "Adjacency Matrix:") logging.debug( adj) if maximum == 0: maximum = 10*len(adj)**2 columns = ad...
Python
nomic_cornstack_python_v1
string Custom exceptions class CustomException extends Exception begin string The base class of all custom exceptions pass end class class NoPrevRequestError extends CustomException begin string Raised when NX-API hasn't been called. pass end class class HttpError extends CustomException begin string Raised when HTTP r...
"""Custom exceptions""" class CustomException(Exception): """The base class of all custom exceptions""" pass class NoPrevRequestError(CustomException): """Raised when NX-API hasn't been called.""" pass class HttpError(CustomException): """Raised when HTTP response code != 200.""" pass cla...
Python
zaydzuhri_stack_edu_python
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import json import requests import plotly.graph_objects as go from dash.dependencies import Input , Output set app = call Dash __name__ meta_tags=list dict string name string viewport ; string content string width=dev...
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import json import requests import plotly.graph_objects as go from dash.dependencies import Input, Output app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}]...
Python
zaydzuhri_stack_edu_python
from PIL import Image import numpy as np import tensorflow as tf import random comment Parameters # comment set the directory name of your target-dataset here for dataset in list string voc07 string voc12 string ca101 string ca256 string mit67 string stCAR string cub200 string nwOB string stACT string fl102 begin for p...
from PIL import Image import numpy as np import tensorflow as tf import random ######################## # Parameters # ######################## for dataset in ['voc07', 'voc12', 'ca101', 'ca256', 'mit67', 'stCAR', 'cub200', 'nwOB', 'stACT', 'fl102']: # set the directory name of your target-dataset here for ...
Python
zaydzuhri_stack_edu_python
async function get_example self request=none name=none filter=none retry=DEFAULT timeout=DEFAULT metadata=tuple begin comment Create or coerce a protobuf request object. comment Quick check: If we got a request object, we should *not* have comment gotten any keyword arguments that map to the request. set has_flattened_...
async def get_example( self, request: Optional[Union[data_labeling_service.GetExampleRequest, dict]] = None, *, name: Optional[str] = None, filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.metho...
Python
nomic_cornstack_python_v1
function _ratio_enum anchor ratios begin set tuple w h x_ctr y_ctr = call _whctrs anchor set size = w * h set size_ratios = size / ratios set ws = round square root size_ratios set hs = round ws * ratios set anchors = call _mkanchors ws hs x_ctr y_ctr return anchors end function
def _ratio_enum(anchor, ratios): w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
Python
nomic_cornstack_python_v1
comment Mohamed Kharaev 43121144 & Ziyuan Zhang 18658215. Lab Section 7 print string <------- 1 -------> function test_number num sign begin string returns True if the number has the property indicated by the string, and False if it doesn't set lst = list string even string odd string positive string negative if sign n...
#Mohamed Kharaev 43121144 & Ziyuan Zhang 18658215. Lab Section 7 print("<------- 1 ------->") def test_number(num: int, sign: str) -> bool: '''returns True if the number has the property indicated by the string, and False if it doesn't''' lst = ["even", 'odd', 'positive', 'negative'] if sign n...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from chapter01.GCD import GCD class TestGCD extends TestCase begin function test_GCD self begin set tests = tuple tuple 2835 95985 405 tuple 3064 47109 383 tuple 25047 33143 253 tuple 4164 91608 4164 tuple 77316 90202 12886 tuple 41492 29520 164 tuple 75750 29400 150 tuple 5359 68735 233 t...
from unittest import TestCase from chapter01.GCD import GCD class TestGCD(TestCase): def test_GCD(self): tests = ((2835, 95985, 405), (3064, 47109, 383), (25047, 33143, 253), (4164, 91608, 4164), (77316, 90202, 12886), (41492, 29520, 164), (75750, 29400, 150), (5359, 687...
Python
zaydzuhri_stack_edu_python
function __init__ self real_part imaginary_part begin set real = real_part set imaginary = imaginary_part end function
def __init__(self, real_part, imaginary_part): self.real = real_part self.imaginary = imaginary_part
Python
nomic_cornstack_python_v1
for _ in range N begin append red list map int split input end for _ in range N begin append blue list map int split input end set match = list for i in red begin append match list comprehension i at 0 < j at 0 and i at 1 < j at 1 for j in blue end set num = 0 while sum list comprehension sum i for i in match > 0 begi...
for _ in range(N): red.append(list(map(int, input().split()))) for _ in range(N): blue.append(list(map(int, input().split()))) match = [] for i in red: match.append([i[0]<j[0] and i[1]<j[1] for j in blue]) num = 0 while sum([sum(i) for i in match]) > 0: a = match.index(min(match)) ...
Python
zaydzuhri_stack_edu_python
from bad_guy import * from good_guy import * from control_panel import * comment Initialize pygame call init comment Define constants for the screen width and height set SCREEN_WIDTH = 800 set SCREEN_HEIGHT = 600 comment all related to player set surf_width = 94 set surf_height = 63 comment Create the screen object com...
from bad_guy import * from good_guy import * from control_panel import * # Initialize pygame pygame.init() # Define constants for the screen width and height SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 # all related to player surf_width = 94 surf_height = 63 # Create the screen object # The size is det...
Python
zaydzuhri_stack_edu_python
function list_folder self folder_id=none begin string Request a list of files and folders in specified folder. Note: if folder_id is not provided, ``Home`` folder will be listed Args: folder_id (:obj:`str`, optional): id of the folder to be listed. Returns: dict: dictionary containing only two keys ("folders", "files")...
def list_folder(self, folder_id=None): """Request a list of files and folders in specified folder. Note: if folder_id is not provided, ``Home`` folder will be listed Args: folder_id (:obj:`str`, optional): id of the folder to be listed. Returns: dic...
Python
jtatman_500k
function listAPIPlugins begin return filter isAPIBasedPlugin call listExistingPlugins end function
def listAPIPlugins(): return filter(Subliminal.isAPIBasedPlugin, Subliminal.listExistingPlugins())
Python
nomic_cornstack_python_v1
function SetTimelineName self timeline_name begin set _timeline_name = timeline_name info format string Timeline name: {0:s} _timeline_name end function
def SetTimelineName(self, timeline_name): self._timeline_name = timeline_name logger.info('Timeline name: {0:s}'.format(self._timeline_name))
Python
nomic_cornstack_python_v1
function calculate_percentage_increase begin comment Constants set width_decrease_percentage = 0.2 set area_increase_multiplier = 1.1199999999999999 comment Calculate new area multiplier set new_area_multiplier = area_increase_multiplier / 1 - width_decrease_percentage comment Calculate length increase percentage set l...
def calculate_percentage_increase(): # Constants width_decrease_percentage = 0.20 area_increase_multiplier = 1.1199999999999999 # Calculate new area multiplier new_area_multiplier = area_increase_multiplier / (1 - width_decrease_percentage) # Calculate length increase percentage le...
Python
dbands_pythonMath
if N % 2 == 1 begin set N = N - 7 end if N % 4 == 2 begin set N = N - 14 end if N % 4 == 0 and N >= 0 begin print string Yes end else begin print string No end
if N%2==1: N = N-7 if N%4==2: N = N-14 if (N%4==0)and(N>=0): print("Yes") else: print("No")
Python
zaydzuhri_stack_edu_python
function read_from_file filename mode begin try begin set f = open filename string r + mode end except Exception as exc begin print exc end set data = read f close f return data end function
def read_from_file(filename, mode): try: f = open(filename, "r" + mode) except Exception as exc: print(exc) data = f.read() f.close() return data
Python
nomic_cornstack_python_v1
function _poll self begin try begin set _q = string while _ser and is_open begin function read_notification begin assert length _q <= 1 if not _q begin set _q = decode read _ser 1 end if not _q begin return tuple none none _q end if not starts with _eol _q begin set tuple ret _q = tuple _q string return tuple none no...
def _poll(self): try: self._q = "" while self._ser and self._ser.is_open: def read_notification(): assert len(self._q) <= 1 if not self._q: self._q = self._ser.read(1).decode() if not sel...
Python
nomic_cornstack_python_v1
import json import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn comment %pylab inline class Referrals extends object begin function __init__ self begin set user_df = read csv string ../data/u.csv sep=string , error_bad_lines=false dtype=dict string UserID string object ; string SourceU...
import json import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn # %pylab inline class Referrals(object): def __init__(self): self.user_df = pd.read_csv('../data/u.csv', sep=',', error_bad_lines=False,...
Python
zaydzuhri_stack_edu_python
function _set_state self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=state is_container=string container yang_name=string state parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true extensions=none namespace=str...
def _set_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass( v, base=state.state, is_container="container", yang_name="state", parent=self, path...
Python
nomic_cornstack_python_v1
function allow_migrate self db app_label model_name=none **hints begin return true end function
def allow_migrate(self, db, app_label, model_name=None, **hints): return True
Python
nomic_cornstack_python_v1
from django.db import models comment Create your models here. class VehicleType extends Model begin set name = call CharField max_length=32 set max_capacity = call PositiveIntegerField function __str__ self begin return name end function end class class Vehicle extends Model begin set name = call CharField max_length=3...
from django.db import models # Create your models here. class VehicleType(models.Model): name = models.CharField(max_length=32) max_capacity = models.PositiveIntegerField() def __str__(self) -> str: return self.name class Vehicle(models.Model): name = models.CharField(max_length=32) pa...
Python
zaydzuhri_stack_edu_python
function makeInserts self tbl columns rows begin set lines = list append lines string INSERT ALL set stmt = format string INTO "{}" ({}) tbl join string , list comprehension string " + name + string " for tuple name *_ in columns set fmt = format string VALUES ({}) join string , list comprehension if expression t in s...
def makeInserts(self, tbl, columns, rows): lines = [] lines.append("INSERT ALL") stmt = ' INTO "{}" ({})'.format( tbl, ", ".join(['"'+name+'"' for name, *_ in columns]) ) fmt = ' VALUES ({})'.format( ", ".join(["{...
Python
nomic_cornstack_python_v1
function mass_stomp query ts dot_first dot_prev index mean std begin set m = length query set dot = call dot_product_stomp ts m dot_first dot_prev index set res = 2 * m * 1 - dot - m * mean at index * mean / m * std at index * std comment Return both the MASS calculation and the dot product return tuple res dot end fun...
def mass_stomp(query, ts, dot_first, dot_prev, index, mean, std): m = len(query) dot = dot_product_stomp(ts, m, dot_first, dot_prev, index) res = 2 * m * (1 - (dot - m * mean[index] * mean) / (m * std[index] * std)) # Return both the MASS calculation and the dot product return res, dot
Python
nomic_cornstack_python_v1
function _on_new_data_received self data begin string Gets called whenever we get a whole new XML element from kik's servers. :param data: The data received (bytes) if data == b' ' begin comment Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's send it back. call call_soon_threadsafe s...
def _on_new_data_received(self, data: bytes): """ Gets called whenever we get a whole new XML element from kik's servers. :param data: The data received (bytes) """ if data == b' ': # Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's ...
Python
jtatman_500k
function solution numbers begin set s = set for i in range length numbers - 1 begin for j in range i + 1 length numbers begin add s numbers at i + numbers at j end end return list sorted s end function set n = list 1 3 5 2 3 print call solution n
def solution(numbers): s = set() for i in range(len(numbers)-1): for j in range(i + 1, len(numbers)): s.add(numbers[i] + numbers[j]) return list(sorted(s)) n = [1,3,5,2,3] print(solution(n))
Python
zaydzuhri_stack_edu_python
import numpy as np import math from scipy import spatial set R = array list list 5 3 0 1 list 4 0 0 1 list 1 1 0 5 list 1 0 0 4 list 0 1 5 4 set tuple user item = shape comment alpha is a learning parameter, beta is for regularization. as iterations increase, a more fine tuned recomm. is obtained set tuple alpha beta i...
import numpy as np import math from scipy import spatial R = np.array([ [5, 3, 0, 1], [4, 0, 0, 1], [1, 1, 0, 5], [1, 0, 0, 4], [0, 1, 5, 4], ]) user,item=R.shape alpha,beta,iterations=0.1,0.01,20 #alpha is a learning parameter, beta is for regularization. as iterations increase, a more fine tu...
Python
zaydzuhri_stack_edu_python
function from_start self begin return time - start end function
def from_start(self): return time.time() - self.start
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import time from datetime import timedelta import os comment Functions and classes for loading and using the Inception model. import inception comment We use Pretty Tensor to define the new classifier. import prettytensor as pt import cifar10 fr...
import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import time from datetime import timedelta import os # Functions and classes for loading and using the Inception model. import inception # We use Pretty Tensor to define the new classifier. import prettytensor as pt import cifar10 from cifar...
Python
zaydzuhri_stack_edu_python
function authenticate_osm username password begin set login_payload = dict set request = call Request string https:// + OSM_API + string /login set cookies = call CookieJar set opener = call build_opener call HTTPCookieProcessor cookies set response_tokenfetch = open request set html = read response_tokenfetch set htm...
def authenticate_osm(username,password): login_payload = {} request = urllib2.Request('https://' + settings.OSM_API + '/login') cookies = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies)) response_tokenfetch = opener.open(request) html = response_tokenfe...
Python
nomic_cornstack_python_v1
function open self filename mode=string r bufsize=- 1 begin set sftp_client = call open_sftp return open filename mode bufsize end function
def open(self, filename, mode='r', bufsize=-1): sftp_client = self.open_sftp() return sftp_client.open(filename, mode, bufsize)
Python
nomic_cornstack_python_v1
set a = list 1 4 9 16 25 36 49 64 81 100 set evens = list comprehension i for i in a if i % 2 == 0 print evens
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] evens = [i for i in a if (i%2) == 0] print(evens)
Python
zaydzuhri_stack_edu_python
function add_config serial begin set baudrate = BAUDRATE set bytesize = BYTESIZE set parity = PARITY set stopbits = STOPBITS return serial end function
def add_config(serial): serial.baudrate = BAUDRATE serial.bytesize = BYTESIZE serial.parity = PARITY serial.stopbits = STOPBITS return serial
Python
nomic_cornstack_python_v1
comment 水仙花数 set sxh = list for i in range 100 1000 begin set s = 0 set m = list string i for n in m begin set s = s + integer n ^ length m end if i == s begin append sxh i end end print string 100-999中的水仙花数有: end=string print sxh
# 水仙花数 sxh=[] for i in range(100,1000): s = 0 m = list(str(i)) for n in m: s+= (int(n))**len(m) if i==s: sxh.append(i) print("100-999中的水仙花数有:",end="") print(sxh)
Python
zaydzuhri_stack_edu_python
function get_object_id self pos begin set object_id = call get_object_id self pos if object_id == - 1 begin comment Try searching remove buttons if call collide_on_remove pos is not none begin set object_id = REMOVE end end return object_id end function
def get_object_id(self, pos): object_id = ScreenGUI.get_object_id(self, pos) if object_id == -1: # Try searching remove buttons if self.product_displays.collide_on_remove(pos) is not None: object_id = self.ids.REMOVE return object_id
Python
nomic_cornstack_python_v1
function multiget self pairs **params begin string Fetches many keys in parallel via threads. :param pairs: list of bucket_type/bucket/key tuple triples :type pairs: list :param params: additional request flags, e.g. r, pr :type params: dict :rtype: list of :class:`RiakObjects <riak.riak_object.RiakObject>`, :class:`Da...
def multiget(self, pairs, **params): """Fetches many keys in parallel via threads. :param pairs: list of bucket_type/bucket/key tuple triples :type pairs: list :param params: additional request flags, e.g. r, pr :type params: dict :rtype: list of :class:`RiakObjects <ria...
Python
jtatman_500k
function _create_normal_request self url begin set request = get factory url set user = call AnonymousUser set middleware = call SessionMiddleware call process_request request save call process_request request return request end function
def _create_normal_request(self, url): request = self.factory.get(url) request.user = AnonymousUser() middleware = SessionMiddleware() middleware.process_request(request) request.session.save() MakoMiddleware().process_request(request) return request
Python
nomic_cornstack_python_v1
function extend_action_space self name begin assert name not in _known_actions msg string Cannot register an action name twice set _known_actions at name = length _known_actions return _known_actions at name end function
def extend_action_space(self, name: str) -> int: assert ( name not in self._known_actions ), "Cannot register an action name twice" self._known_actions[name] = len(self._known_actions) return self._known_actions[name]
Python
nomic_cornstack_python_v1
comment https://www.codewars.com/kata/55908aad6620c066bc00002a comment Check to see if a string has the same amount of 'x's and 'o's. The method must comment return a boolean and be case insensitive. The string can contain any char. function xo s begin set x = 0 set o = 0 for l in s begin if string x == lower l begin s...
# https://www.codewars.com/kata/55908aad6620c066bc00002a # Check to see if a string has the same amount of 'x's and 'o's. The method must # return a boolean and be case insensitive. The string can contain any char. def xo(s): x = 0 o = 0 for l in s: if 'x' == l.lower(): x += 1 i...
Python
zaydzuhri_stack_edu_python
function save_yaml_config config path begin with open path string w as outfile begin dump config outfile default_flow_style=false end end function
def save_yaml_config(config, path): with open(path, 'w') as outfile: yaml.dump(config, outfile, default_flow_style=False)
Python
nomic_cornstack_python_v1
function setup begin call fullScreen call background 165 42 42 end function function main_menu begin global page if page == 0 begin call textSize 200 call fill 0 call text string THE 100 200 call text string SURVIVOR 300 400 comment start button call fill 139 0 0 call rect width / 2 - 150 450 300 100 call textSize 100 ...
def setup(): fullScreen() background(165,42,42) def main_menu(): global page if page == 0: textSize(200) fill(0) text("THE", 100, 200) text("SURVIVOR", 300, 400) #start button fill(139, 0, 0) rect(width/2-150, 450, 300, 100) textSize(100) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment utility function to check if a character is a valid infix operator function isOperator c begin if c == string + or c == string * or c == string / or c == string - or c == string ^ begin return true end else begin return false end end function comment Function to convert infix to pos...
#!/usr/bin/env python # utility function to check if a character is a valid infix operator def isOperator(c): if (c == '+' or c == '*' or c == '/' or c == '-' or c == '^'): return True else: return False # Function to convert infix to postfix expression def infixToPostfix(exp): # Iterate through expres...
Python
flytech_python_25k
function modify_index_return_self self axis startend value begin call modify_index axis startend value return self end function
def modify_index_return_self(self, axis, startend, value): self.modify_index(axis, startend, value) return self
Python
nomic_cornstack_python_v1
comment (EXERCÍCIOS EM RESOLUÇÃO - ATUALIZAÇÃO A MEDIDA DO POSSÍVEL:)) comment Exercícios Numpy (Respostas na Semana #3) comment 1- Importe numpy como ‘np’ e imprima o número da versão. import numpy as np comment print("versão: ", np.version.version) comment 2- Crie uma matriz 1D com números de 0 a 9 comment Saída dese...
# (EXERCÍCIOS EM RESOLUÇÃO - ATUALIZAÇÃO A MEDIDA DO POSSÍVEL:)) #Exercícios Numpy (Respostas na Semana #3) #1- Importe numpy como ‘np’ e imprima o número da versão. import numpy as np # print("versão: ", np.version.version) # 2- Crie uma matriz 1D com números de 0 a 9 # Saída desejada: # array([0,...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict set lucky = default dictionary lambda -> 13 lucky at string a set lucky at string b = lucky at string c print dictionary lucky
from collections import defaultdict lucky = defaultdict(lambda: 13) lucky['a'] lucky['b'] = lucky['c'] print(dict(lucky))
Python
zaydzuhri_stack_edu_python
import cv2 from pylab import * comment Helper function required to display the image at regular modification intervals function show im begin image show string Image im call waitKey 0 call destroyAllWindows end function comment Function required to pad the image prior to performing the DCT operation function imgPad im ...
import cv2 from pylab import * # Helper function required to display the image at regular modification intervals def show(im): cv2.imshow("Image", im) cv2.waitKey(0) cv2.destroyAllWindows() # Function required to pad the image prior to performing the DCT operation def imgPad(im): rows, cols, ch = i...
Python
zaydzuhri_stack_edu_python
function print_matrix name matrix stream=stdout begin tuple print ? stream format string {} [ name for i in range length matrix begin set vec_str = join string list comprehension string x for x in matrix at i set suffix = if expression i < length matrix - 1 then string else string ] tuple print ? stream format string...
def print_matrix(name, matrix, stream=sys.stdout): print >> stream, '{} ['.format(name) for i in range(len(matrix)): vec_str = ' '.join([str(x) for x in matrix[i]]) suffix = '' if i < len(matrix) - 1 else ' ]' print >> stream, ' {}{}'.format(vec_str, suffix)
Python
nomic_cornstack_python_v1
function ticket_edit request ticket_id begin set ticket = call get_object_or_404 Ticket code=ticket_id set categoria = ticket_category set title = call _ string Modifica ticket set sub_title = ticket set allegati = call get_allegati_dict set path_allegati = call get_path call get_folder set form = call compiled_form fi...
def ticket_edit(request, ticket_id): ticket = get_object_or_404(Ticket, code=ticket_id) categoria = ticket.input_module.ticket_category title = _("Modifica ticket") sub_title = ticket allegati = ticket.get_allegati_dict() path_allegati = get_path(ticket.get_folder()) form = ticket.compiled_f...
Python
nomic_cornstack_python_v1
comment Minimal network string The following undirected network consists of seven vertices and twelve edges with a total weight of 243. The same network can be represented by the matrix below. A B C D E F G A - 16 12 21 - - - B 16 - - 17 20 - - C 12 - - 28 - 31 - D 21 17 28 - 18 19 23 E - 20 - 18 - - 11 F - - 31 19 - -...
# Minimal network """ The following undirected network consists of seven vertices and twelve edges with a total weight of 243. The same network can be represented by the matrix below. A B C D E F G A - 16 12 21 - - - B 16 - - 17 20 - - C 12 - - 28 - 31 - D 21 17 28 - 18 19 23 E - 20 - 18 - - 11 F...
Python
zaydzuhri_stack_edu_python
function get_most_recent_saturday begin set today = today comment today.weekday() is 0-indexed starting on Monday (e.g. Thu is 3) comment to get most recent Saturday, we first get nearest Monday, comment then we subtract 2 extra days set offset = call weekday + 2 % 7 set last_sat = today - time delta days=offset return...
def get_most_recent_saturday(): today = date.today() # today.weekday() is 0-indexed starting on Monday (e.g. Thu is 3) # to get most recent Saturday, we first get nearest Monday, # then we subtract 2 extra days offset = (today.weekday()+2) % 7 last_sat = today - timedelta(days=offset) return...
Python
nomic_cornstack_python_v1
string This is a program to solve the farmer, fox, goose, grain problem where a farmer needs needs to get all 3 items across a river without leaving the fox and the goose without him or the goose and the grain without him. set farmer = string farmer set fox = string fox set goose = string goose set grain = string grain...
""" This is a program to solve the farmer, fox, goose, grain problem where a farmer needs needs to get all 3 items across a river without leaving the fox and the goose without him or the goose and the grain without him. """ farmer = "farmer" fox = "fox" goose = "goose" grain = "grain" right...
Python
zaydzuhri_stack_edu_python
function move p U begin set U = U % length p return list p at slice - U : : + list p at slice : - U : end function if __name__ == string __main__ begin set p = range 5 for i in range - 6 7 begin print i move p i end end
def move(p, U): U %= len(p) return list(p[-U:]) + list(p[:-U]) if __name__ == '__main__': p = range(5) for i in range(-6, 7): print(i, move(p, i))
Python
zaydzuhri_stack_edu_python
function get_icon_path filepath ico_name begin set ui_path = parent set icon_path = call joinpath string ico ico_name return string icon_path end function
def get_icon_path(filepath: str, ico_name: str): ui_path = Path(filepath).parent icon_path = ui_path.joinpath("ico", ico_name) return str(icon_path)
Python
nomic_cornstack_python_v1
comment _*_ coding:utf-8_*_ comment Author: Ace Huang comment Time: 9/27/20 11:44 PM comment File: Question1.py class Solution begin function twoSum self nums target begin function v1 nums target begin string 暴力 :param nums: :param target: :return: set _index_i = - 1 for _i in nums begin set _index_i = _index_i + 1 set...
# _*_ coding:utf-8_*_ # Author: Ace Huang # Time: 9/27/20 11:44 PM # File: Question1.py class Solution: def twoSum(self, nums: list[int], target: int) -> list[int]: def v1(nums: list[int], target: int) -> list[int]: """ 暴力 :param nums: :param target: ...
Python
zaydzuhri_stack_edu_python
string The Enemy class import pygame , random from pygame.sprite import Sprite from config import * from Bullet import BulletFixed class Enemy extends Sprite begin function __init__ self begin call __init__ set image = call convert_alpha call set_colorkey WHITE set rect = call get_rect center=tuple random integer integ...
"""The Enemy class""" import pygame, random from pygame.sprite import Sprite from config import * from Bullet import BulletFixed class Enemy(Sprite): def __init__(self): super(Enemy, self).__init__() self.image = pygame.image.load(enemyImg).convert_alpha() self.image.set_colorkey(WHITE) ...
Python
zaydzuhri_stack_edu_python
from typing import List from config import app_key from database import db from schemas import Review , ReviewIndex , ReviewUpdate from argon2 import PasswordHasher from argon2.exceptions import Argon2Error from itsdangerous import BadTimeSignature , TimestampSigner set hasher = call PasswordHasher set signer = call Ti...
from typing import List from .config import app_key from .database import db from .schemas import Review, ReviewIndex, ReviewUpdate from argon2 import PasswordHasher from argon2.exceptions import Argon2Error from itsdangerous import BadTimeSignature, TimestampSigner hasher = PasswordHasher() signer = TimestampSigner...
Python
zaydzuhri_stack_edu_python
import argparse import numpy as np from train import train from data_loader import load_data class Main begin function rippleNet self begin seed 555 set parser = call ArgumentParser call add_argument string --dataset type=str default=string movie help=string dataset to use call add_argument string --batch_size type=int...
import argparse import numpy as np from train import train from data_loader import load_data class Main: def rippleNet(self): np.random.seed(555) parser = argparse.ArgumentParser() parser.add_argument('--dataset', type=str, default='movie', help='dataset to use') parser.add_argumen...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment https://raspberrytips.nl/tm1637-4-digit-led-display-raspberry-pi/ import sys import time import datetime import RPi.GPIO as GPIO import tm1637 import math comment CLK -> GPIO23 (Pin 16) comment DI0 -> GPIO24 (Pin 18) comment Display = tm1637.TM1637(23,24,tm1637.BRIGHT_TYPICAL) comm...
# -*- coding: utf-8 -*- # https://raspberrytips.nl/tm1637-4-digit-led-display-raspberry-pi/ import sys import time import datetime import RPi.GPIO as GPIO import tm1637 import math #CLK -> GPIO23 (Pin 16) #DI0 -> GPIO24 (Pin 18) #Display = tm1637.TM1637(23,24,tm1637.BRIGHT_TYPICAL) #Display.Clear() #Display2.Clear...
Python
zaydzuhri_stack_edu_python
comment Decorators: preliminaries function outer_fun begin set message = string hi function inner_fun begin print message end function return inner_fun end function set my_func = call outer_fun call my_func function outer_fun2 msg begin set message = msg function inner_fun begin print message end function return inner_...
# Decorators: preliminaries def outer_fun(): message = "hi" def inner_fun(): print(message) return inner_fun my_func = outer_fun() my_func() def outer_fun2(msg): message = msg def inner_fun(): print(message) return inner_fun hi_fun = outer_fun2('Hi') bye_fun = outer_fun2("By...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python3 from __future__ import annotations import random from bisect import bisect from dataclasses import dataclass from enum import Enum , auto from typing import Callable , List , Optional , Tuple decorator dataclass class GameState begin set cost : float = 10.0 set output : float = 2.0 set mo...
#! /usr/bin/env python3 from __future__ import annotations import random from bisect import bisect from dataclasses import dataclass from enum import Enum, auto from typing import Callable, List, Optional, Tuple @dataclass class GameState: cost: float = 10.0 output: float = 2.0 morale: floa...
Python
zaydzuhri_stack_edu_python
set tuple n m = split input if n == m begin print m end else if n > m begin print n end else begin print m end
n,m=input().split() if(n==m): print(m) elif(n>m): print(n) else: print(m)
Python
zaydzuhri_stack_edu_python
function kappa_predict sequence network=brnn_network device=device encoding_scheme=encoding_scheme begin comment change sequence to ADK seq set sequence = call change_for_input sequence comment set seq_vector equal to converted amino acid sequence that is a PyTorch tensor of one-hot vectors set seq_vector = call one_ho...
def kappa_predict(sequence, network=brnn_network, device=device, encoding_scheme=encoding_scheme): # change sequence to ADK seq sequence = change_for_input(sequence) # set seq_vector equal to converted amino acid sequence that is a PyTorch tensor of one-hot vectors seq_vector = encode_sequence.one_ho...
Python
nomic_cornstack_python_v1
import pandas as pd from FileLoader import FileLoader function youngestFellah data val begin print string 1 head data set dataY = data at Year == val print string 2 head dataY print string 3 head data return dict string M min ; string F min end function if __name__ == string __main__ begin set loader = call FileLoader ...
import pandas as pd from FileLoader import FileLoader def youngestFellah(data, val): print("1", data.head()) dataY = data[data.Year == val] print("2", dataY.head()) print("3", data.head()) return { 'M': dataY[dataY.Sex == 'M'].Age.min(), 'F': dataY[dataY.Sex == 'F'].Age.min() }...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self data begin set data = data set left = none set right = none end function end class class Height begin function __init__ self begin set h = 0 end function end class function diameterOpt root height begin set lh = call Height set rh = call Height if root is none begin set h = 0 ret...
class Node: def __init__(self,data): self.data = data self.left = self.right = None class Height: def __init__(self): self.h = 0 def diameterOpt(root,height): lh = Height() rh = Height() if root is None: height.h = 0 return 0 lDiameter ...
Python
zaydzuhri_stack_edu_python
string " This module implements an directed Graph API. @author a.k from typing import List , Tuple , Iterable from data_structures.LinkedList import SinglyLinkedList from data_structures.graphs.graph_utils import Edge , GeneralGraph , dfs_print , bfs_print class DGraph extends GeneralGraph begin function __init__ self ...
"""" This module implements an directed Graph API. @author a.k """ from typing import List, Tuple, Iterable from data_structures.LinkedList import SinglyLinkedList from data_structures.graphs.graph_utils import Edge, GeneralGraph, dfs_print, bfs_print class DGraph(GeneralGraph): def __init__(self, V: int): ...
Python
zaydzuhri_stack_edu_python
comment Import module to read csv import csv set colours = list comment Define a function that reads a csv and converts to list function read_csv_file filepath begin with open filepath as csv_file begin set reader = reader csv_file for line in reader begin append colours line end return colours end end function call r...
# Import module to read csv import csv colours = [] # Define a function that reads a csv and converts to list def read_csv_file(filepath): with open(filepath) as csv_file: reader = csv.reader(csv_file) for line in reader: colours.append(line) return colours read_csv_file("colo...
Python
zaydzuhri_stack_edu_python
function main begin string 用来控制整个程序的流程 end function comment 1.创建老王对象 comment 2.创建一个枪对象 comment 3.创建一个弹夹对象 comment 4.创建一些子弹 comment 5.创建一个敌人 comment 6.老王把子弹安装到弹夹中 comment 7.老王把弹夹安装到枪中 comment 8.老王拿枪 comment 9.老王开枪打敌人 comment 老王开枪打敌人 if __name__ == string __main__ begin call main end
def main(): """用来控制整个程序的流程""" #1.创建老王对象 #2.创建一个枪对象 #3.创建一个弹夹对象 #4.创建一些子弹 #5.创建一个敌人 #6.老王把子弹安装到弹夹中 #7.老王把弹夹安装到枪中 #8.老王拿枪 #9.老王开枪打敌人 #老王开枪打敌人 if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
from __future__ import print_function comment tf-idf from pyspark import SparkContext from pyspark.sql import SparkSession from pyspark.mllib.feature import HashingTF , IDF comment KMeans from numpy import array from math import sqrt from pyspark.mllib.clustering import KMeans , KMeansModel if __name__ == string __main...
from __future__ import print_function # tf-idf from pyspark import SparkContext from pyspark.sql import SparkSession from pyspark.mllib.feature import HashingTF, IDF # KMeans from numpy import array from math import sqrt from pyspark.mllib.clustering import KMeans, KMeansModel if __name__ == "__main__": k = 3 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- set __author__ = string daehakim set __email__ = string kdhht5022@gmail.com string slicing을 사용하는 예제 import tensorflow as tf from keras import backend as K set state = call Variable 0 name=string counter set one = call constant 1 set new_value = add tf state on...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "daehakim" __email__ = "kdhht5022@gmail.com" """ slicing을 사용하는 예제 """ import tensorflow as tf from keras import backend as K state = tf.Variable(0, name="counter") one = tf.constant(1) new_value = tf.add(state, one) added_value = tf.assign(state, new...
Python
zaydzuhri_stack_edu_python
function description self begin return _description end function
def description(self): return self._description
Python
nomic_cornstack_python_v1
class CheeseSauce begin function __init__ self cheese_type milk_type saltiness begin set cheese_type = cheese_type set milk_type = milk_type set saltiness = saltiness end function function set_saltiness self saltiness begin set saltiness = saltiness end function end class set cheese_sauce = call CheeseSauce string ched...
class CheeseSauce: def __init__(self, cheese_type, milk_type, saltiness): self.cheese_type = cheese_type self.milk_type = milk_type self.saltiness = saltiness def set_saltiness(self, saltiness): self.saltiness = saltiness cheese_sauce = CheeseSauce('cheddar', 'whole mi...
Python
jtatman_500k
string You will be given the location of a knight, and an end location. The knight can move in a "L" shape. "L" shape movement means that the knight can change it's `x` coordinate by 2 and it's `y` coordinate by 1 or it can change it's `y` coordinate by 2 and it's `x` coordinate by 1 (you can add and subtract from the ...
""" You will be given the location of a knight, and an end location. The knight can move in a "L" shape. "L" shape movement means that the knight can change it's `x` coordinate by 2 and it's `y` coordinate by 1 or it can change it's `y` coordinate by 2 and it's `x` coordinate by 1 (you can add and subtract from the ...
Python
zaydzuhri_stack_edu_python
string Notification structure class Notification begin function __init__ self notificationType text topic=string topicdata=string begin set _text = text set _topic = topic set _topicdata = topicdata set _notificationType = notificationType end function function getDict self begin string returns model as dict return di...
''' Notification structure ''' class Notification(): def __init__(self, notificationType, text, topic='', topicdata=''): self._text = text self._topic = topic self._topicdata = topicdata self._notificationType = notificationType def getDict(self): ''' returns m...
Python
zaydzuhri_stack_edu_python
function get_boto3_doc_link self *parts begin return join string . list boto3_doc_link *parts end function
def get_boto3_doc_link(self, *parts: str) -> str: return ".".join([self.boto3_doc_link, *parts])
Python
nomic_cornstack_python_v1
function us10 dt1 dt2 spouse fam_id begin try begin set date_diff = call get_dates_difference date_time_obj date_time_obj if type date_diff is str begin raise ValueError end if date_diff >= 14 begin return false end if date_diff < 14 begin return true end end except any begin print string Data Error: Birth date ' { dt1...
def us10(dt1, dt2, spouse, fam_id): try: date_diff = Date.get_dates_difference(dt1.date_time_obj, dt2.date_time_obj) if type(date_diff) is str: raise ValueError if date_diff >= 14: return False if date_diff < 14: ...
Python
nomic_cornstack_python_v1
function _permutation s r begin if length s == 1 begin append r s return r end for i in call _permutation s at slice 1 : : r begin append r i + s at 0 append r s at 0 + i end end function function sort_string s begin if not s begin return none end set r = list call _permutation s r return r end function function per...
def _permutation(s, r): if len(s) == 1: r.append(s) return r for i in _permutation(s[1:], r): r.append(i+s[0]) r.append(s[0]+i) def sort_string(s): if not s: return None r = [] _permutation(s, r) return r def permutation(s): if not s:...
Python
zaydzuhri_stack_edu_python
comment Adds rough 'seasonality' info to data set, as the data is temporal comment and appears to have some sort of pattern... let the regression decide this. set f = open string test_times.csv string wb set g = open string test.csv string rb set count = 0 comment divides each day into 6 periods set period = 1091440 co...
################## # Adds rough 'seasonality' info to data set, as the data is temporal # and appears to have some sort of pattern... let the regression decide this. ################ f=open('test_times.csv', 'wb') g = open('test.csv', 'rb') count = 0 period = 1091440 # divides each day into 6 periods # there ...
Python
zaydzuhri_stack_edu_python
set entrada = call raw_input set tuple t1 t2 t3 = split entrada set t1 = integer t1 set t2 = integer t2 set t3 = integer t3
entrada = raw_input() t1,t2,t3 = entrada.split() t1 = int(t1) t2 = int(t2) t3 = int(t3)
Python
zaydzuhri_stack_edu_python
comment !/usr/local/bin/python3.7 comment -*- coding: utf-8 -*- string Created on 2019-2-3 com.financial.ta.engine.TargetDayEngine -- shortdesc com.financial.ta.engine.TargetDayEngine is a description It defines classes_and_methods @author: Tux48 @version: 0.1 @copyright: 2019 organization_name. All rights reserved. @d...
#!/usr/local/bin/python3.7 #-*- coding: utf-8 -*- ''' Created on 2019-2-3 com.financial.ta.engine.TargetDayEngine -- shortdesc com.financial.ta.engine.TargetDayEngine is a description It defines classes_and_methods @author: Tux48 @version: 0.1 @copyright: 2019 organization_name. All rights reserve...
Python
zaydzuhri_stack_edu_python
function use_default_dict begin set color = default dictionary lambda -> string #000000 set color at string White = string #FFFFFF call pprint color at string White call pprint color at string Red end function
def use_default_dict(): color = defaultdict(lambda: "#000000") color["White"] = "#FFFFFF" pp.pprint(color["White"]) pp.pprint(color["Red"])
Python
nomic_cornstack_python_v1
function start engine_name source_lang target_lang **args begin set source_target_lang = string %s-%s % tuple source_lang target_lang if not exists path join path MOSESMODELS_HOME engine_name source_target_lang begin print string Mae angen llwytho'r peiriant i lawr.... call fetchengine engine_name source_lang target_la...
def start(engine_name, source_lang, target_lang, **args): source_target_lang = "%s-%s" % (source_lang, target_lang) if not os.path.exists(os.path.join(MOSESMODELS_HOME, engine_name, source_target_lang)): print("Mae angen llwytho'r peiriant i lawr....") fetchengine(engine_name, source_lang, target_lang, **args) ...
Python
nomic_cornstack_python_v1
function to_music21_time_signature time_signature begin set m21_time_signature = call M21TimeSignature string { numerator } / { denominator } set offset = time return m21_time_signature end function
def to_music21_time_signature( time_signature: TimeSignature, ) -> M21TimeSignature: m21_time_signature = M21TimeSignature( f"{time_signature.numerator}/{time_signature.denominator}" ) m21_time_signature.offset = time_signature.time return m21_time_signature
Python
nomic_cornstack_python_v1
function test_blank_category self begin call signup string Bo string Theo string Bo_theo5@example.com string Bo1995 string Bo1995 call login string Bo_theo5@example.com string Bo1995 set rv = call category string assert in b'Field must be between 1 and 50 characters long.' data end function
def test_blank_category(self): self.signup('Bo', 'Theo', 'Bo_theo5@example.com', 'Bo1995', 'Bo1995') self.login('Bo_theo5@example.com', 'Bo1995') rv = self.category('') self.assertIn(b'Field must be between 1 and 50 characters long.', rv.data)
Python
nomic_cornstack_python_v1
import Tkinter as tk class View extends Toplevel begin set settings = dict string bgcolor string #%02x%02x%02x % tuple 64 204 208 function __init__ self master CanvasScale begin call __init__ self master call protocol string WM_DELETE_WINDOW destroy call bind string <Configure> __resize set canvas = call Canvas self ba...
import Tkinter as tk class View(tk.Toplevel): settings = {'bgcolor' : '#%02x%02x%02x' % (64, 204, 208)} def __init__(self, master, CanvasScale): tk.Toplevel.__init__(self, master) self.protocol('WM_DELETE_WINDOW', self.master.destroy) self.bind("<Configure>", self.__resize) s...
Python
zaydzuhri_stack_edu_python
function links self links begin set _links = links end function
def links(self, links): self._links = links
Python
nomic_cornstack_python_v1
function list_directory self path begin try begin set list = list directory path end except OSError begin call send_error 404 string No permission to list directory return none end sort list key=lambda a -> lower a set r = list try begin set displaypath = unquote path errors=string surrogatepass end except UnicodeDeco...
def list_directory(self, path): try: list = os.listdir(path) except OSError: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) r = [] try: displaypath = urllib.parse.unquote(self....
Python
nomic_cornstack_python_v1
comment https://www.acmicpc.net/problem/11022 comment readline을 사용하기 위해 import합니다. from sys import stdin comment 첫째 줄에 테스트 케이스의 개수 T를 입력합니다. comment 정수형으로 변환합니다. set T = integer read line stdin comment 테스트 케이스의 개수 T만큼 반복합니다. for test_case_idx in range T begin comment A, B를 공백으로 구분해 입력합니다. comment 0 < A, B < 10 comment ...
# https://www.acmicpc.net/problem/11022 # readline을 사용하기 위해 import합니다. from sys import stdin # 첫째 줄에 테스트 케이스의 개수 T를 입력합니다. # 정수형으로 변환합니다. T = int(stdin.readline()) # 테스트 케이스의 개수 T만큼 반복합니다. for test_case_idx in range(T): # A, B를 공백으로 구분해 입력합니다. # 0 < A, B < 10 # 각각 정수형으로 변환합니다. A, B = map(int, stdin....
Python
zaydzuhri_stack_edu_python
import glob , os import cv2 import numpy as np comment Removes the ads function cleanImage image begin set inv = call bitwise_not image set kernel = call getStructuringElement MORPH_RECT tuple 2 2 set closed = call morphologyEx inv MORPH_CLOSE kernel set closed = call morphologyEx closed MORPH_OPEN kernel return closed...
import glob, os import cv2 import numpy as np #Removes the ads def cleanImage(image): inv = cv2.bitwise_not(image) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) closed = cv2.morphologyEx(inv, cv2.MORPH_CLOSE, kernel) closed = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel) return clos...
Python
zaydzuhri_stack_edu_python
from pydub import AudioSegment function remove_silence sound silence_threshold=- 20.0 chunk_size=100 begin string :param sound: :param silence_threshold: in dB :param chunk_size: in ms :return:returns the sound without silence method read each chunk if it is noise append it to the output assert chunk_size > 0 set index...
from pydub import AudioSegment def remove_silence(sound, silence_threshold=-20.0, chunk_size=100): ''' :param sound: :param silence_threshold: in dB :param chunk_size: in ms :return:returns the sound without silence method read each chunk if it is noise append it to the output ''' ...
Python
zaydzuhri_stack_edu_python
function docker_bridge_cidr self begin return get pulumi self string docker_bridge_cidr end function
def docker_bridge_cidr(self) -> Optional[str]: return pulumi.get(self, "docker_bridge_cidr")
Python
nomic_cornstack_python_v1
function request raw_method endpoint _id=none payload=none return_dict=false get_info=_get_required_info begin set method = upper raw_method set full_endpoint = endpoint if _id is not none begin set full_endpoint = full_endpoint + format string /{} _id end set request_string = format string {} /api/{} {} method full_en...
def request(raw_method, endpoint, _id=None, payload=None, return_dict=False, get_info=_get_required_info): method = raw_method.upper() full_endpoint = endpoint if _id is not None: full_endpoint += '/{}'.format(_id) request_string = '{} /api/{} {}'.format( method, full_endpoin...
Python
nomic_cornstack_python_v1
import controller as cnt import model as db import os import time function template begin call system string clear print string #################################### print string --------------PassWD---------------- print string #################################### print string end function if call check_password == tru...
import controller as cnt import model as db import os import time def template(): os.system("clear") print ("####################################") print ("--------------PassWD----------------") print ("####################################") print("\n") if db.check_password() == True: db.st...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu May 30 09:49:26 2019 @author: Matthijs Schrage set starting_state1 = list 1 2 3 4 0 5 7 8 6 set starting_state2 = list 5 8 0 7 6 4 1 2 3 set starting_state3 = list 6 5 2 0 9 3 1 7 8 set starting_state4 = list 0 3 6 5 2 4 9 7 8 set starting_state5 = list 1 2 3 8 0 4 7 ...
# -*- coding: utf-8 -*- """ Created on Thu May 30 09:49:26 2019 @author: Matthijs Schrage """ starting_state1 = [1, 2, 3, 4, 0, 5, 7, 8, 6] starting_state2 = [5, 8, 0, 7, 6, 4, 1, 2, 3] starting_state3 = [6, 5, 2, 0, 9, 3, 1, 7, 8] starting_state4 = [0, 3, 6, 5, 2, 4, 9, 7, 8] starting_state5 = [1, 2, 3, 8...
Python
zaydzuhri_stack_edu_python
function set_fill_color self color begin set color = color return self end function
def set_fill_color(self, color: tuple) -> Rectangle: self.fill.color = color return self
Python
nomic_cornstack_python_v1
comment python3 print string enter the nos : set a = integer input string first no: set b = integer input string second no: print format string the sum of two nos are: {} a + b
# python3 print("enter the nos :") a = int(input("first no:")) b = int(input("second no:")) print(" the sum of two nos are: {}".format(a + b))
Python
zaydzuhri_stack_edu_python
comment Constructiong Alternatif Country Rankings ############################ import pandas as pd set medals = read csv string medals01.csv comment 42 distinct events unique set wheather = read csv string wheather01.csv call idxmax call idxmax axis=string columns call idxmin axis=string columns comment Task 1 comment ...
############################ Constructiong Alternatif Country Rankings ############################ import pandas as pd medals = pd.read_csv('medals01.csv') medals['Sport'].unique() # 42 distinct events wheather = pd.read_csv('wheather01.csv') wheather.idxmax() wheather.T.idxmax(axis='columns') wheather.T.idxmin(ax...
Python
zaydzuhri_stack_edu_python
function get_queryset self begin set tuple lection_id _ = call get_lection return filter lection_id=lection_id end function
def get_queryset(self): lection_id, _ = self.get_lection() return Homework.objects.filter(lection_id=lection_id)
Python
nomic_cornstack_python_v1