code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment -*- coding: utf-8 -*- import cv2 import numpy as np import sys function Update_Pointer pointer y begin return tuple pointer at 0 pointer at 1 + y end function function show_recognized lis path begin comment vars set height = 512 set width = 512 set padx = 120 set pady = 70 set draw_pointer = tuple integer width...
# -*- coding: utf-8 -*- import cv2 import numpy as np import sys def Update_Pointer(pointer, y): return (pointer[0], pointer[1] + y) def show_recognized(lis, path): #vars height = 512 width = 512 padx = 120 pady = 70 draw_pointer = (int(width/2), 70) font = cv2.FONT_HERSHEY_SCRIPT_COM...
Python
zaydzuhri_stack_edu_python
eval string print('abcde') set dict1 = dictionary a=100 b=100 set d = eval string a+b dict1 print d
eval("print('abcde')") dict1 = dict(a=100,b=100) d = eval("a+b",dict1) print(d)
Python
zaydzuhri_stack_edu_python
string Grade II function main score begin string Grade II if score <= 100 and score >= 95 begin print string A end else if score < 95 and score >= 90 begin print string B+ end else if score < 90 and score >= 85 begin print string B end else if score < 85 and score >= 80 begin print string C+ end else if score < 80 and ...
"""Grade II""" def main(score): """Grade II""" if score <= 100 and score >= 95: print("A") elif score < 95 and score >= 90: print("B+") elif score < 90 and score >= 85: print("B") elif score < 85 and score >= 80: print("C+") elif score < 80 and score >...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- from dateutil import parser function parse_timestamp timestamp begin try begin set timestamp = parse parser timestamp set timestamp = replace timestamp minute=0 second=0 set timestamp = string format time timestamp string %Y-%m-%d %H:%M:%S end except any begin rais...
#!/usr/bin/python # -*- coding: utf-8 -*- from dateutil import parser def parse_timestamp(timestamp): try: timestamp = parser.parse(timestamp) timestamp = timestamp.replace(minute=0, second=0) timestamp = timestamp.strftime("%Y-%m-%d %H:%M:%S") except: raise ValueError("Timesta...
Python
zaydzuhri_stack_edu_python
function region self begin return get _values string region end function
def region(self) -> typing.Optional[str]: return self._values.get('region')
Python
nomic_cornstack_python_v1
function __init__ self score_calculator learning_rate=0.01 epochs=100 step=0.01 max_search=5 begin set score_calculator = score_calculator set learning_rate = learning_rate set epochs = epochs set optimizer = adam set alpha = learning_rate set step = step set max_search = max_search end function
def __init__(self, score_calculator, learning_rate=1e-2, epochs=100, step=0.01, max_search=5): self.score_calculator = score_calculator self.learning_rate = learning_rate self.epochs = epochs self.optimizer = Adam() self.optimizer.alpha = learning_rate s...
Python
nomic_cornstack_python_v1
string 数组的变维 import numpy as np set a = array range 1 10 print a shape print string ----------共享数据模式------------- set b = reshape a 3 3 set a at 0 = 998 print string --------a---------- print a print string --------b---------- print b print string -------------复制变维模式--------------- set c = flatten b print string ------...
""" 数组的变维 """ import numpy as np a = np.arange(1, 10) print(a, a.shape) print('----------共享数据模式-------------') b = a.reshape(3,3) a[0] = 998 print('--------a----------') print(a, ) print('--------b----------') print(b, ) print('-------------复制变维模式---------------') c = b.flatten() print('--------c----------') print(c...
Python
zaydzuhri_stack_edu_python
import cv2 as cv import sys import numpy as np import cv2.aruco as aruco from operator import itemgetter , attrgetter comment function that calculates the sum of angles of a 4 line object function quad_sum cnt begin set sum_angles = 0 set p1 = array list cnt at 0 at 0 cnt at 0 at 1 set p2 = array list cnt at 1 at 0 cnt...
import cv2 as cv import sys import numpy as np import cv2.aruco as aruco from operator import itemgetter, attrgetter #function that calculates the sum of angles of a 4 line object def quad_sum(cnt): sum_angles = 0 p1 = np.array([cnt[0][0], cnt[0][1]]) p2 = np.array([cnt[1][0], cnt[1][1]]) p3 = np.a...
Python
zaydzuhri_stack_edu_python
function view_isometric self negative=false render=true begin set position = call get_default_cam_pos negative=negative set camera_position = call CameraPosition *position set camera_set = negative call reset_camera render=render end function
def view_isometric(self, negative=False, render=True): position = self.get_default_cam_pos(negative=negative) self.camera_position = CameraPosition(*position) self.camera_set = negative self.reset_camera(render=render)
Python
nomic_cornstack_python_v1
function test did_pass begin comment Get the caller's line number. set linenum = f_lineno if did_pass begin set msg = format string Test at line {0} ok. linenum end else begin set msg = format string Test at line {0} FAILED. linenum end print msg end function
def test(did_pass): linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg)
Python
nomic_cornstack_python_v1
function load_raw_keylist field **kwargs begin comment load things as usual set filename = call get_keylist_filename field keyword kwargs if not exists path filename begin return tuple none string NO_RAW_KEYLIST_FILE_FOUND end end function comment Some of the keylists are corrupted. This try/except will comment avoid b...
def load_raw_keylist(field, **kwargs): # load things as usual filename = get_keylist_filename(field, **kwargs) if not os.path.exists(filename): return None, 'NO_RAW_KEYLIST_FILE_FOUND' # Some of the keylists are corrupted. This try/except will # avoid breaking things unless necessary
Python
nomic_cornstack_python_v1
import tkinter as tk from tkinter import messagebox as msgBox function submit username password begin if password == string jumping jama and username == string CookieM begin call showinfo string Login Successful string You'll find the cookies under the bed end end function set main_window = call Tk set u_text = call St...
import tkinter as tk from tkinter import messagebox as msgBox def submit(username, password): if password == 'jumping jama' and username == 'CookieM': msgBox.showinfo("Login Successful", "You'll find the cookies under the bed") main_window = tk.Tk() u_text = tk.StringVar() p_text = tk.StringVar() c...
Python
zaydzuhri_stack_edu_python
function loop_until_convergence self begin set i = 0 while cont begin set i = i + 1 yield i end end function
def loop_until_convergence(self) -> int: i = 0 while self.cont: i += 1 yield i
Python
nomic_cornstack_python_v1
import re function classify_string string begin comment Task 1: Classify the string if match string ^[a-zA-Z]+$ string begin set category = string Alphabetic string end else if match string ^\d+$ string begin set category = string Numeric string end else if match string ^[a-zA-Z0-9]+$ string begin set category = string...
import re def classify_string(string): # Task 1: Classify the string if re.match(r'^[a-zA-Z]+$', string): category = 'Alphabetic string' elif re.match(r'^\d+$', string): category = 'Numeric string' elif re.match(r'^[a-zA-Z0-9]+$', string): category = 'Alphanumeric string' el...
Python
jtatman_500k
import sys if __name__ == string __main__ begin set a = open argv at 1 set o = open argv at 2 if string h in argv begin set human = true end else begin set human = false end set answers = list set outputs = list set function_name = 0 set slot = 1 set fixed = 2 set sentinel = 3 set symbolic = 4 set numSentinelTerminat...
import sys if __name__ == "__main__": a = open(sys.argv[1]) o = open(sys.argv[2]) if 'h' in sys.argv: human = True else: human = False answers = [] outputs = [] function_name = 0 slot = 1 fixed = 2 sentinel = 3 symbolic = 4 numSentinelTerminated = 0 numSymbolicLength = 0 numFixedLen...
Python
zaydzuhri_stack_edu_python
function get_capacity self f_error_rate begin assert is instance f_error_rate float assert 0 < f_error_rate < 1 return call _get_n_capacity _m_size f_error_rate end function
def get_capacity(self, f_error_rate): assert isinstance(f_error_rate, float) assert 0 < f_error_rate < 1 return self._get_n_capacity(self._m_size, f_error_rate)
Python
nomic_cornstack_python_v1
string Построить dict для позиций𝑘-mer’ов в геноме SARS-CoV-2 (𝑘–переменная). При каком минимальном𝑘каждому фрагменту соответствует ровно одна позиция? function kmers_dict k genome begin set positions = dictionary for i in range length genome - k begin set k_cur = genome at slice i : i + k : if k_cur not in keys po...
'''Построить dict для позиций𝑘-mer’ов в геноме SARS-CoV-2 (𝑘–переменная). При каком минимальном𝑘каждому фрагменту соответствует ровно одна позиция?''' def kmers_dict(k, genome): positions = dict() for i in range(len(genome) - k): k_cur = genome[i: i + k] if k_cur not in positions.keys(): ...
Python
zaydzuhri_stack_edu_python
comment Function to check if a number is prime function is_prime n begin if n <= 1 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function comment Create the array of integers ranging from -50 to 50 set arr = list range - 50 51 comment Filter a...
# Function to check if a number is prime def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True # Create the array of integers ranging from -50 to 50 arr = list(range(-50, 51)) # Filter and print the prime numbers in...
Python
jtatman_500k
class QuizBrain begin set answer = string function __init__ self questions begin set question_list = questions set question_number = 1 set score = 0 end function function still_has_questions self begin return question_number <= length question_list end function function next_question self begin set question = question...
class QuizBrain(): answer = "" def __init__(self, questions): self.question_list = questions self.question_number = 1 self.score = 0; def still_has_questions(self): return self.question_number <= len(self.question_list) def next_question(self): question = self.question_list[self.question_n...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict class Solution begin function canFinish self numCourses prerequisites begin set dict_co = default dictionary list for tuple x y in prerequisites begin append dict_co at x y end set visited = set set bef_chk = set function func val begin if val in bef_chk begin return false end if val...
from collections import defaultdict class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: dict_co = defaultdict(list) for x,y in prerequisites: dict_co[x].append(y) visited = set() bef_chk = set() def func(val): ...
Python
zaydzuhri_stack_edu_python
function __init__ self nn_architecture begin set nn_architecture = nn_architecture end function
def __init__(self, nn_architecture): self.nn_architecture = nn_architecture
Python
nomic_cornstack_python_v1
function add_abundancecontributions dfgridcontributions dfmodel t_model_days_incpremerger traj_root minparticlespercell=0 begin set t_model_s = t_model_days_incpremerger * 86400 set dfcontribs = dfgridcontributions if string X_Fegroup not in columns begin set dfmodel = concat list dfmodel call DataFrame dict string X_F...
def add_abundancecontributions( dfgridcontributions: pd.DataFrame, dfmodel: pd.DataFrame, t_model_days_incpremerger: float, traj_root: Path, minparticlespercell: int = 0, ) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]: t_model_s = t_model_days_incpremerger * 86400 dfcontribs = dfgridco...
Python
nomic_cornstack_python_v1
async function get_lucky_number self day=none begin return await get LuckyNumber _api day or today end function
async def get_lucky_number(self, day: date = None) -> LuckyNumber: return await LuckyNumber.get(self._api, day or date.today())
Python
nomic_cornstack_python_v1
import os from datetime import datetime comment print(os.name) comment print(os.getcwd()) comment os.chdir('/Users/Bobby/Desktop/ ') comment print(os.getcwd()) comment os.chdir("C:/Users/Bobby/Desktop/python variables") comment s.mkdir("new") comment os.rmdir("new") comment os.makedirs("new//new2") comment print(os.lis...
import os from datetime import datetime #print(os.name) #print(os.getcwd()) #os.chdir('/Users/Bobby/Desktop/ ') #print(os.getcwd()) #os.chdir("C:/Users/Bobby/Desktop/python variables") #s.mkdir("new") #os.rmdir("new") #os.makedirs("new//new2") #print(os.listdir()) #print(os.path.exists("B://")) #os.removedi...
Python
zaydzuhri_stack_edu_python
function addRow self row begin set new_row = call _adjust_data row for col_id in range call _get_col_count begin set cell = new_row at col_id if string in cell begin for line in split cell string begin set l = length line if l > columnWidths at col_id begin set width = width - columnWidths at col_id set columnWidths a...
def addRow(self, row): new_row = self._adjust_data(row) for col_id in range(self._get_col_count()): cell = new_row[col_id] if '\n' in cell: for line in cell.split('\n'): l = len(line) if l > self.columnWidths[col_id]: ...
Python
nomic_cornstack_python_v1
function apply_rules self token_parse_list begin return token_parse_list end function
def apply_rules(self, token_parse_list): return token_parse_list
Python
nomic_cornstack_python_v1
function test_unique self begin comment Assign the asset to the section set container = get objects name=string left set section_asset = call SectionAsset section=section asset=asset container=container save comment Create a new assset set asset = call create_html_asset type=string text title=string Test Asset 2 commen...
def test_unique(self): # Assign the asset to the section container = Container.objects.get(name='left') section_asset = SectionAsset(section=self.section, asset=self.asset, container=container) section_asset.save() # Create a new assset ...
Python
nomic_cornstack_python_v1
function __init__ self v0 v1 begin set vinputs = tuple v0 v1 set xhi = max list v0 at 0 v1 at 0 set tuple yhi ylo = v0 at 1 > v1 at 1 and tuple v0 at 1 v1 at 1 or tuple v1 at 1 v0 at 1 comment (x1-x0)/(y1-y0) set m = v1 at 0 - v0 at 0 / v1 at 1 - v0 at 1 comment x0 - y0*(x1-x0)/(y1-y0) set b = v0 at 0 - v0 at 1 * m end...
def __init__(self,v0,v1): self.vinputs = v0,v1 self.xhi = max([v0[0],v1[0]]) self.yhi,self.ylo = v0[1]>v1[1] and (v0[1],v1[1],) or (v1[1],v0[1]) self.m = (v1[0]-v0[0]) / (v1[1]-v0[1]) ### (x1-x0)/(y1-y0) self.b = v0[0] - (v0[1] * self.m) ### x0 - y0*(x1-x0)/(y1-y0)
Python
nomic_cornstack_python_v1
function getAllRigsByName names begin set rigs = call getAllRigs set matches = list for r in rigs begin set data = call getMetaData r RIG_METACLASS if get data string name in names begin append matches r end end return matches end function
def getAllRigsByName(names): rigs = getAllRigs() matches = [] for r in rigs: data = meta.getMetaData(r, RIG_METACLASS) if data.get('name') in names: matches.append(r) return matches
Python
nomic_cornstack_python_v1
comment Task comment The provided code stub reads and integer, n, from STDIN. For all non-negative integers i<n, print i squared. set n = integer input set i = 0 while i < n begin set squared = i ^ 2 print squared set i = i + 1 end
# Task # The provided code stub reads and integer, n, from STDIN. For all non-negative integers i<n, print i squared. n = int(input()) i = 0 while (i < n): squared = i**2 print(squared) i = i + 1
Python
zaydzuhri_stack_edu_python
function name self begin if has attribute self string module begin return replace __name__ string _ string - end return none end function
def name(self): if hasattr(self, "module"): return self.module.__name__.replace('_', '-') return None
Python
nomic_cornstack_python_v1
import os set img_folder = string D:\Files\GIS\_Tutorial\Data\imgs set img_contents = list directory img_folder for image in img_contents begin print image set full_path = join path img_folder image print full_path end
import os img_folder = r"D:\Files\GIS\_Tutorial\Data\imgs" img_contents = os.listdir(img_folder) for image in img_contents: print(image) full_path = os.path.join(img_folder, image) print(full_path)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri May 19 23:58:22 2017 @author: Alex from __future__ import division import cPickle as pickle from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot import matplotlib.pyplot as plt import numpy as np import pandas as pd import gzip fr...
# -*- coding: utf-8 -*- """ Created on Fri May 19 23:58:22 2017 @author: Alex """ from __future__ import division import cPickle as pickle from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot import matplotlib.pyplot as plt import numpy as np import pandas as pd impo...
Python
zaydzuhri_stack_edu_python
comment project from turtle import * call speed 400 call left 90 call up backward 50 call down call bgcolor string black function branch a begin if a < 10 begin call color string green call stamp call color string brown return end else begin call color string brown call pensize 3 call forward a call left 30 call branch...
#project from turtle import * speed(400) left(90) up() backward(50) down() bgcolor('black') def branch(a): if a < 10: color('green') stamp() color('brown') return else: color('brown') pensize(3) forward(a) left(30) branch(a * 3/4) ...
Python
zaydzuhri_stack_edu_python
import socket , threading , time class EKSResponse begin function __init__ self command status payload begin set command = command set status = status set payload = payload end function function __eq__ self other begin if other == none begin return false end return command == command and status == status and payload ==...
import socket, threading, time class EKSResponse: def __init__(self, command, status, payload): self.command = command self.status = status self.payload = payload def __eq__(self, other): if other == None: return False return self.command == other.command \...
Python
zaydzuhri_stack_edu_python
function test_query_dsl_distinct self begin set tuple status body = call api_get_items current_db current_ns assert equal true status == API_STATUS at string success body set total_items = body at string total_items set items = list set items_count = 10 set distinct_field_value_random = random integer 536870911 214748...
def test_query_dsl_distinct(self): status, body = self.api_get_items(self.current_db, self.current_ns) self.assertEqual(True, status == self.API_STATUS['success'], body) total_items = body['total_items'] items = [] items_count = 10 distinct_field_value_random = random.r...
Python
nomic_cornstack_python_v1
function init_homographies self homography_path n_images begin with open homography_path as f begin set h_data = read lines f end set h_scale = split right strip h_data at 0 string set h_scale_x = integer h_scale at 1 set h_scale_y = integer h_scale at 2 set h_bounds = split right strip h_data at 1 string set h_bounds_...
def init_homographies(self, homography_path, n_images): with open(homography_path) as f: h_data = f.readlines() h_scale = h_data[0].rstrip().split(' ') self.h_scale_x = int(h_scale[1]) self.h_scale_y = int(h_scale[2]) h_bounds = h_data[1].rstrip().split(' ') s...
Python
nomic_cornstack_python_v1
function apply self x latent_dim begin set dim = shape at - 1 set x = dense x latent_dim set x = gelu x set x = dense x dim return x end function
def apply(self, x, latent_dim): dim = x.shape[-1] x = nn.Dense(x, latent_dim) x = nn.gelu(x) x = nn.Dense(x, dim) return x
Python
nomic_cornstack_python_v1
string Assignment 5 Name: 陳彥呈 Student Number:109502569 Course 2020-CE1003-B set tab = string 0123456789ABCDEF function dec_to_hex s begin set n = 1 set ans = string while s > n * 16 begin set n = n * 16 end while n > 0 begin set ans = ans + tab at s // n set s = integer s % n * s // n set n = integer n / 16 end return...
""" Assignment 5 Name: 陳彥呈 Student Number:109502569 Course 2020-CE1003-B """ tab = "0123456789ABCDEF" def dec_to_hex(s): n = 1 ans="" while s>n*16: n*=16 while n>0: ans+=tab[s//n] s=int(s%(n*(s//n))) n=int(n/16) return ans while 1: str_in = input("Binary: ") if str_in=="-1": break sum = 0 for idx in ...
Python
zaydzuhri_stack_edu_python
function test_graph_no_env self begin set resp = get client string /graph/?env= assert equal status_code 200 assert true string <title>Kitchen</title> in content assert true string Environment in content assert true string Please select an environment in content assert false string <img src="/static/img/node_map.svg" i...
def test_graph_no_env(self): resp = self.client.get("/graph/?env=") self.assertEqual(resp.status_code, 200) self.assertTrue("<title>Kitchen</title>" in resp.content) self.assertTrue("Environment" in resp.content) self.assertTrue("Please select an environment" in resp.content) ...
Python
nomic_cornstack_python_v1
function chi2_ndof self begin if string CHI2VEC in __dict__ and string NDOF in __dict__ begin return sum / NDOF end else if string CHI2 in __dict__ and string NDOF in __dict__ begin return CHI2 / NDOF end else begin return 0 end end function
def chi2_ndof(self): if 'CHI2VEC' in self.__dict__ and 'NDOF' in self.__dict__ : return( self.CHI2VEC.sum() / self.NDOF ) elif 'CHI2' in self.__dict__ and 'NDOF' in self.__dict__ : return( self.CHI2 / self.NDOF ) else : return( 0 )
Python
nomic_cornstack_python_v1
string Classify a film review as either Positive or Negative import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer function classify_review review begin set sid = call SentimentIntensityAnalyzer set review_scores = call polarity_scores review if review_scores at string compound > 0.05 begin return str...
""" Classify a film review as either Positive or Negative """ import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer def classify_review(review): sid = SentimentIntensityAnalyzer() review_scores = sid.polarity_scores(review) if review_scores['compound'] > 0.05: return 'Positive' ...
Python
flytech_python_25k
comment -*- encoding: utf-8 -*- string 计算两个整数的和 (这是一个做题的示范,不需要输入任何代码,即可测试,和提交。) comment 相当于主函数 if __name__ == string __main__ begin set a = integer input set b = integer input print integer a + b end
# -*- encoding: utf-8 -*- ''' 计算两个整数的和 (这是一个做题的示范,不需要输入任何代码,即可测试,和提交。) ''' if __name__ == '__main__': # 相当于主函数 a = int(input()) b = int(input()) print(int(a + b))
Python
zaydzuhri_stack_edu_python
string Dnd sort by Max Petschack: sorts your dnd file Usage: Replace demo.txt with your inventory filename (make sure they're in the same folder). Put each item on a new line and label with [?] at the start of the line where ? is the letter of the item's category. Weapons will sort by damage if formula is given. import...
'''Dnd sort by Max Petschack: sorts your dnd file Usage: Replace demo.txt with your inventory filename (make sure they're in the same folder). Put each item on a new line and label with [?] at the start of the line where ? is the letter of the item's category. Weapons will sort by damage if formula is given.''' import...
Python
zaydzuhri_stack_edu_python
string ---------------------------------------------------------------------------------- Script Name: Adds Reference Fields Version: 1.1 Description: This tool adds reference fields into the target shapefile. Created By: Kusasalethu Sithole Date: 2018-11-27 Last Revision: 2019-01-27 -----------------------------------...
"""---------------------------------------------------------------------------------- Script Name: Adds Reference Fields Version: 1.1 Description: This tool adds reference fields into the target shapefile. Created By: Kusasalethu Sithole Date: 2018-11-27 Last Revision: 2019-01-27...
Python
zaydzuhri_stack_edu_python
import torch from torch.utils.data import Dataset from PIL import Image import os function default_loader path begin return open path end function class MyDataset extends Dataset begin function __init__ self txt encoding=string utf-8 data_root=string . transform=none loader=default_loader count=true title=string begin ...
import torch from torch.utils.data import Dataset from PIL import Image import os def default_loader(path): return Image.open(path) class MyDataset(Dataset): def __init__(self, txt, encoding='utf-8', data_root='.', transform=None, loader=default_loader, count=True, title=''): if not...
Python
zaydzuhri_stack_edu_python
function _capture_frame self begin set tuple _ frame = read camera end function
def _capture_frame(self) -> None: _, self.frame = self.camera.read()
Python
nomic_cornstack_python_v1
function lifecycle_state self begin return get pulumi self string lifecycle_state end function
def lifecycle_state(self) -> pulumi.Output[str]: return pulumi.get(self, "lifecycle_state")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Apr 25 19:47:11 2014 @author: Abhishek import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.decomposition import PCA import pylab as pl from itertools import cycle import sys if not count path string .. begin append path st...
# -*- coding: utf-8 -*- """ Created on Fri Apr 25 19:47:11 2014 @author: Abhishek """ import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.decomposition import PCA import pylab as pl from itertools import cycle import sys if not sys.path.count(".."): sys.path.append("..") f...
Python
zaydzuhri_stack_edu_python
function jumpingOnClouds c begin append c 1 set int_Jump = 0 set i = 0 set bln_Stop = true while bln_Stop begin try begin if c at i + 1 == 0 and c at i + 2 == 0 begin set int_Jump = int_Jump + 1 set i = i + 2 print string Jump: int_Jump string & i: i end if c at i + 1 == 1 and c at i + 2 == 0 begin set int_Jump = int_J...
def jumpingOnClouds(c): c.append(1) int_Jump = 0 i = 0 bln_Stop = True while bln_Stop: try: if (c[i + 1] == 0) and (c[i + 2] == 0): int_Jump += 1 i += 2 print("Jump: ", int_Jump, " & i: ", i) if ((c[i + 1] == 1...
Python
zaydzuhri_stack_edu_python
function __setitem__ self addr on begin call switch addr on end function
def __setitem__(self, addr, on): self.switch(addr, on)
Python
nomic_cornstack_python_v1
import dns.resolver from os import path set host = string google.com set words = string brutesub.txt function main begin if exists path words begin set wordlist = open words string r set wordlist = split read wordlist string set subdom = list for w in wordlist begin try begin set a = query resolver format string {}.{}...
import dns.resolver from os import path host = 'google.com' words = 'brutesub.txt' def main(): if path.exists(words): wordlist = open(words, 'r') wordlist = wordlist.read().split('\n') subdom = [] for w in wordlist: try: a = dns.resolver.query('{}.{}'.f...
Python
zaydzuhri_stack_edu_python
function createHotSpotsByMinSearch gridlist cutoff meanradius=0.5 cancelRadius=2.0 protValue=999 outprefix=none **kwargs begin if not is instance gridlist list begin set gridlist = list gridlist end set hm = call HotSpotsManager set multiset = call HotSpotMultipleSet keyword kwargs set hsets = list for grid in gridlis...
def createHotSpotsByMinSearch(gridlist, cutoff, meanradius=0.5, cancelRadius=2.0, protValue=999,outprefix=None, **kwargs): if not isinstance(gridlist, list): gridlist = [gridlist] hm = HotSpotsManager() multiset = HotSpotMultipleSet(**kwargs) hsets = [] for grid in g...
Python
nomic_cornstack_python_v1
function QuerySetMock model *return_value begin string Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily generates QuerySets. Set the results to two items: >>> class Post(object): pass >>> objects = QuerySetMock(Post, 'return', 'values') >>> assert list(objec...
def QuerySetMock(model, *return_value): """ Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily generates QuerySets. Set the results to two items: >>> class Post(object): pass >>> objects = QuerySetMock(Post, 'return', 'values') >>...
Python
jtatman_500k
function _propagate_intra_module_masks self begin for tuple op _ in items _op_to_mask_dict begin call propagate_internal_connectivity_out_channels_to_in_channels call propagate_internal_connectivity_in_channels_to_out_channels end end function
def _propagate_intra_module_masks(self): for op, _ in self._op_to_mask_dict.items(): self._op_to_mask_dict[op].propagate_internal_connectivity_out_channels_to_in_channels() self._op_to_mask_dict[op].propagate_internal_connectivity_in_channels_to_out_channels()
Python
nomic_cornstack_python_v1
function _set_vlan_name self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=text_type is_leaf=true yang_name=string vlan-name parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true namespace=string http://openconfig...
def _set_vlan_name(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="vlan-name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/inter...
Python
nomic_cornstack_python_v1
function Take_Off_Connected_But_Failed self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def Take_Off_Connected_But_Failed(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
function summary begin set results = dict for run in list directory RAW_DATA_DIR begin set snapshot_results = dict set snapshots = filter lambda s -> match string ^.*[0-9]{5}$ s list directory join path RAW_DATA_DIR run for snapshot in snapshots begin try begin set snapshot_results at snapshot = list directory join p...
def summary(): results = {} for run in os.listdir(RAW_DATA_DIR): snapshot_results = {} snapshots = filter(lambda s: re.match(r"^.*[0-9]{5}$", s), os.listdir(os.path.join(RAW_DATA_DIR, run))) for snapshot in snapshots: try: snapshot_results[snapshot] = os.listd...
Python
nomic_cornstack_python_v1
function cost x y begin if x == 343 begin print string Стоимость разговора: 15 * y string руб. end else if x == 381 begin print string Стоимость разговора: 18 * y string руб. end else if x == 473 begin print string Стоимость разговора: 13 * y string руб. end else if x == 485 begin print string Стоимость разговора: 11 *...
def cost(x, y): if x == 343: print('Стоимость разговора:', 15*y,'руб.') elif x == 381: print('Стоимость разговора:', 18*y,'руб.') elif x == 473: print('Стоимость разговора:', 13*y,'руб.') elif x == 485: print('Стоимость разговора:', 11*y,'руб.') else: print('П...
Python
zaydzuhri_stack_edu_python
function _check_columns schema_errors stored expected columns table_name supports begin for column in columns begin if stored at column == expected at column begin continue end add schema_errors string { table_name } . { supports } error string Column %s in database table %s does not support %s (stored=%s != expected=%...
def _check_columns( schema_errors: set[str], stored: Mapping, expected: Mapping, columns: Iterable[str], table_name: str, supports: str, ) -> None: for column in columns: if stored[column] == expected[column]: continue schema_errors.add(f"{table_name}.{supports}")...
Python
nomic_cornstack_python_v1
string TODO: customize help screen add option to schedule tsume segmentize tsume solution import discord from discord.ext import commands import os from dotenv import load_dotenv import json import random import csv from github import Github import itertools import io import re call load_dotenv set DISCORD_TOKEN = call...
""" TODO: customize help screen add option to schedule tsume segmentize tsume solution """ import discord from discord.ext import commands import os from dotenv import load_dotenv import json import random import csv from github import Github import itertools import io import re load_dotenv() DISCORD_TOKEN...
Python
zaydzuhri_stack_edu_python
comment Install the pyautogui and pyserial libraries import serial import time import pyautogui comment Below are the strings used for cursor movements comment taken from the pyautogui reference: comment https://pyautogui.readthedocs.io/en/latest/keyboard.html comment For mouse commands use these: comment https://pyaut...
# Install the pyautogui and pyserial libraries import serial import time import pyautogui # Below are the strings used for cursor movements # taken from the pyautogui reference: # https://pyautogui.readthedocs.io/en/latest/keyboard.html # # For mouse commands use these: # https://pyautogui.readthedocs.io/en/...
Python
zaydzuhri_stack_edu_python
string Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the...
''' Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ type query=none source_retry_count=none source_retry_wait=none begin set __self__ string type string JiraSource if query is not none begin set __self__ string query query end if source_retry_count is not none begin set __self__ string source_retry_count source_retry_count end if source_retry_...
def __init__(__self__, *, type: str, query: Optional[Any] = None, source_retry_count: Optional[Any] = None, source_retry_wait: Optional[Any] = None): pulumi.set(__self__, "type", 'JiraSource') if query is not None: pulumi.se...
Python
nomic_cornstack_python_v1
function _slice tensor size i begin return tensor at tuple slice : : slice i * size : i + 1 * size : end function
def _slice(tensor, size, i): return tensor[:, i * size : (i + 1) * size]
Python
nomic_cornstack_python_v1
function test_tax_net_pay_65 self begin set net_pay_age = call total_calc_tax 100 65 assert equal 95 net_pay_age end function
def test_tax_net_pay_65(self): net_pay_age = tc.total_calc_tax(100, 65) self.assertEqual(95, net_pay_age)
Python
nomic_cornstack_python_v1
function binarySearch arr begin end search begin if end < begin begin return - 1 end set middle = begin + end // 2 if search == arr at middle begin return middle end else if search < arr at middle begin return call binarySearch arr begin middle - 1 search end else begin return call binarySearch arr middle + 1 end searc...
def binarySearch(arr, begin, end, search): if (end<begin): return -1 middle = (begin + end) //2 if (search == arr[middle]): return middle elif (search < arr[middle]): return binarySearch(arr, begin, middle-1, search) else: return binarySearch(arr,...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.backend import transpose , reverse comment The Layers Slope, Reflectance, ShapeIndex, MeanCurvature, MinimalCurvature, comment UnsphericityCurvature, Laplacian, SlopeTrainable, ReflectanceTrainable, comment Sh...
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.backend import transpose, reverse # The Layers Slope, Reflectance, ShapeIndex, MeanCurvature, MinimalCurvature, # UnsphericityCurvature, Laplacian, SlopeTrainable, ReflectanceTrainable, # ShapeIndexTrai...
Python
zaydzuhri_stack_edu_python
class Customer begin function __init__ self name surname idno begin set __Name = name set __Surname = surname set __ID_NO = idno end function function get_name self begin return __Name end function function get_surname self begin return __Surname end function function get_ID self begin return __ID_NO end function funct...
class Customer: def __init__(self, name: str, surname: str, idno: int): self.__Name = name self.__Surname = surname self.__ID_NO = idno def get_name(self): return self.__Name def get_surname(self): return self.__Surname def get_ID(self): return self.__I...
Python
zaydzuhri_stack_edu_python
function showPublishDate self fmt=string %d %B %Y begin return string format time call getPublishDate fmt end function
def showPublishDate(self, fmt="%d %B %Y"): return self.getPublishDate().strftime(fmt)
Python
nomic_cornstack_python_v1
function change_nameservers self nameservers service=string Wi-Fi begin if is instance nameservers list begin set nameservers = join string nameservers end call run_command string { SUDO } { NETWORKSETUP } -setdnsservers { service } { nameservers } end function
def change_nameservers(self, nameservers, service='Wi-Fi'): if isinstance(nameservers, list): nameservers = ' '.join(nameservers) self.run_command(f'{self.SUDO} {self.NETWORKSETUP} -setdnsservers {service} {nameservers}')
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Author: Nikhil Sharma comment Created Date: 16-06-2020 comment Last Updated: 16-06-2020 comment Operating System: Linux and Mac comment Description: comment Import necessary libraries import netfilterqueue import subprocess import re import scapy.layers.l2 as scapy import scapy.all...
#!/usr/bin/env python3 # Author: Nikhil Sharma # Created Date: 16-06-2020 # Last Updated: 16-06-2020 # Operating System: Linux and Mac # Description: # Import necessary libraries import netfilterqueue import subprocess import re import scapy.layers.l2 as scapy import scapy.all as scapy2 # Create a queue to trap the ...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , request set app = call Flask __name__ decorator call route string / function homepage begin return call render_template string index.html title=string My Website end function decorator call route string /form methods=list string GET string POST function form begin if method =...
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def homepage(): return render_template('index.html', title='My Website') @app.route('/form', methods=['GET', 'POST']) def form(): if request.method == 'POST': email = request.form.get('email') return "Your...
Python
jtatman_500k
for n in range N begin set G = integer input set nums = split input string set seen = set for ea in nums begin if ea in seen begin remove seen ea end else begin add seen ea end end print string Case # { n + 1 } : { pop seen } end
for n in range(N): G = int(input()) nums = input().split(' ') seen = set() for ea in nums: if ea in seen: seen.remove(ea) else: seen.add(ea) print(f'Case #{n+1}: {seen.pop()}')
Python
zaydzuhri_stack_edu_python
function ReleaseSelectionAccess self begin return call InvokeTypes 3 LCID 1 tuple 24 0 tuple end function
def ReleaseSelectionAccess(self): return self._oleobj_.InvokeTypes(3, LCID, 1, (24, 0), (),)
Python
nomic_cornstack_python_v1
import logging from datetime import datetime from datetime import timedelta set logger = call getLogger __name__ class Order begin comment each order should be processed within 20 minutes set max_order_completion_time = 20 function __init__ self branch_id date_time order_id hamburgers begin string Args: branch_id (str)...
import logging from datetime import datetime from datetime import timedelta logger = logging.getLogger(__name__) class Order: # each order should be processed within 20 minutes max_order_completion_time = 20 def __init__(self, branch_id, date_time, or...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sun Oct 28 15:34:53 2018 @author: sadams from collections import defaultdict from sklearn.model_selection import cross_val_score from sklearn.metrics import accuracy_score from sklearn.dummy import DummyClassifier from sklearn.neighbors impor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 28 15:34:53 2018 @author: sadams """ from collections import defaultdict from sklearn.model_selection import cross_val_score from sklearn.metrics import accuracy_score from sklearn.dummy import DummyClassifier from sklearn.neighbors import KNeighbo...
Python
zaydzuhri_stack_edu_python
function get_conv_ms self msg subject date begin if subject is not none begin function prepare_subject_for_compare subject begin if length subject > 2 and subject at 2 == string : begin set subject = left strip subject at slice 3 : : end set subject = replace subject string string return subject end function set topi...
def get_conv_ms(self, msg, subject, date): if subject is not None: def prepare_subject_for_compare(subject): if len(subject) > 2 and subject[2] == ':': subject = subject[3:].lstrip() subject = subject.replace(" ","") return subject ...
Python
nomic_cornstack_python_v1
import pygame import sys import random from pygame.math import Vector2 class FRUIT begin function __init__ self begin call randomise end function function draw_fruit self begin set fruit_rect = call Rect x * cell_size y * cell_size cell_size cell_size call blit apple_surface fruit_rect end function function randomise s...
import pygame import sys import random from pygame.math import Vector2 class FRUIT: def __init__(self): self.randomise() def draw_fruit(self): fruit_rect = pygame.Rect(self.pos.x*cell_size, self.pos.y*cell_size, cell_size, cell_size) screen.blit(apple_surface, fruit_rect) ...
Python
zaydzuhri_stack_edu_python
function dead_update self begin call events_buttons end function
def dead_update(self): super().events_buttons()
Python
nomic_cornstack_python_v1
from ui_tools.ui_string import String import enchant import pygame class WordlistDisplay extends object begin set lib = dictionary string en_US function __init__ self parent position size color font=none begin set rect = call Rect position size set surface = call Surface size set color = color set wordlist = list if f...
from ui_tools.ui_string import String import enchant import pygame class WordlistDisplay(object): lib = enchant.Dict("en_US") def __init__(self, parent, position, size, color, font=None): self.rect = pygame.Rect(position, size) self.surface = pygame.Surface(size) self.color = color ...
Python
zaydzuhri_stack_edu_python
function minDistance dist2 set x begin set minimum = 10000 set idx = 0 for i in range x begin if set at i == 0 and dist2 at i <= minimum begin set minimum = dist2 at i set idx = i end end return idx end function function dijkstra matrix s d n begin set r = list for i in range n begin set temp = list append temp 0 app...
def minDistance(dist2,set,x): minimum=10000 idx=0 for i in range(x): if set[i]==0 and dist2[i]<=minimum: minimum=dist2[i] idx=i return idx def dijkstra(matrix,s,d,n): r=[] for i in range(n): temp=[] temp.append(0) temp.append(0) r.append(temp) s-=1 d-=1 dist=[] setPermanent...
Python
zaydzuhri_stack_edu_python
from dao.sqliteDb import sqlDao from dao.mongodbConn import MongoDao from util.Util import datasetForServer , datasetForCpu comment 服务器类用于对接服务器节点 class ServerClass begin comment 读取某一个节点的N条数据 function readOneBmcDate self nodeId num begin set sd = call sqlDao set nodeUUID = tuple string nodeId set sql = string select * f...
from dao.sqliteDb import sqlDao from dao.mongodbConn import MongoDao from util.Util import datasetForServer,datasetForCpu #服务器类用于对接服务器节点 class ServerClass(): #读取某一个节点的N条数据 def readOneBmcDate(self,nodeId,num): sd = sqlDao() nodeUUID = (str(nodeId),) sql = 'select * from server_NodeInfo wh...
Python
zaydzuhri_stack_edu_python
function advance_project self report=none increment=1 begin set time_remaining = time_remaining - increment if time_remaining < 1 begin call finish_project report end save end function
def advance_project(self, report=None, increment=1): self.time_remaining -= increment if self.time_remaining < 1: self.finish_project(report) self.save()
Python
nomic_cornstack_python_v1
for i in range n begin print string Hello World end
for i in range(n): print("Hello World")
Python
jtatman_500k
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import os import pandas as pd class LogisticRegressionGD extends object begin string Logistic Regression Classifier using gradient descent Parameters eta : float Leraning rate (between 0.0 and 1.0) n_iter : int Passes over t...
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import os import pandas as pd class LogisticRegressionGD(object): """ Logistic Regression Classifier using gradient descent Parameters eta : float Leraning rate (between 0.0 and 1.0) n_iter : int ...
Python
zaydzuhri_stack_edu_python
import csv , io from django.http import Http404 from django.shortcuts import render from django.contrib import messages from models import Factory , Car , Dealership , Client function indexView request begin return call render request string index.html end function function factoryView request begin string Display all ...
import csv, io from django.http import Http404 from django.shortcuts import render from django.contrib import messages from .models import Factory, Car, Dealership, Client def indexView(request): return render(request, 'index.html') def factoryView(request): """ Display all the factories in the database ord...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- string 问题描述:合并两个单调递增的链表,合并后的链表也是单调不减的 解题思路:设置一个指针,从2个链表的头结点开始比较,指针指向值小的,并继续循环比较next class ListNode begin function __init__ self x begin set val = x set next = none end function end class class solution begin function Merge self pHead1 pHead2 begin if pHead1 == none begin return pHead2 end i...
# -*- coding:utf-8 -*- """ 问题描述:合并两个单调递增的链表,合并后的链表也是单调不减的 解题思路:设置一个指针,从2个链表的头结点开始比较,指针指向值小的,并继续循环比较next """ class ListNode: def __init__(self, x): self.val = x self.next = None class solution: def Merge(self, pHead1, pHead2): if pHead1 == None: return pHead2 if pHe...
Python
zaydzuhri_stack_edu_python
async function async_main main_data begin set elastic_session = none async_with call ClientSession as http_session begin comment TODO: Control last export with https://docs.github.com/en/rest/overview/resources-in-the-rest-api#conditional-requests set github_session = await call open_github_session http_session main_da...
async def async_main(main_data: dict[str, str]) -> None: elastic_session = None async with aiohttp.ClientSession() as http_session: # TODO: Control last export with https://docs.github.com/en/rest/overview/resources-in-the-rest-api#conditional-requests github_session = await githup.open_github_s...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: UTF-8 -*- string Ler as notas da 1a. e 2a. avaliações de um aluno. Calcular a média aritmética simples e escrever uma mensagem que diga se o aluno foi ou não aprovado (considerar que nota igual ou maior que 6 o aluno é aprovado). Escrever também a média calculada.
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Ler as notas da 1a. e 2a. avaliações de um aluno. Calcular a média aritmética simples e escrever uma mensagem que diga se o aluno foi ou não aprovado (considerar que nota igual ou maior que 6 o aluno é aprovado). Escrever também a média calculada. """
Python
zaydzuhri_stack_edu_python
function __init__ self name createStepName surface stiffness begin call __init__ pass end function
def __init__( self, name: str, createStepName: str, surface: Region, stiffness: float ): super().__init__() pass
Python
nomic_cornstack_python_v1
from __future__ import print_function import numpy as np import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd from torch.autograd import Variable import matplotlib.pyplot as plt import samplers as samplers import math import pdb class MLPJSD ex...
from __future__ import print_function import numpy as np import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd from torch.autograd import Variable import matplotlib.pyplot as plt import samplers as samplers import math import pdb class MLPJSD(...
Python
zaydzuhri_stack_edu_python
class Solution begin function findMaximumXOR self nums begin if length nums < 2 begin return 0 end set tries = dict for i in nums begin set node = tries for j in range 31 - 1 - 1 begin set activ_bit = integer i ? 1 ? j > 0 if activ_bit in node begin set node = node at activ_bit end else begin set node at activ_bit = d...
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: if len(nums) <2: return 0 tries = {} for i in nums: node = tries for j in range(31,-1,-1): activ_bit = int(i&(1<<j) > 0) if activ_bit in node: ...
Python
zaydzuhri_stack_edu_python
function encode self begin set packed = call pack string <2Bl device_number command_number data if message_id is not none begin set packed = packed at slice : 5 : + call pack string B message_id end return packed end function
def encode(self): packed = struct.pack("<2Bl", self.device_number, self.command_number, self.data) if self.message_id is not None: packed = packed[:5] + struct.pack("B", self.message_id) return pac...
Python
nomic_cornstack_python_v1
function build_command self command begin return list string realm command + call realm_arg end function
def build_command(self, command): return ['realm', command] + self.realm_arg()
Python
nomic_cornstack_python_v1
function __len__ self begin set length = length data - 2 * skip_window comment print ('length', length) return length end function comment raise NotImplementedError('Implement the __len__ method of the dataset')
def __len__(self): length = len(self.data) - 2* self.skip_window #print ('length', length) return length #raise NotImplementedError('Implement the __len__ method of the dataset')
Python
nomic_cornstack_python_v1
import socket import re import struct import fcntl import sys set __author__ = string njhazelh function dump_bytes bytes begin string Dump the bytes to hex in 4 column rows. :param bytes: The bytes to dump print for tuple index byte in zip range 1 length bytes + 1 bytes begin write stdout string %2X % byte if index != ...
import socket import re import struct import fcntl import sys __author__ = 'njhazelh' def dump_bytes(bytes): """ Dump the bytes to hex in 4 column rows. :param bytes: The bytes to dump """ print() for index, byte in zip(range(1, len(bytes) + 1), bytes): sys.stdout.write("%2X " % (byte...
Python
zaydzuhri_stack_edu_python
comment -*- encoding: utf-8 -*- comment @File: chapter3_2.py comment @Time: 2020-10-09 23:45 comment @Author: ZHANG comment @Description: chapter3_2 import tensorflow as tf set w1 = call Variable call random_normal tuple 2 3 stddev=1 seed=1 set w2 = call Variable call random_normal tuple 3 1 stddev=1 seed=1 set x = cal...
# -*- encoding: utf-8 -*- # @File: chapter3_2.py # @Time: 2020-10-09 23:45 # @Author: ZHANG # @Description: chapter3_2 import tensorflow as tf w1 = tf.Variable(tf.random_normal((2, 3), stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal((3, 1), stddev=1, seed=1)) x = tf.constant([[0.7, 0.9]]) a = tf.matmul(x...
Python
zaydzuhri_stack_edu_python
function open_file_browser self event begin set wildcard = string netCDF4 files (*.nc)|*.nc|All files (*.*)|*.* set flags = FD_OPEN ? FD_CHANGE_DIR set dlg = call FileDialog self message=string Choose a file defaultDir=get current directory defaultFile=string wildcard=wildcard style=flags if call ShowModal == ID_OK be...
def open_file_browser(self, event): wildcard = "netCDF4 files (*.nc)|*.nc|"\ "All files (*.*)|*.*" flags = wx.FD_OPEN | wx.FD_CHANGE_DIR dlg = wx.FileDialog(self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard=wildcard, style=flags ) i...
Python
nomic_cornstack_python_v1
function update self trans id payload **kwd begin set current_user = user set user_to_update = call by_id call decode_id id comment only allow updating other users if they're admin set editing_someone_else = current_user != user_to_update set is_admin = api_inherit_admin or call is_admin current_user if editing_someone...
def update( self, trans, id, payload, **kwd ): current_user = trans.user user_to_update = self.user_manager.by_id( self.decode_id( id ) ) # only allow updating other users if they're admin editing_someone_else = current_user != user_to_update is_admin = trans.api_inherit_admin o...
Python
nomic_cornstack_python_v1