code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Created by Jasper Davey import sqlite3 , sqlinterface set db_name = call raw_input string Please enter name of database: set conn = call connect db_name
# Created by Jasper Davey import sqlite3, sqlinterface db_name = raw_input("Please enter name of database: ") conn = sqlite3.connect(db_name)
Python
zaydzuhri_stack_edu_python
comment matplotlib.pylot这里并未使用,所以pycharm没有高亮语句 import matplotlib.pyplot as plt import numpy as np comment 引入高级优化方法 import scipy.optimize as opt from plotData import * comment 这一句是可以将同一文件目录下的文件简化引入的 import costFunction as cf import plotDecisionBoundary as pdb import predict as predict from sigmoid import * comment 读取txt...
import matplotlib.pyplot as plt # matplotlib.pylot这里并未使用,所以pycharm没有高亮语句 import numpy as np import scipy.optimize as opt # 引入高级优化方法 from plotData import * import costFunction as cf # 这一句是可以将同一文件目录下的文件简化引入的 import plotDecisionBoundary as pdb import predict as predict from sigmoid import * data = np.loadtxt('ex2dat...
Python
zaydzuhri_stack_edu_python
comment using the and function to create a fxn comment optimal solution: function And a b begin return a and b end function comment my solution (works): function And a b begin return a == true and b == true end function
# using the and function to create a fxn # optimal solution: def And(a, b): return a and b # my solution (works): def And(a, b): return a == True and b == True
Python
zaydzuhri_stack_edu_python
comment Given: A DNA string s of length at most 1000 bp. comment Return: The reverse complement s^c of s. comment Mateusz Dobrychlop, 2014 import sys set inp_string = argv at 1 set complementary = dict string A string T ; string T string A ; string C string G ; string G string C set out_string = string for char in inp...
# Given: A DNA string s of length at most 1000 bp. # # Return: The reverse complement s^c of s. # # Mateusz Dobrychlop, 2014 import sys inp_string = sys.argv[1] complementary = {"A":"T","T":"A","C":"G","G":"C"} out_string = "" for char in inp_string: out_string += complementary[char] out_string = out_string[:...
Python
zaydzuhri_stack_edu_python
function ingredient_from_dict ingr_dict selectable begin string Create an ingredient from an dictionary. This object will be deserialized from yaml comment TODO: This is deprecated in favor of comment ingredient_from_validated_dict comment Describe the required params for each kind of ingredient comment The key is the ...
def ingredient_from_dict(ingr_dict, selectable): """Create an ingredient from an dictionary. This object will be deserialized from yaml """ # TODO: This is deprecated in favor of # ingredient_from_validated_dict # Describe the required params for each kind of ingredient # The key is the param...
Python
jtatman_500k
function porttree_matches name begin string Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko"...
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/p...
Python
jtatman_500k
for _ in range T begin set N = integer input if K == 1 or K == 2 or K == 3 or K == 4 begin set A = N ^ K set B = N - 1 ^ K set List = list 0 * N comment print("Length",len(List)) set List at N - 1 = 1 set List at N - 2 = 0 for i in range N - 2 0 - 1 begin set j = i ^ K comment print(i,j) if B > A begin set A = A + j se...
for _ in range(T): N=int(input()) if K==1 or K==2 or K==3 or K==4: A=N**K B=(N-1)**K List=[0]*N # print("Length",len(List)) List[N-1]=1 List[N-2]=0 for i in range(N-2,0,-1): j=i**K # print(i,j) if B > A: A+=j List[i-1]=1 ...
Python
zaydzuhri_stack_edu_python
function infer_bbox_shape boxes begin call validate_bbox boxes set width : Tensor = boxes at tuple slice : : 1 0 - boxes at tuple slice : : 0 0 + 1 set height : Tensor = boxes at tuple slice : : 2 1 - boxes at tuple slice : : 0 1 + 1 return tuple height width end function
def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: validate_bbox(boxes) width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1 height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1 return height, width
Python
nomic_cornstack_python_v1
function _primes_less_than n begin comment Based on comment https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 set small_primes = array tuple 2 3 5 if n <= 6 begin return small_primes at small_primes < n end set sieve = ones n // 3 + n % 6 == 2 dtype=bool_ set s...
def _primes_less_than(n): # Based on # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 small_primes = np.array((2, 3, 5)) if n <= 6: return small_primes[small_primes < n] sieve = np.ones(n // 3 + (n % 6 == 2), dtype=np.bool_) sieve[0] = False ...
Python
nomic_cornstack_python_v1
import RPi.GPIO as GPIO call setmode BOARD from flask import Flask , render_template import os import time import datetime from temp import temperature set red_pin = 13 set green_pin = 15 set blue_pin = 16 setup GPIO red_pin OUT setup GPIO green_pin OUT setup GPIO blue_pin OUT call output red_pin false call output gree...
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) from flask import Flask, render_template import os import time import datetime from temp import temperature red_pin = 13 green_pin = 15 blue_pin = 16 GPIO.setup(red_pin, GPIO.OUT) GPIO.setup(green_pin, GPIO.OUT) GPIO.setup(blue_pin, GPIO.OUT) GPIO.output(red_pin, False)...
Python
zaydzuhri_stack_edu_python
function convert_to_RGB_255 colors begin return tuple colors at 0 * 255.0 colors at 1 * 255.0 colors at 2 * 255.0 end function
def convert_to_RGB_255(colors): return (colors[0]*255.0, colors[1]*255.0, colors[2]*255.0)
Python
nomic_cornstack_python_v1
function is_complete node name=string begin if not name begin return all generator expression call is_complete node name for name in list string Parameters string Attributes end set tuple docstring_params signature_params = call get_params node name for param in signature_params begin if param not in docstring_params b...
def is_complete(node: Node, name: str = "") -> bool: if not name: return all(is_complete(node, name) for name in ["Parameters", "Attributes"]) docstring_params, signature_params = get_params(node, name) for param in signature_params: if param not in docstring_params: return Fals...
Python
nomic_cornstack_python_v1
comment Here we will take string input from the user print string Enter your Name: set Name = input print string Hello, Name comment or print string Enter your Name: set orName = input print string Hello, + orName comment both above method works comment lets discuss unputting numbers also print string Enter your Number...
# Here we will take string input from the user print("Enter your Name: ") Name = input() print("Hello, ", Name) #or print("Enter your Name: ") orName = input() print("Hello, " + orName) #both above method works # lets discuss unputting numbers also print("Enter your Number: ") Number = input() print("Its your Numbe...
Python
zaydzuhri_stack_edu_python
class PriorityQueue begin function __init__ self begin set heap = list end function function insert self element priority begin append heap tuple element priority call _bubble_up length heap - 1 end function function delete_min self begin if call is_empty begin return none end set min_element = heap at 0 at 0 set last...
class PriorityQueue: def __init__(self): self.heap = [] def insert(self, element, priority): self.heap.append((element, priority)) self._bubble_up(len(self.heap) - 1) def delete_min(self): if self.is_empty(): return None min_element = self.heap[0][0] ...
Python
jtatman_500k
function calcMargiProb cadId M begin return array list comprehension sum cadId == m for m in range M / shape at 0 end function
def calcMargiProb(cadId, M): return np.array([np.sum(cadId == m) for m in range(M)]) / cadId.shape[0]
Python
nomic_cornstack_python_v1
function RL_deconv y kernel iterations=4 mass_conserve=true begin set y_mass = sum y set x_hat = ones shape set r = ones shape comment Iterate towards ML estimate for the latent signal for i in range iterations begin set y_hat = call conv_ x_hat kernel set r at y_hat > 0 = y at y_hat > 0 / y_hat at y_hat > 0 set x_hat ...
def RL_deconv(y, kernel, iterations=4, mass_conserve=True): y_mass = np.sum(y) x_hat = np.ones(y.shape) r = np.ones(y.shape) # Iterate towards ML estimate for the latent signal for i in range(iterations): y_hat = conv_(x_hat, kernel) r[y_hat > 0] = y[y_hat > 0] / y_hat[y_ha...
Python
nomic_cornstack_python_v1
function setBindingStatus self *args begin return call OutwardBindingSite_setBindingStatus self *args end function
def setBindingStatus(self, *args): return _libsbml.OutwardBindingSite_setBindingStatus(self, *args)
Python
nomic_cornstack_python_v1
import numpy as np import math import linear_perceptron import read_data import rbf_svm from prettytable import PrettyTable function run k X y c shuffle=false begin set tuple n d = call shape X set accuracy_percentage = list end function
import numpy as np import math import linear_perceptron import read_data import rbf_svm from prettytable import PrettyTable def run(k,X,y,c, shuffle=False): (n, d) = np.shape(X) accuracy_percentage = []
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D set a = list 4.05 0 0 set b = list 0 4.05 0 set c = list 0 0 4.05 set HKL = list list - 2 2 list - 2 2 list - 2 2 comment create RL primitive vector set V = dot a call cross b c set aa = call cross b c / V set ba = call cross c a...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D a = [4.05, 0, 0] b = [0, 4.05, 0] c = [0, 0, 4.05] HKL = [[-2, 2], [-2, 2], [-2, 2]] # create RL primitive vector V = np.dot(a, np.cross(b, c)) aa = np.cross(b, c)/V ba = np.cross(c, a)/V ca = np.cross(a, b)/V # cre...
Python
zaydzuhri_stack_edu_python
function potion self begin return call potion end function
def potion(self): return self.spec.potion()
Python
nomic_cornstack_python_v1
function test_invalid_partition_in_header self begin set broker = call broker call store_args name=string test_invalid_partition_in_header expect=EXPECT_EXIT_OK set msg_content = string xyz * 100 set msg = call Message msg_content durable=true call send_message string testQueue msg terminate broker set qls_dir = join p...
def test_invalid_partition_in_header(self): broker = self.broker(store_args(), name="test_invalid_partition_in_header", expect=EXPECT_EXIT_OK) msg_content = "xyz"*100 msg = Message(msg_content, durable=True) broker.send_message("testQueue", msg) broker.terminate() qls_di...
Python
nomic_cornstack_python_v1
class position begin function __init__ self x y begin set x = x set y = y end function function __eq__ self other begin if is instance other position begin return x == x and y == y end return false end function function getx self begin return x end function function gety self begin return y end function function update...
class position: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if isinstance(other, position): return self.x == other.x and self.y == other.y return False def getx(self): return self.x def gety(self): return self.y ...
Python
zaydzuhri_stack_edu_python
function CreateTrimmedSheet4 self Curves=defaultNamedNotOptArg PreserveAnalyticCurves=defaultNamedNotOptArg begin set ret = call InvokeTypes 75 LCID 1 tuple 9 0 tuple tuple 12 1 tuple 11 1 Curves PreserveAnalyticCurves if ret is not none begin set ret = call Dispatch ret string CreateTrimmedSheet4 none end return ret e...
def CreateTrimmedSheet4(self, Curves=defaultNamedNotOptArg, PreserveAnalyticCurves=defaultNamedNotOptArg): ret = self._oleobj_.InvokeTypes(75, LCID, 1, (9, 0), ((12, 1), (11, 1)),Curves , PreserveAnalyticCurves) if ret is not None: ret = Dispatch(ret, u'CreateTrimmedSheet4', None) return ret
Python
nomic_cornstack_python_v1
comment ... function ask_user begin while true begin print string Как дела? set user_answer = input if user_answer == string Хорошо begin break end else if user_answer == string Пока begin break end else begin print format string Сам ты {} user_answer end end end function call ask_user
#... def ask_user(): while True: print('Как дела?') user_answer = input() if user_answer == 'Хорошо': break elif user_answer == 'Пока': break else: print('Сам ты {}'.format(user_answer)) ask_user()
Python
zaydzuhri_stack_edu_python
function to_dict self begin return dict field message end function
def to_dict(self): return {self.field: self.message}
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import unittest from tokenizer_new import Token , Tokenizer class TokenizerTest extends TestCase begin string tests for tokenizer_new.py function test_regular self begin string tests a string with mixed alphabetical symbols, numbers, whitespaces, and punctuation set tokens = call tokenize ...
# -*- coding: utf-8 -*- import unittest from tokenizer_new import Token, Tokenizer class TokenizerTest(unittest.TestCase): '''tests for tokenizer_new.py''' def test_regular(self): ''' tests a string with mixed alphabetical symbols, numbers, whitespaces, and punctuation ...
Python
zaydzuhri_stack_edu_python
function plugin_poll handle begin global _handle _restart_config set bluetooth_adr = _handle at string bluetoothAddress at string value set tag = _handle at string tag set asset_prefix = replace format string {} _handle at string assetNamePrefix at string value string %M bluetooth_adr try begin if not is_connected begi...
def plugin_poll(handle): global _handle, _restart_config bluetooth_adr = _handle['bluetoothAddress']['value'] tag = _handle['tag'] asset_prefix = '{}'.format(_handle['assetNamePrefix']['value']).replace('%M', bluetooth_adr) try: if not tag.is_connected: raise RuntimeError("Sens...
Python
nomic_cornstack_python_v1
function power a n begin if a <= 0 or n < 0 begin return string Enter correct numbers end if n == 0 begin return 1 end else begin return a * call power a n - 1 end end function print string a**n= call power a n input
def power(a, n): if a <= 0 or n < 0: return "Enter correct numbers" if n == 0: return 1 else: return a*power(a, n-1) print("a**n= ", power(a, n)) input()
Python
zaydzuhri_stack_edu_python
function look_at vertices eye at=none up=none begin assert ndim == 3 set xp = call get_array_module vertices set batch_size = shape at 0 if at is none begin set at = array list 0 0 0 string float32 end if up is none begin set up = array list 0 1 0 string float32 end if is instance eye list or is instance eye tuple begi...
def look_at(vertices, eye, at=None, up=None): assert (vertices.ndim == 3) xp = chainer.cuda.get_array_module(vertices) batch_size = vertices.shape[0] if at is None: at = xp.array([0, 0, 0], 'float32') if up is None: up = xp.array([0, 1, 0], 'float32') if isinstance(eye, list) o...
Python
nomic_cornstack_python_v1
comment encoding=utf-8 comment Copyright 2015 The TensorFlow Authors. All Rights Reserved. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/licens...
# encoding=utf-8 # Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
Python
zaydzuhri_stack_edu_python
function _testmodel_operations_delete self name begin set appWrapper = _wrapper set r = post url=string https:// + host + string /bps/api/v2/core/testmodel/operations/delete headers=dict string content-type string application/json data=dumps dict string name name verify=false set jsonContent = content is not none and s...
def _testmodel_operations_delete(self, name): appWrapper = self._wrapper r = appWrapper.session.post(url='https://' + appWrapper.host + '/bps/api/v2/core/testmodel/operations/delete', headers={'content-type': 'application/json'}, data=json.dumps({'name': name}), verify=False) jsonContent = r.con...
Python
nomic_cornstack_python_v1
from project1 import redactor set test_string = string My name is Madison, but sometimes I go by Maddi by my friends. comment Tests the redact_names function function test_names begin print string Unredacted text: + test_string set text = call redact_names test_string assert length text at 1 == 2 print string Redacted ...
from project1 import redactor test_string = "My name is Madison, but sometimes I go by Maddi by my friends." #Tests the redact_names function def test_names(): print('\nUnredacted text: ' + test_string) text = redactor.redact_names(test_string) assert len(text[1]) == 2 print('Redacted text: ' + t...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import cache import csvutf8 import os import urllib import urllib2 import json import time set nominatimBaseURL = string http://ubuntu.local/nominatim/search.php? set sleepInterval = 0 comment nominatimBaseURL = 'http://nominatim.openstreetmap.org/search.php?' comment sleepInterval = 1 set ...
#!/usr/bin/env python import cache import csvutf8 import os import urllib import urllib2 import json import time nominatimBaseURL = 'http://ubuntu.local/nominatim/search.php?' sleepInterval = 0 #nominatimBaseURL = 'http://nominatim.openstreetmap.org/search.php?' #sleepInterval = 1 results = [['id', 'lat', 'lon']] br...
Python
zaydzuhri_stack_edu_python
function gen_kCD_checks vv ww h phi psi qhat I9 nn kkin mcJump nmc G0 A0 begin comment Prep meetings set veci = as type random integer 0 nn list nmc int32 comment kkin sample for dimensions of k set nkk = shape at 0 if nkk > 1 begin set veck = kkin at random integer 0 nkk list nmc end else begin set veck = ones list nm...
def gen_kCD_checks(vv, ww, h, phi, psi, qhat, I9, nn, kkin, mcJump, nmc, G0, A0): ## Prep meetings veci = (np.random.randint(0,nn,[nmc])).astype(np.int32) nkk = kkin.shape[0] #kkin sample for dimensions of k if nkk>1: veck = kkin[np.random.randint(0,nkk,[nmc])]...
Python
nomic_cornstack_python_v1
function __init__ self file_path=string data/ batch_size=1 img_size=list 128 2048 max_text_len=256 begin comment filePath needs to be a folder assert file_path at - 1 == string / set current_index = 0 set batch_size = batch_size set img_size = img_size set samples = list comment metadata for words in words.txt set f =...
def __init__(self, file_path="data/", batch_size=1, img_size=[128, 2048], max_text_len=256): # filePath needs to be a folder assert file_path[-1]=='/' self.current_index = 0 self.batch_size = batch_size self.img_size = img_size self.samples = [] # met...
Python
nomic_cornstack_python_v1
string 只加载部分参数,通过提供默认列表 本脚本提供两个测试: 1. 通过key加载部分变量 2. 通过字典序列加载部分变量的同时,重命名变量 import tensorflow as tf function load_some_vars_test begin comment 注意这里Tensorflow在计算图中寻找的是name="xx"的关键字,而不是变量名 set v1 = call Variable call constant 0 shape=list 1 dtype=float32 name=string v1 set saver = call Saver list v1 with call Session as s...
""" 只加载部分参数,通过提供默认列表 本脚本提供两个测试: 1. 通过key加载部分变量 2. 通过字典序列加载部分变量的同时,重命名变量 """ import tensorflow as tf def load_some_vars_test(): # 注意这里Tensorflow在计算图中寻找的是name="xx"的关键字,而不是变量名 v1 = tf.Variable(tf.constant(0, shape=[1], dtype=tf.float32), name="v1") saver = tf.train.Saver([v1]) with tf.Session() as sess: ...
Python
zaydzuhri_stack_edu_python
comment HELPERS function log msg noisy level=string INFO begin if noisy begin print format string [{}] SUBLIME-REMOTE: {} level msg end end function
# # HELPERS # def log(msg,noisy,level='INFO'): if noisy: print("[{}] SUBLIME-REMOTE: {}".format(level,msg))
Python
zaydzuhri_stack_edu_python
comment importing required libraries of opencv import cv2 import numpy as np function withinClassVariance thr hist begin set WB = sum hist at slice : thr : / 64 * 64 if sum hist at slice : thr : == 0 or sum hist at slice thr : : == 0 begin return inf end set meanB = 0 for i in range thr begin set meanB = meanB + i *...
# importing required libraries of opencv import cv2 import numpy as np def withinClassVariance(thr,hist): WB=sum(hist[:thr])/(64*64) if sum(hist[:thr])==0 or sum(hist[thr:])==0 : return np.inf meanB=0 for i in range(thr): meanB+=(i*hist[i]) meanB/=sum(hist[:thr]) varB=0 ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt function straightify values begin set returnval = list for num in values begin append returnval 1000 / num end return returnval end function set data = call read_excel string dataset-whole-rainfall.xlsx set X = values set y = values from sklearn.im...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def straightify(values): returnval = [] for num in values: returnval.append(1000/num) return returnval data = pd.read_excel("dataset-whole-rainfall.xlsx") X = data.iloc[:,[12]].values y = data.iloc[:,[9]].values fr...
Python
zaydzuhri_stack_edu_python
function addlist list begin set sum = 0 for num in list begin set sum = sum + integer num end return print string Sum = sum end function comment Driver Code ########### call addlist list
def addlist(list): sum = 0 for num in list: sum += int (num) return print("Sum = ",sum) ##### Driver Code ########### addlist(list)
Python
zaydzuhri_stack_edu_python
function filter_top_level item begin return parent_item is none end function
def filter_top_level(item): return item.parent_item is None
Python
nomic_cornstack_python_v1
function get_sentence_words sentence unique=false keep_case=false remove_punctuation=true remove_specials=true begin set words = split strip call clean_sentence sentence keep_case=keep_case remove_punctuation=remove_punctuation remove_specials=remove_specials if unique begin set words = list set words end return words ...
def get_sentence_words(sentence: str, unique: Optional[bool] = False, keep_case: Optional[bool] = False, remove_punctuation: Optional[bool] = True, remove_specials: Optional[bool] = True) -> List[str]: words = clean_sentence...
Python
nomic_cornstack_python_v1
function test_plant_create_super_user self begin set url = reverse string plant-list call force_authenticate user=superuser set data = dict string name string Rose ; string description string Description de la rose ; string humidity_spec string 45.2 ; string luminosity_spec string 12.32 ; string temperature_spec string...
def test_plant_create_super_user(self): url = reverse('plant-list') self.client.force_authenticate(user=self.superuser) data = { 'name': 'Rose', 'description': 'Description de la rose', 'humidity_spec': '45.2', 'luminosity_spec': '12.32', ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on 2021/5/6 18:27 Filename : ex_009_thread.py Author : Taosy.W Zhihu : https://www.zhihu.com/people/1105936347 Github : https://github.com/AFei19911012 Description: import threading import time comment 定义线程函数 function print_time thread_name delay begin set count = 0 while co...
# -*- coding: utf-8 -*- """ Created on 2021/5/6 18:27 Filename : ex_009_thread.py Author : Taosy.W Zhihu : https://www.zhihu.com/people/1105936347 Github : https://github.com/AFei19911012 Description: """ import threading import time # 定义线程函数 def print_time(thread_name, delay): count = 0 ...
Python
zaydzuhri_stack_edu_python
from sys import stdout from util.timer import Timer from util.dump import load_object , dump_object import neural_network.reader as reader from feature_selection.spearman import spearman from feature_selection.pearson import pearson from feature_selection.information_gain import information_gain import numpy as np func...
from sys import stdout from util.timer import Timer from util.dump import load_object, dump_object import neural_network.reader as reader from feature_selection.spearman import spearman from feature_selection.pearson import pearson from feature_selection.information_gain import information_gain import numpy as np def...
Python
zaydzuhri_stack_edu_python
from datetime import date set loop = 1 set fdata = open string C:\aof.py\data_friends.txt string w while loop <= 5 begin set tuple Name Nickname Birth Province School = split input string Name : Nickname : Date of Birth : Province : School =====> string : write fdata string %s,%s,%s,%s,%s % tuple Name Nickname Birth Pr...
from datetime import date loop = 1 fdata = open("C:\\aof.py\\data_friends.txt","w") while loop <= 5: Name,Nickname,Birth,Province,School = input("Name : Nickname : Date of Birth : Province : School =====> ").split(':') fdata.write('%s,%s,%s,%s,%s\n'%(Name,Nickname,Birth,Province,School)) loop += 1 fd...
Python
zaydzuhri_stack_edu_python
function _set_scanning_defer_traffic 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=YANGBool is_leaf=true yang_name=string scanning-defer-traffic parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true namespace...
def _set_scanning_defer_traffic(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="scanning-defer-traffic", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://open...
Python
nomic_cornstack_python_v1
set persona1 = integer input string Cuanto dinero va a depositar: set persona2 = integer input string Cuanto dinero va a depositar: set persona3 = integer input string Cuanto dinero va a depositar: set sumatoria = persona1 + persona2 + persona3 print string La cantidad total sumada de dinero es: + string sumatoria prin...
persona1 = int(input("Cuanto dinero va a depositar: ")) persona2 = int(input("Cuanto dinero va a depositar: ")) persona3 = int(input("Cuanto dinero va a depositar: ")) sumatoria= (persona1+persona2+persona3) print("La cantidad total sumada de dinero es: "+str(sumatoria)) print("La primer persona deposito: "+st...
Python
zaydzuhri_stack_edu_python
from models.stock_firm import StockFirm from models.ticker import StockTicker from repositories.stock_firm_writer import StockFirmWriter from repositories.ticker_writer import TickerWriter from stock_reader import StockReader set __all__ = tuple string StockRegisterer class StockRegisterer begin function __init__ self ...
from ..models.stock_firm import StockFirm from ..models.ticker import StockTicker from ..repositories.stock_firm_writer import StockFirmWriter from ..repositories.ticker_writer import TickerWriter from .stock_reader import StockReader __all__ = ("StockRegisterer",) class StockRegisterer: def __init__( se...
Python
zaydzuhri_stack_edu_python
import pytest import hash_table.four_sum as prob class TestFourSum begin function test_example1 self begin set nums1 = list 1 2 set nums2 = list - 2 - 1 set nums3 = list - 1 2 set nums4 = list 0 2 set res = 2 assert call fourSumCount nums1 nums2 nums3 nums4 == res end function function test_example2 self begin set nums...
import pytest import hash_table.four_sum as prob class TestFourSum: def test_example1(self): nums1 = [1,2] nums2 = [-2,-1] nums3 = [-1,2] nums4 = [0,2] res = 2 assert prob.fourSumCount(nums1, nums2, nums3, nums4) == res def test_example2(self): nums...
Python
zaydzuhri_stack_edu_python
from fractions import Fraction function calculate_probability card1 card2 begin set total_cards = 52 comment Probability of drawing the specific card from the first deck set probability_card1 = call Fraction 1 total_cards comment Probability of drawing the specific card from the second deck set probability_card2 = call...
from fractions import Fraction def calculate_probability(card1, card2): total_cards = 52 # Probability of drawing the specific card from the first deck probability_card1 = Fraction(1, total_cards) # Probability of drawing the specific card from the second deck probability_card2 = Fraction...
Python
dbands_pythonMath
function get_other_content self obj begin set has_annotations = get context string has_annotations if not has_annotations and not get context string direct_request begin return none end comment check if the canvas has any non-image annotation pages set sid = obj at string id set req = get context string request set cfg...
def get_other_content(self, obj: SolrResult) -> Optional[List]: has_annotations = self.context.get("has_annotations") if not has_annotations and not self.context.get('direct_request'): return None # check if the canvas has any non-image annotation pages sid = obj["id"] ...
Python
nomic_cornstack_python_v1
function SetSplitterLeft *args **kwargs begin return call PropertyGridManager_SetSplitterLeft *args keyword kwargs end function
def SetSplitterLeft(*args, **kwargs): return _propgrid.PropertyGridManager_SetSplitterLeft(*args, **kwargs)
Python
nomic_cornstack_python_v1
function create_ngram_set input_list ngram_value=2 begin return set zip *[input_list[i:] for i in range(ngram_value)] end function
def create_ngram_set(input_list, ngram_value=2): return set(zip(*[input_list[i:] for i in range(ngram_value)]))
Python
nomic_cornstack_python_v1
function _serverSRPKeyExchange self clientHello serverHello verifierDB cipherSuite privateKey serverCertChain settings begin try begin set tuple sigHash serverCertChain privateKey = call _pickServerKeyExchangeSig settings clientHello serverCertChain privateKey end except TLSHandshakeFailure as alert begin for result in...
def _serverSRPKeyExchange(self, clientHello, serverHello, verifierDB, cipherSuite, privateKey, serverCertChain, settings): try: sigHash, serverCertChain, privateKey = \ self._pickServerKeyExchangeSig(settings, clientHello, ...
Python
nomic_cornstack_python_v1
function topics_with_links self begin comment This is a little kludgy and it seems to be cleaner to just comment handle this in a ``get_absolute_url`` method of the comment ``Category`` model. However, I wanted to keep the knowledge of comment the explore view decoupled from the Categories model in case we comment want...
def topics_with_links(self): # This is a little kludgy and it seems to be cleaner to just # handle this in a ``get_absolute_url`` method of the # ``Category`` model. However, I wanted to keep the knowledge of # the explore view decoupled from the Categories model in case we ...
Python
nomic_cornstack_python_v1
function add self collection data _id=none begin set db = call connect set data = call convert data if _id is not none begin set data at string _id = _id end set _id = insert db at collection data return get self collection _id end function
def add(self, collection, data, _id=None): db = self.connect() data = convert(data) if _id is not None: data['_id'] = _id _id = db[collection].insert(data) return self.get(collection, _id)
Python
nomic_cornstack_python_v1
function julian_date year month=1 day=1 hour=0 minute=0 second=0.0 begin return call julian_day year month day - 0.5 + second + minute * 60.0 + hour * 3600.0 / DAY_S end function
def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0): return julian_day(year, month, day) - 0.5 + ( second + minute * 60.0 + hour * 3600.0) / DAY_S
Python
nomic_cornstack_python_v1
function name self begin return get pulumi self string name end function
def name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import random , string set limit = 2 * 10 ^ 5 set qlimit = 5 * 10 ^ 4 set loop = random integer 1 8 set pattern = join string generator expression random choice string a for _ in call xrange loop set text = pattern * random integer 1 limit / loop set n = random integer length text limit wh...
#!/usr/bin/env python import random, string limit = 2 * 10**5 qlimit = 5 * (10**4) loop = random.randint(1, 8) pattern = ''.join(random.choice('a') for _ in xrange(loop)) text = pattern * random.randint(1, limit / loop) n = random.randint(len(text), limit) while len(text) < n: text += pattern[len(text) % loop] ...
Python
zaydzuhri_stack_edu_python
function test_suggestive_line_input_width dash_threaded begin function assert_callback fig nclicks input_value begin set answer = string if nclicks is not none begin for shape in fig at string layout at string shapes begin if shape at string name == SUGGESTIVE_LINE_LABEL begin if shape at string line at string width =...
def test_suggestive_line_input_width(dash_threaded): def assert_callback(fig, nclicks, input_value): answer = '' if nclicks is not None: for shape in fig['layout']['shapes']: if shape['name'] == SUGGESTIVE_LINE_LABEL: if shape['line']['width'] == floa...
Python
nomic_cornstack_python_v1
function test_import_robot_tags begin with call temporary_dir as output_dir begin call copyfile TEST_ROBOT_OUTPUT_FILES / string robot_1.xml call Path output_dir / string output.xml call import_robot_test_results call FlowTaskFactory output_dir end set test_results = filter method__name=string FakeTestResult set actual...
def test_import_robot_tags(): with temporary_dir() as output_dir: copyfile( TEST_ROBOT_OUTPUT_FILES / "robot_1.xml", Path(output_dir) / "output.xml", ) robot_importer.import_robot_test_results(FlowTaskFactory(), output_dir) test_results = models.TestResult.objects...
Python
nomic_cornstack_python_v1
function test_api__create_workspace_member_role__ok_200__email_notif_disabe_but_invitation_notif_enabled self begin set authorization = tuple string Basic tuple string admin@admin.admin string admin@admin.admin set dbsession = call get_tm_session session_factory manager set admin = call one set workspace_api = call Wor...
def test_api__create_workspace_member_role__ok_200__email_notif_disabe_but_invitation_notif_enabled( self ): self.testapp.authorization = ("Basic", ("admin@admin.admin", "admin@admin.admin")) dbsession = get_tm_session(self.session_factory, transaction.manager) admin = dbsession.quer...
Python
nomic_cornstack_python_v1
class LinkedList begin function __init__ self begin set head = none end function function length self begin set count = 0 set current = head while current begin set count = count + 1 set current = next end return count end function function is_empty_and_length self begin set is_empty = false set length = call length if...
class LinkedList: def __init__(self): self.head = None def length(self): count = 0 current = self.head while current: count += 1 current = current.next return count def is_empty_and_length(self): is_empty = False length = self...
Python
jtatman_500k
for i in t begin if i >= length t or i < 0 begin set list at length t % i = i end else begin set list at i = i end end print join string generator expression string x for x in list
for i in t: if i>=len(t) or i<0 : list[len(t)%i]=i else : list[i]=i print(" ".join(str(x) for x in list))
Python
zaydzuhri_stack_edu_python
class Circulo begin set pi = 3.141592 function __init__ self radio begin set __radio = radio end function decorator property function cuadrado self n begin return n ^ 2 end function decorator setter function area self begin return pi * call cuadrado radio end function function valorRadio self begin return radio end fun...
class Circulo: pi = 3.141592 def __init__(self, radio): self.__radio = radio @property def cuadrado(self, n): return n ** 2 @cuadrado.setter def area(self): return Circulo.pi * self.cuadrado(self.radio) def valorRadio(self): return sel...
Python
zaydzuhri_stack_edu_python
function startRecording2 self folderPath fileName overwrite begin if not proxy begin set proxy = call service string ALVideoRecorder end return call startRecording folderPath fileName overwrite end function
def startRecording2(self, folderPath, fileName, overwrite): if not self.proxy: self.proxy = self.session.service("ALVideoRecorder") return self.proxy.startRecording(folderPath, fileName, overwrite)
Python
nomic_cornstack_python_v1
for i in range length b begin if b at i not in d begin set flag = 1 end end if c == a or flag == 1 begin print string no end else begin print string yes end
for i in range(len(b)): if b[i] not in d: flag=1 if c==a or flag==1: print('no') else: print('yes')
Python
zaydzuhri_stack_edu_python
function position t=string now begin set ra = call true_rightascension t set dec = call true_declination t return tuple ra dec end function
def position(t='now'): ra = true_rightascension(t) dec = true_declination(t) return ra, dec
Python
nomic_cornstack_python_v1
function ow_search self vid=188 pid=none name=none begin string Search for specific memory id/name and return it for m in call get_mems TYPE_1W begin if pid and pid == pid or name and name == name begin return m end end return none end function
def ow_search(self, vid=0xBC, pid=None, name=None): """Search for specific memory id/name and return it""" for m in self.get_mems(MemoryElement.TYPE_1W): if pid and m.pid == pid or name and m.name == name: return m return None
Python
jtatman_500k
import requests from bs4 import BeautifulSoup set url = string https://www.loggedon.co.za/ set response = get requests url verify=false set soup = call BeautifulSoup text string lxml set articles = find all soup string article class_=string post print type articles for i in articles begin set title = find all i string ...
import requests from bs4 import BeautifulSoup url = 'https://www.loggedon.co.za/' response = requests.get(url, verify=False) soup = BeautifulSoup(response.text,'lxml') articles = soup.find_all('article', class_='post') print(type(articles)) for i in articles: title=i.find_all('h1', class_='entry-title') print(...
Python
zaydzuhri_stack_edu_python
comment 决策树 comment 非参数的学习算法 comment 可以解决分类问题,天然可以解决多分类问题 comment 也可以解决回归问题 import numpy as np import matplotlib.pyplot as plt from sklearn import datasets set iris = call load_iris print data set x = data at tuple slice : : slice 2 : : set y = target print y == 2 comment plt.scatter(x[y==0,0],x[y==0,1]) comment p...
# 决策树 # 非参数的学习算法 # 可以解决分类问题,天然可以解决多分类问题 # 也可以解决回归问题 import numpy as np import matplotlib.pyplot as plt from sklearn import datasets iris = datasets.load_iris() print(iris.data) x = iris.data[:,2:] y = iris.target print(y==2) # plt.scatter(x[y==0,0],x[y==0,1]) # plt.scatter(x[y==1,0],x[y==1,1]) # plt.scatter(x[y==2,0],...
Python
zaydzuhri_stack_edu_python
comment Author: UesrName comment Email: UesrEmail comment Time: 2013,09,08 13:31:22 comment Description: count the lines, types and words of files comment Version: 2.0 comment Option: wc -l file comment wc -l -w -c file comment wc -lwc file comment wc file1 file2 comment wc --help file comment wc file --help import os ...
# Author: UesrName # Email: UesrEmail # Time: 2013,09,08 13:31:22 # Description: count the lines, types and words of files # Version: 2.0 # Option: wc -l file # wc -l -w -c file # wc -lwc file # wc file1 file2 # wc --help file # wc file --help import os import sys
Python
zaydzuhri_stack_edu_python
for i in indexes begin if completed at i begin print string { groceries at i } :checked end else begin print string { groceries at i } :uncheck end end
for i in indexes: if completed[i]: print (f'{groceries[i]}:checked') else: print(f'{groceries[i]}:uncheck')
Python
zaydzuhri_stack_edu_python
function getDomain self begin pass end function
def getDomain(self): pass
Python
nomic_cornstack_python_v1
async function wait_message self begin string Blocks until new message appear. if not call empty begin return true end if closed begin return false end await wait _queue return is_active end function
async def wait_message(self): """Blocks until new message appear.""" if not self._queue.empty(): return True if self._queue.closed: return False await self._queue.wait() return self.is_active
Python
jtatman_500k
function create_proxy_model self model parent name multiplicity=ZERO_MANY **kwargs begin call check_type model Part string model call check_type parent Part string parent if category != MODEL begin raise call IllegalArgumentError string The model should be of category MODEL end if category != MODEL begin raise call Ill...
def create_proxy_model( self, model: Part, parent: Part, name: str, multiplicity: Optional[Multiplicity] = Multiplicity.ZERO_MANY, **kwargs, ) -> Part: check_type(model, Part, "model") check_type(parent, Part, "parent") if model.category != Ca...
Python
nomic_cornstack_python_v1
function save self file_name begin with open file_name string w+ as out_file begin set content = dict string version VERSION ; string cached cached dump content out_file end end function
def save(self, file_name): with open(file_name, "w+") as out_file: content = {"version": self.VERSION, "cached": self.cached} pickle.dump(content, out_file)
Python
nomic_cornstack_python_v1
function flatten_node node begin set flat = dict function flatten_node node begin string Replicate the node. if string node_id not in flat begin set flat at string node_id = node_id set flat at string label = label if string project_id in properties begin set tuple program project = split properties at string project_...
def flatten_node(node): flat = {} def flatten_node(node): """Replicate the node.""" if 'node_id' not in flat: flat['node_id'] = node.node_id flat['label'] = node.label if 'project_id' in node.properties: program, project = node.properties['proj...
Python
nomic_cornstack_python_v1
class statement extends object begin comment A statement has a predicate, a set of arguments that is applies to and a list of comment statements/rules that it supports (initially empty). Arguments are processed to comment turn both variables and constants into objects. function __init__ self pattern begin set full = pa...
class statement(object): # A statement has a predicate, a set of arguments that is applies to and a list of # statements/rules that it supports (initially empty). Arguments are processed to # turn both variables and constants into objects. def __init__(self, pattern): self.full = pattern self.pred...
Python
zaydzuhri_stack_edu_python
function parse line begin set tuple c a = tuple index string EWSNFRL line at slice : 1 : integer line at slice 1 : : return tuple a * c == 0 - c == 1 a * c == 2 - c == 3 c == 4 * a a // 90 * c == 5 - c == 6 end function function solve_1 data x y a begin for tuple dx dy df da in data begin set tuple x y a = tuple x + ...
def parse(line): c, a = 'EWSNFRL'.index(line[:1]), int(line[1:]) return a * ((c == 0) - (c == 1)), a * ((c == 2) - (c == 3)), (c == 4) * a, (a//90) * ((c == 5) - (c == 6)) def solve_1(data, x, y, a): for dx, dy, df, da in data: x, y, a = x + dx + xs[a] * df, y + dy + ys[a] * df, (a + da)%4 retu...
Python
zaydzuhri_stack_edu_python
import pygame from pygame import Rect function draw_text surface message font_size center_position color=tuple 255 255 255 begin set font = call Font string freesansbold.ttf font_size set text = call render message true color set text_rect = call get_rect set center = center_position call blit text text_rect end functi...
import pygame from pygame import Rect def draw_text(surface, message, font_size, center_position, color=(255, 255, 255)): font = pygame.font.Font('freesansbold.ttf', font_size) text = font.render(message, True, color) text_rect = text.get_rect() text_rect.center = center_position surface.blit(text...
Python
zaydzuhri_stack_edu_python
function process_compile_entries processor spec entries modpath_logger=none targetpath_logger=none begin string The generalized raw spec entry process invocation loop. comment Contains a mapping of the module name to the compiled file's comment relative path starting from the base build_dir. set all_modpaths = dict se...
def process_compile_entries( processor, spec, entries, modpath_logger=None, targetpath_logger=None): """ The generalized raw spec entry process invocation loop. """ # Contains a mapping of the module name to the compiled file's # relative path starting from the base build_dir. all_modpa...
Python
jtatman_500k
function _get_audio_from_microphone self begin set audio = none if _microphone is not none begin with _microphone as source begin print string Ready for command... call adjust_for_ambient_noise source set audio = call listen source print format string Audio data = {} audio end end return audio end function
def _get_audio_from_microphone(self): audio = None if self._microphone is not None: with self._microphone as source: print('Ready for command...') self._recognizer.adjust_for_ambient_noise(source) audio = self._recognizer.listen(source) ...
Python
nomic_cornstack_python_v1
function load_game_data self begin set factory_service = call FactoryService set factory_service = factory_service set character_factory = call CharacterFactory factory_service=factory_service set character_factory = character_factory set character_factory = character_factory set item_factory = call ItemFactory end fun...
def load_game_data(self): self.game_context.factory_service = FactoryService() factory_service = self.game_context.factory_service character_factory = CharacterFactory(factory_service=self.game_context.factory_service) factory_service.character_factory = character_factory self.ga...
Python
nomic_cornstack_python_v1
import time , datetime import sys import traceback function formatExceptionInfo maxTBlevel=5 begin set tuple cla exc trbk = call exc_info set excName = __name__ try begin set excArgs = __dict__ at string args end except KeyError begin set excArgs = string <no args> end set excTb = call format_tb trbk maxTBlevel return ...
import time, datetime import sys import traceback def formatExceptionInfo(maxTBlevel=5): cla, exc, trbk = sys.exc_info() excName = cla.__name__ try: excArgs = exc.__dict__["args"] except KeyError: excArgs = "<no args>" excTb = traceback.format_tb(trbk, maxTBlevel) return (excNam...
Python
zaydzuhri_stack_edu_python
function getLandingUrlSearchEngine articleData begin try begin return call _getLandingUrlSearchEngine articleData end except pubGetError begin comment already captured raise end except Exception as ex begin exception ex comment capture information on what happened to save to docStatus.tab raise call pubGetError format ...
def getLandingUrlSearchEngine(articleData): try: return _getLandingUrlSearchEngine(articleData) except pubGetError: raise # already captured except Exception as ex: logging.exception(ex) # capture information on what happened to save to docStatus.tab raise pubGetErr...
Python
nomic_cornstack_python_v1
while true begin set aux = input set value = integer aux if value < 0 begin break end set soma = soma + value set n_p = n_p + 1 end print string %.2f % soma / n_p
while True: aux = input() value = int(aux) if value < 0: break soma += value n_p += 1 print("%.2f" % (soma / n_p))
Python
zaydzuhri_stack_edu_python
function set_cell self row col obj begin if is instance obj JavaObject begin set obj = jobject end call jobject string setCell string (IILjava/lang/Object;)V row col obj end function
def set_cell(self, row, col, obj): if isinstance(obj, JavaObject): obj = obj.jobject javabridge.call( self.jobject, "setCell", "(IILjava/lang/Object;)V", row, col, obj)
Python
nomic_cornstack_python_v1
function forward self x begin set X = concatenate tuple ones tuple shape at 0 1 x axis=1 set W = concatenate tuple b w axis=0 set a = dot X W return a raise call NotImplementedError string Layer forward pass not implemented. end function
def forward(self, x): X = np.concatenate((np.ones((x.shape[0],1)), x), axis = 1) W = np.concatenate((self.b, self.w), axis = 0) self.a = np.dot(X,W) return self.a raise NotImplementedError("Layer forward pass not implemented.")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment GET Unique hostnames from OpenPhish import requests set URL_DATA = string https://openphish.com/feed.txt set resp = get requests URL_DATA set urls = list split text string print string Hay { length urls } urls de phishing. set urls_unicas = list for url in urls begin set url = rep...
# -*- coding: utf-8 -*- # GET Unique hostnames from OpenPhish import requests URL_DATA = "https://openphish.com/feed.txt" resp = requests.get(URL_DATA) urls = list(resp.text.split("\n")) print(f"Hay {len(urls)} urls de phishing.") urls_unicas = [] for url in urls: url = url.replace("https://","") url =...
Python
zaydzuhri_stack_edu_python
function data_save self name color_by=0 begin set save_path = join path data_dir name + string .data comment point [type, x, y, z, color] set points = zeros shape set points at tuple slice : : 0 = points at tuple slice : : 5 set points at tuple slice : : slice 1 : 4 : = points at tuple slice : : slice 1 : ...
def data_save(self, name, color_by=0): self.save_path = os.path.join(self.data_dir, name+'.data') #point [type, x, y, z, color] points = np.zeros(self.points[:,0:5].shape) points[:,0] = self.points[:,5] points[:,1:4] = self.points[:,1:4] points[:,4] = self.points[:,9] bonds = np.zeros(self.links[:,0:2].sh...
Python
nomic_cornstack_python_v1
function get_latest_photos self count=30 page=1 begin set uri = string photos/latest set options = dict string per_page count ; string page page return call make_request uri options end function
def get_latest_photos(self, count = 30, page = 1): uri = 'photos/latest' options = { 'per_page': count, 'page': page } return self.make_request(uri, options)
Python
nomic_cornstack_python_v1
import csv from src.portfolio import naive_portfolio from src import event class StopLossTakeProfit extends NaivePortfolio begin string " Naive Portfolio with a Stop Loss and Take Profit. function __init__ self events equity begin set events = events set holdings = dict set updated_list = dict set history = list set...
import csv from src.portfolio import naive_portfolio from src import event class StopLossTakeProfit(naive_portfolio.NaivePortfolio): """" Naive Portfolio with a Stop Loss and Take Profit.""" def __init__(self, events, equity): self.events = events self.holdings = {} self.updated_list ...
Python
zaydzuhri_stack_edu_python
function get tgt fun tgt_type=string glob roster=string flat begin string Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the ros...
def get(tgt, fun, tgt_type='glob', roster='flat'): ''' Get data from the mine based on the target, function and tgt_type This will actually run the function on all targeted minions (like publish.publish), as salt-ssh clients can't update the mine themselves. We will look for mine_functions in the ...
Python
jtatman_500k
from tqdm.auto import tqdm class Explainer begin function __init__ self model recommendations data begin set model = model set recommendations = recommendations set dataset = dataset set num_items = num_item set num_users = num_user set users = group by dataset by=string userId end function function explain_recommendat...
from tqdm.auto import tqdm class Explainer: def __init__(self, model, recommendations, data): self.model = model self.recommendations = recommendations self.dataset = data.dataset self.num_items = data.num_item self.num_users = data.num_user self.users = self.datase...
Python
zaydzuhri_stack_edu_python
import os import sqlite3 set veritabani = string kitaplik.sqlite set dosya_mevcut = exists path veritabani set vt = call connect veritabani set imlec = call cursor execute imlec string UPDATE kitap_bilgisi SET begeni = '****' WHERE begeni='***' execute imlec string UPDATE kitap_bilgisi SET okunma_durumu = 'evet' WHERE ...
import os import sqlite3 veritabani = 'kitaplik.sqlite' dosya_mevcut = os.path.exists(veritabani) vt = sqlite3.connect(veritabani) imlec = vt.cursor() imlec.execute("UPDATE kitap_bilgisi SET begeni = '****' WHERE begeni='***'") imlec.execute("UPDATE kitap_bilgisi SET okunma_durumu = 'evet' WHERE okunma_du...
Python
zaydzuhri_stack_edu_python
import argparse from record import Record , BadRecord from donors import Donors from donations import RepeatDonations class AnalyticsApp extends object begin function __init__ self ofname perc verbosity=1 begin string Constructor :param ofname: output file name :param perc: percentile value (> 0 and <= 100) :param verb...
import argparse from record import Record, BadRecord from donors import Donors from donations import RepeatDonations class AnalyticsApp(object): def __init__(self, ofname, perc, verbosity=1): """ Constructor :param ofname: output file name :param perc: percentile value (>...
Python
zaydzuhri_stack_edu_python
function execute_dmls self sqls begin set cnx = call connect user=__user password=__pwd host=__db_host port=__db_port database=__db set cursor = call cursor try begin comment print("insert begin") print string DML sql begin + sqls execute cursor sqls comment map(cursor.execute, sqls) commit cnx end comment print("inser...
def execute_dmls(self, sqls): cnx = mysql.connector.connect(user=self.__user, password=self.__pwd, host=self.__db_host,port=self.__db_port, database=self.__db) cursor = cnx.cursor() try: # print("insert begin") print("DML sql begin " + sqls) cursor.execute(s...
Python
nomic_cornstack_python_v1
function test_1 self begin set chem_file1 = join path call get_path string tools string data string diffmodels string chem1.inp set dict_file1 = join path call get_path string tools string data string diffmodels string species_dictionary1.txt set chem_file2 = join path call get_path string tools string data string diff...
def test_1(self): chem_file1 = os.path.join(rmgpy.get_path(), 'tools', 'data', 'diffmodels', 'chem1.inp') dict_file1 = os.path.join(rmgpy.get_path(), 'tools', 'data', 'diffmodels', 'species_dictionary1.txt') chem_file2 = os.path.join(rmgpy.get_path(), 'tools', 'data', 'diffmodels', 'chem2.inp')...
Python
nomic_cornstack_python_v1