code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Solution extends object begin function maxUniqueSplit self s begin string :type s: str :rtype: int set res = 1 set seen = set function dfs s i begin if i == length s begin set res = max res length seen comment print(seen) return end for j in range i length s begin if s at slice i : j + 1 : not in seen begin add ...
class Solution(object): def maxUniqueSplit(self, s): """ :type s: str :rtype: int """ self.res = 1 seen = set() def dfs(s, i): if i == len(s): self.res = max(self.res, len(seen)) #print(seen) ...
Python
zaydzuhri_stack_edu_python
import pandas as pd set excel_workbook = string toclean.xlsx set sheet1 = call read_excel excel_workbook print head sheet1 10 comment TASK 1) CREATE SEPERATE LISTS(COLUMNS) FOR FIRST NAME AND LAST NAME set first_name_list = list set last_name_list = list comment FOR LOOP - FOR EVERY ENTRY SEPERATE FIRST NAME AND LAST...
import pandas as pd excel_workbook = 'toclean.xlsx' sheet1 = pd.read_excel(excel_workbook) print(sheet1.head(10)) ## TASK 1) CREATE SEPERATE LISTS(COLUMNS) FOR FIRST NAME AND LAST NAME first_name_list =[] last_name_list =[] # FOR LOOP - FOR EVERY ENTRY SEPERATE FIRST NAME AND LAST N...
Python
zaydzuhri_stack_edu_python
import folium from geopy.geocoders import ArcGIS function find_location place begin string :param place: a place where film was made/produced :return: latitude and longitude set geolocator = call ArcGIS timeout=10 set location = call geocode place set lat = latitude set long = longitude return tuple lat long end functi...
import folium from geopy.geocoders import ArcGIS def find_location(place): ''' :param place: a place where film was made/produced :return: latitude and longitude ''' geolocator = ArcGIS(timeout=10) location = geolocator.geocode(place) lat = location.latitude long = location.longitude ...
Python
zaydzuhri_stack_edu_python
function encode self begin if not call is_valid begin raise call AftlError string Invalid structure for TrillianLogRootDescriptor. end set expected_format_string = format string {}{}s{}{}s FORMAT_STRING_PART_1 root_hash_size FORMAT_STRING_PART_2 at slice 1 : : metadata_size return call pack expected_format_string ver...
def encode(self): if not self.is_valid(): raise AftlError('Invalid structure for TrillianLogRootDescriptor.') expected_format_string = '{}{}s{}{}s'.format( self.FORMAT_STRING_PART_1, self.root_hash_size, self.FORMAT_STRING_PART_2[1:], self.metadata_size) return struct...
Python
nomic_cornstack_python_v1
import sys set dictionary = string ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz set dictionary = list dictionary function main begin for line in stdin begin set words = split line string set words at 3 = words at 3 at slice : - 1 : set outline = string set legal = true set count = 0 for word in words begin i...
import sys dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" dictionary = list(dictionary) def main(): for line in sys.stdin: words = line.split("\t") words[3] = words[3][:-1] outline = "" legal = True count = 0 for word in words: if al...
Python
zaydzuhri_stack_edu_python
string Proxy server for local state. Allows the local state to be accessed remotely. The local object should have an internal variable called "lock" that prevents concurrent accesses of local variables. Created on Nov 14, 2012 @author: danny import socket , threading , traceback , sys , os from lib.session_sock import ...
''' Proxy server for local state. Allows the local state to be accessed remotely. The local object should have an internal variable called "lock" that prevents concurrent accesses of local variables. Created on Nov 14, 2012 @author: danny ''' import socket, threading, traceback, sys, os from lib.session_sock import ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python string This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 import sys from time import time append path string ../tools/ from email_preprocess import preprocess comment features_tr...
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import prep...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from math import sqrt , e , asin , acos , sin , cos , atan , pi import matplotlib.pyplot as plt from scipy.interpolate import KroghInterpolator comment CONSTANTS set L1 = 0.275 set L2 = 0.29 set H = 0.1404 set G = 9.8 set Zch = 0.098 set W = 0.22 comment Adjustable variables set S = 0.28 se...
#!/usr/bin/env python from math import sqrt, e, asin, acos, sin, cos, atan, pi import matplotlib.pyplot as plt from scipy.interpolate import KroghInterpolator # CONSTANTS L1 = 0.275 L2 = 0.290 H = 0.1404 G = 9.8 Zch = 0.098 W = 0.220 # Adjustable variables S = 0.28 T = 0.8 L = 0.52 Hm = 0.08 # Calculate some usef...
Python
zaydzuhri_stack_edu_python
function calculate_weighted_average numbers weights begin if length numbers == 0 or length weights == 0 begin return 0 end set total = 0 set total_weights = 0 for i in range length numbers begin if weights at i <= 0 begin continue end set total = total + numbers at i * weights at i set total_weights = total_weights + w...
def calculate_weighted_average(numbers, weights): if len(numbers) == 0 or len(weights) == 0: return 0 total = 0 total_weights = 0 for i in range(len(numbers)): if weights[i] <= 0: continue total += numbers[i] * weights[i] total_weights += weights[i] if...
Python
jtatman_500k
function getNextFailure self begin return call getNextEvent call __getMtbf__ end function
def getNextFailure(self): return super().getNextEvent(self.__system__.__getMtbf__())
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string File: scanner.py Created on Tue Mar 12 10:10:45 2019 @author: wangchx class Scanner extends object begin function __init__ self sourceStr begin set _handledStr = split sourceStr set _size = length _handledStr set _index = 0 end function function hasNext self begin return _index < _s...
# -*- coding: utf-8 -*- """ File: scanner.py Created on Tue Mar 12 10:10:45 2019 @author: wangchx """ class Scanner(object): def __init__(self, sourceStr): self._handledStr = sourceStr.split() self._size = len(self._handledStr) self._index = 0 def hasNext(self): r...
Python
zaydzuhri_stack_edu_python
function k_cr_n self T begin set T_dim = Delta_T * T + T_ref set delta_k_cr = E_n ^ m_cr_n * l_cr_n_0 ^ m_cr_n / 2 - 1 return call FunctionParameter string Negative electrode cracking rate dict string Temperature [K] T_dim * delta_k_cr end function
def k_cr_n(self, T): T_dim = self.Delta_T * T + self.T_ref delta_k_cr = self.E_n ** self.m_cr_n * self.l_cr_n_0 ** (self.m_cr_n / 2 - 1) return ( pybamm.FunctionParameter( "Negative electrode cracking rate", {"Temperature [K]": T_dim} ) * delta...
Python
nomic_cornstack_python_v1
function set_parameters self parameters begin if type parameters is not list begin raise call ValueError string Parameters is not a list end call set_config string $params parameters end function
def set_parameters(self, parameters): if type(parameters) is not list: raise ValueError("Parameters is not a list") self.set_config("$params", parameters)
Python
nomic_cornstack_python_v1
function getTextArround self img left=true right=false below=false above=false deviationPixel=50 similar=0.7 description=string unknown mainImg=none begin set action = ACTION_GET_TEXT set actionId = call getActionId comment generate rando name set imgName = string %s % uuid 4 set mainImgName = string %s % uuid 4 set co...
def getTextArround(self, img, left=True, right=False, below=False, above=False, deviationPixel=50, similar=0.70, description='unknown', mainImg=None): action = ACTION_GET_TEXT actionId = self.getActionId() #generate rando nam...
Python
nomic_cornstack_python_v1
class Person begin set total_count = 0 set objects = dict function __init__ self name age address begin if not is instance name str begin raise call ValueError string Name must be a string end if not is instance age int or age <= 0 begin raise call ValueError string Age must be a positive integer end if not is instanc...
class Person: total_count = 0 objects = {} def __init__(self, name, age, address): if not isinstance(name, str): raise ValueError("Name must be a string") if not isinstance(age, int) or age <= 0: raise ValueError("Age must be a positive integer") if not isins...
Python
greatdarklord_python_dataset
function age self begin comment NOTE: `created_at` field is aligned to UTC timezone. set age = integer call total_seconds return age end function
def age(self): # NOTE: `created_at` field is aligned to UTC timezone. age = int((datetime.utcnow() - self.created_at).total_seconds()) return age
Python
nomic_cornstack_python_v1
function declared_encoding self begin set content_type = get self string Content-Type string return call http_content_type_encoding content_type end function
def declared_encoding(self) -> Optional[str]: content_type = self.get("Content-Type", "") return http_content_type_encoding(content_type)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment SETMODE 777 comment ----------------------------------------------------------------------------------------# comment ------------------------------------------------------------------------------ HEADER --# string :author: Chris Jennings :synopsis: A one line summary of what this m...
#!/usr/bin/env python #SETMODE 777 #----------------------------------------------------------------------------------------# #------------------------------------------------------------------------------ HEADER --# """ :author: Chris Jennings :synopsis: A one line summary of what this module does. :descri...
Python
zaydzuhri_stack_edu_python
function encrypt message begin set chars = string ABCDEFGHIJKLMNOPQRSTUVWXYZ set encrypted = string for char in message begin if char in chars begin set char_index = find chars char set new_char_index = char_index + 13 % 26 set encrypted = encrypted + chars at new_char_index end else begin set encrypted = encrypted + ...
def encrypt(message): chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' encrypted = '' for char in message: if char in chars: char_index = chars.find(char) new_char_index = (char_index + 13) % 26 encrypted += chars[new_char_index] else: encrypted += char ...
Python
jtatman_500k
comment 이미지 붙여넣기 import cv2 import face_recognition from PIL import Image , ImageDraw from matplotlib import pyplot as plt comment face_image_path = 'data/without_mask/0.jpg' set face_image_path = string ../Photo/person 1.jpg set mask_image_path = string ../data/mask.png set person = face_image_path set image = call im...
#이미지 붙여넣기 import cv2 import face_recognition from PIL import Image, ImageDraw from matplotlib import pyplot as plt #face_image_path = 'data/without_mask/0.jpg' face_image_path = '../Photo/person 1.jpg' mask_image_path = '../data/mask.png' person = face_image_path image = cv2.imread(person, cv2.IMREAD_UNCHANGED) gray...
Python
zaydzuhri_stack_edu_python
function test_connection_action self device begin if get devices_dict at device string Visa_Resource begin set success = call verify_ID devices_dict at device at string Visa_Resource get devices_dict at device string device_IDN_query string *IDN? if not success begin error format string Connection test failed with devi...
def test_connection_action(self, device): if self.variables.devices_dict[device].get("Visa_Resource"): success = self.variables.vcw.verify_ID( self.variables.devices_dict[device]["Visa_Resource"], self.variables.devices_dict[device].get("device_IDN_query", "*IDN?"), ...
Python
nomic_cornstack_python_v1
function save self args=none begin string Save prefix to NIPAP. If the object represents a new prefix unknown to NIPAP (attribute `id` is `None`) this function maps to the function :py:func:`nipap.backend.Nipap.add_prefix` in the backend, used to create a new prefix. Otherwise it maps to the function :py:func:`nipap.ba...
def save(self, args=None): """ Save prefix to NIPAP. If the object represents a new prefix unknown to NIPAP (attribute `id` is `None`) this function maps to the function :py:func:`nipap.backend.Nipap.add_prefix` in the backend, used to create a new prefix. Otherw...
Python
jtatman_500k
import Automato class AFN extends Automato begin function __init__ self sigma estados delta estadoInicial estadosFinais begin for tuple i j in enumerate delta begin for t in delta at j begin if t at 0 == none begin raise call ValueError string Indeterminismo end end end call __init__ sigma estados delta estadoInicial e...
import Automato class AFN(Automato.Automato): def __init__(self, sigma, estados, delta, estadoInicial, estadosFinais): for i, j in enumerate(delta): for t in delta[j]: if t[0] == None: raise ValueError("Indeterminismo") super().__init__(sigma, est...
Python
zaydzuhri_stack_edu_python
import math function find_lambda begin comment Step 2: Define magnitudes of the vectors set magnitude_a = 2 set magnitude_b = 1 comment Step 3: Define the angle in degrees and convert to radians set angle_degrees = 60 set angle_radians = angle_degrees * pi / 180 comment Step 4: Calculate cosine of the angle set cos_ang...
import math def find_lambda(): # Step 2: Define magnitudes of the vectors magnitude_a = 2 magnitude_b = 1 # Step 3: Define the angle in degrees and convert to radians angle_degrees = 60 angle_radians = angle_degrees * (math.pi / 180) # Step 4: Calculate cosine of the angle cos...
Python
dbands_pythonMath
function __init__ self full_name begin set _full_name = full_name set _account_number = call create_acct set _balance = 0 append account_numbers _account_number end function
def __init__(self, full_name): self._full_name = full_name self._account_number = create_acct() self._balance = 0 account_numbers.append(self._account_number)
Python
nomic_cornstack_python_v1
function get_techniques_used_by_software_data software reference_list next_reference_number begin if lower get software string type == string malware begin set techniques_used_by_software = get techniques_used_by_malware software at string id end else begin set techniques_used_by_software = get techniques_used_by_tools...
def get_techniques_used_by_software_data(software, reference_list, next_reference_number): if software.get('type').lower() == "malware": techniques_used_by_software = config.techniques_used_by_malware.get(software['id']) else: techniques_used_by_software = config.techniques_used_by_tools.get(so...
Python
nomic_cornstack_python_v1
function unlock_deadlocks self begin set deadlocked = true while deadlocked begin set youngest_transaction_in_cycle = call identify_youngest_transaction_in_cycle if youngest_transaction_in_cycle is none begin set deadlocked = false end else begin call abort_transaction youngest_transaction_in_cycle string deadlock end ...
def unlock_deadlocks(self): deadlocked = True while deadlocked: youngest_transaction_in_cycle = self.identify_youngest_transaction_in_cycle() if youngest_transaction_in_cycle is None: deadlocked = False else: self.abort_transaction(youn...
Python
nomic_cornstack_python_v1
function rolesNotNull self begin try begin import json set rawRoles = call roles set rolesJson = loads rawRoles comment search json for the device with id then return the device for device in rolesJson begin comment print device if device at string master == string none begin warn string Device has no master: + string ...
def rolesNotNull( self ): try: import json rawRoles = self.roles() rolesJson = json.loads( rawRoles ) # search json for the device with id then return the device for device in rolesJson: # print device if device[ 'master...
Python
nomic_cornstack_python_v1
function test_save_dataframe_excel_xml self begin with temporary directory as tmp begin set name = string test.xlsx set fp = join path tmp name set df = call DataFrame randn 3 3 columns=list string ABC call save_dataframe df fp assert exists path fp end end function
def test_save_dataframe_excel_xml(self): with TemporaryDirectory() as tmp: name = 'test.xlsx' fp = os.path.join(tmp, name) df = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC')) save_dataframe(df, fp) assert os.path.exists(fp)
Python
nomic_cornstack_python_v1
from tkinter import * import os from PIL import ImageTk , Image import requests import tw as tww set pic = list string happy.resized.png string negativ.resized.png string neutral.resized.png function get_weather entry begin set label at string text = call treat entry call get_picture call treat entry end function funct...
from tkinter import * import os from PIL import ImageTk, Image import requests import tw as tww pic=["happy.resized.png","negativ.resized.png","neutral.resized.png"] def get_weather(entry): label['text'] = tww.treat(entry) get_picture(tww.treat(entry)) def get_picture(text): if text=="positive" or text=="wposit...
Python
zaydzuhri_stack_edu_python
comment title: minimum-distance-between-bst-nodes comment detail: https://leetcode.com/submissions/detail/412253541/ comment datetime: Fri Oct 23 21:24:44 2020 comment runtime: 32 ms comment memory: 14.3 MB comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, r...
# title: minimum-distance-between-bst-nodes # detail: https://leetcode.com/submissions/detail/412253541/ # datetime: Fri Oct 23 21:24:44 2020 # runtime: 32 ms # memory: 14.3 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # ...
Python
zaydzuhri_stack_edu_python
string middle 2021-12-22 贪心 (看图理解) https://programmercarl.com/0763.%E5%88%92%E5%88%86%E5%AD%97%E6%AF%8D%E5%8C%BA%E9%97%B4.html#%E6%80%9D%E8%B7%AF 题目:把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中 思路:在遍历的过程中相当于是要找每一个字母的边界,如果找到之前遍历过的所有字母的最远边界,说明这个边界就是分割点了。此时前面出现过所有字母,最远也就到这个边界了。 1、统计每一个字符最后出现的位置 2、从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下...
""" middle 2021-12-22 贪心 (看图理解) https://programmercarl.com/0763.%E5%88%92%E5%88%86%E5%AD%97%E6%AF%8D%E5%8C%BA%E9%97%B4.html#%E6%80%9D%E8%B7%AF 题目:把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中 思路:在遍历的过程中相当于是要找每一个字母的边界,如果找到之前遍历过的所有字母的最远边界,说明这个边界就是分割点了。此时前面出现过所有字母,最远也就到这个边界了。 1、统计每一个字符最后出现的位置 2、从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下标相等...
Python
zaydzuhri_stack_edu_python
async function test_execute hass light_only report_state on brightness value begin await call async_setup_component hass string homeassistant dict await call async_setup_component hass string light dict string light dict string platform string demo await call async_block_till_done await call async_call string light str...
async def test_execute( hass: HomeAssistant, light_only, report_state, on, brightness, value ) -> None: await async_setup_component(hass, "homeassistant", {}) await async_setup_component(hass, "light", {"light": {"platform": "demo"}}) await hass.async_block_till_done() await hass.services.async_cal...
Python
nomic_cornstack_python_v1
function recursively_get_files_contents base strip_base begin set ret = call __recursively_get_files_contents base string tests.utils if __import_facebook_utils begin update ret call __recursively_get_files_contents base string tests.facebook.utils end if strip_base begin comment + 1 is for the / set ret = dictionary c...
def recursively_get_files_contents(base, strip_base): ret = __recursively_get_files_contents(base, "tests.utils") if __import_facebook_utils: ret.update(__recursively_get_files_contents(base, "tests.facebook.utils")) if strip_base: # + 1 is for the / ret = {path[len(base) + 1 :]: ret...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np from matplotlib import pyplot as plt set img = call imread string smarties.png IMREAD_GRAYSCALE set tuple _ mask = call threshold img 220 255 THRESH_BINARY_INV comment If we use [5,5] for rectangle it will increse the size of balls in diagram set kernal = ones list 2 2 uint8 comment Iterat...
import cv2 import numpy as np from matplotlib import pyplot as plt img=cv2.imread('smarties.png',cv2.IMREAD_GRAYSCALE) _,mask=cv2.threshold(img,220,255,cv2.THRESH_BINARY_INV) kernal=np.ones([2,2],np.uint8) #If we use [5,5] for rectangle it will increse the size of balls in diagram dilation=cv2.dila...
Python
zaydzuhri_stack_edu_python
string EXERCISE: GridSearchCV with Stack Overflow competition data import pandas as pd comment define a function to create features function make_features filename begin set df = read csv filename index_col=0 rename columns=dict string OwnerUndeletedAnswerCountAtPostTime string Answers inplace=true set df at string Tit...
''' EXERCISE: GridSearchCV with Stack Overflow competition data ''' import pandas as pd # define a function to create features def make_features(filename): df = pd.read_csv(filename, index_col=0) df.rename(columns={'OwnerUndeletedAnswerCountAtPostTime':'Answers'}, inplace=True) df['TitleLength'] = df.Titl...
Python
zaydzuhri_stack_edu_python
function save self key value begin if key not in memory_cache begin set memory_cache at key = list end append memory_cache at key value end function
def save(self, key: str, value: DataNodeStatus): if key not in self.memory_cache: self.memory_cache[key] = [] self.memory_cache[key].append(value)
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment Itamar da Silva Farias 115210021 comment Programação I set quantidade_notas = integer call raw_input set soma = 0 set final = 0 set soma_final = 0 set total = 0.0 for x in range quantidade_notas begin set nota = decimal call raw_input if nota >= 4.0 and nota < 7.0 begin set final = final +...
# coding: utf-8 # Itamar da Silva Farias 115210021 # Programação I quantidade_notas = int(raw_input()) soma = 0 final = 0 soma_final = 0 total = 0.0 for x in range(quantidade_notas): nota = float(raw_input()) if nota >= 4.0 and nota < 7.0: final += 1 soma_final += nota total += nota percentual = (float(final...
Python
zaydzuhri_stack_edu_python
function to_map self begin return dict string id id ; string name name ; string last_name last_name ; string birth_date call parse_datetime_to_str birth_date ; string telephones list comprehension call to_map for telephone in telephones ; string addresses list comprehension call to_map for address in addresses end func...
def to_map(self): return { 'id':self.id ,'name':self.name ,'last_name':self.last_name ,'birth_date':utilsattr.parse_datetime_to_str(self.birth_date) ,'telephones':[telephone.to_map() for telephone in self.telephones] ,'addresses':[address.to_map() for address in self.addresses] }
Python
nomic_cornstack_python_v1
from intro_help_defs import directions from room_def import Room class Navigator begin string Navigator class handles taking and sanitizing user input, and delegating input function __init__ self begin comment error responses set invalid = string That's not a valid option. comment navigation fail responses set prompt =...
from intro_help_defs import directions from room_def import Room class Navigator: """ Navigator class handles taking and sanitizing user input, and delegating input """ def __init__(self): # error responses self.invalid = "That's not a valid option." # navigation fail response...
Python
zaydzuhri_stack_edu_python
import socket comment Message to send to the server from the client is defined by user input set message = input string Enter Message to send to Server: comment The message is then encoded set modifiedMessage = encode message string utf8 comment IP addresss and local port that will be used for communications set IPaddr...
import socket # Message to send to the server from the client is defined by user input message = input("Enter Message to send to Server: ") # The message is then encoded modifiedMessage = message.encode("utf8") # IP addresss and local port that will be used for communications IPaddress = "127.0.0.1"...
Python
zaydzuhri_stack_edu_python
function _retrieve_profile_scores self soup begin set placement_history = find soup string div dict string class string profile__placements assert placement_history is not none return placement_history end function
def _retrieve_profile_scores(self, soup): placement_history = soup.find("div", {"class": "profile__placements"}) assert placement_history is not None return placement_history
Python
nomic_cornstack_python_v1
string gramatika from analizator.zajednicki.produkcija import Produkcija class Gramatika begin function __init__ self nezavrsni_znakovi zavrsni_znakovi pocetni_nezavrsni produkcije begin comment tipovi definirani u parseru comment skup stringova set nezavrsni_znakovi = nezavrsni_znakovi comment skup stringova set zavrs...
'''gramatika''' from analizator.zajednicki.produkcija import Produkcija class Gramatika: def __init__( self, nezavrsni_znakovi, zavrsni_znakovi, pocetni_nezavrsni, produkcije ): # tipovi definirani u parseru self.nezavrsni_znakovi = nezavrsni_znakovi # skup stringova...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2.7 comment -*- coding: utf-8 -*- string Propagation routines Author(s): Sean Henely Language: Python 2.x Modified: 29 June 2013 Provides routines for state propagation. Functions: KeplerPropagate -- Kepler propagation EphemerisPropagate -- Ephemeris propagation string Change log: Date Autho...
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """Propagation routines Author(s): Sean Henely Language: Python 2.x Modified: 29 June 2013 Provides routines for state propagation. Functions: KeplerPropagate -- Kepler propagation EphemerisPropagate -- Ephemeris propagation """ """Change log: ...
Python
zaydzuhri_stack_edu_python
function _rectify self path begin if path is none or path == string begin set path = string / end if path == string / begin return path end if not path at 0 == string / begin set path = string / + path end if path at slice - 1 : : == string / begin set path = path at slice : - 1 : end return path end function
def _rectify(self, path): if path is None or path == '': path = '/' if path == '/': return path if not path[0] == '/': path = '/' + path if path[-1:] == '/': path = path[:-1] return path
Python
nomic_cornstack_python_v1
function __str__ self begin set s = list append s string device: idcode 0x%08x ir length %d bits - %s % tuple idcode irlen name if ndevs > 1 begin append s string chain: %d devices, %d before %d after % tuple ndevs ndevs_before ndevs_after append s string chain: %d ir bits total, %d before %d after % tuple irlen_total...
def __str__(self): s = [] s.append('device: idcode 0x%08x ir length %d bits - %s' % (self.idcode, self.irlen, self.name)) if self.ndevs > 1: s.append('chain: %d devices, %d before %d after' % (self.ndevs, self.ndevs_before, self.ndevs_after)) s.append('chain: %d ir bits t...
Python
nomic_cornstack_python_v1
string This module contains the API class that allows components to receive and send messages through the network using a variety of middlewares import logging from fmlib.api.rest.interface import RESTInterface from fmlib.api.ros import ROSInterface from fmlib.api.zyre import ZyreInterface from fmlib.utils.messages imp...
"""This module contains the API class that allows components to receive and send messages through the network using a variety of middlewares """ import logging from fmlib.api.rest.interface import RESTInterface from fmlib.api.ros import ROSInterface from fmlib.api.zyre import ZyreInterface from fmlib.utils.messages i...
Python
zaydzuhri_stack_edu_python
function _l self batch_size hidden_state begin comment masks for epsilon greedy exploration & regular sampling comment [batch_size, 1] set p = call random_uniform list batch_size 1 0 1 comment [batch_size, 1] set l_eps_mask = call cast p < epsilon dtype=float32 comment [batch_size, 1] set l_reg_mask = 1.0 - l_eps_mask ...
def _l(self, batch_size, hidden_state): # masks for epsilon greedy exploration & regular sampling p = tf.random_uniform([batch_size, 1], 0, 1) # [batch_size, 1] l_eps_mask = tf.cast(p < self.epsilon, dtype=tf.float32) # [batch_size, 1] l_reg_mask = 1. - l_eps_mask ...
Python
nomic_cornstack_python_v1
comment Assignment 5, question 3 comment Tristan Subroyen comment 14 April 2014 comment This function accepts a string, converts to integer and returns it function get_integer n begin set integer = input string Enter + n + string : while not is digit integer begin set integer = input string Enter + n + string : end set...
# Assignment 5, question 3 # Tristan Subroyen # 14 April 2014 def get_integer(n): # This function accepts a string, converts to integer and returns it integer = input("Enter " + n + ":\n") while not integer.isdigit (): integer = input("Enter " + n + ":\n") integer = eval(integer) retur...
Python
zaydzuhri_stack_edu_python
function drop self variables begin for variable in variables begin if variable in ds and variable != choice begin set i = index list comprehension name for x in x variable del x at i del scale at variable del ds at variable debug string Dropped input variable ' { variable } ' from dataset end else begin raise KeyError ...
def drop(self, variables): for variable in variables: if (variable in self.ds) and (variable != self.choice): i = [x.name for x in self.x].index(variable) del self.x[i] del self.scale[variable] del self.ds[variable] debu...
Python
nomic_cornstack_python_v1
function _whctrs anchor begin set w = anchor at 2 - anchor at 0 + 1 set h = anchor at 3 - anchor at 1 + 1 set x_ctr = anchor at 0 + 0.5 * w - 1 set y_ctr = anchor at 1 + 0.5 * h - 1 return tuple w h x_ctr y_ctr end function
def _whctrs(anchor): w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr
Python
nomic_cornstack_python_v1
function value self begin return _value end function
def value(self) -> float: return self._value
Python
nomic_cornstack_python_v1
import random import turtle from playsound import playsound function random_vector begin return if expression random < 0.5 then 1 else - 1 end function class Ball extends Turtle begin set dx : float set dy : float set reflect_count : int function __init__ self x y dx dy begin call __init__ call goto x y set dx = dx * c...
import random import turtle from playsound import playsound def random_vector(): return 1 if random.random() < 0.5 else -1 class Ball(turtle.Turtle): dx: float dy: float reflect_count: int def __init__(self, x, y, dx, dy): super().__init__() self.goto(x, y) self.dx = dx ...
Python
zaydzuhri_stack_edu_python
function get_country_name city country population=string begin if population begin set full_name = city + string , + country + string - + population return title full_name end else begin set full_name = city + string , + country return title full_name end end function import unittest class CountryNameTestCase extends T...
def get_country_name(city, country, population=''): if population: full_name = city + "," + country + " - " + population return full_name.title() else: full_name = city + "," + country return full_name.title() import unittest class CountryNameTestCase(unittest.TestCase): ...
Python
zaydzuhri_stack_edu_python
function set_dhcp_pools self cidr begin set start = string call IPv4Network cidr at 50 set end = string call IPv4Network cidr at 200 return tuple start end end function
def set_dhcp_pools(self, cidr): start = str(ipaddress.IPv4Network(cidr)[50]) end = str(ipaddress.IPv4Network(cidr)[200]) return start, end
Python
nomic_cornstack_python_v1
comment for linux ssh: set matplotlib to not use the Xwindows backend. import matplotlib call use string Agg import matplotlib.pyplot as plt comment plt.ion() comment plt.ioff() import matplotlib as mp import numpy as np set color_set = tuple string g string r string c string m string y string k string w string b comme...
# for linux ssh: set matplotlib to not use the Xwindows backend. import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # plt.ion() # plt.ioff() import matplotlib as mp import numpy as np color_set = ('g', 'r', 'c', 'm', 'y', 'k', 'w', 'b') # color_set = ('r', 'g', 'b', 'y', 'm', 'c', 'w', 'b') de...
Python
zaydzuhri_stack_edu_python
function insert self ontology list_data begin set _ok = false set _res = none try begin set response = call raw_insert ontology list_data if call is_correct_status_code status_code begin set _res = json response info format string Query result: {} text call add_to_debug_trace format string Query result: {} text set _ok...
def insert(self, ontology, list_data): _ok = False _res = None try: response = self.raw_insert(ontology, list_data) if self.is_correct_status_code(response.status_code): _res = response.json() log.info("Query result: {}".format(response.te...
Python
nomic_cornstack_python_v1
print string equality/inequality operations (return booleans) print string == is equal print string != not equal print string > greater than print string >= greater than or equal to print string < less than print string <= less than or equal to
print('equality/inequality operations (return booleans)') print('\n== is equal') print('\n!= not equal') print('\n> greater than') print('\n>= greater than or equal to') print('\n< less than') print('\n<= less than or equal to')
Python
zaydzuhri_stack_edu_python
function test_camera self begin comment actually, this is tested by setUp() pass end function
def test_camera(self): pass # actually, this is tested by setUp()
Python
nomic_cornstack_python_v1
import urllib3 from bs4 import BeautifulSoup call disable_warnings InsecureRequestWarning set year = input string What year: set numMovies = integer input string How many movies: set url = string http://www.imdb.com/search/title?release_date= + year + string , + year + string &title_type=feature set ourUrl = data set s...
import urllib3 from bs4 import BeautifulSoup urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) year=input("What year: ") numMovies=int(input("How many movies: ")) url = "http://www.imdb.com/search/title?release_date=" + year + "," + year + "&title_type=feature" ourUrl = urllib3.PoolManag...
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin if not is instance other VmsSendTask begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, VmsSendTask): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
import re from urllib.request import urljoin import chardet import requests from bs4 import BeautifulSoup set root_url = string https://m.uctxt.com/index/type-7-1 set soup = call BeautifulSoup open string test.html encoding=string utf-8 string lxml set urls = list set details = find soup string div class_=string detai...
import re from urllib.request import urljoin import chardet import requests from bs4 import BeautifulSoup root_url = 'https://m.uctxt.com/index/type-7-1' soup = BeautifulSoup(open('test.html', encoding='utf-8'), 'lxml') urls = [] details = soup.find('div', class_='details clrfix') if details is not None: item_lis...
Python
zaydzuhri_stack_edu_python
function add_header r begin set headers at string Cache-Control = string no-cache, no-store, must-revalidate set headers at string Pragma = string no-cache set headers at string Expires = string 0 set headers at string Cache-Control = string public, max-age=0 return r end function
def add_header(r): r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public, max-age=0' return r
Python
nomic_cornstack_python_v1
function restore_vm_backup self sVmUuid sBackupUuid sTargetHost nTargetPort sTargetSessionId sTargetVmHomePath=string sTargetVmName=string restore_flags=PVMSL_LOW_SECURITY reserved_flags=0 force_operation=true begin return call Job call PrlSrv_RestoreVmBackup handle sVmUuid sBackupUuid sTargetHost nTargetPort sTarget...
def restore_vm_backup(self, sVmUuid, sBackupUuid, sTargetHost, nTargetPort, sTargetSessionId, sTargetVmHomePath = '', sTargetVmName = '', restore_flags = consts.PVMSL_LOW_SECURITY, reserved_flags = 0, force_operation = True): return Job(SDK.PrlSrv_RestoreVmBackup(self.handle, sVmUuid, sBackupUuid, sTargetHost, nTarge...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import os import sys import subprocess import time import datetime
#!/usr/bin/env python import os import sys import subprocess import time import datetime
Python
zaydzuhri_stack_edu_python
function test_four_operations_three_took_too_long clean_cache capfd begin with call timeit begin pass end with call timeit begin pass end with call timeit begin pass end with call timeit begin pass end set output = call readouterr at 0 assert strip output == ALERT_MSG end function
def test_four_operations_three_took_too_long(clean_cache, capfd): with timeit(): pass with timeit(): pass with timeit(): pass with timeit(): pass output = capfd.readouterr()[0] assert output.strip() == ALERT_MSG
Python
nomic_cornstack_python_v1
comment 부녀회장이 될테야 for _ in range integer input begin set k = integer input set n = integer input set v = list comprehension i for i in range 1 n + 1 for _ in range k begin for j in range 1 n begin set v at j = v at j + v at j - 1 end end print v at - 1 end string #내가 푼것 #map.split()쓰면 런타임에러남...... t=int(input()) for i ...
#부녀회장이 될테야 for _ in range(int(input())): k=int(input()) n=int(input()) v=[i for i in range(1,n+1)] for _ in range(k): for j in range(1,n): v[j]+=v[j-1] print(v[-1]) ''' #내가 푼것 #map.split()쓰면 런타임에러남...... t=int(input()) for i in range(t): k=int(input()) n=int(input()) ...
Python
zaydzuhri_stack_edu_python
function main begin set dic = dictionary comprehension x : x ^ 2 for x in range 1 16 print string Dictionary: { dic } end function if __name__ == string __main__ begin call main end comment Output: comment C:\Users\DELL\py4e>python square_dict.py comment Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64,...
def main(): dic = {x:x**2 for x in range(1,16)} print(f"Dictionary: {dic}") if __name__ == '__main__': main() #Output: # C:\Users\DELL\py4e>python square_dict.py # Dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Python
zaydzuhri_stack_edu_python
function get self entity request_id=string claim=none endorser_id=none timeout=UNSET begin set claims = if expression claim then list claim else none set request = call build_request string GET entity=entity request_id=request_id claims=claims endorser=endorser_id node_id=node_id return call send request end function
def get( self, entity: Entity, *, request_id: Identifier = "", claim: typing.Optional[bytes] = None, endorser_id: typing.Optional[Identifier] = None, timeout: typing.Union[TimeoutTypes, UnsetType] = UNSET, ) -> Response: claims = [claim] if claim else ...
Python
nomic_cornstack_python_v1
set years_list = list 1993 1994 1995 1996 1997 print string years_list is years_list
years_list = [ 1993,1994,1995,1996,1997] print('years_list is',years_list)
Python
zaydzuhri_stack_edu_python
function stopwords self words stoplist begin set wordlist = words for word in stoplist begin for item in wordlist begin if item == word begin remove wordlist item end end end return wordlist end function
def stopwords(self, words, stoplist): wordlist = words for word in stoplist: for item in wordlist: if item == word: wordlist.remove(item) return wordlist
Python
nomic_cornstack_python_v1
while n < 1000 begin if n % 3 == 0 begin set total = total + n end else if n % 5 == 0 begin set total = total + n end set n = n + 1 end print total
while n < 1000: if n%3 == 0: total += n elif n%5 == 0: total += n n += 1 print(total)
Python
zaydzuhri_stack_edu_python
from models import Post , Comment from operator import itemgetter import collections function get_most_post begin set my_dict = dictionary for post in all begin set c = count filter post__id=id set other = dict post c update my_dict other end set my_dict_sorted = sorted items my_dict key=call itemgetter 1 reverse=true ...
from .models import Post, Comment from operator import itemgetter import collections def get_most_post(): my_dict = dict() for post in Post.objects.all(): c = Comment.objects.filter(post__id=post.id).count() other = {post: c} my_dict.update(other) my_dict_sorted = sorted(my_dict.i...
Python
zaydzuhri_stack_edu_python
class List1 begin function __init__ self begin set list1 = list end function function add self item begin append list1 item end function function remove self item begin remove list1 item end function function search self item begin for i in list1 begin if i == item begin return true end end return false end function f...
class List1: def __init__(self): self.list1 = [] def add(self,item): self.list1.append(item) def remove(self,item): self.list1.remove(item) def search(self,item): for i in self.list1: if i == item: return True return False def isEmpty(self): length = len(self.list1) if length == 0: return T...
Python
zaydzuhri_stack_edu_python
function neighbors self point begin comment Sanity checks comment Check that point has same number of dimensions as graph if not length point == length dimensions begin raise exception string Point has + string length point + string dimensions, Coordination Space has + string length dimensions + string dimensions. end ...
def neighbors(self, point): # Sanity checks # Check that point has same number of dimensions as graph if not len(point) == len(self.dimensions): raise Exception("Point has " + str(len(point)) + " dimensions, Coordination Space has " + \ str(len(self.dimens...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import argparse , os , sys import numpy as np from part1 import find_invalid_number , load_data function find_encryption_weakness input_filename preamble_size begin set fail_number = call find_invalid_number input_filename preamble_size if fail_number is not none begin set data = call load...
#!/usr/bin/env python3 import argparse, os, sys import numpy as np from part1 import find_invalid_number, load_data def find_encryption_weakness(input_filename, preamble_size): fail_number = find_invalid_number(input_filename, preamble_size) if fail_number is not None: data = load_data(input_filename) fo...
Python
zaydzuhri_stack_edu_python
function shift_background_auto cls lens_data_class macromodel zsource realization cosmo=none particle_swarm_init=false opt_routine=string free_shear_powerlaw constrain_params=none verbose=false centroid_convention=string IMAGES begin set lens_system_init = call QuadLensSystem macromodel zsource none pyhalo_cosmology=co...
def shift_background_auto(cls, lens_data_class, macromodel, zsource, realization, cosmo=None, particle_swarm_init=False, opt_routine='free_shear_powerlaw', constrain_params=None, verbose=False, centroid_convention='IMAGES'): ...
Python
nomic_cornstack_python_v1
import math import random import pygame from Button import Button from Circle import Circle from Data import Data from Point import Point string This is the Circle Theorems.py file, which uses pygame to create an interactive visual version of multiple circle theorems. Creates and uses buttons to navigate to different t...
import math import random import pygame from Button import Button from Circle import Circle from Data import Data from Point import Point """This is the Circle Theorems.py file, which uses pygame to create an interactive visual version of multiple circle theorems. Creates and uses buttons to navigate to different th...
Python
zaydzuhri_stack_edu_python
string Napisać program wypisujący na ekran liczby od 0 do 100 z następującymi wyjątkami: - dla liczb podzielnych przez 3 i przez 5 wypisać FizzBuzz - dla liczb podzielnych przez 3 wypisać Fizz - dla liczb podzielnych przez 5 wypisać Buzz for i in range 0 100 begin if i % 15 == 0 begin print string FizzBuzz end else if ...
"""Napisać program wypisujący na ekran liczby od 0 do 100 z następującymi wyjątkami: - dla liczb podzielnych przez 3 i przez 5 wypisać FizzBuzz - dla liczb podzielnych przez 3 wypisać Fizz - dla liczb podzielnych przez 5 wypisać Buzz """ for i in range(0, 100): if i % 15 == 0: print('FizzBuzz') elif i ...
Python
zaydzuhri_stack_edu_python
comment This file is incomplete as it got under alien invasion. It was supposed to print out the tag names from a json file and keep a count of how many of each type of tags are present. import pymongo import json from random import randint from pymongo import MongoClient from sys import argv set tuple script ofile sav...
#This file is incomplete as it got under alien invasion. It was supposed to print out the tag names from a json file and keep a count of how many of each type of tags are present. import pymongo import json from random import randint from pymongo import MongoClient from sys import argv script, ofile, savefile = argv ...
Python
zaydzuhri_stack_edu_python
function get_first_prefix test_file begin set f = open test_file set prefix = read line f close f return prefix end function
def get_first_prefix(test_file): f = open(test_file) prefix = f.readline() f.close() return prefix
Python
nomic_cornstack_python_v1
sort nums return nums
nums.sort() return nums
Python
zaydzuhri_stack_edu_python
from math import sqrt , pi , ceil , floor from shapes import * from utils.extract_vectors import extract_vectors import matplotlib import matplotlib.patches from matplotlib.collections import PatchCollection import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import xlim , ylim function draw *obje...
from math import sqrt, pi, ceil, floor from shapes import * from utils.extract_vectors import extract_vectors import matplotlib import matplotlib.patches from matplotlib.collections import PatchCollection import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import xlim, ylim def draw(*objects, ori...
Python
zaydzuhri_stack_edu_python
function test_delete_attribute self attr1 value1 begin assert true call set_attribute app_name attr1 value1 assert equal call get_attribute app_name attr1 value1 assert true call delete_attribute app_name attr1 assert is none call get_attribute app_name attr1 assert equal call get_attribute app_name list end function
def test_delete_attribute(self, attr1, value1): self.assertTrue(self.client.set_attribute(self.app_name, attr1, value1)) self.assertEqual(self.client.get_attribute(self.app_name, attr1), value1) self.assertTrue(self.client.delete_attribute(self.app_name, attr1)) self.assertIsNone(self....
Python
nomic_cornstack_python_v1
comment https://www.codewars.com/kata/57fb04649610ce369a0006b8 function remove s begin set s = split s string set arr = list for el in s begin set left = length el - length left strip el string ! set right = length el - length right strip el string ! set m = min left right set s = string ! * m + strip el string ! + st...
# https://www.codewars.com/kata/57fb04649610ce369a0006b8 def remove(s): s = s.split(" ") arr = [] for el in s: left = len(el) - len(el.lstrip("!")) right = len(el) - len(el.rstrip("!")) m = min(left, right) s = "!" * m + el.strip("!") + "!" * m arr.append(s) retur...
Python
zaydzuhri_stack_edu_python
string Plotting ASOS netCDF4_CLASSIC data. Inspired by UNIDATA MetPy tutorial at https://unidata.github.io/MetPy/latest/examples/meteogram_metpy.html Dean Meyer 2021 import os comment import netCDF4 as nc4 import xarray as xr import pandas as pd import matplotlib.pyplot as plt comment Python standard open example comme...
""" Plotting ASOS netCDF4_CLASSIC data. Inspired by UNIDATA MetPy tutorial at https://unidata.github.io/MetPy/latest/examples/meteogram_metpy.html Dean Meyer 2021 """ import os # import netCDF4 as nc4 import xarray as xr import pandas as pd import matplotlib.pyplot as plt # Python standard open example # with nc4....
Python
zaydzuhri_stack_edu_python
function get_monthly_history self month=none year=none begin return call get_monthly_history month year end function
def get_monthly_history(self, month: int = None, year: int = None) -> \ Tuple[List[Call], List[Call]]: return self.callhistory.get_monthly_history(month, year)
Python
nomic_cornstack_python_v1
function __getattr__ self name begin return call __getattr__ name end function
def __getattr__(self, name): return self[0].__getattr__(name)
Python
nomic_cornstack_python_v1
function pvalues stats stats0 pooled=true begin if pooled begin set n_stats = length stats set stats = call ravel set stats0 = call ravel set n_stats0 = length stats0 set B = n_stats0 / n_stats set indObs = zeros n_stats + n_stats0 dtype=bool set indObs at slice : n_stats : = true set v = horizontal stack list stats ...
def pvalues(stats,stats0,pooled=True): if pooled: n_stats = len(stats) stats = stats.ravel() stats0 = stats0.ravel() n_stats0 = len(stats0) B = n_stats0/n_stats indObs = np.zeros(n_stats + n_stats0,dtype=bool) indObs[:n_stats] = True v = np.hst...
Python
nomic_cornstack_python_v1
string For your first project, you will write Python code that creates dictionaries corresponding to some simple examples of graphs. You will also implement two short functions that compute information about the distribution of the in-degrees for nodes in these graphs. You will then use these functions in the Applicati...
""" For your first project, you will write Python code that creates dictionaries corresponding to some simple examples of graphs. You will also implement two short functions that compute information about the distribution of the in-degrees for nodes in these graphs. You will then use these functions in the Applicat...
Python
zaydzuhri_stack_edu_python
function set self key value timeout=DEFAULT_TIMEOUT version=none client=none begin set key = call make_key key version=version return call _set key value timeout client=client end function
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None, client=None): key = self.make_key(key, version=version) return self._set(key, value, timeout, client=self.client)
Python
nomic_cornstack_python_v1
import copy import random from presenter import SortPresenter set SIZE = 10 set PAUSE_SEC = 0.3 set IS_DISPLAY = true function _swap lst i t begin set v = lst at i set lst at i = lst at t set lst at t = v return lst end function function comb_sort l is_display=true begin set interval = integer SIZE // 1.3 set counter =...
import copy import random from presenter import SortPresenter SIZE = 10 PAUSE_SEC = 0.3 IS_DISPLAY = True def _swap(lst, i, t): v = lst[i] lst[i] = lst[t] lst[t] = v return lst def comb_sort(l, is_display=True): interval = int(SIZE // 1.3) counter = 0 is_swapped = True if is_displa...
Python
zaydzuhri_stack_edu_python
function load_presn_search search start end offset limit begin set now_local = now set timelimit = time delta hours=100 set server = call Server string http://snoplus: + config at string COUCHDB_PASSWORD + string @ + config at string COUCHDB_HOSTNAME set db = server at string pre-supernova set results = list set skip ...
def load_presn_search(search, start, end, offset, limit): now_local = datetime.now() timelimit = timedelta(hours=100) server = couchdb.Server("http://snoplus:"+app.config["COUCHDB_PASSWORD"]+"@"+app.config["COUCHDB_HOSTNAME"]) db = server["pre-supernova"] results = [] skip = offset if sear...
Python
nomic_cornstack_python_v1
function test_delete self begin set query = dict string id 0 set result = delete string /testParaDelete query_string=query assert equal status_code 200 assert equal data string ok end function
def test_delete(self): query = {"id":0} result = self.app.delete('/testParaDelete', query_string=query) self.assertEqual(result.status_code, 200) self.assertEqual(result.data, 'ok')
Python
nomic_cornstack_python_v1
set fruits = list string apple string banana string cherry pop fruits 1 print fruits
fruits = ['apple', 'banana', 'cherry'] fruits.pop(1) print(fruits)
Python
zaydzuhri_stack_edu_python
function get_function callable_ begin if is instance callable_ MethodType begin return im_func end return callable_ end function
def get_function(callable_): if isinstance(callable_, types.MethodType): return callable_.im_func return callable_
Python
nomic_cornstack_python_v1
function botentry msg state begin if string words not in state begin comment expensive initialization, do ALAP info string Loading word corpus... set state at string words = list comprehension w for w in vocab if has_vector end comment cosine = lambda v1, v2: dot(v1, v2) / (norm(v1) * norm(v2)) set entry = list for t ...
def botentry(msg, state): if 'words' not in state: # expensive initialization, do ALAP log.info("Loading word corpus...") state['words'] = [w for w in nlp.nlp.vocab if w.has_vector] #cosine = lambda v1, v2: dot(v1, v2) / (norm(v1) * norm(v2)) entry = [] for t in state['textshape...
Python
nomic_cornstack_python_v1
function __init__ __self__ gateway secret_ref system fs_type=none protection_domain=none read_only=none ssl_enabled=none storage_mode=none storage_pool=none volume_name=none begin set __self__ string gateway gateway set __self__ string secret_ref secret_ref set __self__ string system system if fs_type is not none begin...
def __init__(__self__, *, gateway: str, secret_ref: 'outputs.LicenseMasterSpecVolumesScaleIOSecretRef', system: str, fs_type: Optional[str] = None, protection_domain: Optional[str] = None, read_only: Optional[bool] = N...
Python
nomic_cornstack_python_v1
import math class Solution extends object begin function smallgoodbase self n begin set j = log n 2 for l in range integer j 1 - 1 begin set m = find n l if m != 0 begin return m end end return string n - 1 end function end class function find n i begin set ll = 2 set lr = integer power n 1 / i while lr >= ll begin set...
import math class Solution(object): def smallgoodbase(self,n): j=math.log(n,2) for l in range(int(j),1,-1): m=find(n,l) if(m!=0): return m return str(n-1) def find(n,i): ll=2 lr=int(math.pow(n,1/i)) while(lr>=ll): sum = 0 t ...
Python
zaydzuhri_stack_edu_python
function __init__ self x509Fingerprint=none checkResumedSession=false begin set x509Fingerprint = x509Fingerprint set checkResumedSession = checkResumedSession end function
def __init__(self, x509Fingerprint=None, checkResumedSession=False): self.x509Fingerprint = x509Fingerprint self.checkResumedSession = checkResumedSession
Python
nomic_cornstack_python_v1