code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_disorder_name self lang=string en begin call validate_language lang if lang == string en begin set name = find self pattern_en full_name 1 end else if lang == string pt begin set name = find self pattern_pt full_name 1 end return name end function
def get_disorder_name(self, lang: str = 'en'): self.validate_language(lang) if lang == 'en': name = self.find(pattern_en, self.full_name, 1) elif lang == 'pt': name = self.find(pattern_pt, self.full_name, 1) return name
Python
nomic_cornstack_python_v1
function reduce f s i=none begin if i is not none begin insert s 0 i end set tuple ans j = tuple s at 0 1 while j < length s begin set tuple ans j = tuple f dist ans s at j j + 1 end return ans end function
def reduce (f, s, i=None): if i is not None: s.insert(0,i) ans, j = s[0], 1 while j < len(s): ans, j = f(ans,s[j]), j+1 return ans
Python
nomic_cornstack_python_v1
from collections import defaultdict import torch class GradientStatistics begin set state : dict function __init__ self param_groups n_sigmas_thr begin set param_groups = param_groups set state = default dictionary dict set k_thr = 1 / n_sigmas_thr * n_sigmas_thr set hist = none set params_cnt = 0 end function function...
from collections import defaultdict import torch class GradientStatistics: state: dict def __init__(self, param_groups, n_sigmas_thr): self.param_groups = param_groups self.state = defaultdict(dict) self.k_thr = 1/(n_sigmas_thr*n_sigmas_thr) self.hist = None self.params_...
Python
zaydzuhri_stack_edu_python
function load_data city month day begin set df = read csv CITY_DATA at city set df at string Start Time = call to_datetime df at string Start Time set df at string month = month set df at string day_of_week = weekday_name set df at string hour = hour if month != string all begin set month = index month_list month + 1 s...
def load_data(city, month, day): df=pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name df['hour'] =df['Start Time'].dt.hour if month != 'all': month = month_list.ind...
Python
nomic_cornstack_python_v1
function _set_session self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call YANGListType string local_index yc_session_openconfig_mpls__mpls_signaling_protocols_rsvp_te_sessions_session yang_name=string session parent=self is_container=s...
def _set_session(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("local_index",yc_session_openconfig_mpls__mpls_signaling_protocols_rsvp_te_sessions_session, yang_name="session", parent=self, is_container='list', user_ordered=False, path_helpe...
Python
nomic_cornstack_python_v1
import torch set pred = tensor list list - 0.5816 - 0.3873 - 1.0215 - 1.0145 0.4053 list 0.7265 1.4164 1.3443 1.2035 1.8823 list - 0.4451 0.1673 1.259 - 2.0757 1.7255 list 0.2021 0.3041 0.1383 0.3849 - 1.6311 comment If largest is False then the k smallest elements are returned. set tuple values indices = call topk 2 d...
import torch pred = torch.tensor([[-0.5816, -0.3873, -1.0215, -1.0145, 0.4053], [ 0.7265, 1.4164, 1.3443, 1.2035, 1.8823], [-0.4451, 0.1673, 1.2590, -2.0757, 1.7255], [ 0.2021, 0.3041, 0.1383, 0.3849, -1.6311]]) # If largest is False then the ...
Python
zaydzuhri_stack_edu_python
for tuple i tuple s t x in enumerate STX begin append starts tuple s - x i append ends tuple t - x i end sort starts key=lambda x -> x at 0 reverse=true sort ends key=lambda x -> x at 0 reverse=true import heapq set hq = list call heapify hq set delset = set set ans = list for d in D begin while starts and starts at ...
for i,(s,t,x) in enumerate(STX): starts.append((s-x,i)) ends.append((t-x,i)) starts.sort(key=lambda x:x[0], reverse=True) ends.sort(key=lambda x:x[0], reverse=True) import heapq hq = [] heapq.heapify(hq) delset = set() ans = [] for d in D: while starts and starts[-1][0] <= d: _,i = starts.pop() ...
Python
zaydzuhri_stack_edu_python
function bring_2_front self begin for obj in grfx begin set item = call find_withtag tag call tag_raise item end set __shapeorder = ObjOrder set ObjOrder = ObjOrder + 1 end function
def bring_2_front(self): for obj in self.grfx: item = self.__sheetCanvas.find_withtag(obj.tag) self.__sheetCanvas.tag_raise(item) self.__shapeorder = GrfObject.ObjOrder GrfObject.ObjOrder = GrfObject.ObjOrder + 1
Python
nomic_cornstack_python_v1
import unittest from problem16 import sum_of_digits class Problem16TestCase extends TestCase begin function test_sum_of_digits_of_2 self begin assert equal call sum_of_digits 2 2 end function function test_sum_of_digits_of_10_should_be_1 self begin assert equal call sum_of_digits 10 1 end function function test_sum_of_...
import unittest from problem16 import sum_of_digits class Problem16TestCase(unittest.TestCase): def test_sum_of_digits_of_2(self): self.assertEqual(sum_of_digits(2), 2) def test_sum_of_digits_of_10_should_be_1(self): self.assertEqual(sum_of_digits(10), 1) def test_sum_of_digi...
Python
zaydzuhri_stack_edu_python
function call_later delay callback *args **kwargs begin set server = call current_server false if not server begin append _pending_call_laters tuple delay callback args kwargs end else begin call call_later delay callback *args keyword kwargs end end function
def call_later(delay, callback, *args, **kwargs): server = current_server(False) if not server: _pending_call_laters.append((delay, callback, args, kwargs)) else: server.call_later(delay, callback, *args, **kwargs)
Python
nomic_cornstack_python_v1
function construct_passport line passport begin print line set split_entries = split line string for key_val in split_entries begin set split_key_val = split key_val string : print string split_key_val: { split_key_val } set passport_key = split_key_val at 0 print string passport_key: { passport_key } set passport_val ...
def construct_passport(line, passport): print(line) split_entries = line.split(" ") for key_val in split_entries: split_key_val = key_val.split(":") print(f"split_key_val: {split_key_val}") passport_key = split_key_val[0] print(f"passport_key: {passport_key}") passpor...
Python
zaydzuhri_stack_edu_python
function WFD self begin return fdist end function
def WFD(self) -> pd.DataFrame: return self.fdist
Python
nomic_cornstack_python_v1
if total < c begin set msg = string Sim end else begin set msg = string Nao end print round total 1 print msg
if total < c: msg = "Sim" else: msg = "Nao" print(round(total, 1)) print(msg)
Python
zaydzuhri_stack_edu_python
function test_api__delete_workspace__ok_200__manager_workspace_manager self begin set authorization = tuple string Basic tuple string admin@admin.admin string admin@admin.admin set dbsession = call get_tm_session session_factory manager set admin = call one set uapi = call UserApi current_user=admin session=dbsession c...
def test_api__delete_workspace__ok_200__manager_workspace_manager(self) -> None: self.testapp.authorization = ("Basic", ("admin@admin.admin", "admin@admin.admin")) dbsession = get_tm_session(self.session_factory, transaction.manager) admin = dbsession.query(User).filter(User.email == "admin@admi...
Python
nomic_cornstack_python_v1
from enum import Enum class WeaponTypes extends Enum begin set MACE = 3 set AXE = 5 set SWORD = 6 set BATTLEAXE = 7 function create_list self begin set weapon_list = list for material in WeaponTypes begin append weapon_list material end return weapon_list end function end class
from enum import Enum class WeaponTypes(Enum): MACE = 3 AXE = 5 SWORD = 6 BATTLEAXE = 7 def create_list(self): weapon_list =[] for material in WeaponTypes: weapon_list.append(material) return weapon_list
Python
zaydzuhri_stack_edu_python
function get_debrid_provider provider_name begin set provider = get attribute debrid provider_name set cfg_str = format string {}.{{}} provider_name set tuple args _ _ defaults = call getargspec __init__ comment Strip self set args = args at slice 1 : : set config_argvals = list for arg in args begin set config_sett...
def get_debrid_provider(provider_name): provider = getattr(debrid, provider_name) cfg_str = '{}.{{}}'.format(provider_name) args, _, _, defaults = inspect.getargspec(provider.__init__) args = args[1:] # Strip self config_argvals = [] for arg in args: config_setting = router.addon.getSett...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np set df = read csv string combined_stats.csv comment df.head() function school_list begin set list_schools = call tolist return list_schools end function function get_team team begin set team_stat = loc at df at string TEAM == team set new_df = call tolist set stats = new_df at 0 c...
import pandas as pd import numpy as np df = pd.read_csv('combined_stats.csv') #df.head() def school_list(): list_schools = df['TEAM'].values.tolist() return(list_schools) def get_team(team): team_stat= df.loc[df['TEAM'] == team] new_df = team_stat[['FGA-game','assist_per_game','turnover_per_g...
Python
zaydzuhri_stack_edu_python
function draw_header canvas invoice begin call setLineWidth 2 call line 2 * cm - 4 * cm 19 * cm - 4 * cm string Draws the business address set business_details = BUSINESS_DETAIL set business_data = list for line in business_details begin append business_data list line end set table = call Table business_data colWidths...
def draw_header(canvas, invoice): canvas.setLineWidth(2) canvas.line(2 * cm, -4 * cm, 19 * cm, -4 * cm) """ Draws the business address """ business_details = settings.BUSINESS_DETAIL business_data = [] for line in business_details: business_data.append([line]) table = Table(busines...
Python
nomic_cornstack_python_v1
comment Team2: Yuu Sakaguchi, Felipe Vianna, Chembrolu Surya import numpy as np import pandas as pd comment Given a sequence of a path, generates into Ozocode in XML. comment example comment path = [1,2,7,12,12,12,12,12,12,12,12,12,12,13,14,19,19,19,19,19,14,9,4] comment path = [2,3,4,9,14,19,19,19,19,19,24,23,22,17,12...
# Team2: Yuu Sakaguchi, Felipe Vianna, Chembrolu Surya import numpy as np import pandas as pd # Given a sequence of a path, generates into Ozocode in XML. # example #path = [1,2,7,12,12,12,12,12,12,12,12,12,12,13,14,19,19,19,19,19,14,9,4] #path = [2,3,4,9,14,19,19,19,19,19,24,23,22,17,12,12,12,12,12,12,12,12...
Python
zaydzuhri_stack_edu_python
function dnn_regressor input_columns dnn_hidden_units learning_rate begin comment Following values are hard coded for simplicity in this example, comment However prefarably they should be passsed in as hparams. set input_layers = dictionary comprehension colname : input name=call transformed_name colname shape=tuple d...
def dnn_regressor(input_columns, dnn_hidden_units, learning_rate): # Following values are hard coded for simplicity in this example, # However prefarably they should be passsed in as hparams. input_layers = { colname: tf.keras.layers.Input(name=transformed_name(colname), shape=(), dtype=tf.float32) ...
Python
nomic_cornstack_python_v1
function contains self itemset begin set i = 0 for item in reversed cache begin if rank at itemset at i < rank at item begin break end if itemset at i == item begin set i = i + 1 end if i == length itemset begin return true end end for basenode in nodes at itemset at 0 begin set i = 0 set node = basenode while item is ...
def contains(self, itemset): i = 0 for item in reversed(self.cache): if self.rank[itemset[i]] < self.rank[item]: break if itemset[i] == item: i += 1 if i == len(itemset): return True for basenode in self.nodes[i...
Python
nomic_cornstack_python_v1
import numpy as np from nltk.tokenize import word_tokenize from pyjarowinkler import distance from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from decimal import Decimal import numpy as np from collections import Counter from math import sqrt from ...
import numpy as np from nltk.tokenize import word_tokenize from pyjarowinkler import distance from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from decimal import Decimal import numpy as np from collections import Counter from math import sqrt fro...
Python
zaydzuhri_stack_edu_python
comment 给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示, comment 其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。 comment 请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。 comment 题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。 comment 示例 1: comment 输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] comment 输出:"Sao Paulo" co...
# 给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示, # 其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。 # 请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。 # 题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。 #   # 示例 1: # 输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] # 输出:"Sao Paulo" # 解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" ...
Python
zaydzuhri_stack_edu_python
import hexagon_stone as hs from math import sqrt comment this player has all stones, tm basic stones and mosquito, ladybug class Player_Extended begin function __init__ self color surfaces begin set color = color set surfaces = surfaces set initial_stone_size = integer 0.03 * call get_width set stone_size = initial_sto...
import hexagon_stone as hs from math import sqrt #this player has all stones, tm basic stones and mosquito, ladybug class Player_Extended: def __init__(self, color, surfaces): self.color = color self.surfaces = surfaces self.initial_stone_size = int(0.03 * self.surfaces["surface_full"].get...
Python
zaydzuhri_stack_edu_python
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import Column from sqlalchemy import Integer , String from sqlalchemy.sql import select from sqlalchemy.sql import text set db_uri = string mysql://admin:mypass@127.0.0.1:3306/customers co...
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy import Table from sqlalchemy import Column from sqlalchemy import Integer, String from sqlalchemy.sql import select from sqlalchemy.sql import text db_uri = "mysql://admin:mypass@127.0.0.1:3306/customers" #Create SQ...
Python
zaydzuhri_stack_edu_python
function multiclass_ensemble networks=list model_path=none weights_path=none use_weighted_average=false freeze=false begin if model_path is not none begin print string Loading an already built model from: { model_path } set ensemble = call load_model model_path custom_objects=dict string WeightedAverage WeightedAverag...
def multiclass_ensemble( networks=[], model_path=None, weights_path=None, use_weighted_average=False, freeze=False, ): if model_path is not None: print(f"\nLoading an already built model from: {model_path}") ensemble = tf.keras.models.load_model( model_path, custom_o...
Python
nomic_cornstack_python_v1
from pyomo.opt import SolverFactory import pyomo.environ as pe set __all__ = list string oldroyd_viscosity_model string yaron_viscosity_model comment Shared parameters set atr = list string v string k string c_mu string Sr string st string dB comment List of commom fixed variables function initialize_model m disp=false...
from pyomo.opt import SolverFactory import pyomo.environ as pe __all__ = ['oldroyd_viscosity_model', 'yaron_viscosity_model'] # Shared parameters atr = ['v', 'k', 'c_mu', 'Sr', 'st', 'dB'] # List of commom fixed variables def initialize_model(m, disp = False): """ Initializes viscosit...
Python
zaydzuhri_stack_edu_python
while i <= 10 begin set i = i + 1 print num string * i string = num * i end
while i<=10: i+=1 print(num,"*",i,"=",num*i)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- comment @Time : 2020/3/30 21:31 comment @Author : LI Dongdong comment @FileName: 90. Subsets II.py string string 题目概述: 题目考点: 解决方案: 方法及方法分析: time complexity order: space complexity order: 如何考 class Solution begin function subsetsWithDup self nums begin set res = l...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/3/30 21:31 # @Author : LI Dongdong # @FileName: 90. Subsets II.py '''''' ''' 题目概述: 题目考点: 解决方案: 方法及方法分析: time complexity order: space complexity order: 如何考 ''' class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [...
Python
zaydzuhri_stack_edu_python
string 제어문 : 반복문(while) while 조건식 : 실행문 실행문 comment 카운터, 누적 변수 comment 변수 초기화 set cnt = 0 set tot = 0 while cnt < 5 begin comment 카운터 변수 set cnt = cnt + 1 comment 누적 변수 set tot = tot + cnt print cnt tot end=string / end comment 1 1 / 2 3 / 3 6 / 4 10 / 5 15 / comment True -> Loop(명령문 집합) 실행 while cnt < 5 begin comment ...
''' 제어문 : 반복문(while) while 조건식 : 실행문 실행문 ''' # 카운터, 누적 변수 cnt = tot = 0 # 변수 초기화 while cnt < 5 : cnt += 1 # 카운터 변수 tot += cnt # 누적 변수 print(cnt, tot, end=" / ") # 1 1 / 2 3 / 3 6 / 4 10 / 5 15 / while cnt < 5 : # True -> Loop(명령문 집합) 실행 pass # 아무것도 하지않는다. break # ...
Python
zaydzuhri_stack_edu_python
function __init__ self peerAddr localAddr udpSock begin comment IPv6 addr in printable fmt set peerAddr = peerAddr comment Local teredo address in printable fmt set localAddr = localAddr end function
def __init__(self, peerAddr, localAddr, udpSock): self.peerAddr = peerAddr # IPv6 addr in printable fmt self.localAddr = localAddr # Local teredo address in printable fmt
Python
nomic_cornstack_python_v1
function union_scan_with_prefix self table prefix columns begin comment TODO: Need assertion for columns contains at least 1 element for salt in string 0123456789abcdef begin set salted_prefix = string %s%s % tuple salt prefix set scanner = call scannerOpenWithPrefix table salted_prefix columns for tuple rowkey row in ...
def union_scan_with_prefix(self, table, prefix, columns): # TODO: Need assertion for columns contains at least 1 element for salt in '0123456789abcdef': salted_prefix = "%s%s" % (salt, prefix) scanner = self.client.scannerOpenWithPrefix( table, salted_...
Python
nomic_cornstack_python_v1
from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser , BaseUserManager , PermissionsMixin class UserManager extends BaseUserManager begin function create_user self email username first_name last_name password=none begin string Create...
from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user( self, email, username, first_name, last_name, password=None ): ...
Python
zaydzuhri_stack_edu_python
import numpy as np import random from mesa import Agent import math import util from settings import * class Car extends Agent begin string Basic car agent that attempts to avoid collisions greedily with a small amount of lookahead prediction comment super() args function __init__ self unique_id model pos speed heading...
import numpy as np import random from mesa import Agent import math import util from settings import * class Car(Agent): ''' Basic car agent that attempts to avoid collisions greedily with a small amount of lookahead prediction ''' def __init__(self, unique_id, model, # super() args ...
Python
zaydzuhri_stack_edu_python
function test_intent_classifier_set_params self begin pass end function
def test_intent_classifier_set_params(self): pass
Python
nomic_cornstack_python_v1
function get_min_odd numbers begin if length numbers == 1 begin if numbers at 0 % 2 == 0 begin return 9999 end else begin return numbers at 0 end end if numbers at 0 < numbers at 1 and numbers at 0 % 2 != 0 begin append numbers numbers at 0 return call get_min_odd numbers at slice 1 : : end else begin return call get_...
def get_min_odd(numbers): if len(numbers) == 1: if numbers[0] % 2 == 0: return 9999 else: return numbers[0] if numbers[0] < numbers[1] and numbers[0] % 2 != 0: numbers.append(numbers[0]) return(get_min_odd(numbers[1:])) else: return...
Python
zaydzuhri_stack_edu_python
function FindNearestNode self nodelist node_rnd mode=string Euclidean begin set node_index = 0 if mode == string Euclidean begin set min_dist = x - node_rnd at 0 ^ 2 + y - node_rnd at 1 ^ 2 for iter in range length nodelist begin set distance = x - node_rnd at 0 ^ 2 + y - node_rnd at 1 ^ 2 if distance <= min_dist begin...
def FindNearestNode(self, nodelist, node_rnd, mode="Euclidean"): node_index = 0 if mode == "Euclidean": min_dist = (self.start.x - node_rnd[0]) ** 2 + (self.start.y - node_rnd[1]) ** 2 for iter in range(len(nodelist)): distance = (nodelist[iter].x - node_rnd[0]) *...
Python
nomic_cornstack_python_v1
function log_features data columns begin for col in columns begin comment deal with 0/1 values if sum data at col == 0 > 0 begin print string Replacing 0s with 0.025... set loc at tuple data at col == 0 col = 0.025 end set data at col = log data at col end end function
def log_features(data, columns): for col in columns: # deal with 0/1 values if np.sum(data[col] == 0) > 0: print('Replacing 0s with 0.025...') data.loc[data[col] == 0, col] = 0.025 data[col] = np.log(data[col])
Python
nomic_cornstack_python_v1
for c in range 0 6 + 1 2 begin set s = s + c end print s print string FIM
for c in range(0,6+1,2): s += c print(s) print("FIM")
Python
zaydzuhri_stack_edu_python
string Lab13a Re-implement Lab 08a to replace the data source with a file instead of input(). The file should be the data in the temps.dat file in your data folder. Be sure to account for any bad data that might be contained in this file. function fahr2cent temp begin comment convert to float set fahrenheit = decimal t...
""" Lab13a Re-implement Lab 08a to replace the data source with a file instead of input(). The file should be the data in the temps.dat file in your data folder. Be sure to account for any bad data that might be contained in this file. """ def fahr2cent(temp): fahrenheit = float(temp) # convert to float ...
Python
zaydzuhri_stack_edu_python
function actualizar_repuestos begin import kpis.sap.me2k import kpis.repuestos.salida_datos from datetime import datetime comment Muestra en la interfaz de usuario el texto "Working..." comment label_actualizar_repuestos_procesando.setText("Working...") comment label_actualizar_repuestos_procesando.adjustSize() comment...
def actualizar_repuestos(): import kpis.sap.me2k import kpis.repuestos.salida_datos from datetime import datetime # Muestra en la interfaz de usuario el texto "Working..." #label_actualizar_repuestos_procesando.setText("Working...") #label_actualizar_repuestos_procesando.adjustSize() # Fec...
Python
nomic_cornstack_python_v1
function set_tileargs self tile_size orientation resolution x_idx y_idx z_idx begin set tile_size = integer tile_size set x_idx = integer x_idx set y_idx = integer y_idx set z_idx = integer z_idx try begin if integer resolution in range 0 num_hierarchy_levels begin set resolution = integer resolution end comment TODO -...
def set_tileargs(self, tile_size, orientation, resolution, x_idx, y_idx, z_idx): tile_size = int(tile_size) x_idx = int(x_idx) y_idx = int(y_idx) z_idx = int(z_idx) try: if int(resolution) in range(0, self.experiment.num_hierarchy_levels): self.resol...
Python
nomic_cornstack_python_v1
function _get_default_included_fields self begin return get attribute self string default_included_fields none end function
def _get_default_included_fields(self) -> List[str]: return getattr(self, "default_included_fields", None)
Python
nomic_cornstack_python_v1
function enc_to_clear_filename fname begin string Converts the filename of an encrypted file to cleartext :param fname: :return: filename of clear secret file if found, else None if not ends with lower fname string .json begin raise call CredkeepException string Invalid filetype end if not ends with lower fname string ...
def enc_to_clear_filename(fname): """ Converts the filename of an encrypted file to cleartext :param fname: :return: filename of clear secret file if found, else None """ if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if not fname.lower().endswi...
Python
jtatman_500k
comment cook your dish here for _ in range integer input begin set n = integer input set arr = list map int split input if n <= 2 begin print 1 end else begin set ans = 1 set a = list for i in range n begin append a list i arr at i end set b = list append b a at 0 append b a at 1 set len_b = length b for j in range 2...
# cook your dish here for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) if(n<=2): print(1) else: ans = 1 a = [] for i in range(n): a.append([i,arr[i]]) b = [] b.append(a[0]) b.append(a[1]) le...
Python
zaydzuhri_stack_edu_python
function dialog_filters data add_all=true add_wildcard=true begin set fmt_ext = lambda name exts -> format string {0} ({1})|{1} name join string ; exts set tuple res all = tuple list list for tuple name value in items data begin if type value is str begin set value = tuple value end set value = map lambda ext -> stri...
def dialog_filters(data, add_all=True, add_wildcard=True): fmt_ext = lambda name, exts: '{0} ({1})|{1}'.format(name, ';'.join(exts)) res, all = [], [] for name, value in data.items(): if type(value) is str: value = (value,) value = map(lambda ext: '*.%s' % ext, value) all.extend(value) res.appen...
Python
nomic_cornstack_python_v1
function default_get self cr user fields_list context=none begin if context is none begin set context = dict end set journal_id = get context string journal_id false set partner_id = get context string partner_id false set journal_pool = get pool string account.journal set partner_pool = get pool string res.partner se...
def default_get(self, cr, user, fields_list, context=None): if context is None: context = {} journal_id = context.get('journal_id', False) partner_id = context.get('partner_id', False) journal_pool = self.pool.get('account.journal') partner_pool = self.pool.get('res.p...
Python
nomic_cornstack_python_v1
for i in range n + 1 begin print string madhu end
for i in range(n+1): print("madhu")
Python
zaydzuhri_stack_edu_python
import os import pandas as pd import numpy as np import math import sys import FirstProblem as fp import SecondProblem as sp import ThirdProblem as tp import FourthProblem as fp if __name__ == string __main__ begin set mars_opposition_data = read csv string ../data/01_data_mars_opposition.csv comment print(mars_opposit...
import os import pandas as pd import numpy as np import math import sys import FirstProblem as fp import SecondProblem as sp import ThirdProblem as tp import FourthProblem as fp if __name__ == '__main__': mars_opposition_data = pd.read_csv('../data/01_data_mars_opposition.csv') # print(mars_opposition_data.val...
Python
zaydzuhri_stack_edu_python
import json import math import tensorflow as tf function create_example image path example begin set feature = dict string image call Feature bytes_list=call BytesList value=list call numpy ; string path call Feature bytes_list=call BytesList value=list encode path ; string area call Feature float_list=call FloatList v...
import json import math import tensorflow as tf def create_example(image, path, example): feature = { "image": tf.train.Feature( bytes_list=tf.train.BytesList( value=[tf.io.encode_jpeg(image).numpy()] ) ), "path": tf.train.Feature( bytes_...
Python
zaydzuhri_stack_edu_python
function linearsearch l1 no begin for i in l1 begin if integer no == l1 at i begin set globals at string index = i return true end end return false end function set l1 = list 1 2 3 4 5 6 7 8 set no = input string Enter a number if call linearsearch l1 no begin print string Found at + string index end else begin print s...
def linearsearch(l1,no): for i in l1: if int(no) == l1[i]: globals()['index']=i return True return False l1=[1,2,3,4,5,6,7,8] no=input("Enter a number") if linearsearch(l1,no): print("Found at "+ str(index)) else: print("Not Found")
Python
zaydzuhri_stack_edu_python
function test_grainbin_updates_latest_get_no_updates flaskclient auth_headers begin set grainbin = save set url = call url_for string grainbin.GrainbinUpdatesLatest grainbin_id=id set rep = get flaskclient url headers=auth_headers set rep_json = call get_json assert status_code == 404 assert rep_json at string message ...
def test_grainbin_updates_latest_get_no_updates(flaskclient, auth_headers): grainbin = GrainbinFactory().save() url = url_for("grainbin.GrainbinUpdatesLatest", grainbin_id=grainbin.id) rep = flaskclient.get(url, headers=auth_headers) rep_json = rep.get_json() assert rep.status...
Python
nomic_cornstack_python_v1
async function set_logging_service self request=none project_id=none zone=none cluster_id=none logging_service=none name=none retry=DEFAULT timeout=DEFAULT metadata=tuple begin comment Create or coerce a protobuf request object. comment Quick check: If we got a request object, we should *not* have comment gotten any ke...
async def set_logging_service( self, request: Optional[Union[cluster_service.SetLoggingServiceRequest, dict]] = None, *, project_id: Optional[str] = None, zone: Optional[str] = None, cluster_id: Optional[str] = None, logging_service: Optional[str] = None, ...
Python
nomic_cornstack_python_v1
function DownloadTemplate template begin set pdbl = call PDBList call retrieve_pdb_file template obsolete=false pdir=string ./ file_format=string pdb end function
def DownloadTemplate(template): pdbl = PDBList() pdbl.retrieve_pdb_file(template, obsolete=False, pdir="./", file_format="pdb")
Python
nomic_cornstack_python_v1
string http://www.jb51.net/article/70366.htm
''' http://www.jb51.net/article/70366.htm '''
Python
zaydzuhri_stack_edu_python
function policy_iteration_on_line_world begin comment TODO pass end function
def policy_iteration_on_line_world() -> PolicyAndValueFunction: # TODO pass
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Copyright 2012 Daisuke Yabuki. All Rights Reserved. string Show the upcoming bus service from Roppongi to Shibuya. This script gives the departure time of the next available bus service from Roppongi Hills bound for Shibuya if no time is given as commandlin...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2012 Daisuke Yabuki. All Rights Reserved. """Show the upcoming bus service from Roppongi to Shibuya. This script gives the departure time of the next available bus service from Roppongi Hills bound for Shibuya if no time is given as commandline option. If time is ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Sep 2 23:08:08 2017 @author: shuai.qian set age = input string Please input your age: comment Python中条件判断,首先需要注意的缩进,再就是if 和else 行末的冒号。 set age = integer age if age >= 18 begin print string Your age is age print string Adult end else begin print string Teenager end com...
# -*- coding: utf-8 -*- """ Created on Sat Sep 2 23:08:08 2017 @author: shuai.qian """ age = input('Please input your age: ') #Python中条件判断,首先需要注意的缩进,再就是if 和else 行末的冒号。 age = int(age) if age >= 18 : print ('Your age is ', age) print ('Adult') else : print ('Teenager') #需要多重判断时使用elif,它是else...
Python
zaydzuhri_stack_edu_python
function titles2marc self key values begin string Populate the ``246`` MARC field. Also populates the ``245`` MARC field through side effects. set tuple first rest = tuple values at 0 values at slice 1 : : append set default self string 245 list dict string a get first string title ; string b get first string subtitl...
def titles2marc(self, key, values): """Populate the ``246`` MARC field. Also populates the ``245`` MARC field through side effects. """ first, rest = values[0], values[1:] self.setdefault('245', []).append({ 'a': first.get('title'), 'b': first.get('subtitle'), '9': first.ge...
Python
jtatman_500k
from math import ceil comment divisor最大是maxN,最小是1,二分查找 class Solution begin function smallestDivisor self nums threshold begin function helper divisor begin return sum generator expression ceil n / divisor for n in nums end function set tuple l r = tuple 1 max nums while l < r begin set mid = l + r // 2 if call helper ...
from math import ceil # divisor最大是maxN,最小是1,二分查找 class Solution: def smallestDivisor(self, nums, threshold): def helper(divisor): return sum(ceil(n/divisor) for n in nums) l,r =1,max(nums) while l < r: mid = (l + r) // 2 if helper(mid) > threshold: ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string This small module is usefull to monitor docker process and if it stops, we can automatically restart it. For this, we should send id of the active container to monitoring, and set the script on the crontab. PS: The print statement is only to log what is happening, we probably will f...
# -*- coding: utf-8 -*- u"""This small module is usefull to monitor docker process and if it stops, we can automatically restart it. For this, we should send id of the active container to monitoring, and set the script on the crontab. PS: The print statement is only to log what is happening, we probably will fix it...
Python
zaydzuhri_stack_edu_python
import pygame import os call init call init set tuple WIDTH HEIGHT = tuple 900 500 set WIN = call set_mode tuple WIDTH HEIGHT set WHITE = tuple 255 255 255 set BLACK = tuple 0 0 0 set RED = tuple 255 0 0 set YELLOW = tuple 255 255 0 set BORDER = call Rect WIDTH // 2 - 5 0 10 HEIGHT set BULLET_HIT_SOUND = call Sound joi...
import pygame import os pygame.font.init() pygame.mixer.init() WIDTH, HEIGHT = 900,500 WIN = pygame.display.set_mode((WIDTH,HEIGHT)) WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) YELLOW = (255,255,0) BORDER = pygame.Rect(WIDTH//2 -5,0 ,10,HEIGHT) BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join('Assets',...
Python
zaydzuhri_stack_edu_python
function _p_radical omega p q minpoly n begin comment Ip/pO = kernel of q-th powering. comment omega_j^q = \sum a_i_j omega_i set base_p = call _kernel_of_qpow omega q p minpoly n set l = column comment expand basis of Ip/pO to O/pO call toSubspace set beta_p = call supplementBasis comment basis of Ip comment pulled ba...
def _p_radical(omega, p, q, minpoly, n): # Ip/pO = kernel of q-th powering. # omega_j^q = \sum a_i_j omega_i base_p = _kernel_of_qpow(omega, q, p, minpoly, n) l = base_p.column # expand basis of Ip/pO to O/pO base_p.toSubspace() beta_p = base_p.supplementBasis() # basis of Ip # pul...
Python
nomic_cornstack_python_v1
string Dice game of Yacht is played with 5 standard dice (having from 1 to 6 points on their sides). The player's goal is to gather some beautiful combination of points. Suppose, the following combinations are respected: two of dice have the same points, like 3 6 5 6 1 - called pair; three of dice have the same points,...
''' Dice game of Yacht is played with 5 standard dice (having from 1 to 6 points on their sides). The player's goal is to gather some beautiful combination of points. Suppose, the following combinations are respected: two of dice have the same points, like 3 6 5 6 1 - called pair; three of dice have the same p...
Python
zaydzuhri_stack_edu_python
import os import copy comment Helper Functions set IGNORE_FILE_TYPES = list string swp string pyc function ls_recursive current prepend=list dir_sep=string / begin string returns a list of the full relative path for all FILES (not directories) higher in the directory tree set children = list comment print "current: %...
import os import copy ### Helper Functions IGNORE_FILE_TYPES = ["swp", "pyc"] def ls_recursive(current, prepend=[], dir_sep = '/'): """ returns a list of the full relative path for all FILES (not directories) higher in the directory tree """ children = [] #print "current: %s" % current current_f...
Python
zaydzuhri_stack_edu_python
function construct_graph edges begin set points = set list comprehension point for edge in edges for point in edge set point_neighbors = dict for point in points begin set point_neighbors at point = set for edge in edges begin if point in edge begin update point_neighbors at point list edge end end discard point_neigh...
def construct_graph(edges): points = set([point for edge in edges for point in edge]) point_neighbors = {} for point in points: point_neighbors[point] = set() for edge in edges: if point in edge: point_neighbors[point].update(list(edge)) point_neighbors[po...
Python
zaydzuhri_stack_edu_python
function collapseContinuations self lines begin set l = list set state = 0 for line in lines begin if state == 0 begin if find line b'(' == - 1 begin append l line end else begin append l line at slice : find line b'(' : set state = 1 end end else if find line b')' != - 1 begin set l at - 1 = l at - 1 + b' ' + line a...
def collapseContinuations(self, lines): l = [] state = 0 for line in lines: if state == 0: if line.find(b"(") == -1: l.append(line) else: l.append(line[: line.find(b"(")]) state = 1 ...
Python
nomic_cornstack_python_v1
function _get_single_subject_data self subject begin set filepath = call data_path subject at 0 set data = call loadmat filepath set S = data at string data at tuple slice : : slice 1 : 17 : set stim = data at string data at tuple slice : : - 1 set chnames = list string Fp1 string Fp2 string Fc5 string Fz string...
def _get_single_subject_data(self, subject): filepath = self.data_path(subject)[0] data = loadmat(filepath) S = data['data'][:, 1:17] stim = data['data'][:, -1] chnames = [ 'Fp1', 'Fp2', 'Fc5', 'Fz', 'Fc6', ...
Python
nomic_cornstack_python_v1
comment Welcome to the python challenges of version 82. string Write a Python program that implements the Binary Search algorithm recursively. The function should search for an element in a list or sequence and return its index. If the element is not found, the value returned should be -1. set lists = list range 1 21 s...
# Welcome to the python challenges of version 82. """Write a Python program that implements the Binary Search algorithm recursively. The function should search for an element in a list or sequence and return its index. If the element is not found, the value returned should be -1.""" lists = list(range(1, 21)) n = ...
Python
zaydzuhri_stack_edu_python
function get_variable_attributes model_data header variable variable_name begin append header format string # {}_column: {} variable variable_name for tuple attr value in items variables variables at variable begin if string _range in attr begin append header format string # {}_{}: {},{} variable attr value at 0 value ...
def get_variable_attributes(model_data, header, variable, variable_name): header.append('# {}_column: {}\n'.format(variable, variable_name)) for attr, value in vars(model_data.variables[variable]).items(): if '_range' in attr: header.append('# {}_{}: {},{}\n'.format(variable, attr, value[0],...
Python
nomic_cornstack_python_v1
comment 自动输入 import openpyxl from openpyxl import load_workbook import time set data = call load_workbook string C:\Users\admin\Downloads\123.xlsx set table = call get_sheet_by_name string 基础数据表 for k in range 0 100 begin set Input_Num = input string 请输入站号: for i in range 2 1536 begin set Stop_Num = integer value if in...
#自动输入 import openpyxl from openpyxl import load_workbook import time data=load_workbook('C:\\Users\\admin\Downloads\\123.xlsx') table=data.get_sheet_by_name('基础数据表') for k in range(0,100): Input_Num=input("请输入站号:") for i in range(2,1536): Stop_Num=int(table.cell(row=i,column=2).value) ...
Python
zaydzuhri_stack_edu_python
comment Uncomment this for case 1: Marie, Alex, Aurora, and Smith not invited set facebook_Friends = list string Hannah string Marie string Bob string Sam string Alex string Aurora string Smith set party_Friends = list string Joe string Sam string Carl string Hannah string Bob comment Uncomment for case 2: Everyone is ...
# Uncomment this for case 1: Marie, Alex, Aurora, and Smith not invited facebook_Friends=['Hannah','Marie','Bob','Sam','Alex','Aurora','Smith'] party_Friends=['Joe','Sam','Carl','Hannah','Bob'] # Uncomment for case 2: Everyone is invited # facebook_Friends=['Hannah','Marie','Bob','Sam','Alex','Aurora','Smith'] # pa...
Python
zaydzuhri_stack_edu_python
import sys comment Strings are characters enclosed in double or single quotes print string Any characters enclosed in double or single quotes is considered string in python print string I am also a string comment Print integers or float print 5 print - 5 print 5.5 comment print special number values comment max int val...
import sys # Strings are characters enclosed in double or single quotes print ("Any characters enclosed in double or single quotes is considered string in python") print ('I am also a string') #Print integers or float print (5) print (-5) print (5.5) #print special number values print (sys.maxsize) #max int value whi...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Dec 11 17:04:04 2017 @author: chaka import os , sys , email , re import pandas as pd set input_path = string ../emails set output_path = string ../emails.csv comment Read the data into a DataFrame set emails_df = read csv input_path print...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 11 17:04:04 2017 @author: chaka """ import os,sys, email, re import pandas as pd input_path = '../emails' output_path = '../emails.csv' # Read the data into a DataFrame emails_df = pd.read_csv(input_path) print(emails_df.shape) def get_text_fr...
Python
zaydzuhri_stack_edu_python
string 다른 모든 함수들도 정규식 표현으로 추출 및 검색 가능 # 기본 패턴 - a, X, 9 등등 문자 하나하나의 character들은 정확히 해당 문자와 일치 e.g) 패턴 test는 test 문자열과 일치 대소문자의 경우 기본적으로 구별하나, 구별하지 않도록 설정 가능 - 몇몇 문자들에 대해서는 예외가 존재하는데, 이들은 틀별한 의미로 사용 됨 . ^ $ * + ? { } [ ] \ | ( ) - . (마침표) - 어떤 한개의 character와 일치 (newline(엔터) 제외) - \w - 문자 character와 일치 [a-zA-Z0-9_] - \s ...
''' 다른 모든 함수들도 정규식 표현으로 추출 및 검색 가능 # 기본 패턴 - a, X, 9 등등 문자 하나하나의 character들은 정확히 해당 문자와 일치 e.g) 패턴 test는 test 문자열과 일치 대소문자의 경우 기본적으로 구별하나, 구별하지 않도록 설정 가능 - 몇몇 문자들에 대해서는 예외가 존재하는데, 이들은 틀별한 의미로 사용 됨 . ^ $ * + ? { } [ ] \ | ( ) - . (마침표) - 어떤 한개의 character와 일치 (newline(엔터) 제외) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import tkinter as tk class Application extends Frame begin function __init__ self master=none begin call __init__ self master grid sticky=N + S + E + W call createWidgets end function function createWidgets self begin set canvas = call Canvas bg=string white height=400 width=400 grid set tr...
#!/usr/bin/env python import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid(sticky=tk.N+tk.S+tk.E+tk.W) self.createWidgets() def createWidgets(self): self.canvas = tk.Canvas(bg='white', height=400, width=400)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python set positions = list 19 4 14 3 10 17 24 22 8 2 5 11 7 26 0 25 18 6 21 23 9 13 16 1 12 15 27 20 set values = list 8930 15006 8930 10302 11772 13806 13340 11556 12432 13340 10712 10100 11556 12432 9312 10712 10100 10100 8930 10920 8930 5256 9312 9702 8930 10712 15500 9312 set sorted = list for i...
#!/usr/bin/python positions = [19, 4, 14, 3, 10, 17, 24, 22, 8, 2, 5, 11, 7, 26, 0, 25, 18, 6, 21, 23, 9, 13, 16, 1, 12, 15, 27, 20] values = [8930, 15006, 8930, 10302, 11772, 13806, 13340, 11556, 12432, 13340, 10712, 10100, 11556, 12432, 9312, 10712, 10100, 10100, 8930, 10920, 8930, 5256, 9312, 9702, 8930, 10712, 155...
Python
zaydzuhri_stack_edu_python
function register_geometry name begin comment TODO if anything more needs to be done with geometries than just adding comment coordinates once, they should be reimplemented as class inheritance if not is instance name str begin raise call ValueError string The name of the new geometry type must be a string end function...
def register_geometry(name): # TODO if anything more needs to be done with geometries than just adding # coordinates once, they should be reimplemented as class inheritance if not isinstance(name, str): raise ValueError("The name of the new geometry type must be a string") def wrapper(add_geo...
Python
nomic_cornstack_python_v1
string bencode.py - compatibility helpers. import sys set PY2 = version_info at 0 == 2 set PY3 = version_info at 0 == 3 function is_binary s begin if PY3 begin return is instance s bytes end return is instance s str end function function is_text s begin if PY3 begin return is instance s str end comment noqa: F821 retur...
"""bencode.py - compatibility helpers.""" import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 def is_binary(s): if PY3: return isinstance(s, bytes) return isinstance(s, str) def is_text(s): if PY3: return isinstance(s, str) return isinstanc...
Python
zaydzuhri_stack_edu_python
function lift_buttons self begin call lift call lift end function
def lift_buttons(self): self.new_button.lift() self.import_button.lift()
Python
nomic_cornstack_python_v1
function emp_button_pay_money self cr uid ids context=none begin set uid = SUPERUSER_ID set models_data = get pool string ir.model.data set form_view = call get_object_reference cr uid string employee_pos_ewallet string employee_pay_money_wiz return dict string name call _ string Money Confirmation ; string type string...
def emp_button_pay_money(self, cr, uid, ids, context=None): uid = SUPERUSER_ID models_data = self.pool.get('ir.model.data') form_view = models_data.get_object_reference(cr, uid, 'employee_pos_ewallet', 'employee_pay_money_wiz') return { 'name': _('Money Confirmation'), ...
Python
nomic_cornstack_python_v1
while true begin print string 1 - add task 2 - delete task 3 - look at tasks q - to quit set option = integer input string Please enter a choice from menu: if option == string q begin break end else if option == 1 begin set title = input string please enter a title for task: set priority = input string please enter lev...
while True: print( """ 1 - add task 2 - delete task 3 - look at tasks q - to quit """ ) option = int(input("Please enter a choice from menu: ")) if option == "q": break elif option == 1: title = input("please enter a title for t...
Python
zaydzuhri_stack_edu_python
function random_game nums_actions random_state=none begin set N = length nums_actions if N == 0 begin raise call ValueError string nums_actions must be non-empty end set random_state = call check_random_state random_state set players = list comprehension call Player random nums_actions at slice i : : + nums_actions a...
def random_game(nums_actions, random_state=None): N = len(nums_actions) if N == 0: raise ValueError('nums_actions must be non-empty') random_state = check_random_state(random_state) players = [ Player(random_state.random(nums_actions[i:]+nums_actions[:i])) for i in range(N) ...
Python
nomic_cornstack_python_v1
function __enter__ self begin set tmp_path = call Path make dir temp with call handle_cleanup begin set path = call fetch tmp_path set stubs = call generate_stubs path set pkg_root = call get_root path end return pkg_root or stubs end function
def __enter__(self) -> Union[Path, List[Tuple[Path, Path]]]: self.tmp_path = Path(mkdtemp()) with self.handle_cleanup(): path = self.fetch(self.tmp_path) stubs = self.generate_stubs(path) pkg_root = self.get_root(path) return pkg_root or stubs
Python
nomic_cornstack_python_v1
function update self table_name values constraints=none returning=none begin string Builds and executes and update statement. :param table_name: the name of the table to update :param values: can be either a dict or an enuerable of 2-tuples in the form (column, value). :param constraints: can be any construct that can ...
def update(self, table_name, values, constraints=None, *, returning=None): """Builds and executes and update statement. :param table_name: the name of the table to update :param values: can be either a dict or an enuerable of 2-tuples in the form (column, value). :param constraints: can be any construc...
Python
jtatman_500k
function scrape begin comment Store all the data we scraped in a dictionary set Mars_info = dict comment ----------------------------- comment 1. The latest NASA Mars News comment ------------------------------ comment URL of page to be scraped set url = string https://mars.nasa.gov/news/ comment Retrieve page with th...
def scrape(): # Store all the data we scraped in a dictionary Mars_info = {} # ----------------------------- # 1. The latest NASA Mars News #------------------------------ # URL of page to be scraped url= "https://mars.nasa.gov/news/" # Retrieve page with the requests module browse...
Python
nomic_cornstack_python_v1
function split_timerange_v0 starttime endtime days=1 hours=0 timestep=60 begin set chunks = list set start = starttime set end = start + time delta days=days hours=hours while end <= endtime begin append chunks tuple start + time delta minutes=timestep end set start = end set end = start + time delta days=days hours=h...
def split_timerange_v0(starttime, endtime, days=1, hours=0, timestep=60): chunks = [] start = starttime end = start + timedelta(days=days, hours=hours) while end <= endtime: chunks.append((start + timedelta(minutes=timestep), end)) start = end end = start + timedelta(days...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import urllib , urllib2 import json import sys function getHWResult bData begin string bData: string or list eg: "102a186a103a186a105a186a107a185" or: [ [(102,186),(103,186),(105,186),(107,185)], [...] ] result: {'s':'candicate words','t':1 or 3 or -1} t=1: ok t=3: api error, input cannot ...
# -*- coding: utf-8 -*- import urllib,urllib2 import json import sys def getHWResult(bData): """ bData: string or list eg: "102a186a103a186a105a186a107a185" or: [ [(102,186),(103,186),(105,186),(107,185)], [...] ] result: {'s':'candicate words','t':1 or 3 or -1} t=1: ok t=3: api error, input can...
Python
zaydzuhri_stack_edu_python
comment import PIL comment from PIL import ImageFont comment from PIL import Image comment from PIL import ImageDraw comment font = ImageFont.truetype("Senats-Antiqua.ttf",25) comment img=Image.new("RGBA", (200,200),(120,100,20)) comment draw = ImageDraw.Draw(img) comment draw.text((0, 0),"This is a test",(255,255,0),f...
# import PIL # from PIL import ImageFont # from PIL import Image # from PIL import ImageDraw # font = ImageFont.truetype("Senats-Antiqua.ttf",25) # img=Image.new("RGBA", (200,200),(120,100,20)) # draw = ImageDraw.Draw(img) # draw.text((0, 0),"This is a test",(255,255,0),font=font) # draw = ImageDraw.Draw(img) # draw = ...
Python
zaydzuhri_stack_edu_python
function _list_keys self begin string Retrieves a list of all added Keys and populates the self._keys dict with Key instances :returns: A list of Keys instances set req = call request uri + string /keys set keys = json get req if keys begin set _keys = dict for key in keys begin set _keys at key at string id = call Ke...
def _list_keys(self): """ Retrieves a list of all added Keys and populates the self._keys dict with Key instances :returns: A list of Keys instances """ req = self.request(self.uri + '/keys') keys = req.get().json() if keys: self._keys = {} ...
Python
jtatman_500k
for line in file begin append list strip line end sort list for line in list begin print line end set outFile = open string sorted_month.txt string w for line in list begin write outFile line + string end close file close outFile
for line in file: list.append(line.strip()) list.sort() for line in list: print(line) outFile = open('sorted_month.txt','w') for line in list: outFile.write(line + '\n') file.close() outFile.close()
Python
zaydzuhri_stack_edu_python
function create_model self begin set model = none pass end function
def create_model(self): self.model = None pass
Python
nomic_cornstack_python_v1
function test_autograd self tol begin set weights = random size=6 requires_grad=true set dev = device string default.qubit wires=4 set circuit = call QNode circuit_template dev set circuit2 = call QNode circuit_decomposed dev set res = call circuit weights set res2 = call circuit2 weights assert call allclose res res2 ...
def test_autograd(self, tol): weights = qml.numpy.random.random(size=(6), requires_grad=True) dev = qml.device("default.qubit", wires=4) circuit = qml.QNode(circuit_template, dev) circuit2 = qml.QNode(circuit_decomposed, dev) res = circuit(weights) res2 = circuit2(wei...
Python
nomic_cornstack_python_v1
set a = list range 21 print a set b = list range 3 13 print b set c = list range 2 51 3 print c
a = list(range(21)) print(a) b = list(range(3,13)) print(b) c = list(range(2,51,3)) print(c)
Python
zaydzuhri_stack_edu_python
function from_file cls path begin set name = replace base name path path CURLRC_EXTENSION string set description = none set options = dict with open path as config begin comment Extract description from first line if it is a comment. set first_line = strip read line config if starts with first_line string # begin set ...
def from_file(cls, path): name = os.path.basename(path).replace(CURLRC_EXTENSION, '') description = None options = {} with open(path) as config: # Extract description from first line if it is a comment. first_line = config.readline().strip() if first_l...
Python
nomic_cornstack_python_v1
comment Akhyar I. Kamili comment akamili@andrew.cmu.edu comment This module contains functions which transform comment drag and drop motions into drawing shapes from shapes import * import helper import pygame set BLACK = tuple 0 0 0 set WHITE = tuple 255 255 255 set GREY = tuple 175 175 175 set RED = call Color 255 0 ...
# Akhyar I. Kamili # akamili@andrew.cmu.edu # # This module contains functions which transform # drag and drop motions into drawing shapes from shapes import * import helper import pygame BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) GREY = (175, 175, 175) RED = pygame.Color(255, 0, 0) def drawCircle(start, end, f...
Python
zaydzuhri_stack_edu_python
from flask import Flask , jsonify from flask import Flask , request , jsonify from sklearn.externals import joblib import sys import traceback import pandas as pd import numpy as np set app = call Flask __name__ decorator call route string /predict methods=list string POST comment @app.route('/predict', methods=['POST'...
from flask import Flask, jsonify from flask import Flask, request, jsonify from sklearn.externals import joblib import sys import traceback import pandas as pd import numpy as np app = Flask(__name__) #@app.route('/predict', methods=['POST']) @app.route('/predict', methods= ['POST']) def predict(): json_ = requ...
Python
zaydzuhri_stack_edu_python
function _combine_megacounties data county_col geo_info begin set merged = merge geo_info how=string left left_on=county_col right_on=string GEOID sort=true set missing = set GEOID - set data at county_col for tuple i row in call iterrows begin if call _is_megacounty row at county_col begin set state = row at county_co...
def _combine_megacounties(data: pd.DataFrame, county_col: str, geo_info: gpd.GeoDataFrame) -> gpd.GeoDataFrame: merged = data.merge(geo_info, how="left", left_on=county_col, right_on="GEOID", sort=True) missing = set(geo_info.GEOID) - set(data[county_col]) ...
Python
nomic_cornstack_python_v1
set A = 10 set B = 2 print string O valor da soma e: A + B print format string O valor da soma e {} A + B print format string O valor da soma e {} e o valor da divisao e {} A + B A / B
A = 10 B = 2 print("O valor da soma e: ", A + B) print("O valor da soma e {}".format(A + B)) print("O valor da soma e {} e o valor da divisao e {}".format(A + B, A / B))
Python
zaydzuhri_stack_edu_python
comment %% Load and preprocess import numpy as np import matplotlib.pyplot as plt import cv2 set img = call imread string Images/img.jpg set img = call cvtColor img COLOR_BGR2RGB set img = call resize img tuple 224 224 set fig = figure image show img set img_vector = as type reshape img - 1 3 float32 comment %% OpenCV ...
#%% Load and preprocess import numpy as np import matplotlib.pyplot as plt import cv2 img = cv2.imread('Images/img.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (224,224)) fig = plt.figure() plt.imshow(img) img_vector = img.reshape(-1,3).astype(np.float32) #%% OpenCV K-means filter, K==2 cri...
Python
zaydzuhri_stack_edu_python