code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function ProcessInput self events pressed_keys begin print string uh-oh, you didn't override this in the child class end function
def ProcessInput(self, events, pressed_keys): print("uh-oh, you didn't override this in the child class")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment Define your item pipelines here comment Don't forget to add your pipeline to the ITEM_PIPELINES setting comment See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import csv import codecs class Jobspider2Pipeline extends object begin function __init__ self begin set fi...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import csv import codecs class Jobspider2Pipeline(object): def __init__(self): self.file = codecs.open("tencent.c...
Python
zaydzuhri_stack_edu_python
from pyplasm import * set GRID = call COMP list call INSR PROD call AA QUOTE comment Piano terra set circle = call call CIRCLE 0.18 list 30 1 set column = call EXTRUDE list 1 circle 3.58 set columns = call STRUCT call nn 5 list column call t dist list 1 list 3.94 set columnOnBalcony = call call t dist list 2 list 7.55 ...
from pyplasm import * GRID = COMP([INSR(PROD),AA(QUOTE)]) #Piano terra circle = CIRCLE(0.18)([30,1]) column = EXTRUDE([1,circle,3.58]) columns = STRUCT(NN(5)([column,T([1])([3.94])])) columnOnBalcony = T([2])([7.55])(column) squarePillars = GRID([[0.36,-1.86,0.36,-3.58,0.36,-3.58,0.36],[0.36],[3.29]]) squarePillars =...
Python
zaydzuhri_stack_edu_python
import datetime set m = integer input string month: set d = integer input string date: set y = integer input string year: set i = call datetime y m d print i set n = string format time i string %A print title string it is n print string Successfully finished.
import datetime m=int(input("month: ")) d=int(input("date: ")) y=int(input("year: ")) i=datetime.datetime(y,m,d) print(i) n=i.strftime("%A") print("it is ".title(),n) print("Successfully finished.")
Python
zaydzuhri_stack_edu_python
from game import * from evaluation import * import copy function minimaxBot board arrayLegalMovesO arrayLegalMovesX playTurn depth height alpha beta begin string Node pohon menggunakan AnyNode. Format = (id(board,legalO,legalX),nilaiEval,parent) set alphalocal = deep copy alpha set betalocal = deep copy beta comment Ba...
from game import * from evaluation import * import copy def minimaxBot(board, arrayLegalMovesO, arrayLegalMovesX, playTurn, depth, height, alpha, beta): """Node pohon menggunakan AnyNode. Format = (id(board,legalO,legalX),nilaiEval,parent)""" alphalocal = copy.deepcopy(alpha) betalocal = copy.deepcopy(beta...
Python
zaydzuhri_stack_edu_python
function recursive_group_merge groups begin while length groups at 0 != 1 begin set groups = call merge_triangulations groups end return groups end function
def recursive_group_merge(groups): while len(groups[0])!=1: groups = merge_triangulations(groups) return groups
Python
nomic_cornstack_python_v1
function compute_each_loop self x1_offset x2_offset y_offset compute_num begin set burst_len = ceil compute_num / data_each_block call data_move x1_ub x1_gm at x1_offset 0 1 burst_len 0 0 call data_move x2_ub x2_gm at x2_offset 0 1 burst_len 0 0 set add_loop = compute_num // vector_mask_max * 255 set add_offset = 0 if ...
def compute_each_loop(self, x1_offset, x2_offset, y_offset, compute_num): burst_len = math.ceil(compute_num / self.data_each_block) self.tik_instance.data_move(self.x1_ub, self.x1_gm[x1_offset], 0, 1, burst...
Python
nomic_cornstack_python_v1
string ' def spiral_matrix(matrix): col_end = len(matrix[0])-1 row_end = len(matrix)-1 col_begin = 0 row_begin = 0 while (row_begin <= row_end and col_begin <= col_end): for i in range(col_begin,col_end+1): print(matrix[row_begin][i]) row_begin += 1 for i in range(row_begin,row_end+1): print(matrix[i][col_end]) col_end...
'''' def spiral_matrix(matrix): col_end = len(matrix[0])-1 row_end = len(matrix)-1 col_begin = 0 row_begin = 0 while (row_begin <= row_end and col_begin <= col_end): for i in range(col_begin,col_end+1): print(matrix[row_begin][i]) row_begin += 1 for i in...
Python
zaydzuhri_stack_edu_python
from common import * from baum_welch import baum_welch , convergent , gamma , delta , one_iter class BaumWelchTest extends TestCase begin function setUp self begin comment two values don't sum to 1, this is because we want to accomondate to the rounding error in Moss's lecture set pi = call hashdict list tuple string s...
from common import * from baum_welch import baum_welch, convergent, gamma, delta, one_iter class BaumWelchTest(unittest.TestCase): def setUp(self): self.pi = hashdict([("s", 0.85), ("t", 0.16)]) #two values don't sum to 1, this is because we want to accomondate to the rounding error in Moss's lecture ...
Python
zaydzuhri_stack_edu_python
function check table begin set n = length table set m = length table at 0 set bits = list comprehension list comprehension table at i at j == j + 1 for j in range m for i in range n for row in bits begin if count row false > 2 begin return false end end return true end function set tuple n m = map int split input set t...
def check(table): n = len(table) m = len(table[0]) bits = [[table[i][j] == j+1 for j in range(m)] for i in range(n)] for row in bits: if row.count(False) > 2: return False return True n,m =map(int, input().split()) table = [list(map(int, input().split())) for i in range(n)] for ...
Python
jtatman_500k
function test_view_success_code self begin set response = get client call get_url pk assert equal status_code 200 end function
def test_view_success_code(self): response = self.client.get(self.get_url(self.htsv.pk)) self.assertEqual(response.status_code, 200)
Python
nomic_cornstack_python_v1
function history self begin pass end function
def history(self) -> TimeSeries: pass
Python
nomic_cornstack_python_v1
function MinimizeButton self visible=true begin return call SetFlag buttonMinimize visible end function
def MinimizeButton(self, visible=True): return self.SetFlag(self.buttonMinimize, visible)
Python
nomic_cornstack_python_v1
import copy import sys import numpy as np import scipy.misc import matplotlib.pyplot as plt import matplotlib.cm as cm import pywt import pltutils import matplotlib as mpl set params = dict string axes.labelsize 18 ; string axes.titlesize 20 ; string text.fontsize 22 ; string legend.fontsize 14 ; string xtick.labelsize...
import copy import sys import numpy as np import scipy.misc import matplotlib.pyplot as plt import matplotlib.cm as cm import pywt import pltutils import matplotlib as mpl params = {'axes.labelsize': 18, 'axes.titlesize': 20, 'text.fontsize': 22, 'legend.fontsize': 14, 'xtick...
Python
zaydzuhri_stack_edu_python
function block_measure_info begin return measure_info at meas_desc_block_no end function
def block_measure_info(self, block: int, /) -> numpy.recarray: return self.measure_info[self.block_headers[block].meas_desc_block_no]
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @File : BAYES.py comment @Date : 2020-10-19 comment @Author : YUEYUE-x4 comment @Demo : import numpy as np import math comment 创建句组成的列表 function create_dataset begin set posting_list = list list string my string dog string has string flea string problems string help string please l...
# -*- coding: utf-8 -*- # @File : BAYES.py # @Date : 2020-10-19 # @Author : YUEYUE-x4 # @Demo : import numpy as np import math # 创建句组成的列表 def create_dataset(): posting_list = [['my','dog','has','flea','problems','help','please'], ['maybe','not','take','him','to','dog','park','stupi...
Python
zaydzuhri_stack_edu_python
string Some simple skeleton code for a pygame game/animation This skeleton sets up a basic 800x600 window, an event loop, and a redraw timer to redraw at 30 frames per second. from __future__ import division import math import random import sys import os import pygame comment Some useful functions used in more than one...
"""Some simple skeleton code for a pygame game/animation This skeleton sets up a basic 800x600 window, an event loop, and a redraw timer to redraw at 30 frames per second. """ from __future__ import division import math import random import sys import os import pygame # Some useful functions used in more than one cl...
Python
zaydzuhri_stack_edu_python
function load_training_set self features labels=none feature_id_col_name=none metadata_col_names=none begin set _training = call convert_data_to_format features labels feature_id_col_name metadata_col_names end function
def load_training_set(self, features, labels=None, feature_id_col_name=None, metadata_col_names=None): self._training = self._learner.convert_data_to_format(features, labels, feature_id_col_name, metadata_col_names)
Python
nomic_cornstack_python_v1
from flaskblog import db class item extends Model begin set id = call Column Integer primary_key=true autoincrement=true set name = call Column call String 30 nullable=false set price = call Column Integer nullable=false set cart = call Column Integer nullable=false default=1 set cart_price = call Column Integer nullab...
from flaskblog import db class item(db.Model): id = db.Column(db.Integer,primary_key = True,autoincrement=True) name = db.Column(db.String(30),nullable = False) price = db.Column(db.Integer, nullable = False) cart = db.Column(db.Integer,nullable=False,default = 1) cart_price = db.Column(db.Integer,...
Python
zaydzuhri_stack_edu_python
function __sub__ self other begin set result = call Vector3D x - x y - y z - z return result end function
def __sub__(self, other): result = Vector3D(self.x - other.x, \ self.y - other.y, \ self.z - other.z) return result
Python
nomic_cornstack_python_v1
function compute_vals self vals modes instruction begin comment Use an intermediate string to obtain any missing leading zeros, since our opcode is comment already an int comment Reverse because parameter modes go from right to left set modes = list comprehension integer mode for mode in reversed call zfill length vals...
def compute_vals( self, vals: List[int], modes: int, instruction: MachineInstruction ) -> List[int]: # Use an intermediate string to obtain any missing leading zeros, since our opcode is # already an int # Reverse because parameter modes go from right to left modes = [int(mod...
Python
nomic_cornstack_python_v1
string @author: J.W.Spaak Numerically compute ND and FD for a model import numpy as np from scipy.optimize import brentq , fsolve from warnings import warn function NFD_model f n_spec=2 args=tuple monotone_f=true pars=none experimental=false from_R=false xtol=1e-05 estimate_N_star_mono=false begin string Compute the N...
""" @author: J.W.Spaak Numerically compute ND and FD for a model """ import numpy as np from scipy.optimize import brentq, fsolve from warnings import warn def NFD_model(f, n_spec = 2, args = (), monotone_f = True, pars = None, experimental = False, from_R = False, xtol = 1e-5, es...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string 题目: 给定一个不含有重复值的数组arr,找到每一个i位置左边和右边离i位置最近且值比arr[i]小的位置。返回所有位置相应的信息。 进阶问题:数组arr可以包含重复值 解答: 利用单调栈结构 import unittest from utils.stack import Stack comment arr不含重复值情况 function get_near_less_no_repeat arr begin comment 以二维数组作为结果,-1表示不存在 set res = list none * length arr comment stack按照从栈顶到...
# -*- coding: utf-8 -*- """ 题目: 给定一个不含有重复值的数组arr,找到每一个i位置左边和右边离i位置最近且值比arr[i]小的位置。返回所有位置相应的信息。 进阶问题:数组arr可以包含重复值 解答: 利用单调栈结构 """ import unittest from utils.stack import Stack # arr不含重复值情况 def get_near_less_no_repeat(arr): # 以二维数组作为结果,-1表示不存在 res = [None] * len(arr) # stack按照从栈顶到栈底严格递减顺序存放arr数...
Python
zaydzuhri_stack_edu_python
function teardown self begin for dd in dirs begin if is directory path dd begin remove tree dd end end end function
def teardown(self): for dd in self.dirs: if os.path.isdir(dd): shutil.rmtree(dd)
Python
nomic_cornstack_python_v1
function _set_topMargin self value begin string value will be an int or float. Subclasses may override this method. set bounds = bounds if bounds is none begin set height = value end else begin set tuple xMin yMin xMax yMax = bounds set height = yMax + value end end function
def _set_topMargin(self, value): """ value will be an int or float. Subclasses may override this method. """ bounds = self.bounds if bounds is None: self.height = value else: xMin, yMin, xMax, yMax = bounds self.height = yMax +...
Python
jtatman_500k
comment !/usr/bin/python3 comment carro = input('digite qual o caminho a ser seguido: ') comment a = 'engarrafado' comment b = 'livre' comment se a == 'engarrafado': comment print('melhor ir pela b') comment else: comment print('indo pelo caminho a') exemplo fraco comment Estrutura confdicional simples comment nome = i...
#!/usr/bin/python3 #carro = input('digite qual o caminho a ser seguido: ') #a = 'engarrafado' #b = 'livre' # se a == 'engarrafado': # print('melhor ir pela b') # else: # print('indo pelo caminho a') exemplo fraco ## ## Estrutura confdicional simples ## # nome = input('digite seu nome: ') # sobrenome = inpu...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string Author:zhouhuan Email:18832832911@139.com data:2020/12/12/012 20:09 desc: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from datetime import datetime set subFolder = string format time now string %Y%m%d-%H%M%S set logdir = string ./tfb_logs/ { subFolder }...
# coding=utf-8 ''' Author:zhouhuan Email:18832832911@139.com data:2020/12/12/012 20:09 desc: ''' import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from datetime import datetime subFolder = datetime.now().strftime("%Y%m%d-%H%M%S") logdir = f"./tfb_logs/{subFolder}" tf.logging.set_ve...
Python
zaydzuhri_stack_edu_python
function edit_config_input_target_config_target_candidate_candidate self **kwargs begin string Auto Generated Code set config = call Element string config set edit_config = call Element string edit_config set config = edit_config set input = call SubElement edit_config string input set target = call SubElement input st...
def edit_config_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") edit_config = ET.Element("edit_config") config = edit_config input = ET.SubElement(edit_config, "input") target = ET.SubElement...
Python
jtatman_500k
import socket import gevent import gevent.threadpool print string port? set port = integer input set s = call socket call connect tuple string localhost port set f = call makefile string rw function read_message begin while true begin print read line f end end function function write_message begin while true begin prin...
import socket import gevent import gevent.threadpool print('port? ') port = int(input()) s = socket.socket() s.connect(('localhost', port)) f = s.makefile('rw') def read_message(): while True: print(f.readline()) def write_message(): while True: print(input(), file=f, flush=True) pool = gev...
Python
zaydzuhri_stack_edu_python
function log_evaluation_xgb logger period=1 show_stdv=true begin function _fmt_metric value show_stdv=true begin string format metric string if length value == 2 begin return string %s:%g % tuple value at 0 value at 1 end else if length value == 3 begin if show_stdv begin return string %s:%g+%g % tuple value at 0 value...
def log_evaluation_xgb(logger, period=1, show_stdv=True): def _fmt_metric(value, show_stdv=True): """format metric string""" if len(value) == 2: return '%s:%g' % (value[0], value[1]) elif len(value) == 3: if show_stdv: return '%s:%g+%g' % (value[0], v...
Python
nomic_cornstack_python_v1
class Solution begin function heightChecker self heights begin set count = 0 set sort = sorted heights for tuple index val in enumerate sort begin if sort at index != heights at index begin set count = count + 1 end end return count end function end class
class Solution: def heightChecker(self, heights: List[int]) -> int: count = 0 sort = sorted(heights) for index,val in enumerate(sort): if sort[index]!=heights[index]: count+=1 return count
Python
zaydzuhri_stack_edu_python
comment linear algebra import numpy as np import googlemaps comment data processing, CSV file I/O (e.g. pd.read_csv) import pandas as pd import json import ast import matplotlib.pyplot as plt import seaborn as sns from math import sin , cos , sqrt , atan2 , asin , radians set MajorCities = dict string PARIS tuple 48.85...
import numpy as np # linear algebra import googlemaps import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import json import ast import matplotlib.pyplot as plt import seaborn as sns from math import sin, cos, sqrt, atan2, asin, radians MajorCities = {"PARIS" : (48.8566, 2.3522), "LYON": (45.7640, 4...
Python
zaydzuhri_stack_edu_python
comment Python - Find longest (most words) key in dictionary max generator expression length split k for k in keys d
# Python - Find longest (most words) key in dictionary max(len(k.split()) for k in d.keys())
Python
zaydzuhri_stack_edu_python
function eso_select_raid_runs_query self begin set sess = call _session set data = query sess EsoRaidRunsTable return data end function
def eso_select_raid_runs_query(self) -> List[List]: sess = self._session() data = sess.query(EsoRaidRunsTable) return data
Python
nomic_cornstack_python_v1
import multiprocessing as mp import threading as td import time function job q begin comment print("aaaa") set res = 0 for i in range 5000000 begin set res = res + i + i ^ 2 + i ^ 3 end put res end function comment t1 = td.Thread(target =job,args=(1,2) ) function multicore begin set q = queue set p1 = process target=jo...
import multiprocessing as mp import threading as td import time def job(q): # print("aaaa") res = 0 for i in range(5000000): res+=i+i**2+i**3 q.put(res) # t1 = td.Thread(target =job,args=(1,2) ) def multicore(): q=mp.Queue() p1 = mp.Process(target=job,args = (q,)) p2 = mp.Process(t...
Python
zaydzuhri_stack_edu_python
import numpy as np function read_mat_file vector_file begin with open vector_file string r as f begin set embed = list for tuple i line in enumerate f begin set elems = split right strip line string string append embed elems end end return as type array embed float end function comment def file_write(mat,file_name): c...
import numpy as np def read_mat_file(vector_file): with open(vector_file,'r') as f: embed = [] for i,line in enumerate(f): elems = line.rstrip('\n').split(' ') embed.append(elems) return np.array(embed).astype(float) # def file_write(mat,file_name): # txt_file ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import cv2 import glob comment TODO: fit image width to size of browser class ImageEditor begin function __init__ self input_img begin comment files set image_name = split input_img string . at 0 set image_ext = split input_img string . at 1 set saved_name = none comment images se...
import pandas as pd import numpy as np import cv2 import glob # TODO: fit image width to size of browser class ImageEditor(): def __init__(self, input_img): # files self.image_name = input_img.split('.')[0] self.image_ext = input_img.split('.')[1] self.saved_name = None ...
Python
zaydzuhri_stack_edu_python
function _clean_sys_argv pipeline begin set reserved_opts = set literal pipeline string label string id string stage string station string writers return list comprehension o for o in argv at slice 1 : : if starts with o string -- and split o at slice 2 : : string = at 0 not in reserved_opts end function
def _clean_sys_argv(pipeline: str) -> List[str]: reserved_opts = {pipeline, "label", "id", "stage", "station", "writers"} return [o for o in sys.argv[1:] if o.startswith("--") and o[2:].split("=")[0] not in reserved_opts]
Python
nomic_cornstack_python_v1
function getNoOfPronouns self begin return length list comprehension token for token in call getTokenPOSTags if token at 1 == string PRP or token at 1 == string PRP$ end function
def getNoOfPronouns(self): return len([token for token in self.getTokenPOSTags() if token[1] == "PRP" or token[1] == "PRP$"])
Python
nomic_cornstack_python_v1
import sys import os with open directory name path __file__ + string /input.txt as f begin print string Find 2 numbers (a, b) that sum 2020, get its product, a * b set seen = dict set target = 2020 for line in read lines f begin set n = integer line if target - n in seen begin print format string {0} * {1} = {2} n tar...
import sys import os with open(os.path.dirname(__file__) + '/input.txt') as f: print("Find 2 numbers (a, b) that sum 2020, get its product, a * b") seen = {} target = 2020 for line in f.readlines(): n = int(line) if target - n in seen: print('{0} * {1} = {2}'.format(n, targe...
Python
zaydzuhri_stack_edu_python
function showtext2 self begin call textSize 20 call text string You already own this item 50 50 call text string Type q to leave 1450 890 end function
def showtext2(self): textSize(20) text('You already own this item', 50, 50) text('Type q to leave', 1450, 890)
Python
nomic_cornstack_python_v1
function debug target=none begin call verbose true set man = manager set mode_dbg = true call init_components target call start_app end function
def debug(target=None): logger.verbose(True) man = Manager() man.mode_dbg = True man.init_components(target) man.start_app()
Python
nomic_cornstack_python_v1
function deserialize_numpy self str numpy begin try begin if header is none begin set header = call Header end set end = 0 set _x = self set start = end set end = end + 12 set tuple seq secs nsecs = call unpack str at slice start : end : set start = end set end = end + 4 set tuple length = call unpack str at slice star...
def deserialize_numpy(self, str, numpy): try: if self.header is None: self.header = std_msgs.msg.Header() end = 0 _x = self start = end end += 12 (_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _get_struct_3I().unpack(str[start:end]) start = end ...
Python
nomic_cornstack_python_v1
function cancel_timer self begin comment type: () -> None if timer is none begin warning string [%x] Timer is not active call id self return end call cancel debug string [%x] Timer thread cancelled call id self set timer = none end function
def cancel_timer(self): # type: () -> None if self.timer is None: LOGGER.warning('[%x] Timer is not active', id(self)) return self.timer.cancel() LOGGER.debug('[%x] Timer thread cancelled', id(self)) self.timer = None
Python
nomic_cornstack_python_v1
string Script to extract stellar yields from a given NuGrid data set to translate them into an Enzo-readable table. This relies on Christian Ritter's read_yields.py Author: Andrew Emerick Date : 04/2016 from chemistry.NuGrid import read_yields as ry import numpy as np set master_element_list = list string H string He s...
""" Script to extract stellar yields from a given NuGrid data set to translate them into an Enzo-readable table. This relies on Christian Ritter's read_yields.py Author: Andrew Emerick Date : 04/2016 """ from chemistry.NuGrid import read_yields as ry import numpy as np # master_element_list = ['...
Python
zaydzuhri_stack_edu_python
function _prodterm lexer begin set factor = call _factor lexer set prodterm_prime = call _prodterm_prime lexer if prodterm_prime is none begin return factor end else begin return tuple string and factor prodterm_prime end end function
def _prodterm(lexer): factor = _factor(lexer) prodterm_prime = _prodterm_prime(lexer) if prodterm_prime is None: return factor else: return ("and", factor, prodterm_prime)
Python
nomic_cornstack_python_v1
function show_dialog_open self begin set source_filepath = call getOpenFileName self string Open source file string ./ at 0 if not source_filepath begin return false end set item = item listBandwidths 0 call setSelected true call setCurrentItem item call prepare_data return true end function
def show_dialog_open(self: dict) -> bool: self.config.source_filepath = self.file_dialog_open.getOpenFileName( self, 'Open source file', './')[0] if not self.config.source_filepath: return False item = self.listBandwidths.item(0) item.setSe...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string @author: Allen(Zifeng) An @course: @contact: anz8@mcmaster.ca @file: 21. binarysearch.py @time: 2020/2/5 12:35 comment Definition for singly-linked list. class ListNode begin function __init__ self x next=none begin set val = x set next = next end functi...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @author: Allen(Zifeng) An @course: @contact: anz8@mcmaster.ca @file: 21. binarysearch.py @time: 2020/2/5 12:35 ''' # Definition for singly-linked list. class ListNode: def __init__(self, x,next=None): self.val = x self.next = next e=ListNode(5) d=...
Python
zaydzuhri_stack_edu_python
function test_llhd self test_idxs begin set test_idxs_ = copy np test_idxs set users = unique test_idxs_ at tuple slice : : 0 set train_idxs = copy np edge_idx_d at tuple call in1d edge_idx_d at tuple slice : : 0 users slice : : for tuple en user in enumerate users begin set test_idxs_ at tuple test_idxs_ at tu...
def test_llhd(self, test_idxs): test_idxs_ = np.copy(test_idxs) users = np.unique(test_idxs_[:, 0]) train_idxs = np.copy(self.edge_idx_d[np.in1d(self.edge_idx_d[:, 0], users),:]) for en, user in enumerate(users): test_idxs_[test_idxs_[:, 0] == user, 0] = en tra...
Python
nomic_cornstack_python_v1
import math import numpy as np import factormatrix as qs import time import sys comment This code factors n from start to finish. function solve n begin comment breakpoint() set tuple fact_mat factors row_labels row_labels_unsquared = call quad_sieve n set factors = array factors dtype=string int64 print string Finding...
import math import numpy as np import factormatrix as qs import time import sys #This code factors n from start to finish. def solve(n): #breakpoint() fact_mat,factors,row_labels,row_labels_unsquared=qs.quad_sieve(n) factors=np.array(factors,dtype="int64") print("Finding linear dependencies...") ...
Python
zaydzuhri_stack_edu_python
comment The following iterative sequence is defined for the set of positive integers: comment n -> n/2 (n is even) comment n -> 3n + 1 (n is odd) comment Using the rule above and starting with 13, we generate the following sequence: comment 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 comment It can be seen that...
# The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # It can be seen that this sequence (starting at 13...
Python
zaydzuhri_stack_edu_python
import pandas as pd from causalnex.plots import plot_structure , NODE_STYLE , EDGE_STYLE from causalnex.structure.notears import from_pandas , from_pandas_lasso from causalnex.structure import StructureModel from IPython.display import Image import numpy as np import pandas as pd import seaborn as sns import matplotlib...
import pandas as pd from causalnex.plots import plot_structure, NODE_STYLE, EDGE_STYLE from causalnex.structure.notears import from_pandas, from_pandas_lasso from causalnex.structure import StructureModel from IPython.display import Image import numpy as np import pandas as pd import seaborn as sns import matplotlib.py...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function isAlienSorted self words order begin set d = dict for tuple i c in enumerate order begin set d at c = i end for i in call xrange length words - 1 begin set word1 = words at i set word2 = words at i + 1 set check = false for j in call xrange min length word1 length word2 beg...
class Solution(object): def isAlienSorted(self, words, order): d = {} for i, c in enumerate(order): d[c] = i for i in xrange(len(words)-1): word1 = words[i] word2 = words[i+1] check = False for j in xrange(min(...
Python
zaydzuhri_stack_edu_python
function update self commit=true **kwargs begin string Update model attributes and save to database for tuple attr value in call iteritems begin set attribute self attr value end return commit and save or self end function
def update(self, commit=True, **kwargs): """ Update model attributes and save to database """ for (attr, value) in kwargs.iteritems(): setattr(self, attr, value) return commit and self.save() or self
Python
jtatman_500k
function __init__ self app_dir ui begin set vendor_dir = join path app_dir string vendor if not is directory path vendor_dir begin make directories vendor_dir end set vendor_dir = vendor_dir set ui = ui set _vendor_handlers = none end function
def __init__(self, app_dir, ui): vendor_dir = os.path.join(app_dir, "vendor") if not os.path.isdir(vendor_dir): os.makedirs(vendor_dir) self.vendor_dir = vendor_dir self.ui = ui self._vendor_handlers = None
Python
nomic_cornstack_python_v1
string You are given an integer, N. Write a program to determine if N is an element of the Fibonacci sequence. Rather than compute all fibonacci numbers below N, we will use the fact: A number, n, is a Fibonacci number if and only if (5n^2 + 4) or (5n^2 - 4) is a perfect square. import math function is_fibonacci n begi...
""" You are given an integer, N. Write a program to determine if N is an element of the Fibonacci sequence. Rather than compute all fibonacci numbers below N, we will use the fact: A number, n, is a Fibonacci number if and only if (5n^2 + 4) or (5n^2 - 4) is a perfect square. """ import math def is_fibonacci(n): ...
Python
zaydzuhri_stack_edu_python
function max_pairwise_product_fast numbers begin sort numbers return numbers at - 1 * numbers at - 2 end function if __name__ == string __main__ begin set input_n = integer input set input_numbers = list comprehension integer x for x in split input print call max_pairwise_product_fast input_numbers end
def max_pairwise_product_fast(numbers): numbers.sort() return numbers[-1] * numbers[-2] if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product_fast(input_numbers))
Python
zaydzuhri_stack_edu_python
import torch import tensorflow as tf import numpy as np from torch.autograd import Variable import matplotlib.pyplot as plt import seaborn as sns set POLY_DEGREE = 10 set THETA = zeros POLY_DEGREE + 1 1 set DATASIZE = 200 set TEST_SIZE = 1000 set SIGMA = 1 function getData data_size sigma begin set x = type FloatTensor...
import torch import tensorflow as tf import numpy as np from torch.autograd import Variable import matplotlib.pyplot as plt import seaborn as sns POLY_DEGREE = 10 THETA = torch.zeros(POLY_DEGREE+1,1) DATASIZE = 200 TEST_SIZE = 1000 SIGMA = 1 def getData(data_size,sigma): x = torch.empty(data_size, ).uniform_(0, 1...
Python
zaydzuhri_stack_edu_python
comment Importamos numpy y matplotlib import numpy as np import matplotlib.pyplot as plt comment Importamos time, es un módulo que ya viene con Python, así que no hay que instalarlo import time comment Esta función aplica el esquema que vimos en clase: comment t0: es el tiempo inicial comment tf: es el tiempo final com...
# Importamos numpy y matplotlib import numpy as np import matplotlib.pyplot as plt # Importamos time, es un módulo que ya viene con Python, así que no hay que instalarlo import time # Esta función aplica el esquema que vimos en clase: # t0: es el tiempo inicial # tf: es el tiempo final # x0: inicio del intervalo de pos...
Python
zaydzuhri_stack_edu_python
set str = string This is a sample string set new_str = replace str string string *
str = 'This is a sample string' new_str = str.replace(' ', '*')
Python
jtatman_500k
import argparse import math import numpy as np import pandas as pd import matplotlib.pyplot as plt import keras from keras import layers from keras.models import Sequential from keras import backend as K set parser = call ArgumentParser formatter_class=ArgumentDefaultsHelpFormatter call add_argument string --input_size...
import argparse import math import numpy as np import pandas as pd import matplotlib.pyplot as plt import keras from keras import layers from keras.models import Sequential from keras import backend as K parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--in...
Python
zaydzuhri_stack_edu_python
function test_bad_file begin set bad = join string random choices ascii_uppercase + digits k=5 set tuple rv out = call getstatusoutput string { prg } -f { bad } assert rv != 0 assert match string usage: out I assert search string No such file or directory: ' { bad } ' out end function
def test_bad_file(): bad = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) rv, out = getstatusoutput(f'{prg} -f {bad}') assert rv != 0 assert re.match('usage:', out, re.I) assert re.search(f"No such file or directory: '{bad}'", out)
Python
nomic_cornstack_python_v1
function attributeClass self attribute begin pass end function
def attributeClass(self, attribute): pass
Python
nomic_cornstack_python_v1
function get_surface_correction self surface_option a begin if surface_option is none begin return zeros length modes dtype=ftype end if surface_option == string Kjeldsen2008 begin return a at 0 * modes at string freq ^ b_Kjeldsen2008 end if surface_option == string Kjeldsen2008_scaling begin return a at 0 * modes at s...
def get_surface_correction(self, surface_option, a): if (surface_option is None): return np.zeros(len(self.modes), dtype=ftype) if (surface_option == "Kjeldsen2008"): return a[0]*self.modes['freq']**config.b_Kjeldsen2008 if (surface_option == "Kjeldsen2008_scaling"): r...
Python
nomic_cornstack_python_v1
string >= 70 - A >= 60 - B >= 40 - C < 40 - F < 0 or > 100 - I set marks = decimal input string Enter marks : if marks < 0 or marks > 100 begin print string I end else if marks >= 70 begin print string A end else if marks >= 60 begin print string B end else if marks >= 40 begin print string C end else begin print strin...
''' >= 70 - A >= 60 - B >= 40 - C < 40 - F < 0 or > 100 - I ''' marks = float(input('Enter marks : ')) if marks < 0 or marks > 100: print('I') elif marks >= 70: print('A') elif marks >= 60: print('B') elif marks >= 40: print('C') else: print('F')
Python
zaydzuhri_stack_edu_python
from math import sqrt function fract S begin set terms = list set a0 = integer square root S set m = 0 set d = 1 set a = a0 while a != 2 * a0 begin set m = d * a - m set d = S - m * m / d set a = integer square root S + m / d append terms a end return terms end function function check x y begin if x * x - D * y * y == ...
from math import sqrt def fract(S): terms = list() a0 = int(sqrt(S)) m = 0 d = 1 a = a0 while a != 2 * a0: m = d * a - m d = (S - m * m) / d a = int((sqrt(S) + m) / d) terms.append(a) return terms def check(x, y): if x * x - D * y * y == 1: return True else: return F...
Python
zaydzuhri_stack_edu_python
function matchesProperties self *args begin return call FbcV2ToV1Converter_matchesProperties self *args end function
def matchesProperties(self, *args): return _libsbml.FbcV2ToV1Converter_matchesProperties(self, *args)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment !/usr/bin/env python3 import numpy as np from sklearn import preprocessing import keras from keras.utils import to_categorical , normalize comment Normaliser les données et encoder les labels pour qu'ils prennent la forment comment d'une distribution de probabilité sur les classes ...
# -*- coding: utf-8 -*- #!/usr/bin/env python3 import numpy as np from sklearn import preprocessing import keras from keras.utils import to_categorical, normalize #Normaliser les données et encoder les labels pour qu'ils prennent la forment #d'une distribution de probabilité sur les classes (one hot encoding). def f...
Python
zaydzuhri_stack_edu_python
comment file sc.py comment check & delete special characters set emailTo = list string dwbarne@s/\?>.gov string dd*$(@ear//link`.net set charList1 = list string ; string # string , string ! string $ string ^ string & string * string ( string ) string + string = string { set charList2 = list string } string [ string ] s...
# file sc.py # # check & delete special characters emailTo=['dwbarne@s/\?>.gov','dd*$(@ear//link`.net'] charList1=[';', '#', ',', '!', '$', '^', '&', '*', '(', ')', '+', '=', '{'] charList2=['}', '[', ']', '|', '\\', '/', ":", "?", '>', "<", "`", " "] charList=charList1 + charList2 specialCharactersInEmailAddresses...
Python
zaydzuhri_stack_edu_python
function __init__ self config logger name network allowed=none sources=none tags=none security_group=false additional_settings=none begin call __init__ config logger id additional_settings=additional_settings if call should_use_external_resource ctx begin set name = call assure_resource_id_correct end else if name begi...
def __init__(self, config, logger, name, network, allowed=None, sources=None, tags=None, security_group=False, additional_settings=None, ): su...
Python
nomic_cornstack_python_v1
function calc_transfer_functions self begin try begin set tf = tf set status = call process_transfer_functions if status is true begin call plot_transfer_functions call view_mod_transfer_functions set msg = string Frequency-dependent transfer functions calculated successfully. call _message_information string Calculate...
def calc_transfer_functions(self): try: self.transFuncsModule.tf = self.tf status = self.transFuncsModule.tf.process_transfer_functions() if status is True: self.transFuncsModule.plot_transfer_functions() self.view_mod_transfer_functions() ...
Python
nomic_cornstack_python_v1
function _create_db self begin set _getlatest = dict for entry in _data begin set code = entry at _clmn at string Code set lastupdate = entry at _clmn at string LastUpdated set desc = entry at _clmn at string Description set recordnum = entry at _clmn at string RecordNo if code in keys _getlatest begin if lastupdate >...
def _create_db(self): self._getlatest = {} for entry in self._data: code = entry[self._clmn['Code']] lastupdate = entry[self._clmn['LastUpdated']] desc = entry[self._clmn['Description']] recordnum = entry[self._clmn['RecordNo']] if code in sel...
Python
nomic_cornstack_python_v1
comment pylint: disable=arguments-differ function form_factor self q s t couplings begin set q2 = q ^ 2 * 1e-06 set ss = s * 1e-06 set tt = t * 1e-06 set uu = q2 + MPI0_GEV ^ 2 + 2 * MPI_GEV ^ 2 - ss - tt set ff = call __form_factor q2=q2 s=ss t=tt u=uu couplings=couplings return ff * 1e-09 end function
def form_factor( # pylint: disable=arguments-differ self, q: float, s: RealOrRealArray, t: RealOrRealArray, couplings: Couplings ) -> ComplexOrComplexArray: q2 = q**2 * 1e-6 ss = s * 1e-6 tt = t * 1e-6 uu = q2 + MPI0_GEV**2 + 2 * MPI_GEV**2 - ss - tt ff = self.__for...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment from __future__ import print_function from googleapiclient.discovery import build from yandex_translate import YandexTranslate import sys call reload sys call setdefaultencoding string utf8 class translator extends object begin function __init__ self ke...
#!/usr/bin/env python # -*- coding: utf-8 -*- #from __future__ import print_function from googleapiclient.discovery import build from yandex_translate import YandexTranslate import sys reload(sys) sys.setdefaultencoding('utf8') class translator(object): def __init__(self, key, service_api): #creating o...
Python
zaydzuhri_stack_edu_python
function _get_metrics self clean_audio noise_audio dist_samples begin set cos_dis = call cosine clean_audio dist_samples set feature = dict string cos call _float_feature list cos_dis ; string num_samples call _float_feature list decimal shape at 0 return call Example features=call Features feature=feature end function
def _get_metrics(self, clean_audio, noise_audio, dist_samples): cos_dis = scipy.spatial.distance.cosine(clean_audio, dist_samples) feature = { 'cos': _float_feature([cos_dis]), 'num_samples': _float_feature([float(dist_samples.shape[0])]) } return tf.Example(features=tf.train.Features(fe...
Python
nomic_cornstack_python_v1
function updateGUIFromParameterNode self caller=none event=none begin if _parameterNode is none or _updatingGUIFromParameterNode begin return end comment Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop) set _updatingGUIFromParameterNode = true comment Update node selectors and...
def updateGUIFromParameterNode(self, caller=None, event=None): if self._parameterNode is None or self._updatingGUIFromParameterNode: return # Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop) self._updatingGUIFromParameterNode = True ...
Python
nomic_cornstack_python_v1
comment https://www.acmicpc.net/problem/16165 set tuple N M = map int split input set tuple team_mem mem_team = tuple dict dict for i in range N begin set tuple team_name mem_num = tuple input integer input set team_mem at team_name = list for j in range mem_num begin set name = input append team_mem at team_name na...
#https://www.acmicpc.net/problem/16165 N, M = map(int, input().split()) team_mem, mem_team = {}, {} for i in range(N): team_name, mem_num = input(), int(input()) team_mem[team_name]=[] for j in range(mem_num): name = input() team_mem[team_name].append(name) mem_team[name] = team_n...
Python
zaydzuhri_stack_edu_python
function extract_ngrams dataset n remove_stopwords=true remove_punc=true mode=string spacy begin info string extracting ngrams ... for i in call tnrange length dataset desc=string NGRAMS begin set text_datum = raw_text set tuple ngrams tokens = call extract_ngram_from_text text_datum n remove_stopwords remove_punc mode...
def extract_ngrams(dataset, n, remove_stopwords=True, remove_punc=True, mode='spacy'): logger.info("extracting ngrams ...") for i in tnrange(len(dataset), desc='NGRAMS'): text_datum = dataset[i].raw_text ngrams, tokens =...
Python
nomic_cornstack_python_v1
from __future__ import division from fractions import Fraction import operator function simplify x y begin string Use incorrect cancelling to remove any matching digits on the top or bottom of the fraction. If the cancelling fails, return None set dig1 = x // 10 set dig2 = x % 10 set dig3 = y // 10 set dig4 = y % 10 co...
from __future__ import division from fractions import Fraction import operator def simplify(x, y): """ Use incorrect cancelling to remove any matching digits on the top or bottom of the fraction. If the cancelling fails, return None """ dig1 = x // 10 dig2 = x % 10 dig3 = y // 10 d...
Python
zaydzuhri_stack_edu_python
import platform from subprocess import call set operSys = call system function clear_scr begin if operSys == string Windows begin call string cls shell=true end if operSys == string Linux begin call string clear shell=true end end function
import platform from subprocess import call operSys = platform.system() def clear_scr(): if operSys == "Windows": call('cls', shell=True) if operSys == "Linux": call('clear', shell=True)
Python
zaydzuhri_stack_edu_python
function AppendCmdline cmdline value prefix=string begin if value begin set cmdline = cmdline + prefix + string value end return cmdline end function
def AppendCmdline(cmdline, value, prefix=' '): if value: cmdline += prefix + str(value) return cmdline
Python
nomic_cornstack_python_v1
import glob import os import string import csv import numpy as np from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.preprocessing import Normalizer from sklearn.pipeline import Pipeli...
import glob import os import string import csv import numpy as np from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.preprocessing import Normalizer from sklearn.pipeline import Pipel...
Python
zaydzuhri_stack_edu_python
import itertools set arr = list for _ in range integer input string Enter number of elements: begin append arr integer input string Enter { _ } th element: end set all_triplets = list call combinations arr 3 set results = list for triplet in all_triplets begin if sum triplet == 0 begin append results triplet end end ...
import itertools arr = [] for _ in range(int(input('Enter number of elements: '))): arr.append(int(input(f'Enter {_}th element: '))) all_triplets = list(itertools.combinations(arr, 3)) results = [] for triplet in all_triplets: if sum(triplet) == 0: results.append(triplet) for triplet in results: ...
Python
zaydzuhri_stack_edu_python
function test_get_available_meals test_client begin set response = get test_client string /api/v2/menu assert status_code == 404 end function
def test_get_available_meals(test_client): response = test_client.get("/api/v2/menu") assert response.status_code == 404
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string @author: pheno Data Generator for RatSI dataset RatSI: Rat Social Interaction Dataset by Noldus https://www.noldus.com/projects/phenorat/datasets/ratsi Input image: folder with image frames generated from original videos folder_path/ Sample000XXX.jpg Sampel000XXX.jpg ...... label: o...
# -*- coding: utf-8 -*- """ @author: pheno Data Generator for RatSI dataset RatSI: Rat Social Interaction Dataset by Noldus https://www.noldus.com/projects/phenorat/datasets/ratsi Input image: folder with image frames generated from original videos folder_path/ Sample000XXX.jpg ...
Python
zaydzuhri_stack_edu_python
function __getitem__ self idx begin set img_loc = join path main_dir images at idx set image = call convert string RGB set tensor_image = transform self image return tensor_image end function
def __getitem__(self, idx): img_loc = os.path.join(self.main_dir, self.images[idx]) image = Image.open(img_loc).convert("RGB") tensor_image = self.transform(image) return tensor_image
Python
nomic_cornstack_python_v1
import numpy as np from one_player_map import Map import pandas as pd import pickle class OneGame begin function __init__ self verbose greedy players state_values begin set players = players set turn_counter = 1 set verbose = verbose set greedy = greedy set state_values = state_values set station_finishers = dict strin...
import numpy as np from one_player_map import Map import pandas as pd import pickle class OneGame: def __init__(self, verbose, greedy, players, state_values): self.players = players self.turn_counter = 1 self.verbose = verbose self.greedy = greedy self.state_values = state_...
Python
zaydzuhri_stack_edu_python
comment This functions come from Reddit comment https://github.com/reddit/reddit/blob/master/r2/r2/lib/db/_sorts.pyx comment Additional resources comment http://www.redditblog.com/2009/10/reddits-new-comment-sorting-system.html comment http://www.evanmiller.org/how-not-to-sort-by-average-rating.html comment http://amix...
# This functions come from Reddit # https://github.com/reddit/reddit/blob/master/r2/r2/lib/db/_sorts.pyx # Additional resources # http://www.redditblog.com/2009/10/reddits-new-comment-sorting-system.html # http://www.evanmiller.org/how-not-to-sort-by-average-rating.html # http://amix.dk/blog/post/19588 from datetime ...
Python
zaydzuhri_stack_edu_python
set names = list string Tim string Sue string Tim string Betty print names
names =['Tim', 'Sue', 'Tim', 'Betty'] print(names)
Python
zaydzuhri_stack_edu_python
function idle self begin if call get_state is Stopped or call is_zombie begin call set_state Idle end else begin raise call IdleActionException end end function
def idle(self): if self.get_state() is BaseStates.Stopped or self.is_zombie(): self.set_state(BaseStates.Idle) else: raise IdleActionException()
Python
nomic_cornstack_python_v1
import phonenumbers from authy.api import AuthyApiClient from flask import current_app as app from flask import flash , g , request , session function parse_phone_number full_phone begin string Parses the phone number from E.164 format :param full_phone: phone number in E.164 format :returns: tuple (country_code, phone...
import phonenumbers from authy.api import AuthyApiClient from flask import current_app as app from flask import flash, g, request, session def parse_phone_number(full_phone): """ Parses the phone number from E.164 format :param full_phone: phone number in E.164 format :returns: tuple (country_code, p...
Python
zaydzuhri_stack_edu_python
function anomaly_settings_version self begin return get pulumi self string anomaly_settings_version end function
def anomaly_settings_version(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "anomaly_settings_version")
Python
nomic_cornstack_python_v1
if a % 2 == 0 begin print a % 2 string Четное число end else begin print a % 2 string Нечетное число end
if a % 2 == 0: print(a % 2 ,'Четное число') else: print(a % 2 ,'Нечетное число')
Python
zaydzuhri_stack_edu_python
function createKeyLabels self begin set charLeft = list set charRight = list set numLeft = list set numRight = list for i in range 13 begin append charLeft call Label inputKey text=character i + 97 + string : padx=5 pady=5 grid row=i column=0 end for i in range 13 begin append charRight call Label inputKey text=cha...
def createKeyLabels(self): charLeft = [] charRight = [] numLeft = [] numRight = [] for i in range(13): charLeft.append(Label(self.inputKey, text=chr(i + 97) + ":", padx=5, pady=5)) charLeft[i].grid(row=i, column=0) for i in range(13): ...
Python
nomic_cornstack_python_v1
function bakeOffsets self begin comment get movers set jointMovers = returnJointMovers comment separate mover lists set globalMovers = jointMovers at 0 set offsetMovers = jointMovers at 1 set constraints = list set locators = list comment create locators for the offsetMovers, then zero out offset mover for mover in o...
def bakeOffsets(self): # get movers jointMovers = self.returnJointMovers # separate mover lists globalMovers = jointMovers[0] offsetMovers = jointMovers[1] constraints = [] locators = [] # create locators for the offsetMovers, then zero out offset mover...
Python
nomic_cornstack_python_v1
function doctor ctx client begin string Check your system and repository for potential problems. call secho join string call wrap DOCTOR_INFO + string bold=true from import _checks set is_ok = true for attr in __all__ begin set is_ok = is_ok ? call get attribute _checks attr client end if is_ok begin call secho stri...
def doctor(ctx, client): """Check your system and repository for potential problems.""" click.secho('\n'.join(textwrap.wrap(DOCTOR_INFO)) + '\n', bold=True) from . import _checks is_ok = True for attr in _checks.__all__: is_ok &= getattr(_checks, attr)(client) if is_ok: click....
Python
jtatman_500k
comment -*- coding: utf-8 -*- import os import sqlite3 function create_db db_name begin set conn = call connect db_name set c = call cursor set query = string CREATE TABLE cliente (id_cliente integer PRIMARY KEY AUTOINCREMENT, nombre text,rut text,direccion text,telefono text,empresa text,rut_empresa text,correo text) ...
# -*- coding: utf-8 -*- import os import sqlite3 def create_db(db_name): conn = sqlite3.connect(db_name) c= conn.cursor() query = """CREATE TABLE cliente (id_cliente integer PRIMARY KEY AUTOINCREMENT, nombre text,rut text,direccion text,telefono text,empr...
Python
zaydzuhri_stack_edu_python
import csv comment Definiamo la lista delle province che ci servono set citta = list string Palermo string Napoli string Roma string Milano string Torino function get_data begin comment Apriamo il file che conterrà solo i dati che ci servono set f = open string Densita di posti letto nelle strutture ricettive.csv strin...
import csv citta = ["Palermo", "Napoli", "Roma", "Milano", "Torino"] #Definiamo la lista delle province che ci servono def get_data(): f = open("Densita di posti letto nelle strutture ricettive.csv","wt") #Apriamo il file che conterrà solo i dati che ci servono writer = csv.writer(f) writer.writerow...
Python
zaydzuhri_stack_edu_python
function list cls begin set pipelines = list set _pipeline_data = call _api_get_pipelines for pipeline in _pipeline_data begin set _tmp_pipe = load cls pipeline unknown=EXCLUDE call update_fed_status append pipelines _tmp_pipe end return pipelines end function
def list(cls): pipelines = [] _pipeline_data = cls._api_get_pipelines() for pipeline in _pipeline_data: _tmp_pipe = cls.load(pipeline, unknown=EXCLUDE) _tmp_pipe.update_fed_status() pipelines.append(_tmp_pipe) return pipelines
Python
nomic_cornstack_python_v1
import re import sys import zhon from zhon import hanzi function count_chinese_chars input begin set chars_unique = set set chars_count = 0 set chars = find all string [%s] % characters input if not chars begin return tuple 0 0 end else begin for x in chars begin set chars_count = chars_count + 1 if x not in chars_uniq...
import re import sys import zhon from zhon import hanzi def count_chinese_chars(input): chars_unique = set() chars_count = 0 chars = re.findall('[%s]' % zhon.hanzi.characters, input) if not chars: return 0, 0 else: for x in chars: chars_count = chars_count + 1 if x not in chars_unique: chars_unique....
Python
zaydzuhri_stack_edu_python