code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function read_sp2 file_name debug=false arm_convention=true begin set my_data = read open file_name string rb comment Get file date from name if call system == string Windows begin set split_file_name = split file_name string \ end else begin set split_file_name = split file_name string / end if arm_convention begin se...
def read_sp2(file_name, debug=False, arm_convention=True): my_data = open(file_name, "rb").read() # Get file date from name if platform.system() == "Windows": split_file_name = file_name.split("\\") else: split_file_name = file_name.split("/") if arm_convention: next_split =...
Python
nomic_cornstack_python_v1
function _prepare_meta meta begin assert meta is not none set r = list for tuple k v in meta begin if v is none begin append r tuple k none none end else if has attribute v string _get_uriref begin append r tuple k call _get_uriref true end else begin append r tuple k call unicode v false end end return r end function
def _prepare_meta(meta): assert meta is not None r = [] for k,v in meta: if v is None: r.append((k, None, None)) elif hasattr(v, "_get_uriref"): r.append((k, v._get_uriref(), True)) else: r.append((k, unicode(v), False)) return r
Python
nomic_cornstack_python_v1
function __le__ self *args begin return call var_ref_t___le__ self *args end function
def __le__(self, *args): return _ida_hexrays.var_ref_t___le__(self, *args)
Python
nomic_cornstack_python_v1
function day self begin return get pulumi self string day end function
def day(self) -> Optional[pulumi.Input[Union[str, 'WeekDay']]]: return pulumi.get(self, "day")
Python
nomic_cornstack_python_v1
function local_ports self begin return call PortSet *[p.local_port if p is not None else None for p in self] end function
def local_ports(self): return PortSet(*[p.local_port if p is not None else None for p in self])
Python
nomic_cornstack_python_v1
comment Challenge 1: comment Uncomment the following code. Check that it is correctly creating a file. write open string myfile.txt string w+ string Hello file world! comment Challenge 2: comment First, store in a variable the name of your favorite sports team (or movie). comment Then, write the code necessary to write...
# Challenge 1: # Uncomment the following code. Check that it is correctly creating a file. open('myfile.txt', 'w+').write('Hello file world!') # Challenge 2: # First, store in a variable the name of your favorite sports team (or movie). # Then, write the code necessary to write this data to a file called # "sports_te...
Python
zaydzuhri_stack_edu_python
function get_all_by_is_activated is_activated order_by_field=none begin set queryset = filter is_activated=is_activated if order_by_field begin call order_by order_by_field end return queryset end function
def get_all_by_is_activated(is_activated, order_by_field=None): queryset = OaiRegistry.objects.filter(is_activated=is_activated) if order_by_field: queryset.order_by(order_by_field) return queryset
Python
nomic_cornstack_python_v1
function multiplicacionmatricial matriz_1 matriz_2 begin comment validar que los argumentos son un lista de lista if call valMultiplicacionMatricial matriz_1 matriz_2 == true begin set matriz_3 = list comment ij es un acumulador set ij = 0 comment Crear la matriz donde se guardara el resultado de la multiplicacion mat...
def multiplicacionmatricial(matriz_1,matriz_2): if valMultiplicacionMatricial(matriz_1,matriz_2) == True: #validar que los argumentos son un lista de lista matriz_3 = [] ij = 0 # ij es un acumulador for h in range(0,len(matriz_1)): #Crear la matriz donde se guardara el resultado de la multiplica...
Python
nomic_cornstack_python_v1
function compute_shap_values model data reference_data progress_callback=none begin comment ensure that sampling and SHAP value calculation is same for same data with call temp_seed 0 begin if progress_callback is none begin set progress_callback = dummy_callback end call progress_callback 0 string Computing explanatio...
def compute_shap_values( model: Model, data: Table, reference_data: Table, progress_callback: Callable = None, ) -> Tuple[List[np.ndarray], Table, np.ndarray, np.ndarray]: # ensure that sampling and SHAP value calculation is same for same data with temp_seed(0): if progress_callback is N...
Python
nomic_cornstack_python_v1
function get_hardware_id begin try begin return strip stdout end except any begin info string Not Found return - 1 end end function
def get_hardware_id(): try: return utils.run('crossystem hwid').stdout.strip() except: logging.info("Not Found") return -1
Python
nomic_cornstack_python_v1
from presidio.builders.presidio_dag_builder import PresidioDagBuilder from presidio.builders.smart_model.smart_model_accumulate_operator_builder import SmartModelAccumulateOperatorBuilder from presidio.builders.smart_model.smart_model_operator_builder import SmartModelOperatorBuilder from presidio.utils.airflow.schedul...
from presidio.builders.presidio_dag_builder import PresidioDagBuilder from presidio.builders.smart_model.smart_model_accumulate_operator_builder import SmartModelAccumulateOperatorBuilder from presidio.builders.smart_model.smart_model_operator_builder import SmartModelOperatorBuilder from presidio.utils.airflow.schedul...
Python
zaydzuhri_stack_edu_python
string This function takes a list of stars with their respective distances and brightnesses and organizes them first by distance, then by apparent brightness, and finally by absolute brightness. from pprint import pprint comment Name, Distance, Apparent Brightness, Absolute Brightness set stars = list tuple string Alph...
''' This function takes a list of stars with their respective distances and brightnesses and organizes them first by distance, then by apparent brightness, and finally by absolute brightness. ''' from pprint import pprint #Name, Distance, Apparent Brightness, Absolute Brightness stars = [ ('Alpha Centauri A', 4.3,...
Python
zaydzuhri_stack_edu_python
string Description Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack? Notice You can not divide any item into small pieces. Have you met this question in a real interview? Example If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select...
'''Description Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack? Notice You can not divide any item into small pieces. Have you met this question in a real interview? Example If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select...
Python
zaydzuhri_stack_edu_python
import random import numpy as np from math import sqrt from copy import deepcopy comment TODO comment инициализация comment мутация function fitness_function list_of_x begin set fit_val = 0 for x in list_of_x begin set fit_val = fit_val + x at 0 ^ 2 end return fit_val end function function random_double min_x max_x beg...
import random import numpy as np from math import sqrt from copy import deepcopy # TODO # инициализация # мутация def fitness_function(list_of_x): fit_val = 0 for x in list_of_x: fit_val += x[0] ** 2 return fit_val def random_double(min_x, max_x): return round(random.uniform(min_x, max_x), ...
Python
zaydzuhri_stack_edu_python
function SimpsonOneThird self l u n Fxdx begin set wd = u - l set f0 = call Fxdx l set f11 = 0 set f12 = 0 for i in range 1 n begin set l = l + wd / n if i % 2 == 0 begin set f12 = f12 + call Fxdx l end else begin set f11 = f11 + call Fxdx l end end if n == 1 begin set f11 = call Fxdx l + wd / 2 set n = 2 end set f2 = ...
def SimpsonOneThird(self, l, u, n, Fxdx): wd = u - l f0 = Fxdx(l) f11 = 0 f12 = 0 for i in range(1,n): l += wd / n if (i % 2 == 0): f12 += Fxdx(l) else: f11 += Fxdx(l) if (n == 1): f11 = Fxdx...
Python
nomic_cornstack_python_v1
function _make_fc_layers self in_channels fc_channels dropout_indices norm_cfg out_channels=none begin set fc_layers = list set pre_channel = in_channels for k in range length fc_channels begin append fc_layers call ConvModule pre_channel fc_channels at k kernel_size=tuple 1 1 stride=tuple 1 1 norm_cfg=norm_cfg conv_c...
def _make_fc_layers(self, in_channels: int, fc_channels: list, dropout_indices: list, norm_cfg: dict, out_channels: Optional[int] = None) -> torch.nn.Module: fc_layers = [] pre_channel...
Python
nomic_cornstack_python_v1
class Token begin function __init__ self type value begin set type = type set value = value end function function __str__ self begin return format string Token({type},{value}) type=type value=value end function function __expr__ self begin return call __str__ end function end class class Interpreter begin function __in...
class Token: def __init__(self, type, value): self.type = type self.value = value def __str__(self): return "Token({type},{value})".format(type=self.type,value=self.value) def __expr__(self): return self.__str__() class Interpreter: def __init__(self, text): se...
Python
zaydzuhri_stack_edu_python
comment f = open('this.rb', 'w') comment f.write('I am this file\n this is good') # thus we can creat a text or read in binary or rb with open string this.rb as f begin set content = read f end with open string copy.rb string w as f begin write f content end
# f = open('this.rb', 'w') # f.write('I am this file\n this is good') # thus we can creat a text or read in binary or rb with open('this.rb') as f: content = f.read() with open('copy.rb', 'w') as f: f.write(content)
Python
zaydzuhri_stack_edu_python
function forward_with_grad self z t grad_outputs begin set batch_size = shape at 0 set out = call forward z t set a = grad_outputs set tuple adfdz adfdt *adfdp = grad autograd tuple out tuple z t + tuple parameters self grad_outputs=a allow_unused=true retain_graph=true comment grad method automatically sums gradients ...
def forward_with_grad(self, z, t, grad_outputs): batch_size = z.shape[0] out = self.forward(z, t) a = grad_outputs adfdz, adfdt, *adfdp = torch.autograd.grad( (out,), (z, t) + tuple(self.parameters()), grad_outputs=(a), allow_unused=True, retain_graph=True ...
Python
nomic_cornstack_python_v1
function show_board self boardID begin return get app string /board/ + boardID follow_redirects=true end function
def show_board(self, boardID): return self.app.get('/board/' + boardID, follow_redirects = True)
Python
nomic_cornstack_python_v1
function time_str begin set curr_date = now return string format time curr_date string %Y%m%d_%H%M%S end function
def time_str(): curr_date = datetime.datetime.now() return curr_date.strftime('%Y%m%d_%H%M%S')
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- comment https://cuiqingcai.com/990.html import urllib import urllib2 import re import json class QSBK begin function __init__ self begin set pageIndex = 1 set user_agent = string Mozilla/4.0 (compatible; MSIE 5.5; Windows NT) set headers = dict string User-Agent user_agent set stories = lis...
# -*- coding:utf-8 -*- # https://cuiqingcai.com/990.html import urllib import urllib2 import re import json class QSBK: def __init__(self): self.pageIndex = 1 self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = {'User-Agent': self.user_agent} self.stories = [] self.enable = Fa...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import requests from bs4 import BeautifulSoup comment In[3]: set url = string https://scraping-for-beginner.herokuapp.com/ranking/ set res = get requests url comment In[46]: set soup = call BeautifulSoup text string html.parser comment In[47]: comment 観光...
#!/usr/bin/env python # coding: utf-8 # In[1]: import requests from bs4 import BeautifulSoup # In[3]: url = 'https://scraping-for-beginner.herokuapp.com/ranking/' res = requests.get(url) # In[46]: soup = BeautifulSoup(res.text, 'html.parser') # In[47]: # 観光地情報の取得 spots = soup.find_all('div', attrs={'clas...
Python
zaydzuhri_stack_edu_python
function rsa_decryption data type user=string begin if type == string server begin set server_private_key = call importKey read open string server_private.pem set plain = call new server_private_key set decrypt = call decrypt data set un_hex = call unhexlify decrypt set un_dec = decode un_hex return un_dec end else com...
def rsa_decryption(data, type, user=''): if type == 'server': server_private_key = RSA.importKey(open("server_private.pem").read()) plain = PKCS1_OAEP.new(server_private_key) decrypt = plain.decrypt(data) un_hex = binascii.unhexlify(decrypt) un_dec = un_hex.decode() ...
Python
nomic_cornstack_python_v1
function _deduce_security kwargs begin comment Security should be one of our valid strings set sec_translation = dict string wpa-psk WPA_PSK ; string none NONE ; string wpa-eap WPA_EAP if not get kwargs string securityType begin if get kwargs string psk and get kwargs string eapConfig begin raise call ConfigureArgsErro...
def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES: # Security should be one of our valid strings sec_translation = { 'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK, 'none': nmcli.SECURITY_TYPES.NONE, 'wpa-eap': nmcli.SECURITY_TYPES.WPA_EAP, } if not kwargs.get('securityType'): ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys from sklearn.ensemble import RandomForestClassifier import numpy as np import pickle as pickle import base64 import csv function CreateTestDataArray begin comment open the test train_data set set csv_test_object = reader open string ./test_clean.csv string rb set header = next co...
#!/usr/bin/env python import sys from sklearn.ensemble import RandomForestClassifier import numpy as np import pickle as pickle import base64 import csv def CreateTestDataArray(): #open the test train_data set csv_test_object = csv.reader(open('./test_clean.csv', 'rb')) header = csv_test_object.next() ...
Python
zaydzuhri_stack_edu_python
import numpy as np from diagnnose.activations.activation_reader import ActivationReader from diagnnose.typedefs.activations import ActivationName from diagnnose.typedefs.classifiers import DataDict from diagnnose.typedefs.corpus import Corpus class DataLoader begin string Reads in pickled activations that have been ext...
import numpy as np from diagnnose.activations.activation_reader import ActivationReader from diagnnose.typedefs.activations import ActivationName from diagnnose.typedefs.classifiers import DataDict from diagnnose.typedefs.corpus import Corpus class DataLoader: """ Reads in pickled activations that have been extr...
Python
zaydzuhri_stack_edu_python
function constituentReport self begin from armi.utils import iterables set rows = list list string Constituent string HMFrac string FuelFrac set columns = list - 1 call getHMMass call getFuelMass for base_ele in list string U string PU begin set total = sum list comprehension call getMass name for nuclide in bySymbol a...
def constituentReport(self): from armi.utils import iterables rows = [["Constituent", "HMFrac", "FuelFrac"]] columns = [-1, self.getHMMass(), self.getFuelMass()] for base_ele in ["U", "PU"]: total = sum( [self.getMass(nuclide.name) for nuclide in elements.by...
Python
nomic_cornstack_python_v1
function dimensionNames self begin string Returns a list with the dimension names of the underlying NCDF variable set nSubDims = length _subArrayShape set subArrayDims = list comprehension format string SubDim{} dimNr for dimNr in range nSubDims return list dimensions + tuple subArrayDims end function
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return list(self._ncVar.dimensions + tuple(subArrayDims))
Python
jtatman_500k
string Implemention of linked list for graphs class ll_node begin function __init__ self key begin set data = key set next = none set adj = none end function function print_ll self node=none end=string begin if node == none begin return end set item = node while item != none begin print data end=end set item = next end...
""" Implemention of linked list for graphs """ class ll_node: def __init__(self, key): self.data = key self.next = None self.adj = None def print_ll(self, node = None, end = '\n'): if node == None: return item = node while item != No...
Python
zaydzuhri_stack_edu_python
function bubble_sort arr begin set arr_len = length arr for i in range arr_len - 1 0 - 1 begin for j in range i begin if arr at j > arr at j + 1 begin set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j end end end return arr end function
def bubble_sort(arr): arr_len = len(arr) for i in range(arr_len - 1, 0, -1): for j in range(i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr
Python
nomic_cornstack_python_v1
function prep_file filename dialect key_cols temp_dir out_dir already_sorted already_uniq begin set dups_removed = 0 comment Sort the file if necessary if already_sorted begin if has_header begin call abort string Invalid config: already_sorted and has-header end set sorted_fn = filename end else if quoting == QUOTE_NO...
def prep_file(filename: str, dialect: csvhelper.Dialect, key_cols: List[int], temp_dir: str, out_dir: str, already_sorted: bool, already_uniq: bool) -> Tuple[str, int]: dups_removed = 0 # Sort the file if necessary if alrea...
Python
nomic_cornstack_python_v1
function create_cpix_xarray self dummy_value=none begin set ref_jd = jds at ref_band at ref_frame comment any radius will do set radius = radii at ref_band at 0 set d = data at ref_band at radius at ref_jd if dummy_value is none begin set cen = d at list string xcen string ycen end else begin set cen = call full shape ...
def create_cpix_xarray(self, dummy_value=None): ref_jd = self.jds[self.ref_band][self.ref_frame] radius = self.radii[self.ref_band][0] #any radius will do d = self.data[self.ref_band][radius][ref_jd] if dummy_value is None: cen = d[['xcen','ycen']] else: c...
Python
nomic_cornstack_python_v1
string This is a program using Simpsons rule to integrate the function x^4 - 2x+1 function function x begin return x ^ 4 - 2 * x + 1 end function set N = 10000 set a = 0.0 set b = 2.0 function simpsons f a b N begin set h = b - a / N set __sum__ = 0 set __sum__ = f dist a + f dist b for m in range 1 integer N / 2 begin...
""" This is a program using Simpsons rule to integrate the function x^4 - 2x+1 """ def function(x): return (x**4) - (2*x) + 1 N = 10000 a = 0.0 b = 2.0 def simpsons(f, a,b,N): h = (b-a)/N __sum__ = 0 __sum__ = f(a) + f(b) for m in range(1,int( N/2)): __sum__ += 4*f( a + ((2*m) -1)*h) ...
Python
zaydzuhri_stack_edu_python
import streamlit as st import datetime from business.control.src.manager import UserManager class Proxy extends UserManager begin function __init__ self logged users begin set __logged = logged set users = users end function function list_by_alphabet self begin if __logged begin set lista = list set lista = sorted key...
import streamlit as st import datetime from business.control.src.manager import UserManager class Proxy(UserManager): def __init__(self, logged, users): self.__logged = logged self.users = users def list_by_alphabet(self): if self.__logged: lista = [] ...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import requests import urllib.request as urllib2 import json import argparse import re function getSongsFromWeb download_list api_token download_dir begin with open download_list as file begin for song in file begin call getSongFromWeb strip song api_token download_dir end end end function...
from bs4 import BeautifulSoup import requests import urllib.request as urllib2 import json import argparse import re def getSongsFromWeb(download_list, api_token, download_dir): with open(download_list) as file: for song in file: getSongFromWeb(song.strip(), api_token, download_dir) def getSo...
Python
zaydzuhri_stack_edu_python
function print_zero_pattern n begin if n % 2 == 0 begin set n = n + 1 end for i in range n begin if i == n // 2 begin print string * * n end else begin set pattern = string * * n - 1 // 2 - absolute i - n // 2 set pattern = pattern + string _ * n - length pattern print pattern end end end function comment Test the func...
def print_zero_pattern(n): if n % 2 == 0: n += 1 for i in range(n): if i == n // 2: print("*" * n) else: pattern = "*" * ((n - 1) // 2 - abs(i - n // 2)) pattern += "_" * (n - len(pattern)) print(pattern) # Test the function n = 7 print_ze...
Python
jtatman_500k
for number in numbers begin set sum = sum + integer number end print sum
for number in numbers: sum += int(number) print(sum)
Python
zaydzuhri_stack_edu_python
function bin_search left right x begin while right - left > 1 begin set m = right + left // 2 if vid at m < x begin set left = m end else begin set right = m end end return vid at right end function for x in know begin if call bin_search 0 length vid - 1 x == x begin print string YES file=fout end else begin print stri...
def bin_search(left, right, x): while (right - left) > 1: m = (right + left) // 2 if vid[m] < x: left = m else: right = m return vid[right] for x in know: if bin_search(0, len(vid) - 1, x) == x: print('YES', file=fout) else: ...
Python
zaydzuhri_stack_edu_python
comment for objects function func1 **fruits begin print string orange in fruits print fruits end function call func1 banana=10 orange=20
# for objects def func1(**fruits): print('orange' in fruits) print(fruits) func1(banana=10, orange=20)
Python
zaydzuhri_stack_edu_python
from pathlib import Path import numpy as np from functools import partial from keras.preprocessing.image import img_to_array from osgeo import gdal_array from PIL import Image set repo_dir = parents at 1 set data_dir = repo_dir / string data set input_suffix = string input set pred_suffix = string pred set valid_suffix...
from pathlib import Path import numpy as np from functools import partial from keras.preprocessing.image import img_to_array from osgeo import gdal_array from PIL import Image repo_dir = Path(__file__).parents[1] data_dir = repo_dir / 'data' input_suffix = 'input' pred_suffix = 'pred' valid_suffix = 'valid' modis_p...
Python
zaydzuhri_stack_edu_python
function login_parameters self begin return get pulumi self string login_parameters end function
def login_parameters(self) -> Optional[Mapping[str, str]]: return pulumi.get(self, "login_parameters")
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import matplotlib.patches as mpatches from matplotlib.lines import Line2D import lib.GNIP as gnip from scipy import stats function read_excel_old filename begin set columns = dictionary zip list string sample...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import matplotlib.patches as mpatches from matplotlib.lines import Line2D import lib.GNIP as gnip from scipy import stats def read_excel_old(filename): columns = dict(zip(["sample name","d.18O"],[0,1])) d...
Python
zaydzuhri_stack_edu_python
comment requests 라이브러리 가져오기 import requests comment 크롤링을 쉽게 해주는 라이브러리 from bs4 import BeautifulSoup from pprint import pprint comment pymongo를 임포트 하기 from pymongo import MongoClient comment mongoDB는 27017 포트로 돌아갑니다. set client = call MongoClient string localhost 27017 comment 'dbsparta'라는 이름의 db를 만듭니다. set db = dbspart...
import requests #requests 라이브러리 가져오기 from bs4 import BeautifulSoup #크롤링을 쉽게 해주는 라이브러리 from pprint import pprint from pymongo import MongoClient # pymongo를 임포트 하기 client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다. db = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다. # 타겟 u...
Python
zaydzuhri_stack_edu_python
function path_condition self begin return call EAll call path_conditions end function
def path_condition(self) -> Exp: return EAll(self.path_conditions())
Python
nomic_cornstack_python_v1
comment this program demonstrates how a floating-point number can be displayed as currency comment Filename:dollar_display_AngelSR.py comment Date:02/02/2018 set monthlyPay = 5000.0 set annualPay = monthlyPay * 12 print string Your annual pay is $ format annualPay string ,.2f sep=string comment sep argument
#this program demonstrates how a floating-point number can be displayed as currency #Filename:dollar_display_AngelSR.py #Date:02/02/2018 monthlyPay= 5000.0 annualPay= monthlyPay * 12 print('Your annual pay is $', \ format(annualPay, ',.2f'), \ sep = ' ') #sep argument
Python
zaydzuhri_stack_edu_python
function get_value_list self volume_values time_period=12 begin set df = call DataFrame dict string volume volume_values set df at string prev_volume = call shift time_period set rocv_values = df at string volume - df at string prev_volume / df at string prev_volume * 100 set df = call DataFrame none return rocv_values...
def get_value_list(self, volume_values: pd.Series, time_period: int = 12): self.df = pd.DataFrame({ "volume": volume_values }) self.df["prev_volume"] = self.df["volume"].shift(time_period) rocv_values = (self.df["volume"] - self.df["prev_volume"] ) / se...
Python
nomic_cornstack_python_v1
function debug self begin return _debug end function
def debug(self): return self._debug
Python
nomic_cornstack_python_v1
for node in keys adjList begin set color at node = string W set parent at node = none end function dfs u begin set color at u = string G for v in adjList at u begin if color at v == string W begin set parent at v = u call dfs v end else if color at v == string G and parent at u != v begin print string Cycle Found: u st...
for node in adjList.keys(): color[node]="W" parent[node]=None def dfs(u): color[u]="G" for v in adjList[u]: if color[v]=="W": parent[v]=u dfs(v) elif color[v]=="G" and parent[u]!=v: print("Cycle Found: ", u, "to", v) color[u]="B" ...
Python
zaydzuhri_stack_edu_python
from gurobipy import * from vehicle import Vehicle from obstacle import Obstacle import matplotlib.pyplot as plt from matplotlib.patches import Polygon , Rectangle , Circle from grid_map import GridMap from grid_based_sweep_coverage_path_planner import planning from tools import define_polygon , polygon_contains_point ...
from gurobipy import * from vehicle import Vehicle from obstacle import Obstacle import matplotlib.pyplot as plt from matplotlib.patches import Polygon, Rectangle, Circle from grid_map import GridMap from grid_based_sweep_coverage_path_planner import planning from tools import define_polygon, polygon_contains_point imp...
Python
zaydzuhri_stack_edu_python
function normalize_minmax x min_r max_r begin set x_s = list comprehension i - min x / max x - min x for i in x return list comprehension i * max_r - min_r + min_r for i in x_s end function
def normalize_minmax(x, min_r, max_r): x_s = [(i - min(x))/(max(x) - min(x)) for i in x] return [i * (max_r - min_r) + min_r for i in x_s]
Python
nomic_cornstack_python_v1
function get_sex_value sex_dict begin set sex_values = call get_value_from_radio_button_list values sex_dict return call convert_sex_to_db_form sex_values at 0 sex_values at 1 end function
def get_sex_value(sex_dict): sex_values = get_value_from_radio_button_list(sex_dict.values()) return db_data_converter.convert_sex_to_db_form(sex_values[0], sex_values[1])
Python
nomic_cornstack_python_v1
import cx_Oracle import os comment 建立和数据库系统的连接 set conn = call connect string tdm8032/sa@orcl comment 获取操作游标 set cursor = call cursor execute cursor string select * from dps_user set one = call fetchone print one comment print ('1: id:%s,username:%s,password:%s' % one) comment 获取3条记录!!!注意游标已经到了第二条 set two = call fetchm...
import cx_Oracle import os #建立和数据库系统的连接 conn = cx_Oracle.connect('tdm8032/sa@orcl') #获取操作游标 cursor = conn.cursor() cursor.execute("""select * from dps_user""") one = cursor.fetchone() print (one) # print ('1: id:%s,username:%s,password:%s' % one) # 获取3条记录!!!注意游标已经到了第二条 two = cursor.fetchmany(3) print ('2 and 3:', tw...
Python
zaydzuhri_stack_edu_python
function test_stochatreat_output_treat_col treatments_dict begin set treatments_df = treatments_dict at string treatments assert string treat in columns msg string Treatment column is missing end function
def test_stochatreat_output_treat_col(treatments_dict): treatments_df = treatments_dict["treatments"] assert "treat" in treatments_df.columns, "Treatment column is missing"
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Mar 14 16:20:23 2019 @author: Giannis Meleziadis Compiled and run in python 3.7.1 This program finds a superpermutation from a sequence of numbers (1...n) where n is given. For n equal to [1-4] this program produces the minimum superpermutation that contains all the p...
# -*- coding: utf-8 -*- """ Created on Thu Mar 14 16:20:23 2019 @author: Giannis Meleziadis Compiled and run in python 3.7.1 This program finds a superpermutation from a sequence of numbers (1...n) where n is given. For n equal to [1-4] this program produces the minimum superpermutation that contains all ...
Python
zaydzuhri_stack_edu_python
function _get_ethernet_tag self begin return __ethernet_tag end function
def _get_ethernet_tag(self): return self.__ethernet_tag
Python
nomic_cornstack_python_v1
function test_many_services self begin with call DiagsCollector begin call calicoctl string apply -f - << EOF apiVersion: projectcalico.org/v3 kind: BGPConfiguration metadata: name: default spec: serviceClusterIPs: - cidr: fd00:10:96::/112 EOF comment Assert that a route to the service IP range is present. call retry_u...
def test_many_services(self): with DiagsCollector(): calicoctl("""apply -f - << EOF apiVersion: projectcalico.org/v3 kind: BGPConfiguration metadata: name: default spec: serviceClusterIPs: - cidr: fd00:10:96::/112 EOF """) # Assert that a route to the service IP range is present....
Python
nomic_cornstack_python_v1
set N = integer input set A_list = list map int split input print 1 / sum list comprehension 1 / a for a in A_list
N = int(input()) A_list = list(map(int, input().split())) print(1 / sum([1 / a for a in A_list]))
Python
zaydzuhri_stack_edu_python
import numpy as np import sympy as sym import matplotlib.pyplot as plt set xi = array list 100 200 300 600 400 500 set fi = array list - 160 - 35 - 4.2 21.3 9.0 16.9 comment PROCEDIMIENTO comment Tabla de Diferencias Divididas Avanzadas set titulo = list string i string xi string fi set n = length xi set ki = array ran...
import numpy as np import sympy as sym import matplotlib.pyplot as plt xi = np.array([100, 200, 300, 600, 400, 500]) fi = np.array([-160, -35, -4.2, 21.3, 9.0, 16.9]) # PROCEDIMIENTO # Tabla de Diferencias Divididas Avanzadas titulo = ['i ','xi ','fi '] n = len(xi) ki = np.arange(0,n,1) tabla = np.concatenate(([...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/evn python comment -*- coding:utf-8 -*- comment FileName HandleJson.py comment Author: HeyNiu comment Created Time: 20160728 string 处理json信息,用于后面response body字段比较(含字段类型) import json class HandleJson extends object begin function __init__ self begin set json_list = list set time_param_list = list end...
#!/usr/bin/evn python # -*- coding:utf-8 -*- # FileName HandleJson.py # Author: HeyNiu # Created Time: 20160728 """ 处理json信息,用于后面response body字段比较(含字段类型) """ import json class HandleJson(object): def __init__(self): self.json_list = [] self.time_param_list = [] @staticmethod def print_j...
Python
zaydzuhri_stack_edu_python
function edit self **kwargs begin string Edit a library (Note: agent is required). See :class:`~plexapi.library.Library` for example usage. Parameters: kwargs (dict): Dict of settings to edit. set part = string /library/sections/%s?%s % tuple key url encode kwargs query _server part method=put comment Reload this way s...
def edit(self, **kwargs): """ Edit a library (Note: agent is required). See :class:`~plexapi.library.Library` for example usage. Parameters: kwargs (dict): Dict of settings to edit. """ part = '/library/sections/%s?%s' % (self.key, urlencode(kwargs)) self._se...
Python
jtatman_500k
function __repr__ self begin return format string <Image img_id = {img_id} name = {img_name} found_id = {found_id} lost_id = {lost_id}> img_id=img_id found_id=found_id img_name=img_name lost_id=lost_id end function
def __repr__(self): return "<Image img_id = {img_id} name = {img_name} found_id = {found_id} lost_id = {lost_id}>".format(img_id=self.img_id, found_id=self.found_id, img_name=self.img_name, lost_id=self.lost_id)
Python
nomic_cornstack_python_v1
comment Problem Set 2, hangman.py comment Name: Eduard Tsakhlo comment Collaborators: comment Time spent: 4 hours 30 minutes comment Hangman Game comment ----------------------------------- comment Helper code import random from string import ascii_lowercase set WORDLIST_FILENAME = string words.txt function load_words ...
# Problem Set 2, hangman.py # Name: Eduard Tsakhlo # Collaborators: # Time spent: 4 hours 30 minutes # Hangman Game # ----------------------------------- # Helper code import random from string import ascii_lowercase WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python2 from itertools import permutations function check s begin for tuple i d in enumerate list 1 2 3 5 7 11 13 17 begin if integer join string s at slice i : i + 3 : % d != 0 begin return false end end return true end function set nums = list comprehension i for i in permutations string 0123456789...
#!/usr/bin/python2 from itertools import permutations def check(s): for i,d in enumerate([1,2,3,5,7,11,13,17]): if int(''.join(s[i:i+3]))%d != 0: return False return True nums = [i for i in permutations("0123456789") if i[0] != '0']
Python
zaydzuhri_stack_edu_python
function set_mock_return_value magic_mock return_value begin if __name__ == string AsyncMock begin comment Python 3.8 and above set return_value = return_value end else begin async function coroutine *args **kwargs begin return return_value end function set return_value = call coroutine end end function
def set_mock_return_value(magic_mock: MagicMock, return_value: t.Any): if magic_mock.__class__.__name__ == "AsyncMock": # Python 3.8 and above magic_mock.return_value = return_value else: async def coroutine(*args, **kwargs): return return_value magic_mock.return_va...
Python
nomic_cornstack_python_v1
from models import Profile import re class MainTest begin function __init__ self request begin set _request = request comment self.user = request.user.id set _data = none set _fields = list string name string phone string company string address string email string gender set __required = list string name string phone s...
from models import Profile import re class MainTest(): def __init__(self, request): self._request = request #self.user = request.user.id self._data = None self._fields = ['name','phone','company','address','email','gender'] self.__required = ['name','phone'] self.res...
Python
zaydzuhri_stack_edu_python
function run begin set myList = list string Ram string Hernán string Camila set myDict = dict string name string Ramdhei ; string lastname string López Arcila set super_list = list dict string name string Ramdhei ; string lastname string López Arcila dict string name string Laura ; string lastname string Quiceno Restre...
def run(): myList = ['Ram', 'Hernán', 'Camila'] myDict = {'name': 'Ramdhei', 'lastname': 'López Arcila'} super_list = [ {'name': 'Ramdhei', 'lastname': 'López Arcila'}, {'name': 'Laura', 'lastname': 'Quiceno Restrepo'}, {'name': 'Valeria', 'lastname': 'Salazar Cardona'} ] f...
Python
zaydzuhri_stack_edu_python
import time import Adafruit_BBIO.GPIO as GPIO comment Note: Use P9_22(UART2_RXD) as GPIO. comment Connect the Grove Button to UART Grove port of Beaglebone Green. comment GPIO P9_22 set Button = string P9_22 setup GPIO Button IN
import time import Adafruit_BBIO.GPIO as GPIO # Note: Use P9_22(UART2_RXD) as GPIO. # Connect the Grove Button to UART Grove port of Beaglebone Green. Button = "P9_22" # GPIO P9_22 GPIO.setup(Button, GPIO.IN)
Python
zaydzuhri_stack_edu_python
comment ITP1_10-A Distance set tuple x1 y1 x2 y2 = split input string set x1 = decimal x1 set y1 = decimal y1 set x2 = decimal x2 set y2 = decimal y2 print x1 - x2 ^ 2.0 + y1 - y2 ^ 2.0 ^ 0.5
#ITP1_10-A Distance x1,y1,x2,y2 = input().split(" ") x1=float(x1) y1=float(y1) x2=float(x2) y2=float(y2) print ( ((x1-x2)**2.0 + (y1-y2)**2.0 )**0.5)
Python
zaydzuhri_stack_edu_python
comment !179646VO import sys set dataIn = read stdin set data = split dataIn del dataIn set num = integer data at 0 set x = num * 2 set itemList = list
#!179646VO import sys dataIn = sys.stdin.read() data = dataIn.split() del dataIn num = int(data[0]) x = num*2 itemList = []
Python
zaydzuhri_stack_edu_python
import numpy as np comment Perform Thomas Algorithm function Thomas_Algo L D U B begin set n = length L set P = zeros n set Q = zeros n set P at 0 = D at 0 set Q at 0 = B at 0 for i in range 1 n begin set P at i = D at i - L at i * U at i - 1 / P at i - 1 end for i in range 1 n begin set Q at i = B at i - L at i * Q at...
import numpy as np def Thomas_Algo(L, D, U, B): #Perform Thomas Algorithm n = len(L) P = np.zeros(n) Q = np.zeros(n) P[0] = D[0] Q[0] = B[0] for i in range(1, n): P[i] = D[i] - ((L[i]*U[i-1])/P[i-1]) for i in range(1, n): Q[i] = B[i] - ((L[i]*Q[i-1])/...
Python
zaydzuhri_stack_edu_python
function process_tr tr begin set data = find all tr string td try begin set name_location = split text string @ set name = join string name_location at slice : 1 : set location = join string name_location at slice 1 : 2 : set date = text set genre = text set price_age = text set organizer = text set link = find tr s...
def process_tr(tr): data = tr.find_all('td') try: name_location = (data[1].text).split('@ ') name = ''.join(name_location[:1]) location = ''.join(name_location[1:2]) date = data[0].text genre = data[2].text price_age = data[3].text organizer = data[4].te...
Python
nomic_cornstack_python_v1
import badge import time function cls begin for x in range width begin for y in range height begin call pixel x y 0 end end show screen end function function update xold yold xnew ynew bright begin comment set the old pixel to dark call pixel xold yold 0 comment and the new one to light call pixel xnew ynew 10 show scr...
import badge import time def cls(): for x in range(screen.width): for y in range(screen.height): screen.pixel(x, y, 0) badge.show(screen) def update(xold, yold, xnew, ynew, bright): # set the old pixel to dark screen.pixel(xold, yold, 0) # and the new one to light screen....
Python
zaydzuhri_stack_edu_python
comment print(a) comment print(c) for i in range m begin set d = c at i // a at 0 set b at i = d for j in range n begin set c at i + j = c at i + j - d * a at j end end comment print(c) comment print(b) comment print() print *b[::-1]
#print(a) #print(c) for i in range(m): d=c[i]//a[0] b[i]=d for j in range(n): c[i+j]-=d*a[j] #print(c) #print(b) #print() print(*b[::-1])
Python
zaydzuhri_stack_edu_python
function samples self outputFile n=1 begin try begin set d = call File outputFile string r at string chain set X = array list comprehension d at i for i in zip *[np.random.randint(s, size=n) for s in d.shape[:2]] return tuple X call _predict X end except KeyError begin info string Warning! No existing sampler end end f...
def samples(self, outputFile, n=1): try: d = h5py.File(outputFile, 'r')['chain'] X = np.array([d[i] for i in zip(*[np.random.randint(s, size=n) for s in d.shape[:2]]) ]) return (X, self._predict(X)) except KeyError: logging.info('Warning! No existing samp...
Python
nomic_cornstack_python_v1
comment Perulangan / Pengulangan / Loop print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh print string Teguh comment increment itu penambahan 1 angka ke variabel set i = 1 set i = i + 1 print string ...
# Perulangan / Pengulangan / Loop print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') print('Teguh') # increment itu penambahan 1 angka ke variabel i = 1 i += 1 print('Hasil increment = ',i) # decrement itu pengurangan 1 angka ke vari...
Python
zaydzuhri_stack_edu_python
function whoAreYou self begin set tempDict = dict set tempDict at string Class = format string {0:15} __name__ + string from + join string list comprehension string base for base in __bases__ set tempDict at string Type = type set tempDict at string Name = name return tempDict end function
def whoAreYou(self): tempDict = {} tempDict['Class'] = '{0:15}'.format(self.__class__.__name__) +' from '+' '.join([str(base) for base in self.__class__.__bases__]) tempDict['Type' ] = self.type tempDict['Name' ] = self.name return tempDict
Python
nomic_cornstack_python_v1
for linha in tabuleiro begin print linha end
for linha in tabuleiro: print(linha)
Python
zaydzuhri_stack_edu_python
function test_teacher_change_when_to_show_feedback_for_unopened_hw_8056 self begin set test_updates at string name = string t1.16.029 + co_name at slice 4 : : set test_updates at string tags = list string t1 string t1.16 string t1.16.029 string 8056 set test_updates at string passed = false comment Test steps and ver...
def test_teacher_change_when_to_show_feedback_for_unopened_hw_8056(self): self.ps.test_updates['name'] = 't1.16.029' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.16', 't1.16.029', '8056'] self.ps.test_updates['passed'] = False # Tes...
Python
nomic_cornstack_python_v1
comment author: Ziming Guo comment time: 2020/4/4 string dmeo03: select tcp 服务端 tcp 套接字 IO 并发模型 思路分析: 1)将关注的IO放入到监控列表中中 2)当 IO 就绪的时候会通过 select 返回 3)遍历返回值列表,然后得知哪个 IO 就绪,再进行处理 from socket import * from select import select comment 创建监听套接字作为关注的IO comment 这个创建的监听套接字就是为了处理客户端的连接 set s = call socket call setsockopt SOL_SOCK...
# author: Ziming Guo # time: 2020/4/4 ''' dmeo03: select tcp 服务端 tcp 套接字 IO 并发模型 思路分析: 1)将关注的IO放入到监控列表中中 2)当 IO 就绪的时候会通过 select 返回 3)遍历返回值列表,然后得知哪个 IO 就绪,再进行处理 ''' from socket import * from select import select # 创建监听套接字作为关注的IO s = socket() # 这个创建的监听套接字就是为了处理客户端的连接 s.setsockopt(SOL_SOCKET...
Python
zaydzuhri_stack_edu_python
function train_and_evaluate config workdir begin set ds_info = info set num_train_examples = num_examples comment TODO(marcvanzee): I added this so we can do a test that does only 1 train comment step, but we should find a nicer way of doing this. if string num_train_steps in config begin set num_train_steps = num_trai...
def train_and_evaluate(config: ml_collections.ConfigDict, workdir: str): ds_info = tfds.builder(config.dataset_name).info num_train_examples = ds_info.splits[tfds.Split.TRAIN].num_examples # TODO(marcvanzee): I added this so we can do a test that does only 1 train # step, but we should find a nicer way of doing...
Python
nomic_cornstack_python_v1
from keras.models import Sequential import keras import sys from keras.preprocessing.image import ImageDataGenerator from keras.layers.core import Dense , Dropout , Activation from keras.layers import Conv2D , Flatten , MaxPooling2D , BatchNormalization from keras.utils import np_utils from math import floor import pan...
from keras.models import Sequential import keras import sys from keras.preprocessing.image import ImageDataGenerator from keras.layers.core import Dense, Dropout, Activation from keras.layers import Conv2D, Flatten, MaxPooling2D, BatchNormalization from keras.utils import np_utils from math import floor import pandas a...
Python
zaydzuhri_stack_edu_python
function verify self begin if string robot not in keys self begin raise exception string No Section 'robot' in RobotConfig end comment if "name" not in self["robot"]: comment raise Exception("No robot.name specified in RobotConfig") if string controller_file not in self at string robot begin raise exception string No r...
def verify(self): if "robot" not in self.keys(): raise Exception("No Section 'robot' in RobotConfig") # if "name" not in self["robot"]: # raise Exception("No robot.name specified in RobotConfig") if "controller_file" not in self['robot']: raise Exception("No r...
Python
nomic_cornstack_python_v1
function squarem init objective_fn update_fn max_iters tol par_tol=1e-08 max_step_updates=10 *args **kwargs begin set theta = init set obj = call objective_fn theta *args keyword kwargs for i in range max_iters begin set x1 = call update_fn theta *args keyword kwargs set r = x1 - theta if i == 0 and call objective_fn x...
def squarem(init, objective_fn, update_fn, max_iters, tol, par_tol=1e-8, max_step_updates=10, *args, **kwargs): theta = init obj = objective_fn(theta, *args, **kwargs) for i in range(max_iters): x1 = update_fn(theta, *args, **kwargs) r = x1 - theta if i == 0 and objective_fn(x1, *args, **kwargs) < obj...
Python
nomic_cornstack_python_v1
import itertools comment 练习1: 计算在4张牌中排列4中的可能性 from common.iterable_tools import IterableHelper set tuple_poker = tuple string 红桃3 string 黑桃2 string 梅花5 string 大王 set list_result = list permutations tuple_poker 4 print length list_result list_result comment 练习2:"012345",可以组成多少个不重复的5位偶数 comment list_result = list() comme...
import itertools # 练习1: 计算在4张牌中排列4中的可能性 from common.iterable_tools import IterableHelper tuple_poker = ("红桃3", "黑桃2", "梅花5", "大王") list_result = list(itertools.permutations(tuple_poker, 4)) print(len(list_result), list_result) # 练习2:"012345",可以组成多少个不重复的5位偶数 # list_result = list() # print(len(list_result), list_resu...
Python
zaydzuhri_stack_edu_python
function bank_transfer_payment_method_specific_output self begin return __bank_transfer_payment_method_specific_output end function
def bank_transfer_payment_method_specific_output(self): return self.__bank_transfer_payment_method_specific_output
Python
nomic_cornstack_python_v1
function dswap x y begin comment compute call blas_dswap data data comment and return {x} and {y} return tuple x y end function
def dswap(x, y): # compute gsl.blas_dswap(x.data, y.data) # and return {x} and {y} return x, y
Python
nomic_cornstack_python_v1
function insert conn tab fld val begin try begin set cur = call cursor set sql = string INSERT INTO + tab + string ( + fld + string ) VALUES( + val + string );COMMIT; execute cur sql close cur end except tuple Exception DatabaseError as error begin print error end end function
def insert(conn,tab,fld,val): try: cur = conn.cursor() sql = "INSERT INTO " + tab + "(" + fld + ") VALUES(" + val + ");COMMIT;" cur.execute(sql) cur.close() except (Exception,pyodbc.DatabaseError) as error: print(error)
Python
nomic_cornstack_python_v1
import sys from collections import defaultdict import torch import dlc_practical_prologue as prologue from network import NaiveNet , SharedWeightNet , BenchmarkNet from helpers import train_model , compute_accuracy , bootstrapping from generate_plot import performance_plot set num_samples = 1000 comment Change this par...
import sys from collections import defaultdict import torch import dlc_practical_prologue as prologue from network import NaiveNet, SharedWeightNet, BenchmarkNet from helpers import train_model, compute_accuracy, bootstrapping from generate_plot import performance_plot num_samples = 1000 # Change this parameter to ...
Python
zaydzuhri_stack_edu_python
function _generate_baselining_job_name self job_name=none begin if job_name is not none begin return job_name end if base_job_name begin set base_name = base_job_name end else begin set base_name = _SUGGESTION_JOB_BASE_NAME end return call name_from_base base=base_name end function
def _generate_baselining_job_name(self, job_name=None): if job_name is not None: return job_name if self.base_job_name: base_name = self.base_job_name else: base_name = _SUGGESTION_JOB_BASE_NAME return name_from_base(base=base_name)
Python
nomic_cornstack_python_v1
function to_json value depth=0 **params begin comment TODO: support cycle/circular references (include a list of processed keys) if value is none or is instance value SIMPLE_TYPES begin return value end else if is instance value list begin return list comprehension to json invalue depth=depth keyword params for invalue...
def to_json(value, depth=0, **params): # TODO: support cycle/circular references (include a list of processed keys) if value is None or isinstance(value, SIMPLE_TYPES): return value elif isinstance(value, list): return [to_json(invalue, depth=depth, **params) for invalue in value] ...
Python
nomic_cornstack_python_v1
function is_other self begin return _tag == string other end function
def is_other(self): return self._tag == 'other'
Python
nomic_cornstack_python_v1
function test2SetToolProperties self begin from AthExHelloWorld.AthExHelloWorldConf import HelloAlg from AthExHelloWorld.AthExHelloWorldConf import HelloTool set HelloWorld = call HelloAlg string HelloWorld set msg1 = string A Private Message! set MyPrivateHelloTool = call HelloTool string HelloTool set MyMessage = msg...
def test2SetToolProperties( self ): from AthExHelloWorld.AthExHelloWorldConf import HelloAlg from AthExHelloWorld.AthExHelloWorldConf import HelloTool HelloWorld = HelloAlg( 'HelloWorld' ) msg1 = "A Private Message!" HelloWorld.MyPrivateHelloTool = HelloTool( "HelloTool" ) HelloW...
Python
nomic_cornstack_python_v1
function close self begin comment don't try to compute cycles if the associated message is disabled if call is_message_enabled string cyclic-import begin for cycle in call get_cycles import_graph begin call add_message string cyclic-import args=join string -> cycle end end end function
def close(self): # don't try to compute cycles if the associated message is disabled if self.linter.is_message_enabled('cyclic-import'): for cycle in get_cycles(self.import_graph): self.add_message('cyclic-import', args=' -> '.join(cycle))
Python
nomic_cornstack_python_v1
function classifyOne self query_row neigbor_thres=none max_diff=0 min_maj=1 begin set dist_f = _dist_f set distances = list comprehension call dist_f query_row std_row for std_row in std_rows comment nn_idxs = nn_f(distances) set nn_lineages = std_lineages at nn_idxs comment result_lineage = lineage_reduce_f(nn_lineage...
def classifyOne(self, query_row, neigbor_thres=None, max_diff=0, min_maj=1): dist_f = self._dist_f distances = [dist_f(query_row, std_row) for std_row in std_rows] #nn_idxs = nn_f(distances) nn_lineages = std_lineages[nn_idxs] #result_lineage = lineage...
Python
nomic_cornstack_python_v1
function simxGetDialogResult clientID dialogHandle operationMode begin string Please have a look at the function description/documentation in the V-REP user manual set result = call c_int return tuple call c_GetDialogResult clientID dialogHandle call byref result operationMode value end function
def simxGetDialogResult(clientID, dialogHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' result = ct.c_int() return c_GetDialogResult(clientID, dialogHandle, ct.byref(result), operationMode), result.value
Python
jtatman_500k
function distinguish modhash cookie name begin set dist_data = dict string api_type string json ; string how string yes ; string id name ; string uh modhash set request = post reddit_url + string api/distinguish data=dist_data cookies=cookie set thread_r = json request at string json if length thread_r at string errors...
def distinguish(modhash, cookie, name): dist_data = {'api_type': 'json', 'how': 'yes', 'id': name, 'uh': modhash} request = session.post(reddit_url + 'api/distinguish', data=dist_data, cookies=cookie) thread_r = request.json()['json'] if len(thread_r['errors']) > 0: debug_printer.pprint(thread_...
Python
nomic_cornstack_python_v1
function list_active_customers begin return count where is_active end function
def list_active_customers(): return Customer.select().where(Customer.is_active).count()
Python
nomic_cornstack_python_v1
comment class C2F(float): comment def __init__(self,x): comment self.x = x comment print("%f" % (self.x*1.8+32)) comment class C2F(float): comment def __new__(cls,arg=0.0): comment return float.__new__(cls,arg*1.8+32)
#class C2F(float): # def __init__(self,x): # self.x = x # print("%f" % (self.x*1.8+32)) #class C2F(float): # def __new__(cls,arg=0.0): # return float.__new__(cls,arg*1.8+32)
Python
zaydzuhri_stack_edu_python
comment content based filtering from moviedock import app , db from moviedock.models import User , Movie , Reviews , Recommendations import pandas as pd import numpy as np import operator from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer set bag_of_words ...
#content based filtering from moviedock import app, db from moviedock.models import User, Movie, Reviews, Recommendations import pandas as pd import numpy as np import operator from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer bag_of_words = pd.read_csv('...
Python
zaydzuhri_stack_edu_python