code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python3 string Create Masks https://www.tensorflow.org/tutorials/text/transformer#masking import tensorflow.compat.v2 as tf function create_masks inputs target begin string creates all masks for training/validation Args: inputs: tf.Tensor of shape (batch_size, seq_len_in) that contains the input s...
#!/usr/bin/env python3 '''Create Masks https://www.tensorflow.org/tutorials/text/transformer#masking ''' import tensorflow.compat.v2 as tf def create_masks(inputs, target): '''creates all masks for training/validation Args: inputs: tf.Tensor of shape (batch_size, seq_len_in) that contains the ...
Python
zaydzuhri_stack_edu_python
import cv2 set img = call imread string ..\Photos\question.jpg image show string Original img function rescale_frame frame scale=0.5 begin comment works for images, video and live video set width = integer shape at 1 * scale set height = integer shape at 0 * scale set dimensions = tuple width height return call resize ...
import cv2 img = cv2.imread('..\Photos\question.jpg') cv2.imshow('Original',img) def rescale_frame(frame,scale=0.5): #works for images, video and live video width=int(frame.shape[1]*scale) height=int(frame.shape[0]*scale) dimensions = (width,height) return cv2.resize(frame,dimensions,i...
Python
zaydzuhri_stack_edu_python
function attrSetCallback **kwargs begin set do_calls = list for name in keys kwargs begin if starts with name string _ begin raise call PrivateFunctionalityError name end if starts with name string do__ begin append do_calls name at slice 4 : : del kwargs at name end end function attrSet_callback widget=none begin fo...
def attrSetCallback(**kwargs): do_calls = [] for name in kwargs.keys(): if name.startswith("_"): raise exceptions.PrivateFunctionalityError(name) if name.startswith("do__"): do_calls.append(name[4:]) del kwargs[name] def attrSet_callback(widget=None): for name,value in kwargs.items(): setattr(wid...
Python
nomic_cornstack_python_v1
async function get_hash identifier begin return hex digest md5 encode identifier string utf8 end function
async def get_hash(identifier): return hashlib.md5(identifier.encode('utf8')).hexdigest()
Python
nomic_cornstack_python_v1
import pandas as pd import matplotlib.pyplot as plt comment Loading the data from a csv into a pandas dataframe set Banned_Maps = read csv string Data/banned_maps_stats.csv set Maps_picked = read csv string Data/map_pick_stats.csv set Player_Stats = read csv string Data/player_stats.csv set CTorTsided = read csv string...
import pandas as pd import matplotlib.pyplot as plt #Loading the data from a csv into a pandas dataframe Banned_Maps = pd.read_csv("Data/banned_maps_stats.csv") Maps_picked = pd.read_csv("Data/map_pick_stats.csv") Player_Stats = pd.read_csv("Data/player_stats.csv") CTorTsided = pd.read_csv("Data/side_pick_stats...
Python
zaydzuhri_stack_edu_python
function CreatePersoData nPerso=10 properties=dict preferences=list string clim string mur string passage string sonnerie string wc string weightEtage string window begin set dicoPersos = dict string Nom list comprehension string Dummy%d % i for i in range nPerso set persoData = call DataFrame dicoPersos for tuple pro...
def CreatePersoData( nPerso=10, properties = {}, preferences = ['clim', 'mur', 'passage', 'sonnerie', 'wc', 'weightEtage', 'window'] ) : dicoPersos = {'Nom' : ['Dummy%d'%(i) for i in range(nPerso)]} persoData = pd.DataFrame( dicoPersos) for p...
Python
nomic_cornstack_python_v1
import os import pickle import imageio import numpy as np from typing import Callable function save_tif_to_numpy_pkl base_path=join path string .. string data string Coastal-InSAR file_name=string imgs_numpy.pkl begin string read tif files and convert them in a pickle file base_path: str -- directory containing tiff fi...
import os import pickle import imageio import numpy as np from typing import Callable def save_tif_to_numpy_pkl( base_path: str = os.path.join("..", "data", "Coastal-InSAR"), file_name: str = "imgs_numpy.pkl", ) -> None: """read tif files and convert them in a pickle file\n base_path: st...
Python
zaydzuhri_stack_edu_python
function colour_code_segmentation image label_values begin comment w = image.shape[0] comment h = image.shape[1] comment x = np.zeros([w,h,3]) comment colour_codes = label_values comment for i in range(0, w): comment for j in range(0, h): comment x[i, j, :] = colour_codes[int(image[i, j])] set label_values = list compr...
def colour_code_segmentation(image, label_values): # w = image.shape[0] # h = image.shape[1] # x = np.zeros([w,h,3]) # colour_codes = label_values # for i in range(0, w): # for j in range(0, h): # x[i, j, :] = colour_codes[int(image[i, j])] label_values = [label_values[key] for key in label_values]...
Python
nomic_cornstack_python_v1
comment 349. Intersection of Two Arrays comment Given two arrays, write a function to compute their intersection. comment Example: comment Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] comment Output: [9,4] comment Note: comment Each element in the result must be unique. comment The result can be in any order. comment So...
# 349. Intersection of Two Arrays # Given two arrays, write a function to compute their intersection. # Example: # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # Note: # Each element in the result must be unique. # The result can be in any order. # Solution 1 using set: class Solution: def inte...
Python
zaydzuhri_stack_edu_python
import pytest string This program will check if the login has the correct information given certain inputs of username and password. The first test will pass because the username and the password are the correct information. The second test will fail due to the username of 'wronguser' and the password of 'wrongpassword...
import pytest """ This program will check if the login has the correct information given certain inputs of username and password. The first test will pass because the username and the password are the correct information. The second test will fail due to the username of 'wronguser' and the ...
Python
zaydzuhri_stack_edu_python
import re function strip string el=string begin if el != string begin set stringRegex = compile el end else begin set stringRegex = compile string (^\s)?(\s$)? end return sub string string end function set text = input set letter = input print strip text letter print strip text
import re def strip(string, el=' '): if el != ' ': stringRegex = re.compile(el) else: stringRegex = re.compile(r'(^\s)?(\s$)?') return stringRegex.sub('', string) text = input() letter = input() print(strip(text, letter)) print(strip(text))
Python
zaydzuhri_stack_edu_python
import unittest from assembly import AssemblyChip , READ , WRITE , RUN , global_inc string TODO: * test bounds checks for add/subtract/move with acc * test multiple cascading MOV ops * test remaining ops ( set DEBUG = true function debug msg begin if DEBUG begin print string msg end end function function parse program ...
import unittest from assembly import AssemblyChip, READ, WRITE, RUN, global_inc ''' TODO: * test bounds checks for add/subtract/move with acc * test multiple cascading MOV ops * test remaining ops ( ''' DEBUG = True def debug(msg): if DEBUG: print(str(msg)) def parse(program): # remove extra white...
Python
zaydzuhri_stack_edu_python
function give_meta_output self begin set out = string set out = out + call output if inputs begin set out = out + call output end return out end function
def give_meta_output(self): out = '' out += self.meta.output() if self.inputs: out += self.inputs.output() return out
Python
nomic_cornstack_python_v1
import cv2 comment Classifies a given image into one of the breed classes function classify image begin comment Retrieve the breed classes from the database set breeds = call get_breeds set closest_distance = decimal string inf set closest_breed = none comment Create a feature descriptor for the image set feature_descr...
import cv2 # Classifies a given image into one of the breed classes def classify(image): # Retrieve the breed classes from the database breeds = get_breeds() closest_distance = float('inf') closest_breed = None # Create a feature descriptor for the image feature_descriptor = cv2.xfeatur...
Python
jtatman_500k
function create_user self begin comment TODO-ROB: This is used ONLY when the user registers in flask comment TODO-ROB: Create the cookiecutter.json file comment extra_context overrides user and default configs call cookiecutter user_cookie no_input=true extra_context=dict string user_name user output_dir=users end func...
def create_user(self): # TODO-ROB: This is used ONLY when the user registers in flask # TODO-ROB: Create the cookiecutter.json file # extra_context overrides user and default configs cookiecutter(self.user_cookie, no_input=True, extra_context={"user_name": self.user}, output_dir=self.u...
Python
nomic_cornstack_python_v1
function __lt__ self *args begin return call ctext_position_t___lt__ self *args end function
def __lt__(self, *args): return _ida_hexrays.ctext_position_t___lt__(self, *args)
Python
nomic_cornstack_python_v1
function __init__ self model settings begin call __init__ self set settings = settings call ValidateAndAssignDefaults call GetDefaultParameters set distance_processes = list set model_part = model at call GetString set boundaries_names = call GetStringArray set distance_calculator_settings = parameters KM call AddValu...
def __init__(self, model, settings): KM.Process.__init__(self) self.settings = settings self.settings.ValidateAndAssignDefaults(self.GetDefaultParameters()) self.distance_processes = [] self.model_part = model[self.settings["computing_model_part_name"].GetString()] bou...
Python
nomic_cornstack_python_v1
function get_initial_states energies num_istates_to_generate prefactor average_excitation_energy ref_state begin set nstates = length energies comment Obtain energy of first step for each electronic states set initial_excitation_energies = list for state in range nstates begin set ref_energy = energies at ref_state at...
def get_initial_states( energies, num_istates_to_generate, prefactor, average_excitation_energy, ref_state ): nstates = len(energies) # Obtain energy of first step for each electronic states initial_excitation_energies = [] for state in range( nstates ): ref_energy = energies[ref_state][...
Python
nomic_cornstack_python_v1
function setUp self begin set apiproxy = call APIProxyStubMap set mox = call Mox call StubOutWithMock apiproxy string MakeSyncCall end function
def setUp(self): apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() self.mox = mox.Mox() self.mox.StubOutWithMock(apiproxy_stub_map.apiproxy, 'MakeSyncCall')
Python
nomic_cornstack_python_v1
function download_pil_image self url begin return open url open url end function
def download_pil_image(self, url): return Image.open(urlopen(url))
Python
nomic_cornstack_python_v1
import sys import time import math function inpl begin return list map int split input end function set st = performance counter comment ------------------------------ set tuple A B K = map int split input set ans = list for i in range 1 min A B + 1 begin if A % i == 0 and B % i == 0 begin append ans i end end print a...
import sys import time import math def inpl(): return list(map(int, input().split())) st = time.perf_counter() # ------------------------------ A, B, K = map(int, input().split()) ans = [] for i in range(1, min(A, B)+1): if A%i == 0 and B%i == 0: ans.append(i) print(ans[len(ans)-K]) # -------------------------...
Python
zaydzuhri_stack_edu_python
comment Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd comment Importing the dataset set dataset = read csv string Data.csv set X = values set y = values comment Encoding categorical data from sklearn.preprocessing import LabelEncoder comment from sklearn.preprocessing impor...
# Import the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder #from sklearn.p...
Python
zaydzuhri_stack_edu_python
function merge_many outpath *paths auto_open_zips=true begin if not paths begin raise call ValueError string must have at least one path! end if exists path outpath begin call deldir outpath end make directories outpath set cur_all = none for path in paths begin set to_rezip = list if auto_open_zips begin set to_rezip...
def merge_many(outpath: str, *paths, auto_open_zips=True): if not paths: raise ValueError(f'must have at least one path!') if os.path.exists(outpath): filetools.deldir(outpath) os.makedirs(outpath) cur_all = None for path in paths: to_rezip = [] if au...
Python
nomic_cornstack_python_v1
function test_unboxing_multiply begin set m_per_s = call unit string m / call unit string s set s_per_m = call unit string s / call unit string m assert call m_per_s 5 * call s_per_m 5 == 25 end function
def test_unboxing_multiply(): m_per_s = unit('m') / unit('s') s_per_m = unit('s') / unit('m') assert m_per_s(5) * s_per_m(5) == 25
Python
nomic_cornstack_python_v1
comment 带参数的装饰器 import time print string 带参数的装饰器 comment 装饰器函数 function timmer f begin function inner *args **kwargs begin set start = time comment 被装饰的函数 热接受f()的返回值'ls' set ret = f dist *args keyword kwargs set end = time print end - start comment inner函数返回值ret return ret end function return inner end function decorat...
# 带参数的装饰器 import time print('带参数的装饰器') def timmer(f): # 装饰器函数 def inner(*args, **kwargs): start = time.time() ret = f(*args, **kwargs) # 被装饰的函数 热接受f()的返回值'ls' end = time.time() print(end - start) return ret # inner函数返回值ret return inner @timmer # 语法...
Python
zaydzuhri_stack_edu_python
function make_dict answer begin string Make dictionary form list answer - list of colors comment dic = {i: answer[i] for i in range(len(answer))} comment dict(zip(range(len(answer)), answer)) return dictionary comprehension i : answer at i for i in range length answer end function
def make_dict(answer): """ Make dictionary form list answer - list of colors """ # dic = {i: answer[i] for i in range(len(answer))} return {i: answer[i] for i in range(len(answer))} #dict(zip(range(len(answer)), answer))
Python
zaydzuhri_stack_edu_python
function test_delete_query_index_failure self begin with assert raises CloudantArgumentError as cm begin call delete_query_index none string special string _all_docs end set err = exception assert equal string err string Invalid index type: special. Index type must be either "json" or "text". end function
def test_delete_query_index_failure(self): with self.assertRaises(CloudantArgumentError) as cm: self.db.delete_query_index(None, 'special', '_all_docs') err = cm.exception self.assertEqual( str(err), 'Invalid index type: special. ' 'Index type mus...
Python
nomic_cornstack_python_v1
function challenge_get self environ start_response begin set redirect = get environ at string tiddlyweb.query string tiddlyweb_redirect list string / at 0 set template = call get_template environ string login_form.html set headers = list comment If the current user is expired, log them out as part of this comment requ...
def challenge_get(self, environ, start_response): redirect = (environ['tiddlyweb.query']. get('tiddlyweb_redirect', ['/'])[0]) template = templating.get_template(environ, 'login_form.html') headers = [] # If the current user is expired, log them out as part of this ...
Python
nomic_cornstack_python_v1
from selenium import webdriver set driver = call Chrome executable_path=string C:\Drivers\Chrome\chromedriver.exe get driver string https://www.seleniumeasy.com/test/table-pagination-demo.html set rows = length call find_elements_by_xpath string //*[@id='myTable']/tr set cols = length call find_elements_by_xpath string...
from selenium import webdriver driver = webdriver.Chrome(executable_path = "C:\Drivers\Chrome\chromedriver.exe") driver.get("https://www.seleniumeasy.com/test/table-pagination-demo.html") rows=(len(driver.find_elements_by_xpath("//*[@id='myTable']/tr"))) cols=(len(driver.find_elements_by_xpath("//*[@id='myTable']...
Python
zaydzuhri_stack_edu_python
from abc import ABC , abstractmethod class BaseAgent extends ABC begin decorator abstractmethod function get_action self state env begin pass end function decorator abstractmethod function learn self state action next_state reward begin pass end function end class
from abc import ABC, abstractmethod class BaseAgent(ABC): @abstractmethod def get_action(self, state, env): pass @abstractmethod def learn(self, state, action, next_state, reward): pass
Python
zaydzuhri_stack_edu_python
from covid19.main import COVID set negara = string Indo set covid = call COVID get covid set dataAktif = call getActive country=negara for data in dataAktif begin comment Take the name of the country print string Negara: + data at string country comment Retrieves active corona data print string Aktif : + string data at...
from covid19.main import COVID negara = "Indo" covid = COVID() covid.get() dataAktif = covid.getActive(country=negara) for data in dataAktif: print ("Negara: " + data["country"]) # Take the name of the country print ("Aktif : " + str(data["active"])) # Retrieves active corona data print ("-" * 25)
Python
zaydzuhri_stack_edu_python
function answer request begin set question = GET at string question sleep 0.5 try begin set answerDic = call getAnswers question set answer = answerDic at string answer end except IndexError begin set answer = string Jag har inget svar på din fråga: + question set answerDic = dict string confidence 1 end return call Re...
def answer(request): question = request.GET['question'] sleep(0.5) try: answerDic = queryAnalyzer.getAnswers(question) answer = answerDic['answer'] except IndexError: answer = "Jag har inget svar på din fråga: " + question answerDic = {"confidence": 1} return Response({"answer": answer, "con...
Python
nomic_cornstack_python_v1
comment -*- coding: iso-8859-1 -*- import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from random import uniform import math from Vector2D import * from Paddle import * from Block import * from Pelota import * from Score import * from utils import * from Vista import * comment Fu...
# -*- coding: iso-8859-1 -*- import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from random import uniform import math from Vector2D import * from Paddle import * from Block import * from Pelota import * from Score import * from utils import * from Vista import * ################...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from obspy.core import read , UTCDateTime , Stream import matplotlib.pyplot as plt from scipy import signal import matplotlib as mpl from itertools import combinations import numpy as np set debug = true comment Importing and applying font call rc string font family=string serif call rc str...
#!/usr/bin/env python from obspy.core import read, UTCDateTime, Stream import matplotlib.pyplot as plt from scipy import signal import matplotlib as mpl from itertools import combinations import numpy as np debug = True # Importing and applying font mpl.rc('font', family = 'serif') mpl.rc('font', serif = 'Times') mp...
Python
zaydzuhri_stack_edu_python
import turtle set man = call Turtle backward man 100 comment green call color string green call begin_fill call forward 350 call left 90 call forward 150 call left 90 call forward 350 call left 90 call forward 150 call left 90 call end_fill call forward 350 comment orange call color string orange call begin_fill call l...
import turtle man = turtle.Turtle(); man.backward(100) #green man.color("green") man.begin_fill() man.forward(350) man.left(90) man.forward(150) man.left(90) man.forward(350) man.left(90) man.forward(150) man.left(90) man.end_fill() man.forward(350) #orange man.color("orange") man.begin_fill() man.left(90) man.forwar...
Python
zaydzuhri_stack_edu_python
import random set rzut = call randrange 1 7 set guess = integer input string Podaj, ile oczek kostki wyrzucił komputer: if guess == rzut begin set x = true end else begin set x = false end print format string Komputer wyrzucił: {} rzut print format string Zgadłeś: {} ({}) guess x
import random rzut = random.randrange(1,7) guess = int(input("Podaj, ile oczek kostki wyrzucił komputer: ")) if guess == rzut: x=True else: x=False print("Komputer wyrzucił: {}".format(rzut)) print("Zgadłeś: {} ({})".format(guess,x))
Python
zaydzuhri_stack_edu_python
function exchange_first_last seq begin set first = seq at slice 0 : 1 : set middle = seq at slice 1 : - 1 : set last = seq at slice - 1 : : set seq_copy = last + middle + first return seq_copy end function
def exchange_first_last(seq): first = seq[0:1] middle = seq[1:-1] last = seq[-1:] seq_copy = last + middle + first return seq_copy
Python
nomic_cornstack_python_v1
import copy function check_perf f *args begin import time set n = 10 set t0 = time for i in range n begin f dist *args end set t1 = time return t1 - t0 / n end function class CrazyRobot begin set pointsX = list 1 - 1 0 0 set pointsY = list 0 0 - 1 1 function __init__ self prob depth begin set depth = depth set prob = l...
import copy def check_perf(f, *args): import time n = 10 t0 = time.time() for i in range(n): f(*args) t1 = time.time() return (t1 - t0) / n class CrazyRobot: pointsX = [1, -1, 0, 0] pointsY = [0, 0, -1, 1] def __init__(self, prob, depth): self...
Python
zaydzuhri_stack_edu_python
function get_common_class y_train begin comment Get the unique labels and their counts set labels = list set counts = list for label in y_train begin if label in labels begin set idx = index labels label set counts at idx = counts at idx + 1 end else begin append labels label append counts 0 end end comment Get the i...
def get_common_class(y_train): # Get the unique labels and their counts labels = [] counts = [] for label in y_train: if label in labels: idx = labels.index(label) counts[idx] = counts[idx] + 1 else: labels.append(label) counts.append(0) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set plane_rows = 128 set plane_columns = 8 function compute_id p begin set tuple binf bsup = tuple 0 plane_rows - 1 for letter in p at slice : 7 : begin if letter == string F begin set bsup = bsup - integer bsup - binf + 1 / 2 end else begin set binf = binf + integer bsup - binf + 1 / 2 e...
#!/usr/bin/env python plane_rows = 128 plane_columns = 8 def compute_id(p): binf, bsup = 0, plane_rows - 1 for letter in p[:7]: if letter == "F": bsup -= int((bsup - binf + 1) / 2) else: binf += int((bsup - binf + 1) / 2) row = bsup binf, bsup = 0, plane_colum...
Python
zaydzuhri_stack_edu_python
function add_args_to_parser self parser recursive=false prefix=string begin function str2bool v begin if lower v in tuple string yes string true string on string t string 1 begin return true end else if lower v in tuple string no string false string off string f string 0 begin return false end else begin raise call Val...
def add_args_to_parser(self, parser, recursive=False, prefix=''): def str2bool(v): if v.lower() in ("yes", "true", "on", "t", "1"): return True elif v.lower() in ("no", "false", "off", "f", "0"): return False else: raise ValueE...
Python
nomic_cornstack_python_v1
function getInstanceMethod self inClass method begin call sendConvertSpecial string getInstanceMethod:InClass: %s %s % tuple method inClass return call readResponseConvertNL end function
def getInstanceMethod(self,inClass,method): self.sendConvertSpecial("getInstanceMethod:InClass:\t%s\t%s"%(method,inClass)) return self.readResponseConvertNL()
Python
nomic_cornstack_python_v1
import telebot set bot = call TeleBot string 1435978036:AAGmJOMQv4q89TU0q8Qinq8fSDkdoiFSJYo decorator call message_handler commands=list string start comment weRtr_bot function start m begin print id call send_message id string Hello! /size for setting size of room call register_next_step_handler m picker end function ...
import telebot; bot = telebot.TeleBot('1435978036:AAGmJOMQv4q89TU0q8Qinq8fSDkdoiFSJYo'); #weRtr_bot @bot.message_handler(commands=['start']) def start(m): print(m.chat.id) bot.send_message(m.chat.id,'Hello! \n /size for setting size of room \n') bot.register_next_step_handler(m, picker) def picker...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from datetime import datetime import os import pdb set DATAROOT = string /home/ryan/ml/harrisTrader/data/ function close_prices symbol begin set filename = DATAROOT + symbol + string .csv set history = read csv filename index_col=0 return size end function function percent_change_...
import pandas as pd import numpy as np from datetime import datetime import os import pdb DATAROOT = "/home/ryan/ml/harrisTrader/data/" def close_prices(symbol): filename = DATAROOT + symbol + ".csv" history = pd.read_csv(filename, index_col=0) return history.values[:,5].size def percent_change_single(s...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys import csv import string set f = open string stop-word-list.csv set reader = reader f set onestop = next set stopList = list for word in onestop begin append stopList strip word end set exclude = set punctuation + digits function firstLetter word begin set initialLetter = word at 0 ...
#!/usr/bin/python import sys import csv import string f = open("stop-word-list.csv") reader = csv.reader(f) onestop = reader.next() stopList = [] for word in onestop: stopList.append(word.strip()) exclude=set(string.punctuation+string.digits) def firstLetter(word): initialLetter = word[0]
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Mar 19 21:02:57 2017 @author: priyanshu string Using this Script videos,audios can be downloaded from various sites like facebook, youtube,9gag,Soundcloud etc Follow the Commands in the console Make changes as neccesary suggest changes at :- contactme@priyanshuhazra.t...
# -*- coding: utf-8 -*- """ Created on Sun Mar 19 21:02:57 2017 @author: priyanshu """ """ Using this Script videos,audios can be downloaded from various sites like facebook, youtube,9gag,Soundcloud etc Follow the Commands in the console Make changes as neccesary suggest changes at :- contactme@priyanshuhazra.tk / pr...
Python
zaydzuhri_stack_edu_python
function getDefaultApplicationTools begin Ellipsis end function
def getDefaultApplicationTools() -> java.util.Set: ...
Python
nomic_cornstack_python_v1
function run_parser self cls extension write=false begin set filenames = get SAMPLES extension list assert length filenames >= 1 for filename in filenames begin set tuple fname ext = call splitext filename set tuple path fname = split path fname print string print filename set spec = call cls filename print spec if wri...
def run_parser(self, cls, extension, write=False): filenames = SAMPLES.get(extension, []) assert len(filenames) >= 1 for filename in filenames: fname, ext = os.path.splitext(filename) path, fname = os.path.split(fname) print('') print(filename) ...
Python
nomic_cornstack_python_v1
function get_block_device_list vars=dict log=stderr begin comment make sure we can access to the files/directories in /proc if not call access PROC_PARTITIONS_PATH F_OK begin return none end comment table with valid scsi/sata/ide/raid block device names set valid_blk_names = dict comment add in valid sd and hd block ...
def get_block_device_list(vars = {}, log = sys.stderr): # make sure we can access to the files/directories in /proc if not os.access(PROC_PARTITIONS_PATH, os.F_OK): return None # table with valid scsi/sata/ide/raid block device names valid_blk_names = {} # add in valid sd and hd block devi...
Python
nomic_cornstack_python_v1
function build_model max_seq_len vocab_size emb_size learning_rate encoder_type pretrained_target=true pretrained_input=false input_trainable=false pre_embs=none begin comment Build the TF graph on the GPU. with device string /device:GPU:0 begin call reset_default_graph comment Batch of input definitions (glosses). set...
def build_model(max_seq_len, vocab_size, emb_size, learning_rate, encoder_type, pretrained_target=True, pretrained_input=False, input_trainable=False, pre_embs=None): # Build the TF graph ...
Python
nomic_cornstack_python_v1
comment Ahad Bawany comment Daily code 6/30: comment Given 2 lists of numbers, find the intersection point within them comment Lists to test our function set a = list 1 2 3 5 6 8 9 set b = list 0 7 5 6 7 8 comment Given a list, a, and a list, b, return the intersection function findIntersect a b begin comment Ensure bo...
# Ahad Bawany # Daily code 6/30: # Given 2 lists of numbers, find the intersection point within them # Lists to test our function a = [1, 2, 3, 5, 6, 8, 9] b = [0, 7, 5, 6, 7, 8] # Given a list, a, and a list, b, return the intersection def findIntersect(a,b): # Ensure both a and b exist if ...
Python
zaydzuhri_stack_edu_python
for i in range 1 n + 1 begin set n = n - i if n == 0 begin print string patlu break end set o = 2 * i set n = n - o print n set i = i + 1 if n == 0 or n < 0 begin print string motu break end end
for i in range(1,n+1): n=n-i if n==0: print("patlu") break o=2*i n=n-o print(n) i=i+1 if n==0 or n<0: print("motu") break
Python
zaydzuhri_stack_edu_python
comment https://www.reddit.com/r/dailyprogrammer/comments/4savyr/20160711_challenge_275_easy_splurthian_chemistry/ function verifySymbol chemical symbol begin set chemical = list chemical set chemical = list comprehension lower x for x in chemical set symbol = list symbol if index chemical lower symbol at 0 >= 0 begin ...
# https://www.reddit.com/r/dailyprogrammer/comments/4savyr/20160711_challenge_275_easy_splurthian_chemistry/ def verifySymbol(chemical, symbol): chemical = list(chemical) chemical = [x.lower() for x in chemical] symbol = list(symbol) if chemical.index(symbol[0].lower()) >= 0: if chemical.index...
Python
zaydzuhri_stack_edu_python
import os import shutil print string Copia de Archivos set nombre = input string Ingrese El Nombre Del Archivo [ A ]: function creartxt begin set txt = open nombre + string .txt string w close txt end function function guardartxt begin set txt = open nombre + string .txt string a write txt input string Ingrese El Texto...
import os import shutil print("Copia de Archivos") nombre = input("Ingrese El Nombre Del Archivo [ A ]: ") def creartxt(): txt = open(nombre + '.txt', 'w') txt.close() def guardartxt(): txt = open(nombre + '.txt', 'a') txt.write(input('Ingrese El Texto: ')) txt.close() def le...
Python
zaydzuhri_stack_edu_python
comment function to find maximum number set n1 = integer input string Enter 1st number: set n2 = integer input string Enter 2nd number: set n3 = integer input string Enter 3rd number: function max a b c begin if a > b and a > c begin print a string is the largest number end else if b > a and b > c begin print b string ...
#function to find maximum number n1= int(input('Enter 1st number:')) n2= int(input('Enter 2nd number:')) n3= int(input('Enter 3rd number:')) def max(a,b,c): if a>b and a>c: print(a,'is the largest number') elif b>a and b>c: print(b, 'is the largest number') else: print(c, 'is the lar...
Python
zaydzuhri_stack_edu_python
function count_characters input_string begin set char_count = dict for char in input_string begin if char in char_count begin set char_count at char = char_count at char + 1 end else begin set char_count at char = 1 end end return char_count end function set input_str = string Hello, World! set character_counts = call...
def count_characters(input_string): char_count = {} for char in input_string: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 return char_count input_str = "Hello, World!" character_counts = count_characters(input_str) print(characte...
Python
jtatman_500k
comment !/usr/bin/env python comment take in raw text values from server, comment parse into variables for main RasPlanter program class ServerCommand begin function __init__ self raw_string begin set command = split raw_string string :: set command_type = command at 0 set command_data = command at 1 end function funct...
#!/usr/bin/env python #take in raw text values from server, #parse into variables for main RasPlanter program class ServerCommand: def __init__(self, raw_string): command = raw_string.split("::") self.command_type = command[0] self.command_data = command[1] def get_command_type(self): return self.command_...
Python
zaydzuhri_stack_edu_python
import sys import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import tqdm import os import numpy as np import time from data_sets.data_set_utils import * from nets.pruner import Pruner from render import render from matplotlib import cm from torch.optim.adam import Adam from ...
import sys import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import tqdm import os import numpy as np import time from data_sets.data_set_utils import * from nets.pruner import Pruner from render import render from matplotlib import cm from torch.optim.adam import Adam fr...
Python
zaydzuhri_stack_edu_python
function weirdwalk n a b begin set alice = 0 set bob = 0 set total = 0 for i in range n begin if a at i == b at i and alice == bob begin set total = total + a at i end set alice = alice + a at i set bob = bob + b at i end return total end function set test = integer input for i in range test begin set n = integer input...
def weirdwalk(n, a, b): alice = 0 bob = 0 total = 0 for i in range(n): if((a[i]==b[i]) and (alice==bob)): total+=a[i] alice+=a[i] bob+=b[i] return total test = int(input()) for i in range(test): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) ...
Python
zaydzuhri_stack_edu_python
function get_args begin set parser = call ArgumentParser description=string Runner for tasks call add_argument string --db_url help=string Database url string to the db. required=true return call parse_args end function
def get_args(): parser = argparse.ArgumentParser(description='Runner for tasks') parser.add_argument('--db_url', help='Database url string to the db.', required=True) return parser.parse_args()
Python
nomic_cornstack_python_v1
from random import uniform , choice , random from math import exp set nbobjects = 1000 set objects = dictionary comprehension k : dict string value uniform 40 50 ; string weight uniform 1 5 for k in range nbobjects set max_weight = 100 set sack = dict set o = copy objects set s = copy sack set T = 10 set value = 0 whi...
from random import uniform, choice, random from math import exp nbobjects = 1000 objects = {k: {'value': uniform(40, 50), 'weight': uniform(1, 5)} for k in range(nbobjects)} max_weight = 100 sack = {} o = objects.copy() s = sack.copy() T = 10 value = 0 while T > .01: i = choice(list(objects.keys())) sack[i] =...
Python
zaydzuhri_stack_edu_python
function fit_anonymous self struct1 struct2 begin set tuple min_rms min_mapping = call get_minimax_rms_anonymous struct1 struct2 if min_rms is none or min_rms > stol begin return none end else begin return min_mapping end end function
def fit_anonymous(self, struct1, struct2): min_rms, min_mapping = self.get_minimax_rms_anonymous(struct1, struct2) if min_rms is None or min_rms > self.stol: return None else: return min_mapping
Python
nomic_cornstack_python_v1
function test_portfolio_what_if self begin pass end function
def test_portfolio_what_if(self): pass
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other APIToken begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, APIToken): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function get_aliases_string trembl_list begin set aliases_list = list for row in trembl_list begin set psimi_trembl = string trembl: + row at 1 append aliases_list psimi_trembl end return join string | aliases_list end function
def get_aliases_string(trembl_list): aliases_list = [] for row in trembl_list: psimi_trembl = "trembl:" + row[1] aliases_list.append(psimi_trembl) return "|".join(aliases_list)
Python
nomic_cornstack_python_v1
function fix_logs_paths img_dir data_frame begin set pathfn = lambda p -> join path img_dir split p string / at - 1 set center = apply center pathfn set left = apply left pathfn set right = apply right pathfn end function
def fix_logs_paths(img_dir, data_frame): pathfn = lambda p: os.path.join(img_dir, p.split('/')[-1]) data_frame.center = data_frame.center.apply(pathfn) data_frame.left = data_frame.left.apply(pathfn) data_frame.right = data_frame.right.apply(pathfn)
Python
nomic_cornstack_python_v1
class Node begin function __init__ self value next begin set value = value set next = next end function function printList self begin set head = self while head != none begin print value end=string set head = next end end function end class
class Node: def __init__(self, value, next): self.value = value self.next = next def printList(self): head = self while head != None: print(head.value,end='\t') head = head.next
Python
zaydzuhri_stack_edu_python
function get_ppis self ppi_df begin string Generate Complex Statements from the HPRD PPI data. Parameters ---------- ppi_df : pandas.DataFrame DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. info string Processing PPIs... for tuple ix row in call iterrows begin set agA = call _make_agent row at ...
def get_ppis(self, ppi_df): """Generate Complex Statements from the HPRD PPI data. Parameters ---------- ppi_df : pandas.DataFrame DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. """ logger.info('Processing PPIs...') ...
Python
jtatman_500k
import sqlite3 set conn = call connect string employees.db set cursor = call cursor comment Create the emloyee table execute cursor string CREATE TABLE employee( emp_code text, last_name text, first_name text, age integer, gender text, salary DECIMAL(10,5), city text, state text, country text ) comment make changes to ...
import sqlite3 conn=sqlite3.connect("employees.db") cursor=conn.cursor() #Create the emloyee table cursor.execute("""CREATE TABLE employee( emp_code text, last_name text, first_name text, age integer, gender text, salary DECIMAL(10,5), ...
Python
zaydzuhri_stack_edu_python
from functions import matcher_functions from util import helper from util import models import numpy as np import logging set MIN_MATCHES = 350 function find_next_key_frame idx1 idx2 begin string Finds point matches that are preserved between idx1 and idx2 :param idx1: index to start with :param idx2: index to end with...
from functions import matcher_functions from util import helper from util import models import numpy as np import logging MIN_MATCHES = 350 def find_next_key_frame(idx1, idx2): ''' Finds point matches that are preserved between idx1 and idx2 :param idx1: index to start with :param idx2: index to end ...
Python
zaydzuhri_stack_edu_python
function list_tags begin set tags = all return call render_template string tags.html tags=tags end function
def list_tags(): tags = Tag.query.order_by(Tag.name).all() return render_template('tags.html', tags=tags)
Python
nomic_cornstack_python_v1
function split_string line nth begin return list comprehension integer line at slice i : i + nth : for i in range 0 length line nth end function
def split_string(line, nth): return [int(line[i:i+nth]) for i in range(0, len(line), nth)]
Python
nomic_cornstack_python_v1
while f begin set n = integer input string введите число 0=exit : if n == 0 begin break end set a = list comprehension i for i in range n + 1 set b = list print a for i in range 2 n begin if i ^ 2 <= n and a at i != 0 begin for j in range i ^ 2 n + 1 i begin set a at j = 0 end end end comment print(a) for i in range n...
while f: n=int(input('введите число 0=exit : ')) if n==0: break a= [i for i in range(n+1)] b=[] print (a) for i in range(2,n): if (i**2<=n) and (a[i]!=0): for j in range(i**2,n+1,i): a[j]=0 #print(a) for i in range(n+1): if a[i]!=0...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Feb 22 19:23:14 2016 297. Serialize and Deserialize Binary Tree Total Accepted: 13261 Total Submissions: 49776 Difficulty: Medium Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory...
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 19:23:14 2016 297. Serialize and Deserialize Binary Tree Total Accepted: 13261 Total Submissions: 49776 Difficulty: Medium Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buf...
Python
zaydzuhri_stack_edu_python
function move self game_map player begin comment Move the entity by their current_speed set death_state = none set results = list set tuple dx dy = hex_directions at direction for speed in range 0 current_speed begin set new_x = x + dx if dx == 0 begin set new_y = y + dy end else begin set new_y = y + dy + x % 2 end c...
def move(self, game_map, player): # Move the entity by their current_speed death_state = None results = [] dx, dy = hex_directions[self.direction] for speed in range(0, self.current_speed): new_x = self.owner.x + dx if dx == 0: new_y = self...
Python
nomic_cornstack_python_v1
function __create_author_investigator_str self begin string When investigators is empty, try to get authors from the first publication instead. :return str author: Author names set _author = string try begin for pub in noaa_data_sorted at string Publication begin if string author in pub begin if pub at string author b...
def __create_author_investigator_str(self): """ When investigators is empty, try to get authors from the first publication instead. :return str author: Author names """ _author = "" try: for pub in self.noaa_data_sorted["Publication"]: if "auth...
Python
jtatman_500k
function parameter_bounds self begin set membership_mat = call asarray coefficients_mat set rhs_vec = rhs_vec set parameter_bounds = list for i in range shape at 1 begin set col = call column membership_mat i set ub = min list generator expression col at j * rhs_vec at j for j in range length rhs_vec set lb = 0 append...
def parameter_bounds(self): membership_mat = np.asarray(self.coefficients_mat) rhs_vec = self.rhs_vec parameter_bounds = [] for i in range(membership_mat.shape[1]): col = column(membership_mat, i) ub = min(list(col[j] * rhs_vec[j] for j in range(len(rhs_vec)))) ...
Python
nomic_cornstack_python_v1
function add_large_numbers string1 string2 begin comment Check if the numbers are negative set is_negative1 = string1 at 0 == string - set is_negative2 = string2 at 0 == string - comment Remove the negative sign if present if is_negative1 begin set string1 = string1 at slice 1 : : end if is_negative2 begin set string...
def add_large_numbers(string1, string2): # Check if the numbers are negative is_negative1 = string1[0] == "-" is_negative2 = string2[0] == "-" # Remove the negative sign if present if is_negative1: string1 = string1[1:] if is_negative2: string2 = string2[1:] # Make the numb...
Python
jtatman_500k
function get_model cls begin if model == none begin set graph = call get_default_graph comment with open(os.path.join(model_path, 'modelo_lstm.h5'), 'rb') as inp: print string carregando modelo em join path model_path string modelo_lstm.h5 set model = call load_model join path model_path string modelo_lstm.h5 end retur...
def get_model(cls): if cls.model == None: cls.graph = tf.get_default_graph() #with open(os.path.join(model_path, 'modelo_lstm.h5'), 'rb') as inp: print('carregando modelo em ', os.path.join(model_path, 'modelo_lstm.h5')) cls.model = load_model(os.path.jo...
Python
nomic_cornstack_python_v1
class Employee begin function __init__ self name salary role begin set name = name set salary = salary set role = role end function function __str__ self begin return string The name is { name } , salary is { salary } and role is { role } end function function __repr__ self begin return string Employee(' { name } ',' {...
class Employee: def __init__(self,name,salary,role): self.name=name self.salary=salary self.role=role def __str__(self): return f"The name is {self.name}, salary is {self.salary} and role is {self.role}" def __repr__(self): return f"Employee('{self.name}','{...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment encoding: utf-8 comment Programita 1
#! /usr/bin/env python # encoding: utf-8 # Programita 1
Python
zaydzuhri_stack_edu_python
function run self begin set counter = 0 comment Reporting frequency set counter_increment = 1000 set last_time = 0 if call get_param string record_queue_state begin comment Add event to query queue state. set query_interval = 1 set report_queue_state = call RecordQueueState servers stats_manager query_interval put tupl...
def run(self): counter = 0 counter_increment = 1000 # Reporting frequency last_time = 0 if get_param("record_queue_state"): # Add event to query queue state. query_interval = 1 report_queue_state = RecordQueueState(self.servers, ...
Python
nomic_cornstack_python_v1
import pdb from models.album import Album from models.artist import Artist import repositories.album_repository as album_repository import repositories.artist_repository as artist_repository import os call system string psql -d music_collection -f db/music_collection.sql set artist1 = call Artist string Ozzy set artist...
import pdb from models.album import Album from models.artist import Artist import repositories.album_repository as album_repository import repositories.artist_repository as artist_repository import os os.system('psql -d music_collection -f db/music_collection.sql') artist1 = Artist('Ozzy') artist2 = Artist('Imagin...
Python
zaydzuhri_stack_edu_python
function onSwitchHotSeatPlayer self argsList begin set ePlayer = argsList at 0 end function
def onSwitchHotSeatPlayer(self, argsList): ePlayer = argsList[0]
Python
nomic_cornstack_python_v1
class Name begin function name_func self begin print string My name is { name } end function end class set miah = call Name set name = string Dulal call name_func
class Name : def name_func(self): print(f"My name is {self.name}") miah = Name() miah.name = 'Dulal' miah.name_func()
Python
zaydzuhri_stack_edu_python
comment Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a ...
#Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count o...
Python
zaydzuhri_stack_edu_python
import numpy as np comment from copy import deepcopy comment dont use that function basic_pso f S n bounds maxit w phi_p phi_g verbose begin comment basic particle swarm optimization (PSO) comment f is the function to minimize, f:R^n -> R comment S is the number of particle in the swarm comment n is the dimension of th...
import numpy as np # from copy import deepcopy #dont use that def basic_pso(f, S, n, bounds, maxit, w, phi_p, phi_g, verbose): # basic particle swarm optimization (PSO) # f is the function to minimize, f:R^n -> R # S is the number of particle in the swarm # n is the dimension of the search space # ...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string 逻辑回归 import pickle from django.core.cache import cache from sklearn.linear_model import LogisticRegression function logistic_regression label title begin string :param label: X 特征数据 :param title: Y 标示学习样本为 0 or 1 数据预测 clf.predict(data: list) liblinear 小量数据效果更好 sag or saga 适合大量数据 :return: set...
# coding=utf-8 """逻辑回归""" import pickle from django.core.cache import cache from sklearn.linear_model import LogisticRegression def logistic_regression(label: list, title: list): """ :param label: X 特征数据 :param title: Y 标示学习样本为 0 or 1 数据预测 clf.predict(data: list) liblinear 小量数据效果更好 sag or sag...
Python
zaydzuhri_stack_edu_python
function _compress_snapshots self begin set C_shape = tuple shape at 1 shape at 0 if compression_matrix is string uniform begin set C = uniform 0 1 size=C_shape end else if compression_matrix is string sparse begin set C = random *C_shape density=1.0 end else if compression_matrix is string normal begin set C = call no...
def _compress_snapshots(self): C_shape = (self._snapshots.shape[1], self._snapshots.shape[0]) if self.compression_matrix is 'uniform': C = np.random.uniform(0, 1, size=(C_shape)) elif self.compression_matrix is 'sparse': C = scipy.sparse.random(*C_shape, density=1.) elif self.compression_matrix is 'norm...
Python
nomic_cornstack_python_v1
import unittest set weed = list string white widow string orange bud string bubble kush set weed at 0 = string start set number = integer input string what do you want print weed at number input string hi class TestStringMethods extends TestCase begin function test_upper self begin assert equal upper string foo string ...
import unittest weed = ["white widow", "orange bud", "bubble kush"] weed[0] = "start" number =int(input("what do you want")) print(weed[number]) input("hi") class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FO')
Python
zaydzuhri_stack_edu_python
function projection_sphere k_array r=5 o=array list 0 0 1 begin comment Inputs: comment - k_array: ndarray, shape (n,3) comment - r: float/int comment - o: ndarray, shape (3,) comment Outputs: comment - p: ndarray, shape (n,3) set d = r / call mag k_array set D = T set p = o + k_array * D return p end function
def projection_sphere(k_array, r=5, o=np.array([0, 0, 1])): # Inputs: # - k_array: ndarray, shape (n,3) # - r: float/int # - o: ndarray, shape (3,) # # Outputs: # - p: ndarray, shape (n,3) d = r / lattices.mag(k_array) D = np.vstack((d, d, d)).T p = ...
Python
nomic_cornstack_python_v1
from __future__ import division import pandas as pd import numpy as np import math class ItemCF extends object begin function __init__ self method=string base alpha=0.6 normalized=false begin string @function: 算法参数初始化 @param: method {string} 相似度计算方法 {“base”,"iuf","harryPotter"} alpha harryPotter方法的参数 参数范围 [0,1] normali...
from __future__ import division import pandas as pd import numpy as np import math class ItemCF(object): def __init__(self, method="base", alpha=0.6,normalized=False): """ @function: 算法参数初始化 @param: method {string} 相似度计算方法 {“base”,"iuf","harryPotter"} alpha harr...
Python
zaydzuhri_stack_edu_python
function set_due_date self new_due_date begin set order_due_date = new_due_date save end function
def set_due_date(self, new_due_date): self.order_due_date = new_due_date self.save()
Python
nomic_cornstack_python_v1
function test_metric_angle_between_lines self begin set tuple x1 y1 = call symbols string x1 y1 real=true set P0 = call point 0 0 0 set P1 = call point x1 y1 0 set P2 = call point - y1 x1 0 comment TODO: this feels weird... but ganja does the same set l0 = call Jinv call J P0 ? call J P1 set l1 = call Jinv call J P2 ? ...
def test_metric_angle_between_lines(self): x1, y1 = symbols('x1 y1', real=True) P0 = self.point(0, 0, 0) P1 = self.point(x1, y1, 0) P2 = self.point(-y1, x1, 0) l0 = Jinv(J(P0) ^ J(P1)) # TODO: this feels weird... but ganja does the same l1 = Jinv(J(P2) ^ J(P0)) # ...
Python
nomic_cornstack_python_v1
string 旅馆预订系统,写程序,烙印,要自己设计几个类,和预定,删除,和给出一天,返回空房树,不难, 但很多不确定的,烙印也不给力,想他确认,他就说你看怎么好。 comment not enough time to prepare, but share some thoughts
''' 旅馆预订系统,写程序,烙印,要自己设计几个类,和预定,删除,和给出一天,返回空房树,不难, 但很多不确定的,烙印也不给力,想他确认,他就说你看怎么好。 ''' # not enough time to prepare, but share some thoughts
Python
zaydzuhri_stack_edu_python
function get_available_shipping_methods self begin return list comprehension m for m in call available shop=shop products=product_ids if call is_available_for self end function
def get_available_shipping_methods(self): return [ m for m in ShippingMethod.objects.available(shop=self.shop, products=self.product_ids) if m.is_available_for(self) ]
Python
nomic_cornstack_python_v1
import math from collections import defaultdict from collections.abc import Sequence from functools import cache from typing import Any , Iterable from misc.Tester import FastDijkstra , State from solver import Clue , Clues , ConstraintSolver , generators from solver.constraint_solver import Constraint from solver.gene...
import math from collections import defaultdict from collections.abc import Sequence from functools import cache from typing import Any, Iterable from misc.Tester import FastDijkstra, State from solver import Clue, Clues, ConstraintSolver, generators from solver.constraint_solver import Constraint from solver.generato...
Python
zaydzuhri_stack_edu_python
function make_file cus shop count begin set cus_file_name = string d:/cus_ + string count + string .txt set shop_file_name = string d:/shop_ + string count + string .txt set cus_file = open cus_file_name string w set shop_file = open shop_file_name string w write lines cus_file cus write lines shop_file shop close cus_...
def make_file(cus ,shop ,count): cus_file_name = 'd:/cus_'+str(count)+'.txt' shop_file_name = 'd:/shop_'+str(count)+'.txt' cus_file = open(cus_file_name , 'w') shop_file = open(shop_file_name , 'w') cus_file.writelines(cus) shop_file.writelines(shop) cus_file.close() shop_file.close() ...
Python
zaydzuhri_stack_edu_python
import random set l = integer input string Enter the length of motif set file = open string mot.txt string r set r = read file print string Sequence r set size = length r print string Size of the sequence size set pos = random integer 0 length r - 5 comment pos=1 print string Position pos set motif = r at slice pos : p...
import random l=int(input("Enter the length of motif")) file=open("mot.txt","r") r=file.read() print("Sequence",r) size=len(r) print("Size of the sequence",size) pos=random.randint(0,len(r)-5) #pos=1 print("Position",pos) motif=r[pos:pos+l] print("Motif",motif) i=pos+1 while(i<=size-1): if(motif...
Python
zaydzuhri_stack_edu_python
function submit_job self workflow job_params begin comment type: (Union[Workflow, Dict[str, Any]], Dict[str, Any]) -> Job set submit_url = format string {}/{} __base_url url_suffix set data = dict string job job_params ; string workflow if expression is instance workflow Workflow then call serialize else workflow set r...
def submit_job(self, workflow, job_params): # type: (Union[Workflow, Dict[str, Any]], Dict[str, Any]) -> Job submit_url = '{}/{}'.format(self.__base_url, Job.url_suffix) data = { 'job': job_params, 'workflow': workflow.serialize() if isinstance(workflow, Workflow) else wo...
Python
nomic_cornstack_python_v1