code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment let's pull daily local weather data from noaa_sdk import noaa set n = call NOAA set b = call points_forecast 40.7314 - 73.8656 hourly=false set c = type b comment creating variable for dictionary set d = b at string properties comment for key in d.keys(): # let's take a look at the keys of this dictionary comme...
from noaa_sdk import noaa # let's pull daily local weather data n = noaa.NOAA() b = n.points_forecast(40.7314, -73.8656, hourly=False) c = type(b) d = b["properties"] # creating variable for dictionary #for key in d.keys(): # let's take a look at the keys of this dictionary #print(key) f = d["periods"] # periods ...
Python
zaydzuhri_stack_edu_python
import numpy as np from scipy import stats set data = call genfromtxt string ship-nmpg.csv delimiter=string , names=true dtype=string f8,i8,f8,f8,f8,f8,i8,i8,S35 set hpmean = call nanmean data at string hp set hpmedian = call nanmedian data at string hp set imputeHP = round hpmean + hpmedian / 2.0 for i in range length...
import numpy as np from scipy import stats data = np.genfromtxt('ship-nmpg.csv', delimiter=",", names=True, dtype="f8,i8,f8,f8,f8,f8,i8,i8,S35") hpmean = stats.nanmean(data['hp']) hpmedian = stats.nanmedian(data['hp']) imputeHP = np.round((hpmean + hpmedian)/ 2.0) for i in range(len(data['hp'])): if np.isnan(da...
Python
zaydzuhri_stack_edu_python
function get self remotepath localpath=none begin if not localpath begin set localpath = split path remotepath at 1 end call _sftp_connect get _sftp remotepath localpath end function
def get(self, remotepath, localpath = None): if not localpath: localpath = os.path.split(remotepath)[1] self._sftp_connect() self._sftp.get(remotepath, localpath)
Python
nomic_cornstack_python_v1
function run_id self begin return run_id end function
def run_id(self) -> str: return self._step_execution_context.run_id
Python
nomic_cornstack_python_v1
comment Jerdy Bartholomeus 0919350 RAC17-ICTVT1C 03-10-2017 comment Opdracht 9 import easygui set enq_vraag = call buttonbox string Uw bestelling is afgerond. Heeft u tijd voor een korte enquete? choices=list string Ja string Nee if enq_vraag == string Nee begin call msgbox string Dankuwel voor uw bestelling. print str...
#Jerdy Bartholomeus 0919350 RAC17-ICTVT1C 03-10-2017 #Opdracht 9 import easygui enq_vraag = easygui.buttonbox("Uw bestelling is afgerond. Heeft u tijd voor een korte enquete?", choices = ["Ja", "Nee"]) if enq_vraag == "Nee": easygui.msgbox("Dankuwel voor uw bestelling.") print("Uw bestelling...
Python
zaydzuhri_stack_edu_python
function mean self fex_object ignore_sessions=false *args **kwargs begin if not is instance fex_object tuple Fex DataFrame begin raise call ValueError string Must pass in a Fex object. end append extracted_features call extract_mean ignore_sessions *args keyword kwargs end function
def mean(self, fex_object, ignore_sessions=False, *args, **kwargs): if not isinstance(fex_object, (Fex, DataFrame)): raise ValueError("Must pass in a Fex object.") self.extracted_features.append( fex_object.extract_mean(ignore_sessions, *args, **kwargs) )
Python
nomic_cornstack_python_v1
function test_fetching_all_dishes_when_fails self begin set response = get client string http://localhost:8000/api/dishess assert equal status_code 404 end function
def test_fetching_all_dishes_when_fails(self): response = self.client.get('http://localhost:8000/api/dishess') self.assertEqual(response.status_code, 404)
Python
nomic_cornstack_python_v1
function build_retrieval_model cfg begin info string Building model.... set model = call build_model MODEL OPTIMIZER if exists g_pathmgr PARAMS_FILE begin set init_weights_path = PARAMS_FILE info string Initializing model from: { init_weights_path } set weights = call load_checkpoint init_weights_path device=device str...
def build_retrieval_model(cfg): logging.info("Building model....") model = build_model(cfg.MODEL, cfg.OPTIMIZER) if g_pathmgr.exists(cfg.MODEL.WEIGHTS_INIT.PARAMS_FILE): init_weights_path = cfg.MODEL.WEIGHTS_INIT.PARAMS_FILE logging.info(f"Initializing model from: {init_weights_path}") ...
Python
nomic_cornstack_python_v1
function with_recursion func prog=false begin function fun_k x0 k *args **kwargs begin set xx = zeros tuple k + 1 + shape set xx at 0 = x0 set rg = range k if is instance prog str begin set rg = call progbar rg prog end else if prog begin set rg = call progbar rg string Recurs. end for i in rg begin set xx at i + 1 = c...
def with_recursion(func,prog=False): def fun_k(x0,k,*args,**kwargs): xx = zeros((k+1,)+x0.shape) xx[0] = x0 rg = range(k) if isinstance(prog,str): rg = progbar(rg,prog) elif prog: rg = progbar(rg,'Recurs.') for i in rg: xx[i+1] = func(xx[i],*args,**kwargs) retur...
Python
nomic_cornstack_python_v1
function __init__ self name url code begin set _connection = create_connection set _url = url set _authorization_code = code set _name = name set _status = STATE_OFF set _ws = none set _title = none set _artist = none set _albumart = none set _seek_position = none set _duration = none set _volume = none set _request_id...
def __init__(self, name, url, code): self._connection = create_connection self._url = url self._authorization_code = code self._name = name self._status = STATE_OFF self._ws = None self._title = None self._artist = None self._albumart = None ...
Python
nomic_cornstack_python_v1
function setPickWalkRight self val=string True **kwargs begin pass end function
def setPickWalkRight(self, val='True', **kwargs): pass
Python
nomic_cornstack_python_v1
function __init__ self enclosing_scope begin call __init__ self set members = dict set enclosing_scope = enclosing_scope end function
def __init__ ( self, enclosing_scope ): JSObject.__init__( self ) self.members = { } self.enclosing_scope = enclosing_scope
Python
nomic_cornstack_python_v1
function spotify_track_object begin return dict string album dict string id string ALBUM_ID ; string artists list dict string id string ARTIST_ID ; string id string TRACK_ID end function
def spotify_track_object(): return { 'album': {'id': 'ALBUM_ID'}, 'artists': [{'id': 'ARTIST_ID'}], 'id': 'TRACK_ID' }
Python
nomic_cornstack_python_v1
function deleteBookReview book_id review_id class_name begin comment if 'username' not in login_session: comment return redirect('/login') set bookToReview = call one set reviewToDelete = call one if login_session at string user_id == user_id begin try begin delete reviewToDelete commit session call flash string Review...
def deleteBookReview(book_id, review_id, class_name): # if 'username' not in login_session: # return redirect('/login') bookToReview = session.query(Book).filter_by(id = book_id).one() reviewToDelete = session.query(Review).filter_by(id = review_id).one() if login_session['user_id'] == reviewToDel...
Python
nomic_cornstack_python_v1
from urllib import request set fhand = url open string http://dr-chuck.com/page1.htm for line in fhand begin print strip decode line end
from urllib import request fhand = request.urlopen('http://dr-chuck.com/page1.htm') for line in fhand: print(line.decode().strip())
Python
zaydzuhri_stack_edu_python
function convert_time time begin set hour = integer time at slice : 2 : set minute = integer time at slice 3 : : if hour >= 12 begin set suffix = string PM if hour > 12 begin set hour = hour - 12 end end else begin set suffix = string AM if hour == 0 begin set hour = 12 end end return string hour + string : + string ...
def convert_time(time): hour = int(time[:2]) minute = int(time[3:]) if hour >= 12: suffix = "PM" if hour > 12: hour -= 12 else: suffix = "AM" if hour == 0: hour = 12 return str(hour) + ":" + str(minute) + " " + suffix def convert_time(time)...
Python
jtatman_500k
function image_cleaner_enabled self begin return get pulumi self string image_cleaner_enabled end function
def image_cleaner_enabled(self) -> pulumi.Output[Optional[bool]]: return pulumi.get(self, "image_cleaner_enabled")
Python
nomic_cornstack_python_v1
string Filename: 14_RadarPF.py Created on: April,10, 2021 Author: dhpark import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm set x = none set firstRun = true set Npt = none set tuple pt wt = tuple none none set posp = none function fx x dt begin set A = call eye 3 + dt * array list list 0 1 ...
''' Filename: 14_RadarPF.py Created on: April,10, 2021 Author: dhpark ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm x = None firstRun = True Npt = None pt, wt = None, None posp = None def fx(x, dt): A = np.eye(3) + dt * np.array([[0,1,0],[0,0,0],[0,0,0]]) xp = A @ x ...
Python
zaydzuhri_stack_edu_python
import os import sys import json set SYM = 37 class NFA begin set eps = - 999 function __init__ self n begin set a = n set b = list for i in range n begin append b i end set c = list for i in alphnum begin append c i end set d = list comprehension list comprehension list for j in range SYM if i < SYM for i in range ...
import os import sys import json SYM = 37 class NFA: eps = -999 def __init__(self, n): a=n b=[] for i in range(n): b.append(i) c=[] for i in self.alphnum: c.append(i) d=[[[] for j in range(SYM) if i<SYM]for i in range(n) if i<n]...
Python
zaydzuhri_stack_edu_python
import midi comment Instantiate a MIDI Pattern (contains a list of tracks) set pattern = call Pattern comment Instantiate a MIDI Track (contains a list of MIDI events) append pattern call Track tuple call TimeSignatureEvent tick=0 numerator=4 denominator=4 metronome=24 thirtyseconds=8 call KeySignatureEvent tick=0 call...
import midi # Instantiate a MIDI Pattern (contains a list of tracks) pattern = midi.Pattern() # Instantiate a MIDI Track (contains a list of MIDI events) pattern.append(midi.Track(( midi.TimeSignatureEvent(tick=0,numerator=4,denominator=4, metronome=24, thirty...
Python
zaydzuhri_stack_edu_python
function observation_prob X Xmin=1 Xmax=20 begin set Y = zeros like X set Y at X >= Xmin ? X <= Xmax = 1 return Y end function
def observation_prob(X, Xmin=1, Xmax=20): Y = np.zeros_like(X) Y[(X>=Xmin) & (X<=Xmax)] = 1 return Y
Python
nomic_cornstack_python_v1
function search_insert_position arr value begin set left = 0 set right = length arr - 1 if value > arr at right begin return right + 1 end if value < arr at left begin return left end return call _search_binary_search arr value left right end function function _search_binary_search arr value low high begin if high - lo...
def search_insert_position(arr, value): left = 0 right = len(arr) - 1 if value > arr[right]: return right + 1 if value < arr[left]: return left return _search_binary_search(arr, value, left, right) def _search_binary_search(arr, value, low, high): if high - low <= 0: ...
Python
zaydzuhri_stack_edu_python
string This module contains a model of a chess board and its pieces. class ConflictError extends Exception begin string I am intended to be used to indicate that two pieces on a board conflict with each other. pass end class class Piece extends object begin string I represent an abstract piece on a board - I am not int...
'''This module contains a model of a chess board and its pieces.''' class ConflictError(Exception): '''I am intended to be used to indicate that two pieces on a board conflict with each other.''' pass class Piece(object): '''I represent an abstract piece on a board - I am not intended to be inst...
Python
zaydzuhri_stack_edu_python
function create_new_dir path begin debug string Function Successful: % s string create_new_dir: create_new_dir successfully called from save_single_file_locally extra=d if not exists path path begin debug string Calling Function: % s string create_new_dir: create_new_dir calling makedirs extra=d make directories path d...
def create_new_dir(path): logger.debug('Function Successful: % s', 'create_new_dir: create_new_dir successfully called from save_single_file_locally', extra=d) if not os.path.exists(path): logger.debug('Calling Function: % s', 'create_new_dir: create_new_dir ca...
Python
nomic_cornstack_python_v1
string Following a suggestion by Lee, I am making very rough calculations regarding the acceleration of molecular clouds Created: August 20, 2020 set __author__ = string Ramsey Karim import numpy as np import matplotlib.pyplot as plt import scipy.constants as cst import astropy.units as u function estimate_total_accele...
""" Following a suggestion by Lee, I am making very rough calculations regarding the acceleration of molecular clouds Created: August 20, 2020 """ __author__ = "Ramsey Karim" import numpy as np import matplotlib.pyplot as plt import scipy.constants as cst import astropy.units as u def estimate_total_acceleration()...
Python
zaydzuhri_stack_edu_python
function test_set_parent_when_provided begin comment GIVEN a valid parent set father : str = FATHER comment WHEN running "set_parent_if_missing" set validated_father : str = call set_parent_if_missing father comment THEN the returned string should not have been altered assert validated_father == father end function
def test_set_parent_when_provided(): # GIVEN a valid parent father: str = Pedigree.FATHER # WHEN running "set_parent_if_missing" validated_father: str = set_parent_if_missing(father) # THEN the returned string should not have been altered assert validated_father == father
Python
nomic_cornstack_python_v1
function resource_group_name self begin return get pulumi self string resource_group_name end function
def resource_group_name(self) -> pulumi.Input[str]: return pulumi.get(self, "resource_group_name")
Python
nomic_cornstack_python_v1
comment 876. 链表的中间结点 comment 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。 comment 如果有两个中间结点,则返回第二个中间结点。 comment Definition for singly-linked list. class ListNode begin function __init__ self x begin set val = x set next = none end function end class class Solution begin function middleNode self head begin set mid = head while head...
# 876. 链表的中间结点 # 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。 # 如果有两个中间结点,则返回第二个中间结点。 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: mid = head while head and head....
Python
zaydzuhri_stack_edu_python
import os import flickrapi import requests comment Not sure which image sizes the original dataset has chosen. Most likely not "Original" - too large. set _SIZE = string Original function _download_image image_url filename begin set img_data = content with open filename string wb as f begin write f img_data end end fun...
import os import flickrapi import requests # Not sure which image sizes the original dataset has chosen. Most likely not "Original" - too large. _SIZE = "Original" def _download_image(image_url, filename): img_data = requests.get(image_url).content with open(filename, 'wb') as f: f.write(img_data) class C...
Python
zaydzuhri_stack_edu_python
comment Script to train machine learning model. import pandas as pd from joblib import dump from sklearn.model_selection import train_test_split from ml.data import process_data from ml.model import train_model function get_train_test_data root_path begin string Get data for training and testing Parameters ---------- r...
# Script to train machine learning model. import pandas as pd from joblib import dump from sklearn.model_selection import train_test_split from .ml.data import process_data from .ml.model import train_model def get_train_test_data(root_path): """ Get data for training and testing Parameters -------...
Python
zaydzuhri_stack_edu_python
function get_config self begin set config = dict string units units ; string use_bias use_bias ; string support support ; string activation call serialize activation ; string kernel_initializer call serialize kernel_initializer ; string bias_initializer call serialize bias_initializer ; string kernel_regularizer call s...
def get_config(self): config = { "units": self.units, "use_bias": self.use_bias, "support": self.support, "activation": activations.serialize(self.activation), "kernel_initializer": initializers.serialize(self.kernel_initializer), "bias_ini...
Python
nomic_cornstack_python_v1
function getRawBufferSize self begin return call IFrameGrabber_getRawBufferSize self end function
def getRawBufferSize(self): return _yarp.IFrameGrabber_getRawBufferSize(self)
Python
nomic_cornstack_python_v1
function _interpretMdriztabPars rec begin string Collect task parameters from the MDRIZTAB record and update the master parameters list with those values Note that parameters read from the MDRIZTAB record must be cleaned up in a similar way that parameters read from the user interface are. set tabdict = dict comment f...
def _interpretMdriztabPars(rec): """ Collect task parameters from the MDRIZTAB record and update the master parameters list with those values Note that parameters read from the MDRIZTAB record must be cleaned up in a similar way that parameters read from the user interface are. """ tabd...
Python
jtatman_500k
function equilibrium A begin for i in range length A begin set sl = 0 for il in range i begin set sl = sl + A at il end for ir in range i + 1 length A begin set sl = sl - A at ir end if sl == 0 begin return i end end return - 1 end function function equilibrium_optimised A begin if length A == 1 begin return 1 end set ...
def equilibrium(A): for i in range(len(A)): sl = 0 for il in range(i): sl += A[il] for ir in range(i+1, len(A)): sl -= A[ir] if sl == 0: return i return -1 def equilibrium_optimised(A): if len(A)==1: return 1 left_sum = 0 ...
Python
zaydzuhri_stack_edu_python
function chord_to_notes chord dur begin set note_str = string set ls = list for note in chord begin for i in range dur - 1 begin set note_str = note_str + note + string - end set note_str = note_str + note append ls note_str set note_str = string end print ls return ls end function
def chord_to_notes(chord, dur): note_str = "" ls = [] for note in chord: for i in range(dur-1): note_str += note + "-" note_str += note ls.append(note_str) note_str = "" print(ls) return ls
Python
nomic_cornstack_python_v1
comment Python p127 comment 24. İLERİ DÜZEY FONKSİYONLAR ##### comment LAMBDA FONKSİYONLARI
# Python p127 #### 24. İLERİ DÜZEY FONKSİYONLAR ##### # LAMBDA FONKSİYONLARI
Python
zaydzuhri_stack_edu_python
comment python3 program to solve the leetcode problem of Water Bottles comment Problem statement string Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Return the maximum number ...
#python3 program to solve the leetcode problem of Water Bottles #Problem statement ''' Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Return the maximum number of water bottl...
Python
zaydzuhri_stack_edu_python
function view_global_hmaps token dstore begin string Display the global hazard maps for the calculation. They are used for debugging purposes when comparing the results of two calculations. They are the mean over the sites of the mean hazard maps. set oq = dstore at string oqparam set dt = call dtype list comprehension...
def view_global_hmaps(token, dstore): """ Display the global hazard maps for the calculation. They are used for debugging purposes when comparing the results of two calculations. They are the mean over the sites of the mean hazard maps. """ oq = dstore['oqparam'] dt = numpy.dtype([('%s-%...
Python
jtatman_500k
if r < 5 begin print string bien joué end else begin print string sal petite merde end
if r<5: print('bien joué') else: print('sal petite merde')
Python
zaydzuhri_stack_edu_python
comment 图像开运算 import numpy as np import cv2 set im1 = call imread string data/7.png set im2 = call imread string data/8.png image show string im1 im1 image show string im2 im2 comment 执行开运算 comment 开运算核 set k = ones tuple 10 10 uint8 set r1 = call morphologyEx im1 MORPH_OPEN k set r2 = call morphologyEx im2 MORPH_OPEN ...
#图像开运算 import numpy as np import cv2 im1 = cv2.imread("data/7.png") im2 = cv2.imread("data/8.png") cv2.imshow("im1",im1) cv2.imshow("im2",im2) #执行开运算 k = np.ones((10,10),np.uint8) #开运算核 r1 = cv2.morphologyEx(im1,cv2.MORPH_OPEN,k) r2 = cv2.morphologyEx(im2,cv2.MORPH_OPEN,k) cv2.imshow("im1_open",r1) cv2.imshow("im2_o...
Python
zaydzuhri_stack_edu_python
for i in range length s begin if s at i == string 0 or s at i == string 1 begin set ans = ans + s at i end else if s at i == string B begin set ans = ans at slice : - 1 : end end print ans
for i in range(len(s)): if s[i] == '0' or s[i] == '1': ans += s[i] elif s[i] == 'B': ans = ans[:-1] print(ans)
Python
zaydzuhri_stack_edu_python
from PIL import Image import os , sys comment create JPEG thumbnails from image comment PARAM: Image path function create_thumbnail img_file begin comment TODO: exception handling set img_org = open img_file set img = copy img_org comment max 300px set size = tuple 300 300 comment Set thumbail file path and name set fi...
from PIL import Image import os, sys #create JPEG thumbnails from image #PARAM: Image path def create_thumbnail(img_file): #TODO: exception handling img_org = Image.open(img_file) img = img_org.copy() #max 300px size = (300, 300) #Set thumbail file path and name file_path = os.path.split(...
Python
zaydzuhri_stack_edu_python
function gen_random_matrix_ region_sizes result densities=none begin if densities is none begin set densities = list 0.01 0.02 0.0001 0.0005 end set tuple ab ba aa bb = call gen_random_matrix *region_sizes *densities set mc = call MatrixConnectivity ab=ab ba=ba aa=aa bb=bb call create_connections set reverse_graph = re...
def gen_random_matrix_(region_sizes, result, densities=None): if densities is None: densities = [0.01, 0.02, 0.0001, 0.0005] ab, ba, aa, bb = gen_random_matrix(*region_sizes, *densities) mc = MatrixConnectivity(ab=ab, ba=ba, aa=aa, bb=bb) mc.create_connections() reverse_graph = reverse(mc.gr...
Python
nomic_cornstack_python_v1
function missing_values self layout=dict **kwargs begin set df = as type call isna int update kwargs dict string zmin 0 ; string zmax 1 ; string colors string reds ; string ncolors 9 ; string xgap 3 ; string ygap 3 ; string showscale false set layout = call recursive_update layout updater=dict string xaxis dict string...
def missing_values(self, layout={}, **kwargs): df = self._data.isna().astype(int) kwargs.update( {'zmin': 0, 'zmax': 1, 'colors': 'reds', 'ncolors': 9, 'xgap': 3, 'ygap': 3, 'showscale': False, } ) layout = recursive_update( ...
Python
nomic_cornstack_python_v1
comment Author:ambiguoustexture comment Date: 2020-02-09 import re set pattern_contents = compile string ^\{\{基礎情報.*?$ (.*?) ^\}\}$ MULTILINE + VERBOSE + DOTALL set pattern_fields = compile string ^\| (.+?) \s* = \s* (.+?) (?: (?=\n\|) | (?=\n$) ) MULTILINE + VERBOSE + DOTALL set pattern_emphasis = compile string \'{2,...
# Author:ambiguoustexture # Date: 2020-02-09 import re pattern_contents = re.compile(r' ^\{\{基礎情報.*?$ (.*?) ^\}\}$ ', re.MULTILINE + re.VERBOSE + re.DOTALL) pattern_fields = re.compile(r' ^\| (.+?) \s* = \s* (.+?) (?: (?=\n\|) | (?=\n$) ) ', re.MULTILINE + re.VERBOSE + re.DOTALL) pattern_emphasis = re.compile(r...
Python
zaydzuhri_stack_edu_python
function update self request pk=none begin set missing_keys = call _get_missing_keys if length missing_keys > 0 begin return call Response dict string message string Request body is missing the following required properties: { join string , missing_keys } status=HTTP_400_BAD_REQUEST end set user = get objects id=id set...
def update(self, request, pk=None): missing_keys = self._get_missing_keys() if len(missing_keys) > 0: return Response( {'message': f'Request body is missing the following required properties: {", ".join(missing_keys)}' }, s...
Python
nomic_cornstack_python_v1
import numpy as np import random function pair_to_int te1 te2 begin if te1 == te2 begin return 0 end else if te == string g and te_com == string c begin return 1 end else if te == string c and te_com == string p begin return 1 end else if te == string p and te_com == string g begin return 1 end else begin return 2 end ...
import numpy as np import random def pair_to_int(te1, te2): if te1 == te2: return 0 elif te == "g" and te_com == "c": return 1 elif te == "c" and te_com == "p": return 1 elif te == "p" and te_com == "g": return 1 else: return 2 def int_to_te(te, n): if...
Python
zaydzuhri_stack_edu_python
function plot_shap_interactions shap_values_interactions X_test begin comment Make sure all variables will be plotted. set n_features = length columns call summary_plot shap_values_interactions X_test max_display=n_features show=false set fig = call gcf set ax = call gcf show return tuple fig ax end function
def plot_shap_interactions(shap_values_interactions, X_test): # Make sure all variables will be plotted. n_features = len(X_test.columns) shap.summary_plot(shap_values_interactions, X_test, max_display=n_features, show=False) fig = plt.gcf() ax = plt.gcf() plt.show() ...
Python
nomic_cornstack_python_v1
async function async_get_command self request begin comment HTTP GET to endpoint set res = await call async_get request comment Return text return text end function
async def async_get_command(self, request: str) -> str: # HTTP GET to endpoint res = await self.async_get(request) # Return text return res.text
Python
nomic_cornstack_python_v1
function getResbase self begin try begin return modDict at string resbase at 0 end except KeyError begin return none end end function
def getResbase(self): try: return self.modDict['resbase'][0] except KeyError: return None
Python
nomic_cornstack_python_v1
set sayı1 = integer input string 1.Sayıyı Giriniz: print type sayı1 print string Girdiniz 1. sayı: sayı1 set sayı2 = integer input string 2.Sayıyı Giriniz: print string Girdiğiniz 2. Sayı: set sayı3 = sayı1 + sayı2 print string Sayı1 + Sayı2 = sayı3
sayı1=int(input("1.Sayıyı Giriniz: ")) print(type(sayı1)) print("Girdiniz 1. sayı: ",sayı1) sayı2=int(input("2.Sayıyı Giriniz: ")) print("Girdiğiniz 2. Sayı: ") sayı3=sayı1+sayı2 print("Sayı1 + Sayı2 = ",sayı3)
Python
zaydzuhri_stack_edu_python
function hamming dna1 dna2 begin set length = min length dna1 length dna2 set hamming = max length dna1 length dna2 - length for i in range length begin set nucleotide1 = dna1 at i set nucleotide2 = dna2 at i end end function
def hamming(dna1, dna2): length = min(len(dna1), len(dna2)) hamming = max(len(dna1), len(dna2))-length for i in range(length): nucleotide1 = dna1[i] nucleotide2 = dna2[i]
Python
zaydzuhri_stack_edu_python
function water_leaving_rad_b7 diff_coeff ifname rayleigh_radiance begin set fname = replace ifname string MTL.txt string B7_TOARAD.tif if not exists path fname begin set fname = replace ifname string MTL.txt string ROI_B7_TOARAD.tif end set g = open fname end function
def water_leaving_rad_b7 ( diff_coeff, ifname, rayleigh_radiance ): fname = ifname.replace ( "MTL.txt", "B7_TOARAD.tif" ) if not os.path.exists ( fname ): fname = ifname.replace ( "MTL.txt", "ROI_B7_TOARAD.tif" ) g = gdal.Open ( fname )
Python
nomic_cornstack_python_v1
function unschedule self job=none func=none jobid=none begin if job is none and func is none and jobid is none begin comment future compatibility: comment TODO: unschedule all the jobs and functions comment but for now, just raise an exception raise UnSupportedFeature end else if job is none and func is not none and jo...
def unschedule(self, job=None, func=None, jobid=None): if job is None and func is None and jobid is None: # future compatibility: # TODO: unschedule all the jobs and functions # but for now, just raise an exception raise UnSupportedFeature elif job ...
Python
nomic_cornstack_python_v1
function check_account submit begin set submit_page = text set success = string <p>You can now begin your adventure with your new account.</p> if success in submit_page begin print string Account was successfully created. return true end else comment If account creation fails, print the error if string Warning! in subm...
def check_account(submit): submit_page = submit.text success = '<p>You can now begin your adventure with your new account.</p>' if success in submit_page: print("\nAccount was successfully created.\n") return True elif 'Warning!' in submit_page: # If account creation fails, print the err...
Python
nomic_cornstack_python_v1
import re from collections import Counter class CountPatt begin function __init__ self patt begin set cpatt = compile patt end function function count_patt self fname begin set result = counter with open fname as fobj begin for line in fobj begin set m = search line if m begin update result list call group end end end ...
import re from collections import Counter class CountPatt: def __init__(self,patt): self.cpatt=re.compile(patt) def count_patt(self,fname): result=Counter() with open(fname) as fobj: for line in fobj: m=self.cpatt.search(line) if m: ...
Python
zaydzuhri_stack_edu_python
function memory_index indices t begin set tuple memlen itemsize ndim shape strides offset = t set p = offset for i in range ndim begin set p = p + strides at i * indices at i end return p end function
def memory_index(indices, t): memlen, itemsize, ndim, shape, strides, offset = t p = offset for i in range(ndim): p += strides[i] * indices[i] return p
Python
nomic_cornstack_python_v1
function cl self cl begin set cls = reshape array cl - 1 return call _run_xfoil join string list comprehension string cl { c } for c in cls end function
def cl(self, cl: Union[float, np.ndarray] ) -> Dict[str, np.ndarray]: cls = np.array(cl).reshape(-1) return self._run_xfoil( "\n".join([ f"cl {c}" for c in cls ]) )
Python
nomic_cornstack_python_v1
function gen_equivalent_factors begin yield call SomeFactor yield call SomeFactor inputs=NotSpecified yield call SomeFactor inputs yield call SomeFactor inputs=inputs yield call SomeFactor list foo bar yield call SomeFactor window_length=window_length yield call SomeFactor window_length=NotSpecified yield call SomeFact...
def gen_equivalent_factors(): yield SomeFactor() yield SomeFactor(inputs=NotSpecified) yield SomeFactor(SomeFactor.inputs) yield SomeFactor(inputs=SomeFactor.inputs) yield SomeFactor([SomeDataSet.foo, SomeDataSet.bar]) yield SomeFactor(window_length=SomeFactor.window_length) yield SomeFactor...
Python
nomic_cornstack_python_v1
import json set data = dictionary with open string got-graph-images.json as graph begin set data = load json graph end set new_graph = dictionary set keys = list string mother string father string sibling string lover string spouse set new_graph at string nodes = list set new_graph at string links = list function conta...
import json data = dict() with open("got-graph-images.json") as graph: data = json.load(graph) new_graph = dict() keys = ['mother', 'father', 'sibling', 'lover', 'spouse'] new_graph['nodes'] = list() new_graph['links'] = list() def contains_id(nodes, id): for n in nodes: if n['id'] == id: retu...
Python
zaydzuhri_stack_edu_python
function get_alert_by_alert_id self alert_id environment=none begin set data = dictionary alert_id=alert_id if environment begin set data at string environment = environment end set response = call request_with_refresh_expired_access_token method=string GET path=string /alerts/get-by-id data=data call raise_for_status ...
def get_alert_by_alert_id(self, alert_id: str, environment: Optional[str] = None) -> Tuple[Dict, str]: data = dict(alert_id=alert_id) if environment: data['environment'] = environment response = self.api.request_with_refresh_expired_access_token(method='GET', ...
Python
nomic_cornstack_python_v1
from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import re import json set driver = call Chrome string /usr/lib/chromium-browser/chromedriver get driver string https://www.codechef.com/problems/school set problem_name = list set problem_link = list set content = page_source close drive...
from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import re import json driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver') driver.get("https://www.codechef.com/problems/school") problem_name = [] problem_link = [] content = driver.page_source driver.close() soup = Beaut...
Python
zaydzuhri_stack_edu_python
function options url **kwargs begin set default kwargs string allow_redirects true return call request string options url keyword kwargs end function
def options(url, **kwargs): kwargs.setdefault("allow_redirects", True) return request("options", url, **kwargs)
Python
nomic_cornstack_python_v1
function getDatastreamHistory self pid dsid format=none begin string Get history information for a datastream. :param pid: object pid :param dsid: datastream id :param format: format :rtype: :class:`requests.models.Response` set http_args = dict if format is not none begin set http_args at string format = format end c...
def getDatastreamHistory(self, pid, dsid, format=None): '''Get history information for a datastream. :param pid: object pid :param dsid: datastream id :param format: format :rtype: :class:`requests.models.Response` ''' http_args = {} if format is not None...
Python
jtatman_500k
function get_motion self timeout=5 begin set t_start = time while time - t_start < timeout begin call output spi_cs_gpio 0 set data = call xfer2 list REG_MOTION_BURST + list comprehension 0 for x in range 12 call output spi_cs_gpio 1 set tuple _ dr obs x y quality raw_sum raw_max raw_min shutter_upper shutter_lower = c...
def get_motion(self, timeout=5): t_start = time.time() while time.time() - t_start < timeout: GPIO.output(self.spi_cs_gpio, 0) data = self.spi_dev.xfer2([REG_MOTION_BURST] + [0 for x in range(12)]) GPIO.output(self.spi_cs_gpio, 1) (_, dr, obs, ...
Python
nomic_cornstack_python_v1
import pygame from pygame.locals import * set WINDOW_WIDTH = 500 set WINDOW_HEIGHT = 500 call init set screen = call set_mode tuple WINDOW_WIDTH WINDOW_HEIGHT set backgroundm = load image string menubackground.png set BLACK = tuple 0 0 0 set WHITE = tuple 255 255 255 function fadeintext string a b begin set textToFadeO...
import pygame from pygame.locals import * WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 pygame.init() screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) backgroundm = pygame.image.load('menubackground.png') BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) def fadeintext(string,a,b): textToFadeOut = string ...
Python
zaydzuhri_stack_edu_python
string Question 41 Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). function task_41 n begin set tpl = tuple generator expression power i 2 for i in range 1 n + 1 return tpl end function comment print(task_41(int(input()))) string Question 42...
"""Question 41 Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). """ def task_41(n): tpl = tuple(pow(i, 2) for i in range(1, n+1)) return (tpl) #print(task_41(int(input()))) """Question 42 With a given tuple 12345678910 write a ...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import random as rnd from celluloid import Camera import matplotlib.pyplot as plt from Functions import * import matplotlib.animation as ani import copy import time class Individual begin string Class for individuals. Used to randomly create individuals which are used next in biologically ...
import numpy as np from numpy import random as rnd from celluloid import Camera import matplotlib.pyplot as plt from Functions import * import matplotlib.animation as ani import copy import time class Individual: """Class for individuals. Used to randomly create individuals which are used next i...
Python
zaydzuhri_stack_edu_python
string 문제3) 다음과 같은 메뉴를 이용하여 goods 테이블을 관리하시오. [레코드 처리 메뉴 ] 1. 레코드 조회 2. 레코드 추가 3. 레코드 수정 4. 레코드 삭제 5. 프로그램 종료 메뉴번호 입력 : import pymysql set config = dict string host string 127.0.0.1 ; string user string scott ; string password string tiger ; string database string work ; string port 3306 ; string charset string utf8 ; ...
''' 문제3) 다음과 같은 메뉴를 이용하여 goods 테이블을 관리하시오. [레코드 처리 메뉴 ] 1. 레코드 조회 2. 레코드 추가 3. 레코드 수정 4. 레코드 삭제 5. 프로그램 종료 메뉴번호 입력 : ''' import pymysql config = { 'host' : '127.0.0.1', 'user' : 'scott', 'password' : 'tiger', 'database' : 'work', 'port' : 3306, 'charset':'utf8', ...
Python
zaydzuhri_stack_edu_python
function translate_path self path begin comment abandon query parameters set path = split path string ? 1 at 0 set path = split path string # 1 at 0 set path = call normpath unquote path set words = split path string / set words = filter none words set path = get current directory for word in words begin set tuple driv...
def translate_path(self, path): # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: ...
Python
nomic_cornstack_python_v1
function _observe_selection self change begin set selection = change at string value set node_control = _node_control try begin set tree = call get_widget if not is instance selection basestring and is instance selection Iterable begin set item_selection = call QItemSelection for sel in selection begin set item = call ...
def _observe_selection(self, change): selection = change['value'] node_control = self._node_control try: tree = self.get_widget() if (not isinstance(selection, basestring) and isinstance(selection, collections.Iterable)): item_selectio...
Python
nomic_cornstack_python_v1
function AddSendAction self imgID begin if imgID in __imgRecvDict begin set diffTime = time - __imgRecvDict at imgID set __avgActionProcessTime = __avgActionProcessTime * __processActionNum + diffTime / __processActionNum + 1 set __processActionNum = __processActionNum + 1 set __processImgDict at imgID = time if length...
def AddSendAction(self, imgID): if imgID in self.__imgRecvDict: diffTime = time.time() - self.__imgRecvDict[imgID] self.__avgActionProcessTime = (self.__avgActionProcessTime * self.__processActionNum + diffTime) / ( self.__processActionNum + 1) self.__proc...
Python
nomic_cornstack_python_v1
class Solution begin function missingElement self nums k begin set full_length = nums at - 1 - nums at 0 + 1 set missing = full_length - length nums comment if outside the right bound, then add the rest of the missing number.. if k > missing begin return nums at - 1 + k - missing end else begin comment check in the cur...
class Solution: def missingElement(self, nums: 'List[int]', k: int) -> int: full_length = nums[-1] - nums[0]+1 missing = full_length - len(nums) if k > missing: #if outside the right bound, then add the rest of the missing number.. return nums[-1] + (k-missing) else: #ch...
Python
zaydzuhri_stack_edu_python
function find_type line begin set type_string = strip split line string : at - 1 string ; set isOptional = false if string | in type_string begin set isOptional = true set type_string = strip split type_string string | at 0 end set column_type = type_mapping at type_string call register_imports column_type isOptional r...
def find_type(line): type_string = line.split(':')[-1].strip(";\n ") isOptional = False if "|" in type_string: isOptional = True type_string = type_string.split(' | ')[0].strip() column_type = type_mapping[type_string] register_imports(column_type, isOptional) return (column_t...
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup import pandas as pd import json import flask function getTable id passwd begin set r = post string https://web.sys.scu.edu.tw/login0.asp data=dict string id id ; string passwd passwd set string parselimit string Infinity set encoding = string big5 if string 登入成功! in text be...
import requests from bs4 import BeautifulSoup import pandas as pd import json import flask def getTable(id, passwd): r = requests.post('https://web.sys.scu.edu.tw/login0.asp', data={'id':id,'passwd':passwd}) r.cookies.set('parselimit', 'Infinity') r.encoding = 'big5' if '登入成功!' in r.text: prin...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment @Time: 2019/12/9 00:22 comment Django 模型(数据库) comment Django 模型是与数据库相关的,与数据库相关的代码一般写在 models.py 中,Django 支持 sqlite3, MySQL, PostgreSQL等数据库, comment 只需要在settings.py中配置即可,不用更改models.py中的代码,丰富的API极大的方便了使用。 comment 1. 新建项目和应用 comment django-admin.py startpro...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time: 2019/12/9 00:22 # Django 模型(数据库) # Django 模型是与数据库相关的,与数据库相关的代码一般写在 models.py 中,Django 支持 sqlite3, MySQL, PostgreSQL等数据库, # 只需要在settings.py中配置即可,不用更改models.py中的代码,丰富的API极大的方便了使用。 # 1. 新建项目和应用 # django-admin.py startproject learn_models # 新建一个项目 # cd learn_models # 进...
Python
zaydzuhri_stack_edu_python
comment noqa: E501 function get_home_naif begin return string do some magic! end function
def get_home_naif(): # noqa: E501 return 'do some magic!'
Python
nomic_cornstack_python_v1
import requests from bs4 import BeautifulSoup comment Get the URL set url = string http://www.example.com comment Get the HTML from the URL set r = get requests url set html = text comment Parse the HTML set soup = call BeautifulSoup html string html.parser comment Get the meta tags set metaTags = find all soup string ...
import requests from bs4 import BeautifulSoup # Get the URL url = "http://www.example.com" # Get the HTML from the URL r = requests.get(url) html = r.text # Parse the HTML soup = BeautifulSoup(html, 'html.parser') # Get the meta tags metaTags = soup.find_all('meta') # Print out the meta tags
Python
jtatman_500k
import os import pdb import sys import numpy from sklearn import svm from quant import read_data function train_svr dataset=string begin set tuple train valid test mean std = call read_data columns=1 max_len=10 set x_train = list comprehension list comprehension x at 0 for x in row for row in train at 0 set x_test = li...
import os import pdb import sys import numpy from sklearn import svm from quant import read_data def train_svr(dataset=''): train, valid, test, mean, std = read_data(columns=1, max_len=10) x_train = [[x[0] for x in row] for row in train[0]] x_test = [[x[0] for x in row] for row in test[0]] svr = svm.SV...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Jul 21 12:51:57 2019 @author: Mateusz.Jaworski set cargo = list 40 20 4 5 30 8 2 7 3 19 32 40 20 35 15 32 9 sort cargo reverse cargo print cargo set boxCapacity = 90 set box = list set i = 0 while i < length cargo and boxCapacity - sum box >= min cargo begin if boxCa...
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 12:51:57 2019 @author: Mateusz.Jaworski """ cargo = [40, 20, 4, 5, 30, 8, 2, 7, 3, 19, 32, 40, 20, 35, 15, 32, 9] cargo.sort() cargo.reverse() print(cargo) boxCapacity = 90 box = [] i = 0 while i < len(cargo) and (boxCapacity - sum(box)) >= min(cargo): if (box...
Python
zaydzuhri_stack_edu_python
function test_toElementStampOffsetNaive self begin set delay = call Delay stamp=call datetime 2002 9 10 23 8 25 assert raises ValueError toElement end function
def test_toElementStampOffsetNaive(self): delay = Delay(stamp=datetime(2002, 9, 10, 23, 8, 25)) self.assertRaises(ValueError, delay.toElement)
Python
nomic_cornstack_python_v1
import argparse from library import data_parser from library import session set INPUT_FILE = string data/Consumer_Complaints_sm.csv set parser = call ArgumentParser description=string Parse consumer complaints. call add_argument string --input_file type=str default=INPUT_FILE help=string input csv file of consumer comp...
import argparse from library import data_parser from library import session INPUT_FILE = 'data/Consumer_Complaints_sm.csv' parser = argparse.ArgumentParser(description='Parse consumer complaints.') parser.add_argument('--input_file', type=str, default=INPUT_FILE, help='input csv file of consumer complaints') def m...
Python
zaydzuhri_stack_edu_python
comment Exercise 024: Verifying the firsts letters in a text comment Make a program that read the name of a city and tell if it start ou no with the name "SANTO". set city_name = input string Input here a city name: if starts with upper city_name string SANTO begin print string Yes! The city { city_name } starts with "...
# Exercise 024: Verifying the firsts letters in a text # Make a program that read the name of a city and tell if it start ou no with the name "SANTO". city_name = input('Input here a city name: ') if (city_name.upper()).startswith("SANTO"): print(f'Yes! The city {city_name} starts with "SANTO"') else: print(f'...
Python
zaydzuhri_stack_edu_python
comment major, minor, revision comment major 1, 2, 3 comment minor new feature 1.0, 1.1, 1.2 comment revision small fix 1.1.1, 1.1.2 comment 0.1, 0.5... pre-release versions function get_length version_str begin set nums = split version_str string . set num_size = length nums if num_size == 3 begin return tuple length ...
# major, minor, revision # major 1, 2, 3 # minor new feature 1.0, 1.1, 1.2 # revision small fix 1.1.1, 1.1.2 # 0.1, 0.5... pre-release versions def get_length(version_str): nums = version_str.split('.') num_size = len(nums) if num_size == 3: return len(nums[0]), len(nums[1]), len(nums[2]) elif ...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 import socket import threading import cv2 as cv import numpy as np import pickle import sys set usedPort = 1111 function sendInfo num thread begin call send encode string wesh end function class ClientThread extends Thread begin function __init__ self ip port clientsocket begin call __init__ self ...
# coding: utf-8 import socket import threading import cv2 as cv import numpy as np import pickle import sys usedPort = 1111 def sendInfo(num, thread): thread.clientsocket.send("wesh".encode()) class ClientThread(threading.Thread): def __init__(self, ip, port, clientsocket): threading.Thread.__i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment ! -*- coding: utf-8 -*- comment Bu araç @keyiflerolsun tarafından | @BetikSonu için yazılmıştır. import requests , re from bs4 import BeautifulSoup import json from time import strftime function TR hangi_sayfa begin set udemy_baslik = list set udemy_link = list set link = string h...
#!/usr/bin/env python #! -*- coding: utf-8 -*- # Bu araç @keyiflerolsun tarafından | @BetikSonu için yazılmıştır. import requests, re from bs4 import BeautifulSoup import json from time import strftime def TR(hangi_sayfa): udemy_baslik = [] udemy_link = [] link = f'https://www.discudemy.com/language/Turk...
Python
zaydzuhri_stack_edu_python
comment Valores Unicos em uma Lista set num = list while true begin set n = integer input string Digite um número: if n not in num begin append num n print string Valor adicionado com sucesso... end else begin print string Valor duplicado! Não vou adicionar... end set resp = strip upper string input string Deseja cont...
# Valores Unicos em uma Lista num = [] while True: n = int(input('Digite um número: ')) if n not in num: num.append(n) print('Valor adicionado com sucesso...') else: print('Valor duplicado! Não vou adicionar...') resp = str(input('Deseja continuar? S/N ')).upper().strip() if ...
Python
zaydzuhri_stack_edu_python
string This program takes two words from user input and checks if they are anagrams of each other function main_func begin set words_list = split input string Enter two words seperated with a space: set word1 = words_list at 0 set word2 = words_list at 1 set word1_sorted = call sort_string word1 set word2_sorted = call...
""" This program takes two words from user input and checks if they are anagrams of each other """ def main_func(): words_list = input("Enter two words seperated with a space: ").split() word1 = words_list[0] word2 = words_list[1] word1_sorted = sort_string(word1) word2_sorted = sort_string(word2...
Python
zaydzuhri_stack_edu_python
for i in range length Data_Lines begin set Data_Lines at i = integer right strip Data_Lines at i string set Total_Fuel_Need = Total_Fuel_Need + integer Data_Lines at i / 3 - 2 end print Total_Fuel_Need
for i in range(len(Data_Lines)): Data_Lines[i] = int(Data_Lines[i].rstrip('\n')) Total_Fuel_Need += int(Data_Lines[i] / 3) - 2 print(Total_Fuel_Need)
Python
zaydzuhri_stack_edu_python
function write_namespace_hierarchy self file=none begin set graph = call _get_hierarchy_graph call serialize string bel file=file end function
def write_namespace_hierarchy(self, file: Optional[TextIO] = None): graph = self._get_hierarchy_graph() graph.serialize('bel', file=file)
Python
nomic_cornstack_python_v1
function _get_db_replace_values ticker frame table_name begin set columns = list string `ticker` string `id`, `parent_id`, `item` + list comprehension string `year_%d` % year for period in columns at slice 2 : : return string REPLACE INTO `%s` % table_name + string (%s) VALUES % join string , columns + join string , ...
def _get_db_replace_values(ticker, frame, table_name): columns = [u'`ticker`', u'`id`, `parent_id`, `item`'] + \ [u'`year_%d`' % period.year for period in frame.columns[2:]] return ( u'REPLACE INTO `%s`\n' % table_name + ...
Python
nomic_cornstack_python_v1
function _parse_period self period begin if not period begin return none end else if _period_type == FIXED begin return list period end else begin return sorted list comprehension call parse_enumeration_from_template p intermediate=_period_base base=Period for p in call to_list period end end function
def _parse_period(self, period: Period) -> Optional[List[Period]]: if not period: return None elif self._period_type == PeriodType.FIXED: return [period] else: return sorted( [ parse_enumeration_from_template(p, intermediate...
Python
nomic_cornstack_python_v1
comment Enter your code here. Read input from STDIN. Print output to STDOUT comment Complete the commonChild function below. function commonChild x y begin set z = list comprehension list comprehension 0 for j in range length y + 1 for i in range length x + 1 for tuple i a in enumerate x begin for tuple j b in enumerat...
# Enter your code here. Read input from STDIN. Print output to STDOUT # Complete the commonChild function below. def commonChild(x, y): z=[[0 for j in range(len(y)+1)] for i in range(len(x)+1)] for i, a in enumerate(x): for j, b in enumerate(y): if a == b: z[i+1][j+1...
Python
zaydzuhri_stack_edu_python
function cmd_target_modify context targetid options begin call test_db_updates_allowed comment get targetid if options are for interactive request and validate that comment it is valid. Returns None if interactive request is aborted set targetid = call get_target_id context targetid options if targetid is none begin re...
def cmd_target_modify(context, targetid, options): test_db_updates_allowed() # get targetid if options are for interactive request and validate that # it is valid. Returns None if interactive request is aborted targetid = get_target_id(context, targetid, options) if targetid is None: return ...
Python
nomic_cornstack_python_v1
function find_occurrences number_list begin set counter = counter number_list set occurrences = call most_common return occurrences end function
def find_occurrences(number_list): counter = Counter(number_list) occurrences = counter.most_common() return occurrences
Python
nomic_cornstack_python_v1
function testProductUninstalled self begin call failIf call isProductInstalled string NuPlone end function
def testProductUninstalled(self): self.failIf(self.qitool.isProductInstalled("NuPlone"))
Python
nomic_cornstack_python_v1
if its_hot begin print string It's a hot day print string Drink More Water end else if its_cold begin print string It's a Cold day print string Wear Warm Clothes end else begin print string It's a Lovely Day end print string Enjoy Your Day comment elif is nothing but else if. If the condition in if statement is true th...
if its_hot: print("It's a hot day") print("Drink More Water") elif its_cold: print("It's a Cold day") print("Wear Warm Clothes") else: print("It's a Lovely Day") print("Enjoy Your Day") # elif is nothing but else if. If the condition in if statement is true then if block is executed and ...
Python
zaydzuhri_stack_edu_python
for i in range 100 0 - 10 begin print i end print string ----------------------- for i in range 100 0 - 10 begin print i end=string end
for i in range(100,0,-10): print(i) print("-----------------------") for i in range(100,0,-10): print(i,end='')
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment cherrytree.py import sys import os import re from pathlib import Path from operator import itemgetter import logging import attr from lxml import etree import base64 from fuzzywuzzy import fuzz set logger = call getLogger __name__ set token_specificatio...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # cherrytree.py # import sys import os import re from pathlib import Path from operator import itemgetter import logging import attr from lxml import etree import base64 from fuzzywuzzy import fuzz logger = logging.getLogger(__name__) token_specification = [ ('bul...
Python
zaydzuhri_stack_edu_python
comment # How many votes did you get? comment my_votes = int(input("How many votes did you get in the election? ")) comment # Total votes in the election comment total_votes = int(input("What is the total votes in the election? ")) comment # Calculate the percentage of votes you received. comment percentage_votes = (my...
# # How many votes did you get? # my_votes = int(input("How many votes did you get in the election? ")) # # Total votes in the election # total_votes = int(input("What is the total votes in the election? ")) # # Calculate the percentage of votes you received. # percentage_votes = (my_votes / total_votes) * 100 # print...
Python
zaydzuhri_stack_edu_python