code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function setUp self begin set task = call Task dl end function
def setUp(self): self.task = dl.Task(self.dl)
Python
nomic_cornstack_python_v1
function _get_l2_reg self begin set loss = 0 for param in parameters model begin set loss = loss + sum end return loss end function
def _get_l2_reg(self) -> torch.Tensor: loss = 0 for param in self.model.parameters(): loss += (param ** 2).sum() return loss
Python
nomic_cornstack_python_v1
function test_5_1_5_cron_weekly_user host begin assert user == string root end function
def test_5_1_5_cron_weekly_user(host): assert host.file(CRON_WEEKLY).user == 'root'
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*-coding:utf8-*- comment __author__ = "willian" set data = range 1 4300000000 function binary_search find_str data count begin set count = count + 1 print count set mid = integer length data / 2 comment data只有一个值的时候. if mid == 0 begin if data at mid == find_str begin print string f...
#!/usr/bin/env python # -*-coding:utf8-*- # __author__ = "willian" data = range(1, 4300000000) def binary_search(find_str, data, count): count += 1 print(count) mid = int(len(data)/2) if mid == 0: # data只有一个值的时候. if data[mid] == find_str: print("find it", find_str) else...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import visual_model import word_to_vec import utils set image_repesentation_size = 150 set word_embedding_size = 200 set visual_model_checkpoints_dir = string v_saved_model/ set devise_model_checkpoints_dir = string devise_saved_model/ set word2vec_saved_dir = string word2vec_...
import tensorflow as tf import numpy as np import visual_model import word_to_vec import utils image_repesentation_size = 150 word_embedding_size = 200 visual_model_checkpoints_dir = 'v_saved_model/' devise_model_checkpoints_dir = 'devise_saved_model/' word2vec_saved_dir = 'word2vec_saved/text8model.model' show_every_...
Python
zaydzuhri_stack_edu_python
from customer import Customer class WholesaleCustomer extends Customer begin set amount_threshold = none set price = none set first_rate = none set second_rate = none comment contructor if the rate is mentioned function __init__ self ID name first_rate price begin call __init__ ID name comment default will be $1000 set...
from customer import Customer class WholesaleCustomer(Customer): amount_threshold = None price = None first_rate = None second_rate = None # contructor if the rate is mentioned def __init__(self, ID, name, first_rate, price): super().__init__(ID, name) self.amount_threshold = ...
Python
zaydzuhri_stack_edu_python
from collections import UserDict from random import shuffle , sample , random import pickle import json from common import round_up class WordlistFactory begin function __init__ self my_config begin set _my_config = my_config end function function new_by_wordlib self wordlist_name begin set wordlist = dict string wordl...
from collections import UserDict from random import shuffle, sample, random import pickle import json from .common import round_up class WordlistFactory: def __init__(self, my_config): self._my_config = my_config def new_by_wordlib(self, wordlist_name): wordlist = { "wordlist_pat...
Python
zaydzuhri_stack_edu_python
comment https://leetcode.com/problems/unique-morse-code-words/ class Solution begin set alphabet = list string .- string -... string -.-. string -.. string . string ..-. string --. string .... string .. string .--- string -.- string .-.. string -- string -. string --- string .--. string --.- string .-. string ... strin...
# https://leetcode.com/problems/unique-morse-code-words/ class Solution: alphabet = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] def uniqueMorseRepresentations(self, words: List[str]) ...
Python
zaydzuhri_stack_edu_python
function get_hunk_edited_type self begin return call getActionType end function
def get_hunk_edited_type(self): return Gumtree.gumtree.getActionType()
Python
nomic_cornstack_python_v1
function push self x begin call enqueue x set _size = size q1 while _size > 1 begin call enqueue call dequeue set _size = _size - 1 end end function
def push(self, x: int) -> None: self.q1.enqueue(x) _size = self.q1.size() while _size > 1: self.q1.enqueue(self.q1.dequeue()) _size -= 1
Python
nomic_cornstack_python_v1
function set_requires_grad nets requires_grad=false begin if not is instance nets list begin set nets = list nets end for net in nets begin if net is not none begin for param in parameters net begin set requires_grad = requires_grad end end end end function
def set_requires_grad(nets, requires_grad=False): if not isinstance(nets, list): nets = [nets] for net in nets: if net is not None: for param in net.parameters(): param.requires_grad = requires_grad
Python
nomic_cornstack_python_v1
function scipyTranform self s begin set l = length s set wo = 2 * pi / l set a = 2 / call quad cos n * wo * t t - inf inf set b = 2 / call quad sin n * wo * t t - inf inf end function
def scipyTranform(self,s): l=len(s) wo=2*math.pi/l a=2/scipy.integrate.quad(math.cos(n*wo*t),t,-inf,inf) b=2/scipy.integrate.quad(math.sin(n*wo*t),t,-inf,inf)
Python
nomic_cornstack_python_v1
function deduce_summit peaks begin set id2summits = dict for peak in peaks begin if peak at - 1 not in id2summits begin set id2summits at peak at - 1 = list end append id2summits at peak at - 1 peak at - 2 end set singles = list for summits in values id2summits begin if length summits == 1 begin append singles summi...
def deduce_summit(peaks): id2summits = {} for peak in peaks: if peak[-1] not in id2summits: id2summits[peak[-1]] = [] id2summits[peak[-1]].append(peak[-2]) singles = [] for summits in id2summits.values(): if len(summits) == 1: singles.append(summits[0]) ...
Python
nomic_cornstack_python_v1
function get_steam_info bot trigger begin if not call group 2 begin return call reply string I need a game to look up! end set user_input = call parseargs lower call group 2 set query = get user_input string --query or user_input at string extra_text set region = get user_input string --region or string US set search_h...
def get_steam_info(bot, trigger): if not trigger.group(2): return bot.reply("I need a game to look up!") user_input = parseargs(trigger.group(2).lower()) query = user_input.get("--query") or user_input["extra_text"] region = user_input.get("--region") or "US" search_html = _fetch_search_...
Python
nomic_cornstack_python_v1
from operator import is_ from Utilities import is_prime , fib function main begin set prime_sum = 0 for i in range 2 * 10 ^ 6 begin if call is_prime i begin set prime_sum = prime_sum + i end end print prime_sum end function if __name__ == string __main__ begin call main end
from operator import is_ from Utilities import is_prime, fib def main(): prime_sum = 0 for i in range(2*10**6): if is_prime(i): prime_sum += i print(prime_sum) if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
function DistanceFromPenalty netParams what begin set sum = 0 set i = 0 for param in netParams begin if i % 2 == 0 begin set distance = what - absolute param set distance_squared = power distance 2 set sum = sum + sum distance_squared end set i = i + 1 end return sum end function
def DistanceFromPenalty(netParams, what): sum = 0 i = 0 for param in netParams: if (i % 2) == 0: distance = what-torch.abs(param) distance_squared = torch.pow(distance, 2) sum += torch.sum(distance_squared) i += 1 return sum
Python
nomic_cornstack_python_v1
function add_attachment self identifier path_to_attachment project_id filename=none bypass_rules=false supress_notifications=false begin debug string Adding attachment to { identifier } : { path_to_attachment } if filename is none begin set filename = base name path path_to_attachment end set filename = replace filenam...
def add_attachment( self, *, identifier: str, path_to_attachment: str, project_id: str, filename: Optional[str] = None, bypass_rules: bool = False, supress_notifications: bool = False, ) -> ADOResponse: self.log.debug(f"Adding attachment to {i...
Python
nomic_cornstack_python_v1
from random import choice from string import ascii_uppercase , digits class Robot begin set names = list function __init__ self begin set name = string while true begin set name = call compose_name if name not in names begin append names name break end end end function function compose_name self begin return string {...
from random import choice from string import ascii_uppercase, digits class Robot: names = [] def __init__(self): self.name = '' while True: self.name = self.compose_name() if self.name not in self.names: self.names.append(self.name) bre...
Python
zaydzuhri_stack_edu_python
string mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Ad...
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based ...
Python
zaydzuhri_stack_edu_python
import argparse from collections import Counter function word_list f begin comment cnt = Counter() set words = list comment lines = f.readlines() comment for line in lines: comment for i in line.split(): comment if len(i) < 3: comment continue set words = list comprehension i for line in read lines f for i in split li...
import argparse from collections import Counter def word_list(f): #cnt = Counter() words = [] #lines = f.readlines() #for line in lines: #for i in line.split(): #if len(i) < 3: #continue words = [i for line in f.readlines() for i ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment "sliding window"-like technique: sort the list, then comment adjust L: increase sum comment adjust R: decrease sum class Solution extends object begin function twoSum self nums target begin set nums = sorted enumerate nums key=lambda x -> x at 1 set tuple L R = tuple 0 length nums ...
#!/usr/bin/env python3 # "sliding window"-like technique: sort the list, then # adjust L: increase sum # adjust R: decrease sum class Solution(object): def twoSum(self, nums, target): nums = sorted(enumerate(nums), key=lambda x: x[1]) (L,R) = (0, len(nums)-1) while L<R: tmp = n...
Python
zaydzuhri_stack_edu_python
function test_escape_excluding_html self begin set escaped_content = call escape_markdown CONTENT escape_html=false set expected_content = string \# noqa: E501 from https://github.com/adam\-p/markdown\-here/wiki/Markdown\-Cheatsheet Headers \# H1 \#\# H2 \#\#\# H3 \#\#\#\# H4 \#\#\#\#\# H5 \#\#\#\#\#\# H6 Alternatively...
def test_escape_excluding_html(self): escaped_content = escape_markdown(self.CONTENT, escape_html=False) expected_content = ( r"""\# noqa: E501 """ r"""from https://github.com/adam\-p/markdown\-here/wiki/Markdown\-Cheatsheet """ r"""Headers \# H1 \#\# H2 \#\#\# H3 \#\...
Python
nomic_cornstack_python_v1
function setup begin comment digitalWrite(11, HIGH) pass end function function loop begin call delay 1000 call digitalWrite current HIGH call delay 1000 call digitalWrite current LOW set current = current + 1 if current > 13 begin set current = 11 end end function
def setup(): #digitalWrite(11, HIGH) pass def loop(): delay(1000) digitalWrite(current,HIGH) delay(1000) digitalWrite(current,LOW) current = current + 1 if current > 13: current = 11
Python
zaydzuhri_stack_edu_python
function _get_action self event begin comment default values to return set action = none set to_node = none set to_object = none set to_index = none set data = none set control = _controller comment Get the tree widget item under the cursor. set nid = call itemAt call pos if nid is none begin if hide_root begin set nid...
def _get_action(self, event): # default values to return action = None to_node = None to_object = None to_index = None data = None control = self._controller # Get the tree widget item under the cursor. nid = self.itemAt(event.pos()) if n...
Python
nomic_cornstack_python_v1
import requests import re import json from bs4 import BeautifulSoup from movies import MovieListing function get_top_1000_movie_links begin string Fetch a list of 'fullcredits' links for the top 1000 imdb movies. This makes several HTTP calls to imdb set movie_links = list for start in range 1 1000 50 begin set imdb_m...
import requests import re import json from bs4 import BeautifulSoup from movies import MovieListing def get_top_1000_movie_links(): """ Fetch a list of 'fullcredits' links for the top 1000 imdb movies. This makes several HTTP calls to imdb """ movie_links = [] for start in range (1, 1000, 50...
Python
zaydzuhri_stack_edu_python
function calc_channel_corr cube mask=none begin from scipy.stats import pearsonr if mask is none begin set mask = call include end set mask = mask ? call roll mask - 1 axis=0 set mask at tuple - 1 slice : : = false return pearson correlation filled_data at mask filled_data at call roll mask 1 axis=0 end function
def calc_channel_corr(cube, mask=None): from scipy.stats import pearsonr if mask is None: mask = cube.mask.include() mask &= np.roll(mask, -1, axis=0) mask[-1, :] = False return pearsonr(cube.filled_data[mask], cube.filled_data[np.roll(mask, 1, axis=0)])
Python
nomic_cornstack_python_v1
function notices_en request begin set notice_list = call order_by string published_date set context = dict string notice_list notice_list return call render request string sacms/notices_en.html context end function
def notices_en(request): notice_list = Notice.objects.order_by('published_date') context = {'notice_list': notice_list} return render(request, 'sacms/notices_en.html', context)
Python
nomic_cornstack_python_v1
function solve n k begin set MOD = 998244353 if n > k begin return 0 end if n == 1 begin return power 2 k - 1 MOD end set tuple pf kf = tuple 1 1 for m in range 2 k + 1 begin set pf = kf set kf = kf * m set kf = kf % MOD end set inv = power kf MOD - 2 MOD set invs = list 1 * k + 1 set invs at k = inv for m in range k 1...
def solve(n, k): MOD = 998244353 if n > k: return 0 if n == 1: return pow(2, k - 1, MOD) pf, kf = 1, 1 for m in range(2, k + 1): pf = kf kf *= m kf %= MOD inv = pow(kf, MOD - 2, MOD) invs = [1] * (k + 1) invs[k] = inv for m in range(k, 1, -1)...
Python
jtatman_500k
function evaluate_error_absolute poses_to_test poses_ground_truth begin set poses_ground_truth_as_dict = dictionary comprehension name : pose for tuple name pose in poses_ground_truth set result = list comprehension tuple name + call world_pose_transform_distance pose poses_ground_truth_as_dict at name for tuple name p...
def evaluate_error_absolute(poses_to_test: List[Tuple[str, kapture.PoseTransform]], poses_ground_truth: List[Tuple[str, kapture.PoseTransform]] ) -> List[Tuple[str, float, float]]: poses_ground_truth_as_dict = {name: pose for name, pose in poses_ground_truth} ...
Python
nomic_cornstack_python_v1
function info name object comment=string begin if filename and level in list string DEBUG string INFO begin log name object comment end end function
def info(name,object,comment=""): if filename and level in ["DEBUG","INFO"]: log(name,object,comment)
Python
nomic_cornstack_python_v1
function upload_mobileconfig self jamf_url mobileconfig_name description category mobileconfig_plist computergroup_name template_contents profile_uuid obj_id=0 enc_creds=string token=string begin comment remove newlines, tabs, leading spaces, and XML-escape the payload set mobileconfig_plist = decode mobileconfig_plis...
def upload_mobileconfig( self, jamf_url, mobileconfig_name, description, category, mobileconfig_plist, computergroup_name, template_contents, profile_uuid, obj_id=0, enc_creds="", token="", ): # remove newlines, ...
Python
nomic_cornstack_python_v1
comment [Backtracking] comment https://leetcode.com/problems/restore-ip-addresses/ comment 93. Restore IP Addresses comment History: comment Facebook comment 1. comment Mar 10, 2020 comment 2. comment May 12, 2020 comment Given a string containing only digits, restore it by returning all possible valid IP address comme...
# [Backtracking] # https://leetcode.com/problems/restore-ip-addresses/ # 93. Restore IP Addresses # History: # Facebook # 1. # Mar 10, 2020 # 2. # May 12, 2020 # Given a string containing only digits, restore it by returning all possible valid IP address # combinations. # # A valid IP address consists of exactly four...
Python
zaydzuhri_stack_edu_python
comment Image Uploaded Now run python script comment importing libraries import numpy as np import os import cv2 import face_recognition import sys import shutil comment Delete files in filtered images if not empty set filter_images = string data/filter_images for filename_4 in list directory filter_images begin remove...
#Image Uploaded Now run python script #importing libraries import numpy as np import os import cv2 import face_recognition import sys import shutil #Delete files in filtered images if not empty filter_images = r'data/filter_images' for filename_4 in os.listdir(filter_images): os.remove(os.path.join(filter_images,...
Python
zaydzuhri_stack_edu_python
function render_page graphics_state local_state global_state pre=list post=list begin call clear_all for func in pre begin call func end call render_default_graphics graphics_state local_state global_state for func in post begin call func end end function
def render_page(graphics_state, local_state, global_state, pre=[], post=[]): graphics_state.clear_all() for func in pre: func() render_default_graphics(graphics_state, local_state, global_state) for func in post: func()
Python
nomic_cornstack_python_v1
function read_map self map_name begin set map_dir = join path string maps\\ map_name + string .csv comment Reading game_map type file set df = read csv map_dir index_col=false comment Retrieve game objects and settings for map, indexing by column name comment The concatenation of different length DataFrames result in N...
def read_map(self, map_name: str): map_dir = os.path.join(r'maps\\', (map_name + '.csv')) # Reading game_map type file df = pd.read_csv(map_dir, index_col=False) # Retrieve game objects and settings for map, indexing by column name # The concatenation of different length DataFra...
Python
nomic_cornstack_python_v1
function data_to_binary self begin string :return: bytes set tmp = 0 if 1 in channels begin set tmp = tmp + 3 end if 2 in channels begin set tmp = tmp + 12 end return bytes list COMMAND_CODE tmp end function
def data_to_binary(self): """ :return: bytes """ tmp = 0x00 if 1 in self.channels: tmp += 0x03 if 2 in self.channels: tmp += 0x0c return bytes([COMMAND_CODE, tmp])
Python
jtatman_500k
comment -*- coding: utf-8 -*- string Задание 22.2c Скопировать класс CiscoTelnet из задания 22.2b и изменить метод send_config_commands добавив проверку команд на ошибки. У метода send_config_commands должен быть дополнительный параметр strict: * strict=True значит, что при обнаружении ошибки, необходимо сгенерировать ...
# -*- coding: utf-8 -*- """ Задание 22.2c Скопировать класс CiscoTelnet из задания 22.2b и изменить метод send_config_commands добавив проверку команд на ошибки. У метода send_config_commands должен быть дополнительный параметр strict: * strict=True значит, что при обнаружении ошибки, необходимо сгенерировать искл...
Python
zaydzuhri_stack_edu_python
function get_epoch self begin return second end function
def get_epoch(self) -> int: return self.planting_time.second
Python
nomic_cornstack_python_v1
function wait self timeout=none endtime=none begin if endtime is not none begin set timeout = call _remaining_time endtime end if timeout is none begin set timeout_millis = INFINITE end else begin set timeout_millis = integer timeout * 1000 end if returncode is none begin set result = call WaitForSingleObject _handle t...
def wait(self, timeout=None, endtime=None): if endtime is not None: timeout = self._remaining_time(endtime) if timeout is None: timeout_millis = _winapi.INFINITE else: timeout_millis = int(timeout * 1000) if self.returncode ...
Python
nomic_cornstack_python_v1
import win32api import win32con try begin call ShellExecute 0 string open string notepad.exe string string SW_SHOWNORMAL end except Exception as e begin print string An error occurred: { e } end comment 1. Wrapped the ShellExecute function in a try-except block. comment 2. Used win32con constant for the show command....
import win32api import win32con try: win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', win32con.SW_SHOWNORMAL) except Exception as e: print(f'An error occurred: {e}') # 1. Wrapped the ShellExecute function in a try-except block. # 2. Used win32con constant for the show command. # Executing code.
Python
flytech_python_25k
function absPath path begin return join path directory name path absolute path path __file__ path end function
def absPath(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
Python
nomic_cornstack_python_v1
string Program to count the characters lines and words function main begin set file1 = strip input string Enter a filename: set readfile = open file1 string r set stringFile = read readfile set word = split stringFile set sum1 = 0 for i in word begin set sum1 = sum1 + length i end print string sum1 + string characters ...
'''Program to count the characters lines and words''' def main(): file1 = input("Enter a filename: ").strip() readfile = open(file1, "r") stringFile = readfile.read() word=stringFile.split() sum1=0 for i in word: sum1+=len(i) print(str(sum1) + " characters") print(str(len...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf set matrix1 = call constant list list 3.0 3.0 set matrix2 = call constant list 3.0 3.0 set sess = call Session print matrix1 print run matrix1 print string ------------------------------- print matrix2 print run matrix2 print run add tf matrix1 matrix2
import tensorflow as tf matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([3., 3.]) sess = tf.Session() print(matrix1) print(sess.run(matrix1)) print("-------------------------------") print(matrix2) print(sess.run(matrix2)) print(sess.run(tf.add(matrix1, matrix2)))
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np function apply_threshold_with_denoising image begin set image = call adaptiveThreshold image 250 ADAPTIVE_THRESH_GAUSSIAN_C THRESH_BINARY 115 1 set image = call fastNlMeansDenoising image 1.5 5 5 return image end function function delete_small_components image size begin set tuple _ blackA...
import cv2 import numpy as np def apply_threshold_with_denoising(image): image = cv2.adaptiveThreshold(image, 250, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) image = cv2.fastNlMeansDenoising(image, 1.5, 5, 5) return image def delete_small_components(image, size): _, blackAndWhite = c...
Python
zaydzuhri_stack_edu_python
import pygame import sys import numpy from snake import Snake from food import Food from config import * from scipy.spatial import distance class Game begin function __init__ self begin call init end function function up_score self begin set score = score + 1 end function function reset self display size=tuple SCREEN_W...
import pygame import sys import numpy from snake import Snake from food import Food from config import * from scipy.spatial import distance class Game(): def __init__(self): pygame.init() def up_score(self): self.score += 1 def reset(self, display, size=(SCREEN_WIDTH, SCREEN_HEIGHT)): ...
Python
zaydzuhri_stack_edu_python
import scrapy import json class LoginSpider extends Spider begin set name = string google.com set start_urls = list string https://www.google.com.tw/?gws_rd=ssl function parse self response begin return call from_response response formdata=dict string q string python callback=after_login end function function after_log...
import scrapy import json class LoginSpider(scrapy.Spider): name = 'google.com' start_urls = ['https://www.google.com.tw/?gws_rd=ssl'] def parse(self, response): return scrapy.FormRequest.from_response( response, formdata={'q': 'python'}, callback=self.after_l...
Python
zaydzuhri_stack_edu_python
for i in range 1000000 begin if i > 5678 begin break end print i end
for i in range(1000000): if i > 5678: break print(i)
Python
zaydzuhri_stack_edu_python
function start_gameloop self begin print string Game Loop starting... while true begin set current_turn = call who_goes_first print string The + current_turn + string will go first. while is_active begin if current_turn == string player begin call draw set move = call get_player_move positions is_position_availible cal...
def start_gameloop(self): print("Game Loop starting...") while True: current_turn = self.who_goes_first() print('The ' + current_turn + ' will go first.') while self.is_active: if current_turn == "player": self.board.draw() ...
Python
nomic_cornstack_python_v1
class Solution begin function Add self num1 num2 begin comment write code here set sum = 0 set carry = 0 while num2 begin set sum = num1 ? num2 set carry = num1 ? num2 ? 1 set tuple num1 num2 = tuple sum carry print num1 num2 end return num1 end function end class print add call Solution 5 17 print add call Solution 5 ...
class Solution: def Add(self, num1, num2): # write code here sum = 0 carry = 0 while num2: sum = num1 ^ num2 carry = (num1 & num2) << 1 num1, num2 = sum, carry print(num1, num2) return num1 print(Solution().Add(5, 17)) print(Sol...
Python
zaydzuhri_stack_edu_python
comment while True: comment pizza = input('Enter:') comment if pizza == 'quit': comment break comment else: comment print(f'ok,we will take {pizza}') comment active = True comment while active: comment pizza = input('Enter:') comment if pizza == 'quit': comment active = False comment else: comment print(f'ok,we will ta...
# while True: # pizza = input('Enter:') # if pizza == 'quit': # break # else: # print(f'ok,we will take {pizza}') # active = True # while active: # pizza = input('Enter:') # if pizza == 'quit': # active = False # else: # print(f'ok,we will take {pizza}') # whi...
Python
zaydzuhri_stack_edu_python
import sys set input = readline import bisect function solve num_list begin comment print(num_list) set dp = list for num in num_list begin set idx = call bisect_left dp num if length dp <= idx begin append dp num end else begin set dp at idx = num end end return length dp end function if __name__ == string __main__ b...
import sys input = sys.stdin.readline import bisect def solve(num_list): # print(num_list) dp = [] for num in num_list: idx = bisect.bisect_left(dp, num) if len(dp) <= idx: dp.append(num) else: dp[idx] = num return len(dp) if __name__ == '__main__': ...
Python
zaydzuhri_stack_edu_python
function __eq__ self *args begin pass end function
def __eq__(self,*args): pass
Python
nomic_cornstack_python_v1
function to_dict self begin set _dict = dict if has attribute self string status and status is not none begin set _dict at string status = status end if has attribute self string flags and flags is not none begin set _dict at string flags = flags end if has attribute self string algorithm and algorithm is not none beg...
def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'flags') and self.flags is not None: _dict['flags'] = self.flags if hasattr(self, 'algorithm') and self.algorithm is not No...
Python
nomic_cornstack_python_v1
function compute_predictor model img save_path=string . begin set cfg = cfg comment model device set device = device comment build the data pipeline set test_pipeline = list call LoadImage + pipeline at slice 1 : : set test_pipeline = call Compose test_pipeline comment prepare data set data = dictionary img=img set d...
def compute_predictor(model, img, save_path='.'): cfg = model.cfg device = next(model.parameters()).device # model device # build the data pipeline test_pipeline = [LoadImage()] + cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) # prepare data data = dict(img=img) data ...
Python
nomic_cornstack_python_v1
function get_MVZ self user_info begin set query = string exec payment.get_MVZ @UserID = ?, @AccessType = ?, @isSuperUser = ? execute __cursor query UserID AccessType isSuperUser return call fetchall end function
def get_MVZ(self, user_info): query = ''' exec payment.get_MVZ @UserID = ?, @AccessType = ?, @isSuperUser = ? ''' self.__cursor.execute(query, user_info.UserID, user_info.AccessType, user_info.isSuper...
Python
nomic_cornstack_python_v1
comment encoding = utf8 import pymysql comment mysql工具类 class PymysqlUtil begin comment 初始化方法 function __init__ self host port user passwd dbName charsets begin set host = host set port = port set user = user set passwd = passwd set dbName = dbName set charsets = charsets end function comment 链接数据库 function getCon self...
# encoding = utf8 import pymysql # mysql工具类 class PymysqlUtil(): # 初始化方法 def __init__(self, host, port, user, passwd, dbName, charsets): self.host = host self.port = port self.user = user self.passwd = passwd self.dbName = dbName self.charsets = charsets # ...
Python
zaydzuhri_stack_edu_python
import pygame import networkx as nx import random import time import heapq try begin call init end except any begin print string Erro. Programa não inicializado end set WIDTH = 500 set HEIGHT = 600 set FPS = 30 set tela = call set_mode tuple WIDTH HEIGHT call set_caption string MazegenPRIM comment Define colours set WH...
import pygame import networkx as nx import random import time import heapq try: pygame.init() except: print("Erro. Programa não inicializado") WIDTH = 500 HEIGHT = 600 FPS = 30 tela = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption ("MazegenPRIM") # Define colours WHITE = (255, 255...
Python
zaydzuhri_stack_edu_python
function generative_parameters self begin raise NotImplementedError end function
def generative_parameters(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
function intersect lista listb begin set listinter = list set tuple lena lenb = tuple length lista length listb set tuple idxa idxb = tuple 0 0 while idxa < lena and idxb < lenb begin if lista at idxa == listb at idxb begin append listinter lista at idxa set idxa = idxa + 1 set idxb = idxb + 1 end else if lista at idx...
def intersect(lista, listb): listinter = [] lena, lenb = len(lista), len(listb) idxa, idxb = 0, 0 while idxa < lena and idxb < lenb: if lista[idxa] == listb[idxb]: listinter.append(lista[idxa]) idxa += 1 idxb += 1 elif lista[idxa] < listb[idxb]: ...
Python
zaydzuhri_stack_edu_python
import sys import argparse function parse_data data begin set wires = dict for line in data begin set wire = split right strip line string -> set wires at wire at - 1 = split wire at 0 end return dictionary comprehension key : val for tuple key val in sorted items wires key=lambda ele -> ele at 0 end function function...
import sys import argparse def parse_data(data): wires = {} for line in data: wire = line.rstrip().split(" -> ") wires[wire[-1]] = wire[0].split() return {key: val for key, val in sorted(wires.items(), key = lambda ele: ele[0])} def part1(data): # data = {'x': ['123'], 'y': ['456'], '...
Python
zaydzuhri_stack_edu_python
function html_colorbullets begin comment A much better implementation, avoiding tables, is given comment here: http://www.eng.buffalo.edu/webguide/Bullet_Lists.html if length argv <= 1 begin call _usage_html_colorbullets exit 0 end set red_bullet = string bullet_red2.png set green_bullet = string bullet_green2.png comm...
def html_colorbullets(): # A much better implementation, avoiding tables, is given # here: http://www.eng.buffalo.edu/webguide/Bullet_Lists.html if len(sys.argv) <= 1: _usage_html_colorbullets() sys.exit(0) red_bullet = 'bullet_red2.png' green_bullet = 'bullet_green2.png' #red_b...
Python
nomic_cornstack_python_v1
import pandas as pd function get_shape dataset begin string Retorna una tupla con las dimensiones del DataFrame <dataset> set dt = call DataFrame dataset set shape = shape return shape end function function change_column_names dataset new_names begin string Retorna un DataFrame cuyas columnas han sido renombradas de ac...
import pandas as pd def get_shape(dataset): """Retorna una tupla con las dimensiones del DataFrame <dataset>""" dt=pd.DataFrame(dataset) shape = dt.shape return shape def change_column_names(dataset, new_names): """Retorna un DataFrame cuyas columnas han sido renombradas de acuerdo a los nombres p...
Python
zaydzuhri_stack_edu_python
function check_length phone_number begin if length phone_number == LEN begin return true end else begin return false end end function
def check_length(phone_number): if len(phone_number) == LEN: return True else: return False
Python
nomic_cornstack_python_v1
comment Transfer Learning Cats vs Dogs import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import InceptionV3 import numpy as np import matplotlib.pyplot as plt import os function get_data begin set _URL = string https://storage.googleapis.com/m...
#Transfer Learning Cats vs Dogs import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import InceptionV3 import numpy as np import matplotlib.pyplot as plt import os def get_data(): _URL = 'https://storage.googleapis.com/mledu-datasets/cats_an...
Python
zaydzuhri_stack_edu_python
function list_money_consumptions_by_person_reservation id_client id_reservation id_person_reservation begin set id_client = call validate_id_client id_client function list_money_consumptions_by_person_reservation_on_namespace id_current_client begin set tuple reservation person_reservation = call get_reservation_and_pe...
def list_money_consumptions_by_person_reservation(id_client, id_reservation, id_person_reservation): id_client = validate_id_client(id_client) def list_money_consumptions_by_person_reservation_on_namespace(id_current_client): reservation, person_reservation = get_reservation_and_person_reservation_on_n...
Python
nomic_cornstack_python_v1
function filter_send_tx tx_dict begin if not get tx_dict string signature false begin error string Error: send_tx not signed return end set str_timestamp = string %.8f % tx_dict at string timestamp set str_amount = string %.8f % decimal tx_dict at string amount comment Assemble tx list set data = list list str_timestam...
def filter_send_tx(tx_dict): if not tx_dict.get('signature', False): MANAGER.app_log.error("Error: send_tx not signed") return str_timestamp = '%.8f' % tx_dict['timestamp'] str_amount = '%.8f' % float(tx_dict['amount']) # Assemble tx list data = [[str_timestamp, tx_dict['address'],...
Python
nomic_cornstack_python_v1
function test_heterodyne_offset self begin set segments = list tuple fakedatastart fakedatastart + fakedataduration set fulloutdir = join path fakedatadir string heterodyne_output comment create par file with offset RA and dec set offsetpar = deep copy fakepulsarpar comment make sure name is consistent with par file se...
def test_heterodyne_offset(self): segments = [(self.fakedatastart, self.fakedatastart + self.fakedataduration)] fulloutdir = os.path.join(self.fakedatadir, "heterodyne_output") # create par file with offset RA and dec offsetpar = copy.deepcopy(self.fakepulsarpar) offsetpar["P...
Python
nomic_cornstack_python_v1
function get_imatrix2d self slice=1 split_quads_to_triangles=false ignore_inactive=false return_elements=false begin set layer = slice if slice == call getNumberOfSlices begin set layer = layer - 1 end if slice > call getNumberOfSlices or slice <= 0 begin raise call ValueError string slice number out of range. end set ...
def get_imatrix2d(self, slice=1, split_quads_to_triangles=False, ignore_inactive=False, return_elements=False): layer = slice if slice == self.doc.getNumberOfSlices(): layer -= 1 if slice > self.doc.getNumberOfSlices() or slice <= 0: raise ValueError("slice number out of ...
Python
nomic_cornstack_python_v1
set n = integer input if n ? n - 1 == 0 begin print 1 end else begin set a = string binary n print count a string 1 end
n = int(input()) if((n & n-1)==0): print(1) else: a = str(bin(n)) print(a.count('1'))
Python
zaydzuhri_stack_edu_python
function write_configuration creator creator_version default_values required_values filename=none begin set tuple default_config required_config = call get_default_configuration update default_config default_values update required_config required_values set printdict = dict string prog creator ; string version creator_...
def write_configuration(creator, creator_version, default_values, required_values, filename=None): default_config, required_config = get_default_configuration() default_config.update(default_values) required_config.update(required_values) printdict = {"prog":creator, "version": creator_version} prin...
Python
nomic_cornstack_python_v1
set valid_input = false while not valid_input begin set age = input string Please enter your age: if is digit age begin set age = integer age set valid_input = true end else begin print string Invalid input! Please enter a valid integer. end end print string Your age is age
valid_input = False while not valid_input: age = input("Please enter your age: ") if age.isdigit(): age = int(age) valid_input = True else: print("Invalid input! Please enter a valid integer.") print("Your age is", age)
Python
greatdarklord_python_dataset
import csv function team_splitter experienced_players inexperienced_players begin string Takes a list of experienced players and a list of inexperienced players and divides them up in round-robin fashion and returns a list of players for each team. function assign_team players begin try begin global last_added if last_...
import csv def team_splitter(experienced_players, inexperienced_players): '''Takes a list of experienced players and a list of inexperienced players and divides them up in round-robin fashion and returns a list of players for each team. ''' def assign_team(players): try: ...
Python
zaydzuhri_stack_edu_python
import requests import simplejson as json import PIL from PIL import Image import os comment f = open("./scraping.json", "w+") if is file path string ./scraping.json and st_size != 0 begin set old_file1 = open string ./scraping.json string r+ set data = loads read old_file1 print string Current name is: data at string ...
import requests import simplejson as json import PIL from PIL import Image import os ##f = open("./scraping.json", "w+") if os.path.isfile("./scraping.json") and os.stat("./scraping.json").st_size != 0: old_file1 = open("./scraping.json", "r+") data = json.loads(old_file1.read()) print('Current name is: '...
Python
zaydzuhri_stack_edu_python
import numpy as np function get_instruction l begin set l = split l string if l at 0 == string turn begin set l at 0 = l at 0 + pop l 1 if l at 0 == string turnon begin set command = 1 end else begin set command = 0 end end else begin comment Toggle set command = 2 end set list x0 y0 = split l at 1 string , set list x1...
import numpy as np def get_instruction(l): l = l.split(" ") if l[0]=="turn": l[0] += l.pop(1) if l[0]=="turnon": command=1 else: command=0 else: command=2 # Toggle [x0, y0] = l[1].split(',') [x1, y1] = l[3].split(',') return command, int...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- comment DA+Nils 2018 comment Andrei + Z.TANG + Bowen, 2019 string Lab2: Breaking Ciphers Pwntool client for python3 Install: see install.sh Documentation: https://python3-pwntools.readthedocs.io/en/latest/ Sol1: The plaintext is the story of the Little Red Cap str...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # DA+Nils 2018 # Andrei + Z.TANG + Bowen, 2019 """ Lab2: Breaking Ciphers Pwntool client for python3 Install: see install.sh Documentation: https://python3-pwntools.readthedocs.io/en/latest/ Sol1: The plaintext is the story of the Little Red Cap """ """ Sumedha 1002876 "...
Python
zaydzuhri_stack_edu_python
function update_note self drawer id model custom_headers=none raw=false **operation_config begin comment Construct URL set url = string /v1/content/notes/{drawer}/{id} set path_format_arguments = dict string drawer call url string drawer drawer string int ; string id call url string id id string int set url = call form...
def update_note( self, drawer, id, model, custom_headers=None, raw=False, **operation_config): # Construct URL url = '/v1/content/notes/{drawer}/{id}' path_format_arguments = { 'drawer': self._serialize.url("drawer", drawer, 'int'), 'id': self._serialize.url("...
Python
nomic_cornstack_python_v1
function mo_type self mo_type begin set _mo_type = mo_type end function
def mo_type(self, mo_type): self._mo_type = mo_type
Python
nomic_cornstack_python_v1
function get_tags x begin set poster = x at string _source at string user at string id for user in x at string _source at string users_in_photo begin if user at string user at string id != poster begin yield tuple poster user at string user at string id end end end function
def get_tags(x): poster = x['_source']['user']['id'] for user in x['_source']['users_in_photo']: if user['user']['id'] != poster: yield (poster, user['user']['id'])
Python
nomic_cornstack_python_v1
import threading from FileManager import FileController from ConsensusManager import MerkleTree import hashlib class BlockThread extends Thread begin function __init__ self p_thrd_id p_thrd_name p_block begin string :param p_thrd_id: :param p_thrd_name: :param p_block: call __init__ self set thrd_id = p_thrd_id set thr...
import threading from FileManager import FileController from ConsensusManager import MerkleTree import hashlib class BlockThread(threading.Thread): def __init__(self, p_thrd_id, p_thrd_name, p_block): """ :param p_thrd_id: :param p_thrd_name: :param p_block: """ th...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class focal_loss extends Module begin function __init__ self alpha=0.25 gamma=2 num_classes=2 size_average=true begin string focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class focal_loss(nn.Module): def __init__(self, alpha=0.25, gamma=2, num_classes=2, size_average=True): """ focal_loss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :par...
Python
zaydzuhri_stack_edu_python
function atPodium self sparseOK=false one_mOK=false begin set pos = call getPos set ok = pos == GANG_ON_PODIUM or pos == GANG_AT_DENSE if sparseOK begin set ok = ok or pos == GANG_AT_SPARSE end if one_mOK begin set ok = ok or pos == GANG_AT_1M end return ok end function
def atPodium(self, sparseOK=False, one_mOK=False): pos = self.getPos() ok = (pos == self.GANG_ON_PODIUM) or (pos == self.GANG_AT_DENSE) if sparseOK: ok = ok or (pos == self.GANG_AT_SPARSE) if one_mOK: ok = ok or (pos == self.GANG_AT_1M) return ok
Python
nomic_cornstack_python_v1
function delete self handle begin call LogCommand set tclcode = string stc::delete + handle set result = exec tclcode debug string - Python result - + string result return result end function
def delete(self, handle): self.LogCommand() tclcode = "stc::delete " + handle result = self.Exec(tclcode) logging.debug(" - Python result - " + str(result)) return result
Python
nomic_cornstack_python_v1
string 4 hello 2 ll 4-2 = 2 class Solution extends object begin function strStr self haystack needle begin if length needle == 0 begin return 0 end for i in range length haystack - length needle + 1 begin comment Might have found a needle if haystack at i == needle at 0 begin for j in range length needle begin if hayst...
""" 4 hello 2 ll 4-2 = 2 """ class Solution(object): def strStr(self, haystack, needle): if len(needle) == 0: return 0 for i in range((len(haystack) - len(needle) + 1)): # Might have found a needle if haystack[i] == needle[0]: for j in range(len...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string Given: Positive integers n and k such that 100>=n>0100>=n>0 and 10>=k>010>=k>0. Return: The total number of partial permutations P(n,k)P, modulo 1,000,000. import sys import math set n = integer argv at 1 set k = integer argv at 2 print integer call factorial n / call factorial n - ...
#!/usr/bin/env python3 ''' Given: Positive integers n and k such that 100>=n>0100>=n>0 and 10>=k>010>=k>0. Return: The total number of partial permutations P(n,k)P, modulo 1,000,000. ''' import sys import math n = int(sys.argv[1]) k = int(sys.argv[2]) print(int(math.factorial(n)/(math.factorial(n-k)) % 1000000))
Python
zaydzuhri_stack_edu_python
function stopped self begin return _stopped end function
def stopped(self): return self._stopped
Python
nomic_cornstack_python_v1
function plot_dstats Gvel Utemp Vtemp InputV ddiv dcrl dshr spath ts begin set f = figure figsize=list 9 3 comment dtarg = dt.datetime(2015,1,1) comment t_p1 = B1.condy.get_index(dtarg) comment t_p2 = B2.condy.get_index(dtarg) comment t_p3 = B3.condy.get_index(dtarg) set vlim = 0.4 set a_no = 30 comment a_sc = 3.9e-1 c...
def plot_dstats(Gvel,Utemp,Vtemp,InputV,ddiv,dcrl,dshr,spath,ts): f = plt.figure(figsize=[9,3]) # dtarg = dt.datetime(2015,1,1) # t_p1 = B1.condy.get_index(dtarg) # t_p2 = B2.condy.get_index(dtarg) # t_p3 = B3.condy.get_index(dtarg) vlim = 0.4 a_no = 30 # a_sc = 3.9e-1 # a_sc = 2*np....
Python
nomic_cornstack_python_v1
function test_trees_with_non_timestamp_root self begin info string Testing datageneration with non-timestamp roots set cols = list append cols call VarcharCol c_p_t=dict string asad 0.6 ; string hari 0.4 name=string UserName position=1 level=0 is_root=string Yes parents=none parentscount=none append cols call VarcharC...
def test_trees_with_non_timestamp_root(self): logger.info("Testing datageneration with non-timestamp roots") cols = [] cols.append(VarcharCol(c_p_t={"asad":0.6,"hari":0.4}, name="UserName", position=1, leve...
Python
nomic_cornstack_python_v1
function query_store_retention self begin return get pulumi self string query_store_retention end function
def query_store_retention(self) -> pulumi.Output[Optional[int]]: return pulumi.get(self, "query_store_retention")
Python
nomic_cornstack_python_v1
while percent >= 21 begin print string Не правильное число set percent = integer input string Ведите число от 0 до 20: end if percent == 1 begin print percent string процент end else if 1 < percent < 5 begin print percent string процента end else if percent >= 5 and percent <= 20 or percent == 0 begin print percent str...
while percent >= 21: print('Не правильное число') percent = int(input('Ведите число от 0 до 20: ')) if percent == 1: print(percent, 'процент') elif 1 < percent < 5: print(percent, 'процента') elif percent >= 5 and percent <= 20 or percent == 0: print(percent, 'процентов')
Python
zaydzuhri_stack_edu_python
class Solution begin function factorial self a begin set fact = 1 for i in range 1 a + 1 begin set fact = fact * i end return fact end function function climbStairs self n begin if n < 1 begin return 0 end set steps_1 = n % 2 set steps_2 = n // 2 set count_ways = 1 while steps_2 > 0 begin set count_ways = count_ways + ...
class Solution: def factorial(self, a): fact = 1 for i in range(1,a+1): fact = fact * i return fact def climbStairs(self, n: int) -> int: if n<1: return 0 steps_1 = n%2 steps_2 = n//2 count_ways=1 while (step...
Python
zaydzuhri_stack_edu_python
if absolute b - a % 2 == 0 begin print string Alice end else if absolute b - a % 2 == 1 begin print string Borys end
if abs(b - a) % 2 == 0: print("Alice") elif abs(b - a) % 2 == 1: print("Borys")
Python
zaydzuhri_stack_edu_python
function __get_headers self passed_headers begin comment User-Agent for HTTP request set library_details = list string requests { __version__ } string python { call python_version } string connector { __name__ } set library_details = join string ; library_details set user_agent = string Infermedica-API-Python { __versi...
def __get_headers(self, passed_headers: Dict) -> Dict: # User-Agent for HTTP request library_details = [ f"requests {requests.__version__}", f"python {platform.python_version()}", f"connector {self.__class__.__name__}", ] library_details = "; ".join(l...
Python
nomic_cornstack_python_v1
string Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Input: "aeiou" Output: "" Note: S consists of lowercase English letters only. 1 <= S.length <= 1000 class Solution extends o...
''' Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Input: "aeiou" Output: "" Note: S consists of lowercase English letters only. 1 <= S.length <= 1000 ''' class Soluti...
Python
zaydzuhri_stack_edu_python
import time import datetime as dt function to_dtutc current_time begin string Convert the timeStamp type to datetime with local UTC. Arguments: - current_time: Pandas timeStamp, the time to be converted Returns: - datetime.datetime, converted time format return call to_pydatetime end function function to_unix_timestamp...
import time import datetime as dt def to_dtutc(current_time): """ Convert the timeStamp type to datetime with local UTC. Arguments: - current_time: Pandas timeStamp, the time to be converted Returns: - datetime.datetime, converted time format """ return current_time.to_pydatetime() ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Aug 26 15:37:28 2017 @author: Yuki import numpy as np function evaluate_Tc zeros target begin string Description: Evaluate Tc by calculating the zero resistivity area from 'zeros'. Parameters: zeros: zero resistivity points (np.array) target:zero resistivity points + ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 26 15:37:28 2017 @author: Yuki """ import numpy as np def evaluate_Tc(zeros,target): ''' Description: Evaluate Tc by calculating the zero resistivity area from 'zeros'. Parameters: zeros: zero resistivity points (np.array) target:...
Python
zaydzuhri_stack_edu_python
import time function generate_random_number start end begin comment Get the current time in milliseconds set current_time = integer time * 1000 comment Use the current time as a seed for generating a random number set random_number = current_time % end - start + 1 + start return random_number end function comment Examp...
import time def generate_random_number(start, end): # Get the current time in milliseconds current_time = int(time.time() * 1000) # Use the current time as a seed for generating a random number random_number = (current_time % (end - start + 1)) + start return random_number # Example usag...
Python
greatdarklord_python_dataset
function update_website_graph self from_link to_link begin if not from_link in website_graph begin set website_graph at from_link = list end set website_graph at from_link = website_graph at from_link + list to_link end function
def update_website_graph(self, from_link, to_link): if not from_link in self.website_graph: self.website_graph[from_link] = [] self.website_graph[from_link] += [to_link]
Python
nomic_cornstack_python_v1
function pick_logical_basis H0_num bare_basis begin set H0_num = call Qobj real dims=dims set eigvecs = call eigenstates sparse=false at 1 comment normalize eigvecs to that real part of largest value is positive for tuple i_v vec in enumerate eigvecs begin set val = call find_nonzero data at 2 if real < 0 begin set eig...
def pick_logical_basis(H0_num, bare_basis): H0_num = qutip.Qobj(H0_num.data.real, dims=H0_num.dims) eigvecs = H0_num.eigenstates(sparse=False)[1] # normalize eigvecs to that real part of largest value is positive for (i_v, vec) in enumerate(eigvecs): val = find_nonzero(vec.data)[2] if v...
Python
nomic_cornstack_python_v1
function exc_clear self begin set exception = tuple none none none set exception_raise = _no_exception_to_raise end function
def exc_clear(self): self.exception = (None, None, None) self.exception_raise = self._no_exception_to_raise
Python
nomic_cornstack_python_v1
comment 你有一个字符串,想从左至右将其解析为一个令牌流。 set text = string foo = 23 + 42 * 10 set tokens = list tuple string NAME string foo tuple string EQ string = tuple string NUM string 23 tuple string PLUS string + tuple string NUM string 42 tuple string TIMES string * tuple string NUM string 10 comment 完全看不懂
# 你有一个字符串,想从左至右将其解析为一个令牌流。 text = 'foo = 23 + 42 * 10' tokens = [('NAME', 'foo'), ('EQ','='), ('NUM', '23'), ('PLUS','+'), ('NUM', '42'), ('TIMES', '*'), ('NUM', '10')] # 完全看不懂
Python
zaydzuhri_stack_edu_python